Search in sources :

Example 26 with ProgramDescriptor

use of io.cdap.cdap.app.program.ProgramDescriptor in project cdap by cdapio.

the class RuntimeServiceMainTest method testRuntimeService.

@Test
public void testRuntimeService() throws Exception {
    ArtifactId artifactId = NamespaceId.DEFAULT.artifact("test", "1.0");
    ProgramRunId programRunId = NamespaceId.DEFAULT.app("app").worker("worker").run(RunIds.generate());
    Map<String, String> systemArgs = ImmutableMap.of(SystemArguments.PROFILE_PROVISIONER, NativeProvisioner.SPEC.getName(), SystemArguments.PROFILE_NAME, "default");
    ProgramOptions programOptions = new SimpleProgramOptions(programRunId.getParent(), new BasicArguments(systemArgs), new BasicArguments());
    ProgramDescriptor programDescriptor = new ProgramDescriptor(programRunId.getParent(), null, artifactId);
    // Write out program state events to simulate program start
    Injector appFabricInjector = getServiceMainInstance(AppFabricServiceMain.class).getInjector();
    CConfiguration cConf = appFabricInjector.getInstance(CConfiguration.class);
    ProgramStatePublisher programStatePublisher = new MessagingProgramStatePublisher(appFabricInjector.getInstance(MessagingService.class), NamespaceId.SYSTEM.topic(cConf.get(Constants.AppFabric.PROGRAM_STATUS_RECORD_EVENT_TOPIC)), RetryStrategies.fromConfiguration(cConf, "system.program.state."));
    new MessagingProgramStateWriter(programStatePublisher).start(programRunId, programOptions, null, programDescriptor);
    Injector injector = getServiceMainInstance(RuntimeServiceMain.class).getInjector();
    TransactionRunner txRunner = injector.getInstance(TransactionRunner.class);
    // Should see a STARTING record in the runtime store
    Tasks.waitFor(ProgramRunStatus.STARTING, () -> {
        RunRecordDetail detail = TransactionRunners.run(txRunner, context -> {
            return AppMetadataStore.create(context).getRun(programRunId);
        });
        return detail == null ? null : detail.getStatus();
    }, 5, TimeUnit.SECONDS);
    ProgramStateWriter programStateWriter = createProgramStateWriter(injector, programRunId);
    // Write a running state. We should see a RUNNING record in the runtime store
    programStateWriter.running(programRunId, null);
    Tasks.waitFor(ProgramRunStatus.RUNNING, () -> {
        RunRecordDetail detail = TransactionRunners.run(txRunner, context -> {
            return AppMetadataStore.create(context).getRun(programRunId);
        });
        return detail == null ? null : detail.getStatus();
    }, 5, TimeUnit.SECONDS);
    // Write a complete state. The run record should be removed in the runtime store
    programStateWriter.completed(programRunId);
    Tasks.waitFor(true, () -> TransactionRunners.run(txRunner, context -> AppMetadataStore.create(context).getRun(programRunId) == null), 5, TimeUnit.SECONDS);
}
Also used : Retries(io.cdap.cdap.common.service.Retries) RetryStrategy(io.cdap.cdap.common.service.RetryStrategy) RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) TransactionRunners(io.cdap.cdap.spi.data.transaction.TransactionRunners) BeforeClass(org.junit.BeforeClass) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) Notification(io.cdap.cdap.proto.Notification) Bytes(io.cdap.cdap.api.common.Bytes) RetryStrategies(io.cdap.cdap.common.service.RetryStrategies) TopicId(io.cdap.cdap.proto.id.TopicId) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) Gson(com.google.gson.Gson) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) Map(java.util.Map) SystemArguments(io.cdap.cdap.internal.app.runtime.SystemArguments) NativeProvisioner(io.cdap.cdap.internal.provision.NativeProvisioner) ArtifactId(io.cdap.cdap.proto.id.ArtifactId) AppMetadataStore(io.cdap.cdap.internal.app.store.AppMetadataStore) Tasks(io.cdap.cdap.common.utils.Tasks) Message(io.cdap.cdap.api.messaging.Message) ImmutableMap(com.google.common.collect.ImmutableMap) RunIds(io.cdap.cdap.common.app.RunIds) ProgramStatePublisher(io.cdap.cdap.internal.app.program.ProgramStatePublisher) RetryableException(io.cdap.cdap.api.retry.RetryableException) MessagingService(io.cdap.cdap.messaging.MessagingService) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) MessagingProgramStatePublisher(io.cdap.cdap.internal.app.program.MessagingProgramStatePublisher) RuntimeClient(io.cdap.cdap.internal.app.runtime.monitor.RuntimeClient) Test(org.junit.Test) IOException(java.io.IOException) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) StandardCharsets(java.nio.charset.StandardCharsets) MessageId(io.cdap.cdap.messaging.data.MessageId) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) Constants(io.cdap.cdap.common.conf.Constants) Collections(java.util.Collections) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) ArtifactId(io.cdap.cdap.proto.id.ArtifactId) RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) MessagingService(io.cdap.cdap.messaging.MessagingService) MessagingProgramStatePublisher(io.cdap.cdap.internal.app.program.MessagingProgramStatePublisher) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) Injector(com.google.inject.Injector) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) ProgramStatePublisher(io.cdap.cdap.internal.app.program.ProgramStatePublisher) MessagingProgramStatePublisher(io.cdap.cdap.internal.app.program.MessagingProgramStatePublisher) Test(org.junit.Test)

