Search in sources :

Example 31 with StreamCut

use of io.pravega.client.stream.StreamCut in project pravega by pravega.

the class MetadataScalabilityTest method truncation.

void truncation(ControllerImpl controller, List<List<Segment>> listOfEpochs) {
    int numSegments = getStreamConfig().getScalingPolicy().getMinNumSegments();
    int scalesToPerform = getScalesToPerform();
    Stream stream = new StreamImpl(SCOPE, getStreamName());
    // try SCALES_TO_PERFORM randomly generated stream cuts and truncate stream at those
    // stream cuts.
    List<AtomicInteger> indexes = new LinkedList<>();
    Random rand = new Random();
    for (int i = 0; i < numSegments; i++) {
        indexes.add(new AtomicInteger(1));
    }
    Futures.loop(() -> indexes.stream().allMatch(x -> x.get() < scalesToPerform - 1), () -> {
        // We randomly generate a stream cut in each iteration of this loop. A valid stream
        // cut in this scenario contains for each position i in [0, numSegments -1], a segment
        // from one of the scale epochs of the stream. For each position i, we randomly
        // choose an epoch and pick the segment at position i. It increments the epoch
        // index accordingly (indexes list) so that in the next iteration it chooses a later
        // epoch for the same i.
        // 
        // Because the segment in position i always contain the range [d * (i-1), d * i],
        // where d = 1 / (number of segments), the stream cut is guaranteed to cover
        // the entire key space.
        Map<Segment, Long> map = new HashMap<>();
        for (int i = 0; i < numSegments; i++) {
            AtomicInteger index = indexes.get(i);
            index.set(index.get() + rand.nextInt(scalesToPerform - index.get()));
            map.put(listOfEpochs.get(index.get()).get(i), 0L);
        }
        StreamCut cut = new StreamCutImpl(stream, map);
        log.info("truncating stream at {}", map);
        return controller.truncateStream(SCOPE, streamName, cut).thenCompose(truncated -> {
            log.info("stream truncated successfully at {}", cut);
            assertTrue(truncated);
            // we will just validate that a non empty value is returned.
            return controller.getSuccessors(cut).thenAccept(successors -> {
                assertTrue(successors.getSegments().size() > 0);
                log.info("Successors for streamcut {} are {}", cut, successors);
            });
        });
    }, executorService).join();
}
Also used : Segment(io.pravega.client.segment.impl.Segment) StreamCut(io.pravega.client.stream.StreamCut) StreamImpl(io.pravega.client.stream.impl.StreamImpl) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Random(java.util.Random) CompletableFuture(java.util.concurrent.CompletableFuture) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Stream(io.pravega.client.stream.Stream) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) Map(java.util.Map) After(org.junit.After) Timeout(org.junit.rules.Timeout) URI(java.net.URI) LinkedList(java.util.LinkedList) Before(org.junit.Before) Environment(io.pravega.test.system.framework.Environment) NameUtils(io.pravega.shared.NameUtils) Assert.assertTrue(org.junit.Assert.assertTrue) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Rule(org.junit.Rule) ControllerImpl(io.pravega.client.control.impl.ControllerImpl) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Comparator(java.util.Comparator) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) SystemTestRunner(io.pravega.test.system.framework.SystemTestRunner) StreamCut(io.pravega.client.stream.StreamCut) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) StreamImpl(io.pravega.client.stream.impl.StreamImpl) Stream(io.pravega.client.stream.Stream) HashMap(java.util.HashMap) Map(java.util.Map) LinkedList(java.util.LinkedList)

Example 32 with StreamCut

use of io.pravega.client.stream.StreamCut in project pravega by pravega.

the class OffsetTruncationTest method offsetTruncationTest.

/**
 * This test verifies that truncation works specifying an offset that applies to multiple segments. To this end,
 * the test first writes a set of events on a Stream (with multiple segments) and truncates it at a specified offset
 * (truncatedEvents). The tests asserts that readers first get a TruncatedDataException as they are attempting to
 * read a truncated segment, and then they only read the remaining events that have not been truncated.
 */
