Search in sources :

Example 1 with BlobMetadata

use of org.opensearch.common.blobstore.BlobMetadata in project OpenSearch by opensearch-project.

the class HdfsBlobContainer method listBlobsByPrefix.

@Override
public Map<String, BlobMetadata> listBlobsByPrefix(@Nullable final String prefix) throws IOException {
    FileStatus[] files = store.execute(fileContext -> fileContext.util().listStatus(path, path -> prefix == null || path.getName().startsWith(prefix)));
    Map<String, BlobMetadata> map = new LinkedHashMap<>();
    for (FileStatus file : files) {
        if (file.isFile()) {
            map.put(file.getPath().getName(), new PlainBlobMetadata(file.getPath().getName(), file.getLen()));
        }
    }
    return Collections.unmodifiableMap(map);
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Operation(org.opensearch.repositories.hdfs.HdfsBlobStore.Operation) BlobContainer(org.opensearch.common.blobstore.BlobContainer) FileStatus(org.apache.hadoop.fs.FileStatus) LinkedHashMap(java.util.LinkedHashMap) FSDataOutputStream(org.apache.hadoop.fs.FSDataOutputStream) Options(org.apache.hadoop.fs.Options) FilterInputStream(java.io.FilterInputStream) FileContext(org.apache.hadoop.fs.FileContext) Map(java.util.Map) Path(org.apache.hadoop.fs.Path) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) CreateFlag(org.apache.hadoop.fs.CreateFlag) EnumSet(java.util.EnumSet) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) Nullable(org.opensearch.common.Nullable) FileNotFoundException(java.io.FileNotFoundException) CreateOpts(org.apache.hadoop.fs.Options.CreateOpts) List(java.util.List) DeleteResult(org.opensearch.common.blobstore.DeleteResult) BlobPath(org.opensearch.common.blobstore.BlobPath) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) AbstractBlobContainer(org.opensearch.common.blobstore.support.AbstractBlobContainer) Collections(java.util.Collections) InputStream(java.io.InputStream) FileStatus(org.apache.hadoop.fs.FileStatus) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with BlobMetadata

use of org.opensearch.common.blobstore.BlobMetadata in project OpenSearch by opensearch-project.

the class BlobStoreRepository method cleanupStaleBlobs.

/**
 * Cleans up stale blobs directly under the repository root as well as all indices paths that aren't referenced by any existing
 * snapshots. This method is only to be called directly after a new {@link RepositoryData} was written to the repository and with
 * parameters {@code foundIndices}, {@code rootBlobs}
 *
 * @param deletedSnapshots if this method is called as part of a delete operation, the snapshot ids just deleted or empty if called as
 *                         part of a repository cleanup
 * @param foundIndices     all indices blob containers found in the repository before {@code newRepoData} was written
 * @param rootBlobs        all blobs found directly under the repository root
 * @param newRepoData      new repository data that was just written
 * @param listener         listener to invoke with the combined {@link DeleteResult} of all blobs removed in this operation
 */
private void cleanupStaleBlobs(Collection<SnapshotId> deletedSnapshots, Map<String, BlobContainer> foundIndices, Map<String, BlobMetadata> rootBlobs, RepositoryData newRepoData, ActionListener<DeleteResult> listener) {
    final GroupedActionListener<DeleteResult> groupedListener = new GroupedActionListener<>(ActionListener.wrap(deleteResults -> {
        DeleteResult deleteResult = DeleteResult.ZERO;
        for (DeleteResult result : deleteResults) {
            deleteResult = deleteResult.add(result);
        }
        listener.onResponse(deleteResult);
    }, listener::onFailure), 2);
    final Executor executor = threadPool.executor(ThreadPool.Names.SNAPSHOT);
    final List<String> staleRootBlobs = staleRootBlobs(newRepoData, rootBlobs.keySet());
    if (staleRootBlobs.isEmpty()) {
        groupedListener.onResponse(DeleteResult.ZERO);
    } else {
        executor.execute(ActionRunnable.supply(groupedListener, () -> {
            List<String> deletedBlobs = cleanupStaleRootFiles(newRepoData.getGenId() - 1, deletedSnapshots, staleRootBlobs);
            return new DeleteResult(deletedBlobs.size(), deletedBlobs.stream().mapToLong(name -> rootBlobs.get(name).length()).sum());
        }));
    }
    final Set<String> survivingIndexIds = newRepoData.getIndices().values().stream().map(IndexId::getId).collect(Collectors.toSet());
    if (foundIndices.keySet().equals(survivingIndexIds)) {
        groupedListener.onResponse(DeleteResult.ZERO);
    } else {
        cleanupStaleIndices(foundIndices, survivingIndexIds, groupedListener);
    }
}
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) Executor(java.util.concurrent.Executor) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) ArrayList(java.util.ArrayList) List(java.util.List) DeleteResult(org.opensearch.common.blobstore.DeleteResult)

