Search in sources :

Example 66 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class FixedKeyLengthTableSegmentLayout method compactIfNeeded.

private CompletableFuture<Void> compactIfNeeded(CompactionCandidate candidate) {
    val compactor = new FixedKeyLengthTableCompactor(candidate.getSegment(), this.tableCompactorConfig, this.executor);
    val timer = new TimeoutTimer(this.config.getRecoveryTimeout());
    return compactor.isCompactionRequired().thenComposeAsync(isRequired -> {
        if (isRequired) {
            return compact(candidate.getSegment(), compactor, timer);
        } else {
            log.debug("{}: No compaction required at this time.", this.traceObjectId);
            return CompletableFuture.completedFuture(null);
        }
    }, this.executor);
}
Also used : lombok.val(lombok.val) TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 67 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class FixedKeyLengthTableSegmentLayout method newIterator.

private <T> CompletableFuture<AsyncIterator<IteratorItem<T>>> newIterator(@NonNull DirectSegmentAccess segment, @NonNull GetIteratorItem<T> getItems, @NonNull IteratorArgs args) {
    Preconditions.checkArgument(args.getContinuationToken() == null, "ContinuationToken not supported for FixedKeyLengthTableSegments.");
    val segmentKeyLength = getSegmentKeyLength(segment.getInfo());
    val fromId = args.getFrom() == null ? AttributeId.Variable.minValue(segmentKeyLength) : AttributeId.from(args.getFrom().getCopy());
    val toId = args.getTo() == null ? AttributeId.Variable.maxValue(segmentKeyLength) : AttributeId.from(args.getTo().getCopy());
    val timer = new TimeoutTimer(args.getFetchTimeout());
    return segment.attributeIterator(fromId, toId, timer.getRemaining()).thenApply(ai -> new TableIterator<>(ai, segment, getItems, timer));
}
Also used : lombok.val(lombok.val) TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 68 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class FixedKeyLengthTableSegmentLayout method put.

