Java Code Examples for org.springframework.statemachine.StateContext

The following examples show how to use org.springframework.statemachine.StateContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	super.executeInternal(context);
	ReleaseAnalysisReport releaseAnalysisReport = getReleaseAnalysisReport(context);

	int upgradeStatus = 0;
	// TODO: should check both releases
	String kind = ManifestUtils.resolveKind(releaseAnalysisReport.getReplacingRelease().getManifest().getData());
	UpgradeStrategy upgradeStrategy = this.upgradeStrategyFactory.getUpgradeStrategy(kind);
	boolean ok = upgradeStrategy.checkStatus(releaseAnalysisReport.getReplacingRelease());
	log.debug("upgradeStrategy checkStatus {}", ok);
	if (ok) {
		upgradeStatus = 1;
	}
	else if (!ok && cutOffTimeExceed(context)) {
		upgradeStatus = -1;
	}
	log.debug("Setting upgradeStatus {}", upgradeStatus);
	context.getExtendedState().getVariables().put(SkipperVariables.UPGRADE_STATUS, upgradeStatus);
}
 
Example 2
Source Project: cloudbreak   Source File: AbstractStackDownscaleAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected StackScalingFlowContext createFlowContext(FlowParameters flowParameters, StateContext<StackDownscaleState, StackDownscaleEvent> stateContext,
        P payload) {
    Map<Object, Object> variables = stateContext.getExtendedState().getVariables();
    Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId());
    stack.setResources(new HashSet<>(resourceService.getAllByStackId(payload.getResourceId())));
    MDCBuilder.buildMdcContext(stack);
    Location location = location(region(stack.getRegion()), availabilityZone(stack.getAvailabilityZone()));
    CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.cloudPlatform(), stack.getPlatformVariant(),
            location, stack.getCreator().getUserId(), stack.getWorkspace().getId());
    CloudCredential cloudCredential = stackUtil.getCloudCredential(stack);
    String instanceGroupName = extractInstanceGroupName(payload, variables);
    Set<String> instanceIds = extractInstanceIds(payload, variables, stack);
    Integer adjustment = extractAdjustment(payload, variables);
    CloudStack cloudStack = cloudStackConverter.convertForDownscale(stack, instanceIds);
    return new StackScalingFlowContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack, instanceGroupName, instanceIds, adjustment);
}
 
Example 3
@Override
protected RedbeamsContext createFlowContext(FlowParameters flowParameters,
                                            StateContext<RedbeamsTerminationState, RedbeamsTerminationEvent> stateContext, P payload) {
    Optional<DBStack> optionalDBStack = dbStackService.findById(payload.getResourceId());

    CloudContext cloudContext = null;
    CloudCredential cloudCredential = null;
    DatabaseStack databaseStack = null;
    DBStack dbStack = null;

    if (optionalDBStack.isPresent()) {
        dbStack = optionalDBStack.get();
        MDCBuilder.buildMdcContext(dbStack);
        Location location = location(region(dbStack.getRegion()), availabilityZone(dbStack.getAvailabilityZone()));
        String userName = dbStack.getOwnerCrn().getUserId();
        String accountId = dbStack.getOwnerCrn().getAccountId();
        cloudContext = new CloudContext(dbStack.getId(), dbStack.getName(), dbStack.getCloudPlatform(), dbStack.getPlatformVariant(),
                location, userName, accountId);
        Credential credential = credentialService.getCredentialByEnvCrn(dbStack.getEnvironmentId());
        cloudCredential = credentialConverter.convert(credential);
        databaseStack = databaseStackConverter.convert(dbStack);
    }
    return new RedbeamsContext(flowParameters, cloudContext, cloudCredential, databaseStack, dbStack);
}
 
Example 4
Source Project: cloudbreak   Source File: AbstractRedbeamsStopAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RedbeamsStopContext createFlowContext(FlowParameters flowParameters,
        StateContext<RedbeamsStopState, RedbeamsStopEvent> stateContext, P payload) {
    DBStack dbStack = dbStackService.getById(payload.getResourceId());
    MDCBuilder.buildMdcContext(dbStack);
    Location location = location(region(dbStack.getRegion()), availabilityZone(dbStack.getAvailabilityZone()));
    String userName = dbStack.getOwnerCrn().getUserId();
    String accountId = dbStack.getOwnerCrn().getAccountId();
    CloudContext cloudContext = new CloudContext(dbStack.getId(), dbStack.getName(), dbStack.getCloudPlatform(), dbStack.getPlatformVariant(),
            location, userName, accountId);
    Credential credential = credentialService.getCredentialByEnvCrn(dbStack.getEnvironmentId());
    CloudCredential cloudCredential = credentialConverter.convert(credential);
    DatabaseStack databaseStack = databaseStackConverter.convert(dbStack);

    return new RedbeamsStopContext(flowParameters, cloudContext, cloudCredential, databaseStack);
}
 
