Search in sources :

Example 21 with SegmentHandle

use of io.pravega.segmentstore.storage.SegmentHandle in project pravega by pravega.

the class NoOpStorageUserDataWriteOnlyTests method testSeal.

@Override
@Test
public void testSeal() throws Exception {
    final String segmentName = "sealSegment";
    try (Storage s = createStorage()) {
        s.initialize(DEFAULT_EPOCH);
        SegmentHandle handle = s.openWrite(segmentName).join();
        assertEquals(segmentName, handle.getSegmentName());
        assertEquals(false, handle.isReadOnly());
        s.seal(handle, TIMEOUT).join();
    }
}
Also used : Storage(io.pravega.segmentstore.storage.Storage) SyncStorage(io.pravega.segmentstore.storage.SyncStorage) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) Test(org.junit.Test)

Example 22 with SegmentHandle

use of io.pravega.segmentstore.storage.SegmentHandle in project pravega by pravega.

the class HDFSStorageTest method testFencing.

// region Fencing tests
/**
 * Tests fencing abilities. We create two different Storage objects with different owner ids.
 * Part 1: Creation:
 * * We create the Segment on Storage1:
 * ** We verify that Storage1 can execute all operations.
 * ** We verify that Storage2 can execute only read-only operations.
 * * We open the Segment on Storage2:
 * ** We verify that Storage1 can execute only read-only operations.
 * ** We verify that Storage2 can execute all operations.
 */
@Test
@Override
public void testFencing() throws Exception {
    final long epoch1 = 1;
    final long epoch2 = 2;
    final String segmentName = "segment";
    try (val storage1 = createStorage();
        val storage2 = createStorage()) {
        storage1.initialize(epoch1);
        storage2.initialize(epoch2);
        // Create segment in Storage1 (thus Storage1 owns it for now).
        storage1.create(segmentName, TIMEOUT).join();
        // Storage1 should be able to execute all operations.
        SegmentHandle handle1 = storage1.openWrite(segmentName).join();
        verifyWriteOperationsSucceed(handle1, storage1);
        verifyReadOnlyOperationsSucceed(handle1, storage1);
        // Open the segment in Storage2 (thus Storage2 owns it for now).
        SegmentHandle handle2 = storage2.openWrite(segmentName).join();
        // Storage1 should be able to execute only read-only operations.
        verifyWriteOperationsFail(handle1, storage1);
        verifyReadOnlyOperationsSucceed(handle1, storage1);
        // Storage2 should be able to execute all operations.
        verifyReadOnlyOperationsSucceed(handle2, storage2);
        verifyWriteOperationsSucceed(handle2, storage2);
        // Seal and Delete (these should be run last, otherwise we can't run our test).
        verifyFinalWriteOperationsFail(handle1, storage1);
        verifyFinalWriteOperationsSucceed(handle2, storage2);
    }
}
Also used : lombok.val(lombok.val) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) Test(org.junit.Test)

Example 23 with SegmentHandle

use of io.pravega.segmentstore.storage.SegmentHandle in project pravega by pravega.

the class StorageWriterTests method testWithStorageCorruptionErrors.

/**
 * Tests the StorageWriter in a Scenario where the Storage component throws data corruption exceptions (i.e., badOffset,
 * and after reconciliation, the data is still corrupt).
 */
