Search in sources :

Example 56 with BufferView

use of io.pravega.common.util.BufferView in project pravega by pravega.

the class AsyncReadResultProcessorTests method testProcessAll.

/**
 * Tests the {@link AsyncReadResultProcessor#processAll} method.
 */
@Test
public void testProcessAll() throws Exception {
    // Pre-generate some entries.
    ArrayList<byte[]> entries = new ArrayList<>();
    int totalLength = generateEntries(entries);
    // Setup an entry provider supplier.
    AtomicInteger currentIndex = new AtomicInteger();
    StreamSegmentReadResult.NextEntrySupplier supplier = (offset, length, makeCopy) -> {
        int idx = currentIndex.getAndIncrement();
        if (idx == entries.size() - 1) {
            // Future read result.
            Supplier<BufferView> entryContentsSupplier = () -> new ByteArraySegment(entries.get(idx));
            return new TestFutureReadResultEntry(offset, length, entryContentsSupplier, executorService());
        } else if (idx >= entries.size()) {
            return null;
        }
        // Normal read.
        return new CacheReadResultEntry(offset, entries.get(idx), 0, entries.get(idx).length);
    };
    // Fetch all the data and compare with expected.
    @Cleanup StreamSegmentReadResult rr = new StreamSegmentReadResult(0, totalLength, supplier, "");
    val result = AsyncReadResultProcessor.processAll(rr, executorService(), TIMEOUT);
    val actualData = result.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS).getReader();
    val expectedData = new SequenceInputStream(Iterators.asEnumeration(entries.stream().map(ByteArrayInputStream::new).iterator()));
    AssertExtensions.assertStreamEquals("Unexpected data read back.", expectedData, actualData, totalLength);
}
Also used : AssertExtensions(io.pravega.test.common.AssertExtensions) Exceptions(io.pravega.common.Exceptions) Cleanup(lombok.Cleanup) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) Timeout(org.junit.rules.Timeout) Executor(java.util.concurrent.Executor) SequenceInputStream(java.io.SequenceInputStream) Semaphore(java.util.concurrent.Semaphore) IntentionalException(io.pravega.test.common.IntentionalException) lombok.val(lombok.val) Test(org.junit.Test) ReadResultEntryType(io.pravega.segmentstore.contracts.ReadResultEntryType) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Rule(org.junit.Rule) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) Assert(org.junit.Assert) Futures(io.pravega.common.concurrent.Futures) lombok.val(lombok.val) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ArrayList(java.util.ArrayList) Cleanup(lombok.Cleanup) SequenceInputStream(java.io.SequenceInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Supplier(java.util.function.Supplier) Test(org.junit.Test)

Example 57 with BufferView

use of io.pravega.common.util.BufferView in project pravega by pravega.

the class DirectMemoryCache method insert.

@Override
public int insert(BufferView data) {
    Exceptions.checkNotClosed(this.closed.get(), this);
    Preconditions.checkArgument(data.getLength() <= CacheLayout.MAX_ENTRY_SIZE, "Entry too long. Expected max %s, given %s.", CacheLayout.MAX_ENTRY_SIZE, data.getLength());
    int lastBlockAddress = CacheLayout.NO_ADDRESS;
    int remainingLength = data.getLength();
    try {
        // and write the remaining data to it.
        while (remainingLength > 0 || lastBlockAddress == CacheLayout.NO_ADDRESS) {
            // Get a Buffer to write data to. If we are full, this will throw an appropriate exception.
            DirectMemoryBuffer buffer = getNextAvailableBuffer();
            // Write the data to the buffer.
            BufferView slice = data.slice(data.getLength() - remainingLength, remainingLength);
            DirectMemoryBuffer.WriteResult writeResult = buffer.write(slice, lastBlockAddress);
            if (writeResult == null) {
                // Someone else grabbed this buffer and wrote to it before we got a chance. Go back and find another one.
                continue;
            }
            // invoking delete() will undo this changes as well.
            assert writeResult.getWrittenLength() >= 0 && writeResult.getWrittenLength() <= remainingLength : writeResult.getWrittenLength();
            remainingLength -= writeResult.getWrittenLength();
            this.storedBytes.addAndGet(writeResult.getWrittenLength());
            lastBlockAddress = writeResult.getLastBlockAddress();
        }
    } catch (Throwable ex) {
        if (!Exceptions.mustRethrow(ex) && lastBlockAddress != CacheLayout.NO_ADDRESS) {
            // We wrote something, but got interrupted. We need to clean up whatever we wrote so we don't leave
            // unreferenced data in the cache.
            delete(lastBlockAddress);
        }
        throw ex;
    }
    this.metrics.insert(data.getLength());
    return lastBlockAddress;
}
Also used : BufferView(io.pravega.common.util.BufferView)

Example 58 with BufferView

use of io.pravega.common.util.BufferView in project pravega by pravega.

the class FixedKeyLengthTableSegmentLayout method get.

@Override
CompletableFuture<List<TableEntry>> get(@NonNull DirectSegmentAccess segment, @NonNull List<BufferView> keys, TimeoutTimer timer) {
    val segmentInfo = segment.getInfo();
    ensureSegmentType(segmentInfo.getName(), segmentInfo.getType());
    val attributes = keys.stream().map(key -> {
        ensureValidKeyLength(segmentInfo.getName(), key.getLength());
        return AttributeId.from(key.getCopy());
    }).collect(Collectors.toList());
    logRequest("get", segmentInfo.getName(), keys.size());
    return getByAttributes(segment, attributes, timer);
}
Also used : lombok.val(lombok.val) 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)

