Search in sources :

Example 11 with ClusterStateObserver

use of org.opensearch.cluster.ClusterStateObserver in project OpenSearch by opensearch-project.

the class TransportAddVotingConfigExclusionsAction method masterOperation.

@Override
protected void masterOperation(AddVotingConfigExclusionsRequest request, ClusterState state, ActionListener<AddVotingConfigExclusionsResponse> listener) throws Exception {
    resolveVotingConfigExclusionsAndCheckMaximum(request, state, maxVotingConfigExclusions);
    // throws IAE if no nodes matched or maximum exceeded
    clusterService.submitStateUpdateTask("add-voting-config-exclusions", new ClusterStateUpdateTask(Priority.URGENT) {

        private Set<VotingConfigExclusion> resolvedExclusions;

        @Override
        public ClusterState execute(ClusterState currentState) {
            assert resolvedExclusions == null : resolvedExclusions;
            final int finalMaxVotingConfigExclusions = TransportAddVotingConfigExclusionsAction.this.maxVotingConfigExclusions;
            resolvedExclusions = resolveVotingConfigExclusionsAndCheckMaximum(request, currentState, finalMaxVotingConfigExclusions);
            final CoordinationMetadata.Builder builder = CoordinationMetadata.builder(currentState.coordinationMetadata());
            resolvedExclusions.forEach(builder::addVotingConfigExclusion);
            final Metadata newMetadata = Metadata.builder(currentState.metadata()).coordinationMetadata(builder.build()).build();
            final ClusterState newState = ClusterState.builder(currentState).metadata(newMetadata).build();
            assert newState.getVotingConfigExclusions().size() <= finalMaxVotingConfigExclusions;
            return newState;
        }

        @Override
        public void onFailure(String source, Exception e) {
            listener.onFailure(e);
        }

        @Override
        public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
            final ClusterStateObserver observer = new ClusterStateObserver(clusterService, request.getTimeout(), logger, threadPool.getThreadContext());
            final Set<String> excludedNodeIds = resolvedExclusions.stream().map(VotingConfigExclusion::getNodeId).collect(Collectors.toSet());
            final Predicate<ClusterState> allNodesRemoved = clusterState -> {
                final Set<String> votingConfigNodeIds = clusterState.getLastCommittedConfiguration().getNodeIds();
                return excludedNodeIds.stream().noneMatch(votingConfigNodeIds::contains);
            };
            final Listener clusterStateListener = new Listener() {

                @Override
                public void onNewClusterState(ClusterState state) {
                    listener.onResponse(new AddVotingConfigExclusionsResponse());
                }

                @Override
                public void onClusterServiceClose() {
                    listener.onFailure(new OpenSearchException("cluster service closed while waiting for voting config exclusions " + resolvedExclusions + " to take effect"));
                }

                @Override
                public void onTimeout(TimeValue timeout) {
                    listener.onFailure(new OpenSearchTimeoutException("timed out waiting for voting config exclusions " + resolvedExclusions + " to take effect"));
                }
            };
            if (allNodesRemoved.test(newState)) {
                clusterStateListener.onNewClusterState(newState);
            } else {
                observer.waitForNextChange(clusterStateListener, allNodesRemoved);
            }
        }
    });
}
Also used : VotingConfigExclusion(org.opensearch.cluster.coordination.CoordinationMetadata.VotingConfigExclusion) ClusterState(org.opensearch.cluster.ClusterState) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) Set(java.util.Set) ActionListener(org.opensearch.action.ActionListener) Listener(org.opensearch.cluster.ClusterStateObserver.Listener) OpenSearchTimeoutException(org.opensearch.OpenSearchTimeoutException) Metadata(org.opensearch.cluster.metadata.Metadata) CoordinationMetadata(org.opensearch.cluster.coordination.CoordinationMetadata) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) OpenSearchException(org.opensearch.OpenSearchException) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) OpenSearchTimeoutException(org.opensearch.OpenSearchTimeoutException) Predicate(java.util.function.Predicate) OpenSearchException(org.opensearch.OpenSearchException) TimeValue(org.opensearch.common.unit.TimeValue)

Example 12 with ClusterStateObserver

use of org.opensearch.cluster.ClusterStateObserver in project OpenSearch by opensearch-project.

the class TransportShardBulkAction method dispatchedShardOperationOnPrimary.

