Search in sources :

Example 21 with Index

use of org.opensearch.index.Index in project OpenSearch by opensearch-project.

the class IndicesService method doStop.

@Override
protected void doStop() {
    ThreadPool.terminate(danglingIndicesThreadPoolExecutor, 10, TimeUnit.SECONDS);
    ExecutorService indicesStopExecutor = Executors.newFixedThreadPool(5, daemonThreadFactory(settings, "indices_shutdown"));
    // Copy indices because we modify it asynchronously in the body of the loop
    final Set<Index> indices = this.indices.values().stream().map(s -> s.index()).collect(Collectors.toSet());
    final CountDownLatch latch = new CountDownLatch(indices.size());
    for (final Index index : indices) {
        indicesStopExecutor.execute(() -> {
            try {
                removeIndex(index, IndexRemovalReason.NO_LONGER_ASSIGNED, "shutdown");
            } finally {
                latch.countDown();
            }
        });
    }
    try {
        if (latch.await(shardsClosedTimeout.seconds(), TimeUnit.SECONDS) == false) {
            logger.warn("Not all shards are closed yet, waited {}sec - stopping service", shardsClosedTimeout.seconds());
        }
    } catch (InterruptedException e) {
    // ignore
    } finally {
        indicesStopExecutor.shutdown();
    }
}
Also used : OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) NRTReplicationEngineFactory(org.opensearch.index.engine.NRTReplicationEngineFactory) LongSupplier(java.util.function.LongSupplier) CheckedFunction(org.opensearch.common.CheckedFunction) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) SearchStats(org.opensearch.index.search.stats.SearchStats) Iterables(org.opensearch.common.util.iterable.Iterables) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) MapBuilder.newMapBuilder(org.opensearch.common.collect.MapBuilder.newMapBuilder) IndexShardStats(org.opensearch.action.admin.indices.stats.IndexShardStats) FileSystemUtils(org.opensearch.common.io.FileSystemUtils) MergeStats(org.opensearch.index.merge.MergeStats) AbstractRefCounted(org.opensearch.common.util.concurrent.AbstractRefCounted) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) RecoveryState(org.opensearch.indices.recovery.RecoveryState) AliasFilter(org.opensearch.search.internal.AliasFilter) Map(java.util.Map) IndexModule(org.opensearch.index.IndexModule) NodeEnvironment(org.opensearch.env.NodeEnvironment) ScriptService(org.opensearch.script.ScriptService) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) ShardRequestCache(org.opensearch.index.cache.request.ShardRequestCache) Index(org.opensearch.index.Index) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) IndexingStats(org.opensearch.index.shard.IndexingStats) GetStats(org.opensearch.index.get.GetStats) Executors(java.util.concurrent.Executors) QueryPhase(org.opensearch.search.query.QueryPhase) OpenSearchThreadPoolExecutor(org.opensearch.common.util.concurrent.OpenSearchThreadPoolExecutor) UncheckedIOException(java.io.UncheckedIOException) AbstractLifecycleComponent(org.opensearch.common.component.AbstractLifecycleComponent) CountDownLatch(java.util.concurrent.CountDownLatch) Logger(org.apache.logging.log4j.Logger) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) XContentType(org.opensearch.common.xcontent.XContentType) ShardLock(org.opensearch.env.ShardLock) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) RepositoriesService(org.opensearch.repositories.RepositoriesService) IndexShardState(org.opensearch.index.shard.IndexShardState) ThreadPool(org.opensearch.threadpool.ThreadPool) ValuesSourceRegistry(org.opensearch.search.aggregations.support.ValuesSourceRegistry) Releasable(org.opensearch.common.lease.Releasable) Node(org.opensearch.node.Node) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) ClusterState(org.opensearch.cluster.ClusterState) LegacyESVersion(org.opensearch.LegacyESVersion) IndexingOperationListener(org.opensearch.index.shard.IndexingOperationListener) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) RetentionLeaseStats(org.opensearch.index.seqno.RetentionLeaseStats) CommitStats(org.opensearch.index.engine.CommitStats) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) EngineFactory(org.opensearch.index.engine.EngineFactory) Files(java.nio.file.Files) SearchType(org.opensearch.action.search.SearchType) FlushStats(org.opensearch.index.flush.FlushStats) IOException(java.io.IOException) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) IndexService(org.opensearch.index.IndexService) CollectionUtil(org.apache.lucene.util.CollectionUtil) PluginsService(org.opensearch.plugins.PluginsService) Flag(org.opensearch.action.admin.indices.stats.CommonStatsFlags.Flag) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) RecoveryStats(org.opensearch.index.recovery.RecoveryStats) ClusterService(org.opensearch.cluster.service.ClusterService) ShardStats(org.opensearch.action.admin.indices.stats.ShardStats) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) CommonStats(org.opensearch.action.admin.indices.stats.CommonStats) CREATE_INDEX(org.opensearch.index.IndexService.IndexCreationContext.CREATE_INDEX) IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) SearchContext(org.opensearch.search.internal.SearchContext) OpenSearchException(org.opensearch.OpenSearchException) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) CommonStatsFlags(org.opensearch.action.admin.indices.stats.CommonStatsFlags) XContentParser(org.opensearch.common.xcontent.XContentParser) IndexStorePlugin(org.opensearch.plugins.IndexStorePlugin) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AnalysisRegistry(org.opensearch.index.analysis.AnalysisRegistry) MapperService(org.opensearch.index.mapper.MapperService) RefreshStats(org.opensearch.index.refresh.RefreshStats) CheckedSupplier(org.opensearch.common.CheckedSupplier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RecoveryListener(org.opensearch.indices.recovery.RecoveryListener) Locale(java.util.Locale) OpenSearchExecutors.daemonThreadFactory(org.opensearch.common.util.concurrent.OpenSearchExecutors.daemonThreadFactory) Property(org.opensearch.common.settings.Setting.Property) XContentFactory(org.opensearch.common.xcontent.XContentFactory) SegmentReplicationCheckpointPublisher(org.opensearch.indices.replication.checkpoint.SegmentReplicationCheckpointPublisher) IndicesClusterStateService(org.opensearch.indices.cluster.IndicesClusterStateService) CacheHelper(org.apache.lucene.index.IndexReader.CacheHelper) IndexEventListener(org.opensearch.index.shard.IndexEventListener) Predicate(java.util.function.Predicate) Collections.emptyList(java.util.Collections.emptyList) DirectoryReader(org.apache.lucene.index.DirectoryReader) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) Objects(java.util.Objects) RamUsageEstimator(org.apache.lucene.util.RamUsageEstimator) List(java.util.List) QueryBuilder(org.opensearch.index.query.QueryBuilder) IndexSettings(org.opensearch.index.IndexSettings) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) Optional(java.util.Optional) BigArrays(org.opensearch.common.util.BigArrays) MetaStateService(org.opensearch.gateway.MetaStateService) AbstractQueryBuilder.parseInnerQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder) BytesReference(org.opensearch.common.bytes.BytesReference) NoOpEngine(org.opensearch.index.engine.NoOpEngine) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) CheckedConsumer(org.opensearch.common.CheckedConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamOutput(org.opensearch.common.io.stream.StreamOutput) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) HashMap(java.util.HashMap) EngineConfig(org.opensearch.index.engine.EngineConfig) IndicesFieldDataCache(org.opensearch.indices.fielddata.cache.IndicesFieldDataCache) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Function(java.util.function.Function) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) IndexShard(org.opensearch.index.shard.IndexShard) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) MetadataStateFormat(org.opensearch.gateway.MetadataStateFormat) IllegalIndexShardStateException(org.opensearch.index.shard.IllegalIndexShardStateException) ExecutorService(java.util.concurrent.ExecutorService) StreamInput(org.opensearch.common.io.stream.StreamInput) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Collections.emptyMap(java.util.Collections.emptyMap) Setting(org.opensearch.common.settings.Setting) Iterator(java.util.Iterator) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) CollectionUtils.arrayAsArrayList(org.opensearch.common.util.CollectionUtils.arrayAsArrayList) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Sets(org.opensearch.common.util.set.Sets) METADATA_VERIFICATION(org.opensearch.index.IndexService.IndexCreationContext.METADATA_VERIFICATION) QueryRewriteContext(org.opensearch.index.query.QueryRewriteContext) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) Closeable(java.io.Closeable) ALLOW_EXPENSIVE_QUERIES(org.opensearch.search.SearchService.ALLOW_EXPENSIVE_QUERIES) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) InputStream(java.io.InputStream) ExecutorService(java.util.concurrent.ExecutorService) Index(org.opensearch.index.Index) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 22 with Index

