Search in sources :

Example 1 with Controller

use of io.pravega.client.control.impl.Controller in project pravega by pravega.

the class ParseReaderGroupStreamCommand method execute.

@Override
public void execute() throws Exception {
    ensureArgCount(4);
    final String scope = getArg(0);
    final String readerGroup = getArg(1);
    final String segmentStoreHost = getArg(2);
    final String fileName = getArg(3);
    String stream = NameUtils.getStreamForReaderGroup(readerGroup);
    @Cleanup ConnectionPool pool = createConnectionPool();
    @Cleanup Controller controller = instantiateController(pool);
    @Cleanup CuratorFramework zkClient = createZKClient();
    @Cleanup SegmentHelper segmentHelper = instantiateSegmentHelper(zkClient, pool);
    readRGSegmentToFile(segmentHelper, segmentStoreHost, controller, scope, stream, fileName);
    output("The readerGroup stream has been successfully written into %s", fileName);
}
Also used : ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) CuratorFramework(org.apache.curator.framework.CuratorFramework) Controller(io.pravega.client.control.impl.Controller) SegmentHelper(io.pravega.controller.server.SegmentHelper) Cleanup(lombok.Cleanup)

Example 2 with Controller

use of io.pravega.client.control.impl.Controller in project pravega by pravega.

the class BatchClientFactoryImpl method getStreamSegmentInfo.

private StreamSegmentsIterator getStreamSegmentInfo(final Stream stream, final StreamCut startStreamCut, final StreamCut endStreamCut) {
    log.debug("Start stream cut: {}, End stream cut: {}", startStreamCut, endStreamCut);
    StreamSegmentsInfoImpl.validateStreamCuts(startStreamCut, endStreamCut);
    StreamSegmentSuccessors segments = getAndHandleExceptions(controller.getSegments(startStreamCut, endStreamCut), RuntimeException::new);
    final SortedSet<Segment> segmentSet = new TreeSet<>(segments.getSegments());
    final DelegationTokenProvider tokenProvider = DelegationTokenProviderFactory.create(controller, stream.getScope(), stream.getStreamName(), AccessOperation.READ);
    log.debug("List of Segments between the start and end stream cuts : {}", segmentSet);
    val futures = segmentSet.stream().map(s -> getSegmentRange(s, startStreamCut, endStreamCut, tokenProvider)).collect(Collectors.toList());
    List<SegmentRange> results = Futures.getThrowingException(Futures.allOfWithResults(futures));
    return StreamSegmentsInfoImpl.builder().segmentRangeIterator(results.iterator()).startStreamCut(startStreamCut).endStreamCut(endStreamCut).build();
}
Also used : lombok.val(lombok.val) Segment(io.pravega.client.segment.impl.Segment) StreamCut(io.pravega.client.stream.StreamCut) SortedSet(java.util.SortedSet) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) SegmentMetadataClientFactoryImpl(io.pravega.client.segment.impl.SegmentMetadataClientFactoryImpl) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionPoolImpl(io.pravega.client.connection.impl.ConnectionPoolImpl) SegmentMetadataClientFactory(io.pravega.client.segment.impl.SegmentMetadataClientFactory) TreeSet(java.util.TreeSet) StreamCutHelper(io.pravega.client.admin.impl.StreamCutHelper) SegmentRange(io.pravega.client.batch.SegmentRange) Stream(io.pravega.client.stream.Stream) AccessOperation(io.pravega.shared.security.auth.AccessOperation) SegmentInputStreamFactoryImpl(io.pravega.client.segment.impl.SegmentInputStreamFactoryImpl) BatchClientFactory(io.pravega.client.BatchClientFactory) Serializer(io.pravega.client.stream.Serializer) SegmentInputStreamFactory(io.pravega.client.segment.impl.SegmentInputStreamFactory) Futures.getAndHandleExceptions(io.pravega.common.concurrent.Futures.getAndHandleExceptions) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) SegmentIterator(io.pravega.client.batch.SegmentIterator) lombok.val(lombok.val) SegmentInfo(io.pravega.client.segment.impl.SegmentInfo) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) Collectors(java.util.stream.Collectors) Beta(com.google.common.annotations.Beta) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) SegmentMetadataClient(io.pravega.client.segment.impl.SegmentMetadataClient) StreamSegmentSuccessors(io.pravega.client.stream.impl.StreamSegmentSuccessors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) StreamSegmentsIterator(io.pravega.client.batch.StreamSegmentsIterator) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) ClientConfig(io.pravega.client.ClientConfig) SegmentRange(io.pravega.client.batch.SegmentRange) StreamSegmentSuccessors(io.pravega.client.stream.impl.StreamSegmentSuccessors) TreeSet(java.util.TreeSet) Segment(io.pravega.client.segment.impl.Segment) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider)

