Search in sources :

Example 21 with OperationContext

use of io.pravega.controller.store.stream.OperationContext in project pravega by pravega.

the class DeleteStreamTask method deleteAssociatedStreams.

private CompletableFuture<Void> deleteAssociatedStreams(String scope, String stream, long requestId) {
    String markStream = NameUtils.getMarkStreamForStream(stream);
    OperationContext context = streamMetadataStore.createStreamContext(scope, markStream, requestId);
    return Futures.exceptionallyExpecting(notifyAndDelete(context, scope, markStream, requestId), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, null);
}
Also used : OperationContext(io.pravega.controller.store.stream.OperationContext) StoreException(io.pravega.controller.store.stream.StoreException)

Example 22 with OperationContext

use of io.pravega.controller.store.stream.OperationContext in project pravega by pravega.

the class ScaleOperationTask method execute.

@Override
public CompletableFuture<Void> execute(final ScaleOpEvent request) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    long requestId = request.getRequestId();
    final OperationContext context = streamMetadataStore.createStreamContext(request.getScope(), request.getStream(), requestId);
    log.info(requestId, "starting scale request for {}/{} segments {} to new ranges {}", request.getScope(), request.getStream(), request.getSegmentsToSeal(), request.getNewRanges());
    runScale(request, request.isRunOnlyIfStarted(), context).whenCompleteAsync((res, e) -> {
        if (e != null) {
            Throwable cause = Exceptions.unwrap(e);
            if (cause instanceof RetriesExhaustedException) {
                cause = cause.getCause();
            }
            if (cause instanceof EpochTransitionOperationExceptions.PreConditionFailureException) {
                log.info(requestId, "processing scale request for {}/{} segments {} failed {}", request.getScope(), request.getStream(), request.getSegmentsToSeal(), cause.getClass().getName());
                result.complete(null);
            } else {
                log.warn(requestId, "processing scale request for {}/{} segments {} failed {}", request.getScope(), request.getStream(), request.getSegmentsToSeal(), cause);
                result.completeExceptionally(cause);
            }
        } else {
            log.info(requestId, "scale request for {}/{} segments {} to new ranges {} completed successfully.", request.getScope(), request.getStream(), request.getSegmentsToSeal(), request.getNewRanges());
            result.complete(null);
        }
    }, executor);
    return result;
}
Also used : OperationContext(io.pravega.controller.store.stream.OperationContext) CompletableFuture(java.util.concurrent.CompletableFuture) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException)

Example 23 with OperationContext

use of io.pravega.controller.store.stream.OperationContext in project pravega by pravega.

the class PravegaTablesScope method readAll.

private CompletableFuture<Pair<List<String>, String>> readAll(int limit, String continuationToken, String tableName, OperationContext context) {
    List<String> taken = new ArrayList<>();
    AtomicReference<String> token = new AtomicReference<>(continuationToken);
    AtomicBoolean canContinue = new AtomicBoolean(true);
    return Futures.exceptionallyExpecting(storeHelper.getKeysPaginated(tableName, Unpooled.wrappedBuffer(Base64.getDecoder().decode(token.get())), limit, context.getRequestId()).thenApply(result -> {
        if (result.getValue().isEmpty()) {
            canContinue.set(false);
        } else {
            taken.addAll(result.getValue());
        }
        token.set(Base64.getEncoder().encodeToString(result.getKey().array()));
        return new ImmutablePair<>(taken, token.get());
    }), DATA_NOT_FOUND_PREDICATE, new ImmutablePair<>(Collections.emptyList(), token.get()));
}
Also used : IntStream(java.util.stream.IntStream) OperationContext(io.pravega.controller.store.stream.OperationContext) Exceptions(io.pravega.common.Exceptions) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NameUtils.getQualifiedTableName(io.pravega.shared.NameUtils.getQualifiedTableName) CompletableFuture(java.util.concurrent.CompletableFuture) DATA_NOT_FOUND_PREDICATE(io.pravega.controller.store.stream.PravegaTablesStreamMetadataStore.DATA_NOT_FOUND_PREDICATE) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) TagLogger(io.pravega.common.tracing.TagLogger) StoreException(io.pravega.controller.store.stream.StoreException) Pair(org.apache.commons.lang3.tuple.Pair) SEPARATOR(io.pravega.shared.NameUtils.SEPARATOR) HashHelper(io.pravega.common.hash.HashHelper) Executor(java.util.concurrent.Executor) BYTES_TO_UUID_FUNCTION(io.pravega.controller.store.PravegaTablesStoreHelper.BYTES_TO_UUID_FUNCTION) lombok.val(lombok.val) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) INTERNAL_SCOPE_NAME(io.pravega.shared.NameUtils.INTERNAL_SCOPE_NAME) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) StandardCharsets(java.nio.charset.StandardCharsets) UUID_TO_BYTES_FUNCTION(io.pravega.controller.store.PravegaTablesStoreHelper.UUID_TO_BYTES_FUNCTION) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) TagRecord(io.pravega.controller.store.stream.records.TagRecord) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) SCOPES_TABLE(io.pravega.controller.store.stream.PravegaTablesStreamMetadataStore.SCOPES_TABLE) Preconditions(com.google.common.base.Preconditions) Collections(java.util.Collections) Futures(io.pravega.common.concurrent.Futures) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 24 with OperationContext

