Search in sources :

Example 16 with TableEntry

use of io.pravega.segmentstore.contracts.tables.TableEntry in project pravega by pravega.

the class TableBasedMetadataStore method writeAll.

/**
 * Writes transaction data from a given list to the metadata store.
 *
 * @param dataList List of transaction data to write.
 */
@Override
protected CompletableFuture<Void> writeAll(Collection<TransactionData> dataList) {
    val toUpdate = new ArrayList<TableEntry>();
    val entryToTxnDataMap = new HashMap<TableEntry, TransactionData>();
    val deletedKeyToTxnDataMap = new HashMap<TableKey, TransactionData>();
    val keysToDelete = new ArrayList<TableKey>();
    val t = new Timer();
    return ensureInitialized().thenRunAsync(() -> {
        for (TransactionData txnData : dataList) {
            Preconditions.checkState(null != txnData.getDbObject(), "Missing tracking object");
            val version = (Long) txnData.getDbObject();
            if (null == txnData.getValue()) {
                val toDelete = TableKey.unversioned(new ByteArraySegment(txnData.getKey().getBytes(Charsets.UTF_8)));
                keysToDelete.add(toDelete);
                deletedKeyToTxnDataMap.put(toDelete, txnData);
            }
            try {
                val arraySegment = SERIALIZER.serialize(txnData);
                TableEntry tableEntry = TableEntry.versioned(new ByteArraySegment(txnData.getKey().getBytes(Charsets.UTF_8)), arraySegment, version);
                entryToTxnDataMap.put(tableEntry, txnData);
                toUpdate.add(tableEntry);
            } catch (Exception e) {
                throw new CompletionException(handleException(e));
            }
        }
    }, getExecutor()).thenComposeAsync(v -> {
        // toUpdate includes both modified keys as well updates to deleted keys to mark them as deleted.
        return this.tableStore.put(tableName, toUpdate, timeout).thenComposeAsync(ret -> {
            // Update versions.
            int i = 0;
            for (TableEntry tableEntry : toUpdate) {
                entryToTxnDataMap.get(tableEntry).setDbObject(ret.get(i));
                i++;
            }
            // This next step will just remove them from table store.
            return this.tableStore.remove(tableName, keysToDelete, timeout).handleAsync((v1, ex) -> {
                // keys are already persisted successfully in earlier step.
                if (ex == null) {
                    deletedKeyToTxnDataMap.values().stream().forEach(txnData -> txnData.setDbObject(TableKey.NOT_EXISTS));
                } else {
                    log.warn("Error while deleting keys from table segment {}.", tableName, ex);
                }
                TABLE_WRITE_LATENCY.reportSuccessEvent(t.getElapsed());
                return v1;
            }, getExecutor());
        }, getExecutor());
    }, getExecutor()).exceptionally(e -> {
        val ex = Exceptions.unwrap(e);
        throw new CompletionException(handleException(ex));
    });
}
Also used : lombok.val(lombok.val) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) Getter(lombok.Getter) TableStore(io.pravega.segmentstore.contracts.tables.TableStore) Spliterators(java.util.Spliterators) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ChunkedSegmentStorageConfig(io.pravega.segmentstore.storage.chunklayer.ChunkedSegmentStorageConfig) TABLE_WRITE_LATENCY(io.pravega.segmentstore.storage.metadata.StorageMetadataMetrics.TABLE_WRITE_LATENCY) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) IteratorArgs(io.pravega.segmentstore.contracts.tables.IteratorArgs) ArrayList(java.util.ArrayList) SegmentType(io.pravega.segmentstore.contracts.SegmentType) IteratorItem(io.pravega.segmentstore.contracts.tables.IteratorItem) BufferView(io.pravega.common.util.BufferView) Duration(java.time.Duration) StreamSupport(java.util.stream.StreamSupport) METADATA_FOUND_IN_STORE(io.pravega.segmentstore.storage.metadata.StorageMetadataMetrics.METADATA_FOUND_IN_STORE) METADATA_NOT_FOUND(io.pravega.segmentstore.storage.metadata.StorageMetadataMetrics.METADATA_NOT_FOUND) Charsets(com.google.common.base.Charsets) TABLE_GET_LATENCY(io.pravega.segmentstore.storage.metadata.StorageMetadataMetrics.TABLE_GET_LATENCY) TableKey(io.pravega.segmentstore.contracts.tables.TableKey) Executor(java.util.concurrent.Executor) Collection(java.util.Collection) lombok.val(lombok.val) AsyncIterator(io.pravega.common.util.AsyncIterator) CompletionException(java.util.concurrent.CompletionException) DataLogWriterNotPrimaryException(io.pravega.segmentstore.storage.DataLogWriterNotPrimaryException) Timer(io.pravega.common.Timer) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) ByteArraySegment(io.pravega.common.util.ByteArraySegment) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) Spliterator(java.util.Spliterator) ByteArraySegment(io.pravega.common.util.ByteArraySegment) Timer(io.pravega.common.Timer) HashMap(java.util.HashMap) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) CompletionException(java.util.concurrent.CompletionException) DataLogWriterNotPrimaryException(io.pravega.segmentstore.storage.DataLogWriterNotPrimaryException) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException)

Example 17 with TableEntry

use of io.pravega.segmentstore.contracts.tables.TableEntry in project pravega by pravega.

the class TableBasedMetadataStoreMockTests method testRandomExceptionDuringRead.

