Search in sources :

Example 1 with TaskGroup

use of org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup in project OpenSearch by opensearch-project.

the class TasksIT method testListTasks.

public void testListTasks() throws IOException {
    ListTasksRequest request = new ListTasksRequest();
    ListTasksResponse response = execute(request, highLevelClient().tasks()::list, highLevelClient().tasks()::listAsync);
    assertThat(response, notNullValue());
    assertThat(response.getNodeFailures(), equalTo(emptyList()));
    assertThat(response.getTaskFailures(), equalTo(emptyList()));
    // It's possible that there are other tasks except 'cluster:monitor/tasks/lists[n]' and 'action":"cluster:monitor/tasks/lists'
    assertThat(response.getTasks().size(), greaterThanOrEqualTo(2));
    boolean listTasksFound = false;
    for (TaskGroup taskGroup : response.getTaskGroups()) {
        org.opensearch.tasks.TaskInfo parent = taskGroup.getTaskInfo();
        if ("cluster:monitor/tasks/lists".equals(parent.getAction())) {
            assertThat(taskGroup.getChildTasks().size(), equalTo(1));
            TaskGroup childGroup = taskGroup.getChildTasks().iterator().next();
            assertThat(childGroup.getChildTasks().isEmpty(), equalTo(true));
            org.opensearch.tasks.TaskInfo child = childGroup.getTaskInfo();
            assertThat(child.getAction(), equalTo("cluster:monitor/tasks/lists[n]"));
            assertThat(child.getParentTaskId(), equalTo(parent.getTaskId()));
            listTasksFound = true;
        }
    }
    assertTrue("List tasks were not found", listTasksFound);
}
Also used : ListTasksRequest(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup)

Example 2 with TaskGroup

use of org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup in project OpenSearch by opensearch-project.

the class OpenSearchRestHighLevelClientTestCase method findTaskToRethrottle.

protected static TaskId findTaskToRethrottle(String actionName, String description) throws IOException {
    long start = System.nanoTime();
    ListTasksRequest request = new ListTasksRequest();
    request.setActions(actionName);
    request.setDetailed(true);
    do {
        ListTasksResponse list = highLevelClient().tasks().list(request, RequestOptions.DEFAULT);
        list.rethrowFailures("Finding tasks to rethrottle");
        List<TaskGroup> taskGroups = list.getTaskGroups().stream().filter(taskGroup -> taskGroup.getTaskInfo().getDescription().equals(description)).collect(Collectors.toList());
        assertThat("tasks are left over from the last execution of this test", taskGroups, hasSize(lessThan(2)));
        if (0 == taskGroups.size()) {
            // The parent task hasn't started yet
            continue;
        }
        TaskGroup taskGroup = taskGroups.get(0);
        assertThat(taskGroup.getChildTasks(), empty());
        return taskGroup.getTaskInfo().getTaskId();
    } while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10));
    throw new AssertionError("Couldn't find tasks to rethrottle. Here are the running tasks " + highLevelClient().tasks().list(request, RequestOptions.DEFAULT));
}
Also used : RemoteInfoResponse(org.opensearch.client.cluster.RemoteInfoResponse) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup) Arrays(java.util.Arrays) PutPipelineRequest(org.opensearch.action.ingest.PutPipelineRequest) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) EntityUtils(org.apache.http.util.EntityUtils) ListTasksRequest(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) AfterClass(org.junit.AfterClass) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) SearchHit(org.opensearch.search.SearchHit) Settings(org.opensearch.common.settings.Settings) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) OpenSearchRestTestCase(org.opensearch.test.rest.OpenSearchRestTestCase) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) CheckedRunnable(org.opensearch.common.CheckedRunnable) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) XContentFactory.jsonBuilder(org.opensearch.common.xcontent.XContentFactory.jsonBuilder) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) BytesReference(org.opensearch.common.bytes.BytesReference) ClusterUpdateSettingsRequest(org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest) ClusterUpdateSettingsResponse(org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) Booleans(org.opensearch.common.Booleans) Matchers.lessThan(org.hamcrest.Matchers.lessThan) SearchRequest(org.opensearch.action.search.SearchRequest) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Collections.singletonMap(java.util.Collections.singletonMap) SearchResponse(org.opensearch.action.search.SearchResponse) Before(org.junit.Before) Matchers.empty(org.hamcrest.Matchers.empty) Pipeline(org.opensearch.ingest.Pipeline) TaskId(org.opensearch.tasks.TaskId) IOException(java.io.IOException) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) IOUtils(org.opensearch.core.internal.io.IOUtils) TimeUnit(java.util.concurrent.TimeUnit) JsonXContent(org.opensearch.common.xcontent.json.JsonXContent) RemoteInfoRequest(org.opensearch.client.cluster.RemoteInfoRequest) Collections(java.util.Collections) SearchModule(org.opensearch.search.SearchModule) ListTasksRequest(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup)

