Search in sources :

Example 46 with Tuple

use of org.opensearch.common.collect.Tuple in project OpenSearch by opensearch-project.

the class BlobStoreRepository method writeUpdatedShardMetaDataAndComputeDeletes.

// updates the shard state metadata for shards of a snapshot that is to be deleted. Also computes the files to be cleaned up.
private void writeUpdatedShardMetaDataAndComputeDeletes(Collection<SnapshotId> snapshotIds, RepositoryData oldRepositoryData, boolean useUUIDs, ActionListener<Collection<ShardSnapshotMetaDeleteResult>> onAllShardsCompleted) {
    final Executor executor = threadPool.executor(ThreadPool.Names.SNAPSHOT);
    final List<IndexId> indices = oldRepositoryData.indicesToUpdateAfterRemovingSnapshot(snapshotIds);
    if (indices.isEmpty()) {
        onAllShardsCompleted.onResponse(Collections.emptyList());
        return;
    }
    // Listener that flattens out the delete results for each index
    final ActionListener<Collection<ShardSnapshotMetaDeleteResult>> deleteIndexMetadataListener = new GroupedActionListener<>(ActionListener.map(onAllShardsCompleted, res -> res.stream().flatMap(Collection::stream).collect(Collectors.toList())), indices.size());
    for (IndexId indexId : indices) {
        final Set<SnapshotId> survivingSnapshots = oldRepositoryData.getSnapshots(indexId).stream().filter(id -> snapshotIds.contains(id) == false).collect(Collectors.toSet());
        final StepListener<Collection<Integer>> shardCountListener = new StepListener<>();
        final Collection<String> indexMetaGenerations = snapshotIds.stream().map(id -> oldRepositoryData.indexMetaDataGenerations().indexMetaBlobId(id, indexId)).collect(Collectors.toSet());
        final ActionListener<Integer> allShardCountsListener = new GroupedActionListener<>(shardCountListener, indexMetaGenerations.size());
        final BlobContainer indexContainer = indexContainer(indexId);
        for (String indexMetaGeneration : indexMetaGenerations) {
            executor.execute(ActionRunnable.supply(allShardCountsListener, () -> {
                try {
                    return INDEX_METADATA_FORMAT.read(indexContainer, indexMetaGeneration, namedXContentRegistry).getNumberOfShards();
                } catch (Exception ex) {
                    logger.warn(() -> new ParameterizedMessage("[{}] [{}] failed to read metadata for index", indexMetaGeneration, indexId.getName()), ex);
                    // ignoring it and letting the cleanup deal with it.
                    return null;
                }
            }));
        }
        shardCountListener.whenComplete(counts -> {
            final int shardCount = counts.stream().mapToInt(i -> i).max().orElse(0);
            if (shardCount == 0) {
                deleteIndexMetadataListener.onResponse(null);
                return;
            }
            // Listener for collecting the results of removing the snapshot from each shard's metadata in the current index
            final ActionListener<ShardSnapshotMetaDeleteResult> allShardsListener = new GroupedActionListener<>(deleteIndexMetadataListener, shardCount);
            for (int shardId = 0; shardId < shardCount; shardId++) {
                final int finalShardId = shardId;
                executor.execute(new AbstractRunnable() {

                    @Override
                    protected void doRun() throws Exception {
                        final BlobContainer shardContainer = shardContainer(indexId, finalShardId);
                        final Set<String> blobs = shardContainer.listBlobs().keySet();
                        final BlobStoreIndexShardSnapshots blobStoreIndexShardSnapshots;
                        final long newGen;
                        if (useUUIDs) {
                            newGen = -1L;
                            blobStoreIndexShardSnapshots = buildBlobStoreIndexShardSnapshots(blobs, shardContainer, oldRepositoryData.shardGenerations().getShardGen(indexId, finalShardId)).v1();
                        } else {
                            Tuple<BlobStoreIndexShardSnapshots, Long> tuple = buildBlobStoreIndexShardSnapshots(blobs, shardContainer);
                            newGen = tuple.v2() + 1;
                            blobStoreIndexShardSnapshots = tuple.v1();
                        }
                        allShardsListener.onResponse(deleteFromShardSnapshotMeta(survivingSnapshots, indexId, finalShardId, snapshotIds, shardContainer, blobs, blobStoreIndexShardSnapshots, newGen));
                    }

                    @Override
                    public void onFailure(Exception ex) {
                        logger.warn(() -> new ParameterizedMessage("{} failed to delete shard data for shard [{}][{}]", snapshotIds, indexId.getName(), finalShardId), ex);
                        // Just passing null here to count down the listener instead of failing it, the stale data left behind
                        // here will be retried in the next delete or repository cleanup
                        allShardsListener.onResponse(null);
                    }
                });
            }
        }, deleteIndexMetadataListener::onFailure);
    }
}
Also used : 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) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) Set(java.util.Set) BlobStoreIndexShardSnapshots(org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshots) Executor(java.util.concurrent.Executor) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) IndexId(org.opensearch.repositories.IndexId) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) SnapshotException(org.opensearch.snapshots.SnapshotException) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) NoSuchFileException(java.nio.file.NoSuchFileException) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) RepositoryException(org.opensearch.repositories.RepositoryException) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) SnapshotId(org.opensearch.snapshots.SnapshotId) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) BlobContainer(org.opensearch.common.blobstore.BlobContainer) Collection(java.util.Collection) StepListener(org.opensearch.action.StepListener) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Tuple(org.opensearch.common.collect.Tuple)

