Search in sources :

Example 21 with ActionListener

use of org.elasticsearch.action.ActionListener in project elasticsearch by elastic.

the class TransportRolloverAction method masterOperation.

@Override
protected void masterOperation(final RolloverRequest rolloverRequest, final ClusterState state, final ActionListener<RolloverResponse> listener) {
    final MetaData metaData = state.metaData();
    validate(metaData, rolloverRequest);
    final AliasOrIndex aliasOrIndex = metaData.getAliasAndIndexLookup().get(rolloverRequest.getAlias());
    final IndexMetaData indexMetaData = aliasOrIndex.getIndices().get(0);
    final String sourceProvidedName = indexMetaData.getSettings().get(IndexMetaData.SETTING_INDEX_PROVIDED_NAME, indexMetaData.getIndex().getName());
    final String sourceIndexName = indexMetaData.getIndex().getName();
    final String unresolvedName = (rolloverRequest.getNewIndexName() != null) ? rolloverRequest.getNewIndexName() : generateRolloverIndexName(sourceProvidedName, indexNameExpressionResolver);
    final String rolloverIndexName = indexNameExpressionResolver.resolveDateMathExpression(unresolvedName);
    // will fail if the index already exists
    MetaDataCreateIndexService.validateIndexName(rolloverIndexName, state);
    client.admin().indices().prepareStats(sourceIndexName).clear().setDocs(true).execute(new ActionListener<IndicesStatsResponse>() {

        @Override
        public void onResponse(IndicesStatsResponse statsResponse) {
            final Set<Condition.Result> conditionResults = evaluateConditions(rolloverRequest.getConditions(), statsResponse.getTotal().getDocs(), metaData.index(sourceIndexName));
            if (rolloverRequest.isDryRun()) {
                listener.onResponse(new RolloverResponse(sourceIndexName, rolloverIndexName, conditionResults, true, false, false, false));
                return;
            }
            if (conditionResults.size() == 0 || conditionResults.stream().anyMatch(result -> result.matched)) {
                CreateIndexClusterStateUpdateRequest updateRequest = prepareCreateIndexRequest(unresolvedName, rolloverIndexName, rolloverRequest);
                createIndexService.createIndex(updateRequest, ActionListener.wrap(createIndexClusterStateUpdateResponse -> {
                    indexAliasesService.indicesAliases(prepareRolloverAliasesUpdateRequest(sourceIndexName, rolloverIndexName, rolloverRequest), ActionListener.wrap(aliasClusterStateUpdateResponse -> {
                        if (aliasClusterStateUpdateResponse.isAcknowledged()) {
                            activeShardsObserver.waitForActiveShards(rolloverIndexName, rolloverRequest.getCreateIndexRequest().waitForActiveShards(), rolloverRequest.masterNodeTimeout(), isShardsAcked -> listener.onResponse(new RolloverResponse(sourceIndexName, rolloverIndexName, conditionResults, false, true, true, isShardsAcked)), listener::onFailure);
                        } else {
                            listener.onResponse(new RolloverResponse(sourceIndexName, rolloverIndexName, conditionResults, false, true, false, false));
                        }
                    }, listener::onFailure));
                }, listener::onFailure));
            } else {
                // conditions not met
                listener.onResponse(new RolloverResponse(sourceIndexName, rolloverIndexName, conditionResults, false, false, false, false));
            }
        }

        @Override
        public void onFailure(Exception e) {
            listener.onFailure(e);
        }
    });
}
Also used : AliasOrIndex(org.elasticsearch.cluster.metadata.AliasOrIndex) MetaData(org.elasticsearch.cluster.metadata.MetaData) Arrays(java.util.Arrays) MetaDataCreateIndexService(org.elasticsearch.cluster.metadata.MetaDataCreateIndexService) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ClusterService(org.elasticsearch.cluster.service.ClusterService) ActiveShardsObserver(org.elasticsearch.action.support.ActiveShardsObserver) Inject(org.elasticsearch.common.inject.Inject) TransportMasterNodeAction(org.elasticsearch.action.support.master.TransportMasterNodeAction) IndicesStatsResponse(org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) Locale(java.util.Locale) CreateIndexRequest(org.elasticsearch.action.admin.indices.create.CreateIndexRequest) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TransportService(org.elasticsearch.transport.TransportService) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) AliasAction(org.elasticsearch.cluster.metadata.AliasAction) CreateIndexClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) ActionFilters(org.elasticsearch.action.support.ActionFilters) MetaDataIndexAliasesService(org.elasticsearch.cluster.metadata.MetaDataIndexAliasesService) Client(org.elasticsearch.client.Client) Set(java.util.Set) Collectors(java.util.stream.Collectors) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) List(java.util.List) DocsStats(org.elasticsearch.index.shard.DocsStats) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) IndicesAliasesClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.alias.IndicesAliasesClusterStateUpdateRequest) Pattern(java.util.regex.Pattern) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) ActionListener(org.elasticsearch.action.ActionListener) IndicesStatsResponse(org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse) Set(java.util.Set) AliasOrIndex(org.elasticsearch.cluster.metadata.AliasOrIndex) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) CreateIndexClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 22 with ActionListener

