Ejemplo n.º 1
0
  /**
   * Extracts all the required fields from the RestRequest 'h' parameter. In order to support
   * wildcards like 'bulk.*' this needs potentially parse all the configured headers and its aliases
   * and needs to ensure that everything is only added once to the returned headers, even if
   * 'h=bulk.*.bulk.*' is specified or some headers are contained twice due to matching aliases
   */
  private static Set<String> expandHeadersFromRequest(Table table, RestRequest request) {
    Set<String> headers = new LinkedHashSet<>(table.getHeaders().size());

    // check headers and aliases
    for (String header : Strings.splitStringByCommaToArray(request.param("h"))) {
      if (Regex.isSimpleMatchPattern(header)) {
        for (Table.Cell tableHeaderCell : table.getHeaders()) {
          String configuredHeader = tableHeaderCell.value.toString();
          if (Regex.simpleMatch(header, configuredHeader)) {
            headers.add(configuredHeader);
          } else if (tableHeaderCell.attr.containsKey("alias")) {
            String[] aliases = Strings.splitStringByCommaToArray(tableHeaderCell.attr.get("alias"));
            for (String alias : aliases) {
              if (Regex.simpleMatch(header, alias)) {
                headers.add(configuredHeader);
                break;
              }
            }
          }
        }
      } else {
        headers.add(header);
      }
    }

    return headers;
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    multiSearchRequest.listenerThreaded(false);

    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    String[] types = Strings.splitStringByCommaToArray(request.param("type"));
    IndicesOptions indicesOptions =
        IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions());

    try {
      multiSearchRequest.add(
          request.content(),
          request.contentUnsafe(),
          indices,
          types,
          request.param("search_type"),
          request.param("routing"),
          indicesOptions,
          allowExplicitIndex);
    } catch (Exception e) {
      try {
        XContentBuilder builder = restContentBuilder(request);
        channel.sendResponse(
            new XContentRestResponse(
                request,
                BAD_REQUEST,
                builder.startObject().field("error", e.getMessage()).endObject()));
      } catch (IOException e1) {
        logger.error("Failed to send failure response", e1);
      }
      return;
    }

    client.multiSearch(
        multiSearchRequest,
        new ActionListener<MultiSearchResponse>() {
          @Override
          public void onResponse(MultiSearchResponse response) {
            try {
              XContentBuilder builder = restContentBuilder(request);
              builder.startObject();
              response.toXContent(builder, request);
              builder.endObject();
              channel.sendResponse(new XContentRestResponse(request, OK, builder));
            } catch (Throwable e) {
              onFailure(e);
            }
          }

          @Override
          public void onFailure(Throwable e) {
            try {
              channel.sendResponse(new XContentThrowableRestResponse(request, e));
            } catch (IOException e1) {
              logger.error("Failed to send failure response", e1);
            }
          }
        });
  }
