Search in sources :

Example 1 with ProcessingGuarantee

use of com.hazelcast.jet.config.ProcessingGuarantee in project hazelcast by hazelcast.

the class JmsSourceBuilder method build.

/**
 * Creates and returns the JMS {@link StreamSource} with the supplied
 * components and the projection function {@code projectionFn}.
 * <p>
 * The given function must be stateless.
 *
 * @param projectionFn the function which creates output object from each
 *                    message
 * @param <T> the type of the items the source emits
 */
@Nonnull
public <T> StreamSource<T> build(@Nonnull FunctionEx<? super Message, ? extends T> projectionFn) {
    String usernameLocal = username;
    String passwordLocal = password;
    String destinationLocal = destinationName;
    ProcessingGuarantee maxGuaranteeLocal = maxGuarantee;
    @SuppressWarnings("UnnecessaryLocalVariable") boolean isTopicLocal = isTopic;
    if (connectionFn == null) {
        connectionFn = factory -> requireNonNull(usernameLocal != null || passwordLocal != null ? factory.createConnection(usernameLocal, passwordLocal) : factory.createConnection());
    }
    if (consumerFn == null) {
        checkNotNull(destinationLocal, "neither consumerFn nor destinationName set");
        consumerFn = session -> session.createConsumer(isTopicLocal ? session.createTopic(destinationLocal) : session.createQueue(destinationLocal));
        if (isTopic) {
            // the user didn't specify a custom consumerFn and we know we're using a non-durable consumer
            // for a topic - there's no point in using any guarantee, see `maxGuarantee`
            maxGuaranteeLocal = ProcessingGuarantee.NONE;
        }
    }
    ProcessingGuarantee maxGuaranteeFinal = maxGuaranteeLocal;
    FunctionEx<? super ConnectionFactory, ? extends Connection> connectionFnLocal = connectionFn;
    @SuppressWarnings("UnnecessaryLocalVariable") SupplierEx<? extends ConnectionFactory> factorySupplierLocal = factorySupplier;
    SupplierEx<? extends Connection> newConnectionFn = () -> connectionFnLocal.apply(factorySupplierLocal.get());
    FunctionEx<? super Session, ? extends MessageConsumer> consumerFnLocal = consumerFn;
    boolean isSharedConsumerLocal = isSharedConsumer;
    FunctionEx<? super Message, ?> messageIdFnLocal = messageIdFn;
    FunctionEx<EventTimePolicy<? super T>, ProcessorMetaSupplier> metaSupplierFactory = policy -> isTopicLocal ? streamJmsTopicP(destinationLocal, isSharedConsumerLocal, maxGuaranteeFinal, policy, newConnectionFn, consumerFnLocal, messageIdFnLocal, projectionFn) : streamJmsQueueP(destinationLocal, maxGuaranteeFinal, policy, newConnectionFn, consumerFnLocal, messageIdFnLocal, projectionFn);
    return Sources.streamFromProcessorWithWatermarks(sourceName(), true, metaSupplierFactory);
}
Also used : ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) FunctionEx(com.hazelcast.function.FunctionEx) Connection(javax.jms.Connection) Util.checkSerializable(com.hazelcast.jet.impl.util.Util.checkSerializable) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) EventTimePolicy(com.hazelcast.jet.core.EventTimePolicy) Preconditions.checkNotNull(com.hazelcast.internal.util.Preconditions.checkNotNull) SupplierEx(com.hazelcast.function.SupplierEx) Session(javax.jms.Session) MessageConsumer(javax.jms.MessageConsumer) SourceProcessors.streamJmsTopicP(com.hazelcast.jet.core.processor.SourceProcessors.streamJmsTopicP) Objects.requireNonNull(java.util.Objects.requireNonNull) SourceProcessors.streamJmsQueueP(com.hazelcast.jet.core.processor.SourceProcessors.streamJmsQueueP) ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) Nonnull(javax.annotation.Nonnull) Message(javax.jms.Message) Nullable(javax.annotation.Nullable) ConnectionFactory(javax.jms.ConnectionFactory) EventTimePolicy(com.hazelcast.jet.core.EventTimePolicy) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) Nonnull(javax.annotation.Nonnull)

Example 2 with ProcessingGuarantee

use of com.hazelcast.jet.config.ProcessingGuarantee in project hazelcast by hazelcast.

