Search in sources :

Example 1 with SegmentOutputStream

use of io.pravega.client.segment.impl.SegmentOutputStream in project pravega by pravega.

the class ClientFactoryImpl method createRevisionedStreamClient.

@Override
public <T> RevisionedStreamClient<T> createRevisionedStreamClient(String streamName, Serializer<T> serializer, SynchronizerConfig config) {
    log.info("Creating revisioned stream client for stream: {} with synchronizer configuration: {}", streamName, config);
    Segment segment = new Segment(scope, streamName, 0);
    SegmentInputStream in = inFactory.createInputStreamForSegment(segment);
    // Segment sealed is not expected for Revisioned Stream Client.
    Consumer<Segment> segmentSealedCallBack = s -> {
        throw new IllegalStateException("RevisionedClient: Segmentsealed exception observed for segment:" + s);
    };
    String delegationToken = Futures.getAndHandleExceptions(controller.getOrRefreshDelegationTokenFor(segment.getScope(), segment.getStreamName()), RuntimeException::new);
    SegmentOutputStream out = outFactory.createOutputStreamForSegment(segment, segmentSealedCallBack, config.getEventWriterConfig(), delegationToken);
    SegmentMetadataClient meta = metaFactory.createSegmentMetadataClient(segment, delegationToken);
    return new RevisionedStreamClientImpl<>(segment, in, out, meta, serializer, controller, delegationToken);
}
Also used : StateSynchronizer(io.pravega.client.state.StateSynchronizer) Segment(io.pravega.client.segment.impl.Segment) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SegmentMetadataClientFactoryImpl(io.pravega.client.segment.impl.SegmentMetadataClientFactoryImpl) Supplier(java.util.function.Supplier) SegmentMetadataClientFactory(io.pravega.client.segment.impl.SegmentMetadataClientFactory) Update(io.pravega.client.state.Update) Stream(io.pravega.client.stream.Stream) RevisionedStreamClient(io.pravega.client.state.RevisionedStreamClient) SynchronizerConfig(io.pravega.client.state.SynchronizerConfig) ConnectionFactory(io.pravega.client.netty.impl.ConnectionFactory) SegmentInputStreamFactoryImpl(io.pravega.client.segment.impl.SegmentInputStreamFactoryImpl) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) RevisionedStreamClientImpl(io.pravega.client.state.impl.RevisionedStreamClientImpl) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Serializer(io.pravega.client.stream.Serializer) NameUtils(io.pravega.shared.NameUtils) BatchClientImpl(io.pravega.client.batch.impl.BatchClientImpl) SegmentInputStreamFactory(io.pravega.client.segment.impl.SegmentInputStreamFactory) StateSynchronizerImpl(io.pravega.client.state.impl.StateSynchronizerImpl) lombok.val(lombok.val) EventStreamReader(io.pravega.client.stream.EventStreamReader) InitialUpdate(io.pravega.client.state.InitialUpdate) Revisioned(io.pravega.client.state.Revisioned) SegmentMetadataClient(io.pravega.client.segment.impl.SegmentMetadataClient) SegmentOutputStreamFactory(io.pravega.client.segment.impl.SegmentOutputStreamFactory) Consumer(java.util.function.Consumer) Slf4j(lombok.extern.slf4j.Slf4j) SegmentInputStream(io.pravega.client.segment.impl.SegmentInputStream) SegmentOutputStreamFactoryImpl(io.pravega.client.segment.impl.SegmentOutputStreamFactoryImpl) UpdateOrInitSerializer(io.pravega.client.state.impl.UpdateOrInitSerializer) ConnectionFactoryImpl(io.pravega.client.netty.impl.ConnectionFactoryImpl) ClientFactory(io.pravega.client.ClientFactory) BatchClient(io.pravega.client.batch.BatchClient) InvalidStreamException(io.pravega.client.stream.InvalidStreamException) ReaderConfig(io.pravega.client.stream.ReaderConfig) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Futures(io.pravega.common.concurrent.Futures) ClientConfig(io.pravega.client.ClientConfig) SegmentInputStream(io.pravega.client.segment.impl.SegmentInputStream) RevisionedStreamClientImpl(io.pravega.client.state.impl.RevisionedStreamClientImpl) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) Segment(io.pravega.client.segment.impl.Segment) SegmentMetadataClient(io.pravega.client.segment.impl.SegmentMetadataClient)

Example 2 with SegmentOutputStream

use of io.pravega.client.segment.impl.SegmentOutputStream in project pravega by pravega.

the class EventStreamWriterImpl method beginTxn.

