Search in sources :

Example 21 with Task

use of org.elasticsearch.tasks.Task in project elasticsearch by elastic.

the class CancellableTasksTests method testChildTasksCancellation.

public void testChildTasksCancellation() throws Exception {
    setupTestNodes(Settings.EMPTY);
    connectNodes(testNodes);
    CountDownLatch responseLatch = new CountDownLatch(1);
    final AtomicReference<NodesResponse> responseReference = new AtomicReference<>();
    final AtomicReference<Throwable> throwableReference = new AtomicReference<>();
    Task mainTask = startCancellableTestNodesAction(true, nodesCount, new ActionListener<NodesResponse>() {

        @Override
        public void onResponse(NodesResponse listTasksResponse) {
            responseReference.set(listTasksResponse);
            responseLatch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            throwableReference.set(e);
            responseLatch.countDown();
        }
    });
    // Cancel all child tasks without cancelling the main task, which should quit on its own
    CancelTasksRequest request = new CancelTasksRequest();
    request.setReason("Testing Cancellation");
    request.setParentTaskId(new TaskId(testNodes[0].getNodeId(), mainTask.getId()));
    // And send the cancellation request to a random node
    CancelTasksResponse response = testNodes[randomIntBetween(1, testNodes.length - 1)].transportCancelTasksAction.execute(request).get();
    // Awaiting for the main task to finish
    responseLatch.await();
    // Should have cancelled tasks on all nodes
    assertThat(response.getTasks().size(), equalTo(testNodes.length));
    assertBusy(() -> {
        try {
            // Make sure that main task is no longer running
            ListTasksResponse listTasksResponse = testNodes[randomIntBetween(0, testNodes.length - 1)].transportListTasksAction.execute(new ListTasksRequest().setTaskId(new TaskId(testNodes[0].getNodeId(), mainTask.getId()))).get();
            assertEquals(0, listTasksResponse.getTasks().size());
        } catch (ExecutionException | InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    });
}
Also used : CancellableTask(org.elasticsearch.tasks.CancellableTask) Task(org.elasticsearch.tasks.Task) TaskId(org.elasticsearch.tasks.TaskId) CancelTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse) CancelTasksRequest(org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TaskCancelledException(org.elasticsearch.tasks.TaskCancelledException) ListTasksRequest(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksRequest) ExecutionException(java.util.concurrent.ExecutionException)

Example 22 with Task

use of org.elasticsearch.tasks.Task in project elasticsearch by elastic.

the class CancellableTasksTests method testBasicTaskCancellation.

public void testBasicTaskCancellation() throws Exception {
    setupTestNodes(Settings.EMPTY);
    connectNodes(testNodes);
    CountDownLatch responseLatch = new CountDownLatch(1);
    boolean waitForActionToStart = randomBoolean();
    logger.info("waitForActionToStart is set to {}", waitForActionToStart);
    final AtomicReference<NodesResponse> responseReference = new AtomicReference<>();
    final AtomicReference<Throwable> throwableReference = new AtomicReference<>();
    int blockedNodesCount = randomIntBetween(0, nodesCount);
    Task mainTask = startCancellableTestNodesAction(waitForActionToStart, blockedNodesCount, new ActionListener<NodesResponse>() {

        @Override
        public void onResponse(NodesResponse listTasksResponse) {
            responseReference.set(listTasksResponse);
            responseLatch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            throwableReference.set(e);
            responseLatch.countDown();
        }
    });
    // Cancel main task
    CancelTasksRequest request = new CancelTasksRequest();
    request.setReason("Testing Cancellation");
    request.setTaskId(new TaskId(testNodes[0].getNodeId(), mainTask.getId()));
    // And send the cancellation request to a random node
    CancelTasksResponse response = testNodes[randomIntBetween(0, testNodes.length - 1)].transportCancelTasksAction.execute(request).get();
    // Awaiting for the main task to finish
    responseLatch.await();
    if (response.getTasks().size() == 0) {
        // We didn't cancel the request and it finished successfully
        // That should be rare and can be only in case we didn't block on a single node
        assertEquals(0, blockedNodesCount);
        // Make sure that the request was successful
        assertNull(throwableReference.get());
        assertNotNull(responseReference.get());
        assertEquals(nodesCount, responseReference.get().getNodes().size());
        assertEquals(0, responseReference.get().failureCount());
    } else {
        // We canceled the request, in this case it should have fail, but we should get partial response
        assertNull(throwableReference.get());
        assertEquals(nodesCount, responseReference.get().failureCount() + responseReference.get().getNodes().size());
        // and we should have at least as many failures as the number of blocked operations
        // (we might have cancelled some non-blocked operations before they even started and that's ok)
        assertThat(responseReference.get().failureCount(), greaterThanOrEqualTo(blockedNodesCount));
        // We should have the information about the cancelled task in the cancel operation response
        assertEquals(1, response.getTasks().size());
        assertEquals(mainTask.getId(), response.getTasks().get(0).getId());
        // Verify that all cancelled tasks reported that they support cancellation
        for (TaskInfo taskInfo : response.getTasks()) {
            assertTrue(taskInfo.isCancellable());
        }
    }
    // Make sure that tasks are no longer running
    ListTasksResponse listTasksResponse = testNodes[randomIntBetween(0, testNodes.length - 1)].transportListTasksAction.execute(new ListTasksRequest().setTaskId(new TaskId(testNodes[0].getNodeId(), mainTask.getId()))).get();
    assertEquals(0, listTasksResponse.getTasks().size());
    // Make sure that there are no leftover bans, the ban removal is async, so we might return from the cancellation
    // while the ban is still there, but it should disappear shortly
    assertBusy(() -> {
        for (int i = 0; i < testNodes.length; i++) {
            assertEquals("No bans on the node " + i, 0, testNodes[i].transportService.getTaskManager().getBanCount());
        }
    });
}
Also used : CancellableTask(org.elasticsearch.tasks.CancellableTask) Task(org.elasticsearch.tasks.Task) TaskId(org.elasticsearch.tasks.TaskId) CancelTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse) CancelTasksRequest(org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TaskCancelledException(org.elasticsearch.tasks.TaskCancelledException) TaskInfo(org.elasticsearch.tasks.TaskInfo) ListTasksRequest(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksRequest)

Example 23 with Task

use of org.elasticsearch.tasks.Task in project elasticsearch by elastic.

the class TransportReindexAction method buildRestClient.

/**
     * Build the {@link RestClient} used for reindexing from remote clusters.
     * @param remoteInfo connection information for the remote cluster
     * @param taskId the id of the current task. This is added to the thread name for easier tracking
     * @param threadCollector a list in which we collect all the threads created by the client
     */
static RestClient buildRestClient(RemoteInfo remoteInfo, long taskId, List<Thread> threadCollector) {
    Header[] clientHeaders = new Header[remoteInfo.getHeaders().size()];
    int i = 0;
    for (Map.Entry<String, String> header : remoteInfo.getHeaders().entrySet()) {
        clientHeaders[i] = new BasicHeader(header.getKey(), header.getValue());
    }
    return RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme())).setDefaultHeaders(clientHeaders).setRequestConfigCallback(c -> {
        c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis()));
        c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis()));
        return c;
    }).setHttpClientConfigCallback(c -> {
        if (remoteInfo.getUsername() != null) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteInfo.getUsername(), remoteInfo.getPassword());
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, creds);
            c.setDefaultCredentialsProvider(credentialsProvider);
        }
        AtomicInteger threads = new AtomicInteger();
        c.setThreadFactory(r -> {
            String name = "es-client-" + taskId + "-" + threads.getAndIncrement();
            Thread t = new Thread(r, name);
            threadCollector.add(t);
            return t;
        });
        c.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
        return c;
    }).build();
}
Also used : Versions(org.elasticsearch.common.lucene.uid.Versions) RemoteScrollableHitSource(org.elasticsearch.index.reindex.remote.RemoteScrollableHitSource) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) Property(org.elasticsearch.common.settings.Setting.Property) BiFunction(java.util.function.BiFunction) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Header(org.apache.http.Header) VersionType(org.elasticsearch.index.VersionType) AutoCreateIndex(org.elasticsearch.action.support.AutoCreateIndex) RemoteInfo(org.elasticsearch.index.reindex.remote.RemoteInfo) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) IndexRequest(org.elasticsearch.action.index.IndexRequest) ClusterState(org.elasticsearch.cluster.ClusterState) Operations(org.apache.lucene.util.automaton.Operations) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ParentBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.ParentBulkByScrollTask) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Failure(org.elasticsearch.action.bulk.BulkItemResponse.Failure) Automata(org.apache.lucene.util.automaton.Automata) AbstractAsyncBulkByScrollAction(org.elasticsearch.action.bulk.byscroll.AbstractAsyncBulkByScrollAction) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) WorkingBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.WorkingBulkByScrollTask) BulkByScrollResponse(org.elasticsearch.action.bulk.byscroll.BulkByScrollResponse) ActionFilters(org.elasticsearch.action.support.ActionFilters) Setting(org.elasticsearch.common.settings.Setting) Collections.synchronizedList(java.util.Collections.synchronizedList) Automaton(org.apache.lucene.util.automaton.Automaton) Collections.emptyList(java.util.Collections.emptyList) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) CredentialsProvider(org.apache.http.client.CredentialsProvider) Task(org.elasticsearch.tasks.Task) RestClient(org.elasticsearch.client.RestClient) XContentType(org.elasticsearch.common.xcontent.XContentType) ClusterService(org.elasticsearch.cluster.service.ClusterService) SearchRequest(org.elasticsearch.action.search.SearchRequest) INTERNAL(org.elasticsearch.index.VersionType.INTERNAL) Function(java.util.function.Function) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ScrollableHitSource(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource) HandledTransportAction(org.elasticsearch.action.support.HandledTransportAction) ParentTaskAssigningClient(org.elasticsearch.client.ParentTaskAssigningClient) Objects.requireNonNull(java.util.Objects.requireNonNull) Regex(org.elasticsearch.common.regex.Regex) TransportService(org.elasticsearch.transport.TransportService) CharacterRunAutomaton(org.apache.lucene.util.automaton.CharacterRunAutomaton) Script(org.elasticsearch.script.Script) BulkByScrollParallelizationHelper(org.elasticsearch.action.bulk.byscroll.BulkByScrollParallelizationHelper) Client(org.elasticsearch.client.Client) IOException(java.io.IOException) MinimizationOperations(org.apache.lucene.util.automaton.MinimizationOperations) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) XContentParser(org.elasticsearch.common.xcontent.XContentParser) VersionFieldMapper(org.elasticsearch.index.mapper.VersionFieldMapper) AuthScope(org.apache.http.auth.AuthScope) SearchFailure(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.SearchFailure) BasicHeader(org.apache.http.message.BasicHeader) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) HttpHost(org.apache.http.HttpHost) ScriptService(org.elasticsearch.script.ScriptService) ActionListener(org.elasticsearch.action.ActionListener) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpHost(org.apache.http.HttpHost) Map(java.util.Map) BasicHeader(org.apache.http.message.BasicHeader)

