Search in sources :

Example 1 with DocIdSeqNoAndSource

use of org.opensearch.index.engine.DocIdSeqNoAndSource in project OpenSearch by opensearch-project.

the class RecoveryDuringReplicationTests method testRollbackOnPromotion.

public void testRollbackOnPromotion() throws Exception {
    try (ReplicationGroup shards = createGroup(between(2, 3))) {
        shards.startAll();
        IndexShard newPrimary = randomFrom(shards.getReplicas());
        int initDocs = shards.indexDocs(randomInt(100));
        int inFlightOpsOnNewPrimary = 0;
        int inFlightOps = scaledRandomIntBetween(10, 200);
        for (int i = 0; i < inFlightOps; i++) {
            String id = "extra-" + i;
            IndexRequest primaryRequest = new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON);
            BulkShardRequest replicationRequest = indexOnPrimary(primaryRequest, shards.getPrimary());
            for (IndexShard replica : shards.getReplicas()) {
                if (randomBoolean()) {
                    indexOnReplica(replicationRequest, shards, replica);
                    if (replica == newPrimary) {
                        inFlightOpsOnNewPrimary++;
                    }
                }
            }
            if (randomBoolean()) {
                shards.syncGlobalCheckpoint();
            }
            if (rarely()) {
                shards.flush();
            }
        }
        shards.refresh("test");
        List<DocIdSeqNoAndSource> docsBelowGlobalCheckpoint = EngineTestCase.getDocIds(getEngine(newPrimary), randomBoolean()).stream().filter(doc -> doc.getSeqNo() <= newPrimary.getLastKnownGlobalCheckpoint()).collect(Collectors.toList());
        CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean done = new AtomicBoolean();
        Thread thread = new Thread(() -> {
            List<IndexShard> replicas = new ArrayList<>(shards.getReplicas());
            replicas.remove(newPrimary);
            latch.countDown();
            while (done.get() == false) {
                try {
                    List<DocIdSeqNoAndSource> exposedDocs = EngineTestCase.getDocIds(getEngine(randomFrom(replicas)), randomBoolean());
                    assertThat(docsBelowGlobalCheckpoint, everyItem(is(in(exposedDocs))));
                    assertThat(randomFrom(replicas).getLocalCheckpoint(), greaterThanOrEqualTo(initDocs - 1L));
                } catch (AlreadyClosedException ignored) {
                // replica swaps engine during rollback
                } catch (Exception e) {
                    throw new AssertionError(e);
                }
            }
        });
        thread.start();
        latch.await();
        shards.promoteReplicaToPrimary(newPrimary).get();
        shards.assertAllEqual(initDocs + inFlightOpsOnNewPrimary);
        int moreDocsAfterRollback = shards.indexDocs(scaledRandomIntBetween(1, 20));
        shards.assertAllEqual(initDocs + inFlightOpsOnNewPrimary + moreDocsAfterRollback);
        done.set(true);
        thread.join();
        shards.syncGlobalCheckpoint();
        for (IndexShard shard : shards) {
            shard.flush(new FlushRequest().force(true).waitIfOngoing(true));
            assertThat(shard.translogStats().getUncommittedOperations(), equalTo(0));
        }
    }
}
Also used : BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Matchers.either(org.hamcrest.Matchers.either) IndexableField(org.apache.lucene.index.IndexableField) Matchers.not(org.hamcrest.Matchers.not) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) PrimaryReplicaSyncer(org.opensearch.index.shard.PrimaryReplicaSyncer) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IndexShardTestCase(org.opensearch.index.shard.IndexShardTestCase) Future(java.util.concurrent.Future) Matchers.everyItem(org.hamcrest.Matchers.everyItem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) EnumSet(java.util.EnumSet) DeleteRequest(org.opensearch.action.delete.DeleteRequest) EngineTestCase(org.opensearch.index.engine.EngineTestCase) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) Settings(org.opensearch.common.settings.Settings) Store(org.opensearch.index.store.Store) Collectors(java.util.stream.Collectors) Engine(org.opensearch.index.engine.Engine) CountDownLatch(java.util.concurrent.CountDownLatch) IndexWriter(org.apache.lucene.index.IndexWriter) VersionType(org.opensearch.index.VersionType) List(java.util.List) Logger(org.apache.logging.log4j.Logger) BytesArray(org.opensearch.common.bytes.BytesArray) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) Optional(java.util.Optional) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Matchers.in(org.hamcrest.Matchers.in) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Releasable(org.opensearch.common.lease.Releasable) EngineConfig(org.opensearch.index.engine.EngineConfig) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) InternalEngineTests(org.opensearch.index.engine.InternalEngineTests) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) SourceToParse(org.opensearch.index.mapper.SourceToParse) IndexShard(org.opensearch.index.shard.IndexShard) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Translog(org.opensearch.index.translog.Translog) EngineFactory(org.opensearch.index.engine.EngineFactory) RetentionLease(org.opensearch.index.seqno.RetentionLease) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Versions(org.opensearch.common.lucene.uid.Versions) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) IOException(java.io.IOException) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TimeUnit(java.util.concurrent.TimeUnit) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) IndexShard(org.opensearch.index.shard.IndexShard) ArrayList(java.util.ArrayList) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IndexRequest(org.opensearch.action.index.IndexRequest) CountDownLatch(java.util.concurrent.CountDownLatch) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource)