@Test
public void offsetTruncationTest() {
    final int totalEvents = 200;
    final int truncatedEvents = 50;
    final ClientConfig clientConfig = Utils.buildClientConfig(controllerURI);
    @Cleanup ConnectionFactory connectionFactory = new SocketConnectionFactoryImpl(clientConfig);
    ControllerImpl controller = new ControllerImpl(ControllerImplConfig.builder().clientConfig(clientConfig).build(), connectionFactory.getInternalExecutor());
    @Cleanup ClientFactoryImpl clientFactory = new ClientFactoryImpl(SCOPE, controller, connectionFactory);
    log.info("Invoking offsetTruncationTest test with Controller URI: {}", controllerURI);
    @Cleanup ReaderGroupManager groupManager = ReaderGroupManager.withScope(SCOPE, clientConfig);
    groupManager.createReaderGroup(READER_GROUP, ReaderGroupConfig.builder().stream(Stream.of(SCOPE, STREAM)).build());
    @Cleanup ReaderGroup readerGroup = groupManager.getReaderGroup(READER_GROUP);
    // Write events to the Stream.
    writeEvents(clientFactory, STREAM, totalEvents);
    // Instantiate readers to consume from Stream up to truncatedEvents.
    List<CompletableFuture<Integer>> futures = readEventFutures(clientFactory, READER_GROUP, PARALLELISM, truncatedEvents);
    Futures.allOf(futures).join();
    // Ensure that we have read all the events required before initiating the checkpoint.
    assertEquals("Number of events read is not the expected one.", (Integer) truncatedEvents, futures.stream().map(f -> Futures.getAndHandleExceptions(f, RuntimeException::new)).reduce(Integer::sum).get());
    // Perform truncation on stream segment.
    Checkpoint cp = readerGroup.initiateCheckpoint("truncationCheckpoint", executor).join();
    StreamCut streamCut = cp.asImpl().getPositions().values().iterator().next();
    StreamCut alternativeStreamCut = readerGroup.generateStreamCuts(executor).join().get(Stream.of(SCOPE, STREAM));
    assertEquals("StreamCuts for reader group differ depending on how they are generated.", streamCut, alternativeStreamCut);
    assertTrue(streamManager.truncateStream(SCOPE, STREAM, streamCut));
    // Just after the truncation, read events from the offset defined in truncate call onwards.
    final String newGroupName = READER_GROUP + "new";
    groupManager.createReaderGroup(newGroupName, ReaderGroupConfig.builder().stream(Stream.of(SCOPE, STREAM)).build());
    futures = readEventFutures(clientFactory, newGroupName, PARALLELISM);
    Futures.allOf(futures).join();
    assertEquals("Expected read events: ", totalEvents - truncatedEvents, (int) futures.stream().map(CompletableFuture::join).reduce(Integer::sum).get());
    log.debug("The stream has been successfully truncated at event {}. Offset truncation test passed.", truncatedEvents);
}
Also used : StreamCut(io.pravega.client.stream.StreamCut) MarathonException(mesosphere.marathon.client.MarathonException) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) StreamManager(io.pravega.client.admin.StreamManager) RunWith(org.junit.runner.RunWith) Cleanup(lombok.Cleanup) CompletableFuture(java.util.concurrent.CompletableFuture) ReaderGroup(io.pravega.client.stream.ReaderGroup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) Service(io.pravega.test.system.framework.services.Service) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) After(org.junit.After) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Timeout(org.junit.rules.Timeout) Checkpoint(io.pravega.client.stream.Checkpoint) URI(java.net.URI) Utils(io.pravega.test.system.framework.Utils) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) Before(org.junit.Before) Environment(io.pravega.test.system.framework.Environment) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) ControllerImplConfig(io.pravega.client.control.impl.ControllerImplConfig) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Rule(org.junit.Rule) ControllerImpl(io.pravega.client.control.impl.ControllerImpl) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) RandomFactory(io.pravega.common.hash.RandomFactory) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Futures(io.pravega.common.concurrent.Futures) SystemTestRunner(io.pravega.test.system.framework.SystemTestRunner) Assert.assertEquals(org.junit.Assert.assertEquals) ClientConfig(io.pravega.client.ClientConfig) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) StreamCut(io.pravega.client.stream.StreamCut) ReaderGroup(io.pravega.client.stream.ReaderGroup) ControllerImpl(io.pravega.client.control.impl.ControllerImpl) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) Cleanup(lombok.Cleanup) Checkpoint(io.pravega.client.stream.Checkpoint) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) CompletableFuture(java.util.concurrent.CompletableFuture) Checkpoint(io.pravega.client.stream.Checkpoint) ClientConfig(io.pravega.client.ClientConfig) Test(org.junit.Test)

