Search in sources :

Example 1 with NodeClient

use of org.opensearch.client.node.NodeClient in project OpenSearch by opensearch-project.

the class RestSearchTemplateAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    // Creates the search request with all required params
    SearchRequest searchRequest = new SearchRequest();
    RestSearchAction.parseSearchRequest(searchRequest, request, null, client.getNamedWriteableRegistry(), size -> searchRequest.source().size(size));
    // Creates the search template request
    SearchTemplateRequest searchTemplateRequest;
    try (XContentParser parser = request.contentOrSourceParamParser()) {
        searchTemplateRequest = SearchTemplateRequest.fromXContent(parser);
    }
    searchTemplateRequest.setRequest(searchRequest);
    return channel -> client.execute(SearchTemplateAction.INSTANCE, searchTemplateRequest, new RestStatusToXContentListener<>(channel));
}
Also used : POST(org.opensearch.rest.RestRequest.Method.POST) Arrays(java.util.Arrays) NodeClient(org.opensearch.client.node.NodeClient) Collections.unmodifiableList(java.util.Collections.unmodifiableList) GET(org.opensearch.rest.RestRequest.Method.GET) RestRequest(org.opensearch.rest.RestRequest) Set(java.util.Set) IOException(java.io.IOException) XContentParser(org.opensearch.common.xcontent.XContentParser) RestSearchAction(org.opensearch.rest.action.search.RestSearchAction) HashSet(java.util.HashSet) List(java.util.List) RestStatusToXContentListener(org.opensearch.rest.action.RestStatusToXContentListener) Arrays.asList(java.util.Arrays.asList) SearchRequest(org.opensearch.action.search.SearchRequest) BaseRestHandler(org.opensearch.rest.BaseRestHandler) Collections(java.util.Collections) SearchRequest(org.opensearch.action.search.SearchRequest) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 2 with NodeClient

use of org.opensearch.client.node.NodeClient in project OpenSearch by opensearch-project.

the class RestRenderSearchTemplateAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    // Creates the render template request
    SearchTemplateRequest renderRequest;
    try (XContentParser parser = request.contentOrSourceParamParser()) {
        renderRequest = SearchTemplateRequest.fromXContent(parser);
    }
    renderRequest.setSimulate(true);
    String id = request.param("id");
    if (id != null) {
        renderRequest.setScriptType(ScriptType.STORED);
        renderRequest.setScript(id);
    }
    return channel -> client.execute(SearchTemplateAction.INSTANCE, renderRequest, new RestToXContentListener<>(channel));
}
Also used : XContentParser(org.opensearch.common.xcontent.XContentParser) ScriptType(org.opensearch.script.ScriptType) POST(org.opensearch.rest.RestRequest.Method.POST) List(java.util.List) NodeClient(org.opensearch.client.node.NodeClient) RestToXContentListener(org.opensearch.rest.action.RestToXContentListener) Collections.unmodifiableList(java.util.Collections.unmodifiableList) GET(org.opensearch.rest.RestRequest.Method.GET) RestRequest(org.opensearch.rest.RestRequest) Arrays.asList(java.util.Arrays.asList) IOException(java.io.IOException) BaseRestHandler(org.opensearch.rest.BaseRestHandler) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 3 with NodeClient

use of org.opensearch.client.node.NodeClient in project OpenSearch by opensearch-project.

the class TimeoutTaskCancellationUtility method wrapWithCancellationListener.

/**
 * Wraps a listener with a timeout listener {@link TimeoutRunnableListener} to schedule the task cancellation for provided tasks on
 * generic thread pool
 * @param client - {@link NodeClient}
 * @param taskToCancel - task to schedule cancellation for
 * @param clusterSettings - {@link ClusterSettings}
 * @param listener - original listener associated with the task
 * @return wrapped listener
 */
