Search in sources :

Example 36 with DAG

use of com.hazelcast.jet.core.DAG in project hazelcast-jet-reference-manual by hazelcast.

the class StockExchangeCoreApi method buildDag.

static DAG buildDag() {
    // tag::s1[]
    DistributedToLongFunction<? super Trade> timestampFn = Trade::timestamp;
    DistributedFunction<? super Trade, ?> keyFn = Trade::productId;
    SlidingWindowPolicy winPolicy = slidingWinPolicy(SLIDING_WINDOW_LENGTH_MILLIS, SLIDE_STEP_MILLIS);
    DAG dag = new DAG();
    Vertex tradeSource = dag.newVertex("trade-source", SourceProcessors.<Trade, Long, Trade>streamMapP(TRADES_MAP_NAME, // <1>
    alwaysTrue(), // <1>
    EventJournalMapEvent::getNewValue, // <2>
    JournalInitialPosition.START_FROM_OLDEST, wmGenParams(// <3>
    timestampFn, // <4>
    limitingLag(SECONDS.toMillis(3)), // <5>
    emitByFrame(winPolicy), // <6>
    SECONDS.toMillis(3))));
    Vertex slidingStage1 = dag.newVertex("sliding-stage-1", Processors.accumulateByFrameP(singletonList(keyFn), singletonList(timestampFn), TimestampKind.EVENT, winPolicy, counting()));
    Vertex slidingStage2 = dag.newVertex("sliding-stage-2", Processors.combineToSlidingWindowP(winPolicy, counting(), TimestampedEntry::new));
    Vertex formatOutput = dag.newVertex("format-output", mapUsingContextP(ContextFactory.withCreateFn(x -> DateTimeFormatter.ofPattern("HH:mm:ss.SSS")), (DateTimeFormatter timeFormat, TimestampedEntry<String, Long> tse) -> String.format("%s %5s %4d", timeFormat.format(Instant.ofEpochMilli(tse.getTimestamp()).atZone(ZoneId.systemDefault())), tse.getKey(), tse.getValue())));
    Vertex sink = dag.newVertex("sink", SinkProcessors.writeFileP(OUTPUT_DIR_NAME));
    tradeSource.localParallelism(1);
    return dag.edge(between(tradeSource, slidingStage1).partitioned(keyFn, HASH_CODE)).edge(between(slidingStage1, slidingStage2).partitioned(entryKey(), HASH_CODE).distributed()).edge(between(slidingStage2, formatOutput).isolated()).edge(between(formatOutput, sink));
// end::s1[]
}
Also used : Vertex(com.hazelcast.jet.core.Vertex) SlidingWindowPolicy(com.hazelcast.jet.core.SlidingWindowPolicy) DAG(com.hazelcast.jet.core.DAG) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 37 with DAG

use of com.hazelcast.jet.core.DAG in project hazelcast-jet-reference-manual by hazelcast.

the class S8 method main.

// end::s1[]
static void main() {
    // tag::s2[]
    JetInstance jet = Jet.newJetInstance();
    int upperBound = 10;
    DAG dag = new DAG();
    Vertex generateNumbers = dag.newVertex("generate-numbers", () -> new GenerateNumbersP(upperBound));
    Vertex logInput = dag.newVertex("log-input", DiagnosticProcessors.writeLoggerP(i -> "Received number: " + i));
    dag.edge(Edge.between(generateNumbers, logInput));
    try {
        jet.newJob(dag).join();
    } finally {
        Jet.shutdownAll();
    }
// end::s2[]
}
Also used : IntStream(java.util.stream.IntStream) AbstractProcessor(com.hazelcast.jet.core.AbstractProcessor) Traverser(com.hazelcast.jet.Traverser) DiagnosticProcessors(com.hazelcast.jet.core.processor.DiagnosticProcessors) JetInstance(com.hazelcast.jet.JetInstance) IntStream.range(java.util.stream.IntStream.range) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) Processor(com.hazelcast.jet.core.Processor) Address(com.hazelcast.nio.Address) HashMap(java.util.HashMap) Traversers(com.hazelcast.jet.Traversers) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Vertex(com.hazelcast.jet.core.Vertex) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Map(java.util.Map) Context(com.hazelcast.jet.core.Processor.Context) Jet(com.hazelcast.jet.Jet) DAG(com.hazelcast.jet.core.DAG) Edge(com.hazelcast.jet.core.Edge) Nonnull(javax.annotation.Nonnull) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) Vertex(com.hazelcast.jet.core.Vertex) JetInstance(com.hazelcast.jet.JetInstance) DAG(com.hazelcast.jet.core.DAG)

Example 38 with DAG

