Search in sources :

Example 1 with TaskManager

use of org.opensearch.tasks.TaskManager in project OpenSearch by opensearch-project.

the class CancellableTasksIT method testBanOnlyNodesWithOutstandingDescendantTasks.

public void testBanOnlyNodesWithOutstandingDescendantTasks() throws Exception {
    if (randomBoolean()) {
        internalCluster().startNodes(randomIntBetween(1, 3));
    }
    Set<DiscoveryNode> nodes = StreamSupport.stream(clusterService().state().nodes().spliterator(), false).collect(Collectors.toSet());
    final TestRequest rootRequest = generateTestRequest(nodes, 0, between(1, 4));
    ActionFuture<TestResponse> rootTaskFuture = client().execute(TransportTestAction.ACTION, rootRequest);
    Set<TestRequest> pendingRequests = allowPartialRequest(rootRequest);
    TaskId rootTaskId = getRootTaskId(rootRequest);
    ActionFuture<CancelTasksResponse> cancelFuture = client().admin().cluster().prepareCancelTasks().setTaskId(rootTaskId).waitForCompletion(true).execute();
    if (randomBoolean()) {
        List<TaskInfo> runningTasks = client().admin().cluster().prepareListTasks().setActions(TransportTestAction.ACTION.name()).setDetailed(true).get().getTasks();
        for (TaskInfo subTask : randomSubsetOf(runningTasks)) {
            client().admin().cluster().prepareCancelTasks().setTaskId(subTask.getTaskId()).waitForCompletion(false).get();
        }
    }
    assertBusy(() -> {
        for (DiscoveryNode node : nodes) {
            TaskManager taskManager = internalCluster().getInstance(TransportService.class, node.getName()).getTaskManager();
            Set<TaskId> expectedBans = new HashSet<>();
            for (TestRequest req : pendingRequests) {
                if (req.node.equals(node)) {
                    List<Task> childTasks = taskManager.getTasks().values().stream().filter(t -> t.getParentTaskId() != null && t.getDescription().equals(req.taskDescription())).collect(Collectors.toList());
                    assertThat(childTasks, hasSize(1));
                    CancellableTask childTask = (CancellableTask) childTasks.get(0);
                    assertTrue(childTask.isCancelled());
                    expectedBans.add(childTask.getParentTaskId());
                }
            }
            assertThat(taskManager.getBannedTaskIds(), equalTo(expectedBans));
        }
    }, 30, TimeUnit.SECONDS);
    allowEntireRequest(rootRequest);
    cancelFuture.actionGet();
    waitForRootTask(rootTaskFuture);
    ensureAllBansRemoved();
}
Also used : ActionPlugin(org.opensearch.plugins.ActionPlugin) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) ActionRequest(org.opensearch.action.ActionRequest) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) LatchedActionListener(org.opensearch.action.LatchedActionListener) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Map(java.util.Map) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) ActionResponse(org.opensearch.action.ActionResponse) ActionType(org.opensearch.action.ActionType) CancelTasksResponse(org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse) CancellableTask(org.opensearch.tasks.CancellableTask) NodeClient(org.opensearch.client.node.NodeClient) Collection(java.util.Collection) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Task(org.opensearch.tasks.Task) TransportService(org.opensearch.transport.TransportService) Collectors(java.util.stream.Collectors) TaskManager(org.opensearch.tasks.TaskManager) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ActionFilters(org.opensearch.action.support.ActionFilters) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TaskCancelledException(org.opensearch.tasks.TaskCancelledException) Matchers.anyOf(org.hamcrest.Matchers.anyOf) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) TransportException(org.opensearch.transport.TransportException) HandledTransportAction(org.opensearch.action.support.HandledTransportAction) ActionRunnable(org.opensearch.action.ActionRunnable) ThreadPool(org.opensearch.threadpool.ThreadPool) StreamOutput(org.opensearch.common.io.stream.StreamOutput) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) InternalTestCluster(org.opensearch.test.InternalTestCluster) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) Matchers.hasSize(org.hamcrest.Matchers.hasSize) StreamSupport(java.util.stream.StreamSupport) Before(org.junit.Before) StreamInput(org.opensearch.common.io.stream.StreamInput) Matchers.empty(org.hamcrest.Matchers.empty) SetOnce(org.apache.lucene.util.SetOnce) TaskId(org.opensearch.tasks.TaskId) TransportResponseHandler(org.opensearch.transport.TransportResponseHandler) IOException(java.io.IOException) Plugin(org.opensearch.plugins.Plugin) ActionFuture(org.opensearch.action.ActionFuture) TimeUnit(java.util.concurrent.TimeUnit) Sets(org.opensearch.common.util.set.Sets) TaskInfo(org.opensearch.tasks.TaskInfo) Collections(java.util.Collections) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) CancellableTask(org.opensearch.tasks.CancellableTask) Task(org.opensearch.tasks.Task) TaskId(org.opensearch.tasks.TaskId) CancelTasksResponse(org.opensearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse) TaskInfo(org.opensearch.tasks.TaskInfo) TaskManager(org.opensearch.tasks.TaskManager) CancellableTask(org.opensearch.tasks.CancellableTask) TransportService(org.opensearch.transport.TransportService) HashSet(java.util.HashSet)

