Search in sources :

Example 16 with TaskInfo

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

the class TasksIT method testTaskStoringSuccesfulResult.

public void testTaskStoringSuccesfulResult() throws Exception {
    // Randomly create an empty index to make sure the type is created automatically
    if (randomBoolean()) {
        logger.info("creating an empty results index with custom settings");
        assertAcked(client().admin().indices().prepareCreate(TaskResultsService.TASK_INDEX));
    }
    // we need this to get task id of the process
    registerTaskManageListeners(TestTaskPlugin.TestTaskAction.NAME);
    // Start non-blocking test task
    TestTaskPlugin.TestTaskAction.INSTANCE.newRequestBuilder(client()).setShouldStoreResult(true).setShouldBlock(false).get();
    List<TaskInfo> events = findEvents(TestTaskPlugin.TestTaskAction.NAME, Tuple::v1);
    assertEquals(1, events.size());
    TaskInfo taskInfo = events.get(0);
    TaskId taskId = taskInfo.getTaskId();
    GetResponse resultDoc = client().prepareGet(TaskResultsService.TASK_INDEX, TaskResultsService.TASK_TYPE, taskId.toString()).get();
    assertTrue(resultDoc.isExists());
    Map<String, Object> source = resultDoc.getSource();
    @SuppressWarnings("unchecked") Map<String, Object> task = (Map<String, Object>) source.get("task");
    assertEquals(taskInfo.getTaskId().getNodeId(), task.get("node"));
    assertEquals(taskInfo.getAction(), task.get("action"));
    assertEquals(Long.toString(taskInfo.getId()), task.get("id").toString());
    @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) source.get("response");
    assertEquals("0", result.get("failure_count").toString());
    assertNull(source.get("failure"));
    assertNoFailures(client().admin().indices().prepareRefresh(TaskResultsService.TASK_INDEX).get());
    SearchResponse searchResponse = client().prepareSearch(TaskResultsService.TASK_INDEX).setTypes(TaskResultsService.TASK_TYPE).setSource(SearchSourceBuilder.searchSource().query(QueryBuilders.termQuery("task.action", taskInfo.getAction()))).get();
    assertEquals(1L, searchResponse.getHits().getTotalHits());
    searchResponse = client().prepareSearch(TaskResultsService.TASK_INDEX).setTypes(TaskResultsService.TASK_TYPE).setSource(SearchSourceBuilder.searchSource().query(QueryBuilders.termQuery("task.node", taskInfo.getTaskId().getNodeId()))).get();
    assertEquals(1L, searchResponse.getHits().getTotalHits());
    GetTaskResponse getResponse = expectFinishedTask(taskId);
    assertEquals(result, getResponse.getTask().getResponseAsMap());
    assertNull(getResponse.getTask().getError());
}
Also used : TaskInfo(org.elasticsearch.tasks.TaskInfo) TaskId(org.elasticsearch.tasks.TaskId) GetTaskResponse(org.elasticsearch.action.admin.cluster.node.tasks.get.GetTaskResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) GetResponse(org.elasticsearch.action.get.GetResponse) Map(java.util.Map) HashMap(java.util.HashMap) Tuple(org.elasticsearch.common.collect.Tuple) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Example 17 with TaskInfo

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

the class TasksIT method expectFinishedTask.

/**
     * Fetch the task status from the list tasks API using it's "fallback to get from the task index" behavior. Asserts some obvious stuff
     * about the fetched task and returns a map of it's status.
     */
private GetTaskResponse expectFinishedTask(TaskId taskId) throws IOException {
    GetTaskResponse response = client().admin().cluster().prepareGetTask(taskId).get();
    assertTrue("the task should have been completed before fetching", response.getTask().isCompleted());
    TaskInfo info = response.getTask().getTask();
    assertEquals(taskId, info.getTaskId());
    // The test task doesn't have any status
    assertNull(info.getStatus());
    return response;
}
Also used : TaskInfo(org.elasticsearch.tasks.TaskInfo) GetTaskResponse(org.elasticsearch.action.admin.cluster.node.tasks.get.GetTaskResponse)

Example 18 with TaskInfo

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

the class TasksIT method testTransportBroadcastReplicationTasks.

