Search in sources :

Example 1 with NONE

use of com.hazelcast.jet.config.ProcessingGuarantee.NONE 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 2 with NONE

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

the class GracefulShutdownTest method when_shutDown.

private void when_shutDown(boolean shutdownCoordinator, boolean snapshotted) {
    DAG dag = new DAG();
    final int numItems = 50_000;
    Vertex source = dag.newVertex("source", throttle(() -> new EmitIntegersP(numItems), 10_000)).localParallelism(1);
    Vertex sink = dag.newVertex("sink", SinkProcessors.writeListP("sink"));
    dag.edge(between(source, sink));
    Job job = client.getJet().newJob(dag, new JobConfig().setProcessingGuarantee(snapshotted ? EXACTLY_ONCE : NONE).setSnapshotIntervalMillis(HOURS.toMillis(1)));
    assertJobStatusEventually(job, JobStatus.RUNNING);
    logger.info("sleeping 1 sec");
    sleepSeconds(1);
    int shutDownInstance = shutdownCoordinator ? 0 : 1;
    int liveInstance = shutdownCoordinator ? 1 : 0;
    // When
    logger.info("Shutting down instance...");
    instances[shutDownInstance].shutdown();
    logger.info("Joining job...");
    job.join();
    logger.info("Joined");
    // Then
    // If the shutdown was graceful, output items must not be duplicated
    Map<Integer, Integer> expected;
    Map<Integer, Integer> actual = new ArrayList<>(instances[liveInstance].<Integer>getList("sink")).stream().collect(Collectors.toMap(Function.identity(), item -> 1, Integer::sum));
    if (snapshotted) {
        logger.info("savedCounters=" + EmitIntegersP.savedCounters);
        assertEquals(EmitIntegersP.savedCounters.toString(), 2, EmitIntegersP.savedCounters.size());
        int minCounter = EmitIntegersP.savedCounters.values().stream().mapToInt(Integer::intValue).min().getAsInt();
        expected = IntStream.range(0, numItems).boxed().collect(Collectors.toMap(Function.identity(), item -> item < minCounter ? 2 : 1));
        assertEquals(expected, actual);
    } else {
        // Items 0, 1, ... up to the point when the member was shut down should be 3 times
        // in the output: twice from before shutdown and one from after it, because it will start
        // from the beginning when the job is not snapshotted.
        assertEquals(3, actual.get(0).intValue());
        assertEquals(3, actual.get(1).intValue());
        assertEquals(1, actual.get(numItems - 1).intValue());
    }
}
Also used : IntStream(java.util.stream.IntStream) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) RunWith(org.junit.runner.RunWith) Function(java.util.function.Function) HazelcastSerialClassRunner(com.hazelcast.test.HazelcastSerialClassRunner) MapStore(com.hazelcast.map.MapStore) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) MapConfig(com.hazelcast.config.MapConfig) Future(java.util.concurrent.Future) TestUtil.throttle(com.hazelcast.jet.core.TestUtil.throttle) Map(java.util.Map) Nonnull(javax.annotation.Nonnull) Job(com.hazelcast.jet.Job) Before(org.junit.Before) JobRepository(com.hazelcast.jet.impl.JobRepository) Config(com.hazelcast.config.Config) HazelcastInstance(com.hazelcast.core.HazelcastInstance) Collection(java.util.Collection) EXACTLY_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE) JobConfig(com.hazelcast.jet.config.JobConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) SlowTest(com.hazelcast.test.annotation.SlowTest) Category(org.junit.experimental.categories.Category) Collectors(java.util.stream.Collectors) SupplierEx(com.hazelcast.function.SupplierEx) NoOutputSourceP(com.hazelcast.jet.core.TestProcessors.NoOutputSourceP) NONE(com.hazelcast.jet.config.ProcessingGuarantee.NONE) DynamicConfigurationAwareConfig(com.hazelcast.internal.dynamicconfig.DynamicConfigurationAwareConfig) BroadcastKey.broadcastKey(com.hazelcast.jet.core.BroadcastKey.broadcastKey) SinkProcessors(com.hazelcast.jet.core.processor.SinkProcessors) HOURS(java.util.concurrent.TimeUnit.HOURS) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) Assert.assertEquals(org.junit.Assert.assertEquals) JetServiceBackend(com.hazelcast.jet.impl.JetServiceBackend) Edge.between(com.hazelcast.jet.core.Edge.between) ArrayList(java.util.ArrayList) Job(com.hazelcast.jet.Job) JobConfig(com.hazelcast.jet.config.JobConfig)

