Search in sources :

Example 16 with ClientFactory

use of io.pravega.client.ClientFactory in project pravega by pravega.

the class EndToEndAutoScaleUpWithTxnTest method main.

public static void main(String[] args) throws Exception {
    try {
        @Cleanup TestingServer zkTestServer = new TestingServerStarter().start();
        int port = Config.SERVICE_PORT;
        @Cleanup ControllerWrapper controllerWrapper = new ControllerWrapper(zkTestServer.getConnectString(), port);
        Controller controller = controllerWrapper.getController();
        controllerWrapper.getControllerService().createScope(NameUtils.INTERNAL_SCOPE_NAME).get();
        @Cleanup ConnectionFactory connectionFactory = new ConnectionFactoryImpl(ClientConfig.builder().build());
        @Cleanup ClientFactory internalCF = new ClientFactoryImpl(NameUtils.INTERNAL_SCOPE_NAME, controller, connectionFactory);
        ServiceBuilder serviceBuilder = ServiceBuilder.newInMemoryBuilder(ServiceBuilderConfig.getDefaultConfig());
        serviceBuilder.initialize();
        StreamSegmentStore store = serviceBuilder.createStreamSegmentService();
        @Cleanup SegmentStatsFactory segmentStatsFactory = new SegmentStatsFactory();
        SegmentStatsRecorder statsRecorder = segmentStatsFactory.createSegmentStatsRecorder(store, internalCF, AutoScalerConfig.builder().with(AutoScalerConfig.MUTE_IN_SECONDS, 0).with(AutoScalerConfig.COOLDOWN_IN_SECONDS, 0).build());
        @Cleanup PravegaConnectionListener server = new PravegaConnectionListener(false, "localhost", 12345, store, statsRecorder, null, null, null);
        server.startListening();
        controllerWrapper.awaitRunning();
        controllerWrapper.getControllerService().createScope("test").get();
        controller.createStream(CONFIG).get();
        @Cleanup MockClientFactory clientFactory = new MockClientFactory("test", controller);
        // Mocking pravega service by putting scale up and scale down requests for the stream
        EventWriterConfig writerConfig = EventWriterConfig.builder().transactionTimeoutTime(30000).transactionTimeoutScaleGracePeriod(30000).build();
        EventStreamWriter<String> test = clientFactory.createEventWriter("test", new JavaSerializer<>(), writerConfig);
        // region Successful commit tests
        Transaction<String> txn1 = test.beginTxn();
        txn1.writeEvent("1");
        txn1.flush();
        Map<Double, Double> map = new HashMap<>();
        map.put(0.0, 1.0 / 3.0);
        map.put(1.0 / 3.0, 2.0 / 3.0);
        map.put(2.0 / 3.0, 1.0);
        Stream stream = new StreamImpl("test", "test");
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        controller.scaleStream(stream, Collections.singletonList(0), map, executor).getFuture().get();
        Transaction<String> txn2 = test.beginTxn();
        txn2.writeEvent("2");
        txn2.flush();
        txn2.commit();
        txn1.commit();
        Thread.sleep(1000);
        @Cleanup ReaderGroupManager readerGroupManager = new ReaderGroupManagerImpl("test", controller, clientFactory, connectionFactory);
        readerGroupManager.createReaderGroup("readergrp", ReaderGroupConfig.builder().stream("test").build());
        final EventStreamReader<String> reader = clientFactory.createReader("1", "readergrp", new JavaSerializer<>(), ReaderConfig.builder().build());
        String event1 = reader.readNextEvent(SECONDS.toMillis(60)).getEvent();
        String event2 = reader.readNextEvent(SECONDS.toMillis(60)).getEvent();
        assert event1.equals("1");
        assert event2.equals("2");
        final AtomicBoolean done = new AtomicBoolean(false);
        startWriter(test, done);
        Retry.withExpBackoff(10, 10, 100, 10000).retryingOn(NotDoneException.class).throwingOn(RuntimeException.class).runAsync(() -> controller.getCurrentSegments("test", "test").thenAccept(streamSegments -> {
            if (streamSegments.getSegments().size() > 3) {
                System.err.println("Success");
                log.info("Success");
                System.exit(0);
            } else {
                throw new NotDoneException();
            }
        }), Executors.newSingleThreadScheduledExecutor()).exceptionally(e -> {
            System.err.println("Failure");
            log.error("Failure");
            System.exit(1);
            return null;
        }).get();
    } catch (Throwable e) {
        System.err.print("Test failed with exception: " + e.getMessage());
        log.error("Test failed with exception: {}", e);
        System.exit(-1);
    }
    System.exit(0);
}
Also used : SegmentStatsFactory(io.pravega.segmentstore.server.host.stat.SegmentStatsFactory) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) StreamImpl(io.pravega.client.stream.impl.StreamImpl) Retry(io.pravega.common.util.Retry) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cleanup(lombok.Cleanup) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) JavaSerializer(io.pravega.client.stream.impl.JavaSerializer) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ServiceBuilderConfig(io.pravega.segmentstore.server.store.ServiceBuilderConfig) ServiceBuilder(io.pravega.segmentstore.server.store.ServiceBuilder) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) TestingServerStarter(io.pravega.test.common.TestingServerStarter) Stream(io.pravega.client.stream.Stream) Map(java.util.Map) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TestingServer(org.apache.curator.test.TestingServer) ConnectionFactory(io.pravega.client.netty.impl.ConnectionFactory) PravegaConnectionListener(io.pravega.segmentstore.server.host.handler.PravegaConnectionListener) Transaction(io.pravega.client.stream.Transaction) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) AutoScalerConfig(io.pravega.segmentstore.server.host.stat.AutoScalerConfig) NameUtils(io.pravega.shared.NameUtils) EventStreamReader(io.pravega.client.stream.EventStreamReader) Executors(java.util.concurrent.Executors) Slf4j(lombok.extern.slf4j.Slf4j) Config(io.pravega.controller.util.Config) ConnectionFactoryImpl(io.pravega.client.netty.impl.ConnectionFactoryImpl) ClientFactory(io.pravega.client.ClientFactory) ReaderConfig(io.pravega.client.stream.ReaderConfig) Controller(io.pravega.client.stream.impl.Controller) Collections(java.util.Collections) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) MockClientFactory(io.pravega.client.stream.mock.MockClientFactory) SECONDS(java.util.concurrent.TimeUnit.SECONDS) ClientConfig(io.pravega.client.ClientConfig) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) HashMap(java.util.HashMap) ClientFactory(io.pravega.client.ClientFactory) MockClientFactory(io.pravega.client.stream.mock.MockClientFactory) SegmentStatsFactory(io.pravega.segmentstore.server.host.stat.SegmentStatsFactory) Cleanup(lombok.Cleanup) PravegaConnectionListener(io.pravega.segmentstore.server.host.handler.PravegaConnectionListener) MockClientFactory(io.pravega.client.stream.mock.MockClientFactory) ServiceBuilder(io.pravega.segmentstore.server.store.ServiceBuilder) ConnectionFactory(io.pravega.client.netty.impl.ConnectionFactory) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) Stream(io.pravega.client.stream.Stream) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) TestingServer(org.apache.curator.test.TestingServer) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) TestingServerStarter(io.pravega.test.common.TestingServerStarter) Controller(io.pravega.client.stream.impl.Controller) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) StreamImpl(io.pravega.client.stream.impl.StreamImpl) ConnectionFactoryImpl(io.pravega.client.netty.impl.ConnectionFactoryImpl)