@Test
public void testWithStorageCorruptionErrors() throws Exception {
    AtomicBoolean corruptionHappened = new AtomicBoolean();
    Function<TestContext, ErrorInjector<Exception>> createErrorInjector = context -> {
        byte[] corruptionData = "foo".getBytes();
        SegmentHandle corruptedSegmentHandle = InMemoryStorage.newHandle(context.metadata.getStreamSegmentMetadata(0).getName(), false);
        Supplier<Exception> exceptionSupplier = () -> {
            // Corrupt data. We use an internal method (append) to atomically write data at the end of the segment.
            // GetLength+Write would not work well because there may be concurrent writes that modify the data between
            // requesting the length and attempting to write, thus causing the corruption to fail.
            // NOTE: this is a synchronous call, but append() is also a sync method. If append() would become async,
            // care must be taken not to block a thread while waiting for it.
            context.storage.append(corruptedSegmentHandle, new ByteArrayInputStream(corruptionData), corruptionData.length);
            // Return some other kind of exception.
            return new TimeoutException("Intentional");
        };
        return new ErrorInjector<>(c -> !corruptionHappened.getAndSet(true), exceptionSupplier);
    };
    testWithStorageCriticalErrors(createErrorInjector, ex -> ex instanceof ReconciliationFailureException);
}
Also used : Arrays(java.util.Arrays) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) AssertExtensions(io.pravega.test.common.AssertExtensions) MergeSegmentOperation(io.pravega.segmentstore.server.logs.operations.MergeSegmentOperation) StorageNotPrimaryException(io.pravega.segmentstore.storage.StorageNotPrimaryException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TimeoutException(java.util.concurrent.TimeoutException) Cleanup(lombok.Cleanup) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) Operation(io.pravega.segmentstore.server.logs.operations.Operation) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) StreamSegmentTruncateOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentTruncateOperation) ServiceListeners(io.pravega.segmentstore.server.ServiceListeners) Services(io.pravega.common.concurrent.Services) Attributes(io.pravega.segmentstore.contracts.Attributes) Predicate(java.util.function.Predicate) Collection(java.util.Collection) InMemoryStorage(io.pravega.segmentstore.storage.mocks.InMemoryStorage) UUID(java.util.UUID) DataLogWriterNotPrimaryException(io.pravega.segmentstore.storage.DataLogWriterNotPrimaryException) Collectors(java.util.stream.Collectors) ErrorInjector(io.pravega.test.common.ErrorInjector) List(java.util.List) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) WriterSegmentProcessor(io.pravega.segmentstore.server.WriterSegmentProcessor) TestStorage(io.pravega.segmentstore.server.TestStorage) MetadataBuilder(io.pravega.segmentstore.server.MetadataBuilder) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) EvictableMetadata(io.pravega.segmentstore.server.EvictableMetadata) UpdateableContainerMetadata(io.pravega.segmentstore.server.UpdateableContainerMetadata) SegmentMetadata(io.pravega.segmentstore.server.SegmentMetadata) Timeout(org.junit.rules.Timeout) StreamSegmentMapOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentMapOperation) WriterFactory(io.pravega.segmentstore.server.WriterFactory) NameUtils(io.pravega.shared.NameUtils) UpdateAttributesOperation(io.pravega.segmentstore.server.logs.operations.UpdateAttributesOperation) AttributeId(io.pravega.segmentstore.contracts.AttributeId) IntentionalException(io.pravega.test.common.IntentionalException) lombok.val(lombok.val) MetadataCheckpointOperation(io.pravega.segmentstore.server.logs.operations.MetadataCheckpointOperation) IOException(java.io.IOException) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) Rule(org.junit.Rule) SegmentOperation(io.pravega.segmentstore.server.SegmentOperation) CachedStreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.CachedStreamSegmentAppendOperation) StreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentAppendOperation) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) DataCorruptionException(io.pravega.segmentstore.server.DataCorruptionException) Assert(org.junit.Assert) Collections(java.util.Collections) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ErrorInjector(io.pravega.test.common.ErrorInjector) ByteArrayInputStream(java.io.ByteArrayInputStream) Supplier(java.util.function.Supplier) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 24 with SegmentHandle

use of io.pravega.segmentstore.storage.SegmentHandle in project pravega by pravega.

the class ChunkedSegmentStorage method seal.

