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);
}
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);
}
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);
}
}
}
}
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;
}
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());
}
Aggregations