Search in sources :

Example 6 with StreamSegmentMergedException

use of io.pravega.segmentstore.contracts.StreamSegmentMergedException in project pravega by pravega.

the class StreamSegmentContainerTests method testTransactionOperations.

/**
 * Test the createTransaction, append-to-Transaction, mergeTransaction methods.
 */
@Test
public void testTransactionOperations() throws Exception {
    // Create Transaction and Append to Transaction were partially tested in the Delete test, so we will focus on merge Transaction here.
    @Cleanup TestContext context = createContext();
    context.container.startAsync().awaitRunning();
    // 1. Create the StreamSegments.
    ArrayList<String> segmentNames = createSegments(context);
    HashMap<String, ArrayList<String>> transactionsBySegment = createTransactions(segmentNames, context);
    activateAllSegments(segmentNames, context);
    transactionsBySegment.values().forEach(s -> activateAllSegments(s, context));
    // 2. Add some appends.
    HashMap<String, Long> lengths = new HashMap<>();
    HashMap<String, ByteArrayOutputStream> segmentContents = new HashMap<>();
    appendToParentsAndTransactions(segmentNames, transactionsBySegment, lengths, segmentContents, context);
    // 3. Merge all the Transaction.
    Futures.allOf(mergeTransactions(transactionsBySegment, lengths, segmentContents, context, false)).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    // 4. Add more appends (to the parent segments)
    ArrayList<CompletableFuture<Long>> appendFutures = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        for (String segmentName : segmentNames) {
            RefCountByteArraySegment appendData = getAppendData(segmentName, APPENDS_PER_SEGMENT + i);
            appendFutures.add(context.container.append(segmentName, appendData, null, TIMEOUT));
            lengths.put(segmentName, lengths.getOrDefault(segmentName, 0L) + appendData.getLength());
            recordAppend(segmentName, appendData, segmentContents, null);
            // Verify that we can no longer append to Transaction.
            for (String transactionName : transactionsBySegment.get(segmentName)) {
                AssertExtensions.assertThrows("An append was allowed to a merged Transaction " + transactionName, context.container.append(transactionName, new ByteArraySegment("foo".getBytes()), null, TIMEOUT)::join, ex -> ex instanceof StreamSegmentMergedException || ex instanceof StreamSegmentNotExistsException);
            }
        }
    }
    Futures.allOf(appendFutures).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    // 5. Verify their contents.
    checkReadIndex(segmentContents, lengths, context);
    // 6. Writer moving data to Storage.
    waitForSegmentsInStorage(segmentNames, context).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
    checkStorage(segmentContents, lengths, context);
    context.container.stopAsync().awaitTerminated();
}
Also used : ByteArraySegment(io.pravega.common.util.ByteArraySegment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Cleanup(lombok.Cleanup) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicLong(java.util.concurrent.atomic.AtomicLong) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) Test(org.junit.Test)

Example 7 with StreamSegmentMergedException

use of io.pravega.segmentstore.contracts.StreamSegmentMergedException in project pravega by pravega.

the class ContainerMetadataUpdateTransactionTests method testPreProcessStreamSegmentAppend.

// region StreamSegmentAppendOperation
/**
 * Tests the preProcess method with StreamSegmentAppend operations.
 * Scenarios:
 * * Recovery Mode
 * * Non-recovery mode
 * * StreamSegment is Merged (both in-transaction and in-metadata)
 * * StreamSegment is Sealed (both in-transaction and in-metadata)
 */