use of org.elasticsearch.action.ActionListener in project elasticsearch by elastic.

the class InternalClusterInfoService method refresh.

/**
     * Refreshes the ClusterInfo in a blocking fashion
     */
public final ClusterInfo refresh() {
    if (logger.isTraceEnabled()) {
        logger.trace("Performing ClusterInfoUpdateJob");
    }
    final CountDownLatch nodeLatch = updateNodeStats(new ActionListener<NodesStatsResponse>() {

        @Override
        public void onResponse(NodesStatsResponse nodeStatses) {
            ImmutableOpenMap.Builder<String, DiskUsage> newLeastAvaiableUsages = ImmutableOpenMap.builder();
            ImmutableOpenMap.Builder<String, DiskUsage> newMostAvaiableUsages = ImmutableOpenMap.builder();
            fillDiskUsagePerNode(logger, nodeStatses.getNodes(), newLeastAvaiableUsages, newMostAvaiableUsages);
            leastAvailableSpaceUsages = newLeastAvaiableUsages.build();
            mostAvailableSpaceUsages = newMostAvaiableUsages.build();
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof ReceiveTimeoutTransportException) {
                logger.error("NodeStatsAction timed out for ClusterInfoUpdateJob", e);
            } else {
                if (e instanceof ClusterBlockException) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Failed to execute NodeStatsAction for ClusterInfoUpdateJob", e);
                    }
                } else {
                    logger.warn("Failed to execute NodeStatsAction for ClusterInfoUpdateJob", e);
                }
                // we empty the usages list, to be safe - we don't know what's going on.
                leastAvailableSpaceUsages = ImmutableOpenMap.of();
                mostAvailableSpaceUsages = ImmutableOpenMap.of();
            }
        }
    });
    final CountDownLatch indicesLatch = updateIndicesStats(new ActionListener<IndicesStatsResponse>() {

        @Override
        public void onResponse(IndicesStatsResponse indicesStatsResponse) {
            ShardStats[] stats = indicesStatsResponse.getShards();
            ImmutableOpenMap.Builder<String, Long> newShardSizes = ImmutableOpenMap.builder();
            ImmutableOpenMap.Builder<ShardRouting, String> newShardRoutingToDataPath = ImmutableOpenMap.builder();
            buildShardLevelInfo(logger, stats, newShardSizes, newShardRoutingToDataPath, clusterService.state());
            shardSizes = newShardSizes.build();
            shardRoutingToDataPath = newShardRoutingToDataPath.build();
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof ReceiveTimeoutTransportException) {
                logger.error("IndicesStatsAction timed out for ClusterInfoUpdateJob", e);
            } else {
                if (e instanceof ClusterBlockException) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Failed to execute IndicesStatsAction for ClusterInfoUpdateJob", e);
                    }
                } else {
                    logger.warn("Failed to execute IndicesStatsAction for ClusterInfoUpdateJob", e);
                }
                // we empty the usages list, to be safe - we don't know what's going on.
                shardSizes = ImmutableOpenMap.of();
                shardRoutingToDataPath = ImmutableOpenMap.of();
            }
        }
    });
    try {
        nodeLatch.await(fetchTimeout.getMillis(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // restore interrupt status
        Thread.currentThread().interrupt();
        logger.warn("Failed to update node information for ClusterInfoUpdateJob within {} timeout", fetchTimeout);
    }
    try {
        indicesLatch.await(fetchTimeout.getMillis(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // restore interrupt status
        Thread.currentThread().interrupt();
        logger.warn("Failed to update shard information for ClusterInfoUpdateJob within {} timeout", fetchTimeout);
    }
    ClusterInfo clusterInfo = getClusterInfo();
    for (Listener l : listeners) {
        try {
            l.onNewInfo(clusterInfo);
        } catch (Exception e) {
            logger.info("Failed executing ClusterInfoService listener", e);
        }
    }
    return clusterInfo;
}
Also used : IndicesStatsResponse(org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse) LatchedActionListener(org.elasticsearch.action.LatchedActionListener) ActionListener(org.elasticsearch.action.ActionListener) CountDownLatch(java.util.concurrent.CountDownLatch) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) NodesStatsResponse(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException)

Example 23 with ActionListener

use of org.elasticsearch.action.ActionListener in project elasticsearch by elastic.

the class SyncedFlushService method innerAttemptSyncedFlush.

private void innerAttemptSyncedFlush(final ShardId shardId, final ClusterState state, final ActionListener<ShardsSyncedFlushResult> actionListener) {
    try {
        final IndexShardRoutingTable shardRoutingTable = getShardRoutingTable(shardId, state);
        final List<ShardRouting> activeShards = shardRoutingTable.activeShards();
        final int totalShards = shardRoutingTable.getSize();
        if (activeShards.size() == 0) {
            actionListener.onResponse(new ShardsSyncedFlushResult(shardId, totalShards, "no active shards"));
            return;
        }
        final ActionListener<Map<String, Engine.CommitId>> commitIdsListener = new ActionListener<Map<String, Engine.CommitId>>() {

            @Override
            public void onResponse(final Map<String, Engine.CommitId> commitIds) {
                if (commitIds.isEmpty()) {
                    actionListener.onResponse(new ShardsSyncedFlushResult(shardId, totalShards, "all shards failed to commit on pre-sync"));
                    return;
                }
                final ActionListener<InFlightOpsResponse> inflightOpsListener = new ActionListener<InFlightOpsResponse>() {

                    @Override
                    public void onResponse(InFlightOpsResponse response) {
                        final int inflight = response.opCount();
                        assert inflight >= 0;
                        if (inflight != 0) {
                            actionListener.onResponse(new ShardsSyncedFlushResult(shardId, totalShards, "[" + inflight + "] ongoing operations on primary"));
                        } else {
                            // 3. now send the sync request to all the shards
                            String syncId = UUIDs.base64UUID();
                            sendSyncRequests(syncId, activeShards, state, commitIds, shardId, totalShards, actionListener);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        actionListener.onFailure(e);
                    }
                };
                // 2. fetch in flight operations
                getInflightOpsCount(shardId, state, shardRoutingTable, inflightOpsListener);
            }

            @Override
            public void onFailure(Exception e) {
                actionListener.onFailure(e);
            }
        };
        // 1. send pre-sync flushes to all replicas
        sendPreSyncRequests(activeShards, state, shardId, commitIdsListener);
    } catch (Exception e) {
        actionListener.onFailure(e);
    }
}
Also used : IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ElasticsearchException(org.elasticsearch.ElasticsearchException) IndexClosedException(org.elasticsearch.indices.IndexClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) IOException(java.io.IOException) TransportException(org.elasticsearch.transport.TransportException) ActionListener(org.elasticsearch.action.ActionListener) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) Engine(org.elasticsearch.index.engine.Engine)

Example 24 with ActionListener

use of org.elasticsearch.action.ActionListener in project elasticsearch by elastic.

the class TransportClientNodesServiceTests method testListenerFailures.

public void testListenerFailures() throws InterruptedException {
    int iters = iterations(10, 100);
    for (int i = 0; i < iters; i++) {
        try (TestIteration iteration = new TestIteration()) {
            // stop transport from responding early
            iteration.transport.endConnectMode();
            final CountDownLatch latch = new CountDownLatch(1);
            final AtomicInteger finalFailures = new AtomicInteger();
            final AtomicReference<Throwable> finalFailure = new AtomicReference<>();
            final AtomicReference<TestResponse> response = new AtomicReference<>();
            ActionListener<TestResponse> actionListener = new ActionListener<TestResponse>() {

                @Override
                public void onResponse(TestResponse testResponse) {
                    response.set(testResponse);
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception e) {
                    finalFailures.incrementAndGet();
                    finalFailure.set(e);
                    latch.countDown();
                }
            };
            final AtomicInteger preSendFailures = new AtomicInteger();
            iteration.transportClientNodesService.execute((node, retryListener) -> {
                if (rarely()) {
                    preSendFailures.incrementAndGet();
                    //throw whatever exception that is not a subclass of ConnectTransportException
                    throw new IllegalArgumentException();
                }
                iteration.transportService.sendRequest(node, "action", new TestRequest(), TransportRequestOptions.EMPTY, new TransportResponseHandler<TestResponse>() {

                    @Override
                    public TestResponse newInstance() {
                        return new TestResponse();
                    }

                    @Override
                    public void handleResponse(TestResponse response1) {
                        retryListener.onResponse(response1);
                    }

                    @Override
                    public void handleException(TransportException exp) {
                        retryListener.onFailure(exp);
                    }

                    @Override
                    public String executor() {
                        return randomBoolean() ? ThreadPool.Names.SAME : ThreadPool.Names.GENERIC;
                    }
                });
            }, actionListener);
            assertThat(latch.await(1, TimeUnit.SECONDS), equalTo(true));
            //there can be only either one failure that causes the request to fail straightaway or success
            assertThat(preSendFailures.get() + iteration.transport.failures() + iteration.transport.successes(), lessThanOrEqualTo(1));
            if (iteration.transport.successes() == 1) {
                assertThat(finalFailures.get(), equalTo(0));
                assertThat(finalFailure.get(), nullValue());
                assertThat(response.get(), notNullValue());
            } else {
                assertThat(finalFailures.get(), equalTo(1));
                assertThat(finalFailure.get(), notNullValue());
                assertThat(response.get(), nullValue());
                if (preSendFailures.get() == 0 && iteration.transport.failures() == 0) {
                    assertThat(finalFailure.get(), instanceOf(NoNodeAvailableException.class));
                }
            }
            assertThat(iteration.transport.triedNodes().size(), lessThanOrEqualTo(iteration.listNodesCount));
            assertThat(iteration.transport.triedNodes().size(), equalTo(iteration.transport.connectTransportExceptions() + iteration.transport.failures() + iteration.transport.successes()));
        }
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TransportException(org.elasticsearch.transport.TransportException) TransportException(org.elasticsearch.transport.TransportException) ActionListener(org.elasticsearch.action.ActionListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 25 with ActionListener

use of org.elasticsearch.action.ActionListener in project elasticsearch by elastic.

the class ParentTaskAssigningClientTests method testSetsParentId.

public void testSetsParentId() {
    TaskId[] parentTaskId = new TaskId[] { new TaskId(randomAsciiOfLength(3), randomLong()) };
    // This mock will do nothing but verify that parentTaskId is set on all requests sent to it.
    NoOpClient mock = new NoOpClient(getTestName()) {

        @Override
        protected <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
            assertEquals(parentTaskId[0], request.getParentTask());
            super.doExecute(action, request, listener);
        }
    };
    try (ParentTaskAssigningClient client = new ParentTaskAssigningClient(mock, parentTaskId[0])) {
        // All of these should have the parentTaskId set
        client.bulk(new BulkRequest());
        client.search(new SearchRequest());
        client.clearScroll(new ClearScrollRequest());
        // Now lets verify that unwrapped calls don't have the parentTaskId set
        parentTaskId[0] = TaskId.EMPTY_TASK_ID;
        client.unwrap().bulk(new BulkRequest());
        client.unwrap().search(new SearchRequest());
        client.unwrap().clearScroll(new ClearScrollRequest());
    }
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) Action(org.elasticsearch.action.Action) TaskId(org.elasticsearch.tasks.TaskId) ActionRequest(org.elasticsearch.action.ActionRequest) ClearScrollRequest(org.elasticsearch.action.search.ClearScrollRequest) SearchRequest(org.elasticsearch.action.search.SearchRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ActionResponse(org.elasticsearch.action.ActionResponse) ActionRequestBuilder(org.elasticsearch.action.ActionRequestBuilder) ActionListener(org.elasticsearch.action.ActionListener) ActionRequest(org.elasticsearch.action.ActionRequest) NoOpClient(org.elasticsearch.test.client.NoOpClient) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ClearScrollRequest(org.elasticsearch.action.search.ClearScrollRequest)

Aggregations

ActionListener (org.elasticsearch.action.ActionListener)57 IOException (java.io.IOException)25 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 ThreadPool (org.elasticsearch.threadpool.ThreadPool)18 ClusterState (org.elasticsearch.cluster.ClusterState)17 Settings (org.elasticsearch.common.settings.Settings)17 Index (org.elasticsearch.index.Index)13 IndexNameExpressionResolver (org.elasticsearch.cluster.metadata.IndexNameExpressionResolver)12 ShardId (org.elasticsearch.index.shard.ShardId)12 TransportService (org.elasticsearch.transport.TransportService)12 CountDownLatch (java.util.concurrent.CountDownLatch)11 ArrayList (java.util.ArrayList)10 TimeValue (org.elasticsearch.common.unit.TimeValue)10 CrateUnitTest (io.crate.test.integration.CrateUnitTest)9 List (java.util.List)9 ActionFilters (org.elasticsearch.action.support.ActionFilters)9 TransportException (org.elasticsearch.transport.TransportException)9 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)8 EsRejectedExecutionException (org.elasticsearch.common.util.concurrent.EsRejectedExecutionException)8 ShardResponse (io.crate.executor.transport.ShardResponse)7