Search in sources :

Example 16 with CheckedFunction

use of org.opensearch.common.CheckedFunction in project OpenSearch by opensearch-project.

the class IndexShardIT method testShardHasMemoryBufferOnTranslogRecover.

public void testShardHasMemoryBufferOnTranslogRecover() throws Throwable {
    createIndex("test");
    ensureGreen();
    IndicesService indicesService = getInstanceFromNode(IndicesService.class);
    IndexService indexService = indicesService.indexService(resolveIndex("test"));
    IndexShard shard = indexService.getShardOrNull(0);
    client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get();
    client().prepareDelete("test", "0").get();
    client().prepareIndex("test").setId("1").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).setRefreshPolicy(IMMEDIATE).get();
    CheckedFunction<DirectoryReader, DirectoryReader, IOException> wrapper = directoryReader -> directoryReader;
    shard.close("simon says", false);
    AtomicReference<IndexShard> shardRef = new AtomicReference<>();
    List<Exception> failures = new ArrayList<>();
    IndexingOperationListener listener = new IndexingOperationListener() {

        @Override
        public void postIndex(ShardId shardId, Engine.Index index, Engine.IndexResult result) {
            try {
                assertNotNull(shardRef.get());
                // this is all IMC needs to do - check current memory and refresh
                assertTrue(shardRef.get().getIndexBufferRAMBytesUsed() > 0);
                shardRef.get().refresh("test");
            } catch (Exception e) {
                failures.add(e);
                throw e;
            }
        }

        @Override
        public void postDelete(ShardId shardId, Engine.Delete delete, Engine.DeleteResult result) {
            try {
                assertNotNull(shardRef.get());
                // this is all IMC needs to do - check current memory and refresh
                assertTrue(shardRef.get().getIndexBufferRAMBytesUsed() > 0);
                shardRef.get().refresh("test");
            } catch (Exception e) {
                failures.add(e);
                throw e;
            }
        }
    };
    final IndexShard newShard = newIndexShard(indexService, shard, wrapper, getInstanceFromNode(CircuitBreakerService.class), listener);
    shardRef.set(newShard);
    recoverShard(newShard);
    try {
        ExceptionsHelper.rethrowAndSuppress(failures);
    } finally {
        newShard.close("just do it", randomBoolean());
    }
}
Also used : SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Arrays(java.util.Arrays) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) CheckedFunction(org.opensearch.common.CheckedFunction) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) DirectoryStream(java.nio.file.DirectoryStream) NONE(org.opensearch.action.support.WriteRequest.RefreshPolicy.NONE) RecoveryState(org.opensearch.indices.recovery.RecoveryState) ActionListener(org.opensearch.action.ActionListener) Path(java.nio.file.Path) NodeEnvironment(org.opensearch.env.NodeEnvironment) TimeValue(org.opensearch.common.unit.TimeValue) OpenSearchAssertions.assertNoFailures(org.opensearch.test.hamcrest.OpenSearchAssertions.assertNoFailures) Index(org.opensearch.index.Index) Matchers.allOf(org.hamcrest.Matchers.allOf) ExceptionsHelper(org.opensearch.ExceptionsHelper) Settings(org.opensearch.common.settings.Settings) Engine(org.opensearch.index.engine.Engine) UncheckedIOException(java.io.UncheckedIOException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Stream(java.util.stream.Stream) BytesArray(org.opensearch.common.bytes.BytesArray) CheckedRunnable(org.opensearch.common.CheckedRunnable) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) ShardLock(org.opensearch.env.ShardLock) TestShardRouting.newShardRouting(org.opensearch.cluster.routing.TestShardRouting.newShardRouting) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) ClusterInfoService(org.opensearch.cluster.ClusterInfoService) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) ClusterState(org.opensearch.cluster.ClusterState) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) SearchRequest(org.opensearch.action.search.SearchRequest) CommitStats(org.opensearch.index.engine.CommitStats) Environment(org.opensearch.env.Environment) Versions(org.opensearch.common.lucene.uid.Versions) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) FlushStats(org.opensearch.index.flush.FlushStats) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) IndexService(org.opensearch.index.IndexService) Plugin(org.opensearch.plugins.Plugin) ClusterService(org.opensearch.cluster.service.ClusterService) SETTING_NUMBER_OF_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) Assert(org.junit.Assert) RandomizedTest.randomAsciiLettersOfLength(com.carrotsearch.randomizedtesting.RandomizedTest.randomAsciiLettersOfLength) IndexShardTestCase.getTranslog(org.opensearch.index.shard.IndexShardTestCase.getTranslog) Matchers.either(org.hamcrest.Matchers.either) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) Locale(java.util.Locale) DummyShardLock(org.opensearch.test.DummyShardLock) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) SETTING_NUMBER_OF_REPLICAS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS) CyclicBarrier(java.util.concurrent.CyclicBarrier) Predicate(java.util.function.Predicate) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) DirectoryReader(org.apache.lucene.index.DirectoryReader) Collection(java.util.Collection) IndicesService(org.opensearch.indices.IndicesService) InternalClusterInfoService(org.opensearch.cluster.InternalClusterInfoService) List(java.util.List) IMMEDIATE(org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) TranslogStats(org.opensearch.index.translog.TranslogStats) IndexSettingsModule(org.opensearch.test.IndexSettingsModule) NoOpEngine(org.opensearch.index.engine.NoOpEngine) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) IndicesOptions(org.opensearch.action.support.IndicesOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) SourceToParse(org.opensearch.index.mapper.SourceToParse) InternalSettingsPlugin(org.opensearch.test.InternalSettingsPlugin) IndexShardTestCase.recoverFromStore(org.opensearch.index.shard.IndexShardTestCase.recoverFromStore) Translog(org.opensearch.index.translog.Translog) SearchResponse(org.opensearch.action.search.SearchResponse) UUIDs(org.opensearch.common.UUIDs) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Collections.emptyMap(java.util.Collections.emptyMap) Collections.emptySet(java.util.Collections.emptySet) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) TimeUnit(java.util.concurrent.TimeUnit) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) IndexRequest(org.opensearch.action.index.IndexRequest) Comparator(java.util.Comparator) Collections(java.util.Collections) IndexService(org.opensearch.index.IndexService) DirectoryReader(org.apache.lucene.index.DirectoryReader) ArrayList(java.util.ArrayList) IndicesService(org.opensearch.indices.IndicesService) AtomicReference(java.util.concurrent.atomic.AtomicReference) Index(org.opensearch.index.Index) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService)