use of com.hazelcast.jet.core.DAG in project hazelcast-jet-reference-manual by hazelcast.

the class ExpertZoneDag method s0.

// end::s1[]
static void s0() {
    Pipeline pipeline = Pipeline.create();
    // tag::s0[]
    DAG dag = pipeline.toDag();
// end::s0[]
}
Also used : DAG(com.hazelcast.jet.core.DAG) Pipeline(com.hazelcast.jet.pipeline.Pipeline)

Example 39 with DAG

use of com.hazelcast.jet.core.DAG in project hazelcast by hazelcast.

the class MasterJobContext method tryStartJob.

/**
 * Starts the execution of the job if it is not already completed,
 * cancelled or failed.
 * <p>
 * If the job is already cancelled, triggers the job completion procedure.
 * <p>
 * If the job quorum is not satisfied, reschedules the job restart.
 * <p>
 * If there was a membership change and the partition table is not completely
 * fixed yet, reschedules the job restart.
 */
void tryStartJob(Supplier<Long> executionIdSupplier) {
    mc.coordinationService().submitToCoordinatorThread(() -> {
        executionStartTime = System.currentTimeMillis();
        try {
            JobExecutionRecord jobExecRec = mc.jobExecutionRecord();
            jobExecRec.markExecuted();
            Tuple2<DAG, ClassLoader> dagAndClassloader = resolveDagAndCL(executionIdSupplier);
            if (dagAndClassloader == null) {
                return;
            }
            DAG dag = dagAndClassloader.f0();
            assert dag != null;
            ClassLoader classLoader = dagAndClassloader.f1();
            // must call this before rewriteDagWithSnapshotRestore()
            String dotRepresentation = dag.toDotString(defaultParallelism, defaultQueueSize);
            long snapshotId = jobExecRec.snapshotId();
            String snapshotName = mc.jobConfig().getInitialSnapshotName();
            String mapName = snapshotId >= 0 ? jobExecRec.successfulSnapshotDataMapName(mc.jobId()) : snapshotName != null ? EXPORTED_SNAPSHOTS_PREFIX + snapshotName : null;
            if (mapName != null) {
                rewriteDagWithSnapshotRestore(dag, snapshotId, mapName, snapshotName);
            } else {
                logger.info("Didn't find any snapshot to restore for " + mc.jobIdString());
            }
            MembersView membersView = Util.getMembersView(mc.nodeEngine());
            logger.info("Start executing " + mc.jobIdString() + ", execution graph in DOT format:\n" + dotRepresentation + "\nHINT: You can use graphviz or http://viz-js.com to visualize the printed graph.");
            logger.fine("Building execution plan for " + mc.jobIdString());
            Util.doWithClassLoader(classLoader, () -> mc.setExecutionPlanMap(createExecutionPlans(mc.nodeEngine(), membersView.getMembers(), dag, mc.jobId(), mc.executionId(), mc.jobConfig(), jobExecRec.ongoingSnapshotId(), false, mc.jobRecord().getSubject())));
            logger.fine("Built execution plans for " + mc.jobIdString());
            Set<MemberInfo> participants = mc.executionPlanMap().keySet();
            Version coordinatorVersion = mc.nodeEngine().getLocalMember().getVersion().asVersion();
            Function<ExecutionPlan, Operation> operationCtor = plan -> new InitExecutionOperation(mc.jobId(), mc.executionId(), membersView.getVersion(), coordinatorVersion, participants, mc.nodeEngine().getSerializationService().toData(plan), false);
            mc.invokeOnParticipants(operationCtor, this::onInitStepCompleted, null, false);
        } catch (Throwable e) {
            finalizeJob(e);
        }
    });
}
Also used : Address(com.hazelcast.cluster.Address) SUSPEND(com.hazelcast.jet.impl.TerminationMode.ActionAfterTerminate.SUSPEND) NOT_RUNNING(com.hazelcast.jet.core.JobStatus.NOT_RUNNING) GetLocalJobMetricsOperation(com.hazelcast.jet.impl.operation.GetLocalJobMetricsOperation) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) NonCompletableFuture(com.hazelcast.jet.impl.util.NonCompletableFuture) ExceptionUtil.isTopologyException(com.hazelcast.jet.impl.util.ExceptionUtil.isTopologyException) JobTerminateRequestedException(com.hazelcast.jet.impl.exception.JobTerminateRequestedException) SourceProcessors.readMapP(com.hazelcast.jet.core.processor.SourceProcessors.readMapP) RESTART(com.hazelcast.jet.impl.TerminationMode.ActionAfterTerminate.RESTART) JetDelegatingClassLoader(com.hazelcast.jet.impl.deployment.JetDelegatingClassLoader) TerminatedWithSnapshotException(com.hazelcast.jet.impl.exception.TerminatedWithSnapshotException) Collectors.toMap(java.util.stream.Collectors.toMap) Functions.entryKey(com.hazelcast.function.Functions.entryKey) MemberInfo(com.hazelcast.internal.cluster.MemberInfo) Map(java.util.Map) STARTING(com.hazelcast.jet.core.JobStatus.STARTING) SUSPENDED(com.hazelcast.jet.core.JobStatus.SUSPENDED) DAG(com.hazelcast.jet.core.DAG) JobStatus(com.hazelcast.jet.core.JobStatus) ExceptionUtil(com.hazelcast.jet.impl.util.ExceptionUtil) JobMetrics(com.hazelcast.jet.core.metrics.JobMetrics) CancellationException(java.util.concurrent.CancellationException) CANCEL_GRACEFUL(com.hazelcast.jet.impl.TerminationMode.CANCEL_GRACEFUL) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Collectors(java.util.stream.Collectors) CANCEL_FORCEFUL(com.hazelcast.jet.impl.TerminationMode.CANCEL_FORCEFUL) Objects(java.util.Objects) Util(com.hazelcast.jet.impl.util.Util) List(java.util.List) Util.idToString(com.hazelcast.jet.Util.idToString) ExecutionPlan(com.hazelcast.jet.impl.execution.init.ExecutionPlan) MetricNames(com.hazelcast.jet.core.metrics.MetricNames) Entry(java.util.Map.Entry) TopologyChangedException(com.hazelcast.jet.core.TopologyChangedException) COMPLETED(com.hazelcast.jet.core.JobStatus.COMPLETED) JetDisabledException(com.hazelcast.jet.impl.exception.JetDisabledException) LoggingUtil(com.hazelcast.jet.impl.util.LoggingUtil) ExecutionPlanBuilder.createExecutionPlans(com.hazelcast.jet.impl.execution.init.ExecutionPlanBuilder.createExecutionPlans) Collectors.partitioningBy(java.util.stream.Collectors.partitioningBy) TerminateExecutionOperation(com.hazelcast.jet.impl.operation.TerminateExecutionOperation) ExceptionUtil.isRestartableException(com.hazelcast.jet.impl.util.ExceptionUtil.isRestartableException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) LoggingUtil.logFinest(com.hazelcast.jet.impl.util.LoggingUtil.logFinest) Util.doWithClassLoader(com.hazelcast.jet.impl.util.Util.doWithClassLoader) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionService(com.hazelcast.spi.impl.executionservice.ExecutionService) StartExecutionOperation(com.hazelcast.jet.impl.operation.StartExecutionOperation) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Util.formatJobDuration(com.hazelcast.jet.impl.util.Util.formatJobDuration) ActionAfterTerminate(com.hazelcast.jet.impl.TerminationMode.ActionAfterTerminate) ExecutionNotFoundException(com.hazelcast.jet.impl.exception.ExecutionNotFoundException) ArrayList(java.util.ArrayList) JetException(com.hazelcast.jet.JetException) HashSet(java.util.HashSet) InitExecutionOperation(com.hazelcast.jet.impl.operation.InitExecutionOperation) COORDINATOR(com.hazelcast.jet.impl.JobClassLoaderService.JobPhase.COORDINATOR) ILogger(com.hazelcast.logging.ILogger) SnapshotValidator.validateSnapshot(com.hazelcast.jet.impl.SnapshotValidator.validateSnapshot) ExceptionUtil.rethrow(com.hazelcast.jet.impl.util.ExceptionUtil.rethrow) Operation(com.hazelcast.spi.impl.operationservice.Operation) Util.entry(com.hazelcast.jet.Util.entry) ExceptionUtil.withTryCatch(com.hazelcast.jet.impl.util.ExceptionUtil.withTryCatch) BiConsumer(java.util.function.BiConsumer) MembersView(com.hazelcast.internal.cluster.impl.MembersView) LocalMemberResetException(com.hazelcast.core.LocalMemberResetException) RESTART_GRACEFUL(com.hazelcast.jet.impl.TerminationMode.RESTART_GRACEFUL) Edge(com.hazelcast.jet.core.Edge) Version(com.hazelcast.version.Version) EXPORTED_SNAPSHOTS_PREFIX(com.hazelcast.jet.impl.JobRepository.EXPORTED_SNAPSHOTS_PREFIX) Nonnull(javax.annotation.Nonnull) Tuple2(com.hazelcast.jet.datamodel.Tuple2) Nullable(javax.annotation.Nullable) Job(com.hazelcast.jet.Job) Measurement(com.hazelcast.jet.core.metrics.Measurement) SUSPENDED_EXPORTING_SNAPSHOT(com.hazelcast.jet.core.JobStatus.SUSPENDED_EXPORTING_SNAPSHOT) Util.toList(com.hazelcast.jet.impl.util.Util.toList) RawJobMetrics(com.hazelcast.jet.impl.metrics.RawJobMetrics) MetricTags(com.hazelcast.jet.core.metrics.MetricTags) NONE(com.hazelcast.jet.config.ProcessingGuarantee.NONE) Consumer(java.util.function.Consumer) Vertex(com.hazelcast.jet.core.Vertex) Tuple2.tuple2(com.hazelcast.jet.datamodel.Tuple2.tuple2) CustomClassLoadedObject.deserializeWithCustomClassLoader(com.hazelcast.jet.impl.execution.init.CustomClassLoadedObject.deserializeWithCustomClassLoader) ExceptionUtil.peel(com.hazelcast.jet.impl.util.ExceptionUtil.peel) FAILED(com.hazelcast.jet.core.JobStatus.FAILED) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) Collections(java.util.Collections) IMap(com.hazelcast.map.IMap) Edge.between(com.hazelcast.jet.core.Edge.between) MembersView(com.hazelcast.internal.cluster.impl.MembersView) DAG(com.hazelcast.jet.core.DAG) Util.idToString(com.hazelcast.jet.Util.idToString) GetLocalJobMetricsOperation(com.hazelcast.jet.impl.operation.GetLocalJobMetricsOperation) TerminateExecutionOperation(com.hazelcast.jet.impl.operation.TerminateExecutionOperation) StartExecutionOperation(com.hazelcast.jet.impl.operation.StartExecutionOperation) InitExecutionOperation(com.hazelcast.jet.impl.operation.InitExecutionOperation) Operation(com.hazelcast.spi.impl.operationservice.Operation) ExecutionPlan(com.hazelcast.jet.impl.execution.init.ExecutionPlan) MemberInfo(com.hazelcast.internal.cluster.MemberInfo) Version(com.hazelcast.version.Version) InitExecutionOperation(com.hazelcast.jet.impl.operation.InitExecutionOperation) JetDelegatingClassLoader(com.hazelcast.jet.impl.deployment.JetDelegatingClassLoader) Util.doWithClassLoader(com.hazelcast.jet.impl.util.Util.doWithClassLoader) CustomClassLoadedObject.deserializeWithCustomClassLoader(com.hazelcast.jet.impl.execution.init.CustomClassLoadedObject.deserializeWithCustomClassLoader)

