Search in sources :

Example 1 with BlobStore

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

the class BlobStoreFormatTests method testBlobStoreOperations.

public void testBlobStoreOperations() throws IOException {
    BlobStore blobStore = createTestBlobStore();
    BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
    ChecksumBlobStoreFormat<BlobObj> checksumSMILE = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent);
    // Write blobs in different formats
    checksumSMILE.write(new BlobObj("checksum smile"), blobContainer, "check-smile", false);
    checksumSMILE.write(new BlobObj("checksum smile compressed"), blobContainer, "check-smile-comp", true);
    // Assert that all checksum blobs can be read
    assertEquals(checksumSMILE.read(blobContainer, "check-smile", xContentRegistry()).getText(), "checksum smile");
    assertEquals(checksumSMILE.read(blobContainer, "check-smile-comp", xContentRegistry()).getText(), "checksum smile compressed");
}
Also used : ChecksumBlobStoreFormat(org.opensearch.repositories.blobstore.ChecksumBlobStoreFormat) BlobContainer(org.opensearch.common.blobstore.BlobContainer) FsBlobStore(org.opensearch.common.blobstore.fs.FsBlobStore) BlobStore(org.opensearch.common.blobstore.BlobStore)

Example 2 with BlobStore

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

the class BlobStoreFormatTests method testBlobCorruption.

public void testBlobCorruption() throws IOException {
    BlobStore blobStore = createTestBlobStore();
    BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
    String testString = randomAlphaOfLength(randomInt(10000));
    BlobObj blobObj = new BlobObj(testString);
    ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent);
    checksumFormat.write(blobObj, blobContainer, "test-path", randomBoolean());
    assertEquals(checksumFormat.read(blobContainer, "test-path", xContentRegistry()).getText(), testString);
    randomCorruption(blobContainer, "test-path");
    try {
        checksumFormat.read(blobContainer, "test-path", xContentRegistry());
        fail("Should have failed due to corruption");
    } catch (OpenSearchCorruptionException ex) {
        assertThat(ex.getMessage(), containsString("test-path"));
    } catch (EOFException ex) {
    // This can happen if corrupt the byte length
    }
}
Also used : ChecksumBlobStoreFormat(org.opensearch.repositories.blobstore.ChecksumBlobStoreFormat) OpenSearchCorruptionException(org.opensearch.OpenSearchCorruptionException) BlobContainer(org.opensearch.common.blobstore.BlobContainer) EOFException(java.io.EOFException) Matchers.containsString(org.hamcrest.Matchers.containsString) FsBlobStore(org.opensearch.common.blobstore.fs.FsBlobStore) BlobStore(org.opensearch.common.blobstore.BlobStore)

Example 3 with BlobStore

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

the class GoogleCloudStorageBlobStoreContainerTests method testDeleteBlobsIgnoringIfNotExistsThrowsIOException.

@SuppressWarnings("unchecked")
public void testDeleteBlobsIgnoringIfNotExistsThrowsIOException() throws Exception {
    final List<String> blobs = Arrays.asList("blobA", "blobB");
    final StorageBatch batch = mock(StorageBatch.class);
    if (randomBoolean()) {
        StorageBatchResult<Boolean> result = mock(StorageBatchResult.class);
        when(batch.delete(any(BlobId.class))).thenReturn(result);
        doThrow(new StorageException(new IOException("Batch submit throws a storage exception"))).when(batch).submit();
    } else {
        StorageBatchResult<Boolean> resultA = mock(StorageBatchResult.class);
        doReturn(resultA).when(batch).delete(eq(BlobId.of("bucket", "blobA")));
        doAnswer(invocation -> {
            StorageException storageException = new StorageException(new IOException("Batched delete throws a storage exception"));
            ((BatchResult.Callback) invocation.getArguments()[0]).error(storageException);
            return null;
        }).when(resultA).notify(any(StorageBatchResult.Callback.class));
        StorageBatchResult<Boolean> resultB = mock(StorageBatchResult.class);
        doReturn(resultB).when(batch).delete(eq(BlobId.of("bucket", "blobB")));
        doAnswer(invocation -> {
            if (randomBoolean()) {
                StorageException storageException = new StorageException(new IOException("Batched delete throws a storage exception"));
                ((BatchResult.Callback) invocation.getArguments()[0]).error(storageException);
            } else {
                ((BatchResult.Callback) invocation.getArguments()[0]).success(randomBoolean());
            }
            return null;
        }).when(resultB).notify(any(StorageBatchResult.Callback.class));
        doNothing().when(batch).submit();
    }
    final Storage storage = mock(Storage.class);
    when(storage.get("bucket")).thenReturn(mock(Bucket.class));
    when(storage.batch()).thenReturn(batch);
    final GoogleCloudStorageService storageService = mock(GoogleCloudStorageService.class);
    when(storageService.client(any(String.class), any(String.class), any(GoogleCloudStorageOperationsStats.class))).thenReturn(storage);
    try (BlobStore store = new GoogleCloudStorageBlobStore("bucket", "test", "repo", storageService, randomIntBetween(1, 8) * 1024)) {
        final BlobContainer container = store.blobContainer(new BlobPath());
        IOException e = expectThrows(IOException.class, () -> container.deleteBlobsIgnoringIfNotExists(blobs));
        assertThat(e.getCause(), instanceOf(StorageException.class));
    }
}
Also used : BlobPath(org.opensearch.common.blobstore.BlobPath) IOException(java.io.IOException) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) StorageBatch(com.google.cloud.storage.StorageBatch) BlobContainer(org.opensearch.common.blobstore.BlobContainer) BlobId(com.google.cloud.storage.BlobId) StorageException(com.google.cloud.storage.StorageException) BlobStore(org.opensearch.common.blobstore.BlobStore)