Example 33 with StreamCut

use of io.pravega.client.stream.StreamCut in project pravega by pravega.

the class ReaderGroupStreamCutUpdateTest method testStreamcutsUpdateInReaderGroup.

@Test(timeout = 60000)
public void testStreamcutsUpdateInReaderGroup() throws Exception {
    final String scope = "testStreamcutsUpdateInReaderGroup";
    final String stream = "myStream";
    final String readerGroupName = "testStreamcutsUpdateInReaderGroupRG";
    final int checkpointingIntervalMs = 2000;
    final int readerSleepInterval = 250;
    final int numEvents = 100;
    // First, create the stream.
    @Cleanup StreamManager streamManager = StreamManager.create(controllerURI);
    Assert.assertTrue(streamManager.createScope(scope));
    StreamConfiguration streamConfiguration = StreamConfiguration.builder().scalingPolicy(ScalingPolicy.fixed(2)).build();
    streamManager.createStream(scope, stream, streamConfiguration);
    // Write some events in the stream.
    @Cleanup EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope(scope, ClientConfig.builder().controllerURI(controllerURI).build());
    writeEvents(clientFactory, stream, numEvents);
    // Read the events and test that positions are getting updated.
    ReaderGroupConfig readerGroupConfig = ReaderGroupConfig.builder().stream(Stream.of(scope, stream)).automaticCheckpointIntervalMillis(checkpointingIntervalMs).build();
    @Cleanup ReaderGroupManager readerGroupManager = ReaderGroupManager.withScope(scope, controllerURI);
    readerGroupManager.createReaderGroup(readerGroupName, readerGroupConfig);
    ReaderGroup readerGroup = readerGroupManager.getReaderGroup(readerGroupName);
    @Cleanup EventStreamReader<Double> reader = clientFactory.createReader("myReader", readerGroupName, new JavaSerializer<>(), ReaderConfig.builder().build());
    Map<Stream, StreamCut> currentStreamcuts = readerGroup.getStreamCuts();
    EventRead<Double> eventRead;
    int lastIteration = 0, iteration = 0;
    int assertionFrequency = checkpointingIntervalMs / readerSleepInterval;
    do {
        eventRead = reader.readNextEvent(5000);
        // Check that the streamcuts are being updated periodically via automatic reader group checkpoints.
        if (iteration != lastIteration && iteration % assertionFrequency == 0) {
            log.info("Comparing streamcuts: {} / {} in iteration {}.", currentStreamcuts, readerGroup.getStreamCuts(), iteration);
            Assert.assertNotEquals(currentStreamcuts, readerGroup.getStreamCuts());
            currentStreamcuts = readerGroup.getStreamCuts();
            lastIteration = iteration;
        }
        Thread.sleep(readerSleepInterval);
        if (!eventRead.isCheckpoint()) {
            iteration++;
        }
    } while ((eventRead.isCheckpoint() || eventRead.getEvent() != null) && iteration < numEvents);
}
Also used : ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) StreamCut(io.pravega.client.stream.StreamCut) ReaderGroup(io.pravega.client.stream.ReaderGroup) EventStreamClientFactory(io.pravega.client.EventStreamClientFactory) Cleanup(lombok.Cleanup) StreamManager(io.pravega.client.admin.StreamManager) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) Stream(io.pravega.client.stream.Stream) Test(org.junit.Test)

Example 34 with StreamCut

use of io.pravega.client.stream.StreamCut in project pravega by pravega.

the class RestoreBackUpDataRecoveryTest method getStreamCutsFromWaterMarks.