Example 17 with CheckedFunction

use of org.opensearch.common.CheckedFunction in project OpenSearch by opensearch-project.

the class IndicesService method buildAliasFilter.

public AliasFilter buildAliasFilter(ClusterState state, String index, Set<String> resolvedExpressions) {
    /* Being static, parseAliasFilter doesn't have access to whatever guts it needs to parse a query. Instead of passing in a bunch
         * of dependencies we pass in a function that can perform the parsing. */
    CheckedFunction<BytesReference, QueryBuilder, IOException> filterParser = bytes -> {
        try (InputStream inputStream = bytes.streamInput();
            XContentParser parser = XContentFactory.xContentType(inputStream).xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, inputStream)) {
            return parseInnerQueryBuilder(parser);
        }
    };
    IndexMetadata indexMetadata = state.metadata().index(index);
    String[] aliases = indexNameExpressionResolver.filteringAliases(state, index, resolvedExpressions);
    return new AliasFilter(ShardSearchRequest.parseAliasFilter(filterParser, indexMetadata, aliases), aliases);
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) 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) AliasFilter(org.opensearch.search.internal.AliasFilter) InputStream(java.io.InputStream) QueryBuilder(org.opensearch.index.query.QueryBuilder) AbstractQueryBuilder.parseInnerQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 18 with CheckedFunction

use of org.opensearch.common.CheckedFunction in project OpenSearch by opensearch-project.

the class IndexModule method newIndexService.