Example 2 with DocIdSeqNoAndSource

use of org.opensearch.index.engine.DocIdSeqNoAndSource in project OpenSearch by opensearch-project.

the class IndexShardTests method testResetEngine.

public void testResetEngine() throws Exception {
    IndexShard shard = newStartedShard(false);
    indexOnReplicaWithGaps(shard, between(0, 1000), Math.toIntExact(shard.getLocalCheckpoint()));
    long maxSeqNoBeforeRollback = shard.seqNoStats().getMaxSeqNo();
    final long globalCheckpoint = randomLongBetween(shard.getLastKnownGlobalCheckpoint(), shard.getLocalCheckpoint());
    shard.updateGlobalCheckpointOnReplica(globalCheckpoint, "test");
    Set<String> docBelowGlobalCheckpoint = getShardDocUIDs(shard).stream().filter(id -> Long.parseLong(id) <= globalCheckpoint).collect(Collectors.toSet());
    TranslogStats translogStats = shard.translogStats();
    AtomicBoolean done = new AtomicBoolean();
    CountDownLatch latch = new CountDownLatch(1);
    Thread thread = new Thread(() -> {
        latch.countDown();
        int hitClosedExceptions = 0;
        while (done.get() == false) {
            try {
                List<String> exposedDocIds = EngineTestCase.getDocIds(getEngine(shard), rarely()).stream().map(DocIdSeqNoAndSource::getId).collect(Collectors.toList());
                assertThat("every operations before the global checkpoint must be reserved", docBelowGlobalCheckpoint, everyItem(is(in(exposedDocIds))));
            } catch (AlreadyClosedException ignored) {
                hitClosedExceptions++;
            } catch (IOException e) {
                throw new AssertionError(e);
            }
        }
        // engine reference was switched twice: current read/write engine -> ready-only engine -> new read/write engine
        assertThat(hitClosedExceptions, lessThanOrEqualTo(2));
    });
    thread.start();
    latch.await();
    final CountDownLatch engineResetLatch = new CountDownLatch(1);
    shard.acquireAllReplicaOperationsPermits(shard.getOperationPrimaryTerm(), globalCheckpoint, 0L, ActionListener.wrap(r -> {
        try {
            shard.resetEngineToGlobalCheckpoint();
        } finally {
            r.close();
            engineResetLatch.countDown();
        }
    }, Assert::assertNotNull), TimeValue.timeValueMinutes(1L));
    engineResetLatch.await();
    assertThat(getShardDocUIDs(shard), equalTo(docBelowGlobalCheckpoint));
    assertThat(shard.seqNoStats().getMaxSeqNo(), equalTo(globalCheckpoint));
    if (shard.indexSettings.isSoftDeleteEnabled()) {
        // we might have trimmed some operations if the translog retention policy is ignored (when soft-deletes enabled).
        assertThat(shard.translogStats().estimatedNumberOfOperations(), lessThanOrEqualTo(translogStats.estimatedNumberOfOperations()));
    } else {
        assertThat(shard.translogStats().estimatedNumberOfOperations(), equalTo(translogStats.estimatedNumberOfOperations()));
    }
    assertThat(shard.getMaxSeqNoOfUpdatesOrDeletes(), equalTo(maxSeqNoBeforeRollback));
    done.set(true);
    thread.join();
    closeShard(shard, false);
}
Also used : Matchers.hasToString(org.hamcrest.Matchers.hasToString) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) MockFSDirectoryFactory(org.opensearch.test.store.MockFSDirectoryFactory) Arrays(java.util.Arrays) CheckedFunction(org.opensearch.common.CheckedFunction) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Term(org.apache.lucene.index.Term) Matchers.not(org.hamcrest.Matchers.not) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) InternalEngine(org.opensearch.index.engine.InternalEngine) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) ActionListener(org.opensearch.action.ActionListener) IOContext(org.apache.lucene.store.IOContext) Path(java.nio.file.Path) NodeEnvironment(org.opensearch.env.NodeEnvironment) TimeValue(org.opensearch.common.unit.TimeValue) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ReplicationTracker(org.opensearch.index.seqno.ReplicationTracker) RegexMatcher.matches(org.opensearch.test.hamcrest.RegexMatcher.matches) Engine(org.opensearch.index.engine.Engine) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) FieldMaskingReader(org.opensearch.test.FieldMaskingReader) FileVisitResult(java.nio.file.FileVisitResult) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Logger(org.apache.logging.log4j.Logger) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) Stream(java.util.stream.Stream) Randomness(org.opensearch.common.Randomness) BytesArray(org.opensearch.common.bytes.BytesArray) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.in(org.hamcrest.Matchers.in) XContentFactory.jsonBuilder(org.opensearch.common.xcontent.XContentFactory.jsonBuilder) 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) TestShardRouting.newShardRouting(org.opensearch.cluster.routing.TestShardRouting.newShardRouting) Releasable(org.opensearch.common.lease.Releasable) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) VersionUtils(org.opensearch.test.VersionUtils) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) VersionFieldMapper(org.opensearch.index.mapper.VersionFieldMapper) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) CorruptionUtils(org.opensearch.test.CorruptionUtils) CommitStats(org.opensearch.index.engine.CommitStats) TopDocs(org.apache.lucene.search.TopDocs) ParseContext(org.opensearch.index.mapper.ParseContext) Versions(org.opensearch.common.lucene.uid.Versions) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) SourceFieldMapper(org.opensearch.index.mapper.SourceFieldMapper) IndexFieldDataService(org.opensearch.index.fielddata.IndexFieldDataService) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Matchers.sameInstance(org.hamcrest.Matchers.sameInstance) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) ShardStats(org.opensearch.action.admin.indices.stats.ShardStats) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) Assert(org.junit.Assert) SeqNoFieldMapper(org.opensearch.index.mapper.SeqNoFieldMapper) CommonStats(org.opensearch.action.admin.indices.stats.CommonStats) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine) IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) Matchers.either(org.hamcrest.Matchers.either) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) FieldDataStats(org.opensearch.index.fielddata.FieldDataStats) IndexableField(org.apache.lucene.index.IndexableField) Lucene.cleanLuceneIndex(org.opensearch.common.lucene.Lucene.cleanLuceneIndex) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) OpenSearchException(org.opensearch.OpenSearchException) Releasables(org.opensearch.common.lease.Releasables) CommonStatsFlags(org.opensearch.action.admin.indices.stats.CommonStatsFlags) Matchers.hasKey(org.hamcrest.Matchers.hasKey) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) IndexId(org.opensearch.repositories.IndexId) Matchers.everyItem(org.hamcrest.Matchers.everyItem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Directory(org.apache.lucene.store.Directory) Assertions(org.opensearch.Assertions) XContentFactory(org.opensearch.common.xcontent.XContentFactory) DummyShardLock(org.opensearch.test.DummyShardLock) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) EngineTestCase(org.opensearch.index.engine.EngineTestCase) CyclicBarrier(java.util.concurrent.CyclicBarrier) DeleteResult(org.opensearch.index.engine.Engine.DeleteResult) BytesRef(org.apache.lucene.util.BytesRef) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) SnapshotId(org.opensearch.snapshots.SnapshotId) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) DirectoryReader(org.apache.lucene.index.DirectoryReader) Store(org.opensearch.index.store.Store) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) ShardRoutingHelper(org.opensearch.cluster.routing.ShardRoutingHelper) Uid(org.opensearch.index.mapper.Uid) TranslogStats(org.opensearch.index.translog.TranslogStats) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) IntStream(java.util.stream.IntStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EngineConfig(org.opensearch.index.engine.EngineConfig) StoreUtils(org.opensearch.index.store.StoreUtils) IndicesFieldDataCache(org.opensearch.indices.fielddata.cache.IndicesFieldDataCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HashSet(java.util.HashSet) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) SourceToParse(org.opensearch.index.mapper.SourceToParse) Charset(java.nio.charset.Charset) Translog(org.opensearch.index.translog.Translog) UUIDs(org.opensearch.common.UUIDs) IndicesQueryCache(org.opensearch.indices.IndicesQueryCache) StoreStats(org.opensearch.index.store.StoreStats) RetentionLease(org.opensearch.index.seqno.RetentionLease) StreamInput(org.opensearch.common.io.stream.StreamInput) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.oneOf(org.hamcrest.Matchers.oneOf) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) LongFunction(java.util.function.LongFunction) Collections.emptySet(java.util.Collections.emptySet) AllocationId(org.opensearch.cluster.routing.AllocationId) Semaphore(java.util.concurrent.Semaphore) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) EMPTY_PARAMS(org.opensearch.common.xcontent.ToXContent.EMPTY_PARAMS) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) TermQuery(org.apache.lucene.search.TermQuery) Constants(org.apache.lucene.util.Constants) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) FilterDirectory(org.apache.lucene.store.FilterDirectory) Snapshot(org.opensearch.snapshots.Snapshot) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) TranslogStats(org.opensearch.index.translog.TranslogStats) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Matchers.containsString(org.hamcrest.Matchers.containsString) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 3 with DocIdSeqNoAndSource