Example 3 with TaskGroup

use of org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup in project OpenSearch by opensearch-project.

the class RethrottleTests method testCase.

private void testCase(AbstractBulkByScrollRequestBuilder<?, ?> request, String actionName) throws Exception {
    logger.info("Starting test for [{}] with [{}] slices", actionName, request.request().getSlices());
    /* Add ten documents per slice so most slices will have many documents to process, having to go to multiple batches.
         * We can't rely on the slices being evenly sized but 10 means we have some pretty big slices.
         */
    createIndex("test");
    int numSlices = expectedSlices(request.request().getSlices(), "test");
    List<IndexRequestBuilder> docs = new ArrayList<>();
    for (int i = 0; i < numSlices * 10; i++) {
        docs.add(client().prepareIndex("test").setId(Integer.toString(i)).setSource("foo", "bar"));
    }
    indexRandom(true, docs);
    // Start a request that will never finish unless we rethrottle it
    // Throttle "forever"
    request.setRequestsPerSecond(.000001f);
    // Make sure we use multiple batches
    request.source().setSize(1);
    ActionFuture<? extends BulkByScrollResponse> responseListener = request.execute();
    TaskGroup taskGroupToRethrottle = findTaskToRethrottle(actionName, numSlices);
    TaskId taskToRethrottle = taskGroupToRethrottle.getTaskInfo().getTaskId();
    if (numSlices == 1) {
        assertThat(taskGroupToRethrottle.getChildTasks(), empty());
    } else {
        // There should be a sane number of child tasks running
        assertThat(taskGroupToRethrottle.getChildTasks(), hasSize(allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(numSlices))));
        // Wait for all of the sub tasks to start (or finish, some might finish early, all that matters is that not all do)
        assertBusy(() -> {
            BulkByScrollTask.Status parent = (BulkByScrollTask.Status) client().admin().cluster().prepareGetTask(taskToRethrottle).get().getTask().getTask().getStatus();
            long finishedSubTasks = parent.getSliceStatuses().stream().filter(Objects::nonNull).count();
            ListTasksResponse list = client().admin().cluster().prepareListTasks().setParentTaskId(taskToRethrottle).get();
            list.rethrowFailures("subtasks");
            assertThat(finishedSubTasks + list.getTasks().size(), greaterThanOrEqualTo((long) numSlices));
            assertThat(list.getTasks().size(), greaterThan(0));
        });
    }
    // Now rethrottle it so it'll finish
    // No throttle or "very fast"
    float newRequestsPerSecond = randomBoolean() ? Float.POSITIVE_INFINITY : between(1, 1000) * 100000;
    ListTasksResponse rethrottleResponse = rethrottleTask(taskToRethrottle, newRequestsPerSecond);
    BulkByScrollTask.Status status = (BulkByScrollTask.Status) rethrottleResponse.getTasks().get(0).getStatus();
    // Now check the resulting requests per second.
    if (numSlices == 1) {
        // If there is a single slice it should match perfectly
        assertEquals(newRequestsPerSecond, status.getRequestsPerSecond(), Float.MIN_NORMAL);
    } else {
        /* Check that at least one slice was rethrottled. We won't always rethrottle all of them because they might have completed.
             * With multiple slices these numbers might not add up perfectly, thus the 1.01F. */
        long unfinished = status.getSliceStatuses().stream().filter(Objects::nonNull).filter(slice -> slice.getStatus().getTotal() > slice.getStatus().getSuccessfullyProcessed()).count();
        float maxExpectedSliceRequestsPerSecond = newRequestsPerSecond == Float.POSITIVE_INFINITY ? Float.POSITIVE_INFINITY : (newRequestsPerSecond / unfinished) * 1.01F;
        float minExpectedSliceRequestsPerSecond = newRequestsPerSecond == Float.POSITIVE_INFINITY ? Float.POSITIVE_INFINITY : (newRequestsPerSecond / numSlices) * 0.99F;
        boolean oneSliceRethrottled = false;
        float totalRequestsPerSecond = 0;
        for (BulkByScrollTask.StatusOrException statusOrException : status.getSliceStatuses()) {
            if (statusOrException == null) {
                /* The slice can be null here because it was completed but hadn't reported its success back to the task when the
                     * rethrottle request came through. */
                continue;
            }
            assertNull(statusOrException.getException());
            BulkByScrollTask.Status slice = statusOrException.getStatus();
            if (slice.getTotal() > slice.getSuccessfullyProcessed()) {
                // This slice reports as not having completed so it should have been processed.
                assertThat(slice.getRequestsPerSecond(), both(greaterThanOrEqualTo(minExpectedSliceRequestsPerSecond)).and(lessThanOrEqualTo(maxExpectedSliceRequestsPerSecond)));
            }
            if (minExpectedSliceRequestsPerSecond <= slice.getRequestsPerSecond() && slice.getRequestsPerSecond() <= maxExpectedSliceRequestsPerSecond) {
                oneSliceRethrottled = true;
            }
            totalRequestsPerSecond += slice.getRequestsPerSecond();
        }
        assertTrue("At least one slice must be rethrottled", oneSliceRethrottled);
        /* Now assert that the parent request has the total requests per second. This is a much weaker assertion than that the parent
             * actually has the newRequestsPerSecond. For the most part it will. Sometimes it'll be greater because only unfinished requests
             * are rethrottled, the finished ones just keep whatever requests per second they had while they were running. But it might
             * also be less than newRequestsPerSecond because the newRequestsPerSecond is divided among running sub-requests and then the
             * requests are rethrottled. If one request finishes in between the division and the application of the new throttle then it
             * won't be rethrottled, thus only contributing its lower total. */
        assertEquals(totalRequestsPerSecond, status.getRequestsPerSecond(), totalRequestsPerSecond * 0.0001f);
    }
    // Now the response should come back quickly because we've rethrottled the request
    BulkByScrollResponse response = responseListener.get();
    // It'd be bad if the entire require completed in a single batch. The test wouldn't be testing anything.
    assertThat("Entire request completed in a single batch. This may invalidate the test as throttling is done between batches.", response.getBatches(), greaterThanOrEqualTo(numSlices));
}
Also used : IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) QueryBuilders(org.opensearch.index.query.QueryBuilders) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Matchers.allOf(org.hamcrest.Matchers.allOf) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) ExceptionsHelper(org.opensearch.ExceptionsHelper) TaskId(org.opensearch.tasks.TaskId) OpenSearchException(org.opensearch.OpenSearchException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionFuture(org.opensearch.action.ActionFuture) ArrayList(java.util.ArrayList) Matchers.both(org.hamcrest.Matchers.both) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) TaskId(org.opensearch.tasks.TaskId) ArrayList(java.util.ArrayList) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) Objects(java.util.Objects) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup)

