Search in sources :

Example 11 with ProgramOptions

use of io.cdap.cdap.app.runtime.ProgramOptions in project cdap by caskdata.

the class ProgramNotificationSubscriberService method doStartUp.

@Override
protected void doStartUp() throws Exception {
    super.doStartUp();
    int batchSize = cConf.getInt(Constants.RuntimeMonitor.INIT_BATCH_SIZE);
    RetryStrategy retryStrategy = RetryStrategies.fromConfiguration(cConf, Constants.Service.RUNTIME_MONITOR_RETRY_PREFIX);
    long startTs = System.currentTimeMillis();
    Retries.runWithRetries(() -> store.scanActiveRuns(batchSize, (runRecordDetail) -> {
        if (runRecordDetail.getStartTs() > startTs) {
            return;
        }
        try {
            if (runRecordDetail.getStatus() == ProgramRunStatus.PENDING) {
                runRecordMonitorService.addRequest(runRecordDetail.getProgramRunId());
            } else if (runRecordDetail.getStatus() == ProgramRunStatus.STARTING) {
                runRecordMonitorService.addRequest(runRecordDetail.getProgramRunId());
                // It is unknown what is the state of program runs in STARTING state.
                // A STARTING message is published again to retry STARTING logic.
                ProgramOptions programOptions = new SimpleProgramOptions(runRecordDetail.getProgramRunId().getParent(), new BasicArguments(runRecordDetail.getSystemArgs()), new BasicArguments(runRecordDetail.getUserArgs()));
                LOG.debug("Retrying to start run {}.", runRecordDetail.getProgramRunId());
                programStateWriter.start(runRecordDetail.getProgramRunId(), programOptions, null, this.store.loadProgram(runRecordDetail.getProgramRunId().getParent()));
            }
        } catch (Exception e) {
            ProgramRunId programRunId = runRecordDetail.getProgramRunId();
            LOG.warn("Retrying to start run {} failed. Marking it as failed.", programRunId, e);
            programStateWriter.error(programRunId, e);
        }
    }), retryStrategy, e -> true);
}
Also used : RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) ProvisionRequest(io.cdap.cdap.internal.provision.ProvisionRequest) ProvisionerNotifier(io.cdap.cdap.internal.provision.ProvisionerNotifier) TypeToken(com.google.gson.reflect.TypeToken) ImmutablePair(io.cdap.cdap.common.utils.ImmutablePair) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Notification(io.cdap.cdap.proto.Notification) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) RetryStrategies(io.cdap.cdap.common.service.RetryStrategies) GsonBuilder(com.google.gson.GsonBuilder) WorkflowNode(io.cdap.cdap.api.workflow.WorkflowNode) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) Gson(com.google.gson.Gson) Map(java.util.Map) BasicThrowable(io.cdap.cdap.proto.BasicThrowable) ImmutableMap(com.google.common.collect.ImmutableMap) MessagingService(io.cdap.cdap.messaging.MessagingService) Set(java.util.Set) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) StructuredTableContext(io.cdap.cdap.spi.data.StructuredTableContext) SchedulableProgramType(io.cdap.cdap.api.schedule.SchedulableProgramType) StandardCharsets(java.nio.charset.StandardCharsets) ApplicationSpecificationAdapter(io.cdap.cdap.internal.app.ApplicationSpecificationAdapter) ScheduleProgramInfo(io.cdap.cdap.api.workflow.ScheduleProgramInfo) MetricsContext(io.cdap.cdap.api.metrics.MetricsContext) List(java.util.List) SecurityRequestContext(io.cdap.cdap.security.spi.authentication.SecurityRequestContext) Type(java.lang.reflect.Type) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) Optional(java.util.Optional) Constants(io.cdap.cdap.common.conf.Constants) ProfileId(io.cdap.cdap.proto.id.ProfileId) Queue(java.util.Queue) ProgramOptionConstants(io.cdap.cdap.internal.app.runtime.ProgramOptionConstants) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) RunRecordDetailWithExistingStatus(io.cdap.cdap.internal.app.store.RunRecordDetailWithExistingStatus) ProgramRunners(io.cdap.cdap.internal.app.runtime.ProgramRunners) Retries(io.cdap.cdap.common.service.Retries) RetryStrategy(io.cdap.cdap.common.service.RetryStrategy) Cluster(io.cdap.cdap.runtime.spi.provisioner.Cluster) WorkflowSpecification(io.cdap.cdap.api.workflow.WorkflowSpecification) HashMap(java.util.HashMap) ProgramType(io.cdap.cdap.proto.ProgramType) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ProvisioningService(io.cdap.cdap.internal.provision.ProvisioningService) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ProgramHeartbeatTable(io.cdap.cdap.reporting.ProgramHeartbeatTable) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) SystemArguments(io.cdap.cdap.internal.app.runtime.SystemArguments) WorkflowActionNode(io.cdap.cdap.api.workflow.WorkflowActionNode) LinkedList(java.util.LinkedList) Nullable(javax.annotation.Nullable) AppMetadataStore(io.cdap.cdap.internal.app.store.AppMetadataStore) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) JsonSyntaxException(com.google.gson.JsonSyntaxException) RunIds(io.cdap.cdap.common.app.RunIds) ProgramId(io.cdap.cdap.proto.id.ProgramId) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) IOException(java.io.IOException) ProjectInfo(io.cdap.cdap.common.utils.ProjectInfo) ProgramRunClusterStatus(io.cdap.cdap.proto.ProgramRunClusterStatus) TableNotFoundException(io.cdap.cdap.spi.data.TableNotFoundException) MetricsCollectionService(io.cdap.cdap.api.metrics.MetricsCollectionService) Store(io.cdap.cdap.app.store.Store) TimeUnit(java.util.concurrent.TimeUnit) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) Collections(java.util.Collections) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) RetryStrategy(io.cdap.cdap.common.service.RetryStrategy) 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 12 with ProgramOptions