Example 3 with BlobMetadata

use of org.opensearch.common.blobstore.BlobMetadata in project OpenSearch by opensearch-project.

the class BlobStoreTestUtil method assertSnapshotUUIDs.

private static void assertSnapshotUUIDs(BlobStoreRepository repository, RepositoryData repositoryData) throws IOException {
    final BlobContainer repoRoot = repository.blobContainer();
    final Collection<SnapshotId> snapshotIds = repositoryData.getSnapshotIds();
    final List<String> expectedSnapshotUUIDs = snapshotIds.stream().map(SnapshotId::getUUID).collect(Collectors.toList());
    for (String prefix : new String[] { BlobStoreRepository.SNAPSHOT_PREFIX, BlobStoreRepository.METADATA_PREFIX }) {
        final Collection<String> foundSnapshotUUIDs = repoRoot.listBlobs().keySet().stream().filter(p -> p.startsWith(prefix)).map(p -> p.replace(prefix, "").replace(".dat", "")).collect(Collectors.toSet());
        assertThat(foundSnapshotUUIDs, containsInAnyOrder(expectedSnapshotUUIDs.toArray(Strings.EMPTY_ARRAY)));
    }
    final BlobContainer indicesContainer = repository.getBlobContainer().children().get("indices");
    final Map<String, BlobContainer> indices;
    if (indicesContainer == null) {
        indices = Collections.emptyMap();
    } else {
        indices = indicesContainer.children();
    }
    final Map<IndexId, Integer> maxShardCountsExpected = new HashMap<>();
    final Map<IndexId, Integer> maxShardCountsSeen = new HashMap<>();
    // Assert that for each snapshot, the relevant metadata was written to index and shard folders
    for (SnapshotId snapshotId : snapshotIds) {
        final SnapshotInfo snapshotInfo = repository.getSnapshotInfo(snapshotId);
        for (String index : snapshotInfo.indices()) {
            final IndexId indexId = repositoryData.resolveIndexId(index);
            assertThat(indices, hasKey(indexId.getId()));
            final BlobContainer indexContainer = indices.get(indexId.getId());
            assertThat(indexContainer.listBlobs(), hasKey(String.format(Locale.ROOT, BlobStoreRepository.METADATA_NAME_FORMAT, repositoryData.indexMetaDataGenerations().indexMetaBlobId(snapshotId, indexId))));
            final IndexMetadata indexMetadata = repository.getSnapshotIndexMetaData(repositoryData, snapshotId, indexId);
            for (Map.Entry<String, BlobContainer> entry : indexContainer.children().entrySet()) {
                // Skip Lucene MockFS extraN directory
                if (entry.getKey().startsWith("extra")) {
                    continue;
                }
                final int shardId = Integer.parseInt(entry.getKey());
                final int shardCount = indexMetadata.getNumberOfShards();
                maxShardCountsExpected.compute(indexId, (i, existing) -> existing == null || existing < shardCount ? shardCount : existing);
                final BlobContainer shardContainer = entry.getValue();
                // becomes unreferenced. We should fix that and remove this conditional once its fixed.
                if (shardContainer.listBlobs().keySet().stream().anyMatch(blob -> blob.startsWith("extra") == false)) {
                    final int impliedCount = shardId - 1;
                    maxShardCountsSeen.compute(indexId, (i, existing) -> existing == null || existing < impliedCount ? impliedCount : existing);
                }
                if (shardId < shardCount && snapshotInfo.shardFailures().stream().noneMatch(shardFailure -> shardFailure.index().equals(index) && shardFailure.shardId() == shardId)) {
                    final Map<String, BlobMetadata> shardPathContents = shardContainer.listBlobs();
                    assertThat(shardPathContents, hasKey(String.format(Locale.ROOT, BlobStoreRepository.SNAPSHOT_NAME_FORMAT, snapshotId.getUUID())));
                    assertThat(shardPathContents.keySet().stream().filter(name -> name.startsWith(BlobStoreRepository.INDEX_FILE_PREFIX)).count(), lessThanOrEqualTo(2L));
                }
            }
        }
    }
    maxShardCountsSeen.forEach(((indexId, count) -> assertThat("Found unreferenced shard paths for index [" + indexId + "]", count, lessThanOrEqualTo(maxShardCountsExpected.get(indexId)))));
}
Also used : ShardGenerations(org.opensearch.repositories.ShardGenerations) NoSuchFileException(java.nio.file.NoSuchFileException) OpenSearchTestCase.buildNewFakeTransportAddress(org.opensearch.test.OpenSearchTestCase.buildNewFakeTransportAddress) Metadata(org.opensearch.cluster.metadata.Metadata) Matchers.not(org.hamcrest.Matchers.not) Version(org.opensearch.Version) ClusterStateApplier(org.opensearch.cluster.ClusterStateApplier) Matchers.hasKey(org.hamcrest.Matchers.hasKey) Strings(org.opensearch.common.Strings) XContentParser(org.opensearch.common.xcontent.XContentParser) Assert.assertThat(org.junit.Assert.assertThat) ClusterApplierService(org.opensearch.cluster.service.ClusterApplierService) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IndexId(org.opensearch.repositories.IndexId) ByteArrayInputStream(java.io.ByteArrayInputStream) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Locale(java.util.Locale) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) OpenSearchTestCase.randomIntBetween(org.opensearch.test.OpenSearchTestCase.randomIntBetween) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) TimeValue(org.opensearch.common.unit.TimeValue) SnapshotId(org.opensearch.snapshots.SnapshotId) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) Collectors(java.util.stream.Collectors) BlobStore(org.opensearch.common.blobstore.BlobStore) List(java.util.List) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) XContentType(org.opensearch.common.xcontent.XContentType) Mockito.any(org.mockito.Mockito.any) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Mockito.mock(org.mockito.Mockito.mock) RepositoriesService(org.opensearch.repositories.RepositoriesService) DataInputStream(java.io.DataInputStream) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ActionRunnable(org.opensearch.action.ActionRunnable) ThreadPool(org.opensearch.threadpool.ThreadPool) BlobContainer(org.opensearch.common.blobstore.BlobContainer) HashMap(java.util.HashMap) InternalTestCluster(org.opensearch.test.InternalTestCluster) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) Mockito.anyString(org.mockito.Mockito.anyString) RepositoryData(org.opensearch.repositories.RepositoryData) Matchers.empty(org.hamcrest.Matchers.empty) RepositoriesMetadata(org.opensearch.cluster.metadata.RepositoriesMetadata) Executor(java.util.concurrent.Executor) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) RepositoryMetadata(org.opensearch.cluster.metadata.RepositoryMetadata) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) BlobPath(org.opensearch.common.blobstore.BlobPath) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) SameThreadExecutorService(org.apache.lucene.util.SameThreadExecutorService) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) InputStream(java.io.InputStream) IndexId(org.opensearch.repositories.IndexId) HashMap(java.util.HashMap) Mockito.anyString(org.mockito.Mockito.anyString) SnapshotId(org.opensearch.snapshots.SnapshotId) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) BlobContainer(org.opensearch.common.blobstore.BlobContainer) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with BlobMetadata