Example 5
Source Project: cloudbreak   Source File: AbstractRedbeamsStartAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RedbeamsStartContext createFlowContext(FlowParameters flowParameters,
        StateContext<RedbeamsStartState, RedbeamsStartEvent> stateContext, P payload) {
    DBStack dbStack = dbStackService.getById(payload.getResourceId());
    MDCBuilder.buildMdcContext(dbStack);
    Location location = location(region(dbStack.getRegion()), availabilityZone(dbStack.getAvailabilityZone()));
    String userName = dbStack.getOwnerCrn().getUserId();
    String accountId = dbStack.getOwnerCrn().getAccountId();
    CloudContext cloudContext = new CloudContext(dbStack.getId(), dbStack.getName(), dbStack.getCloudPlatform(), dbStack.getPlatformVariant(),
            location, userName, accountId);
    Credential credential = credentialService.getCredentialByEnvCrn(dbStack.getEnvironmentId());
    CloudCredential cloudCredential = credentialConverter.convert(credential);
    DatabaseStack databaseStack = databaseStackConverter.convert(dbStack);

    return new RedbeamsStartContext(flowParameters, cloudContext, cloudCredential, databaseStack);
}
 
Example 6
Source Project: cloudbreak   Source File: AbstractAction.java    License: Apache License 2.0 6 votes vote down vote up
private void executeAction(StateContext<S, E> context, P payload, C flowContext, Map<Object, Object> variables, String flowStateName) throws Exception {
    Object flowStartTime = variables.get(FLOW_START_TIME);
    if (flowStartTime != null) {
        Object execTime = variables.get(FLOW_START_EXEC_TIME);
        long flowElapsed = (System.currentTimeMillis() - (long) flowStartTime) / MS_PER_SEC;
        long execElapsed = (System.currentTimeMillis() - (long) execTime) / MS_PER_SEC;
        long executionTime = Math.max(execElapsed, flowElapsed);
        LOGGER.debug("Stack: {}, flow state: {}, phase: {}, execution time {} sec", payload.getResourceId(),
                flowStateName, execElapsed > flowElapsed ? "doExec" : "service", executionTime);
        metricService.submit(FlowMetricType.FLOW_STEP, executionTime, Map.of("name", flowStateName.toLowerCase()));
    }
    variables.put(FLOW_STATE_NAME, context.getStateMachine().getState().getId());
    variables.put(FLOW_START_EXEC_TIME, System.currentTimeMillis());
    doExecute(flowContext, payload, variables);
    variables.put(FLOW_START_TIME, System.currentTimeMillis());
}
 
Example 7
@Override
protected InstanceTerminationContext createFlowContext(FlowParameters flowParameters,
        StateContext<InstanceTerminationState, InstanceTerminationEvent> stateContext, P payload) {
    Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId());
    stack.setResources(new HashSet<>(resourceService.getAllByStackId(payload.getResourceId())));
    MDCBuilder.buildMdcContext(stack);
    Location location = location(region(stack.getRegion()), availabilityZone(stack.getAvailabilityZone()));
    CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.cloudPlatform(), stack.getPlatformVariant(),
            location, stack.getCreator().getUserId(), stack.getWorkspace().getId());
    CloudCredential cloudCredential = stackUtil.getCloudCredential(stack);
    Set<String> instanceIds = payload.getInstanceIds();
    CloudStack cloudStack = cloudStackConverter.convert(stack, instanceIds);
    List<CloudResource> cloudResources = cloudResourceConverter.convert(stack.getResources());
    List<InstanceMetaData> instanceMetaDataList = new ArrayList<>();
    List<CloudInstance> cloudInstances = new ArrayList<>();
    for (String instanceId : instanceIds) {
        InstanceMetaData instanceMetaData = instanceMetaDataService.findByStackIdAndInstanceId(stack.getId(), instanceId)
                .orElseThrow(NotFoundException.notFound("instanceMetadata", instanceId));
        CloudInstance cloudInstance = metadataConverter.convert(instanceMetaData);
        instanceMetaDataList.add(instanceMetaData);
        cloudInstances.add(cloudInstance);
    }
    return new InstanceTerminationContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack, cloudResources, cloudInstances,
            instanceMetaDataList);
}
 