@Test
public void testRandomExceptionDuringRead() {
    TableStore mockTableStore = mock(TableStore.class);
    @Cleanup TableBasedMetadataStore tableBasedMetadataStore = new TableBasedMetadataStore("test", mockTableStore, ChunkedSegmentStorageConfig.DEFAULT_CONFIG, executorService());
    when(mockTableStore.createSegment(any(), any(), any())).thenReturn(Futures.failedFuture(new CompletionException(new StreamSegmentExistsException("test"))));
    // Throw random exception
    Exception e = new ArithmeticException();
    val f = new CompletableFuture<List<TableEntry>>();
    f.completeExceptionally(e);
    when(mockTableStore.get(anyString(), any(), any())).thenReturn(f);
    AssertExtensions.assertFutureThrows("read should throw an exception", tableBasedMetadataStore.read("test"), ex -> ex instanceof StorageMetadataException && ex.getCause() == e);
}
Also used : lombok.val(lombok.val) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) Cleanup(lombok.Cleanup) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) DataLogWriterNotPrimaryException(io.pravega.segmentstore.storage.DataLogWriterNotPrimaryException) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) TableStore(io.pravega.segmentstore.contracts.tables.TableStore) InMemoryTableStore(io.pravega.segmentstore.storage.mocks.InMemoryTableStore) Test(org.junit.Test)

Example 18 with TableEntry

use of io.pravega.segmentstore.contracts.tables.TableEntry in project pravega by pravega.

the class InMemoryTableStore method entryIterator.

@Override
public CompletableFuture<AsyncIterator<IteratorItem<TableEntry>>> entryIterator(String segmentName, IteratorArgs args) {
    Collection<TableEntry> tableEntries = getTableEntries(segmentName);
    val item = new IteratorItemImpl<>(args.getContinuationToken(), tableEntries);
    return CompletableFuture.completedFuture(AsyncIterator.singleton(item));
}
Also used : TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) lombok.val(lombok.val)

Example 19 with TableEntry

use of io.pravega.segmentstore.contracts.tables.TableEntry in project pravega by pravega.

the class InMemoryTableStore method keyIterator.

@Override
public CompletableFuture<AsyncIterator<IteratorItem<TableKey>>> keyIterator(String segmentName, IteratorArgs args) {
    Collection<TableEntry> tableEntries = getTableEntries(segmentName);
    val item = new IteratorItemImpl<>(args.getContinuationToken(), tableEntries.stream().map(TableEntry::getKey).collect(Collectors.toList()));
    return CompletableFuture.completedFuture(AsyncIterator.singleton(item));
}
Also used : TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) lombok.val(lombok.val)

Example 20 with TableEntry

use of io.pravega.segmentstore.contracts.tables.TableEntry in project pravega by pravega.

the class PravegaRequestProcessor method updateTableEntries.

@Override
public void updateTableEntries(final WireCommands.UpdateTableEntries updateTableEntries) {
    String segment = updateTableEntries.getSegment();
    final String operation = "updateTableEntries";
    if (!verifyToken(segment, updateTableEntries.getRequestId(), updateTableEntries.getDelegationToken(), operation)) {
        updateTableEntries.release();
        return;
    }
    log.debug(updateTableEntries.getRequestId(), "Update Table Segment Entries: Segment={}, Offset={}, Count={}.", updateTableEntries.getSegment(), updateTableEntries.getTableSegmentOffset(), updateTableEntries.getTableEntries().getEntries().size());
    val entries = new ArrayList<TableEntry>(updateTableEntries.getTableEntries().getEntries().size());
    val conditional = new AtomicBoolean(false);
    val size = new AtomicInteger(0);
    for (val e : updateTableEntries.getTableEntries().getEntries()) {
        val v = TableEntry.versioned(new ByteBufWrapper(e.getKey().getData()), new ByteBufWrapper(e.getValue().getData()), e.getKey().getKeyVersion());
        entries.add(v);
        size.addAndGet(v.getKey().getKey().getLength() + v.getValue().getLength());
        if (v.getKey().hasVersion()) {
            conditional.set(true);
        }
    }
    val timer = new Timer();
    this.connection.adjustOutstandingBytes(size.get());
    tableStore.put(segment, entries, updateTableEntries.getTableSegmentOffset(), TIMEOUT).thenAccept(versions -> {
        connection.send(new WireCommands.TableEntriesUpdated(updateTableEntries.getRequestId(), versions));
        this.tableStatsRecorder.updateEntries(updateTableEntries.getSegment(), entries.size(), conditional.get(), timer.getElapsed());
    }).exceptionally(e -> handleException(updateTableEntries.getRequestId(), segment, updateTableEntries.getTableSegmentOffset(), operation, e)).whenComplete((r, ex) -> {
        this.connection.adjustOutstandingBytes(-size.get());
        updateTableEntries.release();
    });
}
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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Timer(io.pravega.common.Timer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ByteBufWrapper(io.pravega.shared.protocol.netty.ByteBufWrapper)

Aggregations

TableEntry (io.pravega.segmentstore.contracts.tables.TableEntry)36 lombok.val (lombok.val)33 ArrayList (java.util.ArrayList)21 BufferView (io.pravega.common.util.BufferView)20 HashMap (java.util.HashMap)18 Test (org.junit.Test)17 TableKey (io.pravega.segmentstore.contracts.tables.TableKey)16 Duration (java.time.Duration)16 Collectors (java.util.stream.Collectors)16 List (java.util.List)15 CompletableFuture (java.util.concurrent.CompletableFuture)15 Cleanup (lombok.Cleanup)15 Map (java.util.Map)14 ByteArraySegment (io.pravega.common.util.ByteArraySegment)13 SegmentType (io.pravega.segmentstore.contracts.SegmentType)13 TableStore (io.pravega.segmentstore.contracts.tables.TableStore)13 Futures (io.pravega.common.concurrent.Futures)12 Collections (java.util.Collections)12 AttributeId (io.pravega.segmentstore.contracts.AttributeId)11 StreamSegmentStore (io.pravega.segmentstore.contracts.StreamSegmentStore)11