use of org.opensearch.common.blobstore.BlobMetadata in project OpenSearch by opensearch-project.

the class AzureBlobStore method listBlobsByPrefix.

public Map<String, BlobMetadata> listBlobsByPrefix(String keyPath, String prefix) throws URISyntaxException, BlobStorageException {
    final Map<String, BlobMetadata> blobsBuilder = new HashMap<String, BlobMetadata>();
    final Tuple<BlobServiceClient, Supplier<Context>> client = client();
    final BlobContainerClient blobContainer = client.v1().getBlobContainerClient(container);
    logger.trace(() -> new ParameterizedMessage("listing container [{}], keyPath [{}], prefix [{}]", container, keyPath, prefix));
    // NOTE: this should be here: if (prefix == null) prefix = "";
    // however, this is really inefficient since deleteBlobsByPrefix enumerates everything and
    // then does a prefix match on the result; it should just call listBlobsByPrefix with the prefix!
    final ListBlobsOptions listBlobsOptions = new ListBlobsOptions().setDetails(new BlobListDetails().setRetrieveMetadata(true)).setPrefix(keyPath + (prefix == null ? "" : prefix));
    SocketAccess.doPrivilegedVoidException(() -> {
        String continuationToken = null;
        do {
            // Fetch one page at a time, others are going to be fetched by continuation token
            // TODO: reconsider reverting to simplified approach once https://github.com/Azure/azure-sdk-for-java/issues/26064
            // gets addressed
            final Optional<PagedResponse<BlobItem>> pageOpt = blobContainer.listBlobsByHierarchy("/", listBlobsOptions, timeout()).streamByPage(continuationToken).findFirst();
            if (!pageOpt.isPresent()) {
                // No more pages, should never happen
                break;
            }
            final PagedResponse<BlobItem> page = pageOpt.get();
            for (final BlobItem blobItem : page.getValue()) {
                // Skipping over the prefixes, only look for the blobs
                if (blobItem.isPrefix() != null && blobItem.isPrefix()) {
                    continue;
                }
                final String name = getBlobName(blobItem.getName(), container, keyPath);
                logger.trace(() -> new ParameterizedMessage("blob name [{}]", name));
                final BlobItemProperties properties = blobItem.getProperties();
                logger.trace(() -> new ParameterizedMessage("blob name [{}], size [{}]", name, properties.getContentLength()));
                blobsBuilder.put(name, new PlainBlobMetadata(name, properties.getContentLength()));
            }
            // Fetch next continuation token
            continuationToken = page.getContinuationToken();
        } while (StringUtils.isNotBlank(continuationToken));
    });
    return MapBuilder.newMapBuilder(blobsBuilder).immutableMap();
}
Also used : ListBlobsOptions(com.azure.storage.blob.models.ListBlobsOptions) HashMap(java.util.HashMap) BlobListDetails(com.azure.storage.blob.models.BlobListDetails) BlobItem(com.azure.storage.blob.models.BlobItem) BlobContainerClient(com.azure.storage.blob.BlobContainerClient) BlobItemProperties(com.azure.storage.blob.models.BlobItemProperties) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) BlobServiceClient(com.azure.storage.blob.BlobServiceClient) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) Supplier(java.util.function.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) PagedResponse(com.azure.core.http.rest.PagedResponse)