Example 40 with DAG

use of com.hazelcast.jet.core.DAG in project hazelcast by hazelcast.

the class Util method copyMapUsingJob.

// used in jet-enterprise
@SuppressWarnings("WeakerAccess")
public static CompletableFuture<Void> copyMapUsingJob(HazelcastInstance instance, int queueSize, String sourceMap, String targetMap) {
    DAG dag = new DAG();
    Vertex source = dag.newVertex("readMap(" + sourceMap + ')', readMapP(sourceMap));
    Vertex sink = dag.newVertex("writeMap(" + targetMap + ')', writeMapP(targetMap));
    dag.edge(between(source, sink).setConfig(new EdgeConfig().setQueueSize(queueSize)));
    JobConfig jobConfig = new JobConfig().setName("copy-" + sourceMap + "-to-" + targetMap);
    return instance.getJet().newJob(dag, jobConfig).getFuture();
}
Also used : Vertex(com.hazelcast.jet.core.Vertex) EdgeConfig(com.hazelcast.jet.config.EdgeConfig) DAG(com.hazelcast.jet.core.DAG) JobConfig(com.hazelcast.jet.config.JobConfig)

Aggregations

DAG (com.hazelcast.jet.core.DAG)211 Test (org.junit.Test)159 Vertex (com.hazelcast.jet.core.Vertex)127 QuickTest (com.hazelcast.test.annotation.QuickTest)100 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)91 Job (com.hazelcast.jet.Job)64 Entry (java.util.Map.Entry)51 List (java.util.List)38 Assert.assertEquals (org.junit.Assert.assertEquals)37 Map (java.util.Map)36 JobConfig (com.hazelcast.jet.config.JobConfig)35 Assert.assertTrue (org.junit.Assert.assertTrue)31 Edge (com.hazelcast.jet.core.Edge)29 IntStream (java.util.stream.IntStream)29 Category (org.junit.experimental.categories.Category)28 Collectors.toList (java.util.stream.Collectors.toList)26 HazelcastInstance (com.hazelcast.core.HazelcastInstance)23 FunctionEx (com.hazelcast.function.FunctionEx)23 ArrayList (java.util.ArrayList)22 Nonnull (javax.annotation.Nonnull)21