Search in sources :

Example 26 with BufferView

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

the class S3Mock method putObject.

public void putObject(String bucketName, String key, Range range, Object content) {
    String objectName = getObjectName(bucketName, key);
    synchronized (this.objects) {
        ObjectData od = this.objects.get(objectName);
        if (od == null) {
            throw new S3Exception(String.format("Object '%s/%s' does not exist.", bucketName, key), 404, "NoSuchKey", key);
        }
        final int startOffset = (int) (long) range.getFirst();
        final int length = (int) (range.getLast() + 1 - range.getFirst());
        BufferView objectContent = od.content;
        if (startOffset < objectContent.getLength()) {
            objectContent = new ByteArraySegment(objectContent.slice(0, startOffset).getCopy());
        } else if (startOffset > objectContent.getLength()) {
            throw new S3Exception("", HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "InvalidRange", "");
        }
        InputStream source = (InputStream) content;
        byte[] buffer = new byte[length];
        try {
            int copyLength = StreamHelpers.readAll(source, buffer, 0, length);
            assert copyLength == length;
        } catch (IOException ex) {
            throw new S3Exception("Copy error", HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
        od.content = BufferView.wrap(Arrays.asList(objectContent, new ByteArraySegment(buffer)));
    }
}
Also used : ByteArraySegment(io.pravega.common.util.ByteArraySegment) BufferView(io.pravega.common.util.BufferView) S3Exception(com.emc.object.s3.S3Exception) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 27 with BufferView

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

the class ReadResult method readRemaining.

/**
 * Reads the remaining contents of the ReadResult into the given array. This will stop when the given target has been
 * filled or when the current end of the Segment has been reached.
 *
 * @param target       A byte array where the ReadResult will be read into.
 * @param fetchTimeout A timeout to use when needing to fetch the contents of an entry that is not in the Cache.
 * @return The number of bytes read.
 */
@VisibleForTesting
default int readRemaining(byte[] target, Duration fetchTimeout) {
    int bytesRead = 0;
    while (hasNext() && bytesRead < target.length) {
        ReadResultEntry entry = next();
        if (entry.getType() == ReadResultEntryType.EndOfStreamSegment || entry.getType() == ReadResultEntryType.Future) {
            // Reached the end.
            break;
        } else if (!entry.getContent().isDone()) {
            entry.requestContent(fetchTimeout);
        }
        BufferView contents = entry.getContent().join();
        int copied = contents.copyTo(ByteBuffer.wrap(target, bytesRead, Math.min(contents.getLength(), target.length - bytesRead)));
        bytesRead += copied;
    }
    return bytesRead;
}
Also used : BufferView(io.pravega.common.util.BufferView) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 28 with BufferView

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

the class PravegaRequestProcessor method readTableEntriesDelta.

@Override
public void readTableEntriesDelta(WireCommands.ReadTableEntriesDelta readTableEntriesDelta) {
    final String segment = readTableEntriesDelta.getSegment();
    final String operation = "readTableEntriesDelta";
    if (!verifyToken(segment, readTableEntriesDelta.getRequestId(), readTableEntriesDelta.getDelegationToken(), operation)) {
        return;
    }
    final int suggestedEntryCount = readTableEntriesDelta.getSuggestedEntryCount();
    final long fromPosition = readTableEntriesDelta.getFromPosition();
    log.info(readTableEntriesDelta.getRequestId(), "Iterate Table Entries Delta: Segment={} Count={} FromPositon={}.", readTableEntriesDelta.getSegment(), readTableEntriesDelta.getSuggestedEntryCount(), readTableEntriesDelta.getFromPosition());
    val timer = new Timer();
    val result = new DeltaIteratorResult<BufferView, Map.Entry<WireCommands.TableKey, WireCommands.TableValue>>(segment.getBytes().length + WireCommands.TableEntriesRead.HEADER_BYTES);
    tableStore.entryDeltaIterator(segment, fromPosition, TIMEOUT).thenCompose(itr -> itr.collectRemaining(e -> {
        if (result.getItemCount() >= suggestedEntryCount || result.getSizeBytes() >= MAX_READ_SIZE) {
            return false;
        }
        TableEntry entry = e.getEntries().iterator().next();
        DeltaIteratorState state = DeltaIteratorState.deserialize(e.getState());
        // Store all TableEntries.
        val k = new WireCommands.TableKey(toByteBuf(entry.getKey().getKey()), entry.getKey().getVersion());
        val v = new WireCommands.TableValue(toByteBuf(entry.getValue()));
        if (state.isDeletionRecord()) {
            result.remove(entry.getKey().getKey(), k.size() + v.size());
        } else {
            Map.Entry<WireCommands.TableKey, WireCommands.TableValue> old = result.getItem(entry.getKey().getKey());
            if (old != null && old.getKey().getKeyVersion() < entry.getKey().getVersion()) {
                int sizeBytes = (k.size() + v.size()) - (old.getKey().size() + old.getValue().size());
                result.add(entry.getKey().getKey(), new AbstractMap.SimpleImmutableEntry<>(k, v), sizeBytes);
            } else {
                result.add(entry.getKey().getKey(), new AbstractMap.SimpleImmutableEntry<>(k, v), k.size() + v.size());
            }
        }
        result.setState(state);
        // Update total read data.
        return true;
    })).thenAccept(v -> {
        log.debug(readTableEntriesDelta.getRequestId(), "Iterate Table Segment Entries Delta complete ({}).", result.getItemCount());
        connection.send(new WireCommands.TableEntriesDeltaRead(readTableEntriesDelta.getRequestId(), segment, new WireCommands.TableEntries(result.getItems()), result.getState().isShouldClear(), result.getState().isReachedEnd(), result.getState().getFromPosition()));
        this.tableStatsRecorder.iterateEntries(readTableEntriesDelta.getSegment(), result.getItemCount(), timer.getElapsed());
    }).exceptionally(e -> handleException(readTableEntriesDelta.getRequestId(), segment, operation, e));
}
Also used : lombok.val(lombok.val) 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) DeltaIteratorState(io.pravega.segmentstore.server.tables.DeltaIteratorState) TableKey(io.pravega.segmentstore.contracts.tables.TableKey) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) Timer(io.pravega.common.Timer) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Map(java.util.Map) HashMap(java.util.HashMap) AbstractMap(java.util.AbstractMap)