Example 3 with Controller

use of io.pravega.client.control.impl.Controller in project pravega by pravega.

the class KeyValueTableFactory method withScope.

/**
 * Creates a new instance of {@link KeyValueTableFactory}.
 *
 * @param scope  The Key-Value Table scope.
 * @param config Configuration for the client.
 * @return Instance of {@link KeyValueTableFactory} implementation.
 */
static KeyValueTableFactory withScope(String scope, ClientConfig config) {
    ConnectionFactory connectionFactory = new SocketConnectionFactoryImpl(config);
    ConnectionPool connectionPool = new ConnectionPoolImpl(config, connectionFactory);
    Controller controller = new ControllerImpl(ControllerImplConfig.builder().clientConfig(config).build(), connectionFactory.getInternalExecutor());
    return new KeyValueTableFactoryImpl(scope, controller, connectionPool);
}
Also used : ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) KeyValueTableFactoryImpl(io.pravega.client.tables.impl.KeyValueTableFactoryImpl) ConnectionPoolImpl(io.pravega.client.connection.impl.ConnectionPoolImpl) ControllerImpl(io.pravega.client.control.impl.ControllerImpl) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) Controller(io.pravega.client.control.impl.Controller)

Example 4 with Controller

use of io.pravega.client.control.impl.Controller in project pravega by pravega.

the class ConditionalOutputStreamImpl method write.

@Override
public boolean write(ByteBuffer data, long expectedOffset) throws SegmentSealedException {
    Exceptions.checkNotClosed(closed.get(), this);
    synchronized (lock) {
        // Used to preserver order.
        long appendSequence = requestIdGenerator.get();
        return retrySchedule.retryWhen(e -> {
            Throwable cause = Exceptions.unwrap(e);
            boolean hasTokenExpired = cause instanceof TokenExpiredException;
            if (hasTokenExpired) {
                this.tokenProvider.signalTokenExpired();
            }
            return cause instanceof Exception && (hasTokenExpired || cause instanceof ConnectionFailedException);
        }).run(() -> {
            if (client == null || client.isClosed()) {
                client = new RawClient(controller, connectionPool, segmentId);
                long requestId = client.getFlow().getNextSequenceNumber();
                log.debug("Setting up appends on segment {} for ConditionalOutputStream with writer id {}", segmentId, writerId);
                CompletableFuture<Reply> reply = tokenProvider.retrieveToken().thenCompose(token -> {
                    SetupAppend setup = new SetupAppend(requestId, writerId, segmentId.getScopedName(), token);
                    return client.sendRequest(requestId, setup);
                });
                AppendSetup appendSetup = transformAppendSetup(reply.join());
                if (appendSetup.getLastEventNumber() >= appendSequence) {
                    return true;
                }
            }
            long requestId = client.getFlow().getNextSequenceNumber();
            val request = new ConditionalAppend(writerId, appendSequence, expectedOffset, new Event(Unpooled.wrappedBuffer(data)), requestId);
            val reply = client.sendRequest(requestId, request);
            return transformDataAppended(reply.join());
        });
    }
}
Also used : Event(io.pravega.shared.protocol.netty.WireCommands.Event) TokenExpiredException(io.pravega.auth.TokenExpiredException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) Exceptions(io.pravega.common.Exceptions) ConditionalCheckFailed(io.pravega.shared.protocol.netty.WireCommands.ConditionalCheckFailed) RequiredArgsConstructor(lombok.RequiredArgsConstructor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Supplier(java.util.function.Supplier) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) RawClient(io.pravega.client.connection.impl.RawClient) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) ConditionalAppend(io.pravega.shared.protocol.netty.WireCommands.ConditionalAppend) RetryWithBackoff(io.pravega.common.util.Retry.RetryWithBackoff) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) lombok.val(lombok.val) AuthenticationException(io.pravega.auth.AuthenticationException) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) GuardedBy(javax.annotation.concurrent.GuardedBy) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) AtomicLong(java.util.concurrent.atomic.AtomicLong) InvalidEventNumber(io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber) Slf4j(lombok.extern.slf4j.Slf4j) VisibleForTesting(com.google.common.annotations.VisibleForTesting) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Controller(io.pravega.client.control.impl.Controller) lombok.val(lombok.val) ConditionalAppend(io.pravega.shared.protocol.netty.WireCommands.ConditionalAppend) RawClient(io.pravega.client.connection.impl.RawClient) TokenExpiredException(io.pravega.auth.TokenExpiredException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) AuthenticationException(io.pravega.auth.AuthenticationException) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) TokenExpiredException(io.pravega.auth.TokenExpiredException) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) Reply(io.pravega.shared.protocol.netty.Reply) Event(io.pravega.shared.protocol.netty.WireCommands.Event) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 5 with Controller