@Test
public void testPreProcessStreamSegmentAppend() throws Exception {
    val metadata = createMetadata();
    StreamSegmentAppendOperation appendOp = createAppendNoOffset();
    // When everything is OK (in recovery mode) - nothing should change.
    metadata.enterRecoveryMode();
    val txn1 = createUpdateTransaction(metadata);
    txn1.preProcessOperation(appendOp);
    AssertExtensions.assertLessThan("Unexpected StreamSegmentOffset after call to preProcess in recovery mode.", 0, appendOp.getStreamSegmentOffset());
    checkNoSequenceNumberAssigned(appendOp, "call to preProcess in recovery mode");
    Assert.assertEquals("preProcess(Append) seems to have changed the Updater internal state in recovery mode.", SEGMENT_LENGTH, txn1.getStreamSegmentMetadata(SEGMENT_ID).getLength());
    Assert.assertEquals("preProcess(Append) seems to have changed the metadata in recovery mode.", SEGMENT_LENGTH, metadata.getStreamSegmentMetadata(SEGMENT_ID).getLength());
    // When everything is OK (no recovery mode).
    metadata.exitRecoveryMode();
    val txn2 = createUpdateTransaction(metadata);
    txn2.preProcessOperation(appendOp);
    Assert.assertEquals("Unexpected StreamSegmentOffset after call to preProcess in non-recovery mode.", SEGMENT_LENGTH, appendOp.getStreamSegmentOffset());
    checkNoSequenceNumberAssigned(appendOp, "call to preProcess in non-recovery mode");
    Assert.assertEquals("preProcess(Append) seems to have changed the Updater internal state.", SEGMENT_LENGTH, txn2.getStreamSegmentMetadata(SEGMENT_ID).getLength());
    Assert.assertEquals("preProcess(Append) seems to have changed the metadata.", SEGMENT_LENGTH, metadata.getStreamSegmentMetadata(SEGMENT_ID).getLength());
    // When StreamSegment is merged (via transaction).
    StreamSegmentAppendOperation transactionAppendOp = new StreamSegmentAppendOperation(SEALED_SOURCE_ID, DEFAULT_APPEND_DATA, null);
    MergeSegmentOperation mergeOp = createMerge();
    txn2.preProcessOperation(mergeOp);
    txn2.acceptOperation(mergeOp);
    Assert.assertFalse("Transaction should not be merged in metadata (yet).", metadata.getStreamSegmentMetadata(SEALED_SOURCE_ID).isMerged());
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Append) when Segment is merged (in transaction).", () -> txn2.preProcessOperation(transactionAppendOp), ex -> ex instanceof StreamSegmentMergedException);
    // When StreamSegment is merged (via metadata).
    txn2.commit(metadata);
    Assert.assertTrue("Transaction should have been merged in metadata.", metadata.getStreamSegmentMetadata(SEALED_SOURCE_ID).isMerged());
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Append) when Segment is merged (in metadata).", () -> txn2.preProcessOperation(transactionAppendOp), ex -> ex instanceof StreamSegmentMergedException);
    // When StreamSegment is sealed (via transaction).
    StreamSegmentSealOperation sealOp = createSeal();
    txn2.preProcessOperation(sealOp);
    txn2.acceptOperation(sealOp);
    Assert.assertFalse("StreamSegment should not be sealed in metadata (yet).", metadata.getStreamSegmentMetadata(SEGMENT_ID).isSealed());
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Append) when Segment is sealed (in transaction).", () -> txn2.preProcessOperation(createAppendNoOffset()), ex -> ex instanceof StreamSegmentSealedException);
    // When StreamSegment is sealed (via metadata).
    txn2.commit(metadata);
    Assert.assertTrue("StreamSegment should have been sealed in metadata.", metadata.getStreamSegmentMetadata(SEGMENT_ID).isSealed());
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Append) when Segment is sealed (in metadata).", () -> txn2.preProcessOperation(createAppendNoOffset()), ex -> ex instanceof StreamSegmentSealedException);
}
Also used : lombok.val(lombok.val) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) StreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentAppendOperation) MergeSegmentOperation(io.pravega.segmentstore.server.logs.operations.MergeSegmentOperation) Test(org.junit.Test)

Example 8 with StreamSegmentMergedException

use of io.pravega.segmentstore.contracts.StreamSegmentMergedException in project pravega by pravega.

the class ContainerMetadataUpdateTransactionTests method testPreProcessMergeTransaction.

// endregion
// region MergeTransactionOperation
/**
 * Tests the preProcess method with MergeTransactionOperations.
 * Scenarios:
 * * Recovery/non-recovery mode
 * * Target StreamSegment is sealed
 * * Target StreamSegment is a Transaction
 * * Transaction StreamSegment is already merged
 * * Transaction StreamSegment is not sealed
 */
