Search in sources :

Example 21 with IndexMetadata

use of org.opensearch.cluster.metadata.IndexMetadata in project OpenSearch by opensearch-project.

the class IndexShard method startRecovery.

public void startRecovery(RecoveryState recoveryState, PeerRecoveryTargetService recoveryTargetService, PeerRecoveryTargetService.RecoveryListener recoveryListener, RepositoriesService repositoriesService, Consumer<MappingMetadata> mappingUpdateConsumer, IndicesService indicesService) {
    // }
    assert recoveryState.getRecoverySource().equals(shardRouting.recoverySource());
    switch(recoveryState.getRecoverySource().getType()) {
        case EMPTY_STORE:
        case EXISTING_STORE:
            executeRecovery("from store", recoveryState, recoveryListener, this::recoverFromStore);
            break;
        case PEER:
            try {
                markAsRecovering("from " + recoveryState.getSourceNode(), recoveryState);
                recoveryTargetService.startRecovery(this, recoveryState.getSourceNode(), recoveryListener);
            } catch (Exception e) {
                failShard("corrupted preexisting index", e);
                recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
            }
            break;
        case SNAPSHOT:
            final String repo = ((SnapshotRecoverySource) recoveryState.getRecoverySource()).snapshot().getRepository();
            executeRecovery("from snapshot", recoveryState, recoveryListener, l -> restoreFromRepository(repositoriesService.repository(repo), l));
            break;
        case LOCAL_SHARDS:
            final IndexMetadata indexMetadata = indexSettings().getIndexMetadata();
            final Index resizeSourceIndex = indexMetadata.getResizeSourceIndex();
            final List<IndexShard> startedShards = new ArrayList<>();
            final IndexService sourceIndexService = indicesService.indexService(resizeSourceIndex);
            final Set<ShardId> requiredShards;
            final int numShards;
            if (sourceIndexService != null) {
                requiredShards = IndexMetadata.selectRecoverFromShards(shardId().id(), sourceIndexService.getMetadata(), indexMetadata.getNumberOfShards());
                for (IndexShard shard : sourceIndexService) {
                    if (shard.state() == IndexShardState.STARTED && requiredShards.contains(shard.shardId())) {
                        startedShards.add(shard);
                    }
                }
                numShards = requiredShards.size();
            } else {
                numShards = -1;
                requiredShards = Collections.emptySet();
            }
            if (numShards == startedShards.size()) {
                assert requiredShards.isEmpty() == false;
                executeRecovery("from local shards", recoveryState, recoveryListener, l -> recoverFromLocalShards(mappingUpdateConsumer, startedShards.stream().filter((s) -> requiredShards.contains(s.shardId())).collect(Collectors.toList()), l));
            } else {
                final RuntimeException e;
                if (numShards == -1) {
                    e = new IndexNotFoundException(resizeSourceIndex);
                } else {
                    e = new IllegalStateException("not all required shards of index " + resizeSourceIndex + " are started yet, expected " + numShards + " found " + startedShards.size() + " can't recover shard " + shardId());
                }
                throw e;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown recovery source " + recoveryState.getRecoverySource());
    }
}
Also used : Query(org.apache.lucene.search.Query) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Arrays(java.util.Arrays) LongSupplier(java.util.function.LongSupplier) CheckedFunction(org.opensearch.common.CheckedFunction) SnapshotRecoverySource(org.opensearch.cluster.routing.RecoverySource.SnapshotRecoverySource) SearchStats(org.opensearch.index.search.stats.SearchStats) MetadataSnapshot(org.opensearch.index.store.Store.MetadataSnapshot) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ReferenceManager(org.apache.lucene.search.ReferenceManager) DocumentMapperForType(org.opensearch.index.mapper.DocumentMapperForType) MergeStats(org.opensearch.index.merge.MergeStats) UsageTrackingQueryCachingPolicy(org.apache.lucene.search.UsageTrackingQueryCachingPolicy) WriteStateException(org.opensearch.gateway.WriteStateException) RecoveryState(org.opensearch.indices.recovery.RecoveryState) RefreshFailedEngineException(org.opensearch.index.engine.RefreshFailedEngineException) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) QueryCachingPolicy(org.apache.lucene.search.QueryCachingPolicy) ActionListener(org.opensearch.action.ActionListener) GetResult(org.opensearch.index.engine.Engine.GetResult) IndexModule(org.opensearch.index.IndexModule) Segment(org.opensearch.index.engine.Segment) EnumSet(java.util.EnumSet) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) ShardRequestCache(org.opensearch.index.cache.request.ShardRequestCache) Index(org.opensearch.index.Index) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ReplicationTracker(org.opensearch.index.seqno.ReplicationTracker) ShardBitsetFilterCache(org.opensearch.index.cache.bitset.ShardBitsetFilterCache) GetStats(org.opensearch.index.get.GetStats) StandardCharsets(java.nio.charset.StandardCharsets) Engine(org.opensearch.index.engine.Engine) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Logger(org.apache.logging.log4j.Logger) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) CheckedRunnable(org.opensearch.common.CheckedRunnable) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IndexCommit(org.apache.lucene.index.IndexCommit) ShardFieldData(org.opensearch.index.fielddata.ShardFieldData) RepositoriesService(org.opensearch.repositories.RepositoriesService) CodecService(org.opensearch.index.codec.CodecService) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) ThreadPool(org.opensearch.threadpool.ThreadPool) Releasable(org.opensearch.common.lease.Releasable) MeanMetric(org.opensearch.common.metrics.MeanMetric) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) FilterDirectoryReader(org.apache.lucene.index.FilterDirectoryReader) LegacyESVersion(org.opensearch.LegacyESVersion) Mapping(org.opensearch.index.mapper.Mapping) Booleans(org.opensearch.common.Booleans) BiConsumer(java.util.function.BiConsumer) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) RetentionLeaseStats(org.opensearch.index.seqno.RetentionLeaseStats) StreamSupport(java.util.stream.StreamSupport) CommitStats(org.opensearch.index.engine.CommitStats) EngineFactory(org.opensearch.index.engine.EngineFactory) CompletionStats(org.opensearch.search.suggest.completion.CompletionStats) SetOnce(org.apache.lucene.util.SetOnce) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) PendingReplicationActions(org.opensearch.action.support.replication.PendingReplicationActions) RETAIN_ALL(org.opensearch.index.seqno.RetentionLeaseActions.RETAIN_ALL) FlushStats(org.opensearch.index.flush.FlushStats) IOException(java.io.IOException) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) IndexService(org.opensearch.index.IndexService) XContentHelper(org.opensearch.common.xcontent.XContentHelper) AtomicLong(java.util.concurrent.atomic.AtomicLong) RecoveryStats(org.opensearch.index.recovery.RecoveryStats) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) CounterMetric(org.opensearch.common.metrics.CounterMetric) ShardIndexWarmerService(org.opensearch.index.warmer.ShardIndexWarmerService) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) SafeCommitInfo(org.opensearch.index.engine.SafeCommitInfo) EngineException(org.opensearch.index.engine.EngineException) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine) IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) FieldDataStats(org.opensearch.index.fielddata.FieldDataStats) TimeoutException(java.util.concurrent.TimeoutException) OpenSearchException(org.opensearch.OpenSearchException) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) Releasables(org.opensearch.common.lease.Releasables) UpgradeRequest(org.opensearch.action.admin.indices.upgrade.post.UpgradeRequest) RunOnce(org.opensearch.common.util.concurrent.RunOnce) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) MapperService(org.opensearch.index.mapper.MapperService) RefreshStats(org.opensearch.index.refresh.RefreshStats) Locale(java.util.Locale) Assertions(org.opensearch.Assertions) SegmentsStats(org.opensearch.index.engine.SegmentsStats) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) IndicesClusterStateService(org.opensearch.indices.cluster.IndicesClusterStateService) CheckIndex(org.apache.lucene.index.CheckIndex) Sort(org.apache.lucene.search.Sort) DirectoryReader(org.apache.lucene.index.DirectoryReader) IndicesService(org.opensearch.indices.IndicesService) TranslogConfig(org.opensearch.index.translog.TranslogConfig) IndexingMemoryController(org.opensearch.indices.IndexingMemoryController) RestStatus(org.opensearch.rest.RestStatus) Store(org.opensearch.index.store.Store) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) WarmerStats(org.opensearch.index.warmer.WarmerStats) Objects(java.util.Objects) List(java.util.List) ResyncTask(org.opensearch.index.shard.PrimaryReplicaSyncer.ResyncTask) LeafReader(org.apache.lucene.index.LeafReader) IndexSettings(org.opensearch.index.IndexSettings) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) Optional(java.util.Optional) BigArrays(org.opensearch.common.util.BigArrays) Uid(org.opensearch.index.mapper.Uid) TranslogStats(org.opensearch.index.translog.TranslogStats) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardSearchStats(org.opensearch.index.search.stats.ShardSearchStats) ActionRunnable(org.opensearch.action.ActionRunnable) SimilarityService(org.opensearch.index.similarity.SimilarityService) CheckedConsumer(org.opensearch.common.CheckedConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) EngineConfig(org.opensearch.index.engine.EngineConfig) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HashSet(java.util.HashSet) SourceToParse(org.opensearch.index.mapper.SourceToParse) AsyncIOProcessor(org.opensearch.common.util.concurrent.AsyncIOProcessor) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) Translog(org.opensearch.index.translog.Translog) StoreFileMetadata(org.opensearch.index.store.StoreFileMetadata) StoreStats(org.opensearch.index.store.StoreStats) RetentionLease(org.opensearch.index.seqno.RetentionLease) PrintStream(java.io.PrintStream) OpenSearchDirectoryReader(org.opensearch.common.lucene.index.OpenSearchDirectoryReader) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IndexCache(org.opensearch.index.cache.IndexCache) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ShardGetService(org.opensearch.index.get.ShardGetService) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) Closeable(java.io.Closeable) TypeMissingException(org.opensearch.indices.TypeMissingException) Collections(java.util.Collections) IndexService(org.opensearch.index.IndexService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Index(org.opensearch.index.Index) CheckIndex(org.apache.lucene.index.CheckIndex) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) WriteStateException(org.opensearch.gateway.WriteStateException) RefreshFailedEngineException(org.opensearch.index.engine.RefreshFailedEngineException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) IOException(java.io.IOException) EngineException(org.opensearch.index.engine.EngineException) TimeoutException(java.util.concurrent.TimeoutException) OpenSearchException(org.opensearch.OpenSearchException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) TypeMissingException(org.opensearch.indices.TypeMissingException) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 22 with IndexMetadata