Example 2 with TaskManager

use of org.opensearch.tasks.TaskManager in project OpenSearch by opensearch-project.

the class PrimaryReplicaSyncerTests method testSyncerSendsOffCorrectDocuments.

public void testSyncerSendsOffCorrectDocuments() throws Exception {
    IndexShard shard = newStartedShard(true);
    TaskManager taskManager = new TaskManager(Settings.EMPTY, threadPool, Collections.emptySet());
    AtomicBoolean syncActionCalled = new AtomicBoolean();
    List<ResyncReplicationRequest> resyncRequests = new ArrayList<>();
    PrimaryReplicaSyncer.SyncAction syncAction = (request, parentTask, allocationId, primaryTerm, listener) -> {
        logger.info("Sending off {} operations", request.getOperations().length);
        syncActionCalled.set(true);
        resyncRequests.add(request);
        assertThat(parentTask, instanceOf(PrimaryReplicaSyncer.ResyncTask.class));
        listener.onResponse(new ResyncReplicationResponse());
    };
    PrimaryReplicaSyncer syncer = new PrimaryReplicaSyncer(taskManager, syncAction);
    syncer.setChunkSize(new ByteSizeValue(randomIntBetween(1, 10)));
    int numDocs = randomInt(10);
    for (int i = 0; i < numDocs; i++) {
        // Index doc but not advance local checkpoint.
        shard.applyIndexOperationOnPrimary(Versions.MATCH_ANY, VersionType.INTERNAL, new SourceToParse(shard.shardId().getIndexName(), "_doc", Integer.toString(i), new BytesArray("{}"), XContentType.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, true);
    }
    long globalCheckPoint = numDocs > 0 ? randomIntBetween(0, numDocs - 1) : 0;
    boolean syncNeeded = numDocs > 0;
    String allocationId = shard.routingEntry().allocationId().getId();
    shard.updateShardState(shard.routingEntry(), shard.getPendingPrimaryTerm(), null, 1000L, Collections.singleton(allocationId), new IndexShardRoutingTable.Builder(shard.shardId()).addShard(shard.routingEntry()).build());
    shard.updateLocalCheckpointForShard(allocationId, globalCheckPoint);
    assertEquals(globalCheckPoint, shard.getLastKnownGlobalCheckpoint());
    logger.info("Total ops: {}, global checkpoint: {}", numDocs, globalCheckPoint);
    PlainActionFuture<PrimaryReplicaSyncer.ResyncTask> fut = new PlainActionFuture<>();
    syncer.resync(shard, fut);
    PrimaryReplicaSyncer.ResyncTask resyncTask = fut.get();
    if (syncNeeded) {
        assertTrue("Sync action was not called", syncActionCalled.get());
        ResyncReplicationRequest resyncRequest = resyncRequests.remove(0);
        assertThat(resyncRequest.getTrimAboveSeqNo(), equalTo(numDocs - 1L));
        assertThat("trimAboveSeqNo has to be specified in request #0 only", resyncRequests.stream().mapToLong(ResyncReplicationRequest::getTrimAboveSeqNo).filter(seqNo -> seqNo != SequenceNumbers.UNASSIGNED_SEQ_NO).findFirst().isPresent(), is(false));
        assertThat(resyncRequest.getMaxSeenAutoIdTimestampOnPrimary(), equalTo(shard.getMaxSeenAutoIdTimestamp()));
    }
    if (syncNeeded && globalCheckPoint < numDocs - 1) {
        assertThat(resyncTask.getSkippedOperations(), equalTo(0));
        assertThat(resyncTask.getResyncedOperations(), equalTo(Math.toIntExact(numDocs - 1 - globalCheckPoint)));
        if (shard.indexSettings.isSoftDeleteEnabled()) {
            assertThat(resyncTask.getTotalOperations(), equalTo(Math.toIntExact(numDocs - 1 - globalCheckPoint)));
        } else {
            assertThat(resyncTask.getTotalOperations(), equalTo(numDocs));
        }
    } else {
        assertThat(resyncTask.getSkippedOperations(), equalTo(0));
        assertThat(resyncTask.getResyncedOperations(), equalTo(0));
        assertThat(resyncTask.getTotalOperations(), equalTo(0));
    }
    closeShards(shard);
}
Also used : ResyncReplicationResponse(org.opensearch.action.resync.ResyncReplicationResponse) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) IsInstanceOf.instanceOf(org.hamcrest.core.IsInstanceOf.instanceOf) ToXContent(org.opensearch.common.xcontent.ToXContent) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) ByteBufferStreamInput(org.opensearch.common.io.stream.ByteBufferStreamInput) ByteBuffer(java.nio.ByteBuffer) Strings(org.opensearch.common.Strings) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) SourceToParse(org.opensearch.index.mapper.SourceToParse) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) NetworkModule(org.opensearch.common.network.NetworkModule) XContentFactory(org.opensearch.common.xcontent.XContentFactory) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) StreamInput(org.opensearch.common.io.stream.StreamInput) Versions(org.opensearch.common.lucene.uid.Versions) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) Task(org.opensearch.tasks.Task) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) TaskManager(org.opensearch.tasks.TaskManager) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) List(java.util.List) BytesArray(org.opensearch.common.bytes.BytesArray) Matchers.equalTo(org.hamcrest.Matchers.equalTo) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.is(org.hamcrest.Matchers.is) ResyncReplicationRequest(org.opensearch.action.resync.ResyncReplicationRequest) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) BytesArray(org.opensearch.common.bytes.BytesArray) ArrayList(java.util.ArrayList) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) SourceToParse(org.opensearch.index.mapper.SourceToParse) Matchers.containsString(org.hamcrest.Matchers.containsString) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TaskManager(org.opensearch.tasks.TaskManager) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) ResyncReplicationRequest(org.opensearch.action.resync.ResyncReplicationRequest) ResyncReplicationResponse(org.opensearch.action.resync.ResyncReplicationResponse)