Example 47 with Tuple

use of org.opensearch.common.collect.Tuple in project OpenSearch by opensearch-project.

the class BlobStoreRepository method doGetRepositoryData.

private void doGetRepositoryData(ActionListener<RepositoryData> listener) {
    // Retry loading RepositoryData in a loop in case we run into concurrent modifications of the repository.
    // Keep track of the most recent generation we failed to load so we can break out of the loop if we fail to load the same
    // generation repeatedly.
    long lastFailedGeneration = RepositoryData.UNKNOWN_REPO_GEN;
    while (true) {
        final long genToLoad;
        if (bestEffortConsistency) {
            // We're only using #latestKnownRepoGen as a hint in this mode and listing repo contents as a secondary way of trying
            // to find a higher generation
            final long generation;
            try {
                generation = latestIndexBlobId();
            } catch (IOException ioe) {
                listener.onFailure(new RepositoryException(metadata.name(), "Could not determine repository generation from root blobs", ioe));
                return;
            }
            genToLoad = latestKnownRepoGen.updateAndGet(known -> Math.max(known, generation));
            if (genToLoad > generation) {
                logger.info("Determined repository generation [" + generation + "] from repository contents but correct generation must be at least [" + genToLoad + "]");
            }
        } else {
            // We only rely on the generation tracked in #latestKnownRepoGen which is exclusively updated from the cluster state
            genToLoad = latestKnownRepoGen.get();
        }
        try {
            final Tuple<Long, BytesReference> cached = latestKnownRepositoryData.get();
            final RepositoryData loaded;
            // Caching is not used with #bestEffortConsistency see docs on #cacheRepositoryData for details
            if (bestEffortConsistency == false && cached != null && cached.v1() == genToLoad) {
                loaded = repositoryDataFromCachedEntry(cached);
            } else {
                loaded = getRepositoryData(genToLoad);
                // We can cache serialized in the most recent version here without regard to the actual repository metadata version
                // since we're only caching the information that we just wrote and thus won't accidentally cache any information that
                // isn't safe
                cacheRepositoryData(BytesReference.bytes(loaded.snapshotsToXContent(XContentFactory.jsonBuilder(), Version.CURRENT)), genToLoad);
            }
            listener.onResponse(loaded);
            return;
        } catch (RepositoryException e) {
            // If the generation to load changed concurrently and we didn't just try loading the same generation before we retry
            if (genToLoad != latestKnownRepoGen.get() && genToLoad != lastFailedGeneration) {
                lastFailedGeneration = genToLoad;
                logger.warn("Failed to load repository data generation [" + genToLoad + "] because a concurrent operation moved the current generation to [" + latestKnownRepoGen.get() + "]", e);
                continue;
            }
            if (bestEffortConsistency == false && ExceptionsHelper.unwrap(e, NoSuchFileException.class) != null) {
                // We did not find the expected index-N even though the cluster state continues to point at the missing value
                // of N so we mark this repository as corrupted.
                markRepoCorrupted(genToLoad, e, ActionListener.wrap(v -> listener.onFailure(corruptedStateException(e)), listener::onFailure));
            } else {
                listener.onFailure(e);
            }
            return;
        } catch (Exception e) {
            listener.onFailure(new RepositoryException(metadata.name(), "Unexpected exception when loading repository data", e));
            return;
        }
    }
}
Also used : 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) BytesReference(org.opensearch.common.bytes.BytesReference) AtomicLong(java.util.concurrent.atomic.AtomicLong) NoSuchFileException(java.nio.file.NoSuchFileException) RepositoryException(org.opensearch.repositories.RepositoryException) IOException(java.io.IOException) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AbortedSnapshotException(org.opensearch.snapshots.AbortedSnapshotException) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) SnapshotException(org.opensearch.snapshots.SnapshotException) RepositoryVerificationException(org.opensearch.repositories.RepositoryVerificationException) IOException(java.io.IOException) IndexShardSnapshotFailedException(org.opensearch.index.snapshots.IndexShardSnapshotFailedException) NotXContentException(org.opensearch.common.compress.NotXContentException) NoSuchFileException(java.nio.file.NoSuchFileException) SnapshotCreationException(org.opensearch.snapshots.SnapshotCreationException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) RepositoryException(org.opensearch.repositories.RepositoryException) IndexShardRestoreFailedException(org.opensearch.index.snapshots.IndexShardRestoreFailedException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) RepositoryData(org.opensearch.repositories.RepositoryData)