use of org.opensearch.cluster.metadata.IndexMetadata in project OpenSearch by opensearch-project.

the class TransportShardBulkAction method executeBulkItemRequest.

/**
 * Executes bulk item requests and handles request execution exceptions.
 * @return {@code true} if request completed on this thread and the listener was invoked, {@code false} if the request triggered
 *                      a mapping update that will finish and invoke the listener on a different thread
 */
static boolean executeBulkItemRequest(BulkPrimaryExecutionContext context, UpdateHelper updateHelper, LongSupplier nowInMillisSupplier, MappingUpdatePerformer mappingUpdater, Consumer<ActionListener<Void>> waitForMappingUpdate, ActionListener<Void> itemDoneListener) throws Exception {
    final DocWriteRequest.OpType opType = context.getCurrent().opType();
    final UpdateHelper.Result updateResult;
    if (opType == DocWriteRequest.OpType.UPDATE) {
        final UpdateRequest updateRequest = (UpdateRequest) context.getCurrent();
        try {
            updateResult = updateHelper.prepare(updateRequest, context.getPrimary(), nowInMillisSupplier);
        } catch (Exception failure) {
            // we may fail translating a update to index or delete operation
            // we use index result to communicate failure while translating update request
            final Engine.Result result = new Engine.IndexResult(failure, updateRequest.version());
            context.setRequestToExecute(updateRequest);
            context.markOperationAsExecuted(result);
            context.markAsCompleted(context.getExecutionResult());
            return true;
        }
        // execute translated update request
        switch(updateResult.getResponseResult()) {
            case CREATED:
            case UPDATED:
                IndexRequest indexRequest = updateResult.action();
                IndexMetadata metadata = context.getPrimary().indexSettings().getIndexMetadata();
                MappingMetadata mappingMd = metadata.mapping();
                indexRequest.process(metadata.getCreationVersion(), mappingMd, updateRequest.concreteIndex());
                context.setRequestToExecute(indexRequest);
                break;
            case DELETED:
                context.setRequestToExecute(updateResult.action());
                break;
            case NOOP:
                context.markOperationAsNoOp(updateResult.action());
                context.markAsCompleted(context.getExecutionResult());
                return true;
            default:
                throw new IllegalStateException("Illegal update operation " + updateResult.getResponseResult());
        }
    } else {
        context.setRequestToExecute(context.getCurrent());
        updateResult = null;
    }
    // also checks that we're in TRANSLATED state
    assert context.getRequestToExecute() != null;
    final IndexShard primary = context.getPrimary();
    final long version = context.getRequestToExecute().version();
    final boolean isDelete = context.getRequestToExecute().opType() == DocWriteRequest.OpType.DELETE;
    final Engine.Result result;
    if (isDelete) {
        final DeleteRequest request = context.getRequestToExecute();
        result = primary.applyDeleteOperationOnPrimary(version, request.id(), request.versionType(), request.ifSeqNo(), request.ifPrimaryTerm());
    } else {
        final IndexRequest request = context.getRequestToExecute();
        result = primary.applyIndexOperationOnPrimary(version, request.versionType(), new SourceToParse(request.index(), request.id(), request.source(), request.getContentType(), request.routing()), request.ifSeqNo(), request.ifPrimaryTerm(), request.getAutoGeneratedTimestamp(), request.isRetry());
    }
    if (result.getResultType() == Engine.Result.Type.MAPPING_UPDATE_REQUIRED) {
        try {
            primary.mapperService().merge(MapperService.SINGLE_MAPPING_NAME, new CompressedXContent(result.getRequiredMappingUpdate(), ToXContent.EMPTY_PARAMS), MapperService.MergeReason.MAPPING_UPDATE_PREFLIGHT);
        } catch (Exception e) {
            logger.info(() -> new ParameterizedMessage("{} mapping update rejected by primary", primary.shardId()), e);
            onComplete(exceptionToResult(e, primary, isDelete, version), context, updateResult);
            return true;
        }
        mappingUpdater.updateMappings(result.getRequiredMappingUpdate(), primary.shardId(), new ActionListener<Void>() {

            @Override
            public void onResponse(Void v) {
                context.markAsRequiringMappingUpdate();
                waitForMappingUpdate.accept(ActionListener.runAfter(new ActionListener<Void>() {

                    @Override
                    public void onResponse(Void v) {
                        assert context.requiresWaitingForMappingUpdate();
                        context.resetForExecutionForRetry();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        context.failOnMappingUpdate(e);
                    }
                }, () -> itemDoneListener.onResponse(null)));
            }

            @Override
            public void onFailure(Exception e) {
                onComplete(exceptionToResult(e, primary, isDelete, version), context, updateResult);
                // Requesting mapping update failed, so we don't have to wait for a cluster state update
                assert context.isInitial();
                itemDoneListener.onResponse(null);
            }
        });
        return false;
    } else {
        onComplete(result, context, updateResult);
    }
    return true;
}
Also used : UpdateRequest(org.opensearch.action.update.UpdateRequest) IndexShard(org.opensearch.index.shard.IndexShard) SourceToParse(org.opensearch.index.mapper.SourceToParse) IndexRequest(org.opensearch.action.index.IndexRequest) NodeClosedException(org.opensearch.node.NodeClosedException) MapperException(org.opensearch.index.mapper.MapperException) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IOException(java.io.IOException) GetResult(org.opensearch.index.get.GetResult) UpdateHelper(org.opensearch.action.update.UpdateHelper) CompressedXContent(org.opensearch.common.compress.CompressedXContent) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) DocWriteRequest(org.opensearch.action.DocWriteRequest) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) DeleteRequest(org.opensearch.action.delete.DeleteRequest) Engine(org.opensearch.index.engine.Engine)

