Search in sources :

Example 6 with RUNNING

use of com.hazelcast.jet.core.JobStatus.RUNNING in project hazelcast by hazelcast.

the class AsyncTransformUsingServiceBatchP_IntegrationTest method stressTestInt.

private void stressTestInt(boolean restart) {
    /*
        This is a stress test of the cooperative emission using the DAG api. Only through DAG
        API we can configure edge queue sizes, which we use to cause more trouble for the
        cooperative emission.
         */
    // add more input to the source map
    int numItems = 10_000;
    journaledMap.putAll(IntStream.range(NUM_ITEMS, numItems).boxed().collect(toMap(i -> i, i -> i)));
    DAG dag = new DAG();
    Vertex source = dag.newVertex("source", throttle(streamMapP(journaledMap.getName(), alwaysTrue(), EventJournalMapEvent::getNewValue, START_FROM_OLDEST, eventTimePolicy(i -> (long) ((Integer) i), WatermarkPolicy.limitingLag(10), 10, 0, 0)), 5000));
    BiFunctionEx<ExecutorService, List<Integer>, CompletableFuture<Traverser<String>>> flatMapAsyncFn = transformNotPartitionedFn(i -> traverseItems(i + "-1", i + "-2", i + "-3", i + "-4", i + "-5")).andThen(r -> r.thenApply(results -> traverseIterable(results).flatMap(Function.identity())));
    ProcessorSupplier processorSupplier = AsyncTransformUsingServiceBatchedP.supplier(serviceFactory, DEFAULT_MAX_CONCURRENT_OPS, 128, flatMapAsyncFn);
    Vertex map = dag.newVertex("map", processorSupplier).localParallelism(2);
    Vertex sink = dag.newVertex("sink", SinkProcessors.writeListP(sinkList.getName()));
    // Use a shorter queue to not block the barrier from the source for too long due to
    // the backpressure from the slow mapper
    EdgeConfig edgeToMapperConfig = new EdgeConfig().setQueueSize(128);
    // Use a shorter queue on output from the mapper so that we experience backpressure
    // from the sink
    EdgeConfig edgeFromMapperConfig = new EdgeConfig().setQueueSize(10);
    dag.edge(between(source, map).setConfig(edgeToMapperConfig)).edge(between(map, sink).setConfig(edgeFromMapperConfig));
    Job job = instance().getJet().newJob(dag, jobConfig);
    for (int i = 0; restart && i < 5; i++) {
        assertNotNull(job);
        assertTrueEventually(() -> {
            JobStatus status = job.getStatus();
            assertTrue("status=" + status, status == RUNNING || status == COMPLETED);
        });
        sleepMillis(100);
        try {
            job.restart();
        } catch (IllegalStateException e) {
            assertTrue(e.toString(), e.getMessage().startsWith("Cannot RESTART_GRACEFUL"));
            break;
        }
    }
    assertResult(i -> Stream.of(i + "-1", i + "-2", i + "-3", i + "-4", i + "-5"), numItems);
}
Also used : ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) Traverser(com.hazelcast.jet.Traverser) ServiceFactories.sharedService(com.hazelcast.jet.pipeline.ServiceFactories.sharedService) QuickTest(com.hazelcast.test.annotation.QuickTest) BiFunctionEx(com.hazelcast.function.BiFunctionEx) Traversers.traverseIterable(com.hazelcast.jet.Traversers.traverseIterable) Collectors.toMap(java.util.stream.Collectors.toMap) DAG(com.hazelcast.jet.core.DAG) JobStatus(com.hazelcast.jet.core.JobStatus) SimpleTestInClusterSupport(com.hazelcast.jet.SimpleTestInClusterSupport) FunctionEx(com.hazelcast.function.FunctionEx) WatermarkPolicy(com.hazelcast.jet.core.WatermarkPolicy) Pipeline(com.hazelcast.jet.pipeline.Pipeline) JobConfig(com.hazelcast.jet.config.JobConfig) START_FROM_OLDEST(com.hazelcast.jet.pipeline.JournalInitialPosition.START_FROM_OLDEST) Category(org.junit.experimental.categories.Category) Executors(java.util.concurrent.Executors) Collectors.joining(java.util.stream.Collectors.joining) Sources(com.hazelcast.jet.pipeline.Sources) List(java.util.List) Stream(java.util.stream.Stream) EventJournalMapEvent(com.hazelcast.map.EventJournalMapEvent) SinkProcessors(com.hazelcast.jet.core.processor.SinkProcessors) COMPLETED(com.hazelcast.jet.core.JobStatus.COMPLETED) IntStream(java.util.stream.IntStream) PredicateEx.alwaysTrue(com.hazelcast.function.PredicateEx.alwaysTrue) EdgeConfig(com.hazelcast.jet.config.EdgeConfig) BeforeClass(org.junit.BeforeClass) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) DEFAULT_MAX_CONCURRENT_OPS(com.hazelcast.jet.pipeline.GeneralStage.DEFAULT_MAX_CONCURRENT_OPS) TestUtil.throttle(com.hazelcast.jet.core.TestUtil.throttle) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) ServiceFactory(com.hazelcast.jet.pipeline.ServiceFactory) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) ExecutorService(java.util.concurrent.ExecutorService) Job(com.hazelcast.jet.Job) Before(org.junit.Before) IList(com.hazelcast.collection.IList) Config(com.hazelcast.config.Config) SourceProcessors.streamMapP(com.hazelcast.jet.core.processor.SourceProcessors.streamMapP) Util.toList(com.hazelcast.jet.impl.util.Util.toList) Assert.assertNotNull(org.junit.Assert.assertNotNull) EXACTLY_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE) Sinks(com.hazelcast.jet.pipeline.Sinks) Traversers.traverseItems(com.hazelcast.jet.Traversers.traverseItems) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Vertex(com.hazelcast.jet.core.Vertex) EventTimePolicy.eventTimePolicy(com.hazelcast.jet.core.EventTimePolicy.eventTimePolicy) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) Assert.assertEquals(org.junit.Assert.assertEquals) IMap(com.hazelcast.map.IMap) Edge.between(com.hazelcast.jet.core.Edge.between) Vertex(com.hazelcast.jet.core.Vertex) EdgeConfig(com.hazelcast.jet.config.EdgeConfig) EventJournalMapEvent(com.hazelcast.map.EventJournalMapEvent) DAG(com.hazelcast.jet.core.DAG) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) JobStatus(com.hazelcast.jet.core.JobStatus) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) List(java.util.List) IList(com.hazelcast.collection.IList) Util.toList(com.hazelcast.jet.impl.util.Util.toList) Job(com.hazelcast.jet.Job)

