Search in sources :

Example 1 with EngineFactory

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

the class IndexLevelReplicationTests method testDocumentFailureReplication.

/**
 * test document failures (failures after seq_no generation) are added as noop operation to the translog
 * for primary and replica shards
 */
public void testDocumentFailureReplication() throws Exception {
    final IOException indexException = new IOException("simulated indexing failure");
    final EngineFactory engineFactory = config -> InternalEngineTests.createInternalEngine((dir, iwc) -> new IndexWriter(dir, iwc) {

        @Override
        public long addDocument(Iterable<? extends IndexableField> doc) throws IOException {
            boolean isTombstone = false;
            for (IndexableField field : doc) {
                if (SeqNoFieldMapper.TOMBSTONE_NAME.equals(field.name())) {
                    isTombstone = true;
                }
            }
            if (isTombstone) {
                // allow to add Noop
                return super.addDocument(doc);
            } else {
                throw indexException;
            }
        }
    }, null, null, config);
    try (ReplicationGroup shards = new ReplicationGroup(buildIndexMetadata(0)) {

        @Override
        protected EngineFactory getEngineFactory(ShardRouting routing) {
            return engineFactory;
        }
    }) {
        // start with the primary only so two first failures are replicated to replicas via recovery from the translog of the primary.
        shards.startPrimary();
        long primaryTerm = shards.getPrimary().getPendingPrimaryTerm();
        List<Translog.Operation> expectedTranslogOps = new ArrayList<>();
        BulkItemResponse indexResp = shards.index(new IndexRequest(index.getName()).id("1").source("{}", XContentType.JSON));
        assertThat(indexResp.isFailed(), equalTo(true));
        assertThat(indexResp.getFailure().getCause(), equalTo(indexException));
        expectedTranslogOps.add(new Translog.NoOp(0, primaryTerm, indexException.toString()));
        try (Translog.Snapshot snapshot = getTranslog(shards.getPrimary()).newSnapshot()) {
            assertThat(snapshot, SnapshotMatchers.containsOperationsInAnyOrder(expectedTranslogOps));
        }
        shards.assertAllEqual(0);
        int nReplica = randomIntBetween(1, 3);
        for (int i = 0; i < nReplica; i++) {
            shards.addReplica();
        }
        shards.startReplicas(nReplica);
        for (IndexShard shard : shards) {
            try (Translog.Snapshot snapshot = getTranslog(shard).newSnapshot()) {
                // we flush at the end of peer recovery
                if (shard.routingEntry().primary() || shard.indexSettings().isSoftDeleteEnabled() == false) {
                    assertThat(snapshot, SnapshotMatchers.containsOperationsInAnyOrder(expectedTranslogOps));
                } else {
                    assertThat(snapshot.totalOperations(), equalTo(0));
                }
            }
            try (Translog.Snapshot snapshot = shard.newChangesSnapshot("test", 0, Long.MAX_VALUE, false)) {
                assertThat(snapshot, SnapshotMatchers.containsOperationsInAnyOrder(expectedTranslogOps));
            }
        }
        // the failure replicated directly from the replication channel.
        indexResp = shards.index(new IndexRequest(index.getName()).id("any").source("{}", XContentType.JSON));
        assertThat(indexResp.getFailure().getCause(), equalTo(indexException));
        Translog.NoOp noop2 = new Translog.NoOp(1, primaryTerm, indexException.toString());
        expectedTranslogOps.add(noop2);
        for (IndexShard shard : shards) {
            try (Translog.Snapshot snapshot = getTranslog(shard).newSnapshot()) {
                if (shard.routingEntry().primary() || shard.indexSettings().isSoftDeleteEnabled() == false) {
                    assertThat(snapshot, SnapshotMatchers.containsOperationsInAnyOrder(expectedTranslogOps));
                } else {
                    assertThat(snapshot, SnapshotMatchers.containsOperationsInAnyOrder(Collections.singletonList(noop2)));
                }
            }
            try (Translog.Snapshot snapshot = shard.newChangesSnapshot("test", 0, Long.MAX_VALUE, false)) {
                assertThat(snapshot, SnapshotMatchers.containsOperationsInAnyOrder(expectedTranslogOps));
            }
        }
        shards.assertAllEqual(0);
    }
}
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) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Map(java.util.Map) 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) EngineFactory(org.opensearch.index.engine.EngineFactory) IndexShard(org.opensearch.index.shard.IndexShard) ArrayList(java.util.ArrayList) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) IOException(java.io.IOException) IndexRequest(org.opensearch.action.index.IndexRequest) Translog(org.opensearch.index.translog.Translog) IndexableField(org.apache.lucene.index.IndexableField) IndexWriter(org.apache.lucene.index.IndexWriter) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Example 2 with EngineFactory

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