Example 5 with BlobMetadata

use of org.opensearch.common.blobstore.BlobMetadata in project OpenSearch by opensearch-project.

the class FsBlobContainer method listBlobsByPrefix.

@Override
public Map<String, BlobMetadata> listBlobsByPrefix(String blobNamePrefix) throws IOException {
    Map<String, BlobMetadata> builder = new HashMap<>();
    blobNamePrefix = blobNamePrefix == null ? "" : blobNamePrefix;
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, blobNamePrefix + "*")) {
        for (Path file : stream) {
            final BasicFileAttributes attrs;
            try {
                attrs = Files.readAttributes(file, BasicFileAttributes.class);
            } catch (FileNotFoundException | NoSuchFileException e) {
                // The file was concurrently deleted between listing files and trying to get its attributes so we skip it here
                continue;
            }
            if (attrs.isRegularFile()) {
                builder.put(file.getFileName().toString(), new PlainBlobMetadata(file.getFileName().toString(), attrs.size()));
            }
        }
    }
    return unmodifiableMap(builder);
}
Also used : Path(java.nio.file.Path) BlobPath(org.opensearch.common.blobstore.BlobPath) HashMap(java.util.HashMap) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) PlainBlobMetadata(org.opensearch.common.blobstore.support.PlainBlobMetadata) FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

BlobMetadata (org.opensearch.common.blobstore.BlobMetadata)9 BlobContainer (org.opensearch.common.blobstore.BlobContainer)7 BlobPath (org.opensearch.common.blobstore.BlobPath)7 NoSuchFileException (java.nio.file.NoSuchFileException)6 Map (java.util.Map)6 BlobStore (org.opensearch.common.blobstore.BlobStore)6 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 Collections (java.util.Collections)5 List (java.util.List)5 FilterInputStream (java.io.FilterInputStream)4 Collection (java.util.Collection)4 Set (java.util.Set)4 Executor (java.util.concurrent.Executor)4 AtomicLong (java.util.concurrent.atomic.AtomicLong)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Collectors (java.util.stream.Collectors)4 HashMap (java.util.HashMap)3 Supplier (java.util.function.Supplier)3 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)3