Example 27 with ProgramDescriptor

use of io.cdap.cdap.app.program.ProgramDescriptor in project cdap by cdapio.

the class SparkRuntimeContextProvider method createProgram.

private static Program createProgram(CConfiguration cConf, SparkRuntimeContextConfig contextConfig) throws IOException {
    File programJar = new File(PROGRAM_JAR_NAME);
    File programDir = new File(PROGRAM_JAR_EXPANDED_NAME);
    ClassLoader parentClassLoader = new FilterClassLoader(SparkRuntimeContextProvider.class.getClassLoader(), SparkResourceFilters.SPARK_PROGRAM_CLASS_LOADER_FILTER);
    ClassLoader classLoader = new ProgramClassLoader(cConf, programDir, parentClassLoader);
    return new DefaultProgram(new ProgramDescriptor(contextConfig.getProgramId(), contextConfig.getApplicationSpecification()), Locations.toLocation(programJar), classLoader);
}
Also used : FilterClassLoader(io.cdap.cdap.common.lang.FilterClassLoader) ProgramClassLoader(io.cdap.cdap.internal.app.runtime.ProgramClassLoader) ProgramClassLoader(io.cdap.cdap.internal.app.runtime.ProgramClassLoader) FilterClassLoader(io.cdap.cdap.common.lang.FilterClassLoader) DefaultProgram(io.cdap.cdap.app.program.DefaultProgram) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) File(java.io.File)

Example 28 with ProgramDescriptor

use of io.cdap.cdap.app.program.ProgramDescriptor in project cdap by cdapio.

the class ProgramNotificationSubscriberService method handleProgramEvent.