Example 23 with IndexMetadata

use of org.opensearch.cluster.metadata.IndexMetadata in project OpenSearch by opensearch-project.

the class ClusterState method toString.

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    final String TAB = "   ";
    sb.append("cluster uuid: ").append(metadata.clusterUUID()).append(" [committed: ").append(metadata.clusterUUIDCommitted()).append("]").append("\n");
    sb.append("version: ").append(version).append("\n");
    sb.append("state uuid: ").append(stateUUID).append("\n");
    sb.append("from_diff: ").append(wasReadFromDiff).append("\n");
    sb.append("meta data version: ").append(metadata.version()).append("\n");
    sb.append(TAB).append("coordination_metadata:\n");
    sb.append(TAB).append(TAB).append("term: ").append(coordinationMetadata().term()).append("\n");
    sb.append(TAB).append(TAB).append("last_committed_config: ").append(coordinationMetadata().getLastCommittedConfiguration()).append("\n");
    sb.append(TAB).append(TAB).append("last_accepted_config: ").append(coordinationMetadata().getLastAcceptedConfiguration()).append("\n");
    sb.append(TAB).append(TAB).append("voting tombstones: ").append(coordinationMetadata().getVotingConfigExclusions()).append("\n");
    for (IndexMetadata indexMetadata : metadata) {
        sb.append(TAB).append(indexMetadata.getIndex());
        sb.append(": v[").append(indexMetadata.getVersion()).append("], mv[").append(indexMetadata.getMappingVersion()).append("], sv[").append(indexMetadata.getSettingsVersion()).append("], av[").append(indexMetadata.getAliasesVersion()).append("]\n");
        for (int shard = 0; shard < indexMetadata.getNumberOfShards(); shard++) {
            sb.append(TAB).append(TAB).append(shard).append(": ");
            sb.append("p_term [").append(indexMetadata.primaryTerm(shard)).append("], ");
            sb.append("isa_ids ").append(indexMetadata.inSyncAllocationIds(shard)).append("\n");
        }
    }
    if (metadata.customs().isEmpty() == false) {
        sb.append("metadata customs:\n");
        for (final ObjectObjectCursor<String, Metadata.Custom> cursor : metadata.customs()) {
            final String type = cursor.key;
            final Metadata.Custom custom = cursor.value;
            sb.append(TAB).append(type).append(": ").append(custom);
        }
        sb.append("\n");
    }
    sb.append(blocks());
    sb.append(nodes());
    sb.append(routingTable());
    sb.append(getRoutingNodes());
    if (customs.isEmpty() == false) {
        sb.append("customs:\n");
        for (ObjectObjectCursor<String, Custom> cursor : customs) {
            final String type = cursor.key;
            final Custom custom = cursor.value;
            sb.append(TAB).append(type).append(": ").append(custom);
        }
    }
    return sb.toString();
}
Also used : Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) CoordinationMetadata(org.opensearch.cluster.coordination.CoordinationMetadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 24 with IndexMetadata

use of org.opensearch.cluster.metadata.IndexMetadata in project OpenSearch by opensearch-project.

the class ClusterChangedEvent method indicesDeletedFromClusterState.

// Get the deleted indices by comparing the index metadatas in the previous and new cluster states.
// If an index exists in the previous cluster state, but not in the new cluster state, it must have been deleted.
private List<Index> indicesDeletedFromClusterState() {
    // https://github.com/elastic/elasticsearch/issues/11665
    if (metadataChanged() == false || isNewCluster()) {
        return Collections.emptyList();
    }
    Set<Index> deleted = null;
    final Metadata previousMetadata = previousState.metadata();
    final Metadata currentMetadata = state.metadata();
    for (ObjectCursor<IndexMetadata> cursor : previousMetadata.indices().values()) {
        IndexMetadata index = cursor.value;
        IndexMetadata current = currentMetadata.index(index.getIndex());
        if (current == null) {
            if (deleted == null) {
                deleted = new HashSet<>();
            }
            deleted.add(index.getIndex());
        }
    }
    final IndexGraveyard currentGraveyard = currentMetadata.indexGraveyard();
    final IndexGraveyard previousGraveyard = previousMetadata.indexGraveyard();
    // each node should make sure to delete any related data.
    if (currentGraveyard != previousGraveyard) {
        final IndexGraveyardDiff indexGraveyardDiff = (IndexGraveyardDiff) currentGraveyard.diff(previousGraveyard);
        final List<IndexGraveyard.Tombstone> added = indexGraveyardDiff.getAdded();
        if (added.isEmpty() == false) {
            if (deleted == null) {
                deleted = new HashSet<>();
            }
            for (IndexGraveyard.Tombstone tombstone : added) {
                deleted.add(tombstone.getIndex());
            }
        }
    }
    return deleted == null ? Collections.<Index>emptyList() : new ArrayList<>(deleted);
}
Also used : IndexGraveyardDiff(org.opensearch.cluster.metadata.IndexGraveyard.IndexGraveyardDiff) IndexGraveyard(org.opensearch.cluster.metadata.IndexGraveyard) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) Index(org.opensearch.index.Index) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 25 with IndexMetadata