Example 7 with RUNNING

use of com.hazelcast.jet.core.JobStatus.RUNNING 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 8 with RUNNING

use of com.hazelcast.jet.core.JobStatus.RUNNING in project hazelcast by hazelcast.

the class AsyncTransformUsingServiceP_IntegrationTest method stressTestInt.

private void stressTestInt(boolean restart) {
    /*
        This is a stress test of the cooperative emission using the DAG api. Only through DAG
        API we can configure edge queue sizes, which we use to cause more trouble for the
        cooperative emission.
         */
    // add more input to the source map
    int numItems = 10_000;
    journaledMap.putAll(IntStream.range(NUM_ITEMS, numItems).boxed().collect(toMap(i -> i, i -> i)));
    DAG dag = new DAG();
    Vertex source = dag.newVertex("source", throttle(streamMapP(journaledMap.getName(), alwaysTrue(), EventJournalMapEvent::getNewValue, START_FROM_OLDEST, eventTimePolicy(i -> (long) ((Integer) i), WatermarkPolicy.limitingLag(10), 10, 0, 0)), 5000));
    BiFunctionEx<ExecutorService, Integer, CompletableFuture<Traverser<String>>> flatMapAsyncFn = transformNotPartitionedFn(i -> traverseItems(i + "-1", i + "-2", i + "-3", i + "-4", i + "-5"));
    ProcessorSupplier processorSupplier = ordered ? AsyncTransformUsingServiceOrderedP.supplier(serviceFactory, DEFAULT_MAX_CONCURRENT_OPS, flatMapAsyncFn) : AsyncTransformUsingServiceUnorderedP.supplier(serviceFactory, DEFAULT_MAX_CONCURRENT_OPS, flatMapAsyncFn, identity());
    Vertex map = dag.newVertex("map", processorSupplier).localParallelism(2);
    Vertex sink = dag.newVertex("sink", SinkProcessors.writeListP(sinkList.getName()));
    // Use a shorter queue to not block the barrier from the source for too long due to
    // the backpressure from the slow mapper
    EdgeConfig edgeToMapperConfig = new EdgeConfig().setQueueSize(128);
    // Use a shorter queue on output from the mapper so that we experience backpressure
    // from the sink
    EdgeConfig edgeFromMapperConfig = new EdgeConfig().setQueueSize(10);
    dag.edge(between(source, map).setConfig(edgeToMapperConfig)).edge(between(map, sink).setConfig(edgeFromMapperConfig));
    Job job = instance().getJet().newJob(dag, jobConfig);
    for (int i = 0; restart && i < 5; i++) {
        assertJobStatusEventually(job, RUNNING);
        sleepMillis(100);
        job.restart();
    }
    assertResultEventually(i -> Stream.of(i + "-1", i + "-2", i + "-3", i + "-4", i + "-5"), numItems);
}
Also used : ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) Traverser(com.hazelcast.jet.Traverser) ServiceFactories.sharedService(com.hazelcast.jet.pipeline.ServiceFactories.sharedService) QuickTest(com.hazelcast.test.annotation.QuickTest) BiFunctionEx(com.hazelcast.function.BiFunctionEx) Collectors.toMap(java.util.stream.Collectors.toMap) Arrays.asList(java.util.Arrays.asList) DAG(com.hazelcast.jet.core.DAG) SimpleTestInClusterSupport(com.hazelcast.jet.SimpleTestInClusterSupport) FunctionEx(com.hazelcast.function.FunctionEx) WatermarkPolicy(com.hazelcast.jet.core.WatermarkPolicy) HazelcastParametrizedRunner(com.hazelcast.test.HazelcastParametrizedRunner) Pipeline(com.hazelcast.jet.pipeline.Pipeline) Collection(java.util.Collection) JobConfig(com.hazelcast.jet.config.JobConfig) START_FROM_OLDEST(com.hazelcast.jet.pipeline.JournalInitialPosition.START_FROM_OLDEST) Category(org.junit.experimental.categories.Category) Executors(java.util.concurrent.Executors) Collectors.joining(java.util.stream.Collectors.joining) Sources(com.hazelcast.jet.pipeline.Sources) Stream(java.util.stream.Stream) EventJournalMapEvent(com.hazelcast.map.EventJournalMapEvent) SinkProcessors(com.hazelcast.jet.core.processor.SinkProcessors) IntStream(java.util.stream.IntStream) PredicateEx.alwaysTrue(com.hazelcast.function.PredicateEx.alwaysTrue) EdgeConfig(com.hazelcast.jet.config.EdgeConfig) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) CompletableFuture(java.util.concurrent.CompletableFuture) HazelcastSerialParametersRunnerFactory(com.hazelcast.test.HazelcastSerialParametersRunnerFactory) Function(java.util.function.Function) DEFAULT_MAX_CONCURRENT_OPS(com.hazelcast.jet.pipeline.GeneralStage.DEFAULT_MAX_CONCURRENT_OPS) TestUtil.throttle(com.hazelcast.jet.core.TestUtil.throttle) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) ServiceFactory(com.hazelcast.jet.pipeline.ServiceFactory) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) ExecutorService(java.util.concurrent.ExecutorService) Job(com.hazelcast.jet.Job) Before(org.junit.Before) UseParametersRunnerFactory(org.junit.runners.Parameterized.UseParametersRunnerFactory) IList(com.hazelcast.collection.IList) Config(com.hazelcast.config.Config) SourceProcessors.streamMapP(com.hazelcast.jet.core.processor.SourceProcessors.streamMapP) Parameter(org.junit.runners.Parameterized.Parameter) EXACTLY_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE) Sinks(com.hazelcast.jet.pipeline.Sinks) Traversers.traverseItems(com.hazelcast.jet.Traversers.traverseItems) Test(org.junit.Test) Vertex(com.hazelcast.jet.core.Vertex) FunctionEx.identity(com.hazelcast.function.FunctionEx.identity) EventTimePolicy.eventTimePolicy(com.hazelcast.jet.core.EventTimePolicy.eventTimePolicy) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) TriFunction(com.hazelcast.jet.function.TriFunction) Assert.assertEquals(org.junit.Assert.assertEquals) IMap(com.hazelcast.map.IMap) Edge.between(com.hazelcast.jet.core.Edge.between) Vertex(com.hazelcast.jet.core.Vertex) EdgeConfig(com.hazelcast.jet.config.EdgeConfig) EventJournalMapEvent(com.hazelcast.map.EventJournalMapEvent) DAG(com.hazelcast.jet.core.DAG) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) Job(com.hazelcast.jet.Job)

