Search in sources :

Example 26 with ObserveHandle

use of cz.o2.proxima.direct.commitlog.ObserveHandle in project proxima-platform by O2-Czech-Republic.

the class InMemStorageTest method testObserveMultiplePartitions.

@Test
public void testObserveMultiplePartitions() throws InterruptedException {
    final int numPartitions = 3;
    final InMemStorage storage = new InMemStorage();
    final DataAccessor accessor = storage.createAccessor(direct, createFamilyDescriptor(URI.create("inmem:///test"), numPartitions));
    final CommitLogReader reader = Optionals.get(accessor.getCommitLogReader(direct.getContext()));
    final AttributeWriterBase writer = Optionals.get(accessor.getWriter(direct.getContext()));
    final int numElements = 1_000;
    final ConcurrentMap<Partition, Long> partitionHistogram = new ConcurrentHashMap<>();
    final CountDownLatch elementsReceived = new CountDownLatch(numElements);
    // Start observer.
    final ObserveHandle observeHandle = reader.observePartitions(reader.getPartitions(), new CommitLogObserver() {

        @Override
        public void onRepartition(OnRepartitionContext context) {
            assertEquals(numPartitions, context.partitions().size());
        }

        @Override
        public boolean onNext(StreamElement ingest, OnNextContext context) {
            partitionHistogram.merge(context.getPartition(), 1L, Long::sum);
            context.confirm();
            elementsReceived.countDown();
            return elementsReceived.getCount() > 0;
        }

        @Override
        public boolean onError(Throwable error) {
            throw new RuntimeException(error);
        }
    });
    // Write data.
    for (int i = 0; i < numElements; i++) {
        writer.online().write(StreamElement.upsert(entity, data, UUID.randomUUID().toString(), "key_" + i, data.getName(), System.currentTimeMillis(), new byte[] { 1, 2, 3 }), CommitCallback.noop());
    }
    // Wait for all elements to be received.
    elementsReceived.await();
    assertEquals(3, partitionHistogram.size());
    assertEquals(3, observeHandle.getCurrentOffsets().size());
}
Also used : Partition(cz.o2.proxima.storage.Partition) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) DataAccessor(cz.o2.proxima.direct.core.DataAccessor) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) AttributeWriterBase(cz.o2.proxima.direct.core.AttributeWriterBase) StreamElement(cz.o2.proxima.storage.StreamElement) CountDownLatch(java.util.concurrent.CountDownLatch) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Example 27 with ObserveHandle

use of cz.o2.proxima.direct.commitlog.ObserveHandle in project proxima-platform by O2-Czech-Republic.

the class InMemStorageTest method testObserveOffsets.

@Test(timeout = 10000)
public void testObserveOffsets() throws InterruptedException {
    InMemStorage storage = new InMemStorage();
    DataAccessor accessor = storage.createAccessor(direct, createFamilyDescriptor(URI.create("inmem:///inmemstoragetest")));
    CommitLogReader reader = Optionals.get(accessor.getCommitLogReader(direct.getContext()));
    AttributeWriterBase writer = Optionals.get(accessor.getWriter(direct.getContext()));
    List<Byte> received = new ArrayList<>();
    CommitLogObserver observer = new CommitLogObserver() {

        @Override
        public void onRepartition(CommitLogObserver.OnRepartitionContext context) {
            assertEquals(1, context.partitions().size());
        }

        @Override
        public boolean onNext(StreamElement ingest, CommitLogObserver.OnNextContext context) {
            assertEquals(0, context.getPartition().getId());
            received.add(ingest.getValue()[0]);
            return false;
        }

        @Override
        public boolean onError(Throwable error) {
            throw new RuntimeException(error);
        }
    };
    ObserveHandle handle = reader.observePartitions(reader.getPartitions(), observer);
    writer.online().write(StreamElement.upsert(entity, data, UUID.randomUUID().toString(), "key", data.getName(), System.currentTimeMillis(), new byte[] { 1 }), (succ, exc) -> {
    });
    List<Offset> offsets = handle.getCurrentOffsets();
    assertEquals(1, offsets.size());
    assertTrue(offsets.get(0).getWatermark() > 0);
    assertEquals(Collections.singletonList((byte) 1), received);
    handle.close();
    handle = reader.observeBulkOffsets(offsets, observer);
    handle.waitUntilReady();
    offsets = handle.getCurrentOffsets();
    assertEquals(1, offsets.size());
    assertTrue("Expected positive watermark, got " + offsets.get(0).getWatermark(), offsets.get(0).getWatermark() > 0);
    writer.online().write(StreamElement.upsert(entity, data, UUID.randomUUID().toString(), "key", data.getName(), System.currentTimeMillis(), new byte[] { 2 }), (succ, exc) -> {
    });
    assertEquals(Arrays.asList((byte) 1, (byte) 1), received);
    assertEquals(0, ((ConsumedOffset) handle.getCurrentOffsets().get(0)).getConsumedKeyAttr().size());
    handle.close();
}
Also used : ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) DataAccessor(cz.o2.proxima.direct.core.DataAccessor) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) AttributeWriterBase(cz.o2.proxima.direct.core.AttributeWriterBase) ArrayList(java.util.ArrayList) StreamElement(cz.o2.proxima.storage.StreamElement) ConsumedOffset(cz.o2.proxima.direct.storage.InMemStorage.ConsumedOffset) Offset(cz.o2.proxima.direct.commitlog.Offset) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) ConsumedOffset(cz.o2.proxima.direct.storage.InMemStorage.ConsumedOffset) Test(org.junit.Test)