use of org.opensearch.index.Index in project OpenSearch by opensearch-project.

the class IndicesClusterStateService method deleteIndices.

/**
 * Deletes indices (with shard data).
 *
 * @param event cluster change event
 */
private void deleteIndices(final ClusterChangedEvent event) {
    final ClusterState previousState = event.previousState();
    final ClusterState state = event.state();
    final String localNodeId = state.nodes().getLocalNodeId();
    assert localNodeId != null;
    for (Index index : event.indicesDeleted()) {
        if (logger.isDebugEnabled()) {
            logger.debug("[{}] cleaning index, no longer part of the metadata", index);
        }
        AllocatedIndex<? extends Shard> indexService = indicesService.indexService(index);
        final IndexSettings indexSettings;
        if (indexService != null) {
            indexSettings = indexService.getIndexSettings();
            indicesService.removeIndex(index, DELETED, "index no longer part of the metadata");
        } else if (previousState.metadata().hasIndex(index)) {
            // The deleted index was part of the previous cluster state, but not loaded on the local node
            final IndexMetadata metadata = previousState.metadata().index(index);
            indexSettings = new IndexSettings(metadata, settings);
            indicesService.deleteUnassignedIndex("deleted index was not assigned to local node", metadata, state);
        } else {
            // previous cluster state is not initialized/recovered.
            assert state.metadata().indexGraveyard().containsIndex(index) || previousState.blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK);
            final IndexMetadata metadata = indicesService.verifyIndexIsDeleted(index, event.state());
            if (metadata != null) {
                indexSettings = new IndexSettings(metadata, settings);
            } else {
                indexSettings = null;
            }
        }
        if (indexSettings != null) {
            threadPool.generic().execute(new AbstractRunnable() {

                @Override
                public void onFailure(Exception e) {
                    logger.warn(() -> new ParameterizedMessage("[{}] failed to complete pending deletion for index", index), e);
                }

                @Override
                protected void doRun() throws Exception {
                    try {
                        // we are waiting until we can lock the index / all shards on the node and then we ack the delete of the store
                        // to the master. If we can't acquire the locks here immediately there might be a shard of this index still
                        // holding on to the lock due to a "currently canceled recovery" or so. The shard will delete itself BEFORE the
                        // lock is released so it's guaranteed to be deleted by the time we get the lock
                        indicesService.processPendingDeletes(index, indexSettings, new TimeValue(30, TimeUnit.MINUTES));
                    } catch (ShardLockObtainFailedException exc) {
                        logger.warn("[{}] failed to lock all shards for index - timed out after 30 seconds", index);
                    } catch (InterruptedException e) {
                        logger.warn("[{}] failed to lock all shards for index - interrupted", index);
                    }
                }
            });
        }
    }
}
Also used : AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) ClusterState(org.opensearch.cluster.ClusterState) IndexSettings(org.opensearch.index.IndexSettings) Index(org.opensearch.index.Index) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) IndexShardRelocatedException(org.opensearch.index.shard.IndexShardRelocatedException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) TimeValue(org.opensearch.common.unit.TimeValue)

