Search in sources :

Example 11 with TableSegmentEntry

use of io.pravega.client.tables.impl.TableSegmentEntry in project pravega by pravega.

the class ControllerMetadataGetEntryCommand method execute.

@Override
public void execute() throws Exception {
    Preconditions.checkArgument(getArgCount() >= 3 && getArgCount() < 5, "Incorrect argument count.");
    final String tableName = getArg(0);
    final String key = getArg(1);
    final String segmentStoreHost = getArg(2);
    @Cleanup CuratorFramework zkClient = createZKClient();
    @Cleanup AdminSegmentHelper adminSegmentHelper = instantiateAdminSegmentHelper(zkClient);
    ControllerMetadataSerializer serializer = new ControllerMetadataSerializer(tableName, key);
    TableSegmentEntry entry = getTableEntry(tableName, key, segmentStoreHost, adminSegmentHelper);
    if (entry == null) {
        return;
    }
    val value = serializer.deserialize(getByteBuffer(entry.getValue()));
    output("For the given key: %s", key);
    if (getArgCount() == 4) {
        final String jsonFile = getArg(3);
        ControllerMetadataJsonSerializer jsonSerializer = new ControllerMetadataJsonSerializer();
        @Cleanup FileWriter writer = new FileWriter(createFileAndDirectory(jsonFile));
        writer.write(jsonSerializer.toJson(value));
        writer.flush();
        output("Successfully wrote the value to %s in JSON.", jsonFile);
    } else {
        userFriendlyOutput(value.toString(), serializer.getMetadataType());
    }
}
Also used : lombok.val(lombok.val) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) CuratorFramework(org.apache.curator.framework.CuratorFramework) ControllerMetadataSerializer(io.pravega.cli.admin.serializers.controller.ControllerMetadataSerializer) FileWriter(java.io.FileWriter) ControllerMetadataJsonSerializer(io.pravega.cli.admin.json.ControllerMetadataJsonSerializer) AdminSegmentHelper(io.pravega.cli.admin.utils.AdminSegmentHelper) Cleanup(lombok.Cleanup)

Example 12 with TableSegmentEntry

use of io.pravega.client.tables.impl.TableSegmentEntry in project pravega by pravega.

the class ControllerMetadataUpdateEntryCommand method execute.

@Override
public void execute() throws Exception {
    ensureArgCount(4);
    final String tableName = getArg(0);
    final String key = getArg(1);
    final String newValueFile = getArg(3);
    final String segmentStoreHost = getArg(2);
    @Cleanup CuratorFramework zkClient = createZKClient();
    @Cleanup AdminSegmentHelper adminSegmentHelper = instantiateAdminSegmentHelper(zkClient);
    ControllerMetadataSerializer serializer = new ControllerMetadataSerializer(tableName, key);
    ControllerMetadataJsonSerializer jsonSerializer = new ControllerMetadataJsonSerializer();
    String jsonValue;
    try {
        jsonValue = new String(Files.readAllBytes(Paths.get(newValueFile)));
    } catch (NoSuchFileException e) {
        output("File with new value does not exist: %s", newValueFile);
        return;
    }
    ByteBuffer updatedValue = serializer.serialize(jsonSerializer.fromJson(jsonValue, serializer.getMetadataClass()));
    TableSegmentEntry currentEntry = getTableEntry(tableName, key, segmentStoreHost, adminSegmentHelper);
    if (currentEntry == null) {
        return;
    }
    long currentVersion = currentEntry.getKey().getVersion().getSegmentVersion();
    TableSegmentKeyVersion newVersion = updateTableEntry(tableName, key, updatedValue, currentVersion, segmentStoreHost, adminSegmentHelper);
    if (newVersion == null) {
        return;
    }
    output("Successfully updated the key %s in table %s with version %s", key, tableName, newVersion.getSegmentVersion());
}
Also used : TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) CuratorFramework(org.apache.curator.framework.CuratorFramework) ControllerMetadataSerializer(io.pravega.cli.admin.serializers.controller.ControllerMetadataSerializer) NoSuchFileException(java.nio.file.NoSuchFileException) TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion) ControllerMetadataJsonSerializer(io.pravega.cli.admin.json.ControllerMetadataJsonSerializer) AdminSegmentHelper(io.pravega.cli.admin.utils.AdminSegmentHelper) Cleanup(lombok.Cleanup) ByteBuffer(java.nio.ByteBuffer)

Example 13 with TableSegmentEntry

use of io.pravega.client.tables.impl.TableSegmentEntry in project pravega by pravega.

the class PravegaTablesStoreHelper method updateEntry.