Example 24 with Task

use of org.elasticsearch.tasks.Task in project elasticsearch by elastic.

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));
    // 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 : AbstractBulkByScrollRequest(org.elasticsearch.action.bulk.byscroll.AbstractBulkByScrollRequest) BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) BulkByScrollResponse(org.elasticsearch.action.bulk.byscroll.BulkByScrollResponse) IOException(java.io.IOException) HashMap(java.util.HashMap) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) LoggingTaskListener(org.elasticsearch.tasks.LoggingTaskListener) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) Settings(org.elasticsearch.common.settings.Settings) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) RestStatus(org.elasticsearch.rest.RestStatus) Map(java.util.Map) RestRequest(org.elasticsearch.rest.RestRequest) NodeClient(org.elasticsearch.client.node.NodeClient) BulkByScrollTask(org.elasticsearch.action.bulk.byscroll.BulkByScrollTask) Task(org.elasticsearch.tasks.Task) GenericAction(org.elasticsearch.action.GenericAction) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) HashMap(java.util.HashMap) AbstractBulkByScrollRequest(org.elasticsearch.action.bulk.byscroll.AbstractBulkByScrollRequest) RestRequest(org.elasticsearch.rest.RestRequest)

Aggregations

Task (org.elasticsearch.tasks.Task)24 CountDownLatch (java.util.concurrent.CountDownLatch)13 IOException (java.io.IOException)10 ExecutionException (java.util.concurrent.ExecutionException)8 ActionListener (org.elasticsearch.action.ActionListener)8 ListTasksResponse (org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse)7 TransportService (org.elasticsearch.transport.TransportService)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 Map (java.util.Map)6 ActionFilters (org.elasticsearch.action.support.ActionFilters)6 IndexNameExpressionResolver (org.elasticsearch.cluster.metadata.IndexNameExpressionResolver)6 Settings (org.elasticsearch.common.settings.Settings)6 ActionRequestValidationException (org.elasticsearch.action.ActionRequestValidationException)5 CancelTasksResponse (org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse)5 ListTasksRequest (org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksRequest)5 ClusterState (org.elasticsearch.cluster.ClusterState)5 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)5 ClusterService (org.elasticsearch.cluster.service.ClusterService)5 TaskId (org.elasticsearch.tasks.TaskId)5