@Override
CompletableFuture<List<Long>> put(@NonNull DirectSegmentAccess segment, @NonNull List<TableEntry> entries, long tableSegmentOffset, TimeoutTimer timer) {
    val segmentInfo = segment.getInfo();
    ensureSegmentType(segmentInfo.getName(), segmentInfo.getType());
    val segmentKeyLength = getSegmentKeyLength(segmentInfo);
    ensureValidKeyLength(segmentInfo.getName(), segmentKeyLength);
    val attributeUpdates = new AttributeUpdateCollection();
    int batchOffset = 0;
    val batchOffsets = new ArrayList<Integer>();
    boolean isConditional = false;
    for (val e : entries) {
        val key = e.getKey();
        Preconditions.checkArgument(key.getKey().getLength() == segmentKeyLength, "Entry Key Length for key `%s` incompatible with segment '%s' which requires key lengths of %s.", key, segmentInfo.getName(), segmentKeyLength);
        attributeUpdates.add(createIndexUpdate(key, batchOffset));
        isConditional |= key.hasVersion();
        batchOffsets.add(batchOffset);
        batchOffset += this.serializer.getUpdateLength(e);
    }
    logRequest("put", segmentInfo.getName(), isConditional, tableSegmentOffset, entries.size(), batchOffset);
    if (batchOffset > this.config.getMaxBatchSize()) {
        throw new UpdateBatchTooLargeException(batchOffset, this.config.getMaxBatchSize());
    }
    // Update total number of entries in Table (this includes updates to the same key).
    attributeUpdates.add(new AttributeUpdate(TableAttributes.TOTAL_ENTRY_COUNT, AttributeUpdateType.Accumulate, entries.size()));
    val serializedEntries = this.serializer.serializeUpdate(entries);
    val append = tableSegmentOffset == TableSegmentLayout.NO_OFFSET ? segment.append(serializedEntries, attributeUpdates, timer.getRemaining()) : segment.append(serializedEntries, attributeUpdates, tableSegmentOffset, timer.getRemaining());
    return handleConditionalUpdateException(append, segmentInfo).thenApply(segmentOffset -> {
        this.compactionService.process(new CompactionCandidate(segment));
        return batchOffsets.stream().map(offset -> offset + segmentOffset).collect(Collectors.toList());
    });
}
Also used : lombok.val(lombok.val) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) DynamicAttributeValue(io.pravega.segmentstore.contracts.DynamicAttributeValue) TableSegmentConfig(io.pravega.segmentstore.contracts.tables.TableSegmentConfig) SneakyThrows(lombok.SneakyThrows) RequiredArgsConstructor(lombok.RequiredArgsConstructor) RevisionDataInput(io.pravega.common.io.serialization.RevisionDataInput) IteratorArgs(io.pravega.segmentstore.contracts.tables.IteratorArgs) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) ArrayView(io.pravega.common.util.ArrayView) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) Map(java.util.Map) RevisionDataOutput(io.pravega.common.io.serialization.RevisionDataOutput) AsyncReadResultProcessor(io.pravega.segmentstore.server.reading.AsyncReadResultProcessor) VersionedSerializer(io.pravega.common.io.serialization.VersionedSerializer) Attributes(io.pravega.segmentstore.contracts.Attributes) TableKey(io.pravega.segmentstore.contracts.tables.TableKey) NonNull(lombok.NonNull) Collection(java.util.Collection) CompletionException(java.util.concurrent.CompletionException) DynamicAttributeUpdate(io.pravega.segmentstore.contracts.DynamicAttributeUpdate) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) TableSegmentInfo(io.pravega.segmentstore.contracts.tables.TableSegmentInfo) ByteArraySegment(io.pravega.common.util.ByteArraySegment) Builder(lombok.Builder) DelayedProcessor(io.pravega.common.concurrent.DelayedProcessor) WriterSegmentProcessor(io.pravega.segmentstore.server.WriterSegmentProcessor) Futures(io.pravega.common.concurrent.Futures) TableAttributes(io.pravega.segmentstore.contracts.tables.TableAttributes) Getter(lombok.Getter) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) AtomicReference(java.util.concurrent.atomic.AtomicReference) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) ArrayList(java.util.ArrayList) SegmentType(io.pravega.segmentstore.contracts.SegmentType) IteratorItem(io.pravega.segmentstore.contracts.tables.IteratorItem) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AttributeIterator(io.pravega.segmentstore.server.AttributeIterator) StreamSegmentTruncatedException(io.pravega.segmentstore.contracts.StreamSegmentTruncatedException) IteratorState(io.pravega.segmentstore.contracts.tables.IteratorState) TimeoutTimer(io.pravega.common.TimeoutTimer) KeyNotExistsException(io.pravega.segmentstore.contracts.tables.KeyNotExistsException) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) AsyncIterator(io.pravega.common.util.AsyncIterator) IOException(java.io.IOException) Beta(com.google.common.annotations.Beta) ObjectBuilder(io.pravega.common.ObjectBuilder) DirectSegmentAccess(io.pravega.segmentstore.server.DirectSegmentAccess) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) Data(lombok.Data) Preconditions(com.google.common.base.Preconditions) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) AllArgsConstructor(lombok.AllArgsConstructor) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) Collections(java.util.Collections) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) DynamicAttributeUpdate(io.pravega.segmentstore.contracts.DynamicAttributeUpdate) ArrayList(java.util.ArrayList)

Example 69 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class SegmentAggregator method flush.

// endregion
// region Flushing and Merging
/**
 * Flushes the contents of the Aggregator to the Storage.
 *
 * @param force   If true, force-flushes everything accumulated in the {@link SegmentAggregator}, regardless of
 *                the value returned by {@link #mustFlush()}.
 * @param timeout Timeout for the operation.
 * @return A CompletableFuture that, when completed, will contain a summary of the flush operation. If any errors
 * occurred during the flush, the Future will be completed with the appropriate exception.
 */