the class IndicesService method getEngineFactory.

private EngineFactory getEngineFactory(final IndexSettings idxSettings) {
    final IndexMetadata indexMetadata = idxSettings.getIndexMetadata();
    if (indexMetadata != null && indexMetadata.getState() == IndexMetadata.State.CLOSE) {
        // NoOpEngine takes precedence as long as the index is closed
        return NoOpEngine::new;
    }
    final List<Optional<EngineFactory>> engineFactories = engineFactoryProviders.stream().map(engineFactoryProvider -> engineFactoryProvider.apply(idxSettings)).filter(maybe -> Objects.requireNonNull(maybe).isPresent()).collect(Collectors.toList());
    if (engineFactories.isEmpty()) {
        return new InternalEngineFactory();
    } else if (engineFactories.size() == 1) {
        assert engineFactories.get(0).isPresent();
        return engineFactories.get(0).get();
    } else {
        final String message = String.format(Locale.ROOT, "multiple engine factories provided for %s: %s", idxSettings.getIndex(), engineFactories.stream().map(t -> {
            assert t.isPresent();
            return "[" + t.get().getClass().getName() + "]";
        }).collect(Collectors.joining(",")));
        throw new IllegalStateException(message);
    }
}
Also used : OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) 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) 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) 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) Optional(java.util.Optional) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 3 with EngineFactory

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

the class IndexService method createShard.