use of io.cdap.cdap.app.runtime.ProgramOptions in project cdap by caskdata.

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, recordedRunRecord);
            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 13 with ProgramOptions

use of io.cdap.cdap.app.runtime.ProgramOptions in project cdap by caskdata.

the class ProgramNotificationSubscriberServiceTest method testHeartBeatStoreForProgramStatusMessages.

@Test
public void testHeartBeatStoreForProgramStatusMessages() throws Exception {
    ProgramId programId = NamespaceId.DEFAULT.app("someapp", "1.0-SNAPSHOT").program(ProgramType.SERVICE, "s");
    Map<String, String> systemArguments = new HashMap<>();
    systemArguments.put(ProgramOptionConstants.SKIP_PROVISIONING, Boolean.TRUE.toString());
    systemArguments.put(SystemArguments.PROFILE_NAME, ProfileId.NATIVE.getScopedName());
    ProgramOptions programOptions = new SimpleProgramOptions(programId, new BasicArguments(systemArguments), new BasicArguments());
    ProgramRunId runId = programId.run(RunIds.generate());
    ArtifactId artifactId = NamespaceId.DEFAULT.artifact("testArtifact", "1.0").toApiArtifactId();
    ApplicationSpecification appSpec = new DefaultApplicationSpecification("name", "1.0.0", 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(programId, appSpec);
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.start(runId, programOptions, null, programDescriptor);
    });
    checkProgramStatus(artifactId, runId, ProgramRunStatus.STARTING);
    long startTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.running(runId, null);
    });
    // perform scan on heart beat store - ensure latest message notification is running
    checkProgramStatus(artifactId, runId, ProgramRunStatus.RUNNING);
    heartbeatDatasetStatusCheck(startTime, ProgramRunStatus.RUNNING);
    long suspendTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.suspend(runId);
    });
    // perform scan on heart beat store - ensure latest message notification is suspended
    checkProgramStatus(artifactId, runId, ProgramRunStatus.SUSPENDED);
    heartbeatDatasetStatusCheck(suspendTime, ProgramRunStatus.SUSPENDED);
    long resumeTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.resume(runId);
    });
    // app metadata records as RUNNING
    checkProgramStatus(artifactId, runId, ProgramRunStatus.RUNNING);
    // heart beat messages wont have been sent due to high interval. resuming program will be recorded as running
    // in run record by app meta
    heartbeatDatasetStatusCheck(resumeTime, ProgramRunStatus.RUNNING);
    // killed status check after error
    long stopTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.error(runId, new Throwable("Testing"));
    });
    checkProgramStatus(artifactId, runId, ProgramRunStatus.FAILED);
    heartbeatDatasetStatusCheck(stopTime, ProgramRunStatus.FAILED);
    ProgramRunId runId2 = programId.run(RunIds.generate());
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.start(runId2, programOptions, null, programDescriptor);
    });
    checkProgramStatus(artifactId, runId2, ProgramRunStatus.STARTING);
    startTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.running(runId2, null);
    });
    // perform scan on heart beat store - ensure latest message notification is running
    checkProgramStatus(artifactId, runId2, ProgramRunStatus.RUNNING);
    heartbeatDatasetStatusCheck(startTime, ProgramRunStatus.RUNNING);
    // completed status check
    stopTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.completed(runId2);
    });
    checkProgramStatus(artifactId, runId2, ProgramRunStatus.COMPLETED);
    heartbeatDatasetStatusCheck(stopTime, ProgramRunStatus.COMPLETED);
    ProgramRunId runId3 = programId.run(RunIds.generate());
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.start(runId3, programOptions, null, programDescriptor);
    });
    checkProgramStatus(artifactId, runId3, ProgramRunStatus.STARTING);
    startTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.running(runId3, null);
    });
    // perform scan on heart beat store - ensure latest message notification is running
    checkProgramStatus(artifactId, runId3, ProgramRunStatus.RUNNING);
    heartbeatDatasetStatusCheck(startTime, ProgramRunStatus.RUNNING);
    // completed status check
    stopTime = System.currentTimeMillis();
    TransactionRunners.run(transactionRunner, context -> {
        programStateWriter.stop(runId3, 10);
    });
    checkProgramStatus(artifactId, runId3, ProgramRunStatus.STOPPING);
    heartbeatDatasetStatusCheck(stopTime, ProgramRunStatus.KILLED);
}
Also used : ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) HashMap(java.util.HashMap) ProgramId(io.cdap.cdap.proto.id.ProgramId) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) Test(org.junit.Test)