Ejemplo n.º 3
0
  private static List<DisplayHeader> buildDisplayHeaders(Table table, RestRequest request) {
    String pHeaders = request.param("h");
    List<DisplayHeader> display = new ArrayList<DisplayHeader>();
    if (pHeaders != null) {
      for (String possibility : Strings.splitStringByCommaToArray(pHeaders)) {
        DisplayHeader dispHeader = null;

        if (table.getAsMap().containsKey(possibility)) {
          dispHeader = new DisplayHeader(possibility, possibility);
        } else {
          for (Table.Cell headerCell : table.getHeaders()) {
            String aliases = headerCell.attr.get("alias");
            if (aliases != null) {
              for (String alias : Strings.splitStringByCommaToArray(aliases)) {
                if (possibility.equals(alias)) {
                  dispHeader = new DisplayHeader(headerCell.value.toString(), alias);
                  break;
                }
              }
            }
          }
        }

        if (dispHeader != null) {
          // We know we need the header asked for:
          display.add(dispHeader);

          // Look for accompanying sibling column
          Table.Cell hcell = table.getHeaderMap().get(dispHeader.name);
          String siblingFlag = hcell.attr.get("sibling");
          if (siblingFlag != null) {
            // ...link the sibling and check that its flag is set
            String sibling = siblingFlag + "." + dispHeader.name;
            Table.Cell c = table.getHeaderMap().get(sibling);
            if (c != null && request.paramAsBoolean(siblingFlag, false)) {
              display.add(
                  new DisplayHeader(c.value.toString(), siblingFlag + "." + dispHeader.display));
            }
          }
        }
      }
    } else {
      for (Table.Cell cell : table.getHeaders()) {
        String d = cell.attr.get("default");
        if (Booleans.parseBoolean(d, true)) {
          display.add(new DisplayHeader(cell.value.toString(), cell.value.toString()));
        }
      }
    }
    return display;
  }
  @Override
  public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client)
      throws IOException {
    final String[] names = Strings.splitStringByCommaToArray(request.param("name"));

    GetIndexTemplatesRequest getIndexTemplatesRequest = new GetIndexTemplatesRequest(names);
    getIndexTemplatesRequest.local(
        request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
    getIndexTemplatesRequest.masterNodeTimeout(
        request.paramAsTime("master_timeout", getIndexTemplatesRequest.masterNodeTimeout()));

    final boolean implicitAll = getIndexTemplatesRequest.names().length == 0;

    return channel ->
        client
            .admin()
            .indices()
            .getTemplates(
                getIndexTemplatesRequest,
                new RestToXContentListener<GetIndexTemplatesResponse>(channel) {
                  @Override
                  protected RestStatus getStatus(GetIndexTemplatesResponse response) {
                    boolean templateExists = false == response.getIndexTemplates().isEmpty();

                    return (templateExists || implicitAll) ? OK : NOT_FOUND;
                  }
                });
  }
Ejemplo n.º 5
0
  private RestChannelConsumer parseExistingDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    String index = restRequest.param("index");
    String type = restRequest.param("type");
    percolateRequest.indices(
        Strings.splitStringByCommaToArray(restRequest.param("percolate_index", index)));
    percolateRequest.documentType(restRequest.param("percolate_type", type));

    GetRequest getRequest = new GetRequest(index, type, restRequest.param("id"));
    getRequest.routing(restRequest.param("routing"));
    getRequest.preference(restRequest.param("preference"));
    getRequest.refresh(restRequest.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.realtime(restRequest.paramAsBoolean("realtime", getRequest.realtime()));
    getRequest.version(RestActions.parseVersion(restRequest));
    getRequest.versionType(
        VersionType.fromString(restRequest.param("version_type"), getRequest.versionType()));

    percolateRequest.getRequest(getRequest);
    percolateRequest.routing(restRequest.param("percolate_routing"));
    percolateRequest.preference(restRequest.param("percolate_preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
Ejemplo n.º 6
0
  @Override
  public String[] getAsArray(String settingPrefix, String[] defaultArray) throws SettingsException {
    List<String> result = Lists.newArrayList();

    if (get(settingPrefix) != null) {
      String[] strings = Strings.splitStringByCommaToArray(get(settingPrefix));
      if (strings.length > 0) {
        for (String string : strings) {
          result.add(string.trim());
        }
      }
    }

    int counter = 0;
    while (true) {
      String value = get(settingPrefix + '.' + (counter++));
      if (value == null) {
        break;
      }
      result.add(value.trim());
    }
    if (result.isEmpty()) {
      return defaultArray;
    }
    return result.toArray(new String[result.size()]);
  }
 public void testMultipleLaunch() throws Exception {
   Terminal terminal = new MockTerminal();
   final AtomicReference<Boolean> executed = new AtomicReference<>(false);
   final NamedCommand cmd =
       new NamedCommand("cmd", terminal) {
         @Override
         public CliTool.ExitStatus execute(Settings settings, Environment env) {
           executed.set(true);
           return OK;
         }
       };
   SingleCmdTool tool = new SingleCmdTool("tool", terminal, cmd);
   tool.parse("cmd", Strings.splitStringByCommaToArray("--verbose"));
   tool.parse("cmd", Strings.splitStringByCommaToArray("--silent"));
   tool.parse("cmd", Strings.splitStringByCommaToArray("--help"));
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   ForceMergeRequest mergeRequest =
       new ForceMergeRequest(Strings.splitStringByCommaToArray(request.param("index")));
   mergeRequest.indicesOptions(IndicesOptions.fromRequest(request, mergeRequest.indicesOptions()));
   mergeRequest.maxNumSegments(
       request.paramAsInt("max_num_segments", mergeRequest.maxNumSegments()));
   mergeRequest.onlyExpungeDeletes(
       request.paramAsBoolean("only_expunge_deletes", mergeRequest.onlyExpungeDeletes()));
   mergeRequest.flush(request.paramAsBoolean("flush", mergeRequest.flush()));
   client
       .admin()
       .indices()
       .forceMerge(
           mergeRequest,
           new RestBuilderListener<ForceMergeResponse>(channel) {
             @Override
             public RestResponse buildResponse(
                 ForceMergeResponse response, XContentBuilder builder) throws Exception {
               builder.startObject();
               buildBroadcastShardsHeader(builder, request, response);
               builder.endObject();
               return new BytesRestResponse(OK, builder);
             }
           });
 }
Ejemplo n.º 9
0
 public String[] paramAsStringArray(String key, String[] defaultValue) {
   String value = param(key);
   if (value == null) {
     return defaultValue;
   }
   return Strings.splitStringByCommaToArray(value);
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final ClusterSearchShardsRequest clusterSearchShardsRequest =
        Requests.clusterSearchShardsRequest(indices);
    clusterSearchShardsRequest.local(
        request.paramAsBoolean("local", clusterSearchShardsRequest.local()));
    clusterSearchShardsRequest.listenerThreaded(false);

    clusterSearchShardsRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    clusterSearchShardsRequest.routing(request.param("routing"));
    clusterSearchShardsRequest.preference(request.param("preference"));
    clusterSearchShardsRequest.indicesOptions(
        IndicesOptions.fromRequest(request, clusterSearchShardsRequest.indicesOptions()));

    client
        .admin()
        .cluster()
        .searchShards(
            clusterSearchShardsRequest,
            new ActionListener<ClusterSearchShardsResponse>() {
              @Override
              public void onResponse(ClusterSearchShardsResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject();
                  response.toXContent(builder, request);
                  builder.endObject();
                  channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new BytesRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
 @Override
 public void handleRequest(final RestRequest request, final RestChannel channel) {
   PutWarmerRequest putWarmerRequest = new PutWarmerRequest(request.param("name"));
   putWarmerRequest.listenerThreaded(false);
   SearchRequest searchRequest =
       new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")))
           .types(Strings.splitStringByCommaToArray(request.param("type")))
           .source(request.content(), request.contentUnsafe());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   putWarmerRequest.searchRequest(searchRequest);
   putWarmerRequest.timeout(request.paramAsTime("timeout", putWarmerRequest.timeout()));
   putWarmerRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", putWarmerRequest.masterNodeTimeout()));
   client
       .admin()
       .indices()
       .putWarmer(
           putWarmerRequest, new AcknowledgedRestResponseActionListener(request, channel, logger));
 }
Ejemplo n.º 12
0
  public static SearchRequest parseSearchRequest(RestRequest request) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    SearchRequest searchRequest = new SearchRequest(indices);
    // get the content, and put it in the body
    // add content/source as template if template flag is set
    boolean isTemplateRequest = request.path().endsWith("/template");
    if (RestActions.hasBodyContent(request)) {
      if (isTemplateRequest) {
        searchRequest.templateSource(RestActions.getRestContent(request));
      } else {
        searchRequest.source(RestActions.getRestContent(request));
      }
    }

    // do not allow 'query_and_fetch' or 'dfs_query_and_fetch' search types
    // from the REST layer. these modes are an internal optimization and should
    // not be specified explicitly by the user.
    String searchType = request.param("search_type");
    if (SearchType.fromString(searchType).equals(SearchType.QUERY_AND_FETCH)
        || SearchType.fromString(searchType).equals(SearchType.DFS_QUERY_AND_FETCH)) {
      throw new IllegalArgumentException("Unsupported search type [" + searchType + "]");
    } else {
      searchRequest.searchType(searchType);
    }

    searchRequest.extraSource(parseSearchSource(request));
    searchRequest.queryCache(request.paramAsBoolean("query_cache", null));

    String scroll = request.param("scroll");
    if (scroll != null) {
      searchRequest.scroll(new Scroll(parseTimeValue(scroll, null, "scroll")));
    }

    searchRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    searchRequest.routing(request.param("routing"));
    searchRequest.preference(request.param("preference"));
    searchRequest.indicesOptions(
        IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));

    return searchRequest;
  }
 /**
  * Returns an array of string value from a node value.
  *
  * <p>If the node represents an array the corresponding array of strings is returned. Otherwise
  * the node is treated as a comma-separated string.
  */
 public static String[] nodeStringArrayValue(Object node) {
   if (isArray(node)) {
     List list = (List) node;
     String[] arr = new String[list.size()];
     for (int i = 0; i < arr.length; i++) {
       arr[i] = nodeStringValue(list.get(i), null);
     }
     return arr;
   } else {
     return Strings.splitStringByCommaToArray(node.toString());
   }
 }
Ejemplo n.º 14
0
  private RestChannelConsumer parseDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    final String[] aliases = request.paramAsStringArrayOrEmptyIfAll("name");
    final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliases);
    getAliasesRequest.indices(indices);
    getAliasesRequest.indicesOptions(
        IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
    getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));

    client
        .admin()
        .indices()
        .getAliases(
            getAliasesRequest,
            new RestBuilderListener<GetAliasesResponse>(channel) {
              @Override
              public RestResponse buildResponse(
                  GetAliasesResponse response, XContentBuilder builder) throws Exception {
                // empty body, if indices were specified but no aliases were
                if (indices.length > 0 && response.getAliases().isEmpty()) {
                  return new BytesRestResponse(OK, builder.startObject().endObject());
                } else if (response.getAliases().isEmpty()) {
                  String message =
                      String.format(
                          Locale.ROOT,
                          "alias [%s] missing",
                          toNamesString(getAliasesRequest.aliases()));
                  builder
                      .startObject()
                      .field("error", message)
                      .field("status", RestStatus.NOT_FOUND.getStatus())
                      .endObject();
                  return new BytesRestResponse(RestStatus.NOT_FOUND, builder);
                }

                builder.startObject();
                for (ObjectObjectCursor<String, List<AliasMetaData>> entry :
                    response.getAliases()) {
                  builder.startObject(entry.key, XContentBuilder.FieldCaseConversion.NONE);
                  builder.startObject(Fields.ALIASES);
                  for (AliasMetaData alias : entry.value) {
                    AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
                  }
                  builder.endObject();
                  builder.endObject();
                }
                builder.endObject();
                return new BytesRestResponse(OK, builder);
              }
            });
  }
Ejemplo n.º 16
0
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    TypesExistsRequest typesExistsRequest =
        new TypesExistsRequest(
            Strings.splitStringByCommaToArray(request.param("index")),
            Strings.splitStringByCommaToArray(request.param("type")));
    typesExistsRequest.listenerThreaded(false);
    typesExistsRequest.local(request.paramAsBoolean("local", typesExistsRequest.local()));
    typesExistsRequest.indicesOptions(
        IndicesOptions.fromRequest(request, typesExistsRequest.indicesOptions()));
    client
        .admin()
        .indices()
        .typesExists(
            typesExistsRequest,
            new ActionListener<TypesExistsResponse>() {
              @Override
              public void onResponse(TypesExistsResponse response) {
                try {
                  if (response.isExists()) {
                    channel.sendResponse(new BytesRestResponse(OK));
                  } else {
                    channel.sendResponse(new BytesRestResponse(NOT_FOUND));
                  }
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new BytesRestResponse(ExceptionsHelper.status(e)));
                } catch (Exception e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
Ejemplo n.º 17
0
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client)
     throws IOException {
   final SearchRequest searchRequest =
       new SearchRequest(
           Strings.splitStringByCommaToArray(request.param("index")), new SearchSourceBuilder());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   if (RestActions.hasBodyContent(request)) {
     final BytesReference sourceBytes = RestActions.getRestContent(request);
     try (XContentParser parser =
         XContentFactory.xContent(sourceBytes).createParser(sourceBytes)) {
       final QueryParseContext context =
           new QueryParseContext(queryRegistry, parser, parseFieldMatcher);
       searchRequest.source().suggest(SuggestBuilder.fromXContent(context, suggesters));
     }
   } else {
     throw new IllegalArgumentException("no content or source provided to execute suggestion");
   }
   searchRequest.routing(request.param("routing"));
   searchRequest.preference(request.param("preference"));
   client.search(
       searchRequest,
       new RestBuilderListener<SearchResponse>(channel) {
         @Override
         public RestResponse buildResponse(SearchResponse response, XContentBuilder builder)
             throws Exception {
           RestStatus restStatus =
               RestStatus.status(
                   response.getSuccessfulShards(),
                   response.getTotalShards(),
                   response.getShardFailures());
           builder.startObject();
           buildBroadcastShardsHeader(
               builder,
               request,
               response.getTotalShards(),
               response.getSuccessfulShards(),
               response.getFailedShards(),
               response.getShardFailures());
           Suggest suggest = response.getSuggest();
           if (suggest != null) {
             suggest.toInnerXContent(builder, request);
           }
           builder.endObject();
           return new BytesRestResponse(restStatus, builder);
         }
       });
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client)
     throws IOException {
   DeleteByQueryRequest delete =
       new DeleteByQueryRequest(Strings.splitStringByCommaToArray(request.param("index")));
   delete.indicesOptions(IndicesOptions.fromRequest(request, delete.indicesOptions()));
   delete.routing(request.param("routing"));
   if (request.hasParam("timeout")) {
     delete.timeout(request.paramAsTime("timeout", null));
   }
   if (request.hasContent()) {
     XContentParser requestParser =
         XContentFactory.xContent(request.content()).createParser(request.content());
     QueryParseContext context = new QueryParseContext(indicesQueriesRegistry);
     context.reset(requestParser);
     context.parseFieldMatcher(parseFieldMatcher);
     final QueryBuilder<?> builder = context.parseInnerQueryBuilder();
     delete.query(builder);
   } else {
     String source = request.param("source");
     if (source != null) {
       XContentParser requestParser = XContentFactory.xContent(source).createParser(source);
       QueryParseContext context = new QueryParseContext(indicesQueriesRegistry);
       context.reset(requestParser);
       final QueryBuilder<?> builder = context.parseInnerQueryBuilder();
       delete.query(builder);
     } else {
       QueryBuilder<?> queryBuilder = RestActions.urlParamsToQueryBuilder(request);
       if (queryBuilder != null) {
         delete.query(queryBuilder);
       }
     }
   }
   delete.types(Strings.splitStringByCommaToArray(request.param("type")));
   client.execute(INSTANCE, delete, new RestToXContentListener<DeleteByQueryResponse>(channel));
 }
Ejemplo n.º 19
0
  void parseDocPercolate(
      PercolateRequest percolateRequest,
      RestRequest restRequest,
      RestChannel restChannel,
      final Client client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(RestActions.getRestContent(restRequest));

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    executePercolate(percolateRequest, restChannel, client);
  }
Ejemplo n.º 20
0
  private ShardIterator preferenceActiveShardIterator(
      IndexShardRoutingTable indexShard,
      String localNodeId,
      DiscoveryNodes nodes,
      @Nullable String preference) {
    if (preference == null || preference.isEmpty()) {
      String[] awarenessAttributes = awarenessAllocationDecider.awarenessAttributes();
      if (awarenessAttributes.length == 0) {
        return indexShard.activeInitializingShardsRandomIt();
      } else {
        return indexShard.preferAttributesActiveInitializingShardsIt(awarenessAttributes, nodes);
      }
    }
    if (preference.charAt(0) == '_') {
      Preference preferenceType = Preference.parse(preference);
      if (preferenceType == Preference.SHARDS) {
        // starts with _shards, so execute on specific ones
        int index = preference.indexOf(';');

        String shards;
        if (index == -1) {
          shards = preference.substring(Preference.SHARDS.type().length() + 1);
        } else {
          shards = preference.substring(Preference.SHARDS.type().length() + 1, index);
        }
        String[] ids = Strings.splitStringByCommaToArray(shards);
        boolean found = false;
        for (String id : ids) {
          if (Integer.parseInt(id) == indexShard.shardId().id()) {
            found = true;
            break;
          }
        }
        if (!found) {
          return null;
        }
        // no more preference
        if (index == -1 || index == preference.length() - 1) {
          String[] awarenessAttributes = awarenessAllocationDecider.awarenessAttributes();
          if (awarenessAttributes.length == 0) {
            return indexShard.activeInitializingShardsRandomIt();
          } else {
            return indexShard.preferAttributesActiveInitializingShardsIt(
                awarenessAttributes, nodes);
          }
        } else {
          // update the preference and continue
          preference = preference.substring(index + 1);
        }
      }
      preferenceType = Preference.parse(preference);
      switch (preferenceType) {
        case PREFER_NODE:
          return indexShard.preferNodeActiveInitializingShardsIt(
              preference.substring(Preference.PREFER_NODE.type().length() + 1));
        case LOCAL:
          return indexShard.preferNodeActiveInitializingShardsIt(localNodeId);
        case PRIMARY:
          return indexShard.primaryActiveInitializingShardIt();
        case PRIMARY_FIRST:
          return indexShard.primaryFirstActiveInitializingShardsIt();
        case ONLY_LOCAL:
          return indexShard.onlyNodeActiveInitializingShardsIt(localNodeId);
        case ONLY_NODE:
          String nodeId = preference.substring(Preference.ONLY_NODE.type().length() + 1);
          ensureNodeIdExists(nodes, nodeId);
          return indexShard.onlyNodeActiveInitializingShardsIt(nodeId);
        case ONLY_NODES:
          String nodeAttribute = preference.substring(Preference.ONLY_NODES.type().length() + 1);
          return indexShard.onlyNodeSelectorActiveInitializingShardsIt(nodeAttribute, nodes);
        default:
          throw new IllegalArgumentException("unknown preference [" + preferenceType + "]");
      }
    }
    // if not, then use it as the index
    String[] awarenessAttributes = awarenessAllocationDecider.awarenessAttributes();
    if (awarenessAttributes.length == 0) {
      return indexShard.activeInitializingShardsIt(DjbHashFunction.DJB_HASH(preference));
    } else {
      return indexShard.preferAttributesActiveInitializingShardsIt(
          awarenessAttributes, nodes, DjbHashFunction.DJB_HASH(preference));
    }
  }
Ejemplo n.º 21
0
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    UpdateRequest updateRequest =
        new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.listenerThreaded(false);
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(
        request.param(
            "parent")); // order is important, set it after routing, so it will set the routing
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.refresh(request.paramAsBoolean("refresh", updateRequest.refresh()));
    String replicationType = request.param("replication");
    if (replicationType != null) {
      updateRequest.replicationType(ReplicationType.fromString(replicationType));
    }
    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
      updateRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    updateRequest.percolate(request.param("percolate", null));
    updateRequest.script(request.param("script"));
    updateRequest.scriptLang(request.param("lang"));
    for (Map.Entry<String, String> entry : request.params().entrySet()) {
      if (entry.getKey().startsWith("sp_")) {
        updateRequest.addScriptParam(entry.getKey().substring(3), entry.getValue());
      }
    }
    String sField = request.param("fields");
    if (sField != null) {
      String[] sFields = Strings.splitStringByCommaToArray(sField);
      if (sFields != null) {
        updateRequest.fields(sFields);
      }
    }
    updateRequest.retryOnConflict(
        request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));

    // see if we have it in the body
    if (request.hasContent()) {
      try {
        updateRequest.source(
            request.contentByteArray(), request.contentByteArrayOffset(), request.contentLength());
        IndexRequest upsertRequest = updateRequest.upsertRequest();
        if (upsertRequest != null) {
          upsertRequest.routing(request.param("routing"));
          upsertRequest.parent(
              request.param(
                  "parent")); // order is important, set it after routing, so it will set the
          // routing
          upsertRequest.timestamp(request.param("timestamp"));
          if (request.hasParam("ttl")) {
            upsertRequest.ttl(request.paramAsTime("ttl", null).millis());
          }
          upsertRequest.version(RestActions.parseVersion(request));
          upsertRequest.versionType(
              VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
        }
        IndexRequest doc = updateRequest.doc();
        if (doc != null) {
          doc.routing(request.param("routing"));
          doc.parent(
              request.param(
                  "parent")); // order is important, set it after routing, so it will set the
          // routing
          doc.timestamp(request.param("timestamp"));
          if (request.hasParam("ttl")) {
            doc.ttl(request.paramAsTime("ttl", null).millis());
          }
          doc.version(RestActions.parseVersion(request));
          doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
        }
      } catch (Exception e) {
        try {
          channel.sendResponse(new XContentThrowableRestResponse(request, e));
        } catch (IOException e1) {
          logger.warn("Failed to send response", e1);
        }
        return;
      }
    }

    client.update(
        updateRequest,
        new ActionListener<UpdateResponse>() {
          @Override
          public void onResponse(UpdateResponse response) {
            try {
              XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
              builder
                  .startObject()
                  .field(Fields.OK, true)
                  .field(Fields._INDEX, response.index())
                  .field(Fields._TYPE, response.type())
                  .field(Fields._ID, response.id())
                  .field(Fields._VERSION, response.version());

              if (response.getResult() != null) {
                builder.startObject(Fields.GET);
                response.getResult().toXContentEmbedded(builder, request);
                builder.endObject();
              }

              if (response.matches() != null) {
                builder.startArray(Fields.MATCHES);
                for (String match : response.matches()) {
                  builder.value(match);
                }
                builder.endArray();
              }
              builder.endObject();
              RestStatus status = OK;
              if (response.version() == 1) {
                status = CREATED;
              }
              channel.sendResponse(new XContentRestResponse(request, status, builder));
            } catch (Exception e) {
              onFailure(e);
            }
          }

          @Override
          public void onFailure(Throwable e) {
            try {
              channel.sendResponse(new XContentThrowableRestResponse(request, e));
            } catch (IOException e1) {
              logger.error("Failed to send failure response", e1);
            }
          }
        });
  }
  @Override
  public void handleRequest(
      final RestRequest request, final RestChannel channel, final NodeClient client)
      throws Exception {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    String alias = request.param("name");
    Map<String, Object> filter = null;
    String routing = null;
    String indexRouting = null;
    String searchRouting = null;

    if (request.hasContent()) {
      try (XContentParser parser =
          XContentFactory.xContent(request.content()).createParser(request.content())) {
        XContentParser.Token token = parser.nextToken();
        if (token == null) {
          throw new IllegalArgumentException("No index alias is specified");
        }
        String currentFieldName = null;
        while ((token = parser.nextToken()) != null) {
          if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
          } else if (token.isValue()) {
            if ("index".equals(currentFieldName)) {
              indices = Strings.splitStringByCommaToArray(parser.text());
            } else if ("alias".equals(currentFieldName)) {
              alias = parser.text();
            } else if ("routing".equals(currentFieldName)) {
              routing = parser.textOrNull();
            } else if ("indexRouting".equals(currentFieldName)
                || "index-routing".equals(currentFieldName)
                || "index_routing".equals(currentFieldName)) {
              indexRouting = parser.textOrNull();
            } else if ("searchRouting".equals(currentFieldName)
                || "search-routing".equals(currentFieldName)
                || "search_routing".equals(currentFieldName)) {
              searchRouting = parser.textOrNull();
            }
          } else if (token == XContentParser.Token.START_OBJECT) {
            if ("filter".equals(currentFieldName)) {
              filter = parser.mapOrdered();
            }
          }
        }
      }
    }

    IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();
    indicesAliasesRequest.timeout(request.paramAsTime("timeout", indicesAliasesRequest.timeout()));
    indicesAliasesRequest.masterNodeTimeout(
        request.paramAsTime("master_timeout", indicesAliasesRequest.masterNodeTimeout()));

    IndicesAliasesRequest.AliasActions aliasAction =
        AliasActions.add().indices(indices).alias(alias);
    if (routing != null) {
      aliasAction.routing(routing);
    }
    if (searchRouting != null) {
      aliasAction.searchRouting(searchRouting);
    }
    if (indexRouting != null) {
      aliasAction.indexRouting(indexRouting);
    }
    if (filter != null) {
      aliasAction.filter(filter);
    }
    indicesAliasesRequest.addAliasAction(aliasAction);
    client
        .admin()
        .indices()
        .aliases(indicesAliasesRequest, new AcknowledgedRestListener<>(channel));
  }
  @Override
  public void handleRequest(
      final RestRequest request, final RestChannel channel, final Client client) {
    IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest();
    indicesStatsRequest.indicesOptions(
        IndicesOptions.fromRequest(request, indicesStatsRequest.indicesOptions()));
    indicesStatsRequest.indices(Strings.splitStringByCommaToArray(request.param("index")));
    indicesStatsRequest.types(Strings.splitStringByCommaToArray(request.param("types")));

    Set<String> metrics = Strings.splitStringByCommaToSet(request.param("metric", "_all"));
    // short cut, if no metrics have been specified in URI
    if (metrics.size() == 1 && metrics.contains("_all")) {
      indicesStatsRequest.all();
    } else {
      indicesStatsRequest.clear();
      indicesStatsRequest.docs(metrics.contains("docs"));
      indicesStatsRequest.store(metrics.contains("store"));
      indicesStatsRequest.indexing(metrics.contains("indexing"));
      indicesStatsRequest.search(metrics.contains("search"));
      indicesStatsRequest.get(metrics.contains("get"));
      indicesStatsRequest.merge(metrics.contains("merge"));
      indicesStatsRequest.refresh(metrics.contains("refresh"));
      indicesStatsRequest.flush(metrics.contains("flush"));
      indicesStatsRequest.warmer(metrics.contains("warmer"));
      indicesStatsRequest.queryCache(metrics.contains("query_cache"));
      indicesStatsRequest.percolate(metrics.contains("percolate"));
      indicesStatsRequest.segments(metrics.contains("segments"));
      indicesStatsRequest.fieldData(metrics.contains("fielddata"));
      indicesStatsRequest.completion(metrics.contains("completion"));
      indicesStatsRequest.suggest(metrics.contains("suggest"));
      indicesStatsRequest.requestCache(metrics.contains("request_cache"));
      indicesStatsRequest.recovery(metrics.contains("recovery"));
      indicesStatsRequest.translog(metrics.contains("translog"));
    }

    if (request.hasParam("groups")) {
      indicesStatsRequest.groups(Strings.splitStringByCommaToArray(request.param("groups")));
    }

    if (request.hasParam("types")) {
      indicesStatsRequest.types(Strings.splitStringByCommaToArray(request.param("types")));
    }

    if (indicesStatsRequest.completion()
        && (request.hasParam("fields") || request.hasParam("completion_fields"))) {
      indicesStatsRequest.completionFields(
          request.paramAsStringArray(
              "completion_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY)));
    }

    if (indicesStatsRequest.fieldData()
        && (request.hasParam("fields") || request.hasParam("fielddata_fields"))) {
      indicesStatsRequest.fieldDataFields(
          request.paramAsStringArray(
              "fielddata_fields", request.paramAsStringArray("fields", Strings.EMPTY_ARRAY)));
    }

    client
        .admin()
        .indices()
        .stats(
            indicesStatsRequest,
            new RestBuilderListener<IndicesStatsResponse>(channel) {
              @Override
              public RestResponse buildResponse(
                  IndicesStatsResponse response, XContentBuilder builder) throws Exception {
                builder.startObject();
                buildBroadcastShardsHeader(builder, request, response);
                response.toXContent(builder, request);
                builder.endObject();
                return new BytesRestResponse(OK, builder);
              }
            });
  }
  /**
   * Parses restore definition
   *
   * @param source restore definition
   * @return this request
   */
  public RestoreSnapshotRequest source(Map source) {
    boolean ignoreUnavailable = IndicesOptions.lenient().ignoreUnavailable();
    boolean allowNoIndices = IndicesOptions.lenient().allowNoIndices();
    boolean expandWildcardsOpen = IndicesOptions.lenient().expandWildcardsOpen();
    boolean expandWildcardsClosed = IndicesOptions.lenient().expandWildcardsClosed();

    for (Map.Entry<String, Object> entry : ((Map<String, Object>) source).entrySet()) {
      String name = entry.getKey();
      if (name.equals("indices")) {
        if (entry.getValue() instanceof String) {
          indices(Strings.splitStringByCommaToArray((String) entry.getValue()));
        } else if (entry.getValue() instanceof ArrayList) {
          indices((ArrayList<String>) entry.getValue());
        } else {
          throw new ElasticSearchIllegalArgumentException(
              "malformed indices section, should be an array of strings");
        }
      } else if (name.equals("ignore_unavailable") || name.equals("ignoreUnavailable")) {
        assert entry.getValue() instanceof String;
        ignoreUnavailable = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("allow_no_indices") || name.equals("allowNoIndices")) {
        assert entry.getValue() instanceof String;
        allowNoIndices = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("expand_wildcards_open") || name.equals("expandWildcardsOpen")) {
        assert entry.getValue() instanceof String;
        expandWildcardsOpen = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("expand_wildcards_closed") || name.equals("expandWildcardsClosed")) {
        assert entry.getValue() instanceof String;
        expandWildcardsClosed = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("settings")) {
        if (!(entry.getValue() instanceof Map)) {
          throw new ElasticSearchIllegalArgumentException(
              "malformed settings section, should indices an inner object");
        }
        settings((Map<String, Object>) entry.getValue());
      } else if (name.equals("include_global_state")) {
        if (!(entry.getValue() instanceof Boolean)) {
          throw new ElasticSearchIllegalArgumentException(
              "malformed include_global_state, should be boolean");
        }
        includeGlobalState((Boolean) entry.getValue());
      } else if (name.equals("rename_pattern")) {
        if (entry.getValue() instanceof String) {
          renamePattern((String) entry.getValue());
        } else {
          throw new ElasticSearchIllegalArgumentException("malformed rename_pattern");
        }
      } else if (name.equals("rename_replacement")) {
        if (entry.getValue() instanceof String) {
          renameReplacement((String) entry.getValue());
        } else {
          throw new ElasticSearchIllegalArgumentException("malformed rename_replacement");
        }
      } else {
        throw new ElasticSearchIllegalArgumentException("Unknown parameter " + name);
      }
    }
    indicesOptions(
        IndicesOptions.fromOptions(
            ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed));
    return this;
  }
Ejemplo n.º 25
0
  @Override
  public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client)
      throws IOException {
    UpdateRequest updateRequest =
        new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(request.param("parent"));
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.setRefreshPolicy(request.param("refresh"));
    String waitForActiveShards = request.param("wait_for_active_shards");
    if (waitForActiveShards != null) {
      updateRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
    String sField = request.param("fields");
    if (sField != null && fetchSourceContext != null) {
      throw new IllegalArgumentException(
          "[fields] and [_source] cannot be used in the same request");
    }
    if (sField != null) {
      DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead");
      String[] sFields = Strings.splitStringByCommaToArray(sField);
      updateRequest.fields(sFields);
    } else if (fetchSourceContext != null) {
      updateRequest.fetchSource(fetchSourceContext);
    }

    updateRequest.retryOnConflict(
        request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(
        VersionType.fromString(request.param("version_type"), updateRequest.versionType()));

    // see if we have it in the body
    if (request.hasContent()) {
      updateRequest.fromXContent(request.content());
      IndexRequest upsertRequest = updateRequest.upsertRequest();
      if (upsertRequest != null) {
        upsertRequest.routing(request.param("routing"));
        upsertRequest.parent(
            request.param(
                "parent")); // order is important, set it after routing, so it will set the routing
        upsertRequest.timestamp(request.param("timestamp"));
        if (request.hasParam("ttl")) {
          upsertRequest.ttl(request.param("ttl"));
        }
        upsertRequest.version(RestActions.parseVersion(request));
        upsertRequest.versionType(
            VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
      }
      IndexRequest doc = updateRequest.doc();
      if (doc != null) {
        doc.routing(request.param("routing"));
        doc.parent(
            request.param(
                "parent")); // order is important, set it after routing, so it will set the routing
        doc.timestamp(request.param("timestamp"));
        if (request.hasParam("ttl")) {
          doc.ttl(request.param("ttl"));
        }
        doc.version(RestActions.parseVersion(request));
        doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
      }
    }

    return channel ->
        client.update(
            updateRequest,
            new RestStatusToXContentListener<>(
                channel, r -> r.getLocation(updateRequest.routing())));
  }
Ejemplo n.º 26
0
  public MultiSearchRequest add(
      BytesReference data,
      boolean contentUnsafe,
      @Nullable String[] indices,
      @Nullable String[] types,
      @Nullable String searchType,
      @Nullable String routing,
      IndicesOptions indicesOptions,
      boolean allowExplicitIndex)
      throws Exception {
    XContent xContent = XContentFactory.xContent(data);
    int from = 0;
    int length = data.length();
    byte marker = xContent.streamSeparator();
    while (true) {
      int nextMarker = findNextMarker(marker, from, data, length);
      if (nextMarker == -1) {
        break;
      }
      // support first line with \n
      if (nextMarker == 0) {
        from = nextMarker + 1;
        continue;
      }

      SearchRequest searchRequest = new SearchRequest();
      if (indices != null) {
        searchRequest.indices(indices);
      }
      if (indicesOptions != null) {
        searchRequest.indicesOptions(indicesOptions);
      }
      if (types != null && types.length > 0) {
        searchRequest.types(types);
      }
      if (routing != null) {
        searchRequest.routing(routing);
      }
      searchRequest.searchType(searchType);

      IndicesOptions defaultOptions = IndicesOptions.strictExpandOpenAndForbidClosed();
      boolean ignoreUnavailable = defaultOptions.ignoreUnavailable();
      boolean allowNoIndices = defaultOptions.allowNoIndices();
      boolean expandWildcardsOpen = defaultOptions.expandWildcardsOpen();
      boolean expandWildcardsClosed = defaultOptions.expandWildcardsClosed();

      // now parse the action
      if (nextMarker - from > 0) {
        try (XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from))) {
          // Move to START_OBJECT, if token is null, its an empty data
          XContentParser.Token token = parser.nextToken();
          if (token != null) {
            assert token == XContentParser.Token.START_OBJECT;
            String currentFieldName = null;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
              if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
              } else if (token.isValue()) {
                if ("index".equals(currentFieldName) || "indices".equals(currentFieldName)) {
                  if (!allowExplicitIndex) {
                    throw new ElasticsearchIllegalArgumentException(
                        "explicit index in multi search is not allowed");
                  }
                  searchRequest.indices(Strings.splitStringByCommaToArray(parser.text()));
                } else if ("type".equals(currentFieldName) || "types".equals(currentFieldName)) {
                  searchRequest.types(Strings.splitStringByCommaToArray(parser.text()));
                } else if ("search_type".equals(currentFieldName)
                    || "searchType".equals(currentFieldName)) {
                  searchRequest.searchType(parser.text());
                } else if ("query_cache".equals(currentFieldName)
                    || "queryCache".equals(currentFieldName)) {
                  searchRequest.queryCache(parser.booleanValue());
                } else if ("preference".equals(currentFieldName)) {
                  searchRequest.preference(parser.text());
                } else if ("routing".equals(currentFieldName)) {
                  searchRequest.routing(parser.text());
                } else if ("ignore_unavailable".equals(currentFieldName)
                    || "ignoreUnavailable".equals(currentFieldName)) {
                  ignoreUnavailable = parser.booleanValue();
                } else if ("allow_no_indices".equals(currentFieldName)
                    || "allowNoIndices".equals(currentFieldName)) {
                  allowNoIndices = parser.booleanValue();
                } else if ("expand_wildcards".equals(currentFieldName)
                    || "expandWildcards".equals(currentFieldName)) {
                  String[] wildcards = Strings.splitStringByCommaToArray(parser.text());
                  for (String wildcard : wildcards) {
                    if ("open".equals(wildcard)) {
                      expandWildcardsOpen = true;
                    } else if ("closed".equals(wildcard)) {
                      expandWildcardsClosed = true;
                    } else {
                      throw new ElasticsearchIllegalArgumentException(
                          "No valid expand wildcard value [" + wildcard + "]");
                    }
                  }
                }
              } else if (token == XContentParser.Token.START_ARRAY) {
                if ("index".equals(currentFieldName) || "indices".equals(currentFieldName)) {
                  if (!allowExplicitIndex) {
                    throw new ElasticsearchIllegalArgumentException(
                        "explicit index in multi search is not allowed");
                  }
                  searchRequest.indices(parseArray(parser));
                } else if ("type".equals(currentFieldName) || "types".equals(currentFieldName)) {
                  searchRequest.types(parseArray(parser));
                } else if ("expand_wildcards".equals(currentFieldName)
                    || "expandWildcards".equals(currentFieldName)) {
                  String[] wildcards = parseArray(parser);
                  for (String wildcard : wildcards) {
                    if ("open".equals(wildcard)) {
                      expandWildcardsOpen = true;
                    } else if ("closed".equals(wildcard)) {
                      expandWildcardsClosed = true;
                    } else {
                      throw new ElasticsearchIllegalArgumentException(
                          "No valid expand wildcard value [" + wildcard + "]");
                    }
                  }
                } else {
                  throw new ElasticsearchParseException(
                      currentFieldName + " doesn't support arrays");
                }
              }
            }
          }
        }
      }
      searchRequest.indicesOptions(
          IndicesOptions.fromOptions(
              ignoreUnavailable,
              allowNoIndices,
              expandWildcardsOpen,
              expandWildcardsClosed,
              defaultOptions));

      // move pointers
      from = nextMarker + 1;
      // now for the body
      nextMarker = findNextMarker(marker, from, data, length);
      if (nextMarker == -1) {
        break;
      }

      searchRequest.source(data.slice(from, nextMarker - from), contentUnsafe);
      // move pointers
      from = nextMarker + 1;

      add(searchRequest);
    }

    return this;
  }
Ejemplo n.º 27
0
  public static SearchSourceBuilder parseSearchSource(RestRequest request) {
    SearchSourceBuilder searchSourceBuilder = null;

    QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
    if (querySourceBuilder != null) {
      searchSourceBuilder = new SearchSourceBuilder();
      searchSourceBuilder.query(querySourceBuilder);
    }

    int from = request.paramAsInt("from", -1);
    if (from != -1) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.from(from);
    }
    int size = request.paramAsInt("size", -1);
    if (size != -1) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.size(size);
    }

    if (request.hasParam("explain")) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.explain(request.paramAsBoolean("explain", null));
    }
    if (request.hasParam("version")) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.version(request.paramAsBoolean("version", null));
    }
    if (request.hasParam("timeout")) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.timeout(request.paramAsTime("timeout", null));
    }
    if (request.hasParam("terminate_after")) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      int terminateAfter =
          request.paramAsInt("terminate_after", SearchContext.DEFAULT_TERMINATE_AFTER);
      if (terminateAfter < 0) {
        throw new IllegalArgumentException("terminateAfter must be > 0");
      } else if (terminateAfter > 0) {
        searchSourceBuilder.terminateAfter(terminateAfter);
      }
    }

    String sField = request.param("fields");
    if (sField != null) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      if (!Strings.hasText(sField)) {
        searchSourceBuilder.noFields();
      } else {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
          for (String field : sFields) {
            searchSourceBuilder.field(field);
          }
        }
      }
    }
    String sFieldDataFields = request.param("fielddata_fields");
    if (sFieldDataFields != null) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      if (Strings.hasText(sFieldDataFields)) {
        String[] sFields = Strings.splitStringByCommaToArray(sFieldDataFields);
        if (sFields != null) {
          for (String field : sFields) {
            searchSourceBuilder.fieldDataField(field);
          }
        }
      }
    }
    FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
    if (fetchSourceContext != null) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.fetchSource(fetchSourceContext);
    }

    if (request.hasParam("track_scores")) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.trackScores(request.paramAsBoolean("track_scores", false));
    }

    String sSorts = request.param("sort");
    if (sSorts != null) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      String[] sorts = Strings.splitStringByCommaToArray(sSorts);
      for (String sort : sorts) {
        int delimiter = sort.lastIndexOf(":");
        if (delimiter != -1) {
          String sortField = sort.substring(0, delimiter);
          String reverse = sort.substring(delimiter + 1);
          if ("asc".equals(reverse)) {
            searchSourceBuilder.sort(sortField, SortOrder.ASC);
          } else if ("desc".equals(reverse)) {
            searchSourceBuilder.sort(sortField, SortOrder.DESC);
          }
        } else {
          searchSourceBuilder.sort(sort);
        }
      }
    }

    String sStats = request.param("stats");
    if (sStats != null) {
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      searchSourceBuilder.stats(Strings.splitStringByCommaToArray(sStats));
    }

    String suggestField = request.param("suggest_field");
    if (suggestField != null) {
      String suggestText = request.param("suggest_text", request.param("q"));
      int suggestSize = request.paramAsInt("suggest_size", 5);
      if (searchSourceBuilder == null) {
        searchSourceBuilder = new SearchSourceBuilder();
      }
      String suggestMode = request.param("suggest_mode");
      searchSourceBuilder
          .suggest()
          .addSuggestion(
              termSuggestion(suggestField)
                  .field(suggestField)
                  .text(suggestText)
                  .size(suggestSize)
                  .suggestMode(suggestMode));
    }

    return searchSourceBuilder;
  }