use of io.pravega.client.control.impl.Controller in project pravega by pravega.

the class ReaderGroupImpl method resetReaderGroup.

@Override
public void resetReaderGroup(ReaderGroupConfig config) {
    log.info("Reset ReaderGroup {} to {}", getGroupName(), config);
    synchronizer.fetchUpdates();
    while (true) {
        val currentConfig = synchronizer.getState().getConfig();
        // We only move into the block if the state transition has happened successfully.
        if (stateTransition(currentConfig, new UpdatingConfig(true))) {
            if (currentConfig.getReaderGroupId() == ReaderGroupConfig.DEFAULT_UUID && currentConfig.getGeneration() == ReaderGroupConfig.DEFAULT_GENERATION) {
                // Migration code path, for moving a ReaderGroup from version < 0.9 to 0.9+
                final ReaderGroupConfig updateConfig = ReaderGroupConfig.cloneConfig(config, UUID.randomUUID(), 0L);
                final long nextGen = Futures.getThrowingException(controller.createReaderGroup(scope, getGroupName(), updateConfig).thenCompose(conf -> {
                    if (!conf.getReaderGroupId().equals(updateConfig.getReaderGroupId())) {
                        return controller.updateReaderGroup(scope, groupName, ReaderGroupConfig.cloneConfig(updateConfig, conf.getReaderGroupId(), conf.getGeneration()));
                    } else {
                        // ReaderGroup IDs matched so our create was updated on Controller
                        return CompletableFuture.completedFuture(conf.getGeneration());
                    }
                }));
                updateConfigInStateSynchronizer(updateConfig, nextGen);
            } else {
                // normal code path
                // Use the latest generation and reader group Id.
                ReaderGroupConfig newConfig = ReaderGroupConfig.cloneConfig(config, currentConfig.getReaderGroupId(), currentConfig.getGeneration());
                long newGen = Futures.exceptionallyExpecting(controller.updateReaderGroup(scope, groupName, newConfig), e -> Exceptions.unwrap(e) instanceof ReaderGroupConfigRejectedException, -1L).join();
                if (newGen == -1) {
                    log.debug("Synchronize reader group with the one present on controller.");
                    synchronizeReaderGroupConfig();
                    continue;
                }
                updateConfigInStateSynchronizer(newConfig, newGen);
            }
            return;
        }
    }
}
Also used : lombok.val(lombok.val) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) StreamCut(io.pravega.client.stream.StreamCut) ReaderGroupStateInit(io.pravega.client.stream.impl.ReaderGroupState.ReaderGroupStateInit) SneakyThrows(lombok.SneakyThrows) UpdatingConfig(io.pravega.client.stream.impl.ReaderGroupState.UpdatingConfig) ReaderGroup(io.pravega.client.stream.ReaderGroup) ReaderGroupMetrics(io.pravega.client.stream.ReaderGroupMetrics) EndOfDataNotification(io.pravega.client.stream.notifications.EndOfDataNotification) Position(io.pravega.client.stream.Position) Stream(io.pravega.client.stream.Stream) AccessOperation(io.pravega.shared.security.auth.AccessOperation) Duration(java.time.Duration) Map(java.util.Map) Checkpoint(io.pravega.client.stream.Checkpoint) Futures.getThrowingException(io.pravega.common.concurrent.Futures.getThrowingException) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) UUID(java.util.UUID) InitialUpdate(io.pravega.client.state.InitialUpdate) Collectors(java.util.stream.Collectors) SegmentMetadataClient(io.pravega.client.segment.impl.SegmentMetadataClient) NotifierFactory(io.pravega.client.stream.notifications.NotifierFactory) Base64(java.util.Base64) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Observable(io.pravega.client.stream.notifications.Observable) Entry(java.util.Map.Entry) Optional(java.util.Optional) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) ClearCheckpointsBefore(io.pravega.client.stream.impl.ReaderGroupState.ClearCheckpointsBefore) StateSynchronizer(io.pravega.client.state.StateSynchronizer) Segment(io.pravega.client.segment.impl.Segment) NotificationSystem(io.pravega.client.stream.notifications.NotificationSystem) Exceptions(io.pravega.common.Exceptions) SegmentMetadataClientFactoryImpl(io.pravega.client.segment.impl.SegmentMetadataClientFactoryImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ReaderGroupConfigRejectedException(io.pravega.client.control.impl.ReaderGroupConfigRejectedException) SegmentMetadataClientFactory(io.pravega.client.segment.impl.SegmentMetadataClientFactory) ArrayList(java.util.ArrayList) Update(io.pravega.client.state.Update) SegmentNotification(io.pravega.client.stream.notifications.SegmentNotification) CreateCheckpoint(io.pravega.client.stream.impl.ReaderGroupState.CreateCheckpoint) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SynchronizerConfig(io.pravega.client.state.SynchronizerConfig) Serializer(io.pravega.client.stream.Serializer) NameUtils(io.pravega.shared.NameUtils) Futures.getAndHandleExceptions(io.pravega.common.concurrent.Futures.getAndHandleExceptions) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) lombok.val(lombok.val) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Futures.allOfWithResults(io.pravega.common.concurrent.Futures.allOfWithResults) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) SynchronizerClientFactory(io.pravega.client.SynchronizerClientFactory) ReaderSegmentDistribution(io.pravega.client.stream.ReaderSegmentDistribution) Data(lombok.Data) InvalidStreamException(io.pravega.client.stream.InvalidStreamException) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) ReaderGroupConfigRejectedException(io.pravega.client.control.impl.ReaderGroupConfigRejectedException) UpdatingConfig(io.pravega.client.stream.impl.ReaderGroupState.UpdatingConfig)