/**
 * Method to update a single entry.
 * @param tableName tablename
 * @param key key
 * @param toBytes to bytes function
 * @param val value
 * @param ver previous key version
 * @param <T> Type of value to be added
 * @param requestId request id
 * @return CompletableFuture which when completed will indicate that the value is updated in the table.
 */
public <T> CompletableFuture<Version> updateEntry(String tableName, String key, T val, Function<T, byte[]> toBytes, Version ver, long requestId) {
    long version = ver.asLongVersion().getLongValue();
    log.trace(requestId, "updateEntry entry called for : {} key : {} version {}", tableName, key, version);
    byte[] value = toBytes.apply(val);
    long time = System.currentTimeMillis();
    List<TableSegmentEntry> entries = Collections.singletonList(TableSegmentEntry.versioned(key.getBytes(Charsets.UTF_8), value, version));
    return withRetries(() -> segmentHelper.updateTableEntries(tableName, entries, authToken.get(), requestId), () -> String.format("updateEntry: key: %s table: %s", key, tableName), true, requestId).thenApplyAsync(x -> {
        TableSegmentKeyVersion first = x.get(0);
        log.debug(requestId, "entry for key {} updated to table {} with new version {}", key, tableName, first.getSegmentVersion());
        Version newVersion = new Version.LongVersion(first.getSegmentVersion());
        putInCache(tableName, key, new VersionedMetadata<>(val, newVersion), time);
        return newVersion;
    }, executor).exceptionally(e -> {
        invalidateCache(tableName, key);
        throw new CompletionException(e);
    }).whenComplete((r, ex) -> releaseEntries(entries));
}
Also used : TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion) Cache(io.pravega.controller.store.stream.Cache) OperationContext(io.pravega.controller.store.stream.OperationContext) SegmentHelper(io.pravega.controller.server.SegmentHelper) BiFunction(java.util.function.BiFunction) Exceptions(io.pravega.common.Exceptions) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) HostStoreException(io.pravega.controller.store.host.HostStoreException) BitConverter(io.pravega.common.util.BitConverter) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) TagLogger(io.pravega.common.tracing.TagLogger) ByteBuf(io.netty.buffer.ByteBuf) StoreException(io.pravega.controller.store.stream.StoreException) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) HashTableIteratorItem(io.pravega.client.tables.impl.HashTableIteratorItem) RetryHelper(io.pravega.controller.util.RetryHelper) Charsets(org.apache.curator.shaded.com.google.common.base.Charsets) TableSegmentKey(io.pravega.client.tables.impl.TableSegmentKey) Predicate(java.util.function.Predicate) Collection(java.util.Collection) AsyncIterator(io.pravega.common.util.AsyncIterator) CompletionException(java.util.concurrent.CompletionException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) StandardCharsets(java.nio.charset.StandardCharsets) ConnectionDropped(io.pravega.controller.server.WireCommandFailedException.Reason.ConnectionDropped) AbstractMap(java.util.AbstractMap) List(java.util.List) ByteArraySegment(io.pravega.common.util.ByteArraySegment) WireCommandFailedException(io.pravega.controller.server.WireCommandFailedException) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) ContinuationTokenAsyncIterator(io.pravega.common.util.ContinuationTokenAsyncIterator) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) Futures(io.pravega.common.concurrent.Futures) ConnectionFailed(io.pravega.controller.server.WireCommandFailedException.Reason.ConnectionFailed) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion) CompletionException(java.util.concurrent.CompletionException) TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion)

Example 14 with TableSegmentEntry

use of io.pravega.client.tables.impl.TableSegmentEntry in project pravega by pravega.

the class PravegaTablesStoreHelper method addNewEntriesIfAbsent.

/**
 * Method to add a batch of entries if absent. Table implementation on segment store guarantees that either all or none of
 * the entries are added.
 * If segment store responds with success, then it is guaranteed that all entries are added to the store.
 * However, it is important to note that the segment store could respond with Data Exists even if one of the entries exists.
 * In such case, this method will ignore data exist and respond with success for the entire batch. It does not verify
 * if all entries existed or one of the entries existed.
 * Callers should use this only if they are guaranteed to never create the requested entries outside of the requested batch.
 *
 * @param tableName table name
 * @param toAdd map of keys and values to add.
 * @param toBytes function to serialize individual values in the list of items to add.
 * @param requestId request id
 * @param <T>       type of values.
 * @return CompletableFuture which when completed successfully will indicate that all entries have been added successfully.
 */