private List<Map<Stream, StreamCut>> getStreamCutsFromWaterMarks(Stream streamObj, LinkedBlockingQueue<Watermark> watermarks) throws InterruptedException {
    Watermark watermark0 = watermarks.take();
    Watermark watermark1 = watermarks.take();
    assertTrue(watermark0.getLowerTimeBound() <= watermark0.getUpperTimeBound());
    assertTrue(watermark1.getLowerTimeBound() <= watermark1.getUpperTimeBound());
    assertTrue(watermark0.getLowerTimeBound() < watermark1.getLowerTimeBound());
    Map<Segment, Long> positionMap0 = watermark0.getStreamCut().entrySet().stream().collect(Collectors.toMap(x -> new Segment(SCOPE, STREAM1, x.getKey().getSegmentId()), Map.Entry::getValue));
    Map<Segment, Long> positionMap1 = watermark1.getStreamCut().entrySet().stream().collect(Collectors.toMap(x -> new Segment(SCOPE, STREAM1, x.getKey().getSegmentId()), Map.Entry::getValue));
    StreamCut streamCutFirst = new StreamCutImpl(streamObj, positionMap0);
    StreamCut streamCutSecond = new StreamCutImpl(streamObj, positionMap1);
    Map<Stream, StreamCut> firstMarkStreamCut = Collections.singletonMap(streamObj, streamCutFirst);
    Map<Stream, StreamCut> secondMarkStreamCut = Collections.singletonMap(streamObj, streamCutSecond);
    return Arrays.asList(firstMarkStreamCut, secondMarkStreamCut);
}
Also used : Arrays(java.util.Arrays) StreamCut(io.pravega.client.stream.StreamCut) Storage(io.pravega.segmentstore.storage.Storage) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Cleanup(lombok.Cleanup) JavaSerializer(io.pravega.client.stream.impl.JavaSerializer) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ServiceBuilderConfig(io.pravega.segmentstore.server.store.ServiceBuilderConfig) EventRead(io.pravega.client.stream.EventRead) ServiceBuilder(io.pravega.segmentstore.server.store.ServiceBuilder) Position(io.pravega.client.stream.Position) InMemoryStorageFactory(io.pravega.segmentstore.storage.mocks.InMemoryStorageFactory) Duration(java.time.Duration) Map(java.util.Map) ContainerConfig(io.pravega.segmentstore.server.containers.ContainerConfig) InMemoryDurableDataLogFactory(io.pravega.segmentstore.storage.mocks.InMemoryDurableDataLogFactory) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) DurableLogFactory(io.pravega.segmentstore.server.logs.DurableLogFactory) DurableLogConfig(io.pravega.segmentstore.server.logs.DurableLogConfig) DebugStreamSegmentContainer(io.pravega.segmentstore.server.containers.DebugStreamSegmentContainer) Slf4j(lombok.extern.slf4j.Slf4j) StreamManagerImpl(io.pravega.client.admin.impl.StreamManagerImpl) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) TestUtils(io.pravega.test.common.TestUtils) ControllerWrapper(io.pravega.test.integration.demo.ControllerWrapper) Futures(io.pravega.common.concurrent.Futures) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) DebugStreamSegmentContainerTests(io.pravega.segmentstore.server.containers.DebugStreamSegmentContainerTests) StorageFactory(io.pravega.segmentstore.storage.StorageFactory) BookKeeperConfig(io.pravega.segmentstore.storage.impl.bookkeeper.BookKeeperConfig) ArrayList(java.util.ArrayList) DurableDataLogException(io.pravega.segmentstore.storage.DurableDataLogException) RevisionedStreamClient(io.pravega.client.state.RevisionedStreamClient) lombok.val(lombok.val) Assert.assertTrue(org.junit.Assert.assertTrue) EventStreamReader(io.pravega.client.stream.EventStreamReader) Test(org.junit.Test) Watermark(io.pravega.shared.watermarks.Watermark) AtomicLong(java.util.concurrent.atomic.AtomicLong) Assert.assertNull(org.junit.Assert.assertNull) OperationLogFactory(io.pravega.segmentstore.server.OperationLogFactory) ReaderConfig(io.pravega.client.stream.ReaderConfig) TxnFailedException(io.pravega.client.stream.TxnFailedException) Assert(org.junit.Assert) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Futures.loop(io.pravega.common.concurrent.Futures.loop) WriterConfig(io.pravega.segmentstore.server.writer.WriterConfig) TableStore(io.pravega.segmentstore.contracts.tables.TableStore) AssertExtensions(io.pravega.test.common.AssertExtensions) Random(java.util.Random) ReaderGroup(io.pravega.client.stream.ReaderGroup) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) After(org.junit.After) TimeWindow(io.pravega.client.stream.TimeWindow) URI(java.net.URI) PravegaConnectionListener(io.pravega.segmentstore.server.host.handler.PravegaConnectionListener) Transaction(io.pravega.client.stream.Transaction) Services(io.pravega.common.concurrent.Services) WatermarkSerializer(io.pravega.client.watermark.WatermarkSerializer) CompletionException(java.util.concurrent.CompletionException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Controller(io.pravega.client.control.impl.Controller) UTF8StringSerializer(io.pravega.client.stream.impl.UTF8StringSerializer) Segment(io.pravega.client.segment.impl.Segment) SegmentRollingPolicy(io.pravega.segmentstore.storage.SegmentRollingPolicy) StreamManager(io.pravega.client.admin.StreamManager) ServiceConfig(io.pravega.segmentstore.server.store.ServiceConfig) AsyncStorageWrapper(io.pravega.segmentstore.storage.AsyncStorageWrapper) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ContainerRecoveryUtils(io.pravega.segmentstore.server.containers.ContainerRecoveryUtils) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionPoolImpl(io.pravega.client.connection.impl.ConnectionPoolImpl) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) SynchronizerConfig(io.pravega.client.state.SynchronizerConfig) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) TransactionalEventStreamWriter(io.pravega.client.stream.TransactionalEventStreamWriter) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) NameUtils(io.pravega.shared.NameUtils) BookKeeperServiceRunner(io.pravega.segmentstore.storage.impl.bookkeeper.BookKeeperServiceRunner) Iterator(java.util.Iterator) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) RollingStorage(io.pravega.segmentstore.storage.rolling.RollingStorage) Assert.assertNotNull(org.junit.Assert.assertNotNull) TimeUnit(java.util.concurrent.TimeUnit) SynchronizerClientFactory(io.pravega.client.SynchronizerClientFactory) Revision(io.pravega.client.state.Revision) Collections(java.util.Collections) ClientConfig(io.pravega.client.ClientConfig) StreamCut(io.pravega.client.stream.StreamCut) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) AtomicLong(java.util.concurrent.atomic.AtomicLong) Stream(io.pravega.client.stream.Stream) Watermark(io.pravega.shared.watermarks.Watermark) Map(java.util.Map) HashMap(java.util.HashMap) Segment(io.pravega.client.segment.impl.Segment)