Example 48 with Tuple

use of org.opensearch.common.collect.Tuple in project OpenSearch by opensearch-project.

the class BaseRestHandler method unrecognized.

protected final String unrecognized(final RestRequest request, final Set<String> invalids, final Set<String> candidates, final String detail) {
    StringBuilder message = new StringBuilder(String.format(Locale.ROOT, "request [%s] contains unrecognized %s%s: ", request.path(), detail, invalids.size() > 1 ? "s" : ""));
    boolean first = true;
    for (final String invalid : invalids) {
        final LevenshteinDistance ld = new LevenshteinDistance();
        final List<Tuple<Float, String>> scoredParams = new ArrayList<>();
        for (final String candidate : candidates) {
            final float distance = ld.getDistance(invalid, candidate);
            if (distance > 0.5f) {
                scoredParams.add(new Tuple<>(distance, candidate));
            }
        }
        CollectionUtil.timSort(scoredParams, (a, b) -> {
            // sort by distance in reverse order, then parameter name for equal distances
            int compare = a.v1().compareTo(b.v1());
            if (compare != 0)
                return -compare;
            else
                return a.v2().compareTo(b.v2());
        });
        if (first == false) {
            message.append(", ");
        }
        message.append("[").append(invalid).append("]");
        final List<String> keys = scoredParams.stream().map(Tuple::v2).collect(Collectors.toList());
        if (keys.isEmpty() == false) {
            message.append(" -> did you mean ");
            if (keys.size() == 1) {
                message.append("[").append(keys.get(0)).append("]");
            } else {
                message.append("any of ").append(keys.toString());
            }
            message.append("?");
        }
        first = false;
    }
    return message.toString();
}
Also used : ArrayList(java.util.ArrayList) LevenshteinDistance(org.apache.lucene.search.spell.LevenshteinDistance) Tuple(org.opensearch.common.collect.Tuple)

Example 49 with Tuple

use of org.opensearch.common.collect.Tuple in project OpenSearch by opensearch-project.

the class RestRequest method contentOrSourceParam.

/**
 * Get the content of the request or the contents of the {@code source} param or throw an exception if both are missing.
 * Prefer {@link #contentOrSourceParamParser()} or {@link #withContentOrSourceParamParserOrNull(CheckedConsumer)} if you need a parser.
 */