@Override
public CompletableFuture<WriterFlushResult> flush(boolean force, Duration timeout) {
    ensureInitializedAndNotClosed();
    if (this.metadata.isDeletedInStorage()) {
        // Segment has been deleted; don't do anything else.
        return CompletableFuture.completedFuture(new WriterFlushResult());
    }
    long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "flush");
    TimeoutTimer timer = new TimeoutTimer(timeout);
    CompletableFuture<WriterFlushResult> result;
    try {
        switch(this.state.get()) {
            case Writing:
                result = flushNormally(force, timer);
                break;
            case ReconciliationNeeded:
                result = beginReconciliation(timer).thenComposeAsync(v -> reconcile(timer), this.executor);
                break;
            case Reconciling:
                result = reconcile(timer);
                break;
            // $CASES-OMITTED$
            default:
                result = Futures.failedFuture(new IllegalStateException(String.format("Unexpected state for SegmentAggregator (%s) for segment '%s'.", this.state, this.metadata.getName())));
                break;
        }
    } catch (Exception ex) {
        // Convert synchronous errors into async errors - it's easier to handle on the receiving end.
        result = Futures.failedFuture(ex);
    }
    return result.thenApply(r -> {
        LoggerHelpers.traceLeave(log, this.traceObjectId, "flush", traceId, r);
        return r;
    });
}
Also used : Storage(io.pravega.segmentstore.storage.Storage) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) SneakyThrows(lombok.SneakyThrows) MergeSegmentOperation(io.pravega.segmentstore.server.logs.operations.MergeSegmentOperation) Cleanup(lombok.Cleanup) ServiceHaltException(io.pravega.segmentstore.server.ServiceHaltException) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) Operation(io.pravega.segmentstore.server.logs.operations.Operation) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) StreamSegmentTruncateOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentTruncateOperation) Attributes(io.pravega.segmentstore.contracts.Attributes) Predicate(java.util.function.Predicate) CompletionException(java.util.concurrent.CompletionException) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) WriterSegmentProcessor(io.pravega.segmentstore.server.WriterSegmentProcessor) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) SegmentRollingPolicy(io.pravega.segmentstore.storage.SegmentRollingPolicy) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) AbstractTimer(io.pravega.common.AbstractTimer) SegmentMetadata(io.pravega.segmentstore.server.SegmentMetadata) Nullable(javax.annotation.Nullable) LoggerHelpers(io.pravega.common.LoggerHelpers) TimeoutTimer(io.pravega.common.TimeoutTimer) Executor(java.util.concurrent.Executor) AtomicLong(java.util.concurrent.atomic.AtomicLong) SegmentOperation(io.pravega.segmentstore.server.SegmentOperation) CachedStreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.CachedStreamSegmentAppendOperation) StorageOperation(io.pravega.segmentstore.server.logs.operations.StorageOperation) StreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentAppendOperation) Preconditions(com.google.common.base.Preconditions) DataCorruptionException(io.pravega.segmentstore.server.DataCorruptionException) ArrayDeque(java.util.ArrayDeque) DeleteSegmentOperation(io.pravega.segmentstore.server.logs.operations.DeleteSegmentOperation) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) InputStream(java.io.InputStream) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) ServiceHaltException(io.pravega.segmentstore.server.ServiceHaltException) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) CompletionException(java.util.concurrent.CompletionException) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) DataCorruptionException(io.pravega.segmentstore.server.DataCorruptionException) TimeoutTimer(io.pravega.common.TimeoutTimer)

Example 70 with TimeoutTimer

use of io.pravega.common.TimeoutTimer in project pravega by pravega.

the class SegmentAggregator method reconcile.