Example 4 with BlobStore

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

the class GoogleCloudStorageBlobStoreRepositoryTests method testWriteReadLarge.

public void testWriteReadLarge() throws IOException {
    try (BlobStore store = newBlobStore()) {
        final BlobContainer container = store.blobContainer(new BlobPath());
        byte[] data = randomBytes(GoogleCloudStorageBlobStore.LARGE_BLOB_THRESHOLD_BYTE_SIZE + 1);
        writeBlob(container, "foobar", new BytesArray(data), randomBoolean());
        if (randomBoolean()) {
            // override file, to check if we get latest contents
            random().nextBytes(data);
            writeBlob(container, "foobar", new BytesArray(data), false);
        }
        try (InputStream stream = container.readBlob("foobar")) {
            BytesRefBuilder target = new BytesRefBuilder();
            while (target.length() < data.length) {
                byte[] buffer = new byte[scaledRandomIntBetween(1, data.length - target.length())];
                int offset = scaledRandomIntBetween(0, buffer.length - 1);
                int read = stream.read(buffer, offset, buffer.length - offset);
                target.append(new BytesRef(buffer, offset, read));
            }
            assertEquals(data.length, target.length());
            assertArrayEquals(data, Arrays.copyOfRange(target.bytes(), 0, target.length()));
        }
        container.delete();
    }
}
Also used : BlobPath(org.opensearch.common.blobstore.BlobPath) BytesArray(org.opensearch.common.bytes.BytesArray) BytesRefBuilder(org.apache.lucene.util.BytesRefBuilder) InputStream(java.io.InputStream) BlobContainer(org.opensearch.common.blobstore.BlobContainer) BlobStore(org.opensearch.common.blobstore.BlobStore) BytesRef(org.apache.lucene.util.BytesRef)

Example 5 with BlobStore

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

the class BlobStoreRepository method cleanup.

/**
 * Runs cleanup actions on the repository. Increments the repository state id by one before executing any modifications on the
 * repository.
 * TODO: Add shard level cleanups
 * TODO: Add unreferenced index metadata cleanup
 * <ul>
 *     <li>Deleting stale indices {@link #cleanupStaleIndices}</li>
 *     <li>Deleting unreferenced root level blobs {@link #cleanupStaleRootFiles}</li>
 * </ul>
 * @param repositoryStateId     Current repository state id
 * @param repositoryMetaVersion version of the updated repository metadata to write
 * @param listener              Listener to complete when done
 */
public void cleanup(long repositoryStateId, Version repositoryMetaVersion, ActionListener<RepositoryCleanupResult> listener) {
    try {
        if (isReadOnly()) {
            throw new RepositoryException(metadata.name(), "cannot run cleanup on readonly repository");
        }
        Map<String, BlobMetadata> rootBlobs = blobContainer().listBlobs();
        final RepositoryData repositoryData = safeRepositoryData(repositoryStateId, rootBlobs);
        final Map<String, BlobContainer> foundIndices = blobStore().blobContainer(indicesPath()).children();
        final Set<String> survivingIndexIds = repositoryData.getIndices().values().stream().map(IndexId::getId).collect(Collectors.toSet());
        final List<String> staleRootBlobs = staleRootBlobs(repositoryData, rootBlobs.keySet());
        if (survivingIndexIds.equals(foundIndices.keySet()) && staleRootBlobs.isEmpty()) {
            // Nothing to clean up we return
            listener.onResponse(new RepositoryCleanupResult(DeleteResult.ZERO));
        } else {
            // write new index-N blob to ensure concurrent operations will fail
            writeIndexGen(repositoryData, repositoryStateId, repositoryMetaVersion, Function.identity(), ActionListener.wrap(v -> cleanupStaleBlobs(Collections.emptyList(), foundIndices, rootBlobs, repositoryData, ActionListener.map(listener, RepositoryCleanupResult::new)), listener::onFailure));
        }
    } catch (Exception e) {
        listener.onFailure(e);
    }
}
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) RepositoryCleanupResult(org.opensearch.repositories.RepositoryCleanupResult) BlobMetadata(org.opensearch.common.blobstore.BlobMetadata) FsBlobContainer(org.opensearch.common.blobstore.fs.FsBlobContainer) BlobContainer(org.opensearch.common.blobstore.BlobContainer) RepositoryException(org.opensearch.repositories.RepositoryException) 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)

Aggregations

BlobStore (org.opensearch.common.blobstore.BlobStore)15 BlobContainer (org.opensearch.common.blobstore.BlobContainer)12 BlobPath (org.opensearch.common.blobstore.BlobPath)8 BytesArray (org.opensearch.common.bytes.BytesArray)5 InputStream (java.io.InputStream)4 IOException (java.io.IOException)3 BytesRef (org.apache.lucene.util.BytesRef)3 BlobMetadata (org.opensearch.common.blobstore.BlobMetadata)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 NoSuchFileException (java.nio.file.NoSuchFileException)2 Map (java.util.Map)2 Executor (java.util.concurrent.Executor)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 CorruptIndexException (org.apache.lucene.index.CorruptIndexException)2 IndexFormatTooNewException (org.apache.lucene.index.IndexFormatTooNewException)2 IndexFormatTooOldException (org.apache.lucene.index.IndexFormatTooOldException)2 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)2 BytesRefBuilder (org.apache.lucene.util.BytesRefBuilder)2 FsBlobStore (org.opensearch.common.blobstore.fs.FsBlobStore)2 NotXContentException (org.opensearch.common.compress.NotXContentException)2