@Override
public CompletableFuture<Void> seal(SegmentHandle handle, Duration timeout) {
    checkInitialized();
    return executeSerialized(() -> {
        val traceId = LoggerHelpers.traceEnter(log, "seal", handle);
        Timer timer = new Timer();
        log.debug("{} seal - started segment={}.", logPrefix, handle.getSegmentName());
        Preconditions.checkNotNull(handle, "handle");
        String streamSegmentName = handle.getSegmentName();
        Preconditions.checkNotNull(streamSegmentName, "streamSegmentName");
        Preconditions.checkArgument(!handle.isReadOnly(), "handle must not be read only. Segment=%s", handle.getSegmentName());
        return tryWith(metadataStore.beginTransaction(false, handle.getSegmentName()), txn -> txn.get(streamSegmentName).thenComposeAsync(storageMetadata -> {
            val segmentMetadata = (SegmentMetadata) storageMetadata;
            // Validate preconditions.
            checkSegmentExists(streamSegmentName, segmentMetadata);
            checkOwnership(streamSegmentName, segmentMetadata);
            // seal if it is not already sealed.
            if (!segmentMetadata.isSealed()) {
                segmentMetadata.setSealed(true);
                txn.update(segmentMetadata);
                return txn.commit();
            } else {
                return CompletableFuture.completedFuture(null);
            }
        }, executor).thenRunAsync(() -> {
            log.debug("{} seal - finished segment={} latency={}.", logPrefix, handle.getSegmentName(), timer.getElapsedMillis());
            LoggerHelpers.traceLeave(log, "seal", traceId, handle);
        }, executor), executor).exceptionally(ex -> {
            log.warn("{} seal - exception segment={} latency={}.", logPrefix, handle.getSegmentName(), timer.getElapsedMillis(), ex);
            handleException(streamSegmentName, ex);
            return null;
        });
    }, handle.getSegmentName());
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Storage(io.pravega.segmentstore.storage.Storage) ScheduledFuture(java.util.concurrent.ScheduledFuture) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) StorageNotPrimaryException(io.pravega.segmentstore.storage.StorageNotPrimaryException) SLTS_STORAGE_USED_PERCENTAGE(io.pravega.shared.MetricsNames.SLTS_STORAGE_USED_PERCENTAGE) StorageFullException(io.pravega.segmentstore.storage.StorageFullException) ImmutableDate(io.pravega.common.util.ImmutableDate) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) STORAGE_METADATA_SIZE(io.pravega.shared.MetricsNames.STORAGE_METADATA_SIZE) Duration(java.time.Duration) MetadataTransaction(io.pravega.segmentstore.storage.metadata.MetadataTransaction) ChunkMetadata(io.pravega.segmentstore.storage.metadata.ChunkMetadata) StorageMetadataWritesFencedOutException(io.pravega.segmentstore.storage.metadata.StorageMetadataWritesFencedOutException) CompletionException(java.util.concurrent.CompletionException) GuardedBy(javax.annotation.concurrent.GuardedBy) StatusFlags(io.pravega.segmentstore.storage.metadata.StatusFlags) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) ConcurrentModificationException(java.util.ConcurrentModificationException) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) SegmentRollingPolicy(io.pravega.segmentstore.storage.SegmentRollingPolicy) SLTS_STORAGE_USED_BYTES(io.pravega.shared.MetricsNames.SLTS_STORAGE_USED_BYTES) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) SLTS_DELETE_LATENCY(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_DELETE_LATENCY) HashSet(java.util.HashSet) SegmentMetadata(io.pravega.segmentstore.storage.metadata.SegmentMetadata) MultiKeySequentialProcessor(io.pravega.common.concurrent.MultiKeySequentialProcessor) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SLTS_CREATE_LATENCY(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_CREATE_LATENCY) SLTS_DELETE_COUNT(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_DELETE_COUNT) LoggerHelpers(io.pravega.common.LoggerHelpers) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) SLTS_CREATE_COUNT(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_CREATE_COUNT) Executor(java.util.concurrent.Executor) STORAGE_METADATA_NUM_CHUNKS(io.pravega.shared.MetricsNames.STORAGE_METADATA_NUM_CHUNKS) INTERNAL_SCOPE_PREFIX(io.pravega.shared.NameUtils.INTERNAL_SCOPE_PREFIX) lombok.val(lombok.val) Timer(io.pravega.common.Timer) Beta(com.google.common.annotations.Beta) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) ChunkMetadataStore(io.pravega.segmentstore.storage.metadata.ChunkMetadataStore) ReadIndexBlockMetadata(io.pravega.segmentstore.storage.metadata.ReadIndexBlockMetadata) Preconditions(com.google.common.base.Preconditions) InputStream(java.io.InputStream) Timer(io.pravega.common.Timer)