Example 4 with TaskGroup

use of org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup in project OpenSearch by opensearch-project.

the class TasksClientDocumentationIT method testListTasks.

@SuppressWarnings("unused")
public void testListTasks() throws IOException {
    RestHighLevelClient client = highLevelClient();
    {
        // tag::list-tasks-request
        ListTasksRequest request = new ListTasksRequest();
        // end::list-tasks-request
        // tag::list-tasks-request-filter
        // <1>
        request.setActions("cluster:*");
        // <2>
        request.setNodes("nodeId1", "nodeId2");
        // <3>
        request.setParentTaskId(new TaskId("parentTaskId", 42));
        // end::list-tasks-request-filter
        // tag::list-tasks-request-detailed
        // <1>
        request.setDetailed(true);
        // end::list-tasks-request-detailed
        // tag::list-tasks-request-wait-completion
        // <1>
        request.setWaitForCompletion(true);
        // <2>
        request.setTimeout(TimeValue.timeValueSeconds(50));
        // <3>
        request.setTimeout("50s");
    // end::list-tasks-request-wait-completion
    }
    ListTasksRequest request = new ListTasksRequest();
    // tag::list-tasks-execute
    ListTasksResponse response = client.tasks().list(request, RequestOptions.DEFAULT);
    // end::list-tasks-execute
    assertThat(response, notNullValue());
    // tag::list-tasks-response-tasks
    // <1>
    List<TaskInfo> tasks = response.getTasks();
    // end::list-tasks-response-tasks
    // tag::list-tasks-response-calc
    // <1>
    Map<String, List<TaskInfo>> perNodeTasks = response.getPerNodeTasks();
    // <2>
    List<TaskGroup> groups = response.getTaskGroups();
    // end::list-tasks-response-calc
    // tag::list-tasks-response-failures
    // <1>
    List<OpenSearchException> nodeFailures = response.getNodeFailures();
    // <2>
    List<TaskOperationFailure> taskFailures = response.getTaskFailures();
    // end::list-tasks-response-failures
    assertThat(response.getNodeFailures(), equalTo(emptyList()));
    assertThat(response.getTaskFailures(), equalTo(emptyList()));
    assertThat(response.getTasks().size(), greaterThanOrEqualTo(2));
}
Also used : TaskId(org.opensearch.tasks.TaskId) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) TaskInfo(org.opensearch.tasks.TaskInfo) TaskOperationFailure(org.opensearch.action.TaskOperationFailure) ListTasksRequest(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) OpenSearchException(org.opensearch.OpenSearchException) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup)

