Search in sources :

Example 6 with NoSuchSegmentException

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

the class EventStreamWriterImpl method writeLargeEvent.

@GuardedBy("writeFlushLock")
private void writeLargeEvent(String routingKey, List<ByteBuffer> events, CompletableFuture<Void> ackFuture) {
    flush();
    boolean success = false;
    LargeEventWriter writer = new LargeEventWriter(UUID.randomUUID(), controller, connectionPool);
    while (!success) {
        Segment segment = selector.getSegmentForEvent(routingKey);
        try {
            writer.writeLargeEvent(segment, events, tokenProvider, config);
            success = true;
            ackFuture.complete(null);
        } catch (SegmentSealedException | NoSuchSegmentException e) {
            log.warn("Write large event on segment {} failed due to {}, it will be retried.", segment, e.getMessage());
            handleLogSealed(segment);
            tryWaitForSuccessors();
            // Make sure that the successors are not sealed themselves.
            if (selector.isStreamSealed()) {
                ackFuture.completeExceptionally(new SegmentSealedException(segment.toString()));
                break;
            }
            handleMissingLog();
        } catch (AuthenticationException e) {
            ackFuture.completeExceptionally(e);
            break;
        }
    }
}
Also used : AuthenticationException(io.pravega.auth.AuthenticationException) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) Segment(io.pravega.client.segment.impl.Segment) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) GuardedBy(javax.annotation.concurrent.GuardedBy)

Example 7 with NoSuchSegmentException

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

the class SegmentSelector method refreshSegmentEventWritersUponSealed.

/**
 * Refresh segment writers corresponding to the successors of the sealed segment and return inflight event list of the sealed segment.
 * The segment writer for sealed segment is not removed.
 * @param sealedSegment The sealed segment.
 * @param segmentSealedCallback Sealed segment callback.
 * @return List of pending events.
 */
public List<PendingEvent> refreshSegmentEventWritersUponSealed(Segment sealedSegment, Consumer<Segment> segmentSealedCallback) {
    StreamSegmentsWithPredecessors successors = Futures.getAndHandleExceptions(controller.getSuccessors(sealedSegment), t -> {
        log.error("Error while fetching successors for segment: {}", sealedSegment, t);
        // Remove all writers and fail all pending writes
        Exception e = (t instanceof RetriesExhaustedException) ? new ControllerFailureException(t) : new NoSuchSegmentException(sealedSegment.toString(), t);
        removeAllWriters().forEach(event -> event.getAckFuture().completeExceptionally(e));
        return null;
    });
    if (successors == null) {
        return Collections.emptyList();
    } else if (successors.getSegmentToPredecessor().isEmpty()) {
        log.warn("Stream {} is sealed since no successor segments found for segment {} ", sealedSegment.getStream(), sealedSegment);
        Exception e = new IllegalStateException("Writes cannot proceed since the stream is sealed");
        removeAllWriters().forEach(pendingEvent -> pendingEvent.getAckFuture().completeExceptionally(e));
        sealed.set(true);
        return Collections.emptyList();
    } else {
        return updateSegmentsUponSealed(successors, sealedSegment, segmentSealedCallback);
    }
}
Also used : Segment(io.pravega.client.segment.impl.Segment) RequiredArgsConstructor(lombok.RequiredArgsConstructor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Random(java.util.Random) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) ArrayList(java.util.ArrayList) Stream(io.pravega.client.stream.Stream) Map(java.util.Map) ControllerFailureException(io.pravega.client.control.impl.ControllerFailureException) SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Synchronized(lombok.Synchronized) Iterator(java.util.Iterator) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) GuardedBy(javax.annotation.concurrent.GuardedBy) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) SegmentOutputStreamFactory(io.pravega.client.segment.impl.SegmentOutputStreamFactory) Consumer(java.util.function.Consumer) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Entry(java.util.Map.Entry) Preconditions(com.google.common.base.Preconditions) RandomFactory(io.pravega.common.hash.RandomFactory) Collections(java.util.Collections) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) ControllerFailureException(io.pravega.client.control.impl.ControllerFailureException) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) ControllerFailureException(io.pravega.client.control.impl.ControllerFailureException) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException)

Example 8 with NoSuchSegmentException

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

the class PeriodicWatermarking method watermark.