public IndexService newIndexService(IndexService.IndexCreationContext indexCreationContext, NodeEnvironment environment, NamedXContentRegistry xContentRegistry, IndexService.ShardStoreDeleter shardStoreDeleter, CircuitBreakerService circuitBreakerService, BigArrays bigArrays, ThreadPool threadPool, ScriptService scriptService, ClusterService clusterService, Client client, IndicesQueryCache indicesQueryCache, MapperRegistry mapperRegistry, IndicesFieldDataCache indicesFieldDataCache, NamedWriteableRegistry namedWriteableRegistry, BooleanSupplier idFieldDataEnabled, ValuesSourceRegistry valuesSourceRegistry) throws IOException {
    final IndexEventListener eventListener = freeze();
    Function<IndexService, CheckedFunction<DirectoryReader, DirectoryReader, IOException>> readerWrapperFactory = indexReaderWrapper.get() == null ? (shard) -> null : indexReaderWrapper.get();
    eventListener.beforeIndexCreated(indexSettings.getIndex(), indexSettings.getSettings());
    final IndexStorePlugin.DirectoryFactory directoryFactory = getDirectoryFactory(indexSettings, directoryFactories);
    final IndexStorePlugin.RecoveryStateFactory recoveryStateFactory = getRecoveryStateFactory(indexSettings, recoveryStateFactories);
    QueryCache queryCache = null;
    IndexAnalyzers indexAnalyzers = null;
    boolean success = false;
    try {
        if (indexSettings.getValue(INDEX_QUERY_CACHE_ENABLED_SETTING)) {
            BiFunction<IndexSettings, IndicesQueryCache, QueryCache> queryCacheProvider = forceQueryCacheProvider.get();
            if (queryCacheProvider == null) {
                queryCache = new IndexQueryCache(indexSettings, indicesQueryCache);
            } else {
                queryCache = queryCacheProvider.apply(indexSettings, indicesQueryCache);
            }
        } else {
            queryCache = new DisabledQueryCache(indexSettings);
        }
        if (IndexService.needsMapperService(indexSettings, indexCreationContext)) {
            indexAnalyzers = analysisRegistry.build(indexSettings);
        }
        final IndexService indexService = new IndexService(indexSettings, indexCreationContext, environment, xContentRegistry, new SimilarityService(indexSettings, scriptService, similarities), shardStoreDeleter, indexAnalyzers, engineFactory, engineConfigFactory, circuitBreakerService, bigArrays, threadPool, scriptService, clusterService, client, queryCache, directoryFactory, eventListener, readerWrapperFactory, mapperRegistry, indicesFieldDataCache, searchOperationListeners, indexOperationListeners, namedWriteableRegistry, idFieldDataEnabled, allowExpensiveQueries, expressionResolver, valuesSourceRegistry, recoveryStateFactory);
        success = true;
        return indexService;
    } finally {
        if (success == false) {
            IOUtils.closeWhileHandlingException(queryCache, indexAnalyzers);
        }
    }
}
Also used : IndicesQueryCache(org.opensearch.indices.IndicesQueryCache) QueryCache(org.opensearch.index.cache.query.QueryCache) IndicesQueryCache(org.opensearch.indices.IndicesQueryCache) IndexQueryCache(org.opensearch.index.cache.query.IndexQueryCache) DisabledQueryCache(org.opensearch.index.cache.query.DisabledQueryCache) IndexQueryCache(org.opensearch.index.cache.query.IndexQueryCache) IndexEventListener(org.opensearch.index.shard.IndexEventListener) SimilarityService(org.opensearch.index.similarity.SimilarityService) IndexStorePlugin(org.opensearch.plugins.IndexStorePlugin) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) DisabledQueryCache(org.opensearch.index.cache.query.DisabledQueryCache) CheckedFunction(org.opensearch.common.CheckedFunction)

Example 19 with CheckedFunction

use of org.opensearch.common.CheckedFunction in project OpenSearch by opensearch-project.

the class MetadataRolloverServiceTests method mockIndicesServices.

private IndicesService mockIndicesServices(DocumentMapper documentMapper) throws Exception {
    /*
         * Throws Exception because Eclipse uses the lower bound for
         * CheckedFunction's exception type so it thinks the "when" call
         * can throw Exception. javac seems to be ok inferring something
         * else.
         */
    IndicesService indicesService = mock(IndicesService.class);
    when(indicesService.withTempIndexService(any(IndexMetadata.class), any(CheckedFunction.class))).then(invocationOnMock -> {
        IndexService indexService = mock(IndexService.class);
        IndexMetadata indexMetadata = (IndexMetadata) invocationOnMock.getArguments()[0];
        when(indexService.index()).thenReturn(indexMetadata.getIndex());
        MapperService mapperService = mock(MapperService.class);
        when(indexService.mapperService()).thenReturn(mapperService);
        when(mapperService.documentMapper()).thenReturn(documentMapper);
        when(indexService.getIndexEventListener()).thenReturn(new IndexEventListener() {
        });
        when(indexService.getIndexSortSupplier()).thenReturn(() -> null);
        // noinspection unchecked
        return ((CheckedFunction) invocationOnMock.getArguments()[1]).apply(indexService);
    });
    return indicesService;
}
Also used : IndexEventListener(org.opensearch.index.shard.IndexEventListener) MetadataCreateIndexService(org.opensearch.cluster.metadata.MetadataCreateIndexService) IndexService(org.opensearch.index.IndexService) IndicesService(org.opensearch.indices.IndicesService) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) MapperService(org.opensearch.index.mapper.MapperService) CheckedFunction(org.opensearch.common.CheckedFunction)