the class JmsSourceIntegrationTestBase method stressTest.

private void stressTest(boolean graceful, ProcessingGuarantee maxGuarantee, boolean useTopic) throws Exception {
    lastListInStressTest = null;
    final int MESSAGE_COUNT = 4_000;
    Pipeline p = Pipeline.create();
    String destName = "queue-" + counter++;
    JmsSourceBuilder sourceBuilder;
    if (useTopic) {
        sourceBuilder = Sources.jmsTopicBuilder(getConnectionFactory()).sharedConsumer(true).consumerFn(s -> s.createSharedDurableConsumer(s.createTopic(destName), "foo-consumer"));
        // create the durable subscriber now so that it doesn't lose the initial messages
        try (Connection conn = getConnectionFactory().get().createConnection()) {
            conn.setClientID("foo-client-id");
            try (Session sess = conn.createSession(false, DUPS_OK_ACKNOWLEDGE)) {
                sess.createDurableSubscriber(sess.createTopic(destName), "foo-consumer");
            }
        }
    } else {
        sourceBuilder = Sources.jmsQueueBuilder(getConnectionFactory()).destinationName(destName);
    }
    p.readFrom(sourceBuilder.maxGuarantee(maxGuarantee).build(msg -> Long.parseLong(((TextMessage) msg).getText()))).withoutTimestamps().peek().mapStateful(CopyOnWriteArrayList<Long>::new, (list, item) -> {
        lastListInStressTest = list;
        list.add(item);
        return null;
    }).writeTo(Sinks.logger());
    Job job = instance().getJet().newJob(p, new JobConfig().setProcessingGuarantee(ProcessingGuarantee.EXACTLY_ONCE).setSnapshotIntervalMillis(50));
    assertJobStatusEventually(job, RUNNING);
    // start a producer that will produce MESSAGE_COUNT messages on the background to the queue, 1000 msgs/s
    @SuppressWarnings("rawtypes") Future producerFuture = spawn(() -> {
        try (Connection connection = getConnectionFactory().get().createConnection();
            Session session = connection.createSession(false, AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(useTopic ? session.createTopic(destName) : session.createQueue(destName))) {
            long startTime = System.nanoTime();
            for (int i = 0; i < MESSAGE_COUNT; i++) {
                producer.send(session.createTextMessage(String.valueOf(i)));
                Thread.sleep(Math.max(0, i - NANOSECONDS.toMillis(System.nanoTime() - startTime)));
            }
        } catch (Exception e) {
            throw sneakyThrow(e);
        }
    });
    int iteration = 0;
    JobRepository jr = new JobRepository(instance());
    waitForFirstSnapshot(jr, job.getId(), 20, true);
    while (!producerFuture.isDone()) {
        Thread.sleep(ThreadLocalRandom.current().nextInt(200));
        // We also do it before the first restart to workaround https://issues.apache.org/jira/browse/ARTEMIS-2546
        if (iteration++ % 3 == 0) {
            waitForNextSnapshot(jr, job.getId(), 20, true);
        }
        ((JobProxy) job).restart(graceful);
        assertJobStatusEventually(job, RUNNING);
    }
    // call for the side-effect of throwing if the producer failed
    producerFuture.get();
    assertTrueEventually(() -> {
        Map<Long, Long> counts = lastListInStressTest.stream().collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));
        for (long i = 0; i < MESSAGE_COUNT; i++) {
            counts.putIfAbsent(i, 0L);
        }
        String countsStr = "counts: " + counts;
        if (maxGuarantee == NONE) {
            // we don't assert anything and only wait little more and check that the job didn't fail
            sleepSeconds(1);
        } else {
            // in EXACTLY_ONCE the list must have each item exactly once
            // in AT_LEAST_ONCE the list must have each item at least once
            assertTrue(countsStr, counts.values().stream().allMatch(cnt -> maxGuarantee == EXACTLY_ONCE ? cnt == 1 : cnt > 0));
        }
        logger.info(countsStr);
    }, 30);
    assertEquals(job.getStatus(), RUNNING);
}
Also used : AggregateOperations.counting(com.hazelcast.jet.aggregate.AggregateOperations.counting) Mockito.doThrow(org.mockito.Mockito.doThrow) Session(javax.jms.Session) Future(java.util.concurrent.Future) WindowDefinition.tumbling(com.hazelcast.jet.pipeline.WindowDefinition.tumbling) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) MessageProducer(javax.jms.MessageProducer) JobStatus(com.hazelcast.jet.core.JobStatus) SimpleTestInClusterSupport(com.hazelcast.jet.SimpleTestInClusterSupport) FunctionEx(com.hazelcast.function.FunctionEx) Pipeline(com.hazelcast.jet.pipeline.Pipeline) JobConfig(com.hazelcast.jet.config.JobConfig) PredicateEx.alwaysFalse(com.hazelcast.function.PredicateEx.alwaysFalse) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Instant(java.time.Instant) DUPS_OK_ACKNOWLEDGE(javax.jms.Session.DUPS_OK_ACKNOWLEDGE) JMSException(javax.jms.JMSException) Collectors(java.util.stream.Collectors) SupplierEx(com.hazelcast.function.SupplierEx) ZoneId(java.time.ZoneId) Sources(com.hazelcast.jet.pipeline.Sources) List(java.util.List) MessageConsumer(javax.jms.MessageConsumer) Assert.assertFalse(org.junit.Assert.assertFalse) WindowResult(com.hazelcast.jet.datamodel.WindowResult) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeClass(org.junit.BeforeClass) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) AUTO_ACKNOWLEDGE(javax.jms.Session.AUTO_ACKNOWLEDGE) MINUTES(java.util.concurrent.TimeUnit.MINUTES) JobProxy(com.hazelcast.jet.impl.JobProxy) StreamSource(com.hazelcast.jet.pipeline.StreamSource) ExceptionUtil.sneakyThrow(com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) MapWatermarksToString.mapWatermarksToString(com.hazelcast.jet.core.TestProcessors.MapWatermarksToString.mapWatermarksToString) JmsSourceBuilder(com.hazelcast.jet.pipeline.JmsSourceBuilder) Message(javax.jms.Message) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Job(com.hazelcast.jet.Job) Before(org.junit.Before) IList(com.hazelcast.collection.IList) JobRepository(com.hazelcast.jet.impl.JobRepository) Connection(javax.jms.Connection) TextMessage(javax.jms.TextMessage) EXACTLY_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE) Sinks(com.hazelcast.jet.pipeline.Sinks) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) NONE(com.hazelcast.jet.config.ProcessingGuarantee.NONE) TreeMap(java.util.TreeMap) JmsTestUtil.consumeMessages(com.hazelcast.jet.impl.connector.JmsTestUtil.consumeMessages) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) AT_LEAST_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.AT_LEAST_ONCE) ConnectionFactory(javax.jms.ConnectionFactory) Assert.assertEquals(org.junit.Assert.assertEquals) Connection(javax.jms.Connection) MapWatermarksToString.mapWatermarksToString(com.hazelcast.jet.core.TestProcessors.MapWatermarksToString.mapWatermarksToString) JobRepository(com.hazelcast.jet.impl.JobRepository) JmsSourceBuilder(com.hazelcast.jet.pipeline.JmsSourceBuilder) JobConfig(com.hazelcast.jet.config.JobConfig) JMSException(javax.jms.JMSException) Pipeline(com.hazelcast.jet.pipeline.Pipeline) JobProxy(com.hazelcast.jet.impl.JobProxy) Future(java.util.concurrent.Future) MessageProducer(javax.jms.MessageProducer) Job(com.hazelcast.jet.Job) Session(javax.jms.Session)