Example 29 with BufferView

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

the class PravegaRequestProcessor method collectCachedEntries.

/**
 * Reads all of the cachedEntries from the ReadResult and puts their content into the cachedEntries list.
 * Upon encountering a non-cached entry, it stops iterating and returns it.
 */
private ReadResultEntry collectCachedEntries(long initialOffset, ReadResult readResult, ArrayList<BufferView> cachedEntries) {
    long expectedOffset = initialOffset;
    while (readResult.hasNext()) {
        ReadResultEntry entry = readResult.next();
        if (entry.getType() == Cache) {
            Preconditions.checkState(entry.getStreamSegmentOffset() == expectedOffset, "Data returned from read was not contiguous.");
            BufferView content = entry.getContent().getNow(null);
            expectedOffset += content.getLength();
            cachedEntries.add(content);
        } else {
            return entry;
        }
    }
    return null;
}
Also used : BufferView(io.pravega.common.util.BufferView) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry)

Example 30 with BufferView

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

the class StreamSegmentReadIndex method getMultiReadResultEntry.

/**
 * Returns a ReadResultEntry that matches the specified search parameters.
 * <p>
 * Compared to getSingleMemoryReadResultEntry(), this method may return a direct entry or a collection of entries.
 * If the first entry to be returned would constitute a cache hit, then this method will attempt to return data from
 * subsequent (congruent) entries, as long as they are cache hits. If at any time a cache miss occurs, the data collected
 * so far is returned as a single entry, excluding the cache miss entry (exception if the first entry is a miss,
 * then that entry is returned).
 *
 * @param resultStartOffset The Offset within the StreamSegment where to start returning data from.
 * @param maxLength         The maximum number of bytes to return.
 * @param makeCopy          If true, any data retrieved from the Cache will be copied into a Heap buffer before being returned.
 * @return A ReadResultEntry representing the data to return.
 */
private CompletableReadResultEntry getMultiReadResultEntry(long resultStartOffset, int maxLength, boolean makeCopy) {
    int readLength = 0;
    CompletableReadResultEntry nextEntry = getSingleReadResultEntry(resultStartOffset, maxLength, makeCopy);
    if (nextEntry == null || !(nextEntry instanceof CacheReadResultEntry)) {
        // We can only coalesce CacheReadResultEntries.
        return nextEntry;
    }
    // Collect the contents of congruent Index Entries into a list, as long as we still encounter data in the cache.
    ArrayList<BufferView> contents = new ArrayList<>();
    do {
        assert Futures.isSuccessful(nextEntry.getContent()) : "Found CacheReadResultEntry that is not completed yet: " + nextEntry;
        val entryContents = nextEntry.getContent().join();
        contents.add(entryContents);
        readLength += entryContents.getLength();
        if (readLength >= this.config.getMemoryReadMinLength() || readLength >= maxLength) {
            break;
        }
        nextEntry = getSingleMemoryReadResultEntry(resultStartOffset + readLength, maxLength - readLength, makeCopy);
    } while (nextEntry != null);
    // Coalesce the results into a single InputStream and return the result.
    return new CacheReadResultEntry(resultStartOffset, BufferView.wrap(contents));
}
Also used : lombok.val(lombok.val) BufferView(io.pravega.common.util.BufferView) ArrayList(java.util.ArrayList)

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