Example 28 with ObserveHandle

use of cz.o2.proxima.direct.commitlog.ObserveHandle in project proxima-platform by O2-Czech-Republic.

the class ListBatchReader method observe.

@Override
public ObserveHandle observe(List<Partition> partitions, List<AttributeDescriptor<?>> attributes, BatchLogObserver observer) {
    Preconditions.checkArgument(partitions != null);
    Preconditions.checkArgument(attributes != null);
    Preconditions.checkArgument(observer != null);
    Set<AttributeDescriptor<?>> attrSet = new HashSet<>(attributes);
    TerminationContext terminationContext = new TerminationContext(observer);
    context.getExecutorService().submit(() -> {
        terminationContext.setRunningThread();
        for (int i = 0; i < partitions.size() && !terminationContext.isCancelled(); i++) {
            long elementIndex = 0;
            final Partition partition = partitions.get(i);
            final Iterator<StreamElement> iterator = data.get(partition.getId()).iterator();
            while (!Thread.currentThread().isInterrupted() && !terminationContext.isCancelled() && iterator.hasNext()) {
                final StreamElement element = iterator.next();
                final Offset offset = Offset.of(partition, elementIndex++, !iterator.hasNext());
                if (attrSet.contains(element.getAttributeDescriptor()) && !observer.onNext(element, BatchLogObservers.withWatermark(partition, offset, Watermarks.MIN_WATERMARK))) {
                    terminationContext.cancel();
                    break;
                }
            }
        }
        terminationContext.finished();
    });
    return terminationContext.asObserveHandle();
}
Also used : Partition(cz.o2.proxima.storage.Partition) AttributeDescriptor(cz.o2.proxima.repository.AttributeDescriptor) StreamElement(cz.o2.proxima.storage.StreamElement) TerminationContext(cz.o2.proxima.direct.batch.TerminationContext) HashSet(java.util.HashSet) Offset(cz.o2.proxima.direct.batch.Offset)

Example 29 with ObserveHandle

use of cz.o2.proxima.direct.commitlog.ObserveHandle in project proxima-platform by O2-Czech-Republic.

the class ListCommitLog method observe.

@Override
public ObserveHandle observe(@Nullable String name, Position position, CommitLogObserver observer) {
    String consumerName = name == null ? UUID.randomUUID().toString() : name;
    Consumer consumer = CONSUMERS.get(uuid).computeIfAbsent(consumerName, k -> new Consumer(uuid, consumerName, watermarkEstimator));
    ListObserveHandle handle = new ListObserveHandle(uuid, consumerName);
    pushTo((element, offset) -> {
        if (handle.isClosed()) {
            return false;
        }
        final CommitLogObserver.OffsetCommitter committer = (succ, exc) -> {
            if (exc != null) {
                observer.onError(exc);
            }
        };
        final boolean acceptable;
        OnNextContext context = null;
        synchronized (consumer) {
            acceptable = (externalizableOffsets || !consumer.getAckedOffsets().contains(offset) && !consumer.getInflightOffsets().contains(offset));
            if (acceptable) {
                context = consumer.asOnNextContext(committer, offset);
            }
        }
        if (acceptable) {
            return observer.onNext(element, context);
        }
        return true;
    }, externalizableOffsets ? () -> true : allMatchOffset(consumer::isAcked), observer::onCompleted, observer::onCancelled);
    return handle;
}
Also used : CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) Context(cz.o2.proxima.direct.core.Context) IntStream(java.util.stream.IntStream) Iterables(com.google.common.collect.Iterables) Getter(lombok.Getter) Partition(cz.o2.proxima.storage.Partition) OffsetCommitter(cz.o2.proxima.direct.commitlog.CommitLogObserver.OffsetCommitter) URISyntaxException(java.net.URISyntaxException) HashMap(java.util.HashMap) Function(java.util.function.Function) ObserverUtils(cz.o2.proxima.direct.commitlog.ObserverUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) StreamElement(cz.o2.proxima.storage.StreamElement) WatermarkEstimator(cz.o2.proxima.time.WatermarkEstimator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Watermarks(cz.o2.proxima.time.Watermarks) UnaryPredicate(cz.o2.proxima.functional.UnaryPredicate) SerializationException(cz.o2.proxima.scheme.SerializationException) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) Nonnull(javax.annotation.Nonnull) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) OffsetExternalizer(cz.o2.proxima.direct.commitlog.OffsetExternalizer) BiFunction(cz.o2.proxima.functional.BiFunction) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MoreObjects(com.google.common.base.MoreObjects) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) Set(java.util.Set) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Offset(cz.o2.proxima.direct.commitlog.Offset) Objects(java.util.Objects) List(java.util.List) OnNextContext(cz.o2.proxima.direct.commitlog.CommitLogObserver.OnNextContext) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) Position(cz.o2.proxima.storage.commitlog.Position) ObserverUtils.asRepartitionContext(cz.o2.proxima.direct.commitlog.ObserverUtils.asRepartitionContext) OnNextContext(cz.o2.proxima.direct.commitlog.CommitLogObserver.OnNextContext) OffsetCommitter(cz.o2.proxima.direct.commitlog.CommitLogObserver.OffsetCommitter)