use of org.opensearch.cluster.metadata.IndexMetadata in project OpenSearch by opensearch-project.

the class FilterAllocationDecider method canAllocate.

@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
    if (shardRouting.unassigned()) {
        // only for unassigned - we filter allocation right after the index creation (for shard shrinking) to ensure
        // that once it has been allocated post API the replicas can be allocated elsewhere without user interaction
        // this is a setting that can only be set within the system!
        IndexMetadata indexMd = allocation.metadata().getIndexSafe(shardRouting.index());
        DiscoveryNodeFilters initialRecoveryFilters = DiscoveryNodeFilters.trimTier(indexMd.getInitialRecoveryFilters());
        if (initialRecoveryFilters != null && shardRouting.recoverySource().getType() == RecoverySource.Type.LOCAL_SHARDS && initialRecoveryFilters.match(node.node()) == false) {
            String explanation = "initial allocation of the shrunken index is only allowed on nodes [%s] that hold a copy of every shard in the index";
            return allocation.decision(Decision.NO, NAME, explanation, initialRecoveryFilters);
        }
    }
    return shouldFilter(shardRouting, node.node(), allocation);
}
Also used : DiscoveryNodeFilters(org.opensearch.cluster.node.DiscoveryNodeFilters) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Aggregations

IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)419 ClusterState (org.opensearch.cluster.ClusterState)149 Settings (org.opensearch.common.settings.Settings)132 Metadata (org.opensearch.cluster.metadata.Metadata)130 IndexSettings (org.opensearch.index.IndexSettings)93 Index (org.opensearch.index.Index)84 ShardRouting (org.opensearch.cluster.routing.ShardRouting)67 ShardId (org.opensearch.index.shard.ShardId)61 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)56 HashSet (java.util.HashSet)53 ArrayList (java.util.ArrayList)52 HashMap (java.util.HashMap)52 IOException (java.io.IOException)51 Matchers.containsString (org.hamcrest.Matchers.containsString)51 IndexShardRoutingTable (org.opensearch.cluster.routing.IndexShardRoutingTable)47 RoutingTable (org.opensearch.cluster.routing.RoutingTable)46 Map (java.util.Map)44 ClusterService (org.opensearch.cluster.service.ClusterService)40 List (java.util.List)39 ActionListener (org.opensearch.action.ActionListener)36