Example 59 with BufferView

use of io.pravega.common.util.BufferView in project pravega by pravega.

the class SegmentAggregator method getFlushData.

/**
 * Returns a {@link BufferView} which contains the data needing to be flushed to Storage.
 *
 * @return A {@link BufferView} to flush or null if the segment was deleted.
 * @throws DataCorruptionException If a unable to retrieve required data from the Data Source.
 */
@Nullable
private BufferView getFlushData() throws DataCorruptionException {
    StorageOperation first = this.operations.getFirst();
    if (!(first instanceof AggregatedAppendOperation)) {
        // Nothing to flush - first operation is not an AggregatedAppend.
        return null;
    }
    AggregatedAppendOperation appendOp = (AggregatedAppendOperation) first;
    int length = (int) appendOp.getLength();
    BufferView data = null;
    if (length > 0) {
        data = this.dataSource.getAppendData(appendOp.getStreamSegmentId(), appendOp.getStreamSegmentOffset(), length);
        if (data == null) {
            if (this.metadata.isDeleted()) {
                // Segment was deleted - nothing more to do.
                return null;
            }
            throw new DataCorruptionException(String.format("Unable to retrieve CacheContents for '%s'.", appendOp));
        }
    }
    appendOp.seal();
    return data;
}
Also used : BufferView(io.pravega.common.util.BufferView) StorageOperation(io.pravega.segmentstore.server.logs.operations.StorageOperation) DataCorruptionException(io.pravega.segmentstore.server.DataCorruptionException) Nullable(javax.annotation.Nullable)

Example 60 with BufferView

use of io.pravega.common.util.BufferView in project pravega by pravega.

the class SegmentAggregator method reconcileData.

/**
 * Attempts to reconcile the data for the given AggregatedAppendOperation. Since Append Operations can be partially
 * flushed, reconciliation may be for the full operation or for a part of it.
 *
 * @param op          The AggregatedAppendOperation to reconcile.
 * @param storageInfo The current state of the Segment in Storage.
 * @param timer       Timer for the operation.
 * @return A CompletableFuture containing a FlushResult with the number of bytes reconciled, or failed with a ReconciliationFailureException,
 * if the operation cannot be reconciled, based on the in-memory metadata or the current state of the Segment in Storage.
 */
private CompletableFuture<Integer> reconcileData(AggregatedAppendOperation op, SegmentProperties storageInfo, TimeoutTimer timer) {
    BufferView appendData = this.dataSource.getAppendData(op.getStreamSegmentId(), op.getStreamSegmentOffset(), (int) op.getLength());
    if (appendData == null) {
        return Futures.failedFuture(new ReconciliationFailureException(String.format("Unable to reconcile operation '%s' because no append data is associated with it.", op), this.metadata, storageInfo));
    }
    // Only read as much data as we need.
    long readLength = Math.min(op.getLastStreamSegmentOffset(), storageInfo.getLength()) - op.getStreamSegmentOffset();
    assert readLength > 0 : "Append Operation to be reconciled is beyond the Segment's StorageLength (" + storageInfo.getLength() + "): " + op;
    // Read all data from storage.
    byte[] storageData = new byte[(int) readLength];
    AtomicInteger reconciledBytes = new AtomicInteger();
    return Futures.loop(() -> reconciledBytes.get() < readLength, () -> this.storage.read(this.handle.get(), op.getStreamSegmentOffset() + reconciledBytes.get(), storageData, reconciledBytes.get(), (int) readLength - reconciledBytes.get(), timer.getRemaining()), bytesRead -> {
        assert bytesRead > 0 : String.format("Unable to make any read progress when reconciling operation '%s' after reading %s bytes.", op, reconciledBytes);
        reconciledBytes.addAndGet(bytesRead);
    }, this.executor).thenApplyAsync(v -> {
        // Compare, byte-by-byte, the contents of the append.
        verifySame(appendData, storageData, op, storageInfo);
        return reconciledBytes.get();
    }, this.executor);
}
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) BufferView(io.pravega.common.util.BufferView) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Aggregations

BufferView (io.pravega.common.util.BufferView)77 ArrayList (java.util.ArrayList)49 lombok.val (lombok.val)49 ByteArraySegment (io.pravega.common.util.ByteArraySegment)44 Cleanup (lombok.Cleanup)42 Duration (java.time.Duration)39 Test (org.junit.Test)39 List (java.util.List)37 CompletableFuture (java.util.concurrent.CompletableFuture)34 AssertExtensions (io.pravega.test.common.AssertExtensions)29 HashMap (java.util.HashMap)29 Assert (org.junit.Assert)29 ThreadPooledTestSuite (io.pravega.test.common.ThreadPooledTestSuite)28 TimeUnit (java.util.concurrent.TimeUnit)28 AtomicReference (java.util.concurrent.atomic.AtomicReference)26 Collectors (java.util.stream.Collectors)26 AtomicLong (java.util.concurrent.atomic.AtomicLong)25 Exceptions (io.pravega.common.Exceptions)24 TableEntry (io.pravega.segmentstore.contracts.tables.TableEntry)24 Map (java.util.Map)22