use of org.opensearch.index.engine.DocIdSeqNoAndSource in project OpenSearch by opensearch-project.

the class RecoveryTests method testRecoveryTrimsLocalTranslog.

public void testRecoveryTrimsLocalTranslog() throws Exception {
    try (ReplicationGroup shards = createGroup(between(1, 2))) {
        shards.startAll();
        IndexShard oldPrimary = shards.getPrimary();
        shards.indexDocs(scaledRandomIntBetween(1, 100));
        if (randomBoolean()) {
            shards.flush();
        }
        int inflightDocs = scaledRandomIntBetween(1, 100);
        for (int i = 0; i < inflightDocs; i++) {
            final IndexRequest indexRequest = new IndexRequest(index.getName()).id("extra_" + i).source("{}", XContentType.JSON);
            final BulkShardRequest bulkShardRequest = indexOnPrimary(indexRequest, oldPrimary);
            for (IndexShard replica : randomSubsetOf(shards.getReplicas())) {
                indexOnReplica(bulkShardRequest, shards, replica);
            }
            if (rarely()) {
                shards.flush();
            }
        }
        shards.syncGlobalCheckpoint();
        shards.promoteReplicaToPrimary(randomFrom(shards.getReplicas())).get();
        oldPrimary.close("demoted", false);
        oldPrimary.store().close();
        oldPrimary = shards.addReplicaWithExistingPath(oldPrimary.shardPath(), oldPrimary.routingEntry().currentNodeId());
        shards.recoverReplica(oldPrimary);
        for (IndexShard shard : shards) {
            assertConsistentHistoryBetweenTranslogAndLucene(shard);
        }
        final List<DocIdSeqNoAndSource> docsAfterRecovery = getDocIdAndSeqNos(shards.getPrimary());
        for (IndexShard shard : shards.getReplicas()) {
            assertThat(shard.routingEntry().toString(), getDocIdAndSeqNos(shard), equalTo(docsAfterRecovery));
        }
        shards.promoteReplicaToPrimary(oldPrimary).get();
        for (IndexShard shard : shards) {
            assertThat(shard.routingEntry().toString(), getDocIdAndSeqNos(shard), equalTo(docsAfterRecovery));
            assertConsistentHistoryBetweenTranslogAndLucene(shard);
        }
    }
}
Also used : BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) IndexShard(org.opensearch.index.shard.IndexShard) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) IndexRequest(org.opensearch.action.index.IndexRequest)