public static <Response> ActionListener<Response> wrapWithCancellationListener(NodeClient client, CancellableTask taskToCancel, ClusterSettings clusterSettings, ActionListener<Response> listener) {
    final TimeValue globalTimeout = clusterSettings.get(SEARCH_CANCEL_AFTER_TIME_INTERVAL_SETTING);
    final TimeValue timeoutInterval = (taskToCancel.getCancellationTimeout() == null) ? globalTimeout : taskToCancel.getCancellationTimeout();
    // Note: -1 (or no timeout) will help to turn off cancellation. The combinations will be request level set at -1 or request level
    // set to null and cluster level set to -1.
    ActionListener<Response> listenerToReturn = listener;
    if (timeoutInterval.equals(SearchService.NO_TIMEOUT)) {
        return listenerToReturn;
    }
    try {
        final TimeoutRunnableListener<Response> wrappedListener = new TimeoutRunnableListener<>(timeoutInterval, listener, () -> {
            final CancelTasksRequest cancelTasksRequest = new CancelTasksRequest();
            cancelTasksRequest.setTaskId(new TaskId(client.getLocalNodeId(), taskToCancel.getId()));
            cancelTasksRequest.setReason("Cancellation timeout of " + timeoutInterval + " is expired");
            // force the origin to execute the cancellation as a system user
            new OriginSettingClient(client, TASKS_ORIGIN).admin().cluster().cancelTasks(cancelTasksRequest, ActionListener.wrap(r -> logger.debug("Scheduled cancel task with timeout: {} for original task: {} is successfully completed", timeoutInterval, cancelTasksRequest.getTaskId()), e -> logger.error(new ParameterizedMessage("Scheduled cancel task with timeout: {} for original task: {} is failed", timeoutInterval, cancelTasksRequest.getTaskId()), e)));
        });
        wrappedListener.cancellable = client.threadPool().schedule(wrappedListener, timeoutInterval, ThreadPool.Names.GENERIC);
        listenerToReturn = wrappedListener;
    } catch (Exception ex) {
        // if there is any exception in scheduling the cancellation task then continue without it
        logger.warn("Failed to schedule the cancellation task for original task: {}, will continue without it", taskToCancel.getId());
    }
    return listenerToReturn;
}
Also used : TimeValue(org.opensearch.common.unit.TimeValue) NodeClient(org.opensearch.client.node.NodeClient) ThreadPool(org.opensearch.threadpool.ThreadPool) TaskId(org.opensearch.tasks.TaskId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) TimeUnit(java.util.concurrent.TimeUnit) Logger(org.apache.logging.log4j.Logger) CancelTasksRequest(org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest) SEARCH_CANCEL_AFTER_TIME_INTERVAL_SETTING(org.opensearch.action.search.TransportSearchAction.SEARCH_CANCEL_AFTER_TIME_INTERVAL_SETTING) ActionListener(org.opensearch.action.ActionListener) ClusterSettings(org.opensearch.common.settings.ClusterSettings) LogManager(org.apache.logging.log4j.LogManager) OriginSettingClient(org.opensearch.client.OriginSettingClient) CancellableTask(org.opensearch.tasks.CancellableTask) Scheduler(org.opensearch.threadpool.Scheduler) SearchService(org.opensearch.search.SearchService) TASKS_ORIGIN(org.opensearch.action.admin.cluster.node.tasks.get.GetTaskAction.TASKS_ORIGIN) TaskId(org.opensearch.tasks.TaskId) CancelTasksRequest(org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) OriginSettingClient(org.opensearch.client.OriginSettingClient) TimeValue(org.opensearch.common.unit.TimeValue)

Example 4 with NodeClient

use of org.opensearch.client.node.NodeClient in project OpenSearch by opensearch-project.