Aggregations

Controller (io.pravega.client.control.impl.Controller)120 Test (org.junit.Test)95 Cleanup (lombok.Cleanup)81 Segment (io.pravega.client.segment.impl.Segment)53 EventWriterConfig (io.pravega.client.stream.EventWriterConfig)50 StreamConfiguration (io.pravega.client.stream.StreamConfiguration)47 Stream (io.pravega.client.stream.Stream)37 CompletableFuture (java.util.concurrent.CompletableFuture)35 SegmentOutputStreamFactory (io.pravega.client.segment.impl.SegmentOutputStreamFactory)34 SocketConnectionFactoryImpl (io.pravega.client.connection.impl.SocketConnectionFactoryImpl)33 HashMap (java.util.HashMap)29 ClientConfig (io.pravega.client.ClientConfig)28 ClientFactoryImpl (io.pravega.client.stream.impl.ClientFactoryImpl)28 StreamImpl (io.pravega.client.stream.impl.StreamImpl)25 ReaderGroupManager (io.pravega.client.admin.ReaderGroupManager)24 Slf4j (lombok.extern.slf4j.Slf4j)24 Before (org.junit.Before)23 ConnectionFactory (io.pravega.client.connection.impl.ConnectionFactory)22 ConnectionPoolImpl (io.pravega.client.connection.impl.ConnectionPoolImpl)21 ScalingPolicy (io.pravega.client.stream.ScalingPolicy)21