Example 8
Source Project: agile-service-old   Source File: InstanceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Boolean validatorGuard(Long organizationId, String serviceCode, Long transformId, InputDTO inputDTO, StateContext<String, String> context) {
    StateMachineTransformDTO transform = transformMapper.queryById(organizationId, transformId);
    List<StateMachineConfigVO> conditionConfigs = condition(organizationId, transformId);
    List<StateMachineConfigVO> validatorConfigs = validator(organizationId, transformId);
    ExecuteResult executeResult = new ExecuteResult(true, null, null);
    //调用对应服务,执行条件和验证,返回是否成功
    try {
        if (!conditionConfigs.isEmpty()) {
            inputDTO.setConfigs(modelMapper.map(conditionConfigs, new TypeToken<List<StateMachineConfigVO>>() {
            }.getType()));
            executeResult = stateMachineClientService.configExecuteCondition(null, transform.getConditionStrategy(), modelMapper.map(inputDTO, InputDTO.class));
        }
        if (executeResult.getSuccess() && !validatorConfigs.isEmpty()) {
            inputDTO.setConfigs(modelMapper.map(validatorConfigs, new TypeToken<List<StateMachineConfigVO>>() {
            }.getType()));
            executeResult = stateMachineClientService.configExecuteValidator(null, modelMapper.map(inputDTO, InputDTO.class));
        }
    } catch (Exception e) {
        LOGGER.error(EXCEPTION, e);
        executeResult = new ExecuteResult(false, null, "验证调用失败");
    }

    Map<Object, Object> variables = context.getExtendedState().getVariables();
    variables.put("executeResult", executeResult);
    return executeResult.getSuccess();
}
 
Example 9
Source Project: agile-service-old   Source File: InstanceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Boolean postAction(Long organizationId, String serviceCode, Long transformId, InputDTO inputDTO, StateContext<String, String> context) {
    List<StateMachineConfigVO> configs = action(organizationId, transformId);
    inputDTO.setConfigs(modelMapper.map(configs, new TypeToken<List<StateMachineConfigVO>>() {
    }.getType()));
    StateMachineTransformDTO transform = transformMapper.queryById(organizationId, transformId);
    //节点转状态
    Long targetStatusId = nodeDeployMapper.getNodeDeployById(Long.parseLong(context.getTarget().getId())).getStatusId();
    if (targetStatusId == null) {
        throw new CommonException("error.postAction.targetStatusId.notNull");
    }
    ExecuteResult executeResult;
    //调用对应服务,执行动作,返回是否成功
    try {
        executeResult = stateMachineClientService.configExecutePostAction(targetStatusId, transform.getType(), modelMapper.map(inputDTO, InputDTO.class));
        //返回为空则调用对应服务,对应服务方法报错
        if (executeResult == null) {
            executeResult = new ExecuteResult(false, null, "后置动作调用失败");
        }
    } catch (Exception e) {
        LOGGER.error(EXCEPTION, e);
        executeResult = new ExecuteResult(false, null, "后置动作调用失败");
    }
    Map<Object, Object> variables = context.getExtendedState().getVariables();
    variables.put("executeResult", executeResult);
    return executeResult.getSuccess();
}
 
Example 10
@Bean
public Guard<States, Events> s2Guard() {
    return new Guard<States, Events>() {
        @Override
        public boolean evaluate(StateContext<States, Events> context) {
            return false;
        }
    };
}
 
Example 11
@Bean
public Guard<States, Events> s3Guard() {
    return new Guard<States, Events>() {
        @Override
        public boolean evaluate(StateContext<States, Events> context) {
            return true;
        }
    };
}
 
Example 12
Source Project: cloudbreak   Source File: StackStopActions.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected StackStartStopContext createFlowContext(FlowParameters flowParameters, StateContext<StackStopState, StackStopEvent> stateContext,
        P payload) {
    Long stackId = payload.getResourceId();
    Stack stack = stackService.getByIdWithListsInTransaction(stackId);
    stack.setResources(new HashSet<>(resourceService.getAllByStackId(payload.getResourceId())));
    MDCBuilder.buildMdcContext(stack);
    List<InstanceMetaData> instances = new ArrayList<>(instanceMetaDataService.findNotTerminatedForStack(stackId));
    Location location = location(region(stack.getRegion()), availabilityZone(stack.getAvailabilityZone()));
    CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.cloudPlatform(), stack.getPlatformVariant(),
            location, stack.getCreator().getUserId(), stack.getWorkspace().getId());
    CloudCredential cloudCredential = stackUtil.getCloudCredential(stack);
    return new StackStartStopContext(flowParameters, stack, instances, cloudContext, cloudCredential);
}
 