public synchronized IndexShard createShard(final ShardRouting routing, final Consumer<ShardId> globalCheckpointSyncer, final RetentionLeaseSyncer retentionLeaseSyncer) throws IOException {
    Objects.requireNonNull(retentionLeaseSyncer);
    /*
         * TODO: we execute this in parallel but it's a synced method. Yet, we might
         * be able to serialize the execution via the cluster state in the future. for now we just
         * keep it synced.
         */
    if (closed.get()) {
        throw new IllegalStateException("Can't create shard " + routing.shardId() + ", closed");
    }
    final Settings indexSettings = this.indexSettings.getSettings();
    final ShardId shardId = routing.shardId();
    boolean success = false;
    Store store = null;
    IndexShard indexShard = null;
    ShardLock lock = null;
    try {
        lock = nodeEnv.shardLock(shardId, "starting shard", TimeUnit.SECONDS.toMillis(5));
        eventListener.beforeIndexShardCreated(shardId, indexSettings);
        ShardPath path;
        try {
            path = ShardPath.loadShardPath(logger, nodeEnv, shardId, this.indexSettings.customDataPath());
        } catch (IllegalStateException ex) {
            logger.warn("{} failed to load shard path, trying to remove leftover", shardId);
            try {
                ShardPath.deleteLeftoverShardDirectory(logger, nodeEnv, lock, this.indexSettings);
                path = ShardPath.loadShardPath(logger, nodeEnv, shardId, this.indexSettings.customDataPath());
            } catch (Exception inner) {
                ex.addSuppressed(inner);
                throw ex;
            }
        }
        if (path == null) {
            // TODO: we should, instead, hold a "bytes reserved" of how large we anticipate this shard will be, e.g. for a shard
            // that's being relocated/replicated we know how large it will become once it's done copying:
            // Count up how many shards are currently on each data path:
            Map<Path, Integer> dataPathToShardCount = new HashMap<>();
            for (IndexShard shard : this) {
                Path dataPath = shard.shardPath().getRootStatePath();
                Integer curCount = dataPathToShardCount.get(dataPath);
                if (curCount == null) {
                    curCount = 0;
                }
                dataPathToShardCount.put(dataPath, curCount + 1);
            }
            path = ShardPath.selectNewPathForShard(nodeEnv, shardId, this.indexSettings, routing.getExpectedShardSize() == ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE ? getAvgShardSizeInBytes() : routing.getExpectedShardSize(), dataPathToShardCount);
            logger.debug("{} creating using a new path [{}]", shardId, path);
        } else {
            logger.debug("{} creating using an existing path [{}]", shardId, path);
        }
        if (shards.containsKey(shardId.id())) {
            throw new IllegalStateException(shardId + " already exists");
        }
        logger.debug("creating shard_id {}", shardId);
        // if we are on a shared FS we only own the shard (ie. we can safely delete it) if we are the primary.
        final Engine.Warmer engineWarmer = (reader) -> {
            IndexShard shard = getShardOrNull(shardId.getId());
            if (shard != null) {
                warmer.warm(reader, shard, IndexService.this.indexSettings);
            }
        };
        Directory directory = directoryFactory.newDirectory(this.indexSettings, path);
        store = new Store(shardId, this.indexSettings, directory, lock, new StoreCloseListener(shardId, () -> eventListener.onStoreClosed(shardId)));
        eventListener.onStoreCreated(shardId);
        indexShard = new IndexShard(routing, this.indexSettings, path, store, indexSortSupplier, indexCache, mapperService, similarityService, engineFactory, engineConfigFactory, eventListener, readerWrapper, threadPool, bigArrays, engineWarmer, searchOperationListeners, indexingOperationListeners, () -> globalCheckpointSyncer.accept(shardId), retentionLeaseSyncer, circuitBreakerService);
        eventListener.indexShardStateChanged(indexShard, null, indexShard.state(), "shard created");
        eventListener.afterIndexShardCreated(indexShard);
        shards = newMapBuilder(shards).put(shardId.id(), indexShard).immutableMap();
        success = true;
        return indexShard;
    } catch (ShardLockObtainFailedException e) {
        throw new IOException("failed to obtain in-memory shard lock", e);
    } finally {
        if (success == false) {
            if (lock != null) {
                IOUtils.closeWhileHandlingException(lock);
            }
            closeShard("initialization failed", shardId, indexShard, store, eventListener);
        }
    }
}
Also used : Path(java.nio.file.Path) ShardPath(org.opensearch.index.shard.ShardPath) LongSupplier(java.util.function.LongSupplier) CheckedFunction(org.opensearch.common.CheckedFunction) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) MapBuilder.newMapBuilder(org.opensearch.common.collect.MapBuilder.newMapBuilder) BooleanSupplier(java.util.function.BooleanSupplier) IndexStorePlugin(org.opensearch.plugins.IndexStorePlugin) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) WriteStateException(org.opensearch.gateway.WriteStateException) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Directory(org.apache.lucene.store.Directory) Assertions(org.opensearch.Assertions) Property(org.opensearch.common.settings.Setting.Property) Map(java.util.Map) BitsetFilterCache(org.opensearch.index.cache.bitset.BitsetFilterCache) Path(java.nio.file.Path) NodeEnvironment(org.opensearch.env.NodeEnvironment) ScriptService(org.opensearch.script.ScriptService) Client(org.opensearch.client.Client) IndicesClusterStateService(org.opensearch.indices.cluster.IndicesClusterStateService) TimeValue(org.opensearch.common.unit.TimeValue) IndexEventListener(org.opensearch.index.shard.IndexEventListener) Sort(org.apache.lucene.search.Sort) DirectoryReader(org.apache.lucene.index.DirectoryReader) SearchIndexNameMatcher(org.opensearch.index.query.SearchIndexNameMatcher) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) IndexShardClosedException(org.opensearch.index.shard.IndexShardClosedException) Store(org.opensearch.index.store.Store) Nullable(org.opensearch.common.Nullable) Engine(org.opensearch.index.engine.Engine) Objects(java.util.Objects) List(java.util.List) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) Accountable(org.apache.lucene.util.Accountable) QueryShardContext(org.opensearch.index.query.QueryShardContext) BigArrays(org.opensearch.common.util.BigArrays) ShardLock(org.opensearch.env.ShardLock) IndexReader(org.apache.lucene.index.IndexReader) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) IndexSearcher(org.apache.lucene.search.IndexSearcher) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) SimilarityService(org.opensearch.index.similarity.SimilarityService) QueryCache(org.opensearch.index.cache.query.QueryCache) ThreadPool(org.opensearch.threadpool.ThreadPool) ShardNotInPrimaryModeException(org.opensearch.index.shard.ShardNotInPrimaryModeException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ValuesSourceRegistry(org.opensearch.search.aggregations.support.ValuesSourceRegistry) HashMap(java.util.HashMap) IndicesFieldDataCache(org.opensearch.indices.fielddata.cache.IndicesFieldDataCache) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Function(java.util.function.Function) Supplier(java.util.function.Supplier) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) IndexShard(org.opensearch.index.shard.IndexShard) AbstractAsyncTask(org.opensearch.common.util.concurrent.AbstractAsyncTask) IndexingOperationListener(org.opensearch.index.shard.IndexingOperationListener) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) MetadataStateFormat(org.opensearch.gateway.MetadataStateFormat) Translog(org.opensearch.index.translog.Translog) ShardPath(org.opensearch.index.shard.ShardPath) EngineFactory(org.opensearch.index.engine.EngineFactory) Collections.emptyMap(java.util.Collections.emptyMap) Setting(org.opensearch.common.settings.Setting) Iterator(java.util.Iterator) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) SearchOperationListener(org.opensearch.index.shard.SearchOperationListener) IndexCache(org.opensearch.index.cache.IndexCache) IndexFieldDataService(org.opensearch.index.fielddata.IndexFieldDataService) 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) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) Closeable(java.io.Closeable) ClusterService(org.opensearch.cluster.service.ClusterService) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) Collections(java.util.Collections) HashMap(java.util.HashMap) IndexShard(org.opensearch.index.shard.IndexShard) Store(org.opensearch.index.store.Store) IOException(java.io.IOException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) WriteStateException(org.opensearch.gateway.WriteStateException) IndexShardClosedException(org.opensearch.index.shard.IndexShardClosedException) ShardNotInPrimaryModeException(org.opensearch.index.shard.ShardNotInPrimaryModeException) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) ShardId(org.opensearch.index.shard.ShardId) ShardPath(org.opensearch.index.shard.ShardPath) ShardLock(org.opensearch.env.ShardLock) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) Settings(org.opensearch.common.settings.Settings) Engine(org.opensearch.index.engine.Engine) Directory(org.apache.lucene.store.Directory)