Ejemplo n.º 28
0
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
    Set<String> metrics = Strings.splitStringByCommaToSet(request.param("metric", "_all"));

    NodesStatsRequest nodesStatsRequest = new NodesStatsRequest(nodesIds);
    nodesStatsRequest.listenerThreaded(false);

    if (metrics.size() == 1 && metrics.contains("_all")) {
      nodesStatsRequest.all();
      nodesStatsRequest.indices(CommonStatsFlags.ALL);
    } else {
      nodesStatsRequest.clear();
      nodesStatsRequest.os(metrics.contains("os"));
      nodesStatsRequest.jvm(metrics.contains("jvm"));
      nodesStatsRequest.threadPool(metrics.contains("thread_pool"));
      nodesStatsRequest.network(metrics.contains("network"));
      nodesStatsRequest.fs(metrics.contains("fs"));
      nodesStatsRequest.transport(metrics.contains("transport"));
      nodesStatsRequest.http(metrics.contains("http"));
      nodesStatsRequest.indices(metrics.contains("indices"));
      nodesStatsRequest.process(metrics.contains("process"));
      nodesStatsRequest.breaker(metrics.contains("breaker"));

      // check for index specific metrics
      if (metrics.contains("indices")) {
        Set<String> indexMetrics =
            Strings.splitStringByCommaToSet(request.param("indexMetric", "_all"));
        if (indexMetrics.size() == 1 && indexMetrics.contains("_all")) {
          nodesStatsRequest.indices(CommonStatsFlags.ALL);
        } else {
          CommonStatsFlags flags = new CommonStatsFlags();
          for (Flag flag : CommonStatsFlags.Flag.values()) {
            flags.set(flag, indexMetrics.contains(flag.getRestName()));
          }
          nodesStatsRequest.indices(flags);
        }
      }
    }

    if (nodesStatsRequest.indices().isSet(Flag.FieldData)
        && (request.hasParam("fields") || request.hasParam("fielddata_fields"))) {
      nodesStatsRequest
          .indices()
          .fieldDataFields(
              request.paramAsStringArray(
                  "fielddata_fields", request.paramAsStringArray("fields", null)));
    }
    if (nodesStatsRequest.indices().isSet(Flag.Completion)
        && (request.hasParam("fields") || request.hasParam("completion_fields"))) {
      nodesStatsRequest
          .indices()
          .completionDataFields(
              request.paramAsStringArray(
                  "completion_fields", request.paramAsStringArray("fields", null)));
    }
    if (nodesStatsRequest.indices().isSet(Flag.Search) && (request.hasParam("groups"))) {
      nodesStatsRequest.indices().groups(request.paramAsStringArray("groups", null));
    }
    if (nodesStatsRequest.indices().isSet(Flag.Indexing) && (request.hasParam("types"))) {
      nodesStatsRequest.indices().types(request.paramAsStringArray("types", null));
    }

    client
        .admin()
        .cluster()
        .nodesStats(
            nodesStatsRequest,
            new ActionListener<NodesStatsResponse>() {
              @Override
              public void onResponse(NodesStatsResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject();
                  response.toXContent(builder, request);
                  builder.endObject();
                  channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new BytesRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }