Search in sources :

Example 1 with IndexCache

use of org.opensearch.index.cache.IndexCache 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 2 with IndexCache

use of org.opensearch.index.cache.IndexCache in project OpenSearch by opensearch-project.

the class IndexShard method newEngineConfig.

private EngineConfig newEngineConfig(LongSupplier globalCheckpointSupplier) {
    final Sort indexSort = indexSortSupplier.get();
    final Engine.Warmer warmer = reader -> {
        assert Thread.holdsLock(mutex) == false : "warming engine under mutex";
        assert reader != null;
        if (this.warmer != null) {
            this.warmer.warm(reader);
        }
    };
    return this.engineConfigFactory.newEngineConfig(shardId, threadPool, indexSettings, warmer, store, indexSettings.getMergePolicy(), mapperService != null ? mapperService.indexAnalyzer() : null, similarityService.similarity(mapperService), engineConfigFactory.newCodecServiceOrDefault(indexSettings, mapperService, logger, codecService), shardEventListener, indexCache != null ? indexCache.query() : null, cachingPolicy, translogConfig, IndexingMemoryController.SHARD_INACTIVE_TIME_SETTING.get(indexSettings.getSettings()), Arrays.asList(refreshListeners, refreshPendingLocationListener), Collections.singletonList(new RefreshMetricUpdater(refreshMetric)), indexSort, circuitBreakerService, globalCheckpointSupplier, replicationTracker::getRetentionLeases, () -> getOperationPrimaryTerm(), tombstoneDocSupplier());
}
Also used : Query(org.apache.lucene.search.Query) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Arrays(java.util.Arrays) LongSupplier(java.util.function.LongSupplier) CheckedFunction(org.opensearch.common.CheckedFunction) SnapshotRecoverySource(org.opensearch.cluster.routing.RecoverySource.SnapshotRecoverySource) SearchStats(org.opensearch.index.search.stats.SearchStats) MetadataSnapshot(org.opensearch.index.store.Store.MetadataSnapshot) Term(org.apache.lucene.index.Term) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ReferenceManager(org.apache.lucene.search.ReferenceManager) DocumentMapperForType(org.opensearch.index.mapper.DocumentMapperForType) MergeStats(org.opensearch.index.merge.MergeStats) UsageTrackingQueryCachingPolicy(org.apache.lucene.search.UsageTrackingQueryCachingPolicy) WriteStateException(org.opensearch.gateway.WriteStateException) RecoveryState(org.opensearch.indices.recovery.RecoveryState) RefreshFailedEngineException(org.opensearch.index.engine.RefreshFailedEngineException) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) QueryCachingPolicy(org.apache.lucene.search.QueryCachingPolicy) ActionListener(org.opensearch.action.ActionListener) GetResult(org.opensearch.index.engine.Engine.GetResult) IndexModule(org.opensearch.index.IndexModule) Segment(org.opensearch.index.engine.Segment) EnumSet(java.util.EnumSet) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) ShardRequestCache(org.opensearch.index.cache.request.ShardRequestCache) Index(org.opensearch.index.Index) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ReplicationTracker(org.opensearch.index.seqno.ReplicationTracker) ShardBitsetFilterCache(org.opensearch.index.cache.bitset.ShardBitsetFilterCache) GetStats(org.opensearch.index.get.GetStats) StandardCharsets(java.nio.charset.StandardCharsets) Engine(org.opensearch.index.engine.Engine) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Logger(org.apache.logging.log4j.Logger) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) CheckedRunnable(org.opensearch.common.CheckedRunnable) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IndexCommit(org.apache.lucene.index.IndexCommit) ShardFieldData(org.opensearch.index.fielddata.ShardFieldData) RepositoriesService(org.opensearch.repositories.RepositoriesService) CodecService(org.opensearch.index.codec.CodecService) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) ThreadPool(org.opensearch.threadpool.ThreadPool) Releasable(org.opensearch.common.lease.Releasable) MeanMetric(org.opensearch.common.metrics.MeanMetric) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) FilterDirectoryReader(org.apache.lucene.index.FilterDirectoryReader) LegacyESVersion(org.opensearch.LegacyESVersion) Mapping(org.opensearch.index.mapper.Mapping) Booleans(org.opensearch.common.Booleans) BiConsumer(java.util.function.BiConsumer) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) RetentionLeaseStats(org.opensearch.index.seqno.RetentionLeaseStats) StreamSupport(java.util.stream.StreamSupport) CommitStats(org.opensearch.index.engine.CommitStats) EngineFactory(org.opensearch.index.engine.EngineFactory) CompletionStats(org.opensearch.search.suggest.completion.CompletionStats) SetOnce(org.apache.lucene.util.SetOnce) RecoveryFailedException(org.opensearch.indices.recovery.RecoveryFailedException) PendingReplicationActions(org.opensearch.action.support.replication.PendingReplicationActions) RETAIN_ALL(org.opensearch.index.seqno.RetentionLeaseActions.RETAIN_ALL) FlushStats(org.opensearch.index.flush.FlushStats) IOException(java.io.IOException) BytesStreamOutput(org.opensearch.common.io.stream.BytesStreamOutput) IndexService(org.opensearch.index.IndexService) XContentHelper(org.opensearch.common.xcontent.XContentHelper) AtomicLong(java.util.concurrent.atomic.AtomicLong) RecoveryStats(org.opensearch.index.recovery.RecoveryStats) RetentionLeases(org.opensearch.index.seqno.RetentionLeases) CounterMetric(org.opensearch.common.metrics.CounterMetric) ShardIndexWarmerService(org.opensearch.index.warmer.ShardIndexWarmerService) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) SafeCommitInfo(org.opensearch.index.engine.SafeCommitInfo) EngineException(org.opensearch.index.engine.EngineException) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine) IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) FieldDataStats(org.opensearch.index.fielddata.FieldDataStats) TimeoutException(java.util.concurrent.TimeoutException) OpenSearchException(org.opensearch.OpenSearchException) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) Releasables(org.opensearch.common.lease.Releasables) UpgradeRequest(org.opensearch.action.admin.indices.upgrade.post.UpgradeRequest) RunOnce(org.opensearch.common.util.concurrent.RunOnce) ForceMergeRequest(org.opensearch.action.admin.indices.forcemerge.ForceMergeRequest) MapperService(org.opensearch.index.mapper.MapperService) RefreshStats(org.opensearch.index.refresh.RefreshStats) Locale(java.util.Locale) Assertions(org.opensearch.Assertions) SegmentsStats(org.opensearch.index.engine.SegmentsStats) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) IndicesClusterStateService(org.opensearch.indices.cluster.IndicesClusterStateService) CheckIndex(org.apache.lucene.index.CheckIndex) Sort(org.apache.lucene.search.Sort) DirectoryReader(org.apache.lucene.index.DirectoryReader) IndicesService(org.opensearch.indices.IndicesService) TranslogConfig(org.opensearch.index.translog.TranslogConfig) IndexingMemoryController(org.opensearch.indices.IndexingMemoryController) RestStatus(org.opensearch.rest.RestStatus) Store(org.opensearch.index.store.Store) Collectors(java.util.stream.Collectors) SegmentInfos(org.apache.lucene.index.SegmentInfos) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) WarmerStats(org.opensearch.index.warmer.WarmerStats) Objects(java.util.Objects) List(java.util.List) ResyncTask(org.opensearch.index.shard.PrimaryReplicaSyncer.ResyncTask) LeafReader(org.apache.lucene.index.LeafReader) IndexSettings(org.opensearch.index.IndexSettings) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) Optional(java.util.Optional) BigArrays(org.opensearch.common.util.BigArrays) Uid(org.opensearch.index.mapper.Uid) TranslogStats(org.opensearch.index.translog.TranslogStats) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardSearchStats(org.opensearch.index.search.stats.ShardSearchStats) ActionRunnable(org.opensearch.action.ActionRunnable) SimilarityService(org.opensearch.index.similarity.SimilarityService) CheckedConsumer(org.opensearch.common.CheckedConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) EngineConfig(org.opensearch.index.engine.EngineConfig) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HashSet(java.util.HashSet) SourceToParse(org.opensearch.index.mapper.SourceToParse) AsyncIOProcessor(org.opensearch.common.util.concurrent.AsyncIOProcessor) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) Translog(org.opensearch.index.translog.Translog) StoreFileMetadata(org.opensearch.index.store.StoreFileMetadata) StoreStats(org.opensearch.index.store.StoreStats) RetentionLease(org.opensearch.index.seqno.RetentionLease) PrintStream(java.io.PrintStream) OpenSearchDirectoryReader(org.opensearch.common.lucene.index.OpenSearchDirectoryReader) RecoveryTarget(org.opensearch.indices.recovery.RecoveryTarget) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) IndexCache(org.opensearch.index.cache.IndexCache) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ShardGetService(org.opensearch.index.get.ShardGetService) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) Closeable(java.io.Closeable) TypeMissingException(org.opensearch.indices.TypeMissingException) Collections(java.util.Collections) Sort(org.apache.lucene.search.Sort) Engine(org.opensearch.index.engine.Engine) ReadOnlyEngine(org.opensearch.index.engine.ReadOnlyEngine)