Example 20 with CheckedFunction

use of org.opensearch.common.CheckedFunction in project OpenSearch by opensearch-project.

the class IndexShardTests method testReaderWrapperIsUsed.

public void testReaderWrapperIsUsed() throws IOException {
    IndexShard shard = newStartedShard(true);
    indexDoc(shard, "_doc", "0", "{\"foo\" : \"bar\"}");
    indexDoc(shard, "_doc", "1", "{\"foobar\" : \"bar\"}");
    shard.refresh("test");
    try (Engine.GetResult getResult = shard.get(new Engine.Get(false, false, "1", new Term(IdFieldMapper.NAME, Uid.encodeId("1"))))) {
        assertTrue(getResult.exists());
        assertNotNull(getResult.searcher());
    }
    try (Engine.Searcher searcher = shard.acquireSearcher("test")) {
        TopDocs search = searcher.search(new TermQuery(new Term("foo", "bar")), 10);
        assertEquals(search.totalHits.value, 1);
        search = searcher.search(new TermQuery(new Term("foobar", "bar")), 10);
        assertEquals(search.totalHits.value, 1);
    }
    CheckedFunction<DirectoryReader, DirectoryReader, IOException> wrapper = reader -> new FieldMaskingReader("foo", reader);
    closeShards(shard);
    IndexShard newShard = newShard(ShardRoutingHelper.initWithSameId(shard.routingEntry(), RecoverySource.ExistingStoreRecoverySource.INSTANCE), shard.shardPath(), shard.indexSettings().getIndexMetadata(), null, wrapper, new InternalEngineFactory(), shard.getEngineConfigFactory(), () -> {
    }, RetentionLeaseSyncer.EMPTY, EMPTY_EVENT_LISTENER);
    recoverShardFromStore(newShard);
    try (Engine.Searcher searcher = newShard.acquireSearcher("test")) {
        TopDocs search = searcher.search(new TermQuery(new Term("foo", "bar")), 10);
        assertEquals(search.totalHits.value, 0);
        search = searcher.search(new TermQuery(new Term("foobar", "bar")), 10);
        assertEquals(search.totalHits.value, 1);
    }
    try (Engine.GetResult getResult = newShard.get(new Engine.Get(false, false, "1", new Term(IdFieldMapper.NAME, Uid.encodeId("1"))))) {
        assertTrue(getResult.exists());
        // make sure get uses the wrapped reader
        assertNotNull(getResult.searcher());
        assertTrue(getResult.searcher().getIndexReader() instanceof FieldMaskingReader);
    }
    closeShards(newShard);
}
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) TermQuery(org.apache.lucene.search.TermQuery) DirectoryReader(org.apache.lucene.index.DirectoryReader) FieldMaskingReader(org.opensearch.test.FieldMaskingReader) Term(org.apache.lucene.index.Term) IOException(java.io.IOException) TopDocs(org.apache.lucene.search.TopDocs) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) InternalEngine(org.opensearch.index.engine.InternalEngine) Engine(org.opensearch.index.engine.Engine) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine)

Aggregations

CheckedFunction (org.opensearch.common.CheckedFunction)22 IOException (java.io.IOException)19 Collections (java.util.Collections)17 Arrays (java.util.Arrays)15 List (java.util.List)15 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)15 ArrayList (java.util.ArrayList)14 Map (java.util.Map)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)13 Set (java.util.Set)12 Collectors (java.util.stream.Collectors)12 Stream (java.util.stream.Stream)12 OpenSearchException (org.opensearch.OpenSearchException)12 ActionListener (org.opensearch.action.ActionListener)12 NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)12 HashSet (java.util.HashSet)11 Tuple (org.opensearch.common.collect.Tuple)11 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)11 HashMap (java.util.HashMap)10