use of io.pravega.controller.store.stream.OperationContext in project pravega by pravega.

the class TableMetadataTasks method createKeyValueTable.

/**
 *  Create a Key-Value Table.
 *
 * @param scope      scope name.
 * @param kvtName    KVTable name.
 * @param kvtConfig  KVTable configuration.
 * @param createTimestamp  KVTable creation timestamp.
 * @param requestId  request id
 * @return update status.
 */
public CompletableFuture<CreateKeyValueTableStatus.Status> createKeyValueTable(String scope, String kvtName, KeyValueTableConfiguration kvtConfig, final long createTimestamp, long requestId) {
    OperationContext context = kvtMetadataStore.createContext(scope, kvtName, requestId);
    return RetryHelper.withRetriesAsync(() -> {
        // 1. check if scope with this name exists...
        return kvtMetadataStore.checkScopeExists(scope, context, executor).thenCompose(exists -> {
            if (!exists) {
                return CompletableFuture.completedFuture(CreateKeyValueTableStatus.Status.SCOPE_NOT_FOUND);
            }
            return kvtMetadataStore.isScopeSealed(scope, context, executor).thenCompose(isScopeSealed -> {
                if (isScopeSealed) {
                    return CompletableFuture.completedFuture(CreateKeyValueTableStatus.Status.SCOPE_NOT_FOUND);
                }
                // 2. check state of the KVTable, if found
                return Futures.exceptionallyExpecting(kvtMetadataStore.getState(scope, kvtName, true, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, KVTableState.UNKNOWN).thenCompose(state -> {
                    if (state.equals(KVTableState.UNKNOWN) || state.equals(KVTableState.CREATING)) {
                        // 3. get a new UUID for the KVTable we will be creating.
                        UUID id = kvtMetadataStore.newScope(scope).newId();
                        CreateTableEvent event = new CreateTableEvent(scope, kvtName, kvtConfig.getPartitionCount(), kvtConfig.getPrimaryKeyLength(), kvtConfig.getSecondaryKeyLength(), createTimestamp, requestId, id, kvtConfig.getRolloverSizeBytes());
                        // 4. Update ScopeTable with the entry for this KVT and Publish the event for creation
                        return eventHelper.addIndexAndSubmitTask(event, () -> kvtMetadataStore.createEntryForKVTable(scope, kvtName, id, context, executor)).thenCompose(x -> isCreateProcessed(scope, kvtName, kvtConfig, createTimestamp, executor, context));
                    }
                    log.info(requestId, "KeyValue table {}/{} already exists", scope, kvtName);
                    return isCreateProcessed(scope, kvtName, kvtConfig, createTimestamp, executor, context);
                });
            });
        });
    }, e -> Exceptions.unwrap(e) instanceof RetryableException, NUM_RETRIES, executor);
}
Also used : OperationContext(io.pravega.controller.store.stream.OperationContext) OperationContext(io.pravega.controller.store.stream.OperationContext) ControllerEventProcessors(io.pravega.controller.server.eventProcessor.ControllerEventProcessors) SegmentHelper(io.pravega.controller.server.SegmentHelper) Exceptions(io.pravega.common.Exceptions) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) KeyValueTableConfiguration(io.pravega.client.tables.KeyValueTableConfiguration) CreateTableEvent(io.pravega.shared.controller.event.kvtable.CreateTableEvent) TagLogger(io.pravega.common.tracing.TagLogger) DeleteKVTableStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteKVTableStatus) StoreException(io.pravega.controller.store.stream.StoreException) TaskStepsRetryHelper.withRetries(io.pravega.controller.task.Stream.TaskStepsRetryHelper.withRetries) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EventHelper(io.pravega.controller.task.EventHelper) EventStreamClientFactory(io.pravega.client.EventStreamClientFactory) DeleteTableEvent(io.pravega.shared.controller.event.kvtable.DeleteTableEvent) NameUtils.getQualifiedTableSegmentName(io.pravega.shared.NameUtils.getQualifiedTableSegmentName) RetryHelper(io.pravega.controller.util.RetryHelper) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) AbstractKVTableMetadataStore(io.pravega.controller.store.kvtable.AbstractKVTableMetadataStore) Synchronized(lombok.Synchronized) Executor(java.util.concurrent.Executor) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) KVTableMetadataStore(io.pravega.controller.store.kvtable.KVTableMetadataStore) List(java.util.List) RetryableException(io.pravega.controller.retryable.RetryableException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) CreateKeyValueTableStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateKeyValueTableStatus) Futures(io.pravega.common.concurrent.Futures) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) KVTableState(io.pravega.controller.store.kvtable.KVTableState) CreateTableEvent(io.pravega.shared.controller.event.kvtable.CreateTableEvent) RetryableException(io.pravega.controller.retryable.RetryableException) UUID(java.util.UUID)