Example 3 with NONE

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

the class StreamJmsPTest method initializeProcessor.

private void initializeProcessor(String destinationName, boolean isQueue, FunctionEx<Message, String> projectionFn) throws Exception {
    processorConnection = getConnectionFactory().createConnection();
    processorConnection.start();
    FunctionEx<Session, MessageConsumer> consumerFn = s -> s.createConsumer(isQueue ? s.createQueue(destinationName) : s.createTopic(destinationName));
    if (projectionFn == null) {
        projectionFn = m -> ((TextMessage) m).getText();
    }
    processor = new StreamJmsP<>(processorConnection, consumerFn, Message::getJMSMessageID, projectionFn, noEventTime(), NONE);
    outbox = new TestOutbox(1);
    processor.init(outbox, new TestProcessorContext());
}
Also used : Address(com.hazelcast.cluster.Address) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) RunWith(org.junit.runner.RunWith) TestOutbox(com.hazelcast.jet.core.test.TestOutbox) StreamSource(com.hazelcast.jet.pipeline.StreamSource) ActiveMQConnectionFactory(org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory) Function(java.util.function.Function) TestProcessorContext(com.hazelcast.jet.core.test.TestProcessorContext) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) Session(javax.jms.Session) Arrays.asList(java.util.Arrays.asList) After(org.junit.After) MessageProducer(javax.jms.MessageProducer) ClassRule(org.junit.ClassRule) Message(javax.jms.Message) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) EventTimePolicy.noEventTime(com.hazelcast.jet.core.EventTimePolicy.noEventTime) FunctionEx(com.hazelcast.function.FunctionEx) Connection(javax.jms.Connection) JetTestSupport(com.hazelcast.jet.core.JetTestSupport) TextMessage(javax.jms.TextMessage) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) Test(org.junit.Test) Category(org.junit.experimental.categories.Category) EmbeddedActiveMQResource(org.apache.activemq.artemis.junit.EmbeddedActiveMQResource) NONE(com.hazelcast.jet.config.ProcessingGuarantee.NONE) Sources(com.hazelcast.jet.pipeline.Sources) List(java.util.List) MessageConsumer(javax.jms.MessageConsumer) Destination(javax.jms.Destination) HazelcastParallelClassRunner(com.hazelcast.test.HazelcastParallelClassRunner) StreamSourceTransform(com.hazelcast.jet.impl.pipeline.transform.StreamSourceTransform) Queue(java.util.Queue) ConnectionFactory(javax.jms.ConnectionFactory) Assert.assertEquals(org.junit.Assert.assertEquals) MessageConsumer(javax.jms.MessageConsumer) TestOutbox(com.hazelcast.jet.core.test.TestOutbox) TestProcessorContext(com.hazelcast.jet.core.test.TestProcessorContext) Session(javax.jms.Session)

Aggregations

NONE (com.hazelcast.jet.config.ProcessingGuarantee.NONE)3 ArrayList (java.util.ArrayList)3 Function (java.util.function.Function)3 FunctionEx (com.hazelcast.function.FunctionEx)2 SupplierEx (com.hazelcast.function.SupplierEx)2 Job (com.hazelcast.jet.Job)2 JobConfig (com.hazelcast.jet.config.JobConfig)2 EXACTLY_ONCE (com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE)2 RUNNING (com.hazelcast.jet.core.JobStatus.RUNNING)2 JobRepository (com.hazelcast.jet.impl.JobRepository)2 Sources (com.hazelcast.jet.pipeline.Sources)2 StreamSource (com.hazelcast.jet.pipeline.StreamSource)2 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)2 Assert.assertEquals (org.junit.Assert.assertEquals)2 Test (org.junit.Test)2 Category (org.junit.experimental.categories.Category)2 RunWith (org.junit.runner.RunWith)2 Address (com.hazelcast.cluster.Address)1 IList (com.hazelcast.collection.IList)1 Config (com.hazelcast.config.Config)1