@Test
public void testPreProcessMergeTransaction() throws Exception {
    UpdateableContainerMetadata metadata = createMetadata();
    // When everything is OK (recovery mode).
    MergeTransactionOperation recoveryMergeOp = createMerge();
    metadata.enterRecoveryMode();
    val txn1 = createUpdateTransaction(metadata);
    AssertExtensions.assertThrows("preProcess(Merge) handled an operation with no Transaction StreamSegment Length set.", () -> txn1.preProcessOperation(createMerge()), ex -> ex instanceof MetadataUpdateException);
    // In recovery mode, the updater does not set the length; it just validates that it has one.
    recoveryMergeOp.setLength(metadata.getStreamSegmentMetadata(SEALED_TRANSACTION_ID).getLength());
    txn1.preProcessOperation(recoveryMergeOp);
    AssertExtensions.assertLessThan("Unexpected Target StreamSegmentOffset after call to preProcess in recovery mode.", 0, recoveryMergeOp.getStreamSegmentOffset());
    checkNoSequenceNumberAssigned(recoveryMergeOp, "call to preProcess in recovery mode");
    Assert.assertFalse("preProcess(Merge) seems to have changed the Updater internal state in recovery mode.", txn1.getStreamSegmentMetadata(SEALED_TRANSACTION_ID).isMerged());
    Assert.assertFalse("preProcess(Merge) seems to have changed the metadata in recovery mode.", metadata.getStreamSegmentMetadata(SEALED_TRANSACTION_ID).isMerged());
    // When everything is OK (non-recovery mode).
    MergeTransactionOperation mergeOp = createMerge();
    metadata.exitRecoveryMode();
    val txn2 = createUpdateTransaction(metadata);
    txn2.preProcessOperation(mergeOp);
    Assert.assertEquals("Unexpected Transaction StreamSegmentLength after call to preProcess in non-recovery mode.", SEALED_TRANSACTION_LENGTH, mergeOp.getLength());
    Assert.assertEquals("Unexpected Target StreamSegmentOffset after call to preProcess in non-recovery mode.", SEGMENT_LENGTH, mergeOp.getStreamSegmentOffset());
    checkNoSequenceNumberAssigned(mergeOp, "call to preProcess in non-recovery mode");
    Assert.assertFalse("preProcess(Merge) seems to have changed the Updater internal state in non-recovery mode.", txn2.getStreamSegmentMetadata(SEALED_TRANSACTION_ID).isMerged());
    Assert.assertFalse("preProcess(Merge) seems to have changed the metadata in non-recovery mode.", metadata.getStreamSegmentMetadata(SEALED_TRANSACTION_ID).isMerged());
    // When Target StreamSegment is sealed.
    StreamSegmentSealOperation sealTargetOp = createSeal();
    txn2.preProcessOperation(sealTargetOp);
    txn2.acceptOperation(sealTargetOp);
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Merge) when Target StreamSegment is sealed.", () -> txn2.preProcessOperation(createMerge()), ex -> ex instanceof StreamSegmentSealedException);
    // Rollback the seal
    txn2.clear();
    // When Target StreamSegment is a Transaction.
    MergeTransactionOperation mergeToTransactionOp = new MergeTransactionOperation(NOTSEALED_TRANSACTION_ID, SEALED_TRANSACTION_ID);
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Merge) when Target StreamSegment is a Transaction.", () -> txn2.preProcessOperation(mergeToTransactionOp), ex -> ex instanceof MetadataUpdateException);
    // When Transaction is not sealed.
    MergeTransactionOperation mergeNonSealed = new MergeTransactionOperation(NOTSEALED_TRANSACTION_ID, SEGMENT_ID);
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Merge) when Transaction StreamSegment is not sealed.", () -> txn2.preProcessOperation(mergeNonSealed), ex -> ex instanceof StreamSegmentNotSealedException);
    // When Transaction is already merged.
    txn2.preProcessOperation(mergeOp);
    txn2.acceptOperation(mergeOp);
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Merge) when Transaction StreamSegment is already merged (in transaction).", () -> txn2.preProcessOperation(createMerge()), ex -> ex instanceof StreamSegmentMergedException);
    txn2.commit(metadata);
    AssertExtensions.assertThrows("Unexpected behavior for preProcess(Merge) when Transaction StreamSegment is already merged (in metadata).", () -> txn2.preProcessOperation(createMerge()), ex -> ex instanceof StreamSegmentMergedException);
}
Also used : lombok.val(lombok.val) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) UpdateableContainerMetadata(io.pravega.segmentstore.server.UpdateableContainerMetadata) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) StreamSegmentNotSealedException(io.pravega.segmentstore.contracts.StreamSegmentNotSealedException) MergeTransactionOperation(io.pravega.segmentstore.server.logs.operations.MergeTransactionOperation) Test(org.junit.Test)