public void testTransportBroadcastReplicationTasks() {
    // main task
    registerTaskManageListeners(RefreshAction.NAME);
    // shard level tasks
    registerTaskManageListeners(RefreshAction.NAME + "[s]");
    // primary and replica shard tasks
    registerTaskManageListeners(RefreshAction.NAME + "[s][*]");
    createIndex("test");
    // Make sure all shards are allocated
    ensureGreen("test");
    client().admin().indices().prepareRefresh("test").get();
    // the refresh operation should produce one main task
    NumShards numberOfShards = getNumShards("test");
    logger.debug("number of shards, total: [{}], primaries: [{}] ", numberOfShards.totalNumShards, numberOfShards.numPrimaries);
    logger.debug("main events {}", numberOfEvents(RefreshAction.NAME, Tuple::v1));
    logger.debug("main event node {}", findEvents(RefreshAction.NAME, Tuple::v1).get(0).getTaskId().getNodeId());
    logger.debug("[s] events {}", numberOfEvents(RefreshAction.NAME + "[s]", Tuple::v1));
    logger.debug("[s][*] events {}", numberOfEvents(RefreshAction.NAME + "[s][*]", Tuple::v1));
    logger.debug("nodes with the index {}", internalCluster().nodesInclude("test"));
    assertEquals(1, numberOfEvents(RefreshAction.NAME, Tuple::v1));
    // Because it's broadcast replication action we will have as many [s] level requests
    // as we have primary shards on the coordinating node plus we will have one task per primary outside of the
    // coordinating node due to replication.
    // If all primaries are on the coordinating node, the number of tasks should be equal to the number of primaries
    // If all primaries are not on the coordinating node, the number of tasks should be equal to the number of primaries times 2
    assertThat(numberOfEvents(RefreshAction.NAME + "[s]", Tuple::v1), greaterThanOrEqualTo(numberOfShards.numPrimaries));
    assertThat(numberOfEvents(RefreshAction.NAME + "[s]", Tuple::v1), lessThanOrEqualTo(numberOfShards.numPrimaries * 2));
    // Verify that all [s] events have the proper parent
    // This is complicated because if the shard task runs on the same node it has main task as a parent
    // but if it runs on non-coordinating node it would have another intermediate [s] task on the coordinating node as a parent
    TaskInfo mainTask = findEvents(RefreshAction.NAME, Tuple::v1).get(0);
    List<TaskInfo> sTasks = findEvents(RefreshAction.NAME + "[s]", Tuple::v1);
    for (TaskInfo taskInfo : sTasks) {
        if (mainTask.getTaskId().getNodeId().equals(taskInfo.getTaskId().getNodeId())) {
            // This shard level task runs on the same node as a parent task - it should have the main task as a direct parent
            assertParentTask(Collections.singletonList(taskInfo), mainTask);
        } else {
            String description = taskInfo.getDescription();
            // This shard level task runs on another node - it should have a corresponding shard level task on the node where main task
            // is running
            List<TaskInfo> sTasksOnRequestingNode = findEvents(RefreshAction.NAME + "[s]", event -> event.v1() && mainTask.getTaskId().getNodeId().equals(event.v2().getTaskId().getNodeId()) && description.equals(event.v2().getDescription()));
            // There should be only one parent task
            assertEquals(1, sTasksOnRequestingNode.size());
            assertParentTask(Collections.singletonList(taskInfo), sTasksOnRequestingNode.get(0));
        }
    }
    // we will have as many [s][p] and [s][r] tasks as we have primary and replica shards
    assertEquals(numberOfShards.totalNumShards, numberOfEvents(RefreshAction.NAME + "[s][*]", Tuple::v1));
    // we the [s][p] and [s][r] tasks should have a corresponding [s] task on the same node as a parent
    List<TaskInfo> spEvents = findEvents(RefreshAction.NAME + "[s][*]", Tuple::v1);
    for (TaskInfo taskInfo : spEvents) {
        List<TaskInfo> sTask;
        if (taskInfo.getAction().endsWith("[s][p]")) {
            // A [s][p] level task should have a corresponding [s] level task on the same node
            sTask = findEvents(RefreshAction.NAME + "[s]", event -> event.v1() && taskInfo.getTaskId().getNodeId().equals(event.v2().getTaskId().getNodeId()) && taskInfo.getDescription().equals(event.v2().getDescription()));
        } else {
            // A [s][r] level task should have a corresponding [s] level task on the a different node (where primary is located)
            sTask = findEvents(RefreshAction.NAME + "[s]", event -> event.v1() && taskInfo.getParentTaskId().getNodeId().equals(event.v2().getTaskId().getNodeId()) && taskInfo.getDescription().equals(event.v2().getDescription()));
        }
        // There should be only one parent task
        assertEquals(1, sTask.size());
        assertParentTask(Collections.singletonList(taskInfo), sTask.get(0));
    }
}
Also used : TaskInfo(org.elasticsearch.tasks.TaskInfo) MockTaskManagerListener(org.elasticsearch.test.tasks.MockTaskManagerListener) GetResponse(org.elasticsearch.action.get.GetResponse) Arrays(java.util.Arrays) FailedNodeException(org.elasticsearch.action.FailedNodeException) ValidateQueryAction(org.elasticsearch.action.admin.indices.validate.query.ValidateQueryAction) ListTasksAction(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksAction) Matchers.not(org.hamcrest.Matchers.not) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) UpgradeAction(org.elasticsearch.action.admin.indices.upgrade.post.UpgradeAction) TaskResult(org.elasticsearch.tasks.TaskResult) Settings(org.elasticsearch.common.settings.Settings) TaskOperationFailure(org.elasticsearch.action.TaskOperationFailure) Collections.singleton(java.util.Collections.singleton) BulkAction(org.elasticsearch.action.bulk.BulkAction) Map(java.util.Map) TimeValue.timeValueSeconds(org.elasticsearch.common.unit.TimeValue.timeValueSeconds) SearchResponse(org.elasticsearch.action.search.SearchResponse) TaskResultsService(org.elasticsearch.tasks.TaskResultsService) Matchers.emptyCollectionOf(org.hamcrest.Matchers.emptyCollectionOf) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) CyclicBarrier(java.util.concurrent.CyclicBarrier) FieldStatsAction(org.elasticsearch.action.fieldstats.FieldStatsAction) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collections.emptyList(java.util.Collections.emptyList) Matchers.allOf(org.hamcrest.Matchers.allOf) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) Collection(java.util.Collection) TransportReplicationActionTests(org.elasticsearch.action.support.replication.TransportReplicationActionTests) CancelTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse) Matchers.startsWith(org.hamcrest.Matchers.startsWith) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SearchTransportService(org.elasticsearch.action.search.SearchTransportService) ESIntegTestCase(org.elasticsearch.test.ESIntegTestCase) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) MockTaskManager(org.elasticsearch.test.tasks.MockTaskManager) Task(org.elasticsearch.tasks.Task) Matchers.containsString(org.hamcrest.Matchers.containsString) XContentType(org.elasticsearch.common.xcontent.XContentType) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) ListenableActionFuture(org.elasticsearch.action.ListenableActionFuture) TaskId(org.elasticsearch.tasks.TaskId) RefreshAction(org.elasticsearch.action.admin.indices.refresh.RefreshAction) Function(java.util.function.Function) Strings(org.elasticsearch.common.Strings) ArrayList(java.util.ArrayList) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) WriteRequest(org.elasticsearch.action.support.WriteRequest) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) GetTaskResponse(org.elasticsearch.action.admin.cluster.node.tasks.get.GetTaskResponse) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) Regex(org.elasticsearch.common.regex.Regex) TimeValue.timeValueMillis(org.elasticsearch.common.unit.TimeValue.timeValueMillis) Matchers.hasSize(org.hamcrest.Matchers.hasSize) IndexResponse(org.elasticsearch.action.index.IndexResponse) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) ElasticsearchAssertions.assertThrows(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows) SearchAction(org.elasticsearch.action.search.SearchAction) TaskInfo(org.elasticsearch.tasks.TaskInfo) ClusterHealthAction(org.elasticsearch.action.admin.cluster.health.ClusterHealthAction) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Plugin(org.elasticsearch.plugins.Plugin) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) IndexAction(org.elasticsearch.action.index.IndexAction) ReplicationResponse(org.elasticsearch.action.support.replication.ReplicationResponse) Tuple(org.elasticsearch.common.collect.Tuple) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) ElasticsearchAssertions.assertAcked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked) ElasticsearchAssertions.assertNoFailures(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures) Matchers.containsString(org.hamcrest.Matchers.containsString) Tuple(org.elasticsearch.common.collect.Tuple)

