Search in sources :

Example 36 with ObserveHandle

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

the class CassandraDBAccessorTest method testBatchReaderCancelled.

@Test(timeout = 10000)
public void testBatchReaderCancelled() throws InterruptedException {
    TestDBAccessor accessor = new TestDBAccessor(entity, URI.create("cassandra://host:9042/table/?primary=data"), getCfg(TestCqlFactory.class, 2));
    CassandraLogReader reader = accessor.newBatchReader(direct.getContext());
    int numElements = 2;
    ResultSet result = mockResultSet(numElements);
    accessor.setRes(result);
    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<ObserveHandle> handle = new AtomicReference<>();
    handle.set(reader.observe(reader.getPartitions(), Collections.singletonList(attr), new BatchLogObserver() {

        @Override
        public boolean onNext(StreamElement element) {
            handle.get().close();
            return true;
        }

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

        @Override
        public void onCancelled() {
            latch.countDown();
        }

        @Override
        public void onCompleted() {
            fail("onCompleted should have not been called");
        }
    }));
    latch.await();
}
Also used : ObserveHandle(cz.o2.proxima.direct.batch.ObserveHandle) StreamElement(cz.o2.proxima.storage.StreamElement) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ResultSet(com.datastax.driver.core.ResultSet) BatchLogObserver(cz.o2.proxima.direct.batch.BatchLogObserver) Test(org.junit.Test)

Example 37 with ObserveHandle

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

the class CassandraLogReader method observe.

@Override
public ObserveHandle observe(List<Partition> partitions, List<AttributeDescriptor<?>> attributes, BatchLogObserver observer) {
    TerminationContext terminationContext = new TerminationContext(observer);
    observeInternal(partitions, attributes, observer, terminationContext);
    return terminationContext.asObserveHandle();
}
Also used : TerminationContext(cz.o2.proxima.direct.batch.TerminationContext)

Example 38 with ObserveHandle

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

the class LocalKafkaCommitLogDescriptorTest method testBulkObserveWithException.

@Test(timeout = 10000)
public void testBulkObserveWithException() throws InterruptedException {
    Accessor accessor = kafka.createAccessor(direct, createTestFamily(entity, storageUri, partitionsCfg(3)));
    LocalKafkaWriter writer = accessor.newWriter();
    CommitLogReader reader = Optionals.get(accessor.getCommitLogReader(context()));
    final AtomicInteger restarts = new AtomicInteger();
    final AtomicReference<Throwable> exc = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(2);
    final StreamElement update = StreamElement.upsert(entity, attr, UUID.randomUUID().toString(), "key", attr.getName(), System.currentTimeMillis(), new byte[] { 1, 2 });
    final ObserveHandle handle = reader.observeBulk("test", Position.NEWEST, new CommitLogObserver() {

        @Override
        public boolean onNext(StreamElement ingest, OnNextContext context) {
            restarts.incrementAndGet();
            throw new RuntimeException("FAIL!");
        }

        @Override
        public void onCompleted() {
            fail("This should not be called");
        }

        @Override
        public boolean onError(Throwable error) {
            exc.set(error);
            latch.countDown();
            throw new RuntimeException(error);
        }
    });
    writer.write(update, (succ, e) -> {
        assertTrue(succ);
        latch.countDown();
    });
    latch.await();
    assertEquals("FAIL!", exc.get().getMessage());
    assertEquals(1, restarts.get());
    assertEquals(3, handle.getCommittedOffsets().size());
    List<Long> startedOffsets = handle.getCurrentOffsets().stream().map(o -> ((TopicOffset) o).getOffset()).filter(o -> o >= 0).collect(Collectors.toList());
    assertEquals(Collections.singletonList(0L), startedOffsets);
}
Also used : Arrays(java.util.Arrays) LocalKafkaLogReader(cz.o2.proxima.direct.kafka.LocalKafkaCommitLogDescriptor.LocalKafkaLogReader) LocalKafkaWriter(cz.o2.proxima.direct.kafka.LocalKafkaCommitLogDescriptor.LocalKafkaWriter) Partition(cz.o2.proxima.storage.Partition) EntityDescriptor(cz.o2.proxima.repository.EntityDescriptor) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) CachedView(cz.o2.proxima.direct.view.CachedView) StreamElement(cz.o2.proxima.storage.StreamElement) WatermarkEstimator(cz.o2.proxima.time.WatermarkEstimator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Pair(cz.o2.proxima.util.Pair) Serde(org.apache.kafka.common.serialization.Serde) UnaryFunction(cz.o2.proxima.functional.UnaryFunction) Duration(java.time.Duration) Map(java.util.Map) Serdes(org.apache.kafka.common.serialization.Serdes) URI(java.net.URI) WatermarkEstimatorFactory(cz.o2.proxima.time.WatermarkEstimatorFactory) Optionals(cz.o2.proxima.util.Optionals) WatermarkIdlePolicyFactory(cz.o2.proxima.time.WatermarkIdlePolicyFactory) TopicPartition(org.apache.kafka.common.TopicPartition) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) UUID(java.util.UUID) Accessor(cz.o2.proxima.direct.kafka.LocalKafkaCommitLogDescriptor.Accessor) Collectors(java.util.stream.Collectors) RebalanceInProgressException(org.apache.kafka.common.errors.RebalanceInProgressException) Executors(java.util.concurrent.Executors) Serializable(java.io.Serializable) CommitLogObservers(cz.o2.proxima.direct.commitlog.CommitLogObservers) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) ConsumerRebalanceListener(org.apache.kafka.clients.consumer.ConsumerRebalanceListener) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ConfigRepository(cz.o2.proxima.repository.ConfigRepository) Stream(java.util.stream.Stream) KeyValue(cz.o2.proxima.direct.randomaccess.KeyValue) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) OnNextContext(cz.o2.proxima.direct.commitlog.CommitLogObserver.OnNextContext) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) DirectDataOperator(cz.o2.proxima.direct.core.DirectDataOperator) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Context(cz.o2.proxima.direct.core.Context) IntStream(java.util.stream.IntStream) TestUtils.createTestFamily(cz.o2.proxima.util.TestUtils.createTestFamily) KeyPartitioner(cz.o2.proxima.storage.commitlog.KeyPartitioner) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) HashMap(java.util.HashMap) OnlineAttributeWriter(cz.o2.proxima.direct.core.OnlineAttributeWriter) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) ConfigFactory(com.typesafe.config.ConfigFactory) Watermarks(cz.o2.proxima.time.Watermarks) Factory(cz.o2.proxima.functional.Factory) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) WatermarkIdlePolicy(cz.o2.proxima.time.WatermarkIdlePolicy) Before(org.junit.Before) Properties(java.util.Properties) Repository(cz.o2.proxima.repository.Repository) Iterator(java.util.Iterator) AttributeDescriptor(cz.o2.proxima.repository.AttributeDescriptor) MoreObjects(com.google.common.base.MoreObjects) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) Test(org.junit.Test) AttributeFamilyDescriptor(cz.o2.proxima.repository.AttributeFamilyDescriptor) Offset(cz.o2.proxima.direct.commitlog.Offset) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) AtomicLong(java.util.concurrent.atomic.AtomicLong) AttributeDescriptorBase(cz.o2.proxima.repository.AttributeDescriptorBase) Partitioner(cz.o2.proxima.storage.commitlog.Partitioner) Assert(org.junit.Assert) Comparator(java.util.Comparator) Collections(java.util.Collections) Position(cz.o2.proxima.storage.commitlog.Position) LocalKafkaWriter(cz.o2.proxima.direct.kafka.LocalKafkaCommitLogDescriptor.LocalKafkaWriter) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) OnNextContext(cz.o2.proxima.direct.commitlog.CommitLogObserver.OnNextContext) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) StreamElement(cz.o2.proxima.storage.StreamElement) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Accessor(cz.o2.proxima.direct.kafka.LocalKafkaCommitLogDescriptor.Accessor) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 39 with ObserveHandle

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