the class RestRethrottleAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) {
    RethrottleRequest internalRequest = new RethrottleRequest();
    internalRequest.setTaskId(new TaskId(request.param("taskId")));
    Float requestsPerSecond = AbstractBaseReindexRestHandler.parseRequestsPerSecond(request);
    if (requestsPerSecond == null) {
        throw new IllegalArgumentException("requests_per_second is a required parameter");
    }
    internalRequest.setRequestsPerSecond(requestsPerSecond);
    final String groupBy = request.param("group_by", "nodes");
    return channel -> client.execute(RethrottleAction.INSTANCE, internalRequest, listTasksResponseListener(nodesInCluster, groupBy, channel));
}
Also used : POST(org.opensearch.rest.RestRequest.Method.POST) RestListTasksAction.listTasksResponseListener(org.opensearch.rest.action.admin.cluster.RestListTasksAction.listTasksResponseListener) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) List(java.util.List) NodeClient(org.opensearch.client.node.NodeClient) Collections.unmodifiableList(java.util.Collections.unmodifiableList) RestRequest(org.opensearch.rest.RestRequest) Arrays.asList(java.util.Arrays.asList) TaskId(org.opensearch.tasks.TaskId) BaseRestHandler(org.opensearch.rest.BaseRestHandler) Supplier(java.util.function.Supplier) TaskId(org.opensearch.tasks.TaskId)

Example 5 with NodeClient

use of org.opensearch.client.node.NodeClient in project OpenSearch by opensearch-project.

the class AbstractBaseReindexRestHandler method doPrepareRequest.

protected RestChannelConsumer doPrepareRequest(RestRequest request, NodeClient client, boolean includeCreated, boolean includeUpdated) throws IOException {
    // Build the internal request
    Request internal = setCommonOptions(request, buildRequest(request, client.getNamedWriteableRegistry()));
    // Executes the request and waits for completion
    if (request.paramAsBoolean("wait_for_completion", true)) {
        Map<String, String> params = new HashMap<>();
        params.put(BulkByScrollTask.Status.INCLUDE_CREATED, Boolean.toString(includeCreated));
        params.put(BulkByScrollTask.Status.INCLUDE_UPDATED, Boolean.toString(includeUpdated));
        return channel -> client.executeLocally(action, internal, new BulkIndexByScrollResponseContentListener(channel, params));
    } else {
        internal.setShouldStoreResult(true);
    }
    /*
         * Let's try and validate before forking so the user gets some error. The
         * task can't totally validate until it starts but this is better than
         * nothing.
         */
    ActionRequestValidationException validationException = internal.validate();
    if (validationException != null) {
        throw validationException;
    }
    return sendTask(client.getLocalNodeId(), client.executeLocally(action, internal, LoggingTaskListener.instance()));
}
Also used : NodeClient(org.opensearch.client.node.NodeClient) RestRequest(org.opensearch.rest.RestRequest) IOException(java.io.IOException) HashMap(java.util.HashMap) Task(org.opensearch.tasks.Task) RestStatus(org.opensearch.rest.RestStatus) BytesRestResponse(org.opensearch.rest.BytesRestResponse) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) LoggingTaskListener(org.opensearch.tasks.LoggingTaskListener) Map(java.util.Map) ActionType(org.opensearch.action.ActionType) BaseRestHandler(org.opensearch.rest.BaseRestHandler) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) HashMap(java.util.HashMap) RestRequest(org.opensearch.rest.RestRequest)

Aggregations

NodeClient (org.opensearch.client.node.NodeClient)154 List (java.util.List)123 RestRequest (org.opensearch.rest.RestRequest)121 IOException (java.io.IOException)114 BaseRestHandler (org.opensearch.rest.BaseRestHandler)96 Arrays.asList (java.util.Arrays.asList)76 Collections.unmodifiableList (java.util.Collections.unmodifiableList)76 GET (org.opensearch.rest.RestRequest.Method.GET)64 Strings (org.opensearch.common.Strings)62 RestToXContentListener (org.opensearch.rest.action.RestToXContentListener)61 POST (org.opensearch.rest.RestRequest.Method.POST)45 RestResponse (org.opensearch.rest.RestResponse)36 IndicesOptions (org.opensearch.action.support.IndicesOptions)34 Set (java.util.Set)29 Collections.singletonList (java.util.Collections.singletonList)28 Table (org.opensearch.common.Table)27 Settings (org.opensearch.common.settings.Settings)26 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)25 FakeRestRequest (org.opensearch.test.rest.FakeRestRequest)25 Collections (java.util.Collections)23