Example 4 with DocIdSeqNoAndSource

use of org.opensearch.index.engine.DocIdSeqNoAndSource in project OpenSearch by opensearch-project.

the class InternalTestCluster method assertSameDocIdsOnShards.

/**
 * Asserts that all shards with the same shardId should have document Ids.
 */
public void assertSameDocIdsOnShards() throws Exception {
    assertBusy(() -> {
        ClusterState state = client().admin().cluster().prepareState().get().getState();
        for (ObjectObjectCursor<String, IndexRoutingTable> indexRoutingTable : state.routingTable().indicesRouting()) {
            for (IntObjectCursor<IndexShardRoutingTable> indexShardRoutingTable : indexRoutingTable.value.shards()) {
                ShardRouting primaryShardRouting = indexShardRoutingTable.value.primaryShard();
                IndexShard primaryShard = getShardOrNull(state, primaryShardRouting);
                if (primaryShard == null) {
                    continue;
                }
                final List<DocIdSeqNoAndSource> docsOnPrimary;
                try {
                    docsOnPrimary = IndexShardTestCase.getDocIdAndSeqNos(primaryShard);
                } catch (AlreadyClosedException ex) {
                    continue;
                }
                for (ShardRouting replicaShardRouting : indexShardRoutingTable.value.replicaShards()) {
                    IndexShard replicaShard = getShardOrNull(state, replicaShardRouting);
                    if (replicaShard == null) {
                        continue;
                    }
                    final List<DocIdSeqNoAndSource> docsOnReplica;
                    try {
                        docsOnReplica = IndexShardTestCase.getDocIdAndSeqNos(replicaShard);
                    } catch (AlreadyClosedException ex) {
                        continue;
                    }
                    assertThat("out of sync shards: primary=[" + primaryShardRouting + "] num_docs_on_primary=[" + docsOnPrimary.size() + "] vs replica=[" + replicaShardRouting + "] num_docs_on_replica=[" + docsOnReplica.size() + "]", docsOnReplica, equalTo(docsOnPrimary));
                }
            }
        }
    });
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) IndexShard(org.opensearch.index.shard.IndexShard) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Aggregations

DocIdSeqNoAndSource (org.opensearch.index.engine.DocIdSeqNoAndSource)4 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)3 IndexRequest (org.opensearch.action.index.IndexRequest)3 ShardRouting (org.opensearch.cluster.routing.ShardRouting)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 TimeUnit (java.util.concurrent.TimeUnit)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Collectors (java.util.stream.Collectors)2 Logger (org.apache.logging.log4j.Logger)2 IndexableField (org.apache.lucene.index.IndexableField)2 Matchers.either (org.hamcrest.Matchers.either)2 Matchers.equalTo (org.hamcrest.Matchers.equalTo)2 Matchers.everyItem (org.hamcrest.Matchers.everyItem)2