/**
 * This method computes and emits a new watermark for the given stream.
 * It collects all the known writers for the given stream and includes only writers that are active (have reported
 * their marks recently). If all active writers have reported marks greater than the previously emitted watermark,
 * then new watermark is computed and emitted. If not, the window for considering writers as active is progressed.
 * @param stream stream for which watermark should be computed.
 * @return Returns a completableFuture which when completed will have completed another iteration of periodic watermark
 * computation.
 */
public CompletableFuture<Void> watermark(Stream stream) {
    String scope = stream.getScope();
    String streamName = stream.getStreamName();
    long requestId = requestIdGenerator.get();
    String requestDescriptor = RequestTracker.buildRequestDescriptor("watermark", stream.getScope(), stream.getStreamName());
    requestTracker.trackRequest(requestDescriptor, requestId);
    OperationContext context = streamMetadataStore.createStreamContext(scope, streamName, requestId);
    if (scope.equals(NameUtils.INTERNAL_SCOPE_NAME)) {
        return CompletableFuture.completedFuture(null);
    }
    log.debug(requestId, "Periodic background processing for watermarking called for stream {}/{}", scope, streamName);
    CompletableFuture<Map<String, WriterMark>> allWriterMarks = Futures.exceptionallyExpecting(streamMetadataStore.getAllWriterMarks(scope, streamName, context, executor), e -> Exceptions.unwrap(e) instanceof StoreException.DataNotFoundException, Collections.emptyMap());
    return allWriterMarks.thenCompose(writers -> {
        WatermarkClient watermarkClient = watermarkClientCache.getUnchecked(stream);
        try {
            watermarkClient.reinitialize();
        } catch (Exception e) {
            log.warn(requestId, "Watermarking client for stream {} threw exception {} during reinitialize.", stream, Exceptions.unwrap(e).getClass());
            if (Exceptions.unwrap(e) instanceof NoSuchSegmentException) {
                log.info(requestId, "Invalidating the watermark client in cache for stream {}.", stream);
                watermarkClientCache.invalidate(stream);
            }
            throw e;
        }
        return streamMetadataStore.getConfiguration(scope, streamName, context, executor).thenCompose(config -> filterWritersAndComputeWatermark(scope, streamName, context, watermarkClient, writers, config));
    }).exceptionally(e -> {
        log.warn(requestId, "Exception thrown while trying to perform periodic watermark computation. Logging and ignoring.", e);
        return null;
    });
}
Also used : OperationContext(io.pravega.controller.store.stream.OperationContext) LoadingCache(com.google.common.cache.LoadingCache) StreamSegmentRecord(io.pravega.controller.store.stream.records.StreamSegmentRecord) LoggerFactory(org.slf4j.LoggerFactory) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault) TagLogger(io.pravega.common.tracing.TagLogger) StoreException(io.pravega.controller.store.stream.StoreException) Stream(io.pravega.client.stream.Stream) Map(java.util.Map) SegmentWithRange(io.pravega.shared.watermarks.SegmentWithRange) Synchronized(lombok.Synchronized) WatermarkSerializer(io.pravega.client.watermark.WatermarkSerializer) ImmutableMap(com.google.common.collect.ImmutableMap) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) RequestTracker(io.pravega.common.tracing.RequestTracker) Collectors(java.util.stream.Collectors) CacheLoader(com.google.common.cache.CacheLoader) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Entry(java.util.Map.Entry) CacheBuilder(com.google.common.cache.CacheBuilder) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) Futures(io.pravega.common.concurrent.Futures) OperationContext(io.pravega.controller.store.stream.OperationContext) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BucketStore(io.pravega.controller.store.stream.BucketStore) Lists(com.google.common.collect.Lists) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RevisionedStreamClient(io.pravega.client.state.RevisionedStreamClient) SynchronizerConfig(io.pravega.client.state.SynchronizerConfig) LongSummaryStatistics(java.util.LongSummaryStatistics) NameUtils(io.pravega.shared.NameUtils) WriterMark(io.pravega.controller.store.stream.records.WriterMark) Watermark(io.pravega.shared.watermarks.Watermark) TimeUnit(java.util.concurrent.TimeUnit) EpochRecord(io.pravega.controller.store.stream.records.EpochRecord) SynchronizerClientFactory(io.pravega.client.SynchronizerClientFactory) Closeable(java.io.Closeable) Revision(io.pravega.client.state.Revision) RemovalListener(com.google.common.cache.RemovalListener) VisibleForTesting(com.google.common.annotations.VisibleForTesting) RandomFactory(io.pravega.common.hash.RandomFactory) Comparator(java.util.Comparator) Collections(java.util.Collections) ClientConfig(io.pravega.client.ClientConfig) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) StoreException(io.pravega.controller.store.stream.StoreException) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) StoreException(io.pravega.controller.store.stream.StoreException) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException)