Example 19 with TaskInfo

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

the class TransportRethrottleActionTests method testRethrottleWithSomeSucceeded.

public void testRethrottleWithSomeSucceeded() {
    int succeeded = between(1, slices - 1);
    List<BulkByScrollTask.StatusOrException> sliceStatuses = new ArrayList<>(slices);
    for (int i = 0; i < succeeded; i++) {
        BulkByScrollTask.Status status = believeableCompletedStatus(i);
        task.onSliceResponse(neverCalled(), i, new BulkByScrollResponse(timeValueMillis(10), status, emptyList(), emptyList(), false));
        sliceStatuses.add(new BulkByScrollTask.StatusOrException(status));
    }
    List<TaskInfo> tasks = new ArrayList<>();
    for (int i = succeeded; i < slices; i++) {
        BulkByScrollTask.Status status = believeableInProgressStatus(i);
        tasks.add(new TaskInfo(new TaskId("test", 123), "test", "test", "test", status, 0, 0, true, new TaskId("test", task.getId())));
        sliceStatuses.add(new BulkByScrollTask.StatusOrException(status));
    }
    rethrottleTestCase(slices - succeeded, listener -> listener.onResponse(new ListTasksResponse(tasks, emptyList(), emptyList())), expectSuccessfulRethrottleWithStatuses(sliceStatuses));
}
Also used : TaskInfo(org.elasticsearch.tasks.TaskInfo) TaskId(org.elasticsearch.tasks.TaskId) ArrayList(java.util.ArrayList) ParentBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.ParentBulkByScrollTask) BulkByScrollTask(org.elasticsearch.action.bulk.byscroll.BulkByScrollTask) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) BulkByScrollResponse(org.elasticsearch.action.bulk.byscroll.BulkByScrollResponse)