private void handleProgramEvent(ProgramRunId programRunId, ProgramRunStatus programRunStatus, Notification notification, byte[] messageIdBytes, AppMetadataStore appMetadataStore, ProgramHeartbeatTable programHeartbeatTable, List<Runnable> runnables) throws Exception {
    LOG.trace("Processing program status notification: {}", notification);
    Map<String, String> properties = notification.getProperties();
    String twillRunId = notification.getProperties().get(ProgramOptionConstants.TWILL_RUN_ID);
    RunRecordDetail recordedRunRecord;
    switch(programRunStatus) {
        case STARTING:
            try {
                RunRecordDetail runRecordDetail = appMetadataStore.getRun(programRunId);
                if (runRecordDetail != null && runRecordDetail.getStatus() != ProgramRunStatus.PENDING && runRecordDetail.getStatus() != ProgramRunStatus.STARTING) {
                    // This is an invalid state transition happening. Valid state transitions are:
                    // PENDING => STARTING : normal state transition
                    // STARTING => STARTING : state transition after app-fabric restart
                    LOG.debug("Ignoring unexpected request to transition program run {} from {} state to program " + "STARTING state.", programRunId, runRecordDetail.getStatus());
                    return;
                }
            } catch (IllegalStateException ex) {
                LOG.error("Request to transition program run {} from non-existent state to program STARTING state " + "but multiple run IDs exist.", programRunId);
            }
            String systemArgumentsString = properties.get(ProgramOptionConstants.SYSTEM_OVERRIDES);
            Map<String, String> systemArguments = systemArgumentsString == null ? Collections.emptyMap() : GSON.fromJson(systemArgumentsString, STRING_STRING_MAP);
            boolean isInWorkflow = systemArguments.containsKey(ProgramOptionConstants.WORKFLOW_NAME);
            boolean skipProvisioning = Boolean.parseBoolean(systemArguments.get(ProgramOptionConstants.SKIP_PROVISIONING));
            ProgramOptions prgOptions = ProgramOptions.fromNotification(notification, GSON);
            ProgramDescriptor prgDescriptor = GSON.fromJson(properties.get(ProgramOptionConstants.PROGRAM_DESCRIPTOR), ProgramDescriptor.class);
            // state changes into Starting.
            if (isInWorkflow || skipProvisioning) {
                appMetadataStore.recordProgramProvisioning(programRunId, prgOptions.getUserArguments().asMap(), prgOptions.getArguments().asMap(), messageIdBytes, prgDescriptor.getArtifactId().toApiArtifactId());
                appMetadataStore.recordProgramProvisioned(programRunId, 0, messageIdBytes);
            } else {
                runnables.add(() -> {
                    String oldUser = SecurityRequestContext.getUserId();
                    try {
                        SecurityRequestContext.setUserId(prgOptions.getArguments().getOption(ProgramOptionConstants.USER_ID));
                        try {
                            programLifecycleService.startInternal(prgDescriptor, prgOptions, programRunId);
                        } catch (Exception e) {
                            LOG.error("Failed to start program {}", programRunId, e);
                            programStateWriter.error(programRunId, e);
                        }
                    } finally {
                        SecurityRequestContext.setUserId(oldUser);
                    }
                });
            }
            recordedRunRecord = appMetadataStore.recordProgramStart(programRunId, twillRunId, systemArguments, messageIdBytes);
            writeToHeartBeatTable(recordedRunRecord, RunIds.getTime(programRunId.getRun(), TimeUnit.SECONDS), programHeartbeatTable);
            break;
        case RUNNING:
            long logicalStartTimeSecs = getTimeSeconds(notification.getProperties(), ProgramOptionConstants.LOGICAL_START_TIME);
            if (logicalStartTimeSecs == -1) {
                LOG.warn("Ignore program running notification for program {} without {} specified, {}", programRunId, ProgramOptionConstants.LOGICAL_START_TIME, notification);
                return;
            }
            recordedRunRecord = appMetadataStore.recordProgramRunning(programRunId, logicalStartTimeSecs, twillRunId, messageIdBytes);
            writeToHeartBeatTable(recordedRunRecord, logicalStartTimeSecs, programHeartbeatTable);
            runRecordMonitorService.removeRequest(programRunId, true);
            long startDelayTime = logicalStartTimeSecs - RunIds.getTime(programRunId.getRun(), TimeUnit.SECONDS);
            emitStartingTimeMetric(programRunId, startDelayTime);
            break;
        case SUSPENDED:
            long suspendTime = getTimeSeconds(notification.getProperties(), ProgramOptionConstants.SUSPEND_TIME);
            // since we are adding suspend time recently, there might be old suspended notifications for which time
            // can be -1.
            recordedRunRecord = appMetadataStore.recordProgramSuspend(programRunId, messageIdBytes, suspendTime);
            writeToHeartBeatTable(recordedRunRecord, suspendTime, programHeartbeatTable);
            break;
        case RESUMING:
            long resumeTime = getTimeSeconds(notification.getProperties(), ProgramOptionConstants.RESUME_TIME);
            // since we are adding suspend time recently, there might be old suspended notifications for which time
            // can be -1.
            recordedRunRecord = appMetadataStore.recordProgramResumed(programRunId, messageIdBytes, resumeTime);
            writeToHeartBeatTable(recordedRunRecord, resumeTime, programHeartbeatTable);
            break;
        case STOPPING:
            Map<String, String> notificationProperties = notification.getProperties();
            long stoppingTsSecs = getTimeSeconds(notificationProperties, ProgramOptionConstants.STOPPING_TIME);
            if (stoppingTsSecs == -1L) {
                LOG.warn("Ignore program stopping notification for program {} without {} specified, {}", programRunId, ProgramOptionConstants.STOPPING_TIME, notification);
                return;
            }
            long terminateTsSecs = getTimeSeconds(notificationProperties, ProgramOptionConstants.TERMINATE_TIME);
            recordedRunRecord = appMetadataStore.recordProgramStopping(programRunId, messageIdBytes, stoppingTsSecs, terminateTsSecs);
            writeToHeartBeatTable(recordedRunRecord, stoppingTsSecs, programHeartbeatTable);
            break;
        case COMPLETED:
        case KILLED:
        case FAILED:
            recordedRunRecord = handleProgramCompletion(appMetadataStore, programHeartbeatTable, programRunId, programRunStatus, notification, messageIdBytes, runnables);
            break;
        case REJECTED:
            ProgramOptions programOptions = ProgramOptions.fromNotification(notification, GSON);
            ProgramDescriptor programDescriptor = GSON.fromJson(properties.get(ProgramOptionConstants.PROGRAM_DESCRIPTOR), ProgramDescriptor.class);
            recordedRunRecord = appMetadataStore.recordProgramRejected(programRunId, programOptions.getUserArguments().asMap(), programOptions.getArguments().asMap(), messageIdBytes, programDescriptor.getArtifactId().toApiArtifactId());
            writeToHeartBeatTable(recordedRunRecord, RunIds.getTime(programRunId.getRun(), TimeUnit.SECONDS), programHeartbeatTable);
            getEmitMetricsRunnable(programRunId, recordedRunRecord, Constants.Metrics.Program.PROGRAM_REJECTED_RUNS, null).ifPresent(runnables::add);
            runRecordMonitorService.removeRequest(programRunId, true);
            break;
        default:
            // This should not happen
            LOG.error("Unsupported program status {} for program {}, {}", programRunStatus, programRunId, notification);
            return;
    }
    if (recordedRunRecord != null) {
        // We need to publish the message so that the trigger subscriber can pick it up and start the trigger if
        // necessary
        publishRecordedStatus(notification, programRunId, recordedRunRecord.getStatus());
        // publish the deprovisioning event(s).
        if (programRunStatus.isEndState() && programRunStatus != ProgramRunStatus.REJECTED) {
            // if this is a preview run or a program within a workflow, we don't actually need to de-provision the cluster.
            // instead, we just record the state as deprovisioned without notifying the provisioner
            // and we will emit the program status metrics for it
            boolean isInWorkflow = recordedRunRecord.getSystemArgs().containsKey(ProgramOptionConstants.WORKFLOW_NAME);
            boolean skipProvisioning = Boolean.parseBoolean(recordedRunRecord.getSystemArgs().get(ProgramOptionConstants.SKIP_PROVISIONING));
            if (isInWorkflow || skipProvisioning) {
                appMetadataStore.recordProgramDeprovisioning(programRunId, messageIdBytes);
                appMetadataStore.recordProgramDeprovisioned(programRunId, null, messageIdBytes);
            } else {
                provisionerNotifier.deprovisioning(programRunId);
            }
        }
    }
}
Also used : RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) TableNotFoundException(io.cdap.cdap.spi.data.TableNotFoundException)