Example 23 with Index

use of org.opensearch.index.Index in project OpenSearch by opensearch-project.

the class IndicesClusterStateService method createIndices.

private void createIndices(final ClusterState state) {
    // we only create indices for shards that are allocated
    RoutingNode localRoutingNode = state.getRoutingNodes().node(state.nodes().getLocalNodeId());
    if (localRoutingNode == null) {
        return;
    }
    // create map of indices to create with shards to fail if index creation fails
    final Map<Index, List<ShardRouting>> indicesToCreate = new HashMap<>();
    for (ShardRouting shardRouting : localRoutingNode) {
        if (failedShardsCache.containsKey(shardRouting.shardId()) == false) {
            final Index index = shardRouting.index();
            if (indicesService.indexService(index) == null) {
                indicesToCreate.computeIfAbsent(index, k -> new ArrayList<>()).add(shardRouting);
            }
        }
    }
    for (Map.Entry<Index, List<ShardRouting>> entry : indicesToCreate.entrySet()) {
        final Index index = entry.getKey();
        final IndexMetadata indexMetadata = state.metadata().index(index);
        logger.debug("[{}] creating index", index);
        AllocatedIndex<? extends Shard> indexService = null;
        try {
            indexService = indicesService.createIndex(indexMetadata, buildInIndexListener, true);
            if (indexService.updateMapping(null, indexMetadata) && sendRefreshMapping) {
                nodeMappingRefreshAction.nodeMappingRefresh(state.nodes().getMasterNode(), new NodeMappingRefreshAction.NodeMappingRefreshRequest(indexMetadata.getIndex().getName(), indexMetadata.getIndexUUID(), state.nodes().getLocalNodeId()));
            }
        } catch (Exception e) {
            final String failShardReason;
            if (indexService == null) {
                failShardReason = "failed to create index";
            } else {
                failShardReason = "failed to update mapping for index";
                indicesService.removeIndex(index, FAILURE, "removing index (mapping update failed)");
            }
            for (ShardRouting shardRouting : entry.getValue()) {
                sendFailShard(shardRouting, failShardReason, e, state);
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) NO_LONGER_ASSIGNED(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.NO_LONGER_ASSIGNED) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) ClusterStateApplier(org.opensearch.cluster.ClusterStateApplier) PrimaryReplicaSyncer(org.opensearch.index.shard.PrimaryReplicaSyncer) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) RecoveryListener(org.opensearch.indices.recovery.RecoveryListener) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) SegmentReplicationCheckpointPublisher(org.opensearch.indices.replication.checkpoint.SegmentReplicationCheckpointPublisher) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) GatewayService(org.opensearch.gateway.GatewayService) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) TimeValue(org.opensearch.common.unit.TimeValue) DELETED(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.DELETED) IndexEventListener(org.opensearch.index.shard.IndexEventListener) Index(org.opensearch.index.Index) IndicesService(org.opensearch.indices.IndicesService) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ReplicationTracker(org.opensearch.index.seqno.ReplicationTracker) PeerRecoverySourceService(org.opensearch.indices.recovery.PeerRecoverySourceService) Nullable(org.opensearch.common.Nullable) ReplicationState(org.opensearch.indices.replication.common.ReplicationState) Objects(java.util.Objects) AbstractLifecycleComponent(org.opensearch.common.component.AbstractLifecycleComponent) List(java.util.List) Logger(org.apache.logging.log4j.Logger) GlobalCheckpointSyncAction(org.opensearch.index.seqno.GlobalCheckpointSyncAction) ResyncTask(org.opensearch.index.shard.PrimaryReplicaSyncer.ResyncTask) IndexSettings(org.opensearch.index.IndexSettings) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) Type(org.opensearch.cluster.routing.RecoverySource.Type) RoutingNode(org.opensearch.cluster.routing.RoutingNode) RepositoriesService(org.opensearch.repositories.RepositoriesService) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) IndexShardState(org.opensearch.index.shard.IndexShardState) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ThreadPool(org.opensearch.threadpool.ThreadPool) HashMap(java.util.HashMap) SnapshotShardsService(org.opensearch.snapshots.SnapshotShardsService) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) IndexShard(org.opensearch.index.shard.IndexShard) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) BiConsumer(java.util.function.BiConsumer) NodeMappingRefreshAction(org.opensearch.cluster.action.index.NodeMappingRefreshAction) SearchService(org.opensearch.search.SearchService) REOPENED(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.REOPENED) Iterator(java.util.Iterator) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) IndexService(org.opensearch.index.IndexService) IndexShardRelocatedException(org.opensearch.index.shard.IndexShardRelocatedException) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) IndexComponent(org.opensearch.index.IndexComponent) CLOSED(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.CLOSED) ClusterService(org.opensearch.cluster.service.ClusterService) RoutingTable(org.opensearch.cluster.routing.RoutingTable) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) LogManager(org.apache.logging.log4j.LogManager) FAILURE(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.FAILURE) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Index(org.opensearch.index.Index) NodeMappingRefreshAction(org.opensearch.cluster.action.index.NodeMappingRefreshAction) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) IndexShardRelocatedException(org.opensearch.index.shard.IndexShardRelocatedException) RoutingNode(org.opensearch.cluster.routing.RoutingNode) List(java.util.List) ArrayList(java.util.ArrayList) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 24 with Index