public <T> CompletableFuture<Void> addNewEntriesIfAbsent(String tableName, List<Map.Entry<String, T>> toAdd, Function<T, byte[]> toBytes, long requestId) {
    List<TableSegmentEntry> entries = toAdd.stream().map(x -> TableSegmentEntry.notExists(x.getKey().getBytes(Charsets.UTF_8), toBytes.apply(x.getValue()))).collect(Collectors.toList());
    Supplier<String> errorMessage = () -> String.format("addNewEntriesIfAbsent: table: %s", tableName);
    long time = System.currentTimeMillis();
    return expectingDataExists(withRetries(() -> segmentHelper.updateTableEntries(tableName, entries, authToken.get(), requestId), errorMessage, requestId).handle((r, e) -> {
        releaseEntries(entries);
        if (e != null) {
            Throwable unwrap = Exceptions.unwrap(e);
            toAdd.forEach(entry -> invalidateCache(tableName, entry.getKey()));
            if (unwrap instanceof StoreException.WriteConflictException) {
                throw StoreException.create(StoreException.Type.DATA_EXISTS, errorMessage.get());
            } else {
                log.debug(requestId, "add new entries to {} threw exception {} {}", tableName, unwrap.getClass(), unwrap.getMessage());
                throw new CompletionException(e);
            }
        } else {
            log.debug(requestId, "entries added {} to table {}", toAdd, tableName);
            for (int i = 0; i < r.size(); i++) {
                putInCache(tableName, toAdd.get(i).getKey(), new VersionedMetadata<>(toAdd.get(i).getValue(), new Version.LongVersion(r.get(i).getSegmentVersion())), time);
            }
            return null;
        }
    }), null);
}
Also used : TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion) Cache(io.pravega.controller.store.stream.Cache) OperationContext(io.pravega.controller.store.stream.OperationContext) SegmentHelper(io.pravega.controller.server.SegmentHelper) BiFunction(java.util.function.BiFunction) Exceptions(io.pravega.common.Exceptions) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) HostStoreException(io.pravega.controller.store.host.HostStoreException) BitConverter(io.pravega.common.util.BitConverter) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) TagLogger(io.pravega.common.tracing.TagLogger) ByteBuf(io.netty.buffer.ByteBuf) StoreException(io.pravega.controller.store.stream.StoreException) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) HashTableIteratorItem(io.pravega.client.tables.impl.HashTableIteratorItem) RetryHelper(io.pravega.controller.util.RetryHelper) Charsets(org.apache.curator.shaded.com.google.common.base.Charsets) TableSegmentKey(io.pravega.client.tables.impl.TableSegmentKey) Predicate(java.util.function.Predicate) Collection(java.util.Collection) AsyncIterator(io.pravega.common.util.AsyncIterator) CompletionException(java.util.concurrent.CompletionException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) StandardCharsets(java.nio.charset.StandardCharsets) ConnectionDropped(io.pravega.controller.server.WireCommandFailedException.Reason.ConnectionDropped) AbstractMap(java.util.AbstractMap) List(java.util.List) ByteArraySegment(io.pravega.common.util.ByteArraySegment) WireCommandFailedException(io.pravega.controller.server.WireCommandFailedException) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) ContinuationTokenAsyncIterator(io.pravega.common.util.ContinuationTokenAsyncIterator) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) Futures(io.pravega.common.concurrent.Futures) ConnectionFailed(io.pravega.controller.server.WireCommandFailedException.Reason.ConnectionFailed) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) HostStoreException(io.pravega.controller.store.host.HostStoreException) StoreException(io.pravega.controller.store.stream.StoreException) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion) CompletionException(java.util.concurrent.CompletionException)

Aggregations

TableSegmentEntry (io.pravega.client.tables.impl.TableSegmentEntry)14 TableSegmentKeyVersion (io.pravega.client.tables.impl.TableSegmentKeyVersion)8 List (java.util.List)8 HashTableIteratorItem (io.pravega.client.tables.impl.HashTableIteratorItem)7 TableSegmentKey (io.pravega.client.tables.impl.TableSegmentKey)7 PravegaNodeUri (io.pravega.shared.protocol.netty.PravegaNodeUri)7 Map (java.util.Map)7 Collectors (java.util.stream.Collectors)7 Unpooled (io.netty.buffer.Unpooled)6 Futures (io.pravega.common.concurrent.Futures)6 ByteArraySegment (io.pravega.common.util.ByteArraySegment)6 UUID (java.util.UUID)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)5 Exceptions (io.pravega.common.Exceptions)5 TagLogger (io.pravega.common.tracing.TagLogger)5 Preconditions (com.google.common.base.Preconditions)4 ConnectionPool (io.pravega.client.connection.impl.ConnectionPool)4 SegmentHelper (io.pravega.controller.server.SegmentHelper)4