Example 30 with ObserveHandle

use of cz.o2.proxima.direct.commitlog.ObserveHandle in project proxima-platform by O2-Czech-Republic.

the class ListCommitLogTest method testObserveWithCustomWatemarkEstimator.

@Test(timeout = 1000)
public void testObserveWithCustomWatemarkEstimator() throws InterruptedException {
    long now = System.currentTimeMillis() - 1000;
    int numElements = 10;
    CommitLogReader reader = ListCommitLog.of(data(numElements), new TestWatermarkEstimator(now), direct.getContext());
    CountDownLatch latch = new CountDownLatch(1);
    List<Long> watermarks = new ArrayList<>();
    ObserveHandle handle = reader.observe(null, new CommitLogObserver() {

        @Override
        public boolean onError(Throwable error) {
            throw new RuntimeException(error);
        }

        @Override
        public boolean onNext(StreamElement ingest, OnNextContext context) {
            context.confirm();
            watermarks.add(context.getWatermark());
            return true;
        }

        @Override
        public void onCompleted() {
            latch.countDown();
        }
    });
    latch.await();
    assertEquals(numElements, watermarks.size());
    List<Long> expected = IntStream.range(0, numElements).mapToObj(i -> now + i).collect(Collectors.toList());
    assertEquals(expected, watermarks);
}
Also used : IntStream(java.util.stream.IntStream) EntityDescriptor(cz.o2.proxima.repository.EntityDescriptor) HashMap(java.util.HashMap) Function(java.util.function.Function) LogObserverUtils.toList(cz.o2.proxima.direct.commitlog.LogObserverUtils.toList) ArrayList(java.util.ArrayList) StreamElement(cz.o2.proxima.storage.StreamElement) WatermarkEstimator(cz.o2.proxima.time.WatermarkEstimator) ConfigFactory(com.typesafe.config.ConfigFactory) SerializationException(cz.o2.proxima.scheme.SerializationException) TypeReference(com.fasterxml.jackson.core.type.TypeReference) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) ExecutorService(java.util.concurrent.ExecutorService) ListObserveHandle(cz.o2.proxima.direct.storage.ListCommitLog.ListObserveHandle) Repository(cz.o2.proxima.repository.Repository) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AttributeDescriptor(cz.o2.proxima.repository.AttributeDescriptor) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Test(org.junit.Test) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Offset(cz.o2.proxima.direct.commitlog.Offset) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) DirectDataOperator(cz.o2.proxima.direct.core.DirectDataOperator) Assert(org.junit.Assert) Collections(java.util.Collections) ListObserveHandle(cz.o2.proxima.direct.storage.ListCommitLog.ListObserveHandle) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) ArrayList(java.util.ArrayList) StreamElement(cz.o2.proxima.storage.StreamElement) CountDownLatch(java.util.concurrent.CountDownLatch) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) Test(org.junit.Test)

Aggregations

StreamElement (cz.o2.proxima.storage.StreamElement)58 ObserveHandle (cz.o2.proxima.direct.commitlog.ObserveHandle)56 Test (org.junit.Test)52 CommitLogObserver (cz.o2.proxima.direct.commitlog.CommitLogObserver)47 CommitLogReader (cz.o2.proxima.direct.commitlog.CommitLogReader)45 CountDownLatch (java.util.concurrent.CountDownLatch)43 ArrayList (java.util.ArrayList)38 Offset (cz.o2.proxima.direct.commitlog.Offset)32 AtomicReference (java.util.concurrent.atomic.AtomicReference)30 List (java.util.List)29 Partition (cz.o2.proxima.storage.Partition)26 HashMap (java.util.HashMap)26 DirectDataOperator (cz.o2.proxima.direct.core.DirectDataOperator)25 AttributeDescriptor (cz.o2.proxima.repository.AttributeDescriptor)24 UUID (java.util.UUID)24 WatermarkEstimator (cz.o2.proxima.time.WatermarkEstimator)23 Collections (java.util.Collections)23 Collectors (java.util.stream.Collectors)23 Repository (cz.o2.proxima.repository.Repository)22 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)22