Search in sources :

Example 6 with InternalEngine

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

the class IndexShardTests method testCloseShardWhileResettingEngine.

/**
 * This test simulates a scenario seen rarely in ConcurrentSeqNoVersioningIT. Closing a shard while engine is inside
 * resetEngineToGlobalCheckpoint can lead to check index failure in integration tests.
 */
public void testCloseShardWhileResettingEngine() throws Exception {
    CountDownLatch readyToCloseLatch = new CountDownLatch(1);
    CountDownLatch closeDoneLatch = new CountDownLatch(1);
    IndexShard shard = newStartedShard(false, Settings.EMPTY, config -> new InternalEngine(config) {

        @Override
        public InternalEngine recoverFromTranslog(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo) throws IOException {
            readyToCloseLatch.countDown();
            try {
                closeDoneLatch.await();
            } catch (InterruptedException e) {
                throw new AssertionError(e);
            }
            return super.recoverFromTranslog(translogRecoveryRunner, recoverUpToSeqNo);
        }
    });
    Thread closeShardThread = new Thread(() -> {
        try {
            readyToCloseLatch.await();
            shard.close("testing", false);
            // in integration tests, this is done as a listener on IndexService.
            MockFSDirectoryFactory.checkIndex(logger, shard.store(), shard.shardId);
        } catch (InterruptedException | IOException e) {
            throw new AssertionError(e);
        } finally {
            closeDoneLatch.countDown();
        }
    });
    closeShardThread.start();
    final CountDownLatch engineResetLatch = new CountDownLatch(1);
    shard.acquireAllReplicaOperationsPermits(shard.getOperationPrimaryTerm(), shard.getLastKnownGlobalCheckpoint(), 0L, ActionListener.wrap(r -> {
        try (Releasable dummy = r) {
            shard.resetEngineToGlobalCheckpoint();
        } finally {
            engineResetLatch.countDown();
        }
    }, Assert::assertNotNull), TimeValue.timeValueMinutes(1L));
    engineResetLatch.await();
    closeShardThread.join();
    // close store.
    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) NRTReplicationEngineFactory(org.opensearch.index.engine.NRTReplicationEngineFactory) 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) ReferenceManager(org.apache.lucene.search.ReferenceManager) 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) 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) Mockito.mock(org.mockito.Mockito.mock) IndexCommit(org.apache.lucene.index.IndexCommit) 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) 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) Assert(org.junit.Assert) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) 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) ReplicationLuceneIndex(org.opensearch.indices.replication.common.ReplicationLuceneIndex) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) SegmentReplicationCheckpointPublisher(org.opensearch.indices.replication.checkpoint.SegmentReplicationCheckpointPublisher) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) EngineTestCase(org.opensearch.index.engine.EngineTestCase) CyclicBarrier(java.util.concurrent.CyclicBarrier) 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) GatedCloseable(org.opensearch.common.concurrent.GatedCloseable) 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) NRTReplicationEngine(org.opensearch.index.engine.NRTReplicationEngine) 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) ReplicationType(org.opensearch.indices.replication.common.ReplicationType) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) InternalEngine(org.opensearch.index.engine.InternalEngine) Releasable(org.opensearch.common.lease.Releasable)

Example 7 with InternalEngine

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

the class IndexShardTests method testRecordsForceMerges.

public void testRecordsForceMerges() throws IOException {
    IndexShard shard = newStartedShard(true);
    final String initialForceMergeUUID = ((InternalEngine) shard.getEngine()).getForceMergeUUID();
    assertThat(initialForceMergeUUID, nullValue());
    final ForceMergeRequest firstForceMergeRequest = new ForceMergeRequest().maxNumSegments(1);
    shard.forceMerge(firstForceMergeRequest);
    final String secondForceMergeUUID = ((InternalEngine) shard.getEngine()).getForceMergeUUID();
    assertThat(secondForceMergeUUID, notNullValue());
    assertThat(secondForceMergeUUID, equalTo(firstForceMergeRequest.forceMergeUUID()));
    final ForceMergeRequest secondForceMergeRequest = new ForceMergeRequest().maxNumSegments(1);
    shard.forceMerge(secondForceMergeRequest);
    final String thirdForceMergeUUID = ((InternalEngine) shard.getEngine()).getForceMergeUUID();
    assertThat(thirdForceMergeUUID, notNullValue());
    assertThat(thirdForceMergeUUID, not(equalTo(secondForceMergeUUID)));
    assertThat(thirdForceMergeUUID, equalTo(secondForceMergeRequest.forceMergeUUID()));
    closeShards(shard);
}
Also used : ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) Matchers.hasToString(org.hamcrest.Matchers.hasToString) Matchers.containsString(org.hamcrest.Matchers.containsString) InternalEngine(org.opensearch.index.engine.InternalEngine)

Example 8 with InternalEngine

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

the class IndexLevelReplicationTests method testAppendOnlyRecoveryThenReplication.