Example 9 with RUNNING

use of com.hazelcast.jet.core.JobStatus.RUNNING in project hazelcast by hazelcast.

the class GracefulShutdownTest method when_shutdownGracefulWhileRestartGraceful_then_restartsFromTerminalSnapshot.

@Test
public void when_shutdownGracefulWhileRestartGraceful_then_restartsFromTerminalSnapshot() throws Exception {
    MapConfig mapConfig = new MapConfig(JobRepository.SNAPSHOT_DATA_MAP_PREFIX + "*");
    mapConfig.getMapStoreConfig().setClassName(BlockingMapStore.class.getName()).setEnabled(true);
    Config config = instances[0].getConfig();
    ((DynamicConfigurationAwareConfig) config).getStaticConfig().addMapConfig(mapConfig);
    BlockingMapStore.shouldBlock = false;
    BlockingMapStore.wasBlocked = false;
    DAG dag = new DAG();
    int numItems = 5000;
    Vertex source = dag.newVertex("source", throttle(() -> new EmitIntegersP(numItems), 500));
    Vertex sink = dag.newVertex("sink", SinkProcessors.writeListP("sink"));
    dag.edge(between(source, sink));
    source.localParallelism(1);
    Job job = instances[0].getJet().newJob(dag, new JobConfig().setProcessingGuarantee(EXACTLY_ONCE).setSnapshotIntervalMillis(2000));
    // wait for the first snapshot
    JetServiceBackend jetServiceBackend = getNode(instances[0]).nodeEngine.getService(JetServiceBackend.SERVICE_NAME);
    JobRepository jobRepository = jetServiceBackend.getJobCoordinationService().jobRepository();
    assertJobStatusEventually(job, RUNNING);
    assertTrueEventually(() -> assertTrue(jobRepository.getJobExecutionRecord(job.getId()).dataMapIndex() >= 0));
    // When
    BlockingMapStore.shouldBlock = true;
    job.restart();
    assertTrueEventually(() -> assertTrue("blocking did not happen", BlockingMapStore.wasBlocked), 5);
    Future shutdownFuture = spawn(() -> instances[1].shutdown());
    logger.info("savedCounters=" + EmitIntegersP.savedCounters);
    int minCounter = EmitIntegersP.savedCounters.values().stream().mapToInt(Integer::intValue).min().getAsInt();
    BlockingMapStore.shouldBlock = false;
    shutdownFuture.get();
    // Then
    job.join();
    Map<Integer, Integer> actual = new ArrayList<>(instances[0].<Integer>getList("sink")).stream().collect(Collectors.toMap(Function.identity(), item -> 1, Integer::sum));
    Map<Integer, Integer> expected = IntStream.range(0, numItems).boxed().collect(Collectors.toMap(Function.identity(), item -> item < minCounter ? 2 : 1));
    assertEquals(expected, actual);
}
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) MapConfig(com.hazelcast.config.MapConfig) Config(com.hazelcast.config.Config) JobConfig(com.hazelcast.jet.config.JobConfig) DynamicConfigurationAwareConfig(com.hazelcast.internal.dynamicconfig.DynamicConfigurationAwareConfig) ArrayList(java.util.ArrayList) JobRepository(com.hazelcast.jet.impl.JobRepository) JobConfig(com.hazelcast.jet.config.JobConfig) Future(java.util.concurrent.Future) MapConfig(com.hazelcast.config.MapConfig) Job(com.hazelcast.jet.Job) JetServiceBackend(com.hazelcast.jet.impl.JetServiceBackend) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) Test(org.junit.Test) SlowTest(com.hazelcast.test.annotation.SlowTest)