Example 4 with EngineFactory

use of org.opensearch.index.engine.EngineFactory 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) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Map(java.util.Map) 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 5 with EngineFactory

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

the class RecoveryTests method testFailsToIndexDuringPeerRecovery.

public void testFailsToIndexDuringPeerRecovery() throws Exception {
    AtomicReference<IOException> throwExceptionDuringIndexing = new AtomicReference<>(new IOException("simulated"));
    try (ReplicationGroup group = new ReplicationGroup(buildIndexMetadata(0)) {

        @Override
        protected EngineFactory getEngineFactory(ShardRouting routing) {
            if (routing.primary()) {
                return new InternalEngineFactory();
            } else {
                return config -> InternalEngineTests.createInternalEngine((dir, iwc) -> new IndexWriter(dir, iwc) {

                    @Override
                    public long addDocument(Iterable<? extends IndexableField> doc) throws IOException {
                        final IOException error = throwExceptionDuringIndexing.getAndSet(null);
                        if (error != null) {
                            throw error;
                        }
                        return super.addDocument(doc);
                    }
                }, null, null, config);
            }
        }
    }) {
        group.startAll();
        group.indexDocs(randomIntBetween(1, 10));
        allowShardFailures();
        IndexShard replica = group.addReplica();
        expectThrows(Exception.class, () -> group.recoverReplica(replica, (shard, sourceNode) -> new RecoveryTarget(shard, sourceNode, new PeerRecoveryTargetService.RecoveryListener() {

            @Override
            public void onRecoveryDone(RecoveryState state) {
                throw new AssertionError("recovery must fail");
            }

            @Override
            public void onRecoveryFailure(RecoveryState state, RecoveryFailedException e, boolean sendShardFailure) {
                assertThat(ExceptionsHelper.unwrap(e, IOException.class).getMessage(), equalTo("simulated"));
            }
        })));
        expectThrows(AlreadyClosedException.class, () -> replica.refresh("test"));
        group.removeReplica(replica);
        replica.store().close();
        closeShards(replica);
    }
}
Also used : IndexCommit(org.apache.lucene.index.IndexCommit) NoMergePolicy(org.apache.lucene.index.NoMergePolicy) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) IndexableField(org.apache.lucene.index.IndexableField) Matchers.not(org.hamcrest.Matchers.not) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) OpenSearchIndexLevelReplicationTestCase(org.opensearch.index.replication.OpenSearchIndexLevelReplicationTestCase) InternalEngineTests(org.opensearch.index.engine.InternalEngineTests) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) SourceToParse(org.opensearch.index.mapper.SourceToParse) IndexShard(org.opensearch.index.shard.IndexShard) Future(java.util.concurrent.Future) RandomNumbers(com.carrotsearch.randomizedtesting.generators.RandomNumbers) Map(java.util.Map) Translog(org.opensearch.index.translog.Translog) ActionListener(org.opensearch.action.ActionListener) UUIDs(org.opensearch.common.UUIDs) EngineFactory(org.opensearch.index.engine.EngineFactory) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Versions(org.opensearch.common.lucene.uid.Versions) Matchers.empty(org.hamcrest.Matchers.empty) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) DirectoryReader(org.apache.lucene.index.DirectoryReader) BulkShardRequest(org.opensearch.action.bulk.BulkShardRequest) ExceptionsHelper(org.opensearch.ExceptionsHelper) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) Store(org.opensearch.index.store.Store) ShardRouting(org.opensearch.cluster.routing.ShardRouting) 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) BytesArray(org.opensearch.common.bytes.BytesArray) SnapshotMatchers(org.opensearch.index.translog.SnapshotMatchers) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) RecoveryDuringReplicationTests(org.opensearch.index.replication.RecoveryDuringReplicationTests) XContentType(org.opensearch.common.xcontent.XContentType) MergePolicyConfig(org.opensearch.index.MergePolicyConfig) IndexRequest(org.opensearch.action.index.IndexRequest) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) IndexShard(org.opensearch.index.shard.IndexShard) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IndexWriter(org.apache.lucene.index.IndexWriter) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Aggregations

IOException (java.io.IOException)5 List (java.util.List)5 Map (java.util.Map)5 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)5 ShardRouting (org.opensearch.cluster.routing.ShardRouting)5 Settings (org.opensearch.common.settings.Settings)5 Collections (java.util.Collections)4 Set (java.util.Set)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 TimeUnit (java.util.concurrent.TimeUnit)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 TimeValue (org.opensearch.common.unit.TimeValue)4 XContentType (org.opensearch.common.xcontent.XContentType)4 EngineFactory (org.opensearch.index.engine.EngineFactory)4 IndexShard (org.opensearch.index.shard.IndexShard)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Future (java.util.concurrent.Future)3 DirectoryReader (org.apache.lucene.index.DirectoryReader)3 IndexWriter (org.apache.lucene.index.IndexWriter)3