public void testAppendOnlyRecoveryThenReplication() throws Exception {
    CountDownLatch indexedOnPrimary = new CountDownLatch(1);
    CountDownLatch recoveryDone = new CountDownLatch(1);
    try (ReplicationGroup shards = new ReplicationGroup(buildIndexMetadata(1)) {

        @Override
        protected EngineFactory getEngineFactory(ShardRouting routing) {
            return config -> new InternalEngine(config) {

                @Override
                public IndexResult index(Index op) throws IOException {
                    IndexResult result = super.index(op);
                    if (op.origin() == Operation.Origin.PRIMARY) {
                        indexedOnPrimary.countDown();
                        // to make sure that this operation is replicated to the replica via recovery, then via replication.
                        try {
                            recoveryDone.await();
                        } catch (InterruptedException e) {
                            throw new AssertionError(e);
                        }
                    }
                    return result;
                }
            };
        }
    }) {
        shards.startAll();
        Thread thread = new Thread(() -> {
            IndexRequest indexRequest = new IndexRequest(index.getName()).source("{}", XContentType.JSON);
            try {
                shards.index(indexRequest);
            } catch (Exception e) {
                throw new AssertionError(e);
            }
        });
        thread.start();
        IndexShard replica = shards.addReplica();
        Future<Void> fut = shards.asyncRecoverReplica(replica, (shard, node) -> new RecoveryTarget(shard, node, recoveryListener) {

            @Override
            public void prepareForTranslogOperations(int totalTranslogOps, ActionListener<Void> listener) {
                try {
                    indexedOnPrimary.await();
                } catch (InterruptedException e) {
                    throw new AssertionError(e);
                }
                super.prepareForTranslogOperations(totalTranslogOps, listener);
            }
        });
        fut.get();
        recoveryDone.countDown();
        thread.join();
        shards.assertAllEqual(1);
    }
}
Also used : SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Matchers.either(org.hamcrest.Matchers.either) IndexableField(org.apache.lucene.index.IndexableField) Term(org.apache.lucene.index.Term) Iterables(org.opensearch.common.util.iterable.Iterables) TestThreadPool(org.opensearch.threadpool.TestThreadPool) Version(org.opensearch.Version) InternalEngine(org.opensearch.index.engine.InternalEngine) Future(java.util.concurrent.Future) MapperService(org.opensearch.index.mapper.MapperService) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Is.is(org.hamcrest.core.Is.is) ActionListener(org.opensearch.action.ActionListener) SegmentsStats(org.opensearch.index.engine.SegmentsStats) DeleteRequest(org.opensearch.action.delete.DeleteRequest) EngineTestCase(org.opensearch.index.engine.EngineTestCase) CyclicBarrier(java.util.concurrent.CyclicBarrier) TimeValue(org.opensearch.common.unit.TimeValue) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) Store(org.opensearch.index.store.Store) Engine(org.opensearch.index.engine.Engine) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) IndexWriter(org.apache.lucene.index.IndexWriter) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) DocWriteResponse(org.opensearch.action.DocWriteResponse) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) InternalEngineTests(org.opensearch.index.engine.InternalEngineTests) HashSet(java.util.HashSet) IndexShard(org.opensearch.index.shard.IndexShard) SnapshotMatchers.containsOperationsInAnyOrder(org.opensearch.index.translog.SnapshotMatchers.containsOperationsInAnyOrder) Translog(org.opensearch.index.translog.Translog) IndexShardTests(org.opensearch.index.shard.IndexShardTests) EngineFactory(org.opensearch.index.engine.EngineFactory) TopDocs(org.apache.lucene.search.TopDocs) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IOException(java.io.IOException) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TimeUnit(java.util.concurrent.TimeUnit) TermQuery(org.apache.lucene.search.TermQuery) SnapshotMatchers(org.opensearch.index.translog.SnapshotMatchers) Matcher(org.hamcrest.Matcher) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) SeqNoFieldMapper(org.opensearch.index.mapper.SeqNoFieldMapper) IndexShard(org.opensearch.index.shard.IndexShard) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) CountDownLatch(java.util.concurrent.CountDownLatch) IndexRequest(org.opensearch.action.index.IndexRequest) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IOException(java.io.IOException) InternalEngine(org.opensearch.index.engine.InternalEngine) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Example 9 with InternalEngine

use of org.opensearch.index.engine.InternalEngine in project k-NN by opensearch-project.

the class KNNEngineFactory method newReadWriteEngine.

@Override
public Engine newReadWriteEngine(EngineConfig config) {
    codecService.setPostingsFormat(config.getCodec().postingsFormat());
    EngineConfig engineConfig = new EngineConfig(config.getShardId(), config.getThreadPool(), config.getIndexSettings(), config.getWarmer(), config.getStore(), config.getMergePolicy(), config.getAnalyzer(), config.getSimilarity(), codecService, config.getEventListener(), config.getQueryCache(), config.getQueryCachingPolicy(), config.getTranslogConfig(), config.getFlushMergesAfter(), config.getExternalRefreshListener(), config.getInternalRefreshListener(), config.getIndexSort(), config.getCircuitBreakerService(), config.getGlobalCheckpointSupplier(), config.retentionLeasesSupplier(), config.getPrimaryTermSupplier(), config.getTombstoneDocSupplier());
    return new InternalEngine(engineConfig);
}
Also used : EngineConfig(org.opensearch.index.engine.EngineConfig) InternalEngine(org.opensearch.index.engine.InternalEngine)

Aggregations

InternalEngine (org.opensearch.index.engine.InternalEngine)9 IOException (java.io.IOException)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 Engine (org.opensearch.index.engine.Engine)6 IndexSettings (org.opensearch.index.IndexSettings)5 EngineConfig (org.opensearch.index.engine.EngineConfig)5 ArrayList (java.util.ArrayList)4 Collections (java.util.Collections)4 HashSet (java.util.HashSet)4 List (java.util.List)4 Set (java.util.Set)4 CyclicBarrier (java.util.concurrent.CyclicBarrier)4 TimeUnit (java.util.concurrent.TimeUnit)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 IndexableField (org.apache.lucene.index.IndexableField)3 Term (org.apache.lucene.index.Term)3 TermQuery (org.apache.lucene.search.TermQuery)3 TopDocs (org.apache.lucene.search.TopDocs)3 Matchers.either (org.hamcrest.Matchers.either)3