Example 13
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	UpgradeRequest upgradeRequest = context.getExtendedState().get(SkipperEventHeaders.UPGRADE_REQUEST,
			UpgradeRequest.class);
	RollbackRequest rollbackRequest = context.getExtendedState().get(SkipperEventHeaders.ROLLBACK_REQUEST,
			RollbackRequest.class);
	Assert.notNull(upgradeRequest, "'upgradeRequest' not known to the system in extended state");
	ReleaseAnalysisReport releaseAnalysisReport = this.getReleaseReportService().createReport(upgradeRequest,
			rollbackRequest, handlesInitialReport());
	context.getExtendedState().getVariables().put(SkipperVariables.RELEASE_ANALYSIS_REPORT, releaseAnalysisReport);
}
 
Example 14
protected ReleaseAnalysisReport getReleaseAnalysisReport(
		StateContext<SkipperStates, SkipperEvents> context) {
	ReleaseAnalysisReport releaseAnalysisReport = context.getExtendedState()
			.get(SkipperVariables.RELEASE_ANALYSIS_REPORT, ReleaseAnalysisReport.class);
	Assert.notNull(releaseAnalysisReport, "'releaseAnalysisReport' not known to the system in extended state");
	return releaseAnalysisReport;
}
 
Example 15
Source Project: spring-cloud-skipper   Source File: UpgradeStartAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	super.executeInternal(context);
	log.debug("Starting to execute action");
	// get from event headers and fall back checking if it's in context
	// in case machine died and we restored
}
 
Example 16
@Override
public boolean evaluate(StateContext<SkipperStates, SkipperEvents> context) {
	Integer status = context.getExtendedState().get(SkipperVariables.UPGRADE_STATUS, Integer.class);
	log.debug("Checking condition {} with upgradeStatus {}", status, upgradeStatus);
	if (status == null || status == 0) {
		return false;
	}
	else if (upgradeStatus && status > 0) {
		return true;
	}
	else if (!upgradeStatus && status < 0) {
		return true;
	}
	return false;
}
 
Example 17
Source Project: spring-cloud-skipper   Source File: DeleteDeleteAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	log.debug("Starting action " + context);
	String releaseName = context.getMessageHeaders().get(SkipperEventHeaders.RELEASE_NAME, String.class);
	log.info("About to delete {}", releaseName);
	DeleteProperties deleteProperties = context.getExtendedState()
			.get(SkipperEventHeaders.RELEASE_DELETE_PROPERTIES, DeleteProperties.class);
	Assert.notNull(deleteProperties, "'deleteProperties' not known to the system in extended state");
	Release release = this.releaseService.delete(releaseName, deleteProperties.isDeletePackage());
	context.getExtendedState().getVariables().put(SkipperVariables.RELEASE, release);
}
 
Example 18
private boolean cutOffTimeExceed(StateContext<SkipperStates, SkipperEvents> context) {
	long now = System.currentTimeMillis();
	Long cutOffTime = context.getExtendedState().get(SkipperVariables.UPGRADE_CUTOFF_TIME, Long.class);
	if (cutOffTime == null) {
		// missing cutoff, indicate exceed
		return true;
	}
	log.debug("Testing cutOffTime {} to now {}", cutOffTime, now);
	return now > cutOffTime;
}
 
Example 19
Source Project: spring-cloud-skipper   Source File: AbstractAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final void execute(StateContext<SkipperStates, SkipperEvents> context) {
	try {
		executeInternal(context);
	}
	catch (Exception e) {
		// any error here will lead to adding exception into
		// extended state, thus allowing machine to break up
		// from executing state.
		log.error("Action execution failed class=[" + getClass() + "]", e);
		context.getExtendedState().getVariables().put(SkipperStateMachineService.SkipperVariables.ERROR, e);
	}
}
 