Example 25 with SegmentHandle

use of io.pravega.segmentstore.storage.SegmentHandle in project pravega by pravega.

the class ChunkedSegmentStorage method create.

@Override
public CompletableFuture<SegmentHandle> create(String streamSegmentName, SegmentRollingPolicy rollingPolicy, Duration timeout) {
    checkInitialized();
    return executeSerialized(() -> {
        val traceId = LoggerHelpers.traceEnter(log, "create", streamSegmentName, rollingPolicy);
        val timer = new Timer();
        log.debug("{} create - started segment={}, rollingPolicy={}.", logPrefix, streamSegmentName, rollingPolicy);
        return tryWith(metadataStore.beginTransaction(false, streamSegmentName), txn -> {
            // Retrieve metadata and make sure it does not exist.
            return txn.get(streamSegmentName).thenComposeAsync(storageMetadata -> {
                val oldSegmentMetadata = (SegmentMetadata) storageMetadata;
                if (null != oldSegmentMetadata) {
                    throw new CompletionException(new StreamSegmentExistsException(streamSegmentName));
                }
                // Create a new record.
                val newSegmentMetadata = SegmentMetadata.builder().name(streamSegmentName).maxRollinglength(rollingPolicy.getMaxLength() == 0 ? SegmentRollingPolicy.NO_ROLLING.getMaxLength() : rollingPolicy.getMaxLength()).ownerEpoch(this.epoch).build();
                newSegmentMetadata.setActive(true);
                txn.create(newSegmentMetadata);
                // commit.
                return txn.commit().thenApplyAsync(v -> {
                    val retValue = SegmentStorageHandle.writeHandle(streamSegmentName);
                    Duration elapsed = timer.getElapsed();
                    SLTS_CREATE_LATENCY.reportSuccessEvent(elapsed);
                    SLTS_CREATE_COUNT.inc();
                    log.debug("{} create - finished segment={}, rollingPolicy={}, latency={}.", logPrefix, streamSegmentName, rollingPolicy, elapsed.toMillis());
                    LoggerHelpers.traceLeave(log, "create", traceId, retValue);
                    return retValue;
                }, executor);
            }, executor);
        }, executor).handleAsync((v, e) -> {
            if (null != e) {
                log.debug("{} create - exception segment={}, rollingPolicy={}, latency={}.", logPrefix, streamSegmentName, rollingPolicy, timer.getElapsedMillis(), e);
                handleException(streamSegmentName, e);
            }
            return v;
        }, executor);
    }, streamSegmentName);
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Storage(io.pravega.segmentstore.storage.Storage) ScheduledFuture(java.util.concurrent.ScheduledFuture) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) StorageNotPrimaryException(io.pravega.segmentstore.storage.StorageNotPrimaryException) SLTS_STORAGE_USED_PERCENTAGE(io.pravega.shared.MetricsNames.SLTS_STORAGE_USED_PERCENTAGE) StorageFullException(io.pravega.segmentstore.storage.StorageFullException) ImmutableDate(io.pravega.common.util.ImmutableDate) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) STORAGE_METADATA_SIZE(io.pravega.shared.MetricsNames.STORAGE_METADATA_SIZE) Duration(java.time.Duration) MetadataTransaction(io.pravega.segmentstore.storage.metadata.MetadataTransaction) ChunkMetadata(io.pravega.segmentstore.storage.metadata.ChunkMetadata) StorageMetadataWritesFencedOutException(io.pravega.segmentstore.storage.metadata.StorageMetadataWritesFencedOutException) CompletionException(java.util.concurrent.CompletionException) GuardedBy(javax.annotation.concurrent.GuardedBy) StatusFlags(io.pravega.segmentstore.storage.metadata.StatusFlags) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) ConcurrentModificationException(java.util.ConcurrentModificationException) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) SegmentRollingPolicy(io.pravega.segmentstore.storage.SegmentRollingPolicy) SLTS_STORAGE_USED_BYTES(io.pravega.shared.MetricsNames.SLTS_STORAGE_USED_BYTES) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) SLTS_DELETE_LATENCY(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_DELETE_LATENCY) HashSet(java.util.HashSet) SegmentMetadata(io.pravega.segmentstore.storage.metadata.SegmentMetadata) MultiKeySequentialProcessor(io.pravega.common.concurrent.MultiKeySequentialProcessor) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SLTS_CREATE_LATENCY(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_CREATE_LATENCY) SLTS_DELETE_COUNT(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_DELETE_COUNT) LoggerHelpers(io.pravega.common.LoggerHelpers) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) SLTS_CREATE_COUNT(io.pravega.segmentstore.storage.chunklayer.ChunkStorageMetrics.SLTS_CREATE_COUNT) Executor(java.util.concurrent.Executor) STORAGE_METADATA_NUM_CHUNKS(io.pravega.shared.MetricsNames.STORAGE_METADATA_NUM_CHUNKS) INTERNAL_SCOPE_PREFIX(io.pravega.shared.NameUtils.INTERNAL_SCOPE_PREFIX) lombok.val(lombok.val) Timer(io.pravega.common.Timer) Beta(com.google.common.annotations.Beta) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) ChunkMetadataStore(io.pravega.segmentstore.storage.metadata.ChunkMetadataStore) ReadIndexBlockMetadata(io.pravega.segmentstore.storage.metadata.ReadIndexBlockMetadata) Preconditions(com.google.common.base.Preconditions) InputStream(java.io.InputStream) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) Timer(io.pravega.common.Timer) CompletionException(java.util.concurrent.CompletionException) Duration(java.time.Duration)