Example 20 with TaskInfo

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

the class TransportRethrottleActionTests method rethrottleTestCase.

/**
     * Test rethrottling.
     * @param runningSlices the number of slices still running
     * @param simulator simulate a response from the sub-request to rethrottle the child requests
     * @param verifier verify the resulting response
     */
private void rethrottleTestCase(int runningSlices, Consumer<ActionListener<ListTasksResponse>> simulator, Consumer<ActionListener<TaskInfo>> verifier) {
    Client client = mock(Client.class);
    String localNodeId = randomAsciiOfLength(5);
    float newRequestsPerSecond = randomValueOtherThanMany(f -> f <= 0, () -> randomFloat());
    @SuppressWarnings("unchecked") ActionListener<TaskInfo> listener = mock(ActionListener.class);
    TransportRethrottleAction.rethrottle(localNodeId, client, task, newRequestsPerSecond, listener);
    // Capture the sub request and the listener so we can verify they are sane
    ArgumentCaptor<RethrottleRequest> subRequest = ArgumentCaptor.forClass(RethrottleRequest.class);
    // Magical generics incantation.....
    @SuppressWarnings({ "unchecked", "rawtypes" }) ArgumentCaptor<ActionListener<ListTasksResponse>> subListener = ArgumentCaptor.forClass((Class) ActionListener.class);
    if (runningSlices > 0) {
        verify(client).execute(eq(RethrottleAction.INSTANCE), subRequest.capture(), subListener.capture());
        assertEquals(new TaskId(localNodeId, task.getId()), subRequest.getValue().getParentTaskId());
        assertEquals(newRequestsPerSecond / runningSlices, subRequest.getValue().getRequestsPerSecond(), 0.00001f);
        simulator.accept(subListener.getValue());
    }
    verifier.accept(listener);
}
Also used : TaskInfo(org.elasticsearch.tasks.TaskInfo) TaskId(org.elasticsearch.tasks.TaskId) ActionListener(org.elasticsearch.action.ActionListener) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Matchers.containsString(org.hamcrest.Matchers.containsString) Client(org.elasticsearch.client.Client)

Aggregations

TaskInfo (org.elasticsearch.tasks.TaskInfo)25 TaskId (org.elasticsearch.tasks.TaskId)13 ListTasksResponse (org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse)12 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 GetTaskResponse (org.elasticsearch.action.admin.cluster.node.tasks.get.GetTaskResponse)6 Map (java.util.Map)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 Tuple (org.elasticsearch.common.collect.Tuple)5 Task (org.elasticsearch.tasks.Task)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 List (java.util.List)4 CancelTasksResponse (org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse)4 BulkByScrollTask (org.elasticsearch.action.bulk.byscroll.BulkByScrollTask)4 ExecutionException (java.util.concurrent.ExecutionException)3 ActionListener (org.elasticsearch.action.ActionListener)3 FailedNodeException (org.elasticsearch.action.FailedNodeException)3 ListTasksRequest (org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksRequest)3 GetResponse (org.elasticsearch.action.get.GetResponse)3