the class PubSubReader method observe.

private ObserveHandle observe(@Nullable String name, Position position, long minWatermark, CommitLogObserver observer) {
    validatePosition(position);
    String consumerName = asConsumerName(name);
    AtomicLong committedWatermark = new AtomicLong(minWatermark);
    return consume(consumerName, (e, w, c) -> {
        OffsetCommitter committer = (succ, exc) -> {
            if (succ) {
                log.debug("Confirming message {} to PubSub", e);
                committedWatermark.set(w.getWatermark());
                c.ack();
            } else {
                if (exc != null) {
                    log.warn("Error during processing of {}", e, exc);
                } else {
                    log.info("Nacking message {} by request", e);
                }
                c.nack();
            }
        };
        try {
            long watermark = w.getWatermark();
            Offset offset = new PubSubOffset(consumerName, watermark);
            boolean ret = observer.onNext(e, asOnNextContext(committer, offset));
            if (!ret) {
                observer.onCompleted();
            }
            return ret;
        } catch (Exception ex) {
            log.error("Error calling onNext", ex);
            committer.fail(ex);
            throw new RuntimeException(ex);
        }
    }, observer::onError, null, () -> {
    }, observer::onCancelled, committedWatermark);
}
Also used : ObserverUtils.asOnNextContext(cz.o2.proxima.direct.commitlog.ObserverUtils.asOnNextContext) Arrays(java.util.Arrays) Partition(cz.o2.proxima.storage.Partition) Subscriber(com.google.cloud.pubsub.v1.Subscriber) StreamElement(cz.o2.proxima.storage.StreamElement) WatermarkEstimator(cz.o2.proxima.time.WatermarkEstimator) UnaryFunction(cz.o2.proxima.functional.UnaryFunction) Map(java.util.Map) SubscriptionAdminClient(com.google.cloud.pubsub.v1.SubscriptionAdminClient) WatermarkEstimatorFactory(cz.o2.proxima.time.WatermarkEstimatorFactory) WatermarkIdlePolicyFactory(cz.o2.proxima.time.WatermarkIdlePolicyFactory) Collection(java.util.Collection) Set(java.util.Set) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) AlreadyExistsException(com.google.api.gax.rpc.AlreadyExistsException) Serializable(java.io.Serializable) Objects(java.util.Objects) Duration(org.threeten.bp.Duration) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) LimitExceededBehavior(com.google.api.gax.batching.FlowController.LimitExceededBehavior) FieldMask(com.google.protobuf.FieldMask) ProjectSubscriptionName(com.google.pubsub.v1.ProjectSubscriptionName) Optional(java.util.Optional) ObserverUtils.asRepartitionContext(cz.o2.proxima.direct.commitlog.ObserverUtils.asRepartitionContext) Context(cz.o2.proxima.direct.core.Context) IntStream(java.util.stream.IntStream) Iterables(com.google.common.collect.Iterables) Getter(lombok.Getter) UpdateSubscriptionRequest(com.google.pubsub.v1.UpdateSubscriptionRequest) OffsetCommitter(cz.o2.proxima.direct.commitlog.CommitLogObserver.OffsetCommitter) Stable(cz.o2.proxima.annotations.Stable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FlowControlSettings(com.google.api.gax.batching.FlowControlSettings) WatermarkSupplier(cz.o2.proxima.time.WatermarkSupplier) AtomicReference(java.util.concurrent.atomic.AtomicReference) AckReplyConsumer(com.google.cloud.pubsub.v1.AckReplyConsumer) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ProjectTopicName(com.google.pubsub.v1.ProjectTopicName) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) MessageReceiver(com.google.cloud.pubsub.v1.MessageReceiver) AbstractStorage(cz.o2.proxima.storage.AbstractStorage) PubSubUtils(cz.o2.proxima.io.pubsub.util.PubSubUtils) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) IOException(java.io.IOException) Offset(cz.o2.proxima.direct.commitlog.Offset) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Preconditions(com.google.common.base.Preconditions) Subscription(com.google.pubsub.v1.Subscription) VisibleForTesting(com.google.common.annotations.VisibleForTesting) PushConfig(com.google.pubsub.v1.PushConfig) Collections(java.util.Collections) Position(cz.o2.proxima.storage.commitlog.Position) AtomicLong(java.util.concurrent.atomic.AtomicLong) AlreadyExistsException(com.google.api.gax.rpc.AlreadyExistsException) IOException(java.io.IOException) OffsetCommitter(cz.o2.proxima.direct.commitlog.CommitLogObserver.OffsetCommitter) Offset(cz.o2.proxima.direct.commitlog.Offset)