Example 3 with ProcessingGuarantee

use of com.hazelcast.jet.config.ProcessingGuarantee in project hazelcast by hazelcast.

the class WriteFileP method init.

@Override
public void init(@Nonnull Outbox outbox, @Nonnull Context context) throws IOException {
    this.context = context;
    Files.createDirectories(directory);
    ProcessingGuarantee guarantee = context.processingGuarantee() == EXACTLY_ONCE && !exactlyOnce ? AT_LEAST_ONCE : context.processingGuarantee();
    utility = new UnboundedTransactionsProcessorUtility<>(outbox, context, guarantee, this::newFileName, this::newFileResource, this::recoverAndCommit, this::abortUnfinishedTransactions);
}
Also used : ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee)

Example 4 with ProcessingGuarantee

use of com.hazelcast.jet.config.ProcessingGuarantee in project hazelcast by hazelcast.

the class WriteKafkaP method init.

@Override
public void init(@Nonnull Outbox outbox, @Nonnull Context context) {
    this.context = context;
    ProcessingGuarantee guarantee = context.processingGuarantee() == EXACTLY_ONCE && !exactlyOnce ? AT_LEAST_ONCE : context.processingGuarantee();
    snapshotUtility = new TransactionPoolSnapshotUtility<>(outbox, context, false, guarantee, TXN_POOL_SIZE, (processorIndex, txnIndex) -> new KafkaTransactionId(context.jobId(), context.jobConfig().getName(), context.vertexName(), processorIndex, txnIndex), txnId -> {
        if (txnId != null) {
            properties.put("transactional.id", txnId.getKafkaId());
        }
        return new KafkaTransaction<>(txnId, properties, context.logger());
    }, txnId -> {
        try {
            recoverTransaction(txnId, true);
        } catch (ProducerFencedException e) {
            context.logger().warning("Failed to finish the commit of a transaction ID saved in the " + "snapshot, data loss can occur. Transaction id: " + txnId.getKafkaId(), e);
        }
    }, txnId -> recoverTransaction(txnId, false));
}
Also used : ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) LoggingUtil(com.hazelcast.jet.impl.util.LoggingUtil) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) Outbox(com.hazelcast.jet.core.Outbox) Processor(com.hazelcast.jet.core.Processor) HashMap(java.util.HashMap) KafkaProcessors(com.hazelcast.jet.kafka.KafkaProcessors) ExceptionUtil.sneakyThrow(com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Watermark(com.hazelcast.jet.core.Watermark) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) ILogger(com.hazelcast.logging.ILogger) Map(java.util.Map) Inbox(com.hazelcast.jet.core.Inbox) Nonnull(javax.annotation.Nonnull) FunctionEx(com.hazelcast.function.FunctionEx) TransactionalResource(com.hazelcast.jet.impl.processor.TwoPhaseSnapshotCommitUtility.TransactionalResource) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Properties(java.util.Properties) TransactionPoolSnapshotUtility(com.hazelcast.jet.impl.processor.TransactionPoolSnapshotUtility) EXACTLY_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE) SupplierEx(com.hazelcast.function.SupplierEx) Serializable(java.io.Serializable) Objects(java.util.Objects) Util.idToString(com.hazelcast.jet.Util.idToString) InvalidTxnStateException(org.apache.kafka.common.errors.InvalidTxnStateException) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException) ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) Callback(org.apache.kafka.clients.producer.Callback) AT_LEAST_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.AT_LEAST_ONCE) TwoPhaseSnapshotCommitUtility(com.hazelcast.jet.impl.processor.TwoPhaseSnapshotCommitUtility) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException)