Example 29 with ProgramDescriptor

use of io.cdap.cdap.app.program.ProgramDescriptor in project cdap by cdapio.

the class AbstractProgramRuntimeService method run.

@Override
public final RuntimeInfo run(ProgramDescriptor programDescriptor, ProgramOptions options, RunId runId) {
    ProgramId programId = programDescriptor.getProgramId();
    ProgramRunId programRunId = programId.run(runId);
    ClusterMode clusterMode = ProgramRunners.getClusterMode(options);
    // Creates the ProgramRunner based on the cluster mode
    ProgramRunner runner = (clusterMode == ClusterMode.ON_PREMISE ? programRunnerFactory : Optional.ofNullable(remoteProgramRunnerFactory).orElseThrow(UnsupportedOperationException::new)).create(programId.getType());
    File tempDir = createTempDirectory(programId, runId);
    AtomicReference<Runnable> cleanUpTaskRef = new AtomicReference<>(createCleanupTask(tempDir, runner));
    DelayedProgramController controller = new DelayedProgramController(programRunId);
    RuntimeInfo runtimeInfo = createRuntimeInfo(controller, programId, () -> cleanUpTaskRef.get().run());
    updateRuntimeInfo(runtimeInfo);
    executor.execute(() -> {
        try {
            // Get the artifact details and save it into the program options.
            ArtifactId artifactId = programDescriptor.getArtifactId();
            ArtifactDetail artifactDetail = getArtifactDetail(artifactId);
            ApplicationSpecification appSpec = programDescriptor.getApplicationSpecification();
            ProgramDescriptor newProgramDescriptor = programDescriptor;
            boolean isPreview = Boolean.valueOf(options.getArguments().getOption(ProgramOptionConstants.IS_PREVIEW, "false"));
            // for preview we already have a resolved app spec, so no need to regenerate the app spec again
            if (!isPreview && appSpec != null && ClusterMode.ON_PREMISE.equals(clusterMode)) {
                try {
                    ApplicationSpecification generatedAppSpec = regenerateAppSpec(artifactDetail, programId, artifactId, appSpec, options);
                    appSpec = generatedAppSpec != null ? generatedAppSpec : appSpec;
                    newProgramDescriptor = new ProgramDescriptor(programDescriptor.getProgramId(), appSpec);
                } catch (Exception e) {
                    LOG.warn("Failed to regenerate the app spec for program {}, using the existing app spec", programId);
                }
            }
            ProgramOptions runtimeProgramOptions = updateProgramOptions(artifactId, programId, options, runId, clusterMode, Iterables.getFirst(artifactDetail.getMeta().getClasses().getApps(), null));
            // Take a snapshot of all the plugin artifacts used by the program
            ProgramOptions optionsWithPlugins = createPluginSnapshot(runtimeProgramOptions, programId, tempDir, newProgramDescriptor.getApplicationSpecification());
            // Create and run the program
            Program executableProgram = createProgram(cConf, runner, newProgramDescriptor, artifactDetail, tempDir);
            cleanUpTaskRef.set(createCleanupTask(cleanUpTaskRef.get(), executableProgram));
            controller.setProgramController(runner.run(executableProgram, optionsWithPlugins));
        } catch (Exception e) {
            controller.failed(e);
            programStateWriter.error(programRunId, e);
            LOG.error("Exception while trying to run program", e);
        }
    });
    return runtimeInfo;
}
Also used : ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) Program(io.cdap.cdap.app.program.Program) AppDeploymentRuntimeInfo(io.cdap.cdap.internal.app.deploy.pipeline.AppDeploymentRuntimeInfo) SimpleRuntimeInfo(io.cdap.cdap.internal.app.runtime.service.SimpleRuntimeInfo) ArtifactId(io.cdap.cdap.proto.id.ArtifactId) ClusterMode(io.cdap.cdap.app.guice.ClusterMode) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProgramId(io.cdap.cdap.proto.id.ProgramId) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ExecutionException(java.util.concurrent.ExecutionException) ArtifactNotFoundException(io.cdap.cdap.common.ArtifactNotFoundException) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) File(java.io.File) ArtifactDetail(io.cdap.cdap.internal.app.runtime.artifact.ArtifactDetail)

