use of io.pravega.client.stream.mock.MockConnectionFactoryImpl in project pravega by pravega.
the class SegmentOutputStreamTest method testSegmentSealedFollowedbyConnectionDrop.
@Test(timeout = 10000)
public void testSegmentSealedFollowedbyConnectionDrop() throws Exception {
@Cleanup("shutdownNow") ScheduledExecutorService executor = ExecutorServiceHelpers.newScheduledThreadPool(2, "netty-callback");
// Segment sealed callback will finish execution only when the releaseCallbackLatch is released;
ReusableLatch releaseCallbackLatch = new ReusableLatch(false);
ReusableLatch callBackInvokedLatch = new ReusableLatch(false);
final Consumer<Segment> segmentSealedCallback = segment -> Exceptions.handleInterrupted(() -> {
callBackInvokedLatch.release();
releaseCallbackLatch.await();
});
// Setup mocks.
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);
// Mock client connection that is returned for every invocation of ConnectionFactory#establishConnection.
ClientConnection connection = mock(ClientConnection.class);
cf.provideConnection(uri, connection);
InOrder order = Mockito.inOrder(connection);
// Create a Segment writer.
@SuppressWarnings("resource") SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, segmentSealedCallback, RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());
// trigger establishment of connection.
output.reconnect();
// Verify if SetupAppend is sent over the connection.
order.verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
cf.getProcessor(uri).appendSetup(new AppendSetup(output.getRequestId(), SEGMENT, cid, 0));
// Write an event and ensure inflight has an event.
ByteBuffer data = getBuffer("test");
CompletableFuture<Void> ack = new CompletableFuture<>();
output.write(PendingEvent.withoutHeader(null, data, ack));
order.verify(connection).send(new Append(SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(data), null, output.getRequestId()));
assertFalse(ack.isDone());
// Simulate a SegmentIsSealed WireCommand from SegmentStore.
executor.submit(() -> cf.getProcessor(uri).segmentIsSealed(new WireCommands.SegmentIsSealed(output.getRequestId(), SEGMENT, "SomeException", 1)));
// Wait until callback invocation has been triggered, but has not completed.
// If the callback is not invoked the test will fail due to a timeout.
callBackInvokedLatch.await();
// Now trigger a connection drop netty callback and wait until it is executed.
executor.submit(() -> cf.getProcessor(uri).connectionDropped()).get();
// close is invoked on the connection.
order.verify(connection).close();
// Verify no further reconnection attempts which involves sending of SetupAppend wire command.
order.verifyNoMoreInteractions();
// Release latch to ensure the callback is completed.
releaseCallbackLatch.release();
// Verify no further reconnection attempts which involves sending of SetupAppend wire command.
order.verifyNoMoreInteractions();
// Trigger a reconnect again and verify if any new connections are initiated.
output.reconnect();
// Reconnect operation will be executed on the executor service.
ScheduledExecutorService service = executorService();
service.shutdown();
// Wait until all the tasks for reconnect have been completed.
service.awaitTermination(10, TimeUnit.SECONDS);
// Verify no further reconnection attempts which involves sending of SetupAppend wire command.
order.verifyNoMoreInteractions();
}
use of io.pravega.client.stream.mock.MockConnectionFactoryImpl in project pravega by pravega.
the class SegmentOutputStreamTest method testReconnectOnBadAcks.
@Test(timeout = 10000)
public void testReconnectOnBadAcks() throws ConnectionFailedException {
UUID cid = UUID.randomUUID();
PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
MockConnectionFactoryImpl cf = spy(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);
@SuppressWarnings("resource") 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());
// simulate bad ack
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());
cf.getProcessor(uri).dataAppended(new WireCommands.DataAppended(output.getRequestId(), cid, 2, 3, -1));
// check that client reconnected
verify(cf, times(2)).establishConnection(any(), any());
}
use of io.pravega.client.stream.mock.MockConnectionFactoryImpl in project pravega by pravega.
the class RevisionedStreamClientTest method testSegmentTruncation.
@Test
public void testSegmentTruncation() {
String scope = "scope";
String stream = "stream";
PravegaNodeUri endpoint = new PravegaNodeUri("localhost", SERVICE_PORT);
@Cleanup MockConnectionFactoryImpl connectionFactory = new MockConnectionFactoryImpl();
@Cleanup MockController controller = new MockController(endpoint.getEndpoint(), endpoint.getPort(), connectionFactory, false);
createScopeAndStream(scope, stream, controller);
MockSegmentStreamFactory streamFactory = new MockSegmentStreamFactory();
@Cleanup SynchronizerClientFactory clientFactory = new ClientFactoryImpl(scope, controller, connectionFactory, streamFactory, streamFactory, streamFactory, streamFactory);
SynchronizerConfig config = SynchronizerConfig.builder().build();
@Cleanup RevisionedStreamClient<String> client = clientFactory.createRevisionedStreamClient(stream, new JavaSerializer<>(), config);
Revision r0 = client.fetchLatestRevision();
client.writeUnconditionally("a");
Revision ra = client.fetchLatestRevision();
client.writeUnconditionally("b");
Revision rb = client.fetchLatestRevision();
client.writeUnconditionally("c");
Revision rc = client.fetchLatestRevision();
assertEquals(r0, client.fetchOldestRevision());
client.truncateToRevision(r0);
assertEquals(r0, client.fetchOldestRevision());
client.truncateToRevision(ra);
assertEquals(ra, client.fetchOldestRevision());
client.truncateToRevision(r0);
assertEquals(ra, client.fetchOldestRevision());
assertThrows(TruncatedDataException.class, () -> client.readFrom(r0));
Iterator<Entry<Revision, String>> iterA = client.readFrom(ra);
assertTrue(iterA.hasNext());
Iterator<Entry<Revision, String>> iterB = client.readFrom(ra);
assertTrue(iterB.hasNext());
assertEquals("b", iterA.next().getValue());
assertEquals("b", iterB.next().getValue());
client.truncateToRevision(rb);
assertTrue(iterA.hasNext());
assertEquals("c", iterA.next().getValue());
client.truncateToRevision(rc);
assertFalse(iterA.hasNext());
assertTrue(iterB.hasNext());
assertThrows(TruncatedDataException.class, () -> iterB.next());
}
use of io.pravega.client.stream.mock.MockConnectionFactoryImpl in project pravega by pravega.
the class RevisionedStreamClientTest method testRetryOnTimeout.
@Test
public void testRetryOnTimeout() throws ConnectionFailedException {
String scope = "scope";
String stream = "stream";
Segment segment = new Segment(scope, stream, 0L);
// Setup Environment
PravegaNodeUri endpoint = new PravegaNodeUri("localhost", SERVICE_PORT);
// Setup Mocks
JavaSerializer<String> serializer = new JavaSerializer<>();
@Cleanup MockConnectionFactoryImpl connectionFactory = new MockConnectionFactoryImpl();
@Cleanup MockController controller = new MockController(endpoint.getEndpoint(), endpoint.getPort(), connectionFactory, false);
// Setup client connection.
ClientConnection c = mock(ClientConnection.class);
connectionFactory.provideConnection(endpoint, c);
// Create Scope and Stream.
createScopeAndStream(scope, stream, controller);
// Create mock ClientFactory.
SegmentInputStreamFactory segInputFactory = new SegmentInputStreamFactoryImpl(controller, connectionFactory);
SegmentOutputStreamFactory segOutputFactory = mock(SegmentOutputStreamFactory.class);
ConditionalOutputStreamFactory condOutputFactory = new ConditionalOutputStreamFactoryImpl(controller, connectionFactory);
SegmentMetadataClientFactory segMetaFactory = mock(SegmentMetadataClientFactory.class);
SegmentMetadataClient segMetaClient = mock(SegmentMetadataClient.class);
when(segMetaFactory.createSegmentMetadataClient(eq(segment), any(DelegationTokenProvider.class))).thenReturn(segMetaClient);
@Cleanup ClientFactoryImpl clientFactory = new ClientFactoryImpl(scope, controller, connectionFactory, segInputFactory, segOutputFactory, condOutputFactory, segMetaFactory);
RevisionedStreamClientImpl<String> client = spy((RevisionedStreamClientImpl<String>) clientFactory.createRevisionedStreamClient(stream, serializer, SynchronizerConfig.builder().build()));
// Override the readTimeout value for RevisionedClient to 1 second.
doReturn(1000L).when(client).getReadTimeout();
// Setup the SegmentMetadataClient mock.
doReturn(CompletableFuture.completedFuture(new SegmentInfo(segment, 0L, 30L, false, 1L))).when(segMetaClient).getSegmentInfo();
// Get the iterator from Revisioned Stream Client.
Iterator<Entry<Revision, String>> iterator = client.readFrom(new RevisionImpl(segment, 15, 1));
// since we are trying to read @ offset 15 and the writeOffset is 30L a true is returned for hasNext().
assertTrue(iterator.hasNext());
// Setup mock to validate a retry.
doNothing().doAnswer(i -> {
WireCommands.ReadSegment request = i.getArgument(0);
ReplyProcessor rp = connectionFactory.getProcessor(endpoint);
WireCommands.Event event = new WireCommands.Event(Unpooled.wrappedBuffer(serializer.serialize("A")));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
event.writeFields(new DataOutputStream(bout));
ByteBuf eventData = Unpooled.wrappedBuffer(bout.toByteArray());
// Invoke Reply processor to simulate a successful read.
rp.process(new WireCommands.SegmentRead(request.getSegment(), 15L, true, true, eventData, request.getRequestId()));
return null;
}).when(c).send(any(WireCommands.ReadSegment.class));
Entry<Revision, String> r = iterator.next();
assertEquals("A", r.getValue());
// Verify retries have been performed.
verify(c, times(3)).send(any(WireCommands.ReadSegment.class));
}
use of io.pravega.client.stream.mock.MockConnectionFactoryImpl in project pravega by pravega.
the class RevisionedStreamClientTest method testSegmentSealedFromSegmentOutputStreamError.
@Test
public void testSegmentSealedFromSegmentOutputStreamError() {
String scope = "scope";
String stream = "stream";
// Setup Environment
PravegaNodeUri endpoint = new PravegaNodeUri("localhost", SERVICE_PORT);
@Cleanup MockConnectionFactoryImpl connectionFactory = new MockConnectionFactoryImpl();
@Cleanup MockController controller = new MockController(endpoint.getEndpoint(), endpoint.getPort(), connectionFactory, false);
createScopeAndStream(scope, stream, controller);
MockSegmentStreamFactory streamFactory = new MockSegmentStreamFactory();
// Setup mock
SegmentOutputStreamFactory outFactory = mock(SegmentOutputStreamFactory.class);
SegmentOutputStream out = mock(SegmentOutputStream.class);
when(outFactory.createOutputStreamForSegment(eq(new Segment(scope, stream, 0)), any(), any(), any(DelegationTokenProvider.class))).thenReturn(out);
@Cleanup SynchronizerClientFactory clientFactory = new ClientFactoryImpl(scope, controller, connectionFactory, streamFactory, outFactory, streamFactory, streamFactory);
CompletableFuture<Void> writeFuture = new CompletableFuture<>();
PendingEvent event1 = PendingEvent.withoutHeader("key", ByteBufferUtils.EMPTY, writeFuture);
PendingEvent event2 = PendingEvent.withoutHeader("key", ByteBufferUtils.EMPTY, null);
// Two events are returned when the callback invokes getUnackedEventsOnSeal
when(out.getUnackedEventsOnSeal()).thenReturn(Arrays.asList(event1, event2));
@Cleanup RevisionedStreamClient<String> client = clientFactory.createRevisionedStreamClient(stream, new JavaSerializer<>(), SynchronizerConfig.builder().build());
// simulate invocation of handleSegmentSealed by Segment writer.
((RevisionedStreamClientImpl) client).handleSegmentSealed();
// Verify SegmentOutputStream#getUnackedEventsOnSeal is invoked.
verify(out, times(1)).getUnackedEventsOnSeal();
assertTrue(writeFuture.isCompletedExceptionally());
assertThrows(SegmentSealedException.class, writeFuture::get);
}
Aggregations