Example 9 with StreamSegmentMergedException

use of io.pravega.segmentstore.contracts.StreamSegmentMergedException in project pravega by pravega.

the class PravegaRequestProcessor method commitTransaction.

@Override
public void commitTransaction(CommitTransaction commitTx) {
    String transactionName = StreamSegmentNameUtils.getTransactionNameFromId(commitTx.getSegment(), commitTx.getTxid());
    long requestId = commitTx.getRequestId();
    log.debug("Committing transaction {} ", commitTx);
    if (!verifyToken(commitTx.getSegment(), commitTx.getRequestId(), commitTx.getDelegationToken(), READ_UPDATE, "Commit Transaction")) {
        return;
    }
    // Seal and Merge can execute concurrently, as long as they are invoked in the correct order (first Seal, then Merge).
    // If Seal fails for whatever reason (except already sealed), then Merge will also fail because the txn is not sealed,
    // but invoking them in parallel does provide benefits in terms of reduced latency.
    val seal = segmentStore.sealStreamSegment(transactionName, TIMEOUT).exceptionally(this::ignoreSegmentSealed).thenCompose(v -> recordStatForTransaction(transactionName, commitTx.getSegment()).exceptionally(e -> {
        // gobble up any errors from stat recording so we do not affect rest of the flow.
        log.error("exception while computing stats while merging txn {}", e);
        return null;
    }));
    val merge = segmentStore.mergeTransaction(transactionName, TIMEOUT).thenAccept(v -> connection.send(new TransactionCommitted(requestId, commitTx.getSegment(), commitTx.getTxid())));
    CompletableFuture.allOf(seal, merge).exceptionally(e -> {
        if (Exceptions.unwrap(e) instanceof StreamSegmentMergedException) {
            log.info("Stream segment is already merged '{}'.", transactionName);
            connection.send(new TransactionCommitted(requestId, commitTx.getSegment(), commitTx.getTxid()));
            return null;
        } else {
            return handleException(requestId, transactionName, "Commit transaction", e);
        }
    });
}
Also used : lombok.val(lombok.val) SCALE_POLICY_RATE(io.pravega.segmentstore.contracts.Attributes.SCALE_POLICY_RATE) Arrays(java.util.Arrays) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) SEGMENT_CREATE_LATENCY(io.pravega.shared.MetricsNames.SEGMENT_CREATE_LATENCY) AuthHandler(io.pravega.auth.AuthHandler) SegmentIsTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentIsTruncated) CREATION_TIME(io.pravega.segmentstore.contracts.Attributes.CREATION_TIME) MetricsNames.nameFromSegment(io.pravega.shared.MetricsNames.nameFromSegment) GetStreamSegmentInfo(io.pravega.shared.protocol.netty.WireCommands.GetStreamSegmentInfo) ReadResultEntryContents(io.pravega.segmentstore.contracts.ReadResultEntryContents) Duration(java.time.Duration) Map(java.util.Map) SegmentCreated(io.pravega.shared.protocol.netty.WireCommands.SegmentCreated) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) Attributes(io.pravega.segmentstore.contracts.Attributes) CancellationException(java.util.concurrent.CancellationException) ContainerNotFoundException(io.pravega.segmentstore.contracts.ContainerNotFoundException) Slf4j(lombok.extern.slf4j.Slf4j) CreateSegment(io.pravega.shared.protocol.netty.WireCommands.CreateSegment) SealSegment(io.pravega.shared.protocol.netty.WireCommands.SealSegment) SegmentSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentSealed) EndOfStreamSegment(io.pravega.segmentstore.contracts.ReadResultEntryType.EndOfStreamSegment) SegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.SegmentAttribute) SEGMENT_READ_LATENCY(io.pravega.shared.MetricsNames.SEGMENT_READ_LATENCY) Exceptions(io.pravega.common.Exceptions) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) GetSegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.GetSegmentAttribute) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) SegmentRead(io.pravega.shared.protocol.netty.WireCommands.SegmentRead) AccessLevel(lombok.AccessLevel) Future(io.pravega.segmentstore.contracts.ReadResultEntryType.Future) FailingRequestProcessor(io.pravega.shared.protocol.netty.FailingRequestProcessor) StreamHelpers(io.pravega.common.io.StreamHelpers) StreamSegmentTruncatedException(io.pravega.segmentstore.contracts.StreamSegmentTruncatedException) StatsLogger(io.pravega.shared.metrics.StatsLogger) OpStatsLogger(io.pravega.shared.metrics.OpStatsLogger) lombok.val(lombok.val) SEGMENT_WRITE_EVENTS(io.pravega.shared.MetricsNames.SEGMENT_WRITE_EVENTS) IOException(java.io.IOException) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) SegmentDeleted(io.pravega.shared.protocol.netty.WireCommands.SegmentDeleted) CreateTransaction(io.pravega.shared.protocol.netty.WireCommands.CreateTransaction) Truncated(io.pravega.segmentstore.contracts.ReadResultEntryType.Truncated) SegmentTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentTruncated) RequestProcessor(io.pravega.shared.protocol.netty.RequestProcessor) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) Preconditions(com.google.common.base.Preconditions) TransactionInfo(io.pravega.shared.protocol.netty.WireCommands.TransactionInfo) AbortTransaction(io.pravega.shared.protocol.netty.WireCommands.AbortTransaction) AuthenticationException(io.pravega.common.auth.AuthenticationException) Cache(io.pravega.segmentstore.contracts.ReadResultEntryType.Cache) SneakyThrows(lombok.SneakyThrows) ByteBuffer(java.nio.ByteBuffer) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) UpdateSegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.UpdateSegmentAttribute) UpdateSegmentPolicy(io.pravega.shared.protocol.netty.WireCommands.UpdateSegmentPolicy) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) CommitTransaction(io.pravega.shared.protocol.netty.WireCommands.CommitTransaction) Collection(java.util.Collection) UUID(java.util.UUID) Math.min(java.lang.Math.min) StreamSegmentNameUtils(io.pravega.shared.segment.StreamSegmentNameUtils) MetricsProvider(io.pravega.shared.metrics.MetricsProvider) List(java.util.List) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) PassingTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.PassingTokenVerifier) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) DelegationTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.DelegationTokenVerifier) Math.max(java.lang.Math.max) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) ReadResult(io.pravega.segmentstore.contracts.ReadResult) TransactionAborted(io.pravega.shared.protocol.netty.WireCommands.TransactionAborted) DeleteSegment(io.pravega.shared.protocol.netty.WireCommands.DeleteSegment) SegmentPolicyUpdated(io.pravega.shared.protocol.netty.WireCommands.SegmentPolicyUpdated) Getter(lombok.Getter) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) CompletableFuture(java.util.concurrent.CompletableFuture) GetTransactionInfo(io.pravega.shared.protocol.netty.WireCommands.GetTransactionInfo) DynamicLogger(io.pravega.shared.metrics.DynamicLogger) SEGMENT_WRITE_BYTES(io.pravega.shared.MetricsNames.SEGMENT_WRITE_BYTES) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) SEGMENT_READ_BYTES(io.pravega.shared.MetricsNames.SEGMENT_READ_BYTES) SCALE_POLICY_TYPE(io.pravega.segmentstore.contracts.Attributes.SCALE_POLICY_TYPE) TransactionCommitted(io.pravega.shared.protocol.netty.WireCommands.TransactionCommitted) TYPE_PLUS_LENGTH_SIZE(io.pravega.shared.protocol.netty.WireCommands.TYPE_PLUS_LENGTH_SIZE) StreamSegmentInfo(io.pravega.shared.protocol.netty.WireCommands.StreamSegmentInfo) TransactionCreated(io.pravega.shared.protocol.netty.WireCommands.TransactionCreated) TruncateSegment(io.pravega.shared.protocol.netty.WireCommands.TruncateSegment) ReadSegment(io.pravega.shared.protocol.netty.WireCommands.ReadSegment) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) LoggerHelpers(io.pravega.common.LoggerHelpers) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) Timer(io.pravega.common.Timer) SegmentAttributeUpdated(io.pravega.shared.protocol.netty.WireCommands.SegmentAttributeUpdated) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) Collections(java.util.Collections) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) TransactionCommitted(io.pravega.shared.protocol.netty.WireCommands.TransactionCommitted)