private CompletableFuture<WriterFlushResult> reconcile(TimeoutTimer timer) {
    ReconciliationState rc = this.reconciliationState.get();
    WriterFlushResult result = new WriterFlushResult();
    if (rc == null) {
        setState(AggregatorState.Writing);
        return CompletableFuture.completedFuture(result);
    } else if (this.hasDeletePending.get()) {
        // Do not bother with anything else. If we know we are going to delete this segment, then do no bother doing
        // any other kind of reconciliation work.
        setState(AggregatorState.Writing);
        return deleteSegment(timer);
    }
    SegmentProperties storageInfo = rc.getStorageInfo();
    long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "reconcile", rc);
    // Process each Operation in sequence, as long as its starting offset is less than ReconciliationState.getStorageInfo().getLength()
    AtomicBoolean exceededStorageLength = new AtomicBoolean(false);
    return Futures.loop(() -> this.operations.size() > 0 && !exceededStorageLength.get(), () -> {
        StorageOperation op = this.operations.getFirst();
        return reconcileOperation(op, storageInfo, timer).thenApply(partialFlushResult -> {
            if (op.getLastStreamSegmentOffset() >= storageInfo.getLength()) {
                // This operation crosses the boundary of StorageLength. It has been reconciled,
                // and as such it is the last operation that we need to inspect.
                exceededStorageLength.set(true);
            }
            log.info("{}: Reconciled {} ({}).", this.traceObjectId, op, partialFlushResult);
            return partialFlushResult;
        });
    }, result::withFlushResult, this.executor).thenApply(v -> {
        updateMetadata(storageInfo);
        this.reconciliationState.set(null);
        setState(AggregatorState.Writing);
        LoggerHelpers.traceLeave(log, this.traceObjectId, "reconcile", traceId, result);
        return result;
    });
}
Also used : Storage(io.pravega.segmentstore.storage.Storage) StreamSegmentInformation(io.pravega.segmentstore.contracts.StreamSegmentInformation) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) SneakyThrows(lombok.SneakyThrows) MergeSegmentOperation(io.pravega.segmentstore.server.logs.operations.MergeSegmentOperation) Cleanup(lombok.Cleanup) ServiceHaltException(io.pravega.segmentstore.server.ServiceHaltException) UpdateableSegmentMetadata(io.pravega.segmentstore.server.UpdateableSegmentMetadata) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentHandle(io.pravega.segmentstore.storage.SegmentHandle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) Operation(io.pravega.segmentstore.server.logs.operations.Operation) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) StreamSegmentTruncateOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentTruncateOperation) Attributes(io.pravega.segmentstore.contracts.Attributes) Predicate(java.util.function.Predicate) CompletionException(java.util.concurrent.CompletionException) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) WriterSegmentProcessor(io.pravega.segmentstore.server.WriterSegmentProcessor) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) SegmentRollingPolicy(io.pravega.segmentstore.storage.SegmentRollingPolicy) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) AbstractTimer(io.pravega.common.AbstractTimer) SegmentMetadata(io.pravega.segmentstore.server.SegmentMetadata) Nullable(javax.annotation.Nullable) LoggerHelpers(io.pravega.common.LoggerHelpers) TimeoutTimer(io.pravega.common.TimeoutTimer) Executor(java.util.concurrent.Executor) AtomicLong(java.util.concurrent.atomic.AtomicLong) SegmentOperation(io.pravega.segmentstore.server.SegmentOperation) CachedStreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.CachedStreamSegmentAppendOperation) StorageOperation(io.pravega.segmentstore.server.logs.operations.StorageOperation) StreamSegmentAppendOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentAppendOperation) Preconditions(com.google.common.base.Preconditions) DataCorruptionException(io.pravega.segmentstore.server.DataCorruptionException) ArrayDeque(java.util.ArrayDeque) DeleteSegmentOperation(io.pravega.segmentstore.server.logs.operations.DeleteSegmentOperation) StreamSegmentSealOperation(io.pravega.segmentstore.server.logs.operations.StreamSegmentSealOperation) InputStream(java.io.InputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StorageOperation(io.pravega.segmentstore.server.logs.operations.StorageOperation) WriterFlushResult(io.pravega.segmentstore.server.WriterFlushResult) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties)

Aggregations

TimeoutTimer (io.pravega.common.TimeoutTimer)97 lombok.val (lombok.val)55 CompletableFuture (java.util.concurrent.CompletableFuture)52 Duration (java.time.Duration)51 Futures (io.pravega.common.concurrent.Futures)47 Preconditions (com.google.common.base.Preconditions)41 CompletionException (java.util.concurrent.CompletionException)41 Slf4j (lombok.extern.slf4j.Slf4j)41 Collectors (java.util.stream.Collectors)40 SneakyThrows (lombok.SneakyThrows)40 Exceptions (io.pravega.common.Exceptions)39 BufferView (io.pravega.common.util.BufferView)37 Getter (lombok.Getter)37 SegmentProperties (io.pravega.segmentstore.contracts.SegmentProperties)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)36 StreamSegmentNotExistsException (io.pravega.segmentstore.contracts.StreamSegmentNotExistsException)34 SegmentMetadata (io.pravega.segmentstore.server.SegmentMetadata)34 RequiredArgsConstructor (lombok.RequiredArgsConstructor)34 ArrayList (java.util.ArrayList)33 List (java.util.List)31