public final Tuple<XContentType, BytesReference> contentOrSourceParam() {
    if (hasContentOrSourceParam() == false) {
        throw new OpenSearchParseException("request body or source parameter is required");
    } else if (hasContent()) {
        return new Tuple<>(xContentType.get(), requiredContent());
    }
    String source = param("source");
    String typeParam = param("source_content_type");
    if (source == null || typeParam == null) {
        throw new IllegalStateException("source and source_content_type parameters are required");
    }
    BytesArray bytes = new BytesArray(source);
    final XContentType xContentType = parseContentType(Collections.singletonList(typeParam));
    if (xContentType == null) {
        throw new IllegalStateException("Unknown value for source_content_type [" + typeParam + "]");
    }
    return new Tuple<>(xContentType, bytes);
}
Also used : BytesArray(org.opensearch.common.bytes.BytesArray) XContentType(org.opensearch.common.xcontent.XContentType) OpenSearchParseException(org.opensearch.OpenSearchParseException) Tuple(org.opensearch.common.collect.Tuple)

Example 50 with Tuple

use of org.opensearch.common.collect.Tuple in project OpenSearch by opensearch-project.

the class DeleteResponseTests method doFromXContentTestWithRandomFields.

private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException {
    final Tuple<DeleteResponse, DeleteResponse> tuple = randomDeleteResponse();
    DeleteResponse deleteResponse = tuple.v1();
    DeleteResponse expectedDeleteResponse = tuple.v2();
    boolean humanReadable = randomBoolean();
    final XContentType xContentType = randomFrom(XContentType.values());
    BytesReference originalBytes = toShuffledXContent(deleteResponse, xContentType, ToXContent.EMPTY_PARAMS, humanReadable);
    BytesReference mutated;
    if (addRandomFields) {
        // The ShardInfo.Failure's exception is rendered out in a "reason" object. We shouldn't add anything random there
        // because exception rendering and parsing are very permissive: any extra object or field would be rendered as
        // a exception custom metadata and be parsed back as a custom header, making it impossible to compare the results
        // in this test.
        Predicate<String> excludeFilter = path -> path.contains("reason");
        mutated = insertRandomFields(xContentType, originalBytes, excludeFilter, random());
    } else {
        mutated = originalBytes;
    }
    DeleteResponse parsedDeleteResponse;
    try (XContentParser parser = createParser(xContentType.xContent(), mutated)) {
        parsedDeleteResponse = DeleteResponse.fromXContent(parser);
        assertNull(parser.nextToken());
    }
    // We can't use equals() to compare the original and the parsed delete response
    // because the random delete response can contain shard failures with exceptions,
    // and those exceptions are not parsed back with the same types.
    assertDocWriteResponse(expectedDeleteResponse, parsedDeleteResponse);
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) BytesReference(org.opensearch.common.bytes.BytesReference) XContentTestUtils.insertRandomFields(org.opensearch.test.XContentTestUtils.insertRandomFields) Predicate(java.util.function.Predicate) ToXContent(org.opensearch.common.xcontent.ToXContent) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) IOException(java.io.IOException) INDEX_UUID_NA_VALUE(org.opensearch.cluster.metadata.IndexMetadata.INDEX_UUID_NA_VALUE) Strings(org.opensearch.common.Strings) Tuple(org.opensearch.common.collect.Tuple) XContentParser(org.opensearch.common.xcontent.XContentParser) ShardId(org.opensearch.index.shard.ShardId) IndexResponseTests.assertDocWriteResponse(org.opensearch.action.index.IndexResponseTests.assertDocWriteResponse) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) XContentType(org.opensearch.common.xcontent.XContentType) RandomObjects(org.opensearch.test.RandomObjects) XContentType(org.opensearch.common.xcontent.XContentType) XContentParser(org.opensearch.common.xcontent.XContentParser)

Aggregations

Tuple (org.opensearch.common.collect.Tuple)151 ArrayList (java.util.ArrayList)65 List (java.util.List)49 IOException (java.io.IOException)45 Collections (java.util.Collections)44 HashMap (java.util.HashMap)40 Map (java.util.Map)40 Settings (org.opensearch.common.settings.Settings)38 ClusterState (org.opensearch.cluster.ClusterState)34 HashSet (java.util.HashSet)28 ShardId (org.opensearch.index.shard.ShardId)28 Arrays (java.util.Arrays)27 Collectors (java.util.stream.Collectors)26 Set (java.util.Set)25 Index (org.opensearch.index.Index)25 BytesReference (org.opensearch.common.bytes.BytesReference)24 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)24 CountDownLatch (java.util.concurrent.CountDownLatch)22 Version (org.opensearch.Version)21 Strings (org.opensearch.common.Strings)21