Example 5 with TaskGroup

use of org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup in project OpenSearch by opensearch-project.

the class RethrottleTests method findTaskToRethrottle.

private TaskGroup findTaskToRethrottle(String actionName, int sliceCount) {
    long start = System.nanoTime();
    do {
        ListTasksResponse tasks = client().admin().cluster().prepareListTasks().setActions(actionName).setDetailed(true).get();
        tasks.rethrowFailures("Finding tasks to rethrottle");
        assertThat("tasks are left over from the last execution of this test", tasks.getTaskGroups(), hasSize(lessThan(2)));
        if (0 == tasks.getTaskGroups().size()) {
            // The parent task hasn't started yet
            continue;
        }
        TaskGroup taskGroup = tasks.getTaskGroups().get(0);
        if (sliceCount != 1) {
            BulkByScrollTask.Status status = (BulkByScrollTask.Status) taskGroup.getTaskInfo().getStatus();
            /*
                 * If there are child tasks wait for all of them to start. It
                 * is possible that we'll end up with some very small slices
                 * (maybe even empty!) that complete super fast so we have to
                 * count them too.
                 */
            long finishedChildStatuses = status.getSliceStatuses().stream().filter(n -> n != null).count();
            logger.info("Expected [{}] total children, [{}] are running and [{}] are finished\n{}", sliceCount, taskGroup.getChildTasks().size(), finishedChildStatuses, status.getSliceStatuses());
            if (sliceCount == finishedChildStatuses) {
                fail("all slices finished:\n" + status);
            }
            if (sliceCount != taskGroup.getChildTasks().size() + finishedChildStatuses) {
                continue;
            }
        }
        return taskGroup;
    } while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10));
    throw new AssertionError("Couldn't find tasks to rethrottle. Here are the running tasks " + client().admin().cluster().prepareListTasks().get());
}
Also used : IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) QueryBuilders(org.opensearch.index.query.QueryBuilders) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Matchers.allOf(org.hamcrest.Matchers.allOf) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) ExceptionsHelper(org.opensearch.ExceptionsHelper) TaskId(org.opensearch.tasks.TaskId) OpenSearchException(org.opensearch.OpenSearchException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ActionFuture(org.opensearch.action.ActionFuture) ArrayList(java.util.ArrayList) Matchers.both(org.hamcrest.Matchers.both) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Matchers.hasSize(org.hamcrest.Matchers.hasSize) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) TaskGroup(org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup)

Aggregations

ListTasksResponse (org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse)7 TaskGroup (org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup)7 List (java.util.List)6 ListTasksRequest (org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest)5 ArrayList (java.util.ArrayList)4 TaskId (org.opensearch.tasks.TaskId)4 Objects (java.util.Objects)3 TimeUnit (java.util.concurrent.TimeUnit)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Matchers.empty (org.hamcrest.Matchers.empty)3 Matchers.greaterThan (org.hamcrest.Matchers.greaterThan)3 Matchers.hasSize (org.hamcrest.Matchers.hasSize)3 Matchers.lessThan (org.hamcrest.Matchers.lessThan)3 OpenSearchException (org.opensearch.OpenSearchException)3 IOException (java.io.IOException)2 Collections (java.util.Collections)2 Map (java.util.Map)2 Matchers.allOf (org.hamcrest.Matchers.allOf)2 Matchers.both (org.hamcrest.Matchers.both)2 Matchers.equalTo (org.hamcrest.Matchers.equalTo)2