@Override
protected void dispatchedShardOperationOnPrimary(BulkShardRequest request, IndexShard primary, ActionListener<PrimaryResult<BulkShardRequest, BulkShardResponse>> listener) {
    ClusterStateObserver observer = new ClusterStateObserver(clusterService, request.timeout(), logger, threadPool.getThreadContext());
    performOnPrimary(request, primary, updateHelper, threadPool::absoluteTimeInMillis, (update, shardId, mappingListener) -> {
        assert update != null;
        assert shardId != null;
        mappingUpdatedAction.updateMappingOnMaster(shardId.getIndex(), update, mappingListener);
    }, mappingUpdateListener -> observer.waitForNextChange(new ClusterStateObserver.Listener() {

        @Override
        public void onNewClusterState(ClusterState state) {
            mappingUpdateListener.onResponse(null);
        }

        @Override
        public void onClusterServiceClose() {
            mappingUpdateListener.onFailure(new NodeClosedException(clusterService.localNode()));
        }

        @Override
        public void onTimeout(TimeValue timeout) {
            mappingUpdateListener.onFailure(new MapperException("timed out while waiting for a dynamic mapping update"));
        }
    }), listener, threadPool, executor(primary));
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) ActionListener(org.opensearch.action.ActionListener) NodeClosedException(org.opensearch.node.NodeClosedException) MapperException(org.opensearch.index.mapper.MapperException) TimeValue(org.opensearch.common.unit.TimeValue)

Example 13 with ClusterStateObserver

use of org.opensearch.cluster.ClusterStateObserver in project OpenSearch by opensearch-project.

the class ActiveShardsObserver method waitForActiveShards.

/**
 * Waits on the specified number of active shards to be started before executing the
 *
 * @param indexNames the indices to wait for active shards on
 * @param activeShardCount the number of active shards to wait on before returning
 * @param timeout the timeout value
 * @param onResult a function that is executed in response to the requisite shards becoming active or a timeout (whichever comes first)
 * @param onFailure a function that is executed in response to an error occurring during waiting for the active shards
 */
public void waitForActiveShards(final String[] indexNames, final ActiveShardCount activeShardCount, final TimeValue timeout, final Consumer<Boolean> onResult, final Consumer<Exception> onFailure) {
    // wait for the configured number of active shards to be allocated before executing the result consumer
    if (activeShardCount == ActiveShardCount.NONE) {
        // not waiting, so just run whatever we were to run when the waiting is
        onResult.accept(true);
        return;
    }
    final ClusterState state = clusterService.state();
    final ClusterStateObserver observer = new ClusterStateObserver(state, clusterService, null, logger, threadPool.getThreadContext());
    if (activeShardCount.enoughShardsActive(state, indexNames)) {
        onResult.accept(true);
    } else {
        final Predicate<ClusterState> shardsAllocatedPredicate = newState -> activeShardCount.enoughShardsActive(newState, indexNames);
        final ClusterStateObserver.Listener observerListener = new ClusterStateObserver.Listener() {

            @Override
            public void onNewClusterState(ClusterState state) {
                onResult.accept(true);
            }

            @Override
            public void onClusterServiceClose() {
                logger.debug("[{}] cluster service closed while waiting for enough shards to be started.", Arrays.toString(indexNames));
                onFailure.accept(new NodeClosedException(clusterService.localNode()));
            }

            @Override
            public void onTimeout(TimeValue timeout) {
                onResult.accept(false);
            }
        };
        observer.waitForNextChange(observerListener, shardsAllocatedPredicate, timeout);
    }
}
Also used : Consumer(java.util.function.Consumer) ClusterState(org.opensearch.cluster.ClusterState) Arrays(java.util.Arrays) Logger(org.apache.logging.log4j.Logger) TimeValue(org.opensearch.common.unit.TimeValue) Predicate(java.util.function.Predicate) ThreadPool(org.opensearch.threadpool.ThreadPool) ClusterService(org.opensearch.cluster.service.ClusterService) NodeClosedException(org.opensearch.node.NodeClosedException) ActionListener(org.opensearch.action.ActionListener) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) LogManager(org.apache.logging.log4j.LogManager) ClusterState(org.opensearch.cluster.ClusterState) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) ActionListener(org.opensearch.action.ActionListener) NodeClosedException(org.opensearch.node.NodeClosedException) TimeValue(org.opensearch.common.unit.TimeValue)

Example 14 with ClusterStateObserver

use of org.opensearch.cluster.ClusterStateObserver in project OpenSearch by opensearch-project.

the class TransportClusterStateAction method masterOperation.