Aggregations

SegmentHandle (io.pravega.segmentstore.storage.SegmentHandle)43 lombok.val (lombok.val)27 Test (org.junit.Test)26 Storage (io.pravega.segmentstore.storage.Storage)20 ByteArrayInputStream (java.io.ByteArrayInputStream)20 StreamSegmentNotExistsException (io.pravega.segmentstore.contracts.StreamSegmentNotExistsException)14 SegmentProperties (io.pravega.segmentstore.contracts.SegmentProperties)13 StreamSegmentSealedException (io.pravega.segmentstore.contracts.StreamSegmentSealedException)12 StorageNotPrimaryException (io.pravega.segmentstore.storage.StorageNotPrimaryException)12 Exceptions (io.pravega.common.Exceptions)10 Cleanup (lombok.Cleanup)10 CompletableFuture (java.util.concurrent.CompletableFuture)9 Futures (io.pravega.common.concurrent.Futures)8 StreamSegmentExistsException (io.pravega.segmentstore.contracts.StreamSegmentExistsException)8 NameUtils (io.pravega.shared.NameUtils)8 List (java.util.List)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 Preconditions (com.google.common.base.Preconditions)7 StreamSegmentInformation (io.pravega.segmentstore.contracts.StreamSegmentInformation)7 SegmentRollingPolicy (io.pravega.segmentstore.storage.SegmentRollingPolicy)7