Example 3 with IndexCache

use of org.opensearch.index.cache.IndexCache in project OpenSearch by opensearch-project.

the class IndexShardTestCase method newShard.

/**
 * creates a new initializing shard.
 * @param routing                       shard routing to use
 * @param shardPath                     path to use for shard data
 * @param indexMetadata                 indexMetadata for the shard, including any mapping
 * @param storeProvider                 an optional custom store provider to use. If null a default file based store will be created
 * @param indexReaderWrapper            an optional wrapper to be used during search
 * @param globalCheckpointSyncer        callback for syncing global checkpoints
 * @param indexEventListener            index event listener
 * @param listeners                     an optional set of listeners to add to the shard
 */
protected IndexShard newShard(ShardRouting routing, ShardPath shardPath, IndexMetadata indexMetadata, @Nullable CheckedFunction<IndexSettings, Store, IOException> storeProvider, @Nullable CheckedFunction<DirectoryReader, DirectoryReader, IOException> indexReaderWrapper, @Nullable EngineFactory engineFactory, @Nullable EngineConfigFactory engineConfigFactory, Runnable globalCheckpointSyncer, RetentionLeaseSyncer retentionLeaseSyncer, IndexEventListener indexEventListener, IndexingOperationListener... listeners) throws IOException {
    final Settings nodeSettings = Settings.builder().put("node.name", routing.currentNodeId()).build();
    final IndexSettings indexSettings = new IndexSettings(indexMetadata, nodeSettings);
    final IndexShard indexShard;
    if (storeProvider == null) {
        storeProvider = is -> createStore(is, shardPath);
    }
    final Store store = storeProvider.apply(indexSettings);
    boolean success = false;
    try {
        IndexCache indexCache = new IndexCache(indexSettings, new DisabledQueryCache(indexSettings), null);
        MapperService mapperService = MapperTestUtils.newMapperService(xContentRegistry(), createTempDir(), indexSettings.getSettings(), "index");
        mapperService.merge(indexMetadata, MapperService.MergeReason.MAPPING_RECOVERY);
        SimilarityService similarityService = new SimilarityService(indexSettings, null, Collections.emptyMap());
        final Engine.Warmer warmer = createTestWarmer(indexSettings);
        ClusterSettings clusterSettings = new ClusterSettings(nodeSettings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
        CircuitBreakerService breakerService = new HierarchyCircuitBreakerService(nodeSettings, Collections.emptyList(), clusterSettings);
        indexShard = new IndexShard(routing, indexSettings, shardPath, store, () -> null, indexCache, mapperService, similarityService, engineFactory, engineConfigFactory, indexEventListener, indexReaderWrapper, threadPool, BigArrays.NON_RECYCLING_INSTANCE, warmer, Collections.emptyList(), Arrays.asList(listeners), globalCheckpointSyncer, retentionLeaseSyncer, breakerService);
        indexShard.addShardFailureCallback(DEFAULT_SHARD_FAILURE_HANDLER);
        success = true;
    } finally {
        if (success == false) {
            IOUtils.close(store);
        }
    }
    return indexShard;
}
Also used : ClusterSettings(org.opensearch.common.settings.ClusterSettings) IndexSettings(org.opensearch.index.IndexSettings) Store(org.opensearch.index.store.Store) IndexCache(org.opensearch.index.cache.IndexCache) SimilarityService(org.opensearch.index.similarity.SimilarityService) HierarchyCircuitBreakerService(org.opensearch.indices.breaker.HierarchyCircuitBreakerService) HierarchyCircuitBreakerService(org.opensearch.indices.breaker.HierarchyCircuitBreakerService) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) ClusterSettings(org.opensearch.common.settings.ClusterSettings) DisabledQueryCache(org.opensearch.index.cache.query.DisabledQueryCache) MapperService(org.opensearch.index.mapper.MapperService) Engine(org.opensearch.index.engine.Engine)