use of org.opensearch.index.Index in project OpenSearch by opensearch-project.

the class NodeIndicesStats method writeTo.

@Override
public void writeTo(StreamOutput out) throws IOException {
    stats.writeTo(out);
    out.writeBoolean(statsByShard != null);
    if (statsByShard != null) {
        out.writeVInt(statsByShard.size());
        for (Map.Entry<Index, List<IndexShardStats>> entry : statsByShard.entrySet()) {
            entry.getKey().writeTo(out);
            out.writeVInt(entry.getValue().size());
            for (IndexShardStats indexShardStats : entry.getValue()) {
                indexShardStats.writeTo(out);
            }
        }
    }
}
Also used : Index(org.opensearch.index.Index) ArrayList(java.util.ArrayList) List(java.util.List) IndexShardStats(org.opensearch.action.admin.indices.stats.IndexShardStats) HashMap(java.util.HashMap) Map(java.util.Map)

Example 25 with Index

use of org.opensearch.index.Index in project OpenSearch by opensearch-project.

the class ShardLimitValidator method validateShardLimit.

/**
 * Validates whether a list of indices can be opened without going over the cluster shard limit.  Only counts indices which are
 * currently closed and will be opened, ignores indices which are already open.
 *
 * @param currentState The current cluster state.
 * @param indicesToOpen The indices which are to be opened.
 * @throws ValidationException If this operation would take the cluster over the limit and enforcement is enabled.
 */