Example 3 with TaskManager

use of org.opensearch.tasks.TaskManager in project OpenSearch by opensearch-project.

the class TransportActionFilterChainTests method testActionFiltersRequest.

public void testActionFiltersRequest() throws InterruptedException {
    int numFilters = randomInt(10);
    Set<Integer> orders = new HashSet<>(numFilters);
    while (orders.size() < numFilters) {
        orders.add(randomInt(10));
    }
    Set<ActionFilter> filters = new HashSet<>();
    for (Integer order : orders) {
        filters.add(new RequestTestFilter(order, randomFrom(RequestOperation.values())));
    }
    String actionName = randomAlphaOfLength(randomInt(30));
    ActionFilters actionFilters = new ActionFilters(filters);
    TransportAction<TestRequest, TestResponse> transportAction = new TransportAction<TestRequest, TestResponse>(actionName, actionFilters, new TaskManager(Settings.EMPTY, threadPool, Collections.emptySet())) {

        @Override
        protected void doExecute(Task task, TestRequest request, ActionListener<TestResponse> listener) {
            listener.onResponse(new TestResponse());
        }
    };
    ArrayList<ActionFilter> actionFiltersByOrder = new ArrayList<>(filters);
    actionFiltersByOrder.sort(Comparator.comparingInt(ActionFilter::order));
    List<ActionFilter> expectedActionFilters = new ArrayList<>();
    boolean errorExpected = false;
    for (ActionFilter filter : actionFiltersByOrder) {
        RequestTestFilter testFilter = (RequestTestFilter) filter;
        expectedActionFilters.add(testFilter);
        if (testFilter.callback == RequestOperation.LISTENER_FAILURE) {
            errorExpected = true;
        }
        if (!(testFilter.callback == RequestOperation.CONTINUE_PROCESSING)) {
            break;
        }
    }
    PlainActionFuture<TestResponse> future = PlainActionFuture.newFuture();
    transportAction.execute(new TestRequest(), future);
    try {
        assertThat(future.get(), notNullValue());
        assertThat("shouldn't get here if an error is expected", errorExpected, equalTo(false));
    } catch (ExecutionException e) {
        assertThat("shouldn't get here if an error is not expected " + e.getMessage(), errorExpected, equalTo(true));
    }
    List<RequestTestFilter> testFiltersByLastExecution = new ArrayList<>();
    for (ActionFilter actionFilter : actionFilters.filters()) {
        testFiltersByLastExecution.add((RequestTestFilter) actionFilter);
    }
    testFiltersByLastExecution.sort(Comparator.comparingInt(o -> o.executionToken));
    ArrayList<RequestTestFilter> finalTestFilters = new ArrayList<>();
    for (ActionFilter filter : testFiltersByLastExecution) {
        RequestTestFilter testFilter = (RequestTestFilter) filter;
        finalTestFilters.add(testFilter);
        if (!(testFilter.callback == RequestOperation.CONTINUE_PROCESSING)) {
            break;
        }
    }
    assertThat(finalTestFilters.size(), equalTo(expectedActionFilters.size()));
    for (int i = 0; i < finalTestFilters.size(); i++) {
        RequestTestFilter testFilter = finalTestFilters.get(i);
        assertThat(testFilter, equalTo(expectedActionFilters.get(i)));
        assertThat(testFilter.runs.get(), equalTo(1));
        assertThat(testFilter.lastActionName, equalTo(actionName));
    }
}
Also used : CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ThreadPool(org.opensearch.threadpool.ThreadPool) StreamOutput(org.opensearch.common.io.stream.StreamOutput) ActionRequest(org.opensearch.action.ActionRequest) Node(org.opensearch.node.Node) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) ArrayList(java.util.ArrayList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) HashSet(java.util.HashSet) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) LatchedActionListener(org.opensearch.action.LatchedActionListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) ActionListener(org.opensearch.action.ActionListener) ActionResponse(org.opensearch.action.ActionResponse) Before(org.junit.Before) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) Task(org.opensearch.tasks.Task) TaskManager(org.opensearch.tasks.TaskManager) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) OpenSearchTimeoutException(org.opensearch.OpenSearchTimeoutException) Comparator(java.util.Comparator) Collections(java.util.Collections) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Task(org.opensearch.tasks.Task) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ExecutionException(java.util.concurrent.ExecutionException) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TaskManager(org.opensearch.tasks.TaskManager) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener)