Example 17 with ClientFactory

use of io.pravega.client.ClientFactory in project pravega by pravega.

the class BatchClientTest method testBatchClient.

@Test(timeout = 50000)
public void testBatchClient() throws Exception {
    StreamConfiguration config = StreamConfiguration.builder().scope(SCOPE).streamName(STREAM).scalingPolicy(ScalingPolicy.fixed(1)).build();
    Controller controller = controllerWrapper.getController();
    controllerWrapper.getControllerService().createScope(SCOPE).get();
    controller.createStream(config).get();
    // create reader and writer.
    @Cleanup ClientFactory clientFactory = ClientFactory.withScope(SCOPE, controllerUri);
    @Cleanup ReaderGroupManager groupManager = ReaderGroupManager.withScope(SCOPE, controllerUri);
    groupManager.createReaderGroup("group", ReaderGroupConfig.builder().disableAutomaticCheckpoints().stream(Stream.of(SCOPE, STREAM)).build());
    @Cleanup EventStreamWriter<String> writer = clientFactory.createEventWriter(STREAM, serializer, EventWriterConfig.builder().build());
    // write events to stream with 1 segment.
    writeEvents(writer);
    // scale up and write events.
    Stream stream = new StreamImpl(SCOPE, STREAM);
    Map<Double, Double> map = new HashMap<>();
    map.put(0.0, 0.33);
    map.put(0.33, 0.66);
    map.put(0.66, 1.0);
    Boolean result = controller.scaleStream(stream, Collections.singletonList(0), map, executor).getFuture().get();
    assertTrue("Scale up operation", result);
    writeEvents(writer);
    // scale down and write events.
    map = new HashMap<>();
    map.put(0.0, 0.5);
    map.put(0.5, 1.0);
    result = controller.scaleStream(stream, Arrays.asList(1, 2, 3), map, executor).getFuture().get();
    assertTrue("Scale down operation result", result);
    writeEvents(writer);
    BatchClient batchClient = clientFactory.createBatchClient();
    // List out all the segments in the stream.
    ArrayList<SegmentRange> segments = Lists.newArrayList(batchClient.getSegments(stream, null, null).getIterator());
    assertEquals("Expected number of segments", 6, segments.size());
    // Batch read all events from stream.
    List<String> batchEventList = new ArrayList<>();
    segments.forEach(segInfo -> {
        @Cleanup SegmentIterator<String> segmentIterator = batchClient.readSegment(segInfo, serializer);
        batchEventList.addAll(Lists.newArrayList(segmentIterator));
    });
    assertEquals("Event count", 9, batchEventList.size());
    // read from a given offset.
    Segment seg0 = new Segment(SCOPE, STREAM, 0);
    SegmentRange seg0Info = SegmentRangeImpl.builder().segment(seg0).startOffset(60).endOffset(90).build();
    @Cleanup SegmentIterator<String> seg0Iterator = batchClient.readSegment(seg0Info, serializer);
    ArrayList<String> dataAtOffset = Lists.newArrayList(seg0Iterator);
    assertEquals(1, dataAtOffset.size());
    assertEquals(DATA_OF_SIZE_30, dataAtOffset.get(0));
}
Also used : SegmentRange(io.pravega.client.batch.SegmentRange) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) HashMap(java.util.HashMap) BatchClient(io.pravega.client.batch.BatchClient) ClientFactory(io.pravega.client.ClientFactory) ArrayList(java.util.ArrayList) Controller(io.pravega.client.stream.impl.Controller) Cleanup(lombok.Cleanup) Segment(io.pravega.client.segment.impl.Segment) StreamImpl(io.pravega.client.stream.impl.StreamImpl) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) Stream(io.pravega.client.stream.Stream) Test(org.junit.Test)