@Override
public Transaction<Type> beginTxn() {
    TxnSegments txnSegments = getAndHandleExceptions(controller.createTransaction(stream, config.getTransactionTimeoutTime(), config.getTransactionTimeoutScaleGracePeriod()), RuntimeException::new);
    UUID txnId = txnSegments.getTxnId();
    Map<Segment, SegmentTransaction<Type>> transactions = new HashMap<>();
    for (Segment s : txnSegments.getSteamSegments().getSegments()) {
        SegmentOutputStream out = outputStreamFactory.createOutputStreamForTransaction(s, txnId, segmentSealedCallBack, config, txnSegments.getSteamSegments().getDelegationToken());
        SegmentTransactionImpl<Type> impl = new SegmentTransactionImpl<>(txnId, out, serializer);
        transactions.put(s, impl);
    }
    pinger.startPing(txnId);
    return new TransactionImpl<Type>(txnId, transactions, txnSegments.getSteamSegments(), controller, stream, pinger);
}
Also used : HashMap(java.util.HashMap) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) UUID(java.util.UUID) Segment(io.pravega.client.segment.impl.Segment)

Example 3 with SegmentOutputStream

use of io.pravega.client.segment.impl.SegmentOutputStream in project pravega by pravega.

the class EventStreamWriterImpl method getTxn.

@Override
public Transaction<Type> getTxn(UUID txId) {
    StreamSegments segments = getAndHandleExceptions(controller.getCurrentSegments(stream.getScope(), stream.getStreamName()), RuntimeException::new);
    Status status = getAndHandleExceptions(controller.checkTransactionStatus(stream, txId), RuntimeException::new);
    if (status != Status.OPEN) {
        return new TransactionImpl<>(txId, controller, stream);
    }
    Map<Segment, SegmentTransaction<Type>> transactions = new HashMap<>();
    for (Segment s : segments.getSegments()) {
        SegmentOutputStream out = outputStreamFactory.createOutputStreamForTransaction(s, txId, segmentSealedCallBack, config, segments.getDelegationToken());
        SegmentTransactionImpl<Type> impl = new SegmentTransactionImpl<>(txId, out, serializer);
        transactions.put(s, impl);
    }
    return new TransactionImpl<Type>(txId, transactions, segments, controller, stream, pinger);
}
Also used : Status(io.pravega.client.stream.Transaction.Status) HashMap(java.util.HashMap) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) Segment(io.pravega.client.segment.impl.Segment)

Example 4 with SegmentOutputStream

use of io.pravega.client.segment.impl.SegmentOutputStream in project pravega by pravega.

the class EventStreamWriterImpl method writeEvents.

@Override
public CompletableFuture<Void> writeEvents(String routingKey, List<Type> events) {
    Preconditions.checkNotNull(routingKey);
    Preconditions.checkNotNull(events);
    Exceptions.checkNotClosed(closed.get(), this);
    List<ByteBuffer> data = events.stream().map(serializer::serialize).collect(Collectors.toList());
    CompletableFuture<Void> ackFuture = new CompletableFuture<Void>();
    synchronized (writeFlushLock) {
        if (config.isEnableLargeEvents() && data.stream().mapToInt(m -> m.remaining()).sum() > Serializer.MAX_EVENT_SIZE) {
            writeLargeEvent(routingKey, data, ackFuture);
        } else {
            synchronized (writeSealLock) {
                SegmentOutputStream segmentWriter = getSegmentWriter(routingKey);
                segmentWriter.write(PendingEvent.withHeader(routingKey, data, ackFuture));
            }
        }
    }
    return ackFuture;
}
Also used : Segment(io.pravega.client.segment.impl.Segment) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) Retry(io.pravega.common.util.Retry) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) ByteBufferUtils(io.pravega.common.util.ByteBufferUtils) Stream(io.pravega.client.stream.Stream) AccessOperation(io.pravega.shared.security.auth.AccessOperation) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ToString(lombok.ToString) ExecutorService(java.util.concurrent.ExecutorService) ReusableLatch(io.pravega.common.util.ReusableLatch) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Serializer(io.pravega.client.stream.Serializer) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) AuthenticationException(io.pravega.auth.AuthenticationException) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) UUID(java.util.UUID) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) SegmentOutputStreamFactory(io.pravega.client.segment.impl.SegmentOutputStreamFactory) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Preconditions(com.google.common.base.Preconditions) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) Controller(io.pravega.client.control.impl.Controller) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CompletableFuture(java.util.concurrent.CompletableFuture) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) ByteBuffer(java.nio.ByteBuffer)

Example 5 with SegmentOutputStream

use of io.pravega.client.segment.impl.SegmentOutputStream in project pravega by pravega.

the class EventStreamWriterImpl method handleLogSealed.

/**
 * If a log sealed is encountered, we need to: 1. Find the new segments to write to. 2. For each outstanding
 * message find which new segment it should go to and send it there.
 */