public void validateShardLimit(ClusterState currentState, Index[] indicesToOpen) {
    int shardsToOpen = Arrays.stream(indicesToOpen).filter(index -> !systemIndices.validateSystemIndex(index.getName())).filter(index -> currentState.metadata().index(index).getState().equals(IndexMetadata.State.CLOSE)).mapToInt(index -> getTotalShardCount(currentState, index)).sum();
    Optional<String> error = checkShardLimit(shardsToOpen, currentState);
    if (error.isPresent()) {
        ValidationException ex = new ValidationException();
        ex.addValidationError(error.get());
        throw ex;
    }
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) Arrays(java.util.Arrays) Setting(org.opensearch.common.settings.Setting) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Index(org.opensearch.index.Index) ClusterService(org.opensearch.cluster.service.ClusterService) Optional(java.util.Optional) INDEX_NUMBER_OF_SHARDS_SETTING(org.opensearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING) Settings(org.opensearch.common.settings.Settings) ValidationException(org.opensearch.common.ValidationException) ValidationException(org.opensearch.common.ValidationException)

Aggregations

Index (org.opensearch.index.Index)432 Settings (org.opensearch.common.settings.Settings)165 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)147 ClusterState (org.opensearch.cluster.ClusterState)143 ShardId (org.opensearch.index.shard.ShardId)140 ArrayList (java.util.ArrayList)101 HashMap (java.util.HashMap)93 IOException (java.io.IOException)92 Map (java.util.Map)88 List (java.util.List)87 HashSet (java.util.HashSet)84 ShardRouting (org.opensearch.cluster.routing.ShardRouting)80 ClusterService (org.opensearch.cluster.service.ClusterService)76 IndicesService (org.opensearch.indices.IndicesService)71 Collections (java.util.Collections)70 Version (org.opensearch.Version)68 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)67 Matchers.containsString (org.hamcrest.Matchers.containsString)66 Set (java.util.Set)63 Metadata (org.opensearch.cluster.metadata.Metadata)63