Search in sources :

Example 61 with Releasable

use of org.opensearch.common.lease.Releasable in project OpenSearch by opensearch-project.

the class Translog method rollGeneration.

/**
 * Roll the current translog generation into a new generation if it's not empty. This does not commit the translog.
 *
 * @throws IOException if an I/O exception occurred during any file operations
 */
public void rollGeneration() throws IOException {
    syncBeforeRollGeneration();
    if (current.totalOperations() == 0 && primaryTermSupplier.getAsLong() == current.getPrimaryTerm()) {
        return;
    }
    try (Releasable ignored = writeLock.acquire()) {
        ensureOpen();
        try {
            final TranslogReader reader = current.closeIntoReader();
            readers.add(reader);
            assert Checkpoint.read(location.resolve(CHECKPOINT_FILE_NAME)).generation == current.getGeneration();
            copyCheckpointTo(location.resolve(getCommitCheckpointFileName(current.getGeneration())));
            // create a new translog file; this will sync it and update the checkpoint data;
            current = createWriter(current.getGeneration() + 1);
            logger.trace("current translog set to [{}]", current.getGeneration());
        } catch (final Exception e) {
            tragedy.setTragicException(e);
            closeOnTragicEvent(e);
            throw e;
        }
    }
}
Also used : Releasable(org.opensearch.common.lease.Releasable) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) EOFException(java.io.EOFException) MissingHistoryOperationsException(org.opensearch.index.engine.MissingHistoryOperationsException) IOException(java.io.IOException)

Example 62 with Releasable

use of org.opensearch.common.lease.Releasable in project OpenSearch by opensearch-project.

the class BlobStoreRepository method executeOneFileSnapshot.