private void handleLogSealed(Segment segment) {
    sealedSegmentQueueEmptyLatch.reset();
    sealedSegmentQueue.add(segment);
    retransmitPool.execute(() -> {
        Retry.indefinitelyWithExpBackoff(config.getInitialBackoffMillis(), config.getBackoffMultiple(), config.getMaxBackoffMillis(), t -> log.error("Encountered exception when handling a sealed segment: ", t)).run(() -> {
            /*
                      * Using writeSealLock prevents concurrent segmentSealedCallback for different segments
                      * from being invoked concurrently, or concurrently with write.
                      * 
                      * By calling flush while the write lock is held we can ensure that any inflight
                      * entries that will succeed in being written to a new segment are written and any
                      * segmentSealedCallbacks that will be called happen before the next write is invoked.
                      */
            synchronized (writeSealLock) {
                Segment toSeal = sealedSegmentQueue.poll();
                log.info("Sealing segment {} ", toSeal);
                while (toSeal != null) {
                    resend(selector.refreshSegmentEventWritersUponSealed(toSeal, segmentSealedCallBack));
                    // remove segment writer after resending inflight events of the sealed segment.
                    selector.removeSegmentWriter(toSeal);
                    /* In the case of segments merging Flush ensures there can't be anything left
                              * inflight that will need to be resent to the new segment when the write lock
                              * is released. (To preserve order)
                              */
                    for (SegmentOutputStream writer : selector.getWriters().values()) {
                        try {
                            writer.write(PendingEvent.withoutHeader(null, ByteBufferUtils.EMPTY, null));
                            writer.flush();
                        } catch (SegmentSealedException e) {
                            // Segment sealed exception observed during a flush. Re-run flush on all the
                            // available writers.
                            log.info("Flush on segment {} failed due to {}, it will be retried.", writer.getSegmentName(), e.getMessage());
                        } catch (RetriesExhaustedException e1) {
                            log.warn("Flush on segment {} failed after all retries", writer.getSegmentName(), e1);
                        }
                    }
                    toSeal = sealedSegmentQueue.poll();
                    if (toSeal != null) {
                        log.info("Sealing another segment {} ", toSeal);
                    }
                }
                sealedSegmentQueueEmptyLatch.release();
            }
            return null;
        });
    });
}
Also used : Segment(io.pravega.client.segment.impl.Segment) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) Retry(io.pravega.common.util.Retry) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) ByteBufferUtils(io.pravega.common.util.ByteBufferUtils) Stream(io.pravega.client.stream.Stream) AccessOperation(io.pravega.shared.security.auth.AccessOperation) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ToString(lombok.ToString) ExecutorService(java.util.concurrent.ExecutorService) ReusableLatch(io.pravega.common.util.ReusableLatch) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Serializer(io.pravega.client.stream.Serializer) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) AuthenticationException(io.pravega.auth.AuthenticationException) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) UUID(java.util.UUID) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) SegmentOutputStreamFactory(io.pravega.client.segment.impl.SegmentOutputStreamFactory) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Preconditions(com.google.common.base.Preconditions) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) Controller(io.pravega.client.control.impl.Controller) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) Segment(io.pravega.client.segment.impl.Segment)

Aggregations

SegmentOutputStream (io.pravega.client.segment.impl.SegmentOutputStream)57 Segment (io.pravega.client.segment.impl.Segment)49 Test (org.junit.Test)41 Cleanup (lombok.Cleanup)35 Controller (io.pravega.client.control.impl.Controller)31 MockController (io.pravega.client.stream.mock.MockController)26 MockSegmentStreamFactory (io.pravega.client.stream.mock.MockSegmentStreamFactory)24 AtomicLong (java.util.concurrent.atomic.AtomicLong)19 EventWriterConfig (io.pravega.client.stream.EventWriterConfig)18 SegmentOutputStreamFactory (io.pravega.client.segment.impl.SegmentOutputStreamFactory)16 ByteBuffer (java.nio.ByteBuffer)15 CompletableFuture (java.util.concurrent.CompletableFuture)11 DelegationTokenProvider (io.pravega.client.security.auth.DelegationTokenProvider)10 InOrder (org.mockito.InOrder)9 EventSegmentReader (io.pravega.client.segment.impl.EventSegmentReader)8 SegmentMetadataClient (io.pravega.client.segment.impl.SegmentMetadataClient)7 SegmentSealedException (io.pravega.client.segment.impl.SegmentSealedException)6 MockConnectionFactoryImpl (io.pravega.client.stream.mock.MockConnectionFactoryImpl)6 PravegaNodeUri (io.pravega.shared.protocol.netty.PravegaNodeUri)6 UUID (java.util.UUID)6