2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
23 import java.sql.Timestamp;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.UUID;
27 import javax.persistence.EntityNotFoundException;
28 import org.camunda.bpm.engine.delegate.DelegateExecution;
29 import org.onap.aai.domain.yang.Vnfc;
30 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
31 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
32 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
33 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
34 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
35 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
36 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
37 import org.onap.so.client.aai.AAIObjectType;
38 import org.onap.so.client.exception.ExceptionBuilder;
39 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
40 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
41 import org.onap.so.db.catalog.client.CatalogDbClient;
42 import org.onap.so.db.request.beans.InfraActiveRequests;
43 import org.onap.so.db.request.client.RequestsDbClient;
44 import org.onap.so.serviceinstancebeans.RequestReferences;
45 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.core.env.Environment;
50 import org.springframework.stereotype.Component;
51 import com.fasterxml.jackson.core.JsonProcessingException;
52 import com.fasterxml.jackson.databind.ObjectMapper;
55 public class WorkflowActionBBTasks {
57 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
58 private static final String G_REQUEST_ID = "mso-request-id";
59 private static final String G_ALACARTE = "aLaCarte";
60 private static final String G_ACTION = "requestAction";
61 private static final String RETRY_COUNT = "retryCount";
62 private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
63 private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
64 private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
65 protected String maxRetries = "mso.rainyDay.maxRetries";
66 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
69 private RequestsDbClient requestDbclient;
71 private WorkflowAction workflowAction;
73 private WorkflowActionBBFailure workflowActionBBFailure;
75 private Environment environment;
77 private BBInputSetupUtils bbInputSetupUtils;
79 private CatalogDbClient catalogDbClient;
81 public void selectBB(DelegateExecution execution) {
82 List<ExecuteBuildingBlock> flowsToExecute =
83 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
84 execution.setVariable("MacroRollback", false);
85 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
86 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
88 if (ebb.getBuildingBlock().getBpmnFlowName().equals("ConfigAssignVnfBB")
89 || ebb.getBuildingBlock().getBpmnFlowName().equals("ConfigDeployVnfBB")) {
90 String vnfCustomizationUUID = ebb.getBuildingBlock().getKey();
92 List<VnfResourceCustomization> vnfResourceCustomizations = catalogDbClient
93 .getVnfResourceCustomizationByModelUuid(ebb.getRequestDetails().getModelInfo().getModelUuid());
94 if (vnfResourceCustomizations != null && vnfResourceCustomizations.size() >= 1) {
95 VnfResourceCustomization vrc = catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID,
96 vnfResourceCustomizations);
97 boolean skipConfigVNF = vrc.isSkipPostInstConf();
100 ebb = flowsToExecute.get(currentSequence);
105 boolean homing = (boolean) execution.getVariable("homing");
106 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
107 if (homing && !calledHoming) {
108 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
110 execution.setVariable("calledHoming", true);
113 ebb.setHoming(false);
115 execution.setVariable("buildingBlock", ebb);
117 if (currentSequence >= flowsToExecute.size()) {
118 execution.setVariable("completed", true);
120 execution.setVariable("completed", false);
122 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
125 public void updateFlowStatistics(DelegateExecution execution) {
127 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
128 if (currentSequence > 1) {
129 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
130 requestDbclient.updateInfraActiveRequests(request);
132 } catch (Exception ex) {
134 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
138 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
139 List<ExecuteBuildingBlock> flowsToExecute =
140 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
141 String requestId = (String) execution.getVariable(G_REQUEST_ID);
142 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
143 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
144 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
145 int completedBBs = currentSequence - 1;
146 int totalBBs = flowsToExecute.size();
147 int remainingBBs = totalBBs - completedBBs;
148 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
149 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
150 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
151 request.setFlowStatus(statusMessage);
152 request.setProgress(percentProgress);
153 request.setLastModifiedBy("CamundaBPMN");
157 protected Long getPercentProgress(int completedBBs, int totalBBs) {
158 double ratio = (completedBBs / (totalBBs * 1.0));
159 int percentProgress = (int) (ratio * 95);
160 return new Long(percentProgress + 5);
163 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
164 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
165 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
169 public void sendSyncAck(DelegateExecution execution) {
170 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
171 final String resourceId = (String) execution.getVariable("resourceId");
172 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
173 RequestReferences requestRef = new RequestReferences();
174 requestRef.setInstanceId(resourceId);
175 requestRef.setRequestId(requestId);
176 serviceInstancesResponse.setRequestReferences(requestRef);
177 ObjectMapper mapper = new ObjectMapper();
178 String jsonRequest = "";
180 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
181 } catch (JsonProcessingException e) {
182 workflowAction.buildAndThrowException(execution,
183 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
185 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
186 callbackResponse.setStatusCode(200);
187 callbackResponse.setMessage("Success");
188 callbackResponse.setResponse(jsonRequest);
189 String processKey = execution.getProcessEngineServices().getRepositoryService()
190 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
191 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
193 logger.info("Successfully sent sync ack.");
194 updateInstanceId(execution);
197 public void sendErrorSyncAck(DelegateExecution execution) {
198 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
200 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
201 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
202 if (errorMsg == null) {
203 errorMsg = "WorkflowAction failed unexpectedly.";
205 String processKey = exceptionBuilder.getProcessKey(execution);
206 String buildworkflowException =
207 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
209 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
210 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
211 callbackResponse.setStatusCode(500);
212 callbackResponse.setMessage("Fail");
213 callbackResponse.setResponse(buildworkflowException);
214 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
216 execution.setVariable("sentSyncResponse", true);
217 } catch (Exception ex) {
218 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
222 public void updateRequestStatusToComplete(DelegateExecution execution) {
224 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
225 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
226 final String action = (String) execution.getVariable(G_ACTION);
227 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
228 final String resourceName = (String) execution.getVariable("resourceName");
229 String statusMessage = (String) execution.getVariable("StatusMessage");
230 String macroAction = "";
231 if (statusMessage == null) {
233 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
235 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
238 macroAction = statusMessage;
240 execution.setVariable("finalStatusMessage", macroAction);
241 Timestamp endTime = new Timestamp(System.currentTimeMillis());
242 request.setEndTime(endTime);
243 request.setFlowStatus("Successfully completed all Building Blocks");
244 request.setStatusMessage(macroAction);
245 request.setProgress(Long.valueOf(100));
246 request.setRequestStatus("COMPLETE");
247 request.setLastModifiedBy("CamundaBPMN");
248 requestDbclient.updateInfraActiveRequests(request);
249 } catch (Exception ex) {
250 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
254 public void checkRetryStatus(DelegateExecution execution) {
255 String handlingCode = (String) execution.getVariable("handlingCode");
256 String requestId = (String) execution.getVariable(G_REQUEST_ID);
257 String retryDuration = (String) execution.getVariable("RetryDuration");
258 int retryCount = (int) execution.getVariable(RETRY_COUNT);
261 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
262 } catch (Exception ex) {
263 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
266 int nextCount = retryCount + 1;
267 if (handlingCode.equals("Retry")) {
268 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
270 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
271 request.setRetryStatusMessage(
272 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
273 requestDbclient.updateInfraActiveRequests(request);
274 } catch (Exception ex) {
275 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
277 if (retryCount < envMaxRetries) {
278 int currSequence = (int) execution.getVariable("gCurrentSequence");
279 execution.setVariable("gCurrentSequence", currSequence - 1);
280 execution.setVariable(RETRY_COUNT, nextCount);
282 workflowAction.buildAndThrowException(execution,
283 "Exceeded maximum retries. Ending flow with status Abort");
286 execution.setVariable(RETRY_COUNT, 0);
291 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
294 public void rollbackExecutionPath(DelegateExecution execution) {
295 if (!(boolean) execution.getVariable("isRollback")) {
296 List<ExecuteBuildingBlock> flowsToExecute =
297 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
298 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
299 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
300 int listSize = flowsToExecute.size();
301 for (int i = listSize - 1; i >= 0; i--) {
302 if (i > currentSequence - 1) {
303 flowsToExecute.remove(i);
305 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
306 if (flowName.contains("Assign")) {
307 flowName = "Unassign" + flowName.substring(6, flowName.length());
308 } else if (flowName.contains("Create")) {
309 flowName = "Delete" + flowName.substring(6, flowName.length());
310 } else if (flowName.contains("Activate")) {
311 flowName = "Deactivate" + flowName.substring(8, flowName.length());
315 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
316 rollbackFlows.add(flowsToExecute.get(i));
320 String handlingCode = (String) execution.getVariable("handlingCode");
321 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
322 rollbackFlowsFiltered.addAll(rollbackFlows);
323 if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
324 for (int i = 0; i < rollbackFlows.size(); i++) {
325 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
326 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
327 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
328 && handlingCode.equals("RollbackToCreated")) {
329 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
334 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
336 if (rollbackFlows.isEmpty())
337 execution.setVariable("isRollbackNeeded", false);
339 execution.setVariable("isRollbackNeeded", true);
340 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
341 execution.setVariable("handlingCode", "PreformingRollback");
342 execution.setVariable("isRollback", true);
343 execution.setVariable("gCurrentSequence", 0);
344 execution.setVariable(RETRY_COUNT, 0);
346 workflowAction.buildAndThrowException(execution,
347 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
351 protected void updateInstanceId(DelegateExecution execution) {
353 String requestId = (String) execution.getVariable(G_REQUEST_ID);
354 String resourceId = (String) execution.getVariable("resourceId");
355 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
356 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
357 if (resourceType == WorkflowType.SERVICE) {
358 request.setServiceInstanceId(resourceId);
359 } else if (resourceType == WorkflowType.VNF) {
360 request.setVnfId(resourceId);
361 } else if (resourceType == WorkflowType.VFMODULE) {
362 request.setVfModuleId(resourceId);
363 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
364 request.setVolumeGroupId(resourceId);
365 } else if (resourceType == WorkflowType.NETWORK) {
366 request.setNetworkId(resourceId);
367 } else if (resourceType == WorkflowType.CONFIGURATION) {
368 request.setConfigurationId(resourceId);
369 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
370 request.setInstanceGroupId(resourceId);
372 requestDbclient.updateInfraActiveRequests(request);
373 } catch (Exception ex) {
374 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
378 public void postProcessingExecuteBB(DelegateExecution execution) {
379 List<ExecuteBuildingBlock> flowsToExecute =
380 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
381 String handlingCode = (String) execution.getVariable("handlingCode");
382 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
383 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
384 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
385 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
386 if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
387 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
391 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
392 List<ExecuteBuildingBlock> flowsToExecute) {
394 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
395 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
396 String vfModuleId = ebb.getResourceId();
397 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
398 String serviceModelUUID =
399 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
400 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
401 String vfModuleCustomizationUUID =
402 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
404 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
405 logger.debug("Vnfc Size: {}", vnfcs.size());
406 for (Vnfc vnfc : vnfcs) {
407 String modelCustomizationId = vnfc.getModelCustomizationId();
408 logger.debug("Processing Vnfc: {}", modelCustomizationId);
409 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
410 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
411 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
412 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
413 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
414 String configurationId = UUID.randomUUID().toString();
415 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
416 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
417 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
418 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
419 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
420 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
421 configurationId, configurationResourceKeys);
422 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
423 configurationId, configurationResourceKeys);
424 flowsToExecute.add(assignConfigBB);
425 flowsToExecute.add(activateConfigBB);
426 flowsToExecute.stream()
427 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
428 executeBB.getBuildingBlock().getBpmnFlowName()));
429 execution.setVariable("flowsToExecute", flowsToExecute);
430 execution.setVariable("completed", false);
432 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
435 } catch (EntityNotFoundException e) {
436 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
437 } catch (Exception e) {
438 String errorMessage = "Error occurred in post processing of Vf Module create";
439 execution.setVariable("handlingCode", "RollbackToCreated");
440 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
441 logger.error(errorMessage, e);
445 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
446 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
447 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
448 BuildingBlock buildingBlock = new BuildingBlock();
449 buildingBlock.setBpmnFlowName(bbName);
450 buildingBlock.setMsoId(UUID.randomUUID().toString());
451 configBB.setaLaCarte(ebb.isaLaCarte());
452 configBB.setApiVersion(ebb.getApiVersion());
453 configBB.setRequestAction(ebb.getRequestAction());
454 configBB.setVnfType(ebb.getVnfType());
455 configBB.setRequestId(ebb.getRequestId());
456 configBB.setRequestDetails(ebb.getRequestDetails());
457 configBB.setBuildingBlock(buildingBlock);
458 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
459 workflowResourceIds.setConfigurationId(configurationId);
460 configBB.setWorkflowResourceIds(workflowResourceIds);
461 configBB.setConfigurationResourceKeys(configurationResourceKeys);