Aggregations

ProcessingGuarantee (com.hazelcast.jet.config.ProcessingGuarantee)4 FunctionEx (com.hazelcast.function.FunctionEx)3 SupplierEx (com.hazelcast.function.SupplierEx)3 AT_LEAST_ONCE (com.hazelcast.jet.config.ProcessingGuarantee.AT_LEAST_ONCE)2 EXACTLY_ONCE (com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE)2 ExceptionUtil.sneakyThrow (com.hazelcast.jet.impl.util.ExceptionUtil.sneakyThrow)2 Connection (javax.jms.Connection)2 ConnectionFactory (javax.jms.ConnectionFactory)2 Message (javax.jms.Message)2 MessageConsumer (javax.jms.MessageConsumer)2 Session (javax.jms.Session)2 IList (com.hazelcast.collection.IList)1 PredicateEx.alwaysFalse (com.hazelcast.function.PredicateEx.alwaysFalse)1 Preconditions.checkNotNull (com.hazelcast.internal.util.Preconditions.checkNotNull)1 Job (com.hazelcast.jet.Job)1 SimpleTestInClusterSupport (com.hazelcast.jet.SimpleTestInClusterSupport)1 Util.idToString (com.hazelcast.jet.Util.idToString)1 AggregateOperations.counting (com.hazelcast.jet.aggregate.AggregateOperations.counting)1 JobConfig (com.hazelcast.jet.config.JobConfig)1 NONE (com.hazelcast.jet.config.ProcessingGuarantee.NONE)1