Example 10 with StreamSegmentMergedException

use of io.pravega.segmentstore.contracts.StreamSegmentMergedException in project pravega by pravega.

the class PravegaRequestProcessor method mergeSegmentsBatch.

@Override
public void mergeSegmentsBatch(WireCommands.MergeSegmentsBatch mergeSegments) {
    final String operation = "mergeSegmentsBatch";
    List<String> sources = mergeSegments.getSourceSegmentIds();
    if (!verifyTokenForUpdate(mergeSegments.getTargetSegmentId(), mergeSegments.getRequestId(), mergeSegments.getDelegationToken(), operation)) {
        return;
    }
    for (String s : sources) {
        if (!verifyToken(s, mergeSegments.getRequestId(), mergeSegments.getDelegationToken(), operation)) {
            return;
        }
    }
    log.info(mergeSegments.getRequestId(), "Merging Segments Batch in-order {} ", mergeSegments);
    Futures.allOfWithResults(sources.stream().map(source -> Futures.handleCompose(segmentStore.mergeStreamSegment(mergeSegments.getTargetSegmentId(), source, TIMEOUT), (r, e) -> {
        if (e != null) {
            Throwable unwrap = Exceptions.unwrap(e);
            if (unwrap instanceof StreamSegmentMergedException) {
                log.info(mergeSegments.getRequestId(), "Stream segment already merged '{}'.", source);
                return segmentStore.getStreamSegmentInfo(mergeSegments.getTargetSegmentId(), TIMEOUT).thenApply(SegmentProperties::getLength);
            }
            if (unwrap instanceof StreamSegmentNotExistsException) {
                StreamSegmentNotExistsException ex = (StreamSegmentNotExistsException) unwrap;
                if (ex.getStreamSegmentName().equals(source)) {
                    log.info(mergeSegments.getRequestId(), "Stream segment already merged '{}'.", source);
                    return segmentStore.getStreamSegmentInfo(mergeSegments.getTargetSegmentId(), TIMEOUT).thenApply(SegmentProperties::getLength);
                }
            }
            throw new CompletionException(e);
        } else {
            recordStatForTransaction(r, mergeSegments.getTargetSegmentId());
            return CompletableFuture.completedFuture(r.getTargetSegmentLength());
        }
    })).collect(Collectors.toUnmodifiableList())).thenAccept(mergeResults -> {
        connection.send(new WireCommands.SegmentsBatchMerged(mergeSegments.getRequestId(), mergeSegments.getTargetSegmentId(), sources, mergeResults));
    }).exceptionally(e -> {
        log.debug("error");
        return handleException(mergeSegments.getRequestId(), mergeSegments.getTargetSegmentId(), operation, e);
    });
}
Also used : SCALE_POLICY_RATE(io.pravega.segmentstore.contracts.Attributes.SCALE_POLICY_RATE) Arrays(java.util.Arrays) TableSegmentConfig(io.pravega.segmentstore.contracts.tables.TableSegmentConfig) ErrorCode(io.pravega.shared.protocol.netty.WireCommands.ErrorMessage.ErrorCode) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) SegmentIsTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentIsTruncated) CreateTableSegment(io.pravega.shared.protocol.netty.WireCommands.CreateTableSegment) CREATION_TIME(io.pravega.segmentstore.contracts.Attributes.CREATION_TIME) GetStreamSegmentInfo(io.pravega.shared.protocol.netty.WireCommands.GetStreamSegmentInfo) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) MergeSegments(io.pravega.shared.protocol.netty.WireCommands.MergeSegments) Duration(java.time.Duration) Map(java.util.Map) SegmentCreated(io.pravega.shared.protocol.netty.WireCommands.SegmentCreated) DeltaIteratorState(io.pravega.segmentstore.server.tables.DeltaIteratorState) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) Attributes(io.pravega.segmentstore.contracts.Attributes) TableKey(io.pravega.segmentstore.contracts.tables.TableKey) CancellationException(java.util.concurrent.CancellationException) NonNull(lombok.NonNull) ThreadSafe(javax.annotation.concurrent.ThreadSafe) ContainerNotFoundException(io.pravega.segmentstore.contracts.ContainerNotFoundException) GuardedBy(javax.annotation.concurrent.GuardedBy) CreateSegment(io.pravega.shared.protocol.netty.WireCommands.CreateSegment) SealSegment(io.pravega.shared.protocol.netty.WireCommands.SealSegment) SegmentSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentSealed) EndOfStreamSegment(io.pravega.segmentstore.contracts.ReadResultEntryType.EndOfStreamSegment) Futures(io.pravega.common.concurrent.Futures) SegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.SegmentAttribute) IllegalContainerStateException(io.pravega.segmentstore.server.IllegalContainerStateException) Exceptions(io.pravega.common.Exceptions) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) GetSegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.GetSegmentAttribute) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) SegmentType(io.pravega.segmentstore.contracts.SegmentType) SegmentRead(io.pravega.shared.protocol.netty.WireCommands.SegmentRead) AccessLevel(lombok.AccessLevel) Future(io.pravega.segmentstore.contracts.ReadResultEntryType.Future) FailingRequestProcessor(io.pravega.shared.protocol.netty.FailingRequestProcessor) TokenException(io.pravega.auth.TokenException) StreamSegmentTruncatedException(io.pravega.segmentstore.contracts.StreamSegmentTruncatedException) KeyNotExistsException(io.pravega.segmentstore.contracts.tables.KeyNotExistsException) DeleteTableSegment(io.pravega.shared.protocol.netty.WireCommands.DeleteTableSegment) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) Throwables(com.google.common.base.Throwables) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) SegmentDeleted(io.pravega.shared.protocol.netty.WireCommands.SegmentDeleted) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) Truncated(io.pravega.segmentstore.contracts.ReadResultEntryType.Truncated) SegmentTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentTruncated) RequestProcessor(io.pravega.shared.protocol.netty.RequestProcessor) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) Preconditions(com.google.common.base.Preconditions) Callbacks.invokeSafely(io.pravega.common.function.Callbacks.invokeSafely) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) EMPTY_BUFFER(io.netty.buffer.Unpooled.EMPTY_BUFFER) Cache(io.pravega.segmentstore.contracts.ReadResultEntryType.Cache) TokenExpiredException(io.pravega.auth.TokenExpiredException) TableStore(io.pravega.segmentstore.contracts.tables.TableStore) LoggerFactory(org.slf4j.LoggerFactory) Unpooled(io.netty.buffer.Unpooled) IteratorArgs(io.pravega.segmentstore.contracts.tables.IteratorArgs) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) TagLogger(io.pravega.common.tracing.TagLogger) UpdateSegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.UpdateSegmentAttribute) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) UpdateSegmentPolicy(io.pravega.shared.protocol.netty.WireCommands.UpdateSegmentPolicy) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) ROLLOVER_SIZE(io.pravega.segmentstore.contracts.Attributes.ROLLOVER_SIZE) Collection(java.util.Collection) CompletionException(java.util.concurrent.CompletionException) Math.min(java.lang.Math.min) Collectors(java.util.stream.Collectors) List(java.util.List) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) PassingTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.PassingTokenVerifier) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) DelegationTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.DelegationTokenVerifier) Math.max(java.lang.Math.max) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) ReadResult(io.pravega.segmentstore.contracts.ReadResult) IntStream(java.util.stream.IntStream) Setter(lombok.Setter) DeleteSegment(io.pravega.shared.protocol.netty.WireCommands.DeleteSegment) SegmentPolicyUpdated(io.pravega.shared.protocol.netty.WireCommands.SegmentPolicyUpdated) Getter(lombok.Getter) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Iterators(com.google.common.collect.Iterators) TableSegmentNotEmpty(io.pravega.shared.protocol.netty.WireCommands.TableSegmentNotEmpty) TableSegmentNotEmptyException(io.pravega.segmentstore.contracts.tables.TableSegmentNotEmptyException) ByteBuf(io.netty.buffer.ByteBuf) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) SCALE_POLICY_TYPE(io.pravega.segmentstore.contracts.Attributes.SCALE_POLICY_TYPE) TYPE_PLUS_LENGTH_SIZE(io.pravega.shared.protocol.netty.WireCommands.TYPE_PLUS_LENGTH_SIZE) StreamSegmentInfo(io.pravega.shared.protocol.netty.WireCommands.StreamSegmentInfo) TruncateSegment(io.pravega.shared.protocol.netty.WireCommands.TruncateSegment) ReadSegment(io.pravega.shared.protocol.netty.WireCommands.ReadSegment) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) ByteBufWrapper(io.pravega.shared.protocol.netty.ByteBufWrapper) LoggerHelpers(io.pravega.common.LoggerHelpers) MergeStreamSegmentResult(io.pravega.segmentstore.contracts.MergeStreamSegmentResult) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) Timer(io.pravega.common.Timer) TableSegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.TableSegmentStatsRecorder) SegmentAttributeUpdated(io.pravega.shared.protocol.netty.WireCommands.SegmentAttributeUpdated) Consumer(java.util.function.Consumer) AbstractMap(java.util.AbstractMap) Collectors.toList(java.util.stream.Collectors.toList) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) Collections(java.util.Collections) CompletionException(java.util.concurrent.CompletionException) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException)

