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.client.CatalogDbClient;
41 import org.onap.so.db.request.beans.InfraActiveRequests;
42 import org.onap.so.db.request.client.RequestsDbClient;
43 import org.onap.so.serviceinstancebeans.RequestReferences;
44 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.core.env.Environment;
49 import org.springframework.stereotype.Component;
50 import com.fasterxml.jackson.core.JsonProcessingException;
51 import com.fasterxml.jackson.databind.ObjectMapper;
54 public class WorkflowActionBBTasks {
56 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
57 private static final String G_REQUEST_ID = "mso-request-id";
58 private static final String G_ALACARTE = "aLaCarte";
59 private static final String G_ACTION = "requestAction";
60 private static final String RETRY_COUNT = "retryCount";
61 private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
62 private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
63 private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
64 protected String maxRetries = "mso.rainyDay.maxRetries";
65 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
68 private RequestsDbClient requestDbclient;
70 private WorkflowAction workflowAction;
72 private WorkflowActionBBFailure workflowActionBBFailure;
74 private Environment environment;
76 private BBInputSetupUtils bbInputSetupUtils;
78 private CatalogDbClient catalogDbClient;
80 public void selectBB(DelegateExecution execution) {
81 List<ExecuteBuildingBlock> flowsToExecute =
82 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
83 execution.setVariable("MacroRollback", false);
84 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
85 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
86 boolean homing = (boolean) execution.getVariable("homing");
87 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
88 if (homing && !calledHoming) {
89 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
91 execution.setVariable("calledHoming", true);
96 execution.setVariable("buildingBlock", ebb);
98 if (currentSequence >= flowsToExecute.size()) {
99 execution.setVariable("completed", true);
101 execution.setVariable("completed", false);
103 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
106 public void updateFlowStatistics(DelegateExecution execution) {
108 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
109 if (currentSequence > 1) {
110 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
111 requestDbclient.updateInfraActiveRequests(request);
113 } catch (Exception ex) {
115 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
119 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
120 List<ExecuteBuildingBlock> flowsToExecute =
121 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
122 String requestId = (String) execution.getVariable(G_REQUEST_ID);
123 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
124 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
125 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
126 int completedBBs = currentSequence - 1;
127 int totalBBs = flowsToExecute.size();
128 int remainingBBs = totalBBs - completedBBs;
129 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
130 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
131 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
132 request.setFlowStatus(statusMessage);
133 request.setProgress(percentProgress);
134 request.setLastModifiedBy("CamundaBPMN");
138 protected Long getPercentProgress(int completedBBs, int totalBBs) {
139 double ratio = (completedBBs / (totalBBs * 1.0));
140 int percentProgress = (int) (ratio * 95);
141 return new Long(percentProgress + 5);
144 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
145 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
146 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
150 public void sendSyncAck(DelegateExecution execution) {
151 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
152 final String resourceId = (String) execution.getVariable("resourceId");
153 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
154 RequestReferences requestRef = new RequestReferences();
155 requestRef.setInstanceId(resourceId);
156 requestRef.setRequestId(requestId);
157 serviceInstancesResponse.setRequestReferences(requestRef);
158 ObjectMapper mapper = new ObjectMapper();
159 String jsonRequest = "";
161 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
162 } catch (JsonProcessingException e) {
163 workflowAction.buildAndThrowException(execution,
164 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
166 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
167 callbackResponse.setStatusCode(200);
168 callbackResponse.setMessage("Success");
169 callbackResponse.setResponse(jsonRequest);
170 String processKey = execution.getProcessEngineServices().getRepositoryService()
171 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
172 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
174 logger.info("Successfully sent sync ack.");
175 updateInstanceId(execution);
178 public void sendErrorSyncAck(DelegateExecution execution) {
179 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
181 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
182 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
183 if (errorMsg == null) {
184 errorMsg = "WorkflowAction failed unexpectedly.";
186 String processKey = exceptionBuilder.getProcessKey(execution);
187 String buildworkflowException =
188 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
190 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
191 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
192 callbackResponse.setStatusCode(500);
193 callbackResponse.setMessage("Fail");
194 callbackResponse.setResponse(buildworkflowException);
195 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
197 execution.setVariable("sentSyncResponse", true);
198 } catch (Exception ex) {
199 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
203 public void updateRequestStatusToComplete(DelegateExecution execution) {
205 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
206 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
207 final String action = (String) execution.getVariable(G_ACTION);
208 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
209 final String resourceName = (String) execution.getVariable("resourceName");
210 String macroAction = "";
212 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
214 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
216 execution.setVariable("finalStatusMessage", macroAction);
217 Timestamp endTime = new Timestamp(System.currentTimeMillis());
218 request.setEndTime(endTime);
219 request.setFlowStatus("Successfully completed all Building Blocks");
220 request.setStatusMessage(macroAction);
221 request.setProgress(Long.valueOf(100));
222 request.setRequestStatus("COMPLETE");
223 request.setLastModifiedBy("CamundaBPMN");
224 requestDbclient.updateInfraActiveRequests(request);
225 } catch (Exception ex) {
226 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
230 public void checkRetryStatus(DelegateExecution execution) {
231 String handlingCode = (String) execution.getVariable("handlingCode");
232 String requestId = (String) execution.getVariable(G_REQUEST_ID);
233 String retryDuration = (String) execution.getVariable("RetryDuration");
234 int retryCount = (int) execution.getVariable(RETRY_COUNT);
237 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
238 } catch (Exception ex) {
239 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
242 int nextCount = retryCount + 1;
243 if (handlingCode.equals("Retry")) {
244 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
246 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
247 request.setRetryStatusMessage(
248 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
249 requestDbclient.updateInfraActiveRequests(request);
250 } catch (Exception ex) {
251 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
253 if (retryCount < envMaxRetries) {
254 int currSequence = (int) execution.getVariable("gCurrentSequence");
255 execution.setVariable("gCurrentSequence", currSequence - 1);
256 execution.setVariable(RETRY_COUNT, nextCount);
258 workflowAction.buildAndThrowException(execution,
259 "Exceeded maximum retries. Ending flow with status Abort");
262 execution.setVariable(RETRY_COUNT, 0);
267 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
270 public void rollbackExecutionPath(DelegateExecution execution) {
271 if (!(boolean) execution.getVariable("isRollback")) {
272 List<ExecuteBuildingBlock> flowsToExecute =
273 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
274 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
275 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
276 int listSize = flowsToExecute.size();
277 for (int i = listSize - 1; i >= 0; i--) {
278 if (i > currentSequence - 1) {
279 flowsToExecute.remove(i);
281 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
282 if (flowName.contains("Assign")) {
283 flowName = "Unassign" + flowName.substring(6, flowName.length());
284 } else if (flowName.contains("Create")) {
285 flowName = "Delete" + flowName.substring(6, flowName.length());
286 } else if (flowName.contains("Activate")) {
287 flowName = "Deactivate" + flowName.substring(8, flowName.length());
291 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
292 rollbackFlows.add(flowsToExecute.get(i));
296 String handlingCode = (String) execution.getVariable("handlingCode");
297 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
298 rollbackFlowsFiltered.addAll(rollbackFlows);
299 if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
300 for (int i = 0; i < rollbackFlows.size(); i++) {
301 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
302 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
303 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
304 && handlingCode.equals("RollbackToCreated")) {
305 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
310 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
312 if (rollbackFlows.isEmpty())
313 execution.setVariable("isRollbackNeeded", false);
315 execution.setVariable("isRollbackNeeded", true);
316 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
317 execution.setVariable("handlingCode", "PreformingRollback");
318 execution.setVariable("isRollback", true);
319 execution.setVariable("gCurrentSequence", 0);
320 execution.setVariable(RETRY_COUNT, 0);
322 workflowAction.buildAndThrowException(execution,
323 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
327 protected void updateInstanceId(DelegateExecution execution) {
329 String requestId = (String) execution.getVariable(G_REQUEST_ID);
330 String resourceId = (String) execution.getVariable("resourceId");
331 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
332 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
333 if (resourceType == WorkflowType.SERVICE) {
334 request.setServiceInstanceId(resourceId);
335 } else if (resourceType == WorkflowType.VNF) {
336 request.setVnfId(resourceId);
337 } else if (resourceType == WorkflowType.VFMODULE) {
338 request.setVfModuleId(resourceId);
339 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
340 request.setVolumeGroupId(resourceId);
341 } else if (resourceType == WorkflowType.NETWORK) {
342 request.setNetworkId(resourceId);
343 } else if (resourceType == WorkflowType.CONFIGURATION) {
344 request.setConfigurationId(resourceId);
345 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
346 request.setInstanceGroupId(resourceId);
348 requestDbclient.updateInfraActiveRequests(request);
349 } catch (Exception ex) {
350 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
354 public void postProcessingExecuteBB(DelegateExecution execution) {
355 List<ExecuteBuildingBlock> flowsToExecute =
356 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
357 String handlingCode = (String) execution.getVariable("handlingCode");
358 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
359 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
360 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
361 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
362 if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
363 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
367 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
368 List<ExecuteBuildingBlock> flowsToExecute) {
370 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
371 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
372 String vfModuleId = ebb.getResourceId();
373 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
374 String serviceModelUUID =
375 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
376 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
377 String vfModuleCustomizationUUID =
378 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
380 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
381 logger.debug("Vnfc Size: {}", vnfcs.size());
382 for (Vnfc vnfc : vnfcs) {
383 String modelCustomizationId = vnfc.getModelCustomizationId();
384 logger.debug("Processing Vnfc: {}", modelCustomizationId);
385 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
386 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
387 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
388 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
389 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
390 String configurationId = UUID.randomUUID().toString();
391 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
392 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
393 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
394 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
395 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
396 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
397 configurationId, configurationResourceKeys);
398 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
399 configurationId, configurationResourceKeys);
400 flowsToExecute.add(assignConfigBB);
401 flowsToExecute.add(activateConfigBB);
402 flowsToExecute.stream()
403 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
404 executeBB.getBuildingBlock().getBpmnFlowName()));
405 execution.setVariable("flowsToExecute", flowsToExecute);
406 execution.setVariable("completed", false);
408 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
411 } catch (EntityNotFoundException e) {
412 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
413 } catch (Exception e) {
414 String errorMessage = "Error occurred in post processing of Vf Module create";
415 execution.setVariable("handlingCode", "RollbackToCreated");
416 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
417 logger.error(errorMessage, e);
421 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
422 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
423 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
424 BuildingBlock buildingBlock = new BuildingBlock();
425 buildingBlock.setBpmnFlowName(bbName);
426 buildingBlock.setMsoId(UUID.randomUUID().toString());
427 configBB.setaLaCarte(ebb.isaLaCarte());
428 configBB.setApiVersion(ebb.getApiVersion());
429 configBB.setRequestAction(ebb.getRequestAction());
430 configBB.setVnfType(ebb.getVnfType());
431 configBB.setRequestId(ebb.getRequestId());
432 configBB.setRequestDetails(ebb.getRequestDetails());
433 configBB.setBuildingBlock(buildingBlock);
434 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
435 workflowResourceIds.setConfigurationId(configurationId);
436 configBB.setWorkflowResourceIds(workflowResourceIds);
437 configBB.setConfigurationResourceKeys(configurationResourceKeys);