Example 9 with NoSuchSegmentException

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

the class EventStreamReaderImpl method fetchEvent.

@Override
public Type fetchEvent(EventPointer pointer) throws NoSuchEventException {
    Preconditions.checkNotNull(pointer);
    // Create SegmentInputStream
    @Cleanup EventSegmentReader inputStream = inputStreamFactory.createEventReaderForSegment(pointer.asImpl().getSegment(), pointer.asImpl().getEventLength());
    inputStream.setOffset(pointer.asImpl().getEventStartOffset());
    // Read event
    try {
        ByteBuffer buffer = inputStream.read();
        return deserializer.deserialize(buffer);
    } catch (EndOfSegmentException e) {
        throw new NoSuchEventException(e.getMessage());
    } catch (NoSuchSegmentException | SegmentTruncatedException e) {
        throw new NoSuchEventException("Event no longer exists.");
    }
}
Also used : EndOfSegmentException(io.pravega.client.segment.impl.EndOfSegmentException) EventSegmentReader(io.pravega.client.segment.impl.EventSegmentReader) NoSuchEventException(io.pravega.client.segment.impl.NoSuchEventException) SegmentTruncatedException(io.pravega.client.segment.impl.SegmentTruncatedException) Cleanup(lombok.Cleanup) ByteBuffer(java.nio.ByteBuffer) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException)

Example 10 with NoSuchSegmentException

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

the class SegmentTransactionTest method testSegmentDoesNotExist.

@Test(timeout = 5000)
public void testSegmentDoesNotExist() {
    UUID uuid = UUID.randomUUID();
    SegmentOutputStream outputStream = Mockito.mock(SegmentOutputStream.class);
    @SuppressWarnings("resource") SegmentTransactionImpl<String> txn = new SegmentTransactionImpl<>(uuid, outputStream, new JavaSerializer<String>());
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            PendingEvent event = (PendingEvent) invocation.getArgument(0);
            event.getAckFuture().completeExceptionally(new NoSuchSegmentException("segment"));
            return null;
        }
    }).when(outputStream).write(Mockito.any(PendingEvent.class));
    AssertExtensions.assertThrows(TxnFailedException.class, () -> txn.writeEvent("hi"));
    verify(outputStream).write(Mockito.any(PendingEvent.class));
    AssertExtensions.assertThrows(TxnFailedException.class, () -> txn.flush());
    Mockito.verifyNoMoreInteractions(outputStream);
}
Also used : SegmentOutputStream(io.pravega.client.segment.impl.SegmentOutputStream) InvocationOnMock(org.mockito.invocation.InvocationOnMock) UUID(java.util.UUID) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) Test(org.junit.Test)

Aggregations

NoSuchSegmentException (io.pravega.client.segment.impl.NoSuchSegmentException)10 Segment (io.pravega.client.segment.impl.Segment)6 Cleanup (lombok.Cleanup)5 Controller (io.pravega.client.control.impl.Controller)3 DelegationTokenProvider (io.pravega.client.security.auth.DelegationTokenProvider)3 SegmentOutputStream (io.pravega.client.segment.impl.SegmentOutputStream)3 SegmentSealedException (io.pravega.client.segment.impl.SegmentSealedException)3 EventWriterConfig (io.pravega.client.stream.EventWriterConfig)3 Stream (io.pravega.client.stream.Stream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 List (java.util.List)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 AuthenticationException (io.pravega.auth.AuthenticationException)2 SegmentMetadataClient (io.pravega.client.segment.impl.SegmentMetadataClient)2 TruncatedDataException (io.pravega.client.stream.TruncatedDataException)2 Exceptions (io.pravega.common.Exceptions)2 Futures (io.pravega.common.concurrent.Futures)2 RandomFactory (io.pravega.common.hash.RandomFactory)2