Example 20
Source Project: cloudbreak   Source File: ClusterUpscaleActions.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ClusterUpscaleContext createFlowContext(FlowParameters flowParameters, StateContext<ClusterUpscaleState,
        ClusterUpscaleEvent> stateContext, P payload) {
    Map<Object, Object> variables = stateContext.getExtendedState().getVariables();
    StackView stack = stackService.getViewByIdWithoutAuth(payload.getResourceId());
    MDCBuilder.buildMdcContext(stack.getClusterView());
    return new ClusterUpscaleContext(flowParameters, stack, getHostgroupName(variables), getAdjustment(variables),
            isSinglePrimaryGateway(variables), getPrimaryGatewayHostName(variables), getClusterManagerType(variables));
}
 
Example 21
Source Project: spring-cloud-skipper   Source File: ScaleScaleAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	log.debug("Starting action " + context);
	String releaseName = context.getMessageHeaders().get(SkipperEventHeaders.RELEASE_NAME, String.class);
	ScaleRequest scaleRequest = context.getExtendedState().get(SkipperEventHeaders.SCALE_REQUEST,
			ScaleRequest.class);
	log.info("About to scale {} with the {} ", releaseName, scaleRequest);
	Assert.notNull(scaleRequest, "'scaleRequest' not known to the system in extended state");
	Release release = this.releaseService.scale(releaseName, scaleRequest);
	context.getExtendedState().getVariables().put(SkipperVariables.RELEASE, release);
}
 
Example 22
Source Project: spring-cloud-skipper   Source File: UpgradeCancelAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	super.executeInternal(context);

	Long upgradeTimeout = context.getExtendedState().get(SkipperEventHeaders.UPGRADE_TIMEOUT, Long.class);
	Long cutOffTime = context.getExtendedState().get(SkipperVariables.UPGRADE_CUTOFF_TIME, Long.class);
	SkipperEvents event = context.getEvent();
	if (event == SkipperEvents.UPGRADE_CANCEL && cutOffTime != null) {
		// looks like we're manually cancelling, as we have UPGRADE_CANCEL in context,
		// calculate new timeout for reporting so that we can give number
		// how long user waited before cancelling.
		upgradeTimeout = System.currentTimeMillis() - (cutOffTime - upgradeTimeout);
	}
	else {
		// else assume timeout upgrade is using
		upgradeTimeout = context.getExtendedState().get(SkipperEventHeaders.UPGRADE_TIMEOUT, Long.class);
	}

	ReleaseAnalysisReport releaseAnalysisReport = getReleaseAnalysisReport(context);

	// check if we're doing rollback and pass flag to strategy
	RollbackRequest rollbackRequest = context.getExtendedState().get(SkipperEventHeaders.ROLLBACK_REQUEST,
			RollbackRequest.class);
	// TODO: should check both releases
	String kind = ManifestUtils.resolveKind(releaseAnalysisReport.getExistingRelease().getManifest().getData());
	UpgradeStrategy upgradeStrategy = this.upgradeStrategyFactory.getUpgradeStrategy(kind);
	upgradeStrategy.cancel(releaseAnalysisReport.getExistingRelease(), releaseAnalysisReport.getReplacingRelease(),
			releaseAnalysisReport, upgradeTimeout, event == SkipperEvents.UPGRADE_CANCEL, rollbackRequest != null);
}
 
Example 23
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	super.executeInternal(context);
	ReleaseAnalysisReport releaseAnalysisReport = getReleaseAnalysisReport(context);

	// TODO: should check both releases
	String kind = ManifestUtils.resolveKind(releaseAnalysisReport.getExistingRelease().getManifest().getData());
	UpgradeStrategy upgradeStrategy = this.upgradeStrategyFactory.getUpgradeStrategy(kind);
	log.info("Using UpgradeStrategy {}", upgradeStrategy);
	setUpgradeCutOffTime(context);
	upgradeStrategy.deployApps(releaseAnalysisReport.getExistingRelease(),
			releaseAnalysisReport.getReplacingRelease(), releaseAnalysisReport);
	context.getExtendedState().getVariables().put(SkipperVariables.RELEASE, releaseAnalysisReport.getReplacingRelease());
}
 
Example 24
@Override
protected void executeInternal(StateContext<SkipperStates, SkipperEvents> context) {
	super.executeInternal(context);
	ReleaseAnalysisReport releaseAnalysisReport = getReleaseAnalysisReport(context);

	// check if we're doing rollback and pass flag to strategy
	RollbackRequest rollbackRequest = context.getExtendedState().get(SkipperEventHeaders.ROLLBACK_REQUEST,
			RollbackRequest.class);

	// TODO: should check both releases
	String kind = ManifestUtils.resolveKind(releaseAnalysisReport.getExistingRelease().getManifest().getData());
	UpgradeStrategy upgradeStrategy = this.upgradeStrategyFactory.getUpgradeStrategy(kind);
	upgradeStrategy.accept(releaseAnalysisReport.getExistingRelease(), releaseAnalysisReport.getReplacingRelease(),
			releaseAnalysisReport, rollbackRequest != null);
}
 