Aggregations

StreamSegmentMergedException (io.pravega.segmentstore.contracts.StreamSegmentMergedException)12 StreamSegmentSealedException (io.pravega.segmentstore.contracts.StreamSegmentSealedException)8 lombok.val (lombok.val)8 Test (org.junit.Test)8 StreamSegmentNotExistsException (io.pravega.segmentstore.contracts.StreamSegmentNotExistsException)6 ArrayList (java.util.ArrayList)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 AttributeUpdate (io.pravega.segmentstore.contracts.AttributeUpdate)5 StreamSegmentStore (io.pravega.segmentstore.contracts.StreamSegmentStore)5 StreamSegmentSealOperation (io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation)5 Preconditions (com.google.common.base.Preconditions)4 Exceptions (io.pravega.common.Exceptions)4 LoggerHelpers (io.pravega.common.LoggerHelpers)4 AttributeId (io.pravega.segmentstore.contracts.AttributeId)4 AttributeUpdateType (io.pravega.segmentstore.contracts.AttributeUpdateType)4 Attributes (io.pravega.segmentstore.contracts.Attributes)4 BadAttributeUpdateException (io.pravega.segmentstore.contracts.BadAttributeUpdateException)4 ReadResult (io.pravega.segmentstore.contracts.ReadResult)4 PassingTokenVerifier (io.pravega.segmentstore.server.host.delegationtoken.PassingTokenVerifier)4 SegmentStatsRecorder (io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder)4