Example 40 with ObserveHandle

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

the class PubSubReader method consume.

private ObserveHandle consume(String consumerName, PubSubConsumer consumer, UnaryFunction<Throwable, Boolean> errorHandler, @Nullable Runnable onInit, Runnable onRestart, Runnable onCancel, AtomicLong committedWatermark) {
    ProjectSubscriptionName subscription = ProjectSubscriptionName.of(project, consumerName);
    AtomicReference<Subscriber> subscriber = new AtomicReference<>();
    AtomicBoolean stopProcessing = new AtomicBoolean();
    AtomicReference<MessageReceiver> receiver = new AtomicReference<>();
    WatermarkEstimator watermarkEstimator = createWatermarkEstimator(committedWatermark.get());
    receiver.set(createMessageReceiver(subscription, subscriber, stopProcessing, consumer, watermarkEstimator, errorHandler, onRestart, receiver));
    subscriber.set(newSubscriber(subscription, receiver.get()));
    subscriber.get().startAsync();
    if (onInit != null) {
        executor().submit(() -> {
            subscriber.get().awaitRunning();
            if (onInit != null) {
                onInit.run();
            }
        });
    }
    return new ObserveHandle() {

        @Override
        public void close() {
            log.debug("Cancelling observer {}", consumerName);
            stopProcessing.set(true);
            Subscriber sub = stopAsync(subscriber);
            if (sub != null) {
                sub.awaitTerminated();
            }
            onCancel.run();
        }

        @Override
        public List<Offset> getCommittedOffsets() {
            return Collections.singletonList(new PubSubOffset(consumerName, committedWatermark.get()));
        }

        @Override
        public void resetOffsets(List<Offset> offsets) {
        // nop
        }

        @Override
        public List<Offset> getCurrentOffsets() {
            return getCommittedOffsets();
        }

        @Override
        public void waitUntilReady() {
            subscriber.get().awaitRunning();
        }
    };
}
Also used : ProjectSubscriptionName(com.google.pubsub.v1.ProjectSubscriptionName) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) WatermarkEstimator(cz.o2.proxima.time.WatermarkEstimator) Subscriber(com.google.cloud.pubsub.v1.Subscriber) MessageReceiver(com.google.cloud.pubsub.v1.MessageReceiver) AtomicReference(java.util.concurrent.atomic.AtomicReference) List(java.util.List) ArrayList(java.util.ArrayList) Offset(cz.o2.proxima.direct.commitlog.Offset)

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