Example 30 with ProgramDescriptor

use of io.cdap.cdap.app.program.ProgramDescriptor in project cdap by cdapio.

the class CoreSchedulerServiceTest method testProgramEvents.

@Test
@Category(XSlowTests.class)
public void testProgramEvents() throws Exception {
    // Deploy the app
    deploy(AppWithMultipleSchedules.class, 200);
    CConfiguration cConf = getInjector().getInstance(CConfiguration.class);
    TopicId programEventTopic = NamespaceId.SYSTEM.topic(cConf.get(Constants.AppFabric.PROGRAM_STATUS_RECORD_EVENT_TOPIC));
    ProgramStateWriter programStateWriter = new MessagingProgramStateWriter(cConf, messagingService);
    // These notifications should not trigger the program
    ProgramRunId anotherWorkflowRun = ANOTHER_WORKFLOW.run(RunIds.generate());
    ArtifactId artifactId = ANOTHER_WORKFLOW.getNamespaceId().artifact("test", "1.0").toApiArtifactId();
    ApplicationSpecification appSpec = new DefaultApplicationSpecification(AppWithMultipleSchedules.NAME, ApplicationId.DEFAULT_VERSION, ProjectInfo.getVersion().toString(), "desc", null, artifactId, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap());
    ProgramDescriptor programDescriptor = new ProgramDescriptor(anotherWorkflowRun.getParent(), appSpec);
    BasicArguments systemArgs = new BasicArguments(ImmutableMap.of(ProgramOptionConstants.SKIP_PROVISIONING, Boolean.TRUE.toString()));
    ProgramOptions programOptions = new SimpleProgramOptions(anotherWorkflowRun.getParent(), systemArgs, new BasicArguments(), false);
    programStateWriter.start(anotherWorkflowRun, programOptions, null, programDescriptor);
    programStateWriter.running(anotherWorkflowRun, null);
    long lastProcessed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    programStateWriter.error(anotherWorkflowRun, null);
    waitUntilProcessed(programEventTopic, lastProcessed);
    ProgramRunId someWorkflowRun = SOME_WORKFLOW.run(RunIds.generate());
    programDescriptor = new ProgramDescriptor(someWorkflowRun.getParent(), appSpec);
    programStateWriter.start(someWorkflowRun, new SimpleProgramOptions(someWorkflowRun.getParent(), systemArgs, new BasicArguments()), null, programDescriptor);
    programStateWriter.running(someWorkflowRun, null);
    lastProcessed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    programStateWriter.killed(someWorkflowRun);
    waitUntilProcessed(programEventTopic, lastProcessed);
    Assert.assertEquals(0, getRuns(TRIGGERED_WORKFLOW, ProgramRunStatus.ALL));
    // Enable the schedule
    scheduler.enableSchedule(APP_MULT_ID.schedule(AppWithMultipleSchedules.WORKFLOW_COMPLETED_SCHEDULE));
    // Start a program with user arguments
    startProgram(ANOTHER_WORKFLOW, ImmutableMap.of(AppWithMultipleSchedules.ANOTHER_RUNTIME_ARG_KEY, AppWithMultipleSchedules.ANOTHER_RUNTIME_ARG_VALUE), 200);
    // Wait for a completed run record
    waitForCompleteRuns(1, TRIGGERED_WORKFLOW);
    assertProgramRuns(TRIGGERED_WORKFLOW, ProgramRunStatus.COMPLETED, 1);
    RunRecord run = getProgramRuns(TRIGGERED_WORKFLOW, ProgramRunStatus.COMPLETED).get(0);
    Map<String, List<WorkflowTokenDetail.NodeValueDetail>> tokenData = getWorkflowToken(TRIGGERED_WORKFLOW, run.getPid(), null, null).getTokenData();
    // There should be 2 entries in tokenData
    Assert.assertEquals(2, tokenData.size());
    // The value of TRIGGERED_RUNTIME_ARG_KEY should be ANOTHER_RUNTIME_ARG_VALUE from the triggering workflow
    Assert.assertEquals(AppWithMultipleSchedules.ANOTHER_RUNTIME_ARG_VALUE, tokenData.get(AppWithMultipleSchedules.TRIGGERED_RUNTIME_ARG_KEY).get(0).getValue());
    // The value of TRIGGERED_TOKEN_KEY should be ANOTHER_TOKEN_VALUE from the triggering workflow
    Assert.assertEquals(AppWithMultipleSchedules.ANOTHER_TOKEN_VALUE, tokenData.get(AppWithMultipleSchedules.TRIGGERED_TOKEN_KEY).get(0).getValue());
}
Also used : ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) RunRecord(io.cdap.cdap.proto.RunRecord) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) TopicId(io.cdap.cdap.proto.id.TopicId) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) WorkflowTokenDetail(io.cdap.cdap.proto.WorkflowTokenDetail) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Aggregations

ProgramDescriptor (io.cdap.cdap.app.program.ProgramDescriptor)66 BasicArguments (io.cdap.cdap.internal.app.runtime.BasicArguments)34 SimpleProgramOptions (io.cdap.cdap.internal.app.runtime.SimpleProgramOptions)34 Test (org.junit.Test)32 ApplicationSpecification (io.cdap.cdap.api.app.ApplicationSpecification)30 ProgramId (io.cdap.cdap.proto.id.ProgramId)30 ProgramOptions (io.cdap.cdap.app.runtime.ProgramOptions)26 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)26 File (java.io.File)24 HashMap (java.util.HashMap)20 ArtifactId (io.cdap.cdap.api.artifact.ArtifactId)18 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)18 IOException (java.io.IOException)18 Injector (com.google.inject.Injector)14 SystemArguments (io.cdap.cdap.internal.app.runtime.SystemArguments)14 ProgramType (io.cdap.cdap.proto.ProgramType)14 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)14 Collections (java.util.Collections)14 Location (org.apache.twill.filesystem.Location)14 Program (io.cdap.cdap.app.program.Program)12