Example 35 with StreamCut

use of io.pravega.client.stream.StreamCut in project pravega by pravega.

the class WatermarkingTest method watermarkTest.

@Test(timeout = 120000)
public void watermarkTest() throws Exception {
    Controller controller = PRAVEGA.getLocalController();
    String scope = "scope";
    String stream = "watermarkTest";
    StreamConfiguration config = StreamConfiguration.builder().scalingPolicy(ScalingPolicy.fixed(5)).build();
    ClientConfig clientConfig = ClientConfig.builder().controllerURI(PRAVEGA.getControllerURI()).build();
    @Cleanup StreamManager streamManager = StreamManager.create(clientConfig);
    streamManager.createScope(scope);
    streamManager.createStream(scope, stream, config);
    Stream streamObj = Stream.of(scope, stream);
    // create 2 writers
    @Cleanup EventStreamClientFactory clientFactory = EventStreamClientFactory.withScope(scope, clientConfig);
    JavaSerializer<Long> javaSerializer = new JavaSerializer<>();
    @Cleanup EventStreamWriter<Long> writer1 = clientFactory.createEventWriter(stream, javaSerializer, EventWriterConfig.builder().build());
    @Cleanup EventStreamWriter<Long> writer2 = clientFactory.createEventWriter(stream, javaSerializer, EventWriterConfig.builder().build());
    AtomicBoolean stopFlag = new AtomicBoolean(false);
    // write events
    CompletableFuture<Void> writer1Future = writeEvents(writer1, stopFlag);
    CompletableFuture<Void> writer2Future = writeEvents(writer2, stopFlag);
    // scale the stream several times so that we get complex positions
    scale(controller, streamObj, config);
    @Cleanup ConnectionFactory connectionFactory = new SocketConnectionFactoryImpl(clientConfig);
    @Cleanup ClientFactoryImpl syncClientFactory = new ClientFactoryImpl(scope, new ControllerImpl(ControllerImplConfig.builder().clientConfig(clientConfig).build(), connectionFactory.getInternalExecutor()), connectionFactory);
    String markStream = NameUtils.getMarkStreamForStream(stream);
    @Cleanup RevisionedStreamClient<Watermark> watermarkReader = syncClientFactory.createRevisionedStreamClient(markStream, new WatermarkSerializer(), SynchronizerConfig.builder().build());
    LinkedBlockingQueue<Watermark> watermarks = new LinkedBlockingQueue<>();
    fetchWatermarks(watermarkReader, watermarks, stopFlag);
    AssertExtensions.assertEventuallyEquals(true, () -> watermarks.size() >= 2, 100000);
    stopFlag.set(true);
    writer1Future.join();
    writer2Future.join();
    // read events from the stream
    @Cleanup ReaderGroupManager readerGroupManager = new ReaderGroupManagerImpl(scope, controller, syncClientFactory);
    Watermark watermark0 = watermarks.take();
    Watermark watermark1 = watermarks.take();
    assertTrue(watermark0.getLowerTimeBound() <= watermark0.getUpperTimeBound());
    assertTrue(watermark1.getLowerTimeBound() <= watermark1.getUpperTimeBound());
    assertTrue(watermark0.getLowerTimeBound() < watermark1.getLowerTimeBound());
    Map<Segment, Long> positionMap0 = watermark0.getStreamCut().entrySet().stream().collect(Collectors.toMap(x -> new Segment(scope, stream, x.getKey().getSegmentId()), Map.Entry::getValue));
    Map<Segment, Long> positionMap1 = watermark1.getStreamCut().entrySet().stream().collect(Collectors.toMap(x -> new Segment(scope, stream, x.getKey().getSegmentId()), Map.Entry::getValue));
    StreamCut streamCutFirst = new StreamCutImpl(streamObj, positionMap0);
    StreamCut streamCutSecond = new StreamCutImpl(streamObj, positionMap1);
    Map<Stream, StreamCut> firstMarkStreamCut = Collections.singletonMap(streamObj, streamCutFirst);
    Map<Stream, StreamCut> secondMarkStreamCut = Collections.singletonMap(streamObj, streamCutSecond);
    // read from stream cut of first watermark
    String readerGroup = "watermarkTest-group";
    readerGroupManager.createReaderGroup(readerGroup, ReaderGroupConfig.builder().stream(streamObj).startingStreamCuts(firstMarkStreamCut).endingStreamCuts(secondMarkStreamCut).disableAutomaticCheckpoints().build());
    @Cleanup final EventStreamReader<Long> reader = clientFactory.createReader("myreader", readerGroup, javaSerializer, ReaderConfig.builder().build());
    EventRead<Long> event = reader.readNextEvent(10000L);
    TimeWindow currentTimeWindow = reader.getCurrentTimeWindow(streamObj);
    while (event.getEvent() != null && currentTimeWindow.getLowerTimeBound() == null && currentTimeWindow.getUpperTimeBound() == null) {
        event = reader.readNextEvent(10000L);
        currentTimeWindow = reader.getCurrentTimeWindow(streamObj);
    }
    assertNotNull(currentTimeWindow.getUpperTimeBound());
    // read all events and verify that all events are below the bounds
    while (event.getEvent() != null) {
        Long time = event.getEvent();
        log.info("timewindow = {} event = {}", currentTimeWindow, time);
        assertTrue(currentTimeWindow.getLowerTimeBound() == null || time >= currentTimeWindow.getLowerTimeBound());
        assertTrue(currentTimeWindow.getUpperTimeBound() == null || time <= currentTimeWindow.getUpperTimeBound());
        TimeWindow nextTimeWindow = reader.getCurrentTimeWindow(streamObj);
        assertTrue(currentTimeWindow.getLowerTimeBound() == null || nextTimeWindow.getLowerTimeBound() >= currentTimeWindow.getLowerTimeBound());
        assertTrue(currentTimeWindow.getUpperTimeBound() == null || nextTimeWindow.getUpperTimeBound() >= currentTimeWindow.getUpperTimeBound());
        currentTimeWindow = nextTimeWindow;
        event = reader.readNextEvent(10000L);
        if (event.isCheckpoint()) {
            event = reader.readNextEvent(10000L);
        }
    }
    assertNotNull(currentTimeWindow.getLowerTimeBound());
}
Also used : StreamCut(io.pravega.client.stream.StreamCut) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) AssertExtensions(io.pravega.test.common.AssertExtensions) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Cleanup(lombok.Cleanup) JavaSerializer(io.pravega.client.stream.impl.JavaSerializer) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) EventRead(io.pravega.client.stream.EventRead) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) Duration(java.time.Duration) Map(java.util.Map) TimeWindow(io.pravega.client.stream.TimeWindow) ClassRule(org.junit.ClassRule) Transaction(io.pravega.client.stream.Transaction) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) WatermarkSerializer(io.pravega.client.watermark.WatermarkSerializer) CompletionException(java.util.concurrent.CompletionException) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) ControllerImplConfig(io.pravega.client.control.impl.ControllerImplConfig) Slf4j(lombok.extern.slf4j.Slf4j) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) Segment(io.pravega.client.segment.impl.Segment) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) StreamManager(io.pravega.client.admin.StreamManager) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) EventStreamClientFactory(io.pravega.client.EventStreamClientFactory) RevisionedStreamClient(io.pravega.client.state.RevisionedStreamClient) SynchronizerConfig(io.pravega.client.state.SynchronizerConfig) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) TransactionalEventStreamWriter(io.pravega.client.stream.TransactionalEventStreamWriter) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) NameUtils(io.pravega.shared.NameUtils) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) EventStreamReader(io.pravega.client.stream.EventStreamReader) Test(org.junit.Test) Watermark(io.pravega.shared.watermarks.Watermark) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Assert.assertNull(org.junit.Assert.assertNull) SynchronizerClientFactory(io.pravega.client.SynchronizerClientFactory) ControllerImpl(io.pravega.client.control.impl.ControllerImpl) Revision(io.pravega.client.state.Revision) ReaderConfig(io.pravega.client.stream.ReaderConfig) TxnFailedException(io.pravega.client.stream.TxnFailedException) Collections(java.util.Collections) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Assert.assertEquals(org.junit.Assert.assertEquals) ClientConfig(io.pravega.client.ClientConfig) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) EventStreamClientFactory(io.pravega.client.EventStreamClientFactory) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Cleanup(lombok.Cleanup) JavaSerializer(io.pravega.client.stream.impl.JavaSerializer) Segment(io.pravega.client.segment.impl.Segment) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) Stream(io.pravega.client.stream.Stream) ClientConfig(io.pravega.client.ClientConfig) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) StreamCut(io.pravega.client.stream.StreamCut) ControllerImpl(io.pravega.client.control.impl.ControllerImpl) WatermarkSerializer(io.pravega.client.watermark.WatermarkSerializer) Controller(io.pravega.client.control.impl.Controller) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) TimeWindow(io.pravega.client.stream.TimeWindow) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamManager(io.pravega.client.admin.StreamManager) AtomicLong(java.util.concurrent.atomic.AtomicLong) Watermark(io.pravega.shared.watermarks.Watermark) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Aggregations

StreamCut (io.pravega.client.stream.StreamCut)79 Stream (io.pravega.client.stream.Stream)65 Test (org.junit.Test)65 Segment (io.pravega.client.segment.impl.Segment)48 ReaderGroupConfig (io.pravega.client.stream.ReaderGroupConfig)47 HashMap (java.util.HashMap)39 StreamCutImpl (io.pravega.client.stream.impl.StreamCutImpl)37 Cleanup (lombok.Cleanup)30 StreamConfiguration (io.pravega.client.stream.StreamConfiguration)26 Map (java.util.Map)25 ReaderGroupManager (io.pravega.client.admin.ReaderGroupManager)21 ScalingPolicy (io.pravega.client.stream.ScalingPolicy)21 ArgumentMatchers.anyLong (org.mockito.ArgumentMatchers.anyLong)20 CompletableFuture (java.util.concurrent.CompletableFuture)19 ReaderGroup (io.pravega.client.stream.ReaderGroup)18 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)18 EventStreamClientFactory (io.pravega.client.EventStreamClientFactory)17 ClientConfig (io.pravega.client.ClientConfig)16 Futures (io.pravega.common.concurrent.Futures)15 AtomicLong (java.util.concurrent.atomic.AtomicLong)15