Example 4 with IndexCache

use of org.opensearch.index.cache.IndexCache in project OpenSearch by opensearch-project.

the class DefaultSearchContextTests method testPreProcess.

public void testPreProcess() throws Exception {
    TimeValue timeout = new TimeValue(randomIntBetween(1, 100));
    ShardSearchRequest shardSearchRequest = mock(ShardSearchRequest.class);
    when(shardSearchRequest.searchType()).thenReturn(SearchType.DEFAULT);
    ShardId shardId = new ShardId("index", UUID.randomUUID().toString(), 1);
    when(shardSearchRequest.shardId()).thenReturn(shardId);
    ThreadPool threadPool = new TestThreadPool(this.getClass().getName());
    IndexShard indexShard = mock(IndexShard.class);
    QueryCachingPolicy queryCachingPolicy = mock(QueryCachingPolicy.class);
    when(indexShard.getQueryCachingPolicy()).thenReturn(queryCachingPolicy);
    when(indexShard.getThreadPool()).thenReturn(threadPool);
    int maxResultWindow = randomIntBetween(50, 100);
    int maxRescoreWindow = randomIntBetween(50, 100);
    int maxSlicesPerScroll = randomIntBetween(50, 100);
    Settings settings = Settings.builder().put("index.max_result_window", maxResultWindow).put("index.max_slices_per_scroll", maxSlicesPerScroll).put("index.max_rescore_window", maxRescoreWindow).put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 2).build();
    IndexService indexService = mock(IndexService.class);
    IndexCache indexCache = mock(IndexCache.class);
    QueryCache queryCache = mock(QueryCache.class);
    when(indexCache.query()).thenReturn(queryCache);
    when(indexService.cache()).thenReturn(indexCache);
    QueryShardContext queryShardContext = mock(QueryShardContext.class);
    when(indexService.newQueryShardContext(eq(shardId.id()), any(), any(), nullable(String.class))).thenReturn(queryShardContext);
    MapperService mapperService = mock(MapperService.class);
    when(mapperService.hasNested()).thenReturn(randomBoolean());
    when(indexService.mapperService()).thenReturn(mapperService);
    IndexMetadata indexMetadata = IndexMetadata.builder("index").settings(settings).build();
    IndexSettings indexSettings = new IndexSettings(indexMetadata, Settings.EMPTY);
    when(indexService.getIndexSettings()).thenReturn(indexSettings);
    when(mapperService.getIndexSettings()).thenReturn(indexSettings);
    BigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService());
    try (Directory dir = newDirectory();
        RandomIndexWriter w = new RandomIndexWriter(random(), dir)) {
        final Supplier<Engine.SearcherSupplier> searcherSupplier = () -> new Engine.SearcherSupplier(Function.identity()) {

            @Override
            protected void doClose() {
            }

            @Override
            protected Engine.Searcher acquireSearcherInternal(String source) {
                try {
                    IndexReader reader = w.getReader();
                    return new Engine.Searcher("test", reader, IndexSearcher.getDefaultSimilarity(), IndexSearcher.getDefaultQueryCache(), IndexSearcher.getDefaultQueryCachingPolicy(), reader);
                } catch (IOException exc) {
                    throw new AssertionError(exc);
                }
            }
        };
        SearchShardTarget target = new SearchShardTarget("node", shardId, null, OriginalIndices.NONE);
        ReaderContext readerWithoutScroll = new ReaderContext(newContextId(), indexService, indexShard, searcherSupplier.get(), randomNonNegativeLong(), false);
        DefaultSearchContext contextWithoutScroll = new DefaultSearchContext(readerWithoutScroll, shardSearchRequest, target, null, bigArrays, null, timeout, null, false, Version.CURRENT);
        contextWithoutScroll.from(300);
        contextWithoutScroll.close();
        // resultWindow greater than maxResultWindow and scrollContext is null
        IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> contextWithoutScroll.preProcess(false));
        assertThat(exception.getMessage(), equalTo("Result window is too large, from + size must be less than or equal to:" + " [" + maxResultWindow + "] but was [310]. See the scroll api for a more efficient way to request large data sets. " + "This limit can be set by changing the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey() + "] index level setting."));
        // resultWindow greater than maxResultWindow and scrollContext isn't null
        when(shardSearchRequest.scroll()).thenReturn(new Scroll(TimeValue.timeValueMillis(randomInt(1000))));
        ReaderContext readerContext = new LegacyReaderContext(newContextId(), indexService, indexShard, searcherSupplier.get(), shardSearchRequest, randomNonNegativeLong());
        DefaultSearchContext context1 = new DefaultSearchContext(readerContext, shardSearchRequest, target, null, bigArrays, null, timeout, null, false, Version.CURRENT);
        context1.from(300);
        exception = expectThrows(IllegalArgumentException.class, () -> context1.preProcess(false));
        assertThat(exception.getMessage(), equalTo("Batch size is too large, size must be less than or equal to: [" + maxResultWindow + "] but was [310]. Scroll batch sizes cost as much memory as result windows so they are " + "controlled by the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey() + "] index level setting."));
        // resultWindow not greater than maxResultWindow and both rescore and sort are not null
        context1.from(0);
        DocValueFormat docValueFormat = mock(DocValueFormat.class);
        SortAndFormats sortAndFormats = new SortAndFormats(new Sort(), new DocValueFormat[] { docValueFormat });
        context1.sort(sortAndFormats);
        RescoreContext rescoreContext = mock(RescoreContext.class);
        when(rescoreContext.getWindowSize()).thenReturn(500);
        context1.addRescore(rescoreContext);
        exception = expectThrows(IllegalArgumentException.class, () -> context1.preProcess(false));
        assertThat(exception.getMessage(), equalTo("Cannot use [sort] option in conjunction with [rescore]."));
        // rescore is null but sort is not null and rescoreContext.getWindowSize() exceeds maxResultWindow
        context1.sort(null);
        exception = expectThrows(IllegalArgumentException.class, () -> context1.preProcess(false));
        assertThat(exception.getMessage(), equalTo("Rescore window [" + rescoreContext.getWindowSize() + "] is too large. " + "It must be less than [" + maxRescoreWindow + "]. This prevents allocating massive heaps for storing the results " + "to be rescored. This limit can be set by changing the [" + IndexSettings.MAX_RESCORE_WINDOW_SETTING.getKey() + "] index level setting."));
        readerContext.close();
        readerContext = new ReaderContext(newContextId(), indexService, indexShard, searcherSupplier.get(), randomNonNegativeLong(), false);
        // rescore is null but sliceBuilder is not null
        DefaultSearchContext context2 = new DefaultSearchContext(readerContext, shardSearchRequest, target, null, bigArrays, null, timeout, null, false, Version.CURRENT);
        SliceBuilder sliceBuilder = mock(SliceBuilder.class);
        int numSlices = maxSlicesPerScroll + randomIntBetween(1, 100);
        when(sliceBuilder.getMax()).thenReturn(numSlices);
        context2.sliceBuilder(sliceBuilder);
        exception = expectThrows(IllegalArgumentException.class, () -> context2.preProcess(false));
        assertThat(exception.getMessage(), equalTo("The number of slices [" + numSlices + "] is too large. It must " + "be less than [" + maxSlicesPerScroll + "]. This limit can be set by changing the [" + IndexSettings.MAX_SLICES_PER_SCROLL.getKey() + "] index level setting."));
        // No exceptions should be thrown
        when(shardSearchRequest.getAliasFilter()).thenReturn(AliasFilter.EMPTY);
        when(shardSearchRequest.indexBoost()).thenReturn(AbstractQueryBuilder.DEFAULT_BOOST);
        DefaultSearchContext context3 = new DefaultSearchContext(readerContext, shardSearchRequest, target, null, bigArrays, null, timeout, null, false, Version.CURRENT);
        ParsedQuery parsedQuery = ParsedQuery.parsedMatchAllQuery();
        context3.sliceBuilder(null).parsedQuery(parsedQuery).preProcess(false);
        assertEquals(context3.query(), context3.buildFilteredQuery(parsedQuery.query()));
        when(queryShardContext.getIndexSettings()).thenReturn(indexSettings);
        when(queryShardContext.fieldMapper(anyString())).thenReturn(mock(MappedFieldType.class));
        when(shardSearchRequest.indexRoutings()).thenReturn(new String[0]);
        readerContext.close();
        readerContext = new ReaderContext(newContextId(), indexService, indexShard, searcherSupplier.get(), randomNonNegativeLong(), false);
        DefaultSearchContext context4 = new DefaultSearchContext(readerContext, shardSearchRequest, target, null, bigArrays, null, timeout, null, false, Version.CURRENT);
        context4.sliceBuilder(new SliceBuilder(1, 2)).parsedQuery(parsedQuery).preProcess(false);
        Query query1 = context4.query();
        context4.sliceBuilder(new SliceBuilder(0, 2)).parsedQuery(parsedQuery).preProcess(false);
        Query query2 = context4.query();
        assertTrue(query1 instanceof MatchNoDocsQuery || query2 instanceof MatchNoDocsQuery);
        readerContext.close();
        threadPool.shutdown();
    }
}
Also used : QueryCachingPolicy(org.apache.lucene.search.QueryCachingPolicy) QueryCache(org.opensearch.index.cache.query.QueryCache) RescoreContext(org.opensearch.search.rescore.RescoreContext) MockPageCacheRecycler(org.opensearch.common.util.MockPageCacheRecycler) Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) IndexService(org.opensearch.index.IndexService) ParsedQuery(org.opensearch.index.query.ParsedQuery) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) IndexSettings(org.opensearch.index.IndexSettings) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ThreadPool(org.opensearch.threadpool.ThreadPool) LegacyReaderContext(org.opensearch.search.internal.LegacyReaderContext) Mockito.anyString(org.mockito.Mockito.anyString) MockBigArrays(org.opensearch.common.util.MockBigArrays) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ShardId(org.opensearch.index.shard.ShardId) ReaderContext(org.opensearch.search.internal.ReaderContext) LegacyReaderContext(org.opensearch.search.internal.LegacyReaderContext) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) QueryShardContext(org.opensearch.index.query.QueryShardContext) Sort(org.apache.lucene.search.Sort) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) TimeValue(org.opensearch.common.unit.TimeValue) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) Engine(org.opensearch.index.engine.Engine) Directory(org.apache.lucene.store.Directory) IndexShard(org.opensearch.index.shard.IndexShard) IndexSearcher(org.apache.lucene.search.IndexSearcher) IOException(java.io.IOException) SortAndFormats(org.opensearch.search.sort.SortAndFormats) MockBigArrays(org.opensearch.common.util.MockBigArrays) BigArrays(org.opensearch.common.util.BigArrays) SliceBuilder(org.opensearch.search.slice.SliceBuilder) IndexCache(org.opensearch.index.cache.IndexCache) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) IndexReader(org.apache.lucene.index.IndexReader) MapperService(org.opensearch.index.mapper.MapperService) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

Settings (org.opensearch.common.settings.Settings)4 IndexCache (org.opensearch.index.cache.IndexCache)4 Engine (org.opensearch.index.engine.Engine)4 MapperService (org.opensearch.index.mapper.MapperService)4 IOException (java.io.IOException)3 Sort (org.apache.lucene.search.Sort)3 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)3 TimeValue (org.opensearch.common.unit.TimeValue)3 BigArrays (org.opensearch.common.util.BigArrays)3 IndexSettings (org.opensearch.index.IndexSettings)3 SimilarityService (org.opensearch.index.similarity.SimilarityService)3 Store (org.opensearch.index.store.Store)3 CircuitBreakerService (org.opensearch.indices.breaker.CircuitBreakerService)3 ThreadPool (org.opensearch.threadpool.ThreadPool)3 Closeable (java.io.Closeable)2 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2 Objects (java.util.Objects)2 Set (java.util.Set)2