Example 14 with ProgramOptions

use of io.cdap.cdap.app.runtime.ProgramOptions in project cdap by caskdata.

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)

Example 15 with ProgramOptions

use of io.cdap.cdap.app.runtime.ProgramOptions in project cdap by caskdata.

the class ProvisioningServiceTest method createTaskInfo.

private TaskFields createTaskInfo(ProvisionerInfo provisionerInfo) {
    ProgramRunId programRunId = NamespaceId.DEFAULT.app("app").workflow("wf").run(RunIds.generate());
    Map<String, String> systemArgs = new HashMap<>();
    Map<String, String> userArgs = new HashMap<>();
    Profile profile = new Profile(ProfileId.NATIVE.getProfile(), "label", "desc", provisionerInfo);
    SystemArguments.addProfileArgs(systemArgs, profile);
    systemArgs.put(Constants.APP_CDAP_VERSION, APP_CDAP_VERSION);
    ProgramOptions programOptions = new SimpleProgramOptions(programRunId.getParent(), new BasicArguments(systemArgs), new BasicArguments(userArgs));
    ArtifactId artifactId = NamespaceId.DEFAULT.artifact("testArtifact", "1.0").toApiArtifactId();
    ApplicationSpecification appSpec = new DefaultApplicationSpecification("name", "1.0.0", APP_CDAP_VERSION, "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(programRunId.getParent(), appSpec);
    return new TaskFields(programDescriptor, programOptions, programRunId);
}
Also used : ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) HashMap(java.util.HashMap) Profile(io.cdap.cdap.proto.profile.Profile) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) ProgramOptions(io.cdap.cdap.app.runtime.ProgramOptions) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) DefaultApplicationSpecification(io.cdap.cdap.internal.app.DefaultApplicationSpecification) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor)

Aggregations

ProgramOptions (io.cdap.cdap.app.runtime.ProgramOptions)68 SimpleProgramOptions (io.cdap.cdap.internal.app.runtime.SimpleProgramOptions)52 BasicArguments (io.cdap.cdap.internal.app.runtime.BasicArguments)40 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)40 ProgramDescriptor (io.cdap.cdap.app.program.ProgramDescriptor)32 HashMap (java.util.HashMap)26 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)24 IOException (java.io.IOException)24 ProgramId (io.cdap.cdap.proto.id.ProgramId)22 ApplicationSpecification (io.cdap.cdap.api.app.ApplicationSpecification)20 Test (org.junit.Test)14 ArtifactId (io.cdap.cdap.api.artifact.ArtifactId)12 Program (io.cdap.cdap.app.program.Program)12 ProgramStateWriter (io.cdap.cdap.app.runtime.ProgramStateWriter)12 SystemArguments (io.cdap.cdap.internal.app.runtime.SystemArguments)12 Map (java.util.Map)12 Injector (com.google.inject.Injector)10 MetricsCollectionService (io.cdap.cdap.api.metrics.MetricsCollectionService)10 ClusterMode (io.cdap.cdap.app.guice.ClusterMode)10 MessagingService (io.cdap.cdap.messaging.MessagingService)10