@Override
protected void masterOperation(final ClusterStateRequest request, final ClusterState state, final ActionListener<ClusterStateResponse> listener) throws IOException {
    final Predicate<ClusterState> acceptableClusterStatePredicate = request.waitForMetadataVersion() == null ? clusterState -> true : clusterState -> clusterState.metadata().version() >= request.waitForMetadataVersion();
    final Predicate<ClusterState> acceptableClusterStateOrNotMasterPredicate = request.local() ? acceptableClusterStatePredicate : acceptableClusterStatePredicate.or(clusterState -> clusterState.nodes().isLocalNodeElectedMaster() == false);
    if (acceptableClusterStatePredicate.test(state)) {
        ActionListener.completeWith(listener, () -> buildResponse(request, state));
    } else {
        assert acceptableClusterStateOrNotMasterPredicate.test(state) == false;
        new ClusterStateObserver(state, clusterService, request.waitForTimeout(), logger, threadPool.getThreadContext()).waitForNextChange(new ClusterStateObserver.Listener() {

            @Override
            public void onNewClusterState(ClusterState newState) {
                if (acceptableClusterStatePredicate.test(newState)) {
                    ActionListener.completeWith(listener, () -> buildResponse(request, newState));
                } else {
                    listener.onFailure(new NotMasterException("cluster-manager stepped down waiting for metadata version " + request.waitForMetadataVersion()));
                }
            }

            @Override
            public void onClusterServiceClose() {
                listener.onFailure(new NodeClosedException(clusterService.localNode()));
            }

            @Override
            public void onTimeout(TimeValue timeout) {
                try {
                    listener.onResponse(new ClusterStateResponse(state.getClusterName(), null, true));
                } catch (Exception e) {
                    listener.onFailure(e);
                }
            }
        }, acceptableClusterStateOrNotMasterPredicate);
    }
}
Also used : StreamInput(org.opensearch.common.io.stream.StreamInput) TimeValue(org.opensearch.common.unit.TimeValue) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) Predicate(java.util.function.Predicate) ThreadPool(org.opensearch.threadpool.ThreadPool) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) TransportService(org.opensearch.transport.TransportService) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ActionFilters(org.opensearch.action.support.ActionFilters) ClusterState(org.opensearch.cluster.ClusterState) Logger(org.apache.logging.log4j.Logger) NotMasterException(org.opensearch.cluster.NotMasterException) ClusterService(org.opensearch.cluster.service.ClusterService) NodeClosedException(org.opensearch.node.NodeClosedException) RoutingTable(org.opensearch.cluster.routing.RoutingTable) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) LogManager(org.apache.logging.log4j.LogManager) Custom(org.opensearch.cluster.metadata.Metadata.Custom) TransportMasterNodeReadAction(org.opensearch.action.support.master.TransportMasterNodeReadAction) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) ClusterState(org.opensearch.cluster.ClusterState) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) NodeClosedException(org.opensearch.node.NodeClosedException) NotMasterException(org.opensearch.cluster.NotMasterException) TimeValue(org.opensearch.common.unit.TimeValue) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) IOException(java.io.IOException) NotMasterException(org.opensearch.cluster.NotMasterException) NodeClosedException(org.opensearch.node.NodeClosedException)

Aggregations

ClusterState (org.opensearch.cluster.ClusterState)14 ClusterStateObserver (org.opensearch.cluster.ClusterStateObserver)14 TimeValue (org.opensearch.common.unit.TimeValue)12 ClusterService (org.opensearch.cluster.service.ClusterService)9 ThreadPool (org.opensearch.threadpool.ThreadPool)9 ActionListener (org.opensearch.action.ActionListener)8 NodeClosedException (org.opensearch.node.NodeClosedException)8 IOException (java.io.IOException)7 Predicate (java.util.function.Predicate)7 LogManager (org.apache.logging.log4j.LogManager)6 Logger (org.apache.logging.log4j.Logger)6 Metadata (org.opensearch.cluster.metadata.Metadata)5 TransportService (org.opensearch.transport.TransportService)5 OpenSearchTimeoutException (org.opensearch.OpenSearchTimeoutException)4 ActionFilters (org.opensearch.action.support.ActionFilters)4 ClusterStateUpdateTask (org.opensearch.cluster.ClusterStateUpdateTask)4 ClusterBlockException (org.opensearch.cluster.block.ClusterBlockException)4 IndexNameExpressionResolver (org.opensearch.cluster.metadata.IndexNameExpressionResolver)4 StreamInput (org.opensearch.common.io.stream.StreamInput)4 CountDownLatch (java.util.concurrent.CountDownLatch)3