Example 4 with TaskManager

use of org.opensearch.tasks.TaskManager in project OpenSearch by opensearch-project.

the class CancellableTasksTests method testRegisterAndExecuteChildTaskWhileParentTaskIsBeingCanceled.

public void testRegisterAndExecuteChildTaskWhileParentTaskIsBeingCanceled() throws Exception {
    setupTestNodes(Settings.EMPTY);
    connectNodes(testNodes);
    final TaskManager taskManager = testNodes[0].transportService.getTaskManager();
    CancellableNodesRequest parentRequest = new CancellableNodesRequest("parent");
    final Task parentTask = taskManager.register("test", "test", parentRequest);
    final TaskId parentTaskId = parentTask.taskInfo(testNodes[0].getNodeId(), false).getTaskId();
    taskManager.setBan(new TaskId(testNodes[0].getNodeId(), parentTask.getId()), "test");
    CancellableNodesRequest childRequest = new CancellableNodesRequest("child");
    childRequest.setParentTask(parentTaskId);
    CancellableTestNodesAction testAction = new CancellableTestNodesAction("internal:testAction", threadPool, testNodes[1].clusterService, testNodes[0].transportService, false, new CountDownLatch(1));
    TaskCancelledException cancelledException = expectThrows(TaskCancelledException.class, () -> testAction.execute(childRequest, ActionListener.wrap(() -> fail("must not execute"))));
    assertThat(cancelledException.getMessage(), startsWith("Task cancelled before it started:"));
    CountDownLatch latch = new CountDownLatch(1);
    taskManager.startBanOnChildrenNodes(parentTaskId.getId(), latch::countDown);
    assertTrue("onChildTasksCompleted() is not invoked", latch.await(1, TimeUnit.SECONDS));
}
Also used : CancellableTask(org.opensearch.tasks.CancellableTask) Task(org.opensearch.tasks.Task) TaskManager(org.opensearch.tasks.TaskManager) TaskId(org.opensearch.tasks.TaskId) TaskCancelledException(org.opensearch.tasks.TaskCancelledException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 5 with TaskManager

use of org.opensearch.tasks.TaskManager in project OpenSearch by opensearch-project.

the class CancellableTasksTests method testCancelConcurrently.

public void testCancelConcurrently() throws Exception {
    setupTestNodes(Settings.EMPTY);
    final TaskManager taskManager = testNodes[0].transportService.getTaskManager();
    int numTasks = randomIntBetween(1, 10);
    List<CancellableTask> tasks = new ArrayList<>(numTasks);
    for (int i = 0; i < numTasks; i++) {
        tasks.add((CancellableTask) taskManager.register("type-" + i, "action-" + i, new CancellableNodeRequest()));
    }
    Thread[] threads = new Thread[randomIntBetween(1, 8)];
    AtomicIntegerArray notified = new AtomicIntegerArray(threads.length);
    Phaser phaser = new Phaser(threads.length + 1);
    final CancellableTask cancellingTask = randomFrom(tasks);
    for (int i = 0; i < threads.length; i++) {
        int idx = i;
        threads[i] = new Thread(() -> {
            phaser.arriveAndAwaitAdvance();
            taskManager.cancel(cancellingTask, "test", () -> assertTrue(notified.compareAndSet(idx, 0, 1)));
        });
        threads[i].start();
    }
    phaser.arriveAndAwaitAdvance();
    taskManager.unregister(cancellingTask);
    for (int i = 0; i < threads.length; i++) {
        threads[i].join();
        assertThat(notified.get(i), equalTo(1));
    }
    AtomicBoolean called = new AtomicBoolean();
    taskManager.cancel(cancellingTask, "test", () -> assertTrue(called.compareAndSet(false, true)));
    assertTrue(called.get());
}
Also used : AtomicIntegerArray(java.util.concurrent.atomic.AtomicIntegerArray) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TaskManager(org.opensearch.tasks.TaskManager) CancellableTask(org.opensearch.tasks.CancellableTask) ArrayList(java.util.ArrayList) Phaser(java.util.concurrent.Phaser)

Aggregations

TaskManager (org.opensearch.tasks.TaskManager)20 Task (org.opensearch.tasks.Task)12 TaskId (org.opensearch.tasks.TaskId)9 IOException (java.io.IOException)8 ActionListener (org.opensearch.action.ActionListener)8 CountDownLatch (java.util.concurrent.CountDownLatch)7 ClusterState (org.opensearch.cluster.ClusterState)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Matchers.equalTo (org.hamcrest.Matchers.equalTo)6 Mockito.anyString (org.mockito.Mockito.anyString)6 Settings (org.opensearch.common.settings.Settings)6 ArrayList (java.util.ArrayList)5 TimeUnit (java.util.concurrent.TimeUnit)5 ActionFilters (org.opensearch.action.support.ActionFilters)5 Metadata (org.opensearch.cluster.metadata.Metadata)5 Collections (java.util.Collections)4 List (java.util.List)4 Map (java.util.Map)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 NamedWriteableRegistry (org.opensearch.common.io.stream.NamedWriteableRegistry)4