Example 10 with RUNNING

use of com.hazelcast.jet.core.JobStatus.RUNNING in project hazelcast by hazelcast.

the class ManualRestartTest method when_terminalSnapshotFails_then_previousSnapshotUsed.

@Test
public void when_terminalSnapshotFails_then_previousSnapshotUsed() {
    MapConfig mapConfig = new MapConfig(JobRepository.SNAPSHOT_DATA_MAP_PREFIX + "*");
    mapConfig.getMapStoreConfig().setClassName(FailingMapStore.class.getName()).setEnabled(true);
    Config config = instances[0].getConfig();
    ((DynamicConfigurationAwareConfig) config).getStaticConfig().addMapConfig(mapConfig);
    FailingMapStore.fail = false;
    FailingMapStore.failed = false;
    DAG dag = new DAG();
    Vertex source = dag.newVertex("source", throttle(() -> new SequencesInPartitionsGeneratorP(2, 10000, true), 1000));
    Vertex sink = dag.newVertex("sink", writeListP("sink"));
    dag.edge(between(source, sink));
    source.localParallelism(1);
    Job job = instances[0].getJet().newJob(dag, new JobConfig().setProcessingGuarantee(EXACTLY_ONCE).setSnapshotIntervalMillis(2000));
    // wait for the first snapshot
    JetServiceBackend jetServiceBackend = getNode(instances[0]).nodeEngine.getService(JetServiceBackend.SERVICE_NAME);
    JobRepository jobRepository = jetServiceBackend.getJobCoordinationService().jobRepository();
    assertJobStatusEventually(job, RUNNING);
    assertTrueEventually(() -> assertTrue(jobRepository.getJobExecutionRecord(job.getId()).dataMapIndex() >= 0));
    // When
    sleepMillis(100);
    FailingMapStore.fail = true;
    job.restart();
    assertTrueEventually(() -> assertTrue(FailingMapStore.failed));
    FailingMapStore.fail = false;
    job.join();
    Map<Integer, Integer> actual = new ArrayList<>(instances[0].<Entry<Integer, Integer>>getList("sink")).stream().filter(// we'll only check partition 0
    e -> e.getKey() == 0).map(Entry::getValue).collect(Collectors.toMap(e -> e, e -> 1, (o, n) -> o + n, TreeMap::new));
    assertEquals("first item != 1, " + actual.toString(), (Integer) 1, actual.get(0));
    assertEquals("last item != 1, " + actual.toString(), (Integer) 1, actual.get(9999));
    // the result should be some ones, then some twos and then some ones. The twos should be during the time
    // since the last successful snapshot until the actual termination, when there was reprocessing.
    boolean sawTwo = false;
    boolean sawOneAgain = false;
    for (Integer v : actual.values()) {
        if (v == 1) {
            if (sawTwo) {
                sawOneAgain = true;
            }
        } else if (v == 2) {
            assertFalse("got a 2 in another group", sawOneAgain);
            sawTwo = true;
        } else {
            fail("v=" + v);
        }
    }
    assertTrue("didn't see any 2s", sawTwo);
}
Also used : ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) RunWith(org.junit.runner.RunWith) JetInitDataSerializerHook(com.hazelcast.jet.impl.execution.init.JetInitDataSerializerHook) HazelcastSerialClassRunner(com.hazelcast.test.HazelcastSerialClassRunner) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) MapConfig(com.hazelcast.config.MapConfig) SequencesInPartitionsGeneratorP(com.hazelcast.jet.core.JobRestartWithSnapshotTest.SequencesInPartitionsGeneratorP) PacketFiltersUtil.rejectOperationsBetween(com.hazelcast.test.PacketFiltersUtil.rejectOperationsBetween) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) TestUtil.throttle(com.hazelcast.jet.core.TestUtil.throttle) Map(java.util.Map) STARTING(com.hazelcast.jet.core.JobStatus.STARTING) Assert.fail(org.junit.Assert.fail) ExpectedException(org.junit.rules.ExpectedException) 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) MockPS(com.hazelcast.jet.core.TestProcessors.MockPS) EXACTLY_ONCE(com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE) JobConfig(com.hazelcast.jet.config.JobConfig) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Category(org.junit.experimental.categories.Category) AMapStore(com.hazelcast.client.map.helpers.AMapStore) Collectors(java.util.stream.Collectors) NoOutputSourceP(com.hazelcast.jet.core.TestProcessors.NoOutputSourceP) DynamicConfigurationAwareConfig(com.hazelcast.internal.dynamicconfig.DynamicConfigurationAwareConfig) Serializable(java.io.Serializable) Rule(org.junit.Rule) TreeMap(java.util.TreeMap) Assert.assertFalse(org.junit.Assert.assertFalse) Entry(java.util.Map.Entry) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) PacketFiltersUtil.resetPacketFiltersFrom(com.hazelcast.test.PacketFiltersUtil.resetPacketFiltersFrom) Assert.assertEquals(org.junit.Assert.assertEquals) JetServiceBackend(com.hazelcast.jet.impl.JetServiceBackend) Edge.between(com.hazelcast.jet.core.Edge.between) SinkProcessors.writeListP(com.hazelcast.jet.core.processor.SinkProcessors.writeListP) MapConfig(com.hazelcast.config.MapConfig) Config(com.hazelcast.config.Config) JobConfig(com.hazelcast.jet.config.JobConfig) DynamicConfigurationAwareConfig(com.hazelcast.internal.dynamicconfig.DynamicConfigurationAwareConfig) ArrayList(java.util.ArrayList) JobRepository(com.hazelcast.jet.impl.JobRepository) JobConfig(com.hazelcast.jet.config.JobConfig) SequencesInPartitionsGeneratorP(com.hazelcast.jet.core.JobRestartWithSnapshotTest.SequencesInPartitionsGeneratorP) MapConfig(com.hazelcast.config.MapConfig) Job(com.hazelcast.jet.Job) JetServiceBackend(com.hazelcast.jet.impl.JetServiceBackend) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Aggregations

RUNNING (com.hazelcast.jet.core.JobStatus.RUNNING)15 Job (com.hazelcast.jet.Job)12 JobConfig (com.hazelcast.jet.config.JobConfig)12 Assert.assertEquals (org.junit.Assert.assertEquals)11 Test (org.junit.Test)11 List (java.util.List)9 Assert.assertTrue (org.junit.Assert.assertTrue)9 Category (org.junit.experimental.categories.Category)9 Edge.between (com.hazelcast.jet.core.Edge.between)8 Map (java.util.Map)8 Config (com.hazelcast.config.Config)7 DAG (com.hazelcast.jet.core.DAG)7 COMPLETED (com.hazelcast.jet.core.JobStatus.COMPLETED)7 JobRepository (com.hazelcast.jet.impl.JobRepository)7 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)7 Function (java.util.function.Function)7 HazelcastInstance (com.hazelcast.core.HazelcastInstance)6 STARTING (com.hazelcast.jet.core.JobStatus.STARTING)6 Vertex (com.hazelcast.jet.core.Vertex)6 QuickTest (com.hazelcast.test.annotation.QuickTest)6