Search in sources :

Example 1 with ClientConnection

use of io.pravega.client.connection.impl.ClientConnection in project pravega by pravega.

the class SegmentOutputStreamImpl method reconnect.

@VisibleForTesting
void reconnect() {
    if (state.isClosed()) {
        return;
    }
    log.debug("(Re)connect invoked, Segment: {}, writerID: {}", segmentName, writerId);
    state.setupConnection.registerAndRunReleaser(() -> {
        // retry on all exceptions.
        retrySchedule.retryWhen(t -> t instanceof Exception).runAsync(() -> {
            log.debug("Running reconnect for segment {} writer {}", segmentName, writerId);
            if (state.isClosed() || state.needSuccessors.get()) {
                // stop reconnect when writer is closed or resend inflight to successors has been triggered.
                return CompletableFuture.completedFuture(null);
            }
            Preconditions.checkState(state.getConnection() == null);
            log.info("Fetching endpoint for segment {}, writer {}", segmentName, writerId);
            return controller.getEndpointForSegment(segmentName).thenComposeAsync((PravegaNodeUri uri) -> {
                log.info("Establishing connection to {} for {}, writerID: {}", uri, segmentName, writerId);
                return establishConnection(uri);
            }, connectionPool.getInternalExecutor()).thenCombineAsync(tokenProvider.retrieveToken(), AbstractMap.SimpleEntry<ClientConnection, String>::new, connectionPool.getInternalExecutor()).thenComposeAsync(pair -> {
                ClientConnection connection = pair.getKey();
                String token = pair.getValue();
                CompletableFuture<Void> connectionSetupFuture = state.newConnection(connection);
                SetupAppend cmd = new SetupAppend(requestId, writerId, segmentName, token);
                try {
                    connection.send(cmd);
                } catch (ConnectionFailedException e1) {
                    // This needs to be invoked here because call to failConnection from netty may occur before state.newConnection above.
                    state.failConnection(e1);
                    throw Exceptions.sneakyThrow(e1);
                }
                return connectionSetupFuture.exceptionally(t1 -> {
                    Throwable exception = Exceptions.unwrap(t1);
                    if (exception instanceof InvalidTokenException) {
                        log.info("Ending reconnect attempts on writer {} to {} because token verification failed due to invalid token", writerId, segmentName);
                        return null;
                    }
                    if (exception instanceof SegmentSealedException) {
                        log.info("Ending reconnect attempts on writer {} to {} because segment is sealed", writerId, segmentName);
                        return null;
                    }
                    if (exception instanceof NoSuchSegmentException) {
                        log.info("Ending reconnect attempts on writer {} to {} because segment is truncated", writerId, segmentName);
                        return null;
                    }
                    throw Exceptions.sneakyThrow(t1);
                });
            }, connectionPool.getInternalExecutor());
        }, connectionPool.getInternalExecutor()).exceptionally(t -> {
            log.error("Error while attempting to establish connection for writer {}", writerId, t);
            failAndRemoveUnackedEvents(t);
            return null;
        });
    }, new CompletableFuture<ClientConnection>());
}
Also used : TokenExpiredException(io.pravega.auth.TokenExpiredException) Retry(io.pravega.common.util.Retry) RequiredArgsConstructor(lombok.RequiredArgsConstructor) ClientConnection(io.pravega.client.connection.impl.ClientConnection) FailingReplyProcessor(io.pravega.shared.protocol.netty.FailingReplyProcessor) Map(java.util.Map) ToString(lombok.ToString) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) Flow(io.pravega.client.connection.impl.Flow) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) UUID(java.util.UUID) ReusableFutureLatch(io.pravega.common.util.ReusableFutureLatch) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Entry(java.util.Map.Entry) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) PendingEvent(io.pravega.client.stream.impl.PendingEvent) Append(io.pravega.shared.protocol.netty.Append) ArrayList(java.util.ArrayList) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) KeepAlive(io.pravega.shared.protocol.netty.WireCommands.KeepAlive) ReusableLatch(io.pravega.common.util.ReusableLatch) NameUtils(io.pravega.shared.NameUtils) RetryWithBackoff(io.pravega.common.util.Retry.RetryWithBackoff) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) Consumer(java.util.function.Consumer) WireCommand(io.pravega.shared.protocol.netty.WireCommand) AbstractMap(java.util.AbstractMap) InvalidTokenException(io.pravega.auth.InvalidTokenException) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) InvalidTokenException(io.pravega.auth.InvalidTokenException) ToString(lombok.ToString) TokenExpiredException(io.pravega.auth.TokenExpiredException) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) InvalidTokenException(io.pravega.auth.InvalidTokenException) CompletableFuture(java.util.concurrent.CompletableFuture) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) ClientConnection(io.pravega.client.connection.impl.ClientConnection) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 2 with ClientConnection

use of io.pravega.client.connection.impl.ClientConnection in project pravega by pravega.

the class SegmentOutputStreamImpl method close.

/**
 * @see SegmentOutputStream#close()
 */
@Override
public void close() throws SegmentSealedException {
    if (state.isClosed()) {
        return;
    }
    log.debug("Closing writer: {}", writerId);
    // Wait until all the inflight events are written
    flush();
    state.setClosed(true);
    ClientConnection connection = state.getConnection();
    if (connection != null) {
        connection.close();
    }
}
Also used : ClientConnection(io.pravega.client.connection.impl.ClientConnection)

Example 3 with ClientConnection

use of io.pravega.client.connection.impl.ClientConnection in project pravega by pravega.

the class SegmentOutputStreamTest method testFlushDuringTransactionAbort.

@Test(timeout = 10000)
public void testFlushDuringTransactionAbort() throws Exception {
    UUID cid = UUID.randomUUID();
    PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
    MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    cf.setExecutor(executorService());
    MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
    ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(uri, connection);
    InOrder order = Mockito.inOrder(connection);
    @SuppressWarnings("resource") SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(TXN_SEGMENT, true, controller, cf, cid, segmentSealedCallback, RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
    output.reconnect();
    order.verify(connection).send(new SetupAppend(output.getRequestId(), cid, TXN_SEGMENT, ""));
    cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), TXN_SEGMENT, cid, 0));
    ByteBuffer data = getBuffer("test");
    // Write an Event.
    CompletableFuture<Void> ack = new CompletableFuture<>();
    output.write(PendingEvent.withoutHeader(null, data, ack));
    order.verify(connection).send(new Append(TXN_SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
    // writer is not complete until a response from Segment Store is received.
    assertFalse(ack.isDone());
    // Validate that flush() is blocking until there is a response from Segment Store.
    AssertExtensions.assertBlocks(() -> {
        // A flush() should throw a SegmentSealedException.
        AssertExtensions.assertThrows(SegmentSealedException.class, () -> output.flush());
    }, () -> {
        // Simulate a NoSuchSegment response from SegmentStore due to a Transaction abort.
        cf.getProcessor(uri).noSuchSegment(new WireCommands.NoSuchSegment(output.getRequestId(), TXN_SEGMENT, "SomeException", -1L));
    });
    AssertExtensions.assertThrows(SegmentSealedException.class, () -> output.flush());
}
Also used : InOrder(org.mockito.InOrder) ByteBuffer(java.nio.ByteBuffer) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) CompletableFuture(java.util.concurrent.CompletableFuture) Append(io.pravega.shared.protocol.netty.Append) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Test(org.junit.Test)

Example 4 with ClientConnection

use of io.pravega.client.connection.impl.ClientConnection in project pravega by pravega.

the class SegmentOutputStreamTest method testConnectAndConnectionDrop.

@Test(timeout = 10000)
public void testConnectAndConnectionDrop() throws Exception {
    UUID cid = UUID.randomUUID();
    PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
    MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
    // Ensure task submitted to executor is run inline.
    implementAsDirectExecutor(executor);
    cf.setExecutor(executor);
    MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
    ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(uri, connection);
    @Cleanup SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, segmentSealedCallback, RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
    output.reconnect();
    verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
    reset(connection);
    // simulate a connection dropped
    cf.getProcessor(uri).connectionDropped();
    // Ensure setup Append is invoked on the executor.
    verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) UUID(java.util.UUID) Cleanup(lombok.Cleanup) Test(org.junit.Test)

Example 5 with ClientConnection

use of io.pravega.client.connection.impl.ClientConnection in project pravega by pravega.

the class SegmentOutputStreamTest method testFlush.

@Test(timeout = 10000)
public void testFlush() throws ConnectionFailedException, SegmentSealedException {
    UUID cid = UUID.randomUUID();
    PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
    MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    ScheduledExecutorService executor = mock(ScheduledExecutorService.class);
    // Ensure task submitted to executor is run inline.
    implementAsDirectExecutor(executor);
    cf.setExecutor(executor);
    MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
    ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(uri, connection);
    InOrder order = Mockito.inOrder(connection);
    @Cleanup SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, segmentSealedCallback, RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
    output.reconnect();
    order.verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
    cf.getProcessor(uri).appendSetup(new AppendSetup(1, SEGMENT, cid, 0));
    ByteBuffer data = getBuffer("test");
    CompletableFuture<Void> acked1 = new CompletableFuture<>();
    output.write(PendingEvent.withoutHeader(null, data, acked1));
    order.verify(connection).send(new Append(SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
    assertEquals(false, acked1.isDone());
    AssertExtensions.assertBlocks(() -> output.flush(), () -> cf.getProcessor(uri).dataAppended(new WireCommands.DataAppended(output.getRequestId(), cid, 1, 0, -1)));
    assertEquals(false, acked1.isCompletedExceptionally());
    assertEquals(true, acked1.isDone());
    order.verify(connection).send(new WireCommands.KeepAlive());
    CompletableFuture<Void> acked2 = new CompletableFuture<>();
    output.write(PendingEvent.withoutHeader(null, data, acked2));
    order.verify(connection).send(new Append(SEGMENT, cid, 2, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
    assertEquals(false, acked2.isDone());
    AssertExtensions.assertBlocks(() -> output.flush(), () -> cf.getProcessor(uri).dataAppended(new WireCommands.DataAppended(output.getRequestId(), cid, 2, 1, -1)));
    assertEquals(false, acked2.isCompletedExceptionally());
    assertEquals(true, acked2.isDone());
    order.verify(connection).send(new WireCommands.KeepAlive());
    order.verifyNoMoreInteractions();
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InOrder(org.mockito.InOrder) Cleanup(lombok.Cleanup) ByteBuffer(java.nio.ByteBuffer) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) CompletableFuture(java.util.concurrent.CompletableFuture) Append(io.pravega.shared.protocol.netty.Append) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Test(org.junit.Test)

Aggregations

ClientConnection (io.pravega.client.connection.impl.ClientConnection)87 PravegaNodeUri (io.pravega.shared.protocol.netty.PravegaNodeUri)81 MockController (io.pravega.client.stream.mock.MockController)79 MockConnectionFactoryImpl (io.pravega.client.stream.mock.MockConnectionFactoryImpl)78 Test (org.junit.Test)77 Cleanup (lombok.Cleanup)51 InvocationOnMock (org.mockito.invocation.InvocationOnMock)43 WireCommands (io.pravega.shared.protocol.netty.WireCommands)40 SetupAppend (io.pravega.shared.protocol.netty.WireCommands.SetupAppend)35 AppendSetup (io.pravega.shared.protocol.netty.WireCommands.AppendSetup)34 UUID (java.util.UUID)34 ReplyProcessor (io.pravega.shared.protocol.netty.ReplyProcessor)33 ByteBuffer (java.nio.ByteBuffer)31 CompletableFuture (java.util.concurrent.CompletableFuture)30 InOrder (org.mockito.InOrder)27 Append (io.pravega.shared.protocol.netty.Append)23 ConnectionFailedException (io.pravega.shared.protocol.netty.ConnectionFailedException)23 Answer (org.mockito.stubbing.Answer)17 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)16 ArrayList (java.util.ArrayList)14