Example 25 with OperationContext

use of io.pravega.controller.store.stream.OperationContext in project pravega by pravega.

the class StreamMetadataTasks method deleteStream.

public CompletableFuture<DeleteStreamStatus.Status> deleteStream(final String scope, final String stream, final OperationContext context) {
    Preconditions.checkNotNull(context, "Operation Context is null");
    // We can delete streams only if they are sealed. However, for partially created streams, they could be in different
    // stages of partial creation and we should be able to clean them up.
    // Case 1: A partially created stream may just have some initial metadata created, in which case the Stream's state may not
    // have been set up it may be present under the scope.
    // In this case we can simply delete all metadata for the stream directly.
    // Case 2: A partially created stream could be in state CREATING, in which case it would definitely have metadata created
    // and possibly segments too. This requires same clean up as for a sealed stream - metadata + segments.
    // So we will submit delete workflow.
    long requestId = context.getRequestId();
    return eventHelperFuture.thenCompose(eventHelper -> Futures.exceptionallyExpecting(streamMetadataStore.getState(scope, stream, false, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, State.UNKNOWN).thenCompose(state -> {
        if (State.SEALED.equals(state) || State.CREATING.equals(state)) {
            return streamMetadataStore.getCreationTime(scope, stream, context, executor).thenApply(time -> new DeleteStreamEvent(scope, stream, requestId, time)).thenCompose(eventHelper::writeEvent).thenApply(x -> true);
        } else if (State.UNKNOWN.equals(state)) {
            // so we can simply delete the stream metadata which deletes stream from scope as well.
            return streamMetadataStore.deleteStream(scope, stream, context, executor).exceptionally(e -> {
                throw new CompletionException(e);
            }).thenApply(v -> true);
        } else {
            // we cannot delete the stream. Return false from here.
            return CompletableFuture.completedFuture(false);
        }
    }).thenCompose(result -> {
        if (result) {
            return eventHelper.checkDone(() -> isDeleted(scope, stream, context)).thenApply(x -> DeleteStreamStatus.Status.SUCCESS);
        } else {
            return CompletableFuture.completedFuture(DeleteStreamStatus.Status.STREAM_NOT_SEALED);
        }
    })).exceptionally(ex -> {
        return handleDeleteStreamError(ex, requestId, NameUtils.getScopedStreamName(scope, stream));
    });
}
Also used : UpdateStreamEvent(io.pravega.shared.controller.event.UpdateStreamEvent) StreamCut(io.pravega.controller.stream.api.grpc.v1.Controller.StreamCut) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) AbstractStreamMetadataStore(io.pravega.controller.store.stream.AbstractStreamMetadataStore) StoreException(io.pravega.controller.store.stream.StoreException) TaskMetadataStore(io.pravega.controller.store.task.TaskMetadataStore) Duration(java.time.Duration) Map(java.util.Map) RGStreamCutRecord(io.pravega.shared.controller.event.RGStreamCutRecord) LockFailedException(io.pravega.controller.store.task.LockFailedException) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) StreamCutReferenceRecord(io.pravega.controller.store.stream.records.StreamCutReferenceRecord) StreamTruncationRecord(io.pravega.controller.store.stream.records.StreamTruncationRecord) DeleteStreamEvent(io.pravega.shared.controller.event.DeleteStreamEvent) Set(java.util.Set) GuardedBy(javax.annotation.concurrent.GuardedBy) ControllerEvent(io.pravega.shared.controller.event.ControllerEvent) Serializable(java.io.Serializable) ReaderGroupState(io.pravega.controller.store.stream.ReaderGroupState) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) Futures(io.pravega.common.concurrent.Futures) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) StreamMetrics(io.pravega.controller.metrics.StreamMetrics) CreateReaderGroupResponse(io.pravega.controller.stream.api.grpc.v1.Controller.CreateReaderGroupResponse) TransactionMetrics(io.pravega.controller.metrics.TransactionMetrics) RetentionPolicy(io.pravega.client.stream.RetentionPolicy) Exceptions(io.pravega.common.Exceptions) TruncateStreamEvent(io.pravega.shared.controller.event.TruncateStreamEvent) RetentionSet(io.pravega.controller.store.stream.records.RetentionSet) Supplier(java.util.function.Supplier) UpdateSubscriberStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateSubscriberStatus) ArrayList(java.util.ArrayList) ReaderGroupConfigRecord(io.pravega.controller.store.stream.records.ReaderGroupConfigRecord) ReaderGroupConfiguration(io.pravega.controller.stream.api.grpc.v1.Controller.ReaderGroupConfiguration) StreamInfo(io.pravega.controller.stream.api.grpc.v1.Controller.StreamInfo) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EventHelper(io.pravega.controller.task.EventHelper) CreateReaderGroupEvent(io.pravega.shared.controller.event.CreateReaderGroupEvent) RetryHelper(io.pravega.controller.util.RetryHelper) Task(io.pravega.controller.task.Task) Executor(java.util.concurrent.Executor) CreateStreamResponse(io.pravega.controller.store.stream.CreateStreamResponse) WireCommands(io.pravega.shared.protocol.netty.WireCommands) SegmentRange(io.pravega.controller.stream.api.grpc.v1.Controller.SegmentRange) AtomicLong(java.util.concurrent.atomic.AtomicLong) StreamConfigurationRecord(io.pravega.controller.store.stream.records.StreamConfigurationRecord) TreeMap(java.util.TreeMap) WireCommandFailedException(io.pravega.controller.server.WireCommandFailedException) Preconditions(com.google.common.base.Preconditions) DeleteReaderGroupStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteReaderGroupStatus) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) ControllerEventProcessors(io.pravega.controller.server.eventProcessor.ControllerEventProcessors) StreamSegmentRecord(io.pravega.controller.store.stream.records.StreamSegmentRecord) DeleteReaderGroupEvent(io.pravega.shared.controller.event.DeleteReaderGroupEvent) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) SealStreamEvent(io.pravega.shared.controller.event.SealStreamEvent) TagLogger(io.pravega.common.tracing.TagLogger) VersionedMetadata(io.pravega.controller.store.VersionedMetadata) TaskStepsRetryHelper.withRetries(io.pravega.controller.task.Stream.TaskStepsRetryHelper.withRetries) Stream(io.pravega.client.stream.Stream) SubscribersResponse(io.pravega.controller.stream.api.grpc.v1.Controller.SubscribersResponse) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) EpochTransitionRecord(io.pravega.controller.store.stream.records.EpochTransitionRecord) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) EpochTransitionOperationExceptions(io.pravega.controller.store.stream.EpochTransitionOperationExceptions) DeleteScopeEvent(io.pravega.shared.controller.event.DeleteScopeEvent) CompletionException(java.util.concurrent.CompletionException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) List(java.util.List) Config(io.pravega.controller.util.Config) RetryableException(io.pravega.controller.retryable.RetryableException) Optional(java.util.Optional) Resource(io.pravega.controller.store.task.Resource) IntStream(java.util.stream.IntStream) OperationContext(io.pravega.controller.store.stream.OperationContext) SegmentHelper(io.pravega.controller.server.SegmentHelper) ModelHelper(io.pravega.client.control.impl.ModelHelper) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ScaleStatusResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleStatusResponse) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) BucketStore(io.pravega.controller.store.stream.BucketStore) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) EventStreamClientFactory(io.pravega.client.EventStreamClientFactory) NameUtils.getQualifiedStreamSegmentName(io.pravega.shared.NameUtils.getQualifiedStreamSegmentName) ScaleResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleResponse) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) ControllerService(io.pravega.controller.server.ControllerService) UpdateReaderGroupResponse(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateReaderGroupResponse) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) TaskBase(io.pravega.controller.task.TaskBase) StreamCutRecord(io.pravega.controller.store.stream.records.StreamCutRecord) Timer(io.pravega.common.Timer) AbstractMap(java.util.AbstractMap) EpochRecord(io.pravega.controller.store.stream.records.EpochRecord) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) State(io.pravega.controller.store.stream.State) VisibleForTesting(com.google.common.annotations.VisibleForTesting) UpdateReaderGroupEvent(io.pravega.shared.controller.event.UpdateReaderGroupEvent) Comparator(java.util.Comparator) ReaderGroupConfigResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ReaderGroupConfigResponse) ScaleOpEvent(io.pravega.shared.controller.event.ScaleOpEvent) DeleteStreamEvent(io.pravega.shared.controller.event.DeleteStreamEvent) CompletionException(java.util.concurrent.CompletionException) StoreException(io.pravega.controller.store.stream.StoreException)

Aggregations

OperationContext (io.pravega.controller.store.stream.OperationContext)76 CompletableFuture (java.util.concurrent.CompletableFuture)53 Futures (io.pravega.common.concurrent.Futures)48 StreamMetadataStore (io.pravega.controller.store.stream.StreamMetadataStore)44 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)42 Exceptions (io.pravega.common.Exceptions)41 Collectors (java.util.stream.Collectors)41 UUID (java.util.UUID)39 StoreException (io.pravega.controller.store.stream.StoreException)38 List (java.util.List)38 TagLogger (io.pravega.common.tracing.TagLogger)37 LoggerFactory (org.slf4j.LoggerFactory)37 Preconditions (com.google.common.base.Preconditions)36 Map (java.util.Map)32 NameUtils (io.pravega.shared.NameUtils)31 VisibleForTesting (com.google.common.annotations.VisibleForTesting)27 StreamConfiguration (io.pravega.client.stream.StreamConfiguration)26 State (io.pravega.controller.store.stream.State)26 CompletionException (java.util.concurrent.CompletionException)26 BucketStore (io.pravega.controller.store.stream.BucketStore)25