Example 25
@Override
public void execute(StateContext<String, String> context) {
	String appVersion = (String) context.getMessageHeader(HEADER_APP_VERSION);

	// we control type so casting is safe
	@SuppressWarnings("unchecked")
	List<String> contextRunArgs = (List<String>) context.getMessageHeader(HEADER_CONTEXT_RUN_ARGS);

	String applicationId = getYarnCloudAppService().submitApplication(appVersion, CloudAppType.TASK, contextRunArgs);
	logger.info("New application id is {}", applicationId);
	context.getExtendedState().getVariables().put(VAR_APPLICATION_ID, applicationId);
}
 
Example 26
@Override
public void execute(StateContext<String, String> context) {
	String appVersion = (String) context.getMessageHeader(HEADER_APP_VERSION);

	if (!StringUtils.hasText(appVersion)) {
		context.getExtendedState().getVariables().put(VAR_ERROR, new RuntimeException("appVersion not defined"));
	} else {
		Collection<CloudAppInfo> appInfos = yarnCloudAppService.getApplications(cloudAppType);
		for (CloudAppInfo appInfo : appInfos) {
			if (appInfo.getName().equals(appVersion)) {
				context.getExtendedState().getVariables().put(VAR_APP_VERSION, appVersion);
			}
		}
	}
}
 
Example 27
@Override
public void execute(StateContext<String, String> context) {
	Resource artifact = (Resource) context.getMessageHeader(HEADER_ARTIFACT);
	String artifactDir = (String) context.getMessageHeader(HEADER_ARTIFACT_DIR);
	if (!isHdfsResource(artifact)) {
		yarnCloudAppService.pushArtifact(artifact, artifactDir);
	} else {
		if (!artifact.exists()) {
			context.getExtendedState().getVariables().put(VAR_ERROR, new RuntimeException("hdfs artifact missing"));
		}
	}
}
 
Example 28
@Override
protected StackContext createFlowContext(FlowParameters flowParameters, StateContext<MaintenanceModeValidationState,
        MaintenanceModeValidationEvent> stateContext, P payload) {
    Stack stack = stackService.getByIdWithListsInTransaction(payload.getResourceId());
    stack.setResources(new HashSet<>(resourceService.getAllByStackId(payload.getResourceId())));
    MDCBuilder.buildMdcContext(stack);
    Location location = location(region(stack.getRegion()), availabilityZone(stack.getAvailabilityZone()));
    CloudContext cloudContext = new CloudContext(stack.getId(), stack.getName(), stack.cloudPlatform(), stack.getPlatformVariant(),
            location, stack.getCreator().getUserId(), stack.getWorkspace().getId());
    CloudCredential cloudCredential = stackUtil.getCloudCredential(stack);
    CloudStack cloudStack = cloudStackConverter.convert(stack);
    return new StackContext(flowParameters, stack, cloudContext, cloudCredential, cloudStack);
}
 
Example 29
@Override
public void execute(StateContext<String, String> context) {
	String appVersion = (String) context.getMessageHeader(HEADER_APP_VERSION);
	String groupId = (String) context.getMessageHeader(HEADER_GROUP_ID);
	String appName = "scdstream:" + appVersion + ":" + groupId;
	CloudAppInstanceInfo appInstanceInfo = findRunningInstance(appName);
	if (appInstanceInfo != null) {
		context.getExtendedState().getVariables().put(VAR_APPLICATION_ID, appInstanceInfo.getApplicationId());
	}
}
 
Example 30
@Override
public void execute(StateContext<String, String> context) {
	String appVersion = (String) context.getMessageHeader(HEADER_APP_VERSION);

	// we control type so casting is safe
	@SuppressWarnings("unchecked")
	List<String> contextRunArgs = (List<String>) context.getMessageHeader(HEADER_CONTEXT_RUN_ARGS);
	String applicationId = getYarnCloudAppService().submitApplication(appVersion, CloudAppType.STREAM, contextRunArgs);
	context.getExtendedState().getVariables().put(VAR_APPLICATION_ID, applicationId);
}