private void executeOneFileSnapshot(Store store, SnapshotId snapshotId, IndexId indexId, IndexShardSnapshotStatus snapshotStatus, BlockingQueue<BlobStoreIndexShardSnapshot.FileInfo> filesToSnapshot, Executor executor, ActionListener<Void> listener) throws InterruptedException {
    final ShardId shardId = store.shardId();
    final BlobStoreIndexShardSnapshot.FileInfo snapshotFileInfo = filesToSnapshot.poll(0L, TimeUnit.MILLISECONDS);
    if (snapshotFileInfo == null) {
        listener.onResponse(null);
    } else {
        executor.execute(ActionRunnable.wrap(listener, l -> {
            try (Releasable ignored = incrementStoreRef(store, snapshotStatus, shardId)) {
                snapshotFile(snapshotFileInfo, indexId, shardId, snapshotId, snapshotStatus, store);
                executeOneFileSnapshot(store, snapshotId, indexId, snapshotStatus, filesToSnapshot, executor, l);
            }
        }));
    }
}
Also used : RepositoryShardId(org.opensearch.repositories.RepositoryShardId) ShardId(org.opensearch.index.shard.ShardId) Metadata(org.opensearch.cluster.metadata.Metadata) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) ActionListener(org.opensearch.action.ActionListener) IOContext(org.apache.lucene.store.IOContext) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) BlobStoreIndexShardSnapshot(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot) BlockingQueue(java.util.concurrent.BlockingQueue) AbstractLifecycleComponent(org.opensearch.common.component.AbstractLifecycleComponent) Logger(org.apache.logging.log4j.Logger) RepositoryOperation(org.opensearch.repositories.RepositoryOperation) Stream(java.util.stream.Stream) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) BytesArray(org.opensearch.common.bytes.BytesArray) BlobStoreIndexShardSnapshots(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshots) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) StepListener(org.opensearch.action.StepListener) XContentType(org.opensearch.common.xcontent.XContentType) IndexCommit(org.apache.lucene.index.IndexCommit) ThreadPool(org.opensearch.threadpool.ThreadPool) BlobContainer(org.opensearch.common.blobstore.BlobContainer) Releasable(org.opensearch.common.lease.Releasable) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) Numbers(org.opensearch.common.Numbers) SlicedInputStream(org.opensearch.index.snapshots.blobstore.SlicedInputStream) SnapshotException(org.opensearch.snapshots.SnapshotException) Streams(org.opensearch.common.io.Streams) CompressorFactory(org.opensearch.common.compress.CompressorFactory) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) RepositoryCleanupInProgress(org.opensearch.cluster.RepositoryCleanupInProgress) InputStreamIndexInput(org.opensearch.common.lucene.store.InputStreamIndexInput) LongStream(java.util.stream.LongStream) IndexInput(org.apache.lucene.store.IndexInput) SetOnce(org.apache.lucene.util.SetOnce) RepositoriesMetadata(org.opensearch.cluster.metadata.RepositoriesMetadata) Executor(java.util.concurrent.Executor) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) RepositoryMetadata(org.opensearch.cluster.metadata.RepositoryMetadata) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) AtomicLong(java.util.concurrent.atomic.AtomicLong) RepositoryCleanupResult(org.opensearch.repositories.RepositoryCleanupResult) BlobPath(org.opensearch.common.blobstore.BlobPath) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) CounterMetric(org.opensearch.common.metrics.CounterMetric) ShardGenerations(org.opensearch.repositories.ShardGenerations) NoSuchFileException(java.nio.file.NoSuchFileException) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) SnapshotFiles(org.opensearch.index.snapshots.blobstore.SnapshotFiles) SnapshotsService(org.opensearch.snapshots.SnapshotsService) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) XContentParser(org.opensearch.common.xcontent.XContentParser) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) IndexId(org.opensearch.repositories.IndexId) XContentFactory(org.opensearch.common.xcontent.XContentFactory) RepositoryStats(org.opensearch.repositories.RepositoryStats) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) RepositoryException(org.opensearch.repositories.RepositoryException) FileInfo.canonicalName(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot.FileInfo.canonicalName) BytesRef(org.apache.lucene.util.BytesRef) SnapshotId(org.opensearch.snapshots.SnapshotId) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Store(org.opensearch.index.store.Store) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) BlobStore(org.opensearch.common.blobstore.BlobStore) List(java.util.List) Optional(java.util.Optional) BytesReference(org.opensearch.common.bytes.BytesReference) RateLimitingInputStream(org.opensearch.index.snapshots.blobstore.RateLimitingInputStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ActionRunnable(org.opensearch.action.ActionRunnable) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) SnapshotDeletionsInProgress(org.opensearch.cluster.SnapshotDeletionsInProgress) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) FilterInputStream(java.io.FilterInputStream) IndexShardSnapshotStatus(org.opensearch.index.snapshots.IndexShardSnapshotStatus) IndexMetaDataGenerations(org.opensearch.repositories.IndexMetaDataGenerations) UUIDs(org.opensearch.common.UUIDs) StoreFileMetadata(org.opensearch.index.store.StoreFileMetadata) IndexOutput(org.apache.lucene.store.IndexOutput) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) RepositoryData(org.opensearch.repositories.RepositoryData) Setting(org.opensearch.common.settings.Setting) RepositoryShardId(org.opensearch.repositories.RepositoryShardId) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) DeleteResult(org.opensearch.common.blobstore.DeleteResult) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) RateLimiter(org.apache.lucene.store.RateLimiter) InputStream(java.io.InputStream) BlobStoreIndexShardSnapshot(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot) Releasable(org.opensearch.common.lease.Releasable)

Example 63 with Releasable

use of org.opensearch.common.lease.Releasable in project OpenSearch by opensearch-project.

the class SearchService method executeQueryPhase.

private SearchPhaseResult executeQueryPhase(ShardSearchRequest request, SearchShardTask task, boolean keepStatesInContext) throws Exception {
    final ReaderContext readerContext = createOrGetReaderContext(request, keepStatesInContext);
    try (Releasable ignored = readerContext.markAsUsed(getKeepAlive(request));
        SearchContext context = createContext(readerContext, request, task, true)) {
        final long afterQueryTime;
        try (SearchOperationListenerExecutor executor = new SearchOperationListenerExecutor(context)) {
            loadOrExecuteQueryPhase(request, context);
            if (context.queryResult().hasSearchContext() == false && readerContext.singleSession()) {
                freeReaderContext(readerContext.id());
            }
            afterQueryTime = executor.success();
        }
        if (request.numberOfShards() == 1) {
            return executeFetchPhase(readerContext, context, afterQueryTime);
        } else {
            // Pass the rescoreDocIds to the queryResult to send them the coordinating node and receive them back in the fetch phase.
            // We also pass the rescoreDocIds to the LegacyReaderContext in case the search state needs to stay in the data node.
            final RescoreDocIds rescoreDocIds = context.rescoreDocIds();
            context.queryResult().setRescoreDocIds(rescoreDocIds);
            readerContext.setRescoreDocIds(rescoreDocIds);
            return context.queryResult();
        }
    } catch (Exception e) {
        // execution exception can happen while loading the cache, strip it
        if (e instanceof ExecutionException) {
            e = (e.getCause() == null || e.getCause() instanceof Exception) ? (Exception) e.getCause() : new OpenSearchException(e.getCause());
        }
        logger.trace("Query phase failed", e);
        processFailure(readerContext, e);
        throw e;
    }
}
Also used : LegacyReaderContext(org.opensearch.search.internal.LegacyReaderContext) ReaderContext(org.opensearch.search.internal.ReaderContext) SearchContext(org.opensearch.search.internal.SearchContext) Releasable(org.opensearch.common.lease.Releasable) OpenSearchException(org.opensearch.OpenSearchException) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) AggregationInitializationException(org.opensearch.search.aggregations.AggregationInitializationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) OpenSearchException(org.opensearch.OpenSearchException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException)

Example 64 with Releasable

use of org.opensearch.common.lease.Releasable in project OpenSearch by opensearch-project.

the class SearchService method executeQueryPhase.

public void executeQueryPhase(QuerySearchRequest request, SearchShardTask task, ActionListener<QuerySearchResult> listener) {
    final ReaderContext readerContext = findReaderContext(request.contextId(), request.shardSearchRequest());
    final ShardSearchRequest shardSearchRequest = readerContext.getShardSearchRequest(request.shardSearchRequest());
    final Releasable markAsUsed = readerContext.markAsUsed(getKeepAlive(shardSearchRequest));
    runAsync(getExecutor(readerContext.indexShard()), () -> {
        readerContext.setAggregatedDfs(request.dfs());
        try (SearchContext searchContext = createContext(readerContext, shardSearchRequest, task, true);
            SearchOperationListenerExecutor executor = new SearchOperationListenerExecutor(searchContext)) {
            searchContext.searcher().setAggregatedDfs(request.dfs());
            queryPhase.execute(searchContext);
            if (searchContext.queryResult().hasSearchContext() == false && readerContext.singleSession()) {
                // no hits, we can release the context since there will be no fetch phase
                freeReaderContext(readerContext.id());
            }
            executor.success();
            // Pass the rescoreDocIds to the queryResult to send them the coordinating node and receive them back in the fetch phase.
            // We also pass the rescoreDocIds to the LegacyReaderContext in case the search state needs to stay in the data node.
            final RescoreDocIds rescoreDocIds = searchContext.rescoreDocIds();
            searchContext.queryResult().setRescoreDocIds(rescoreDocIds);
            readerContext.setRescoreDocIds(rescoreDocIds);
            return searchContext.queryResult();
        } catch (Exception e) {
            assert TransportActions.isShardNotAvailableException(e) == false : new AssertionError(e);
            logger.trace("Query phase failed", e);
            // we handle the failure in the failure listener below
            throw e;
        }
    }, wrapFailureListener(listener, readerContext, markAsUsed));
}
Also used : LegacyReaderContext(org.opensearch.search.internal.LegacyReaderContext) ReaderContext(org.opensearch.search.internal.ReaderContext) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) SearchContext(org.opensearch.search.internal.SearchContext) Releasable(org.opensearch.common.lease.Releasable) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) AggregationInitializationException(org.opensearch.search.aggregations.AggregationInitializationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) OpenSearchException(org.opensearch.OpenSearchException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException)

Example 65 with Releasable

use of org.opensearch.common.lease.Releasable in project OpenSearch by opensearch-project.

the class SearchService method executeFetchPhase.

public void executeFetchPhase(InternalScrollSearchRequest request, SearchShardTask task, ActionListener<ScrollQueryFetchSearchResult> listener) {
    final LegacyReaderContext readerContext = (LegacyReaderContext) findReaderContext(request.contextId(), request);
    final Releasable markAsUsed;
    try {
        markAsUsed = readerContext.markAsUsed(getScrollKeepAlive(request.scroll()));
    } catch (Exception e) {
        // We need to release the reader context of the scroll when we hit any exception (here the keep_alive can be too large)
        freeReaderContext(readerContext.id());
        throw e;
    }
    runAsync(getExecutor(readerContext.indexShard()), () -> {
        final ShardSearchRequest shardSearchRequest = readerContext.getShardSearchRequest(null);
        try (SearchContext searchContext = createContext(readerContext, shardSearchRequest, task, false);
            SearchOperationListenerExecutor executor = new SearchOperationListenerExecutor(searchContext)) {
            searchContext.assignRescoreDocIds(readerContext.getRescoreDocIds(null));
            searchContext.searcher().setAggregatedDfs(readerContext.getAggregatedDfs(null));
            processScroll(request, readerContext, searchContext);
            queryPhase.execute(searchContext);
            final long afterQueryTime = executor.success();
            QueryFetchSearchResult fetchSearchResult = executeFetchPhase(readerContext, searchContext, afterQueryTime);
            return new ScrollQueryFetchSearchResult(fetchSearchResult, searchContext.shardTarget());
        } catch (Exception e) {
            assert TransportActions.isShardNotAvailableException(e) == false : new AssertionError(e);
            logger.trace("Fetch phase failed", e);
            // we handle the failure in the failure listener below
            throw e;
        }
    }, wrapFailureListener(listener, readerContext, markAsUsed));
}
Also used : ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) ScrollQueryFetchSearchResult(org.opensearch.search.fetch.ScrollQueryFetchSearchResult) QueryFetchSearchResult(org.opensearch.search.fetch.QueryFetchSearchResult) LegacyReaderContext(org.opensearch.search.internal.LegacyReaderContext) SearchContext(org.opensearch.search.internal.SearchContext) Releasable(org.opensearch.common.lease.Releasable) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) AggregationInitializationException(org.opensearch.search.aggregations.AggregationInitializationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) OpenSearchException(org.opensearch.OpenSearchException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ScrollQueryFetchSearchResult(org.opensearch.search.fetch.ScrollQueryFetchSearchResult)

Aggregations

Releasable (org.opensearch.common.lease.Releasable)161 ShardId (org.opensearch.index.shard.ShardId)50 IOException (java.io.IOException)45 CountDownLatch (java.util.concurrent.CountDownLatch)36 Settings (org.opensearch.common.settings.Settings)35 IndexingPressurePerShardStats (org.opensearch.index.stats.IndexingPressurePerShardStats)32 ExecutionException (java.util.concurrent.ExecutionException)30 ArrayList (java.util.ArrayList)28 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)28 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)27 OpenSearchException (org.opensearch.OpenSearchException)25 ThreadPool (org.opensearch.threadpool.ThreadPool)25 PlainActionFuture (org.opensearch.action.support.PlainActionFuture)24 ActionListener (org.opensearch.action.ActionListener)23 IndexRequest (org.opensearch.action.index.IndexRequest)22 ShardRouting (org.opensearch.cluster.routing.ShardRouting)22 IndexingPressureStats (org.opensearch.index.stats.IndexingPressureStats)22 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)21 List (java.util.List)20 Translog (org.opensearch.index.translog.Translog)19