Example 18 with ClientFactory

use of io.pravega.client.ClientFactory in project pravega by pravega.

the class MultiReadersEndToEndTest method runTest.

private void runTest(final Set<String> streamNames, final int numParallelReaders, final int numSegments) throws Exception {
    @Cleanup StreamManager streamManager = StreamManager.create(ClientConfig.builder().controllerURI(SETUP_UTILS.getControllerUri()).build());
    streamManager.createScope(SETUP_UTILS.getScope());
    streamNames.stream().forEach(stream -> {
        streamManager.createStream(SETUP_UTILS.getScope(), stream, StreamConfiguration.builder().scope(SETUP_UTILS.getScope()).streamName(stream).scalingPolicy(ScalingPolicy.fixed(numSegments)).build());
        log.info("Created stream: {}", stream);
    });
    @Cleanup ClientFactory clientFactory = ClientFactory.withScope(SETUP_UTILS.getScope(), ClientConfig.builder().controllerURI(SETUP_UTILS.getControllerUri()).build());
    streamNames.stream().forEach(stream -> {
        EventStreamWriter<Integer> eventWriter = clientFactory.createEventWriter(stream, new IntegerSerializer(), EventWriterConfig.builder().build());
        for (Integer i = 0; i < NUM_TEST_EVENTS; i++) {
            eventWriter.writeEvent(String.valueOf(i), i);
        }
        eventWriter.flush();
        log.info("Wrote {} events", NUM_TEST_EVENTS);
    });
    final String readerGroupName = "testreadergroup" + RandomStringUtils.randomAlphanumeric(10).toLowerCase();
    @Cleanup ReaderGroupManager readerGroupManager = ReaderGroupManager.withScope(SETUP_UTILS.getScope(), ClientConfig.builder().controllerURI(SETUP_UTILS.getControllerUri()).build());
    ReaderGroupConfig.ReaderGroupConfigBuilder builder = ReaderGroupConfig.builder();
    streamNames.forEach(s -> builder.stream(Stream.of(SETUP_UTILS.getScope(), s)));
    readerGroupManager.createReaderGroup(readerGroupName, builder.build());
    Collection<Integer> read = readAllEvents(numParallelReaders, clientFactory, readerGroupName, numSegments);
    Assert.assertEquals(NUM_TEST_EVENTS * streamNames.size(), read.size());
    // Check unique events.
    Assert.assertEquals(NUM_TEST_EVENTS, new TreeSet<>(read).size());
    readerGroupManager.deleteReaderGroup(readerGroupName);
}
Also used : ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) StreamManager(io.pravega.client.admin.StreamManager) MockStreamManager(io.pravega.client.stream.mock.MockStreamManager) TreeSet(java.util.TreeSet) ClientFactory(io.pravega.client.ClientFactory) MockClientFactory(io.pravega.client.stream.mock.MockClientFactory) Cleanup(lombok.Cleanup) IntegerSerializer(io.pravega.test.integration.utils.IntegerSerializer)

Example 19 with ClientFactory

use of io.pravega.client.ClientFactory in project pravega by pravega.

the class AutoScaleTest method scaleUpTest.

/**
 * Invoke the simple scale up Test, produce traffic from multiple writers in parallel.
 * The test will periodically check if a scale event has occured by talking to controller via
 * controller client.
 *
 * @throws InterruptedException if interrupted
 * @throws URISyntaxException   If URI is invalid
 */
private CompletableFuture<Void> scaleUpTest() {
    ClientFactory clientFactory = getClientFactory();
    ControllerImpl controller = getController();
    final AtomicBoolean exit = new AtomicBoolean(false);
    startNewWriter(clientFactory, exit);
    startNewWriter(clientFactory, exit);
    startNewWriter(clientFactory, exit);
    startNewWriter(clientFactory, exit);
    startNewWriter(clientFactory, exit);
    startNewWriter(clientFactory, exit);
    // overall wait for test to complete in 260 seconds (4.2 minutes) or scale up, whichever happens first.
    return Retry.withExpBackoff(10, 10, 30, Duration.ofSeconds(10).toMillis()).retryingOn(ScaleOperationNotDoneException.class).throwingOn(RuntimeException.class).runAsync(() -> controller.getCurrentSegments(SCOPE, SCALE_UP_STREAM_NAME).thenAccept(x -> {
        log.debug("size ==" + x.getSegments().size());
        if (x.getSegments().size() == 1) {
            throw new ScaleOperationNotDoneException();
        } else {
            log.info("scale up done successfully");
            exit.set(true);
        }
    }), EXECUTOR_SERVICE);
}
Also used : EventStreamWriter(io.pravega.client.stream.EventStreamWriter) StreamImpl(io.pravega.client.stream.impl.StreamImpl) Retry(io.pravega.common.util.Retry) URISyntaxException(java.net.URISyntaxException) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cleanup(lombok.Cleanup) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) JavaSerializer(io.pravega.client.stream.impl.JavaSerializer) ControllerImpl(io.pravega.client.stream.impl.ControllerImpl) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) Service(io.pravega.test.system.framework.services.Service) Duration(java.time.Duration) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Status(io.grpc.Status) URI(java.net.URI) Utils(io.pravega.test.system.framework.Utils) Transaction(io.pravega.client.stream.Transaction) Before(org.junit.Before) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Environment(io.pravega.test.system.framework.Environment) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Executors(java.util.concurrent.Executors) StatusRuntimeException(io.grpc.StatusRuntimeException) Objects(java.util.Objects) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ClientFactory(io.pravega.client.ClientFactory) Controller(io.pravega.client.stream.impl.Controller) Collections(java.util.Collections) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Futures(io.pravega.common.concurrent.Futures) SystemTestRunner(io.pravega.test.system.framework.SystemTestRunner) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StatusRuntimeException(io.grpc.StatusRuntimeException) ClientFactory(io.pravega.client.ClientFactory) ControllerImpl(io.pravega.client.stream.impl.ControllerImpl)

Example 20 with ClientFactory

use of io.pravega.client.ClientFactory in project pravega by pravega.

the class MultiSegmentStoreTest method testReadWrite.

private void testReadWrite() {
    List<URI> ctlURIs = this.controllerInstance.getServiceDetails();
    URI controllerUri = ctlURIs.get(0);
    String scope = "testscope" + RandomStringUtils.randomAlphanumeric(10);
    String stream = "teststream" + RandomStringUtils.randomAlphanumeric(10);
    @Cleanup StreamManager streamManager = StreamManager.create(ClientConfig.builder().controllerURI(controllerUri).build());
    Assert.assertTrue(streamManager.createScope(scope));
    // Create stream with large number of segments so that most segment containers are used.
    Assert.assertTrue(streamManager.createStream(scope, stream, StreamConfiguration.builder().scope(scope).streamName(stream).scalingPolicy(ScalingPolicy.fixed(10)).build()));
    @Cleanup ClientFactory clientFactory = ClientFactory.withScope(scope, ClientConfig.builder().controllerURI(controllerUri).build());
    log.info("Invoking writer with controller URI: {}", controllerUri);
    @Cleanup EventStreamWriter<Serializable> writer = clientFactory.createEventWriter(stream, new JavaSerializer<>(), EventWriterConfig.builder().build());
    final int numEvents = 1000;
    final String fixedEvent = "testevent";
    for (int i = 0; i < numEvents; i++) {
        log.debug("Producing event: {} ", fixedEvent);
        writer.writeEvent(String.valueOf(i), fixedEvent);
    }
    writer.flush();
    log.info("Invoking reader with controller URI: {}", controllerUri);
    final String readerGroup = "testreadergroup" + RandomStringUtils.randomAlphanumeric(10);
    ReaderGroupManager groupManager = ReaderGroupManager.withScope(scope, ClientConfig.builder().controllerURI(controllerUri).build());
    groupManager.createReaderGroup(readerGroup, ReaderGroupConfig.builder().disableAutomaticCheckpoints().stream(Stream.of(scope, stream)).build());
    @Cleanup EventStreamReader<String> reader = clientFactory.createReader(UUID.randomUUID().toString(), readerGroup, new JavaSerializer<>(), ReaderConfig.builder().build());
    for (int i = 0; i < numEvents; i++) {
        try {
            String event = reader.readNextEvent(60000).getEvent();
            Assert.assertEquals(fixedEvent, event);
        } catch (ReinitializationRequiredException e) {
            log.error("Unexpected request to reinitialize {}", e);
            throw new IllegalStateException("Unexpected request to reinitialize");
        }
    }
}
Also used : Serializable(java.io.Serializable) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) ClientFactory(io.pravega.client.ClientFactory) URI(java.net.URI) Cleanup(lombok.Cleanup) ReinitializationRequiredException(io.pravega.client.stream.ReinitializationRequiredException) StreamManager(io.pravega.client.admin.StreamManager)

Aggregations

ClientFactory (io.pravega.client.ClientFactory)47 Cleanup (lombok.Cleanup)39 Test (org.junit.Test)36 HashMap (java.util.HashMap)22 ReaderGroupManager (io.pravega.client.admin.ReaderGroupManager)21 StreamConfiguration (io.pravega.client.stream.StreamConfiguration)20 ClientFactoryImpl (io.pravega.client.stream.impl.ClientFactoryImpl)20 Controller (io.pravega.client.stream.impl.Controller)17 SynchronizerConfig (io.pravega.client.state.SynchronizerConfig)15 MockConnectionFactoryImpl (io.pravega.client.stream.mock.MockConnectionFactoryImpl)15 MockController (io.pravega.client.stream.mock.MockController)15 MockSegmentStreamFactory (io.pravega.client.stream.mock.MockSegmentStreamFactory)15 PravegaNodeUri (io.pravega.shared.protocol.netty.PravegaNodeUri)15 ConnectionFactoryImpl (io.pravega.client.netty.impl.ConnectionFactoryImpl)14 Stream (io.pravega.client.stream.Stream)13 AtomicLong (java.util.concurrent.atomic.AtomicLong)13 Segment (io.pravega.client.segment.impl.Segment)12 StreamImpl (io.pravega.client.stream.impl.StreamImpl)12 ReaderGroupManagerImpl (io.pravega.client.admin.impl.ReaderGroupManagerImpl)10 ConnectionFactory (io.pravega.client.netty.impl.ConnectionFactory)9