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.DelegateExecutionImpl;
31 import org.onap.so.bpmn.common.listener.db.RequestsDbListenerRunner;
32 import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner;
33 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
34 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
35 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
36 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
37 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
38 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
39 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
40 import org.onap.so.client.aai.AAIObjectType;
41 import org.onap.so.client.aai.entities.Configuration;
42 import org.onap.so.client.exception.ExceptionBuilder;
43 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
44 import org.onap.so.db.catalog.client.CatalogDbClient;
45 import org.onap.so.db.request.beans.InfraActiveRequests;
46 import org.onap.so.db.request.client.RequestsDbClient;
47 import org.onap.so.serviceinstancebeans.RequestReferences;
48 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.core.env.Environment;
53 import org.springframework.stereotype.Component;
54 import com.fasterxml.jackson.core.JsonProcessingException;
55 import com.fasterxml.jackson.databind.ObjectMapper;
58 public class WorkflowActionBBTasks {
60 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
61 private static final String G_REQUEST_ID = "mso-request-id";
62 private static final String G_ALACARTE = "aLaCarte";
63 private static final String G_ACTION = "requestAction";
64 private static final String RETRY_COUNT = "retryCount";
65 private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
66 private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
67 private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
68 private static final String COMPLETED = "completed";
69 private static final String HANDLINGCODE = "handlingCode";
70 private static final String ROLLBACKTOCREATED = "RollbackToCreated";
71 protected String maxRetries = "mso.rainyDay.maxRetries";
72 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
75 private RequestsDbClient requestDbclient;
77 private WorkflowAction workflowAction;
79 private WorkflowActionBBFailure workflowActionBBFailure;
81 private Environment environment;
83 private BBInputSetupUtils bbInputSetupUtils;
85 private CatalogDbClient catalogDbClient;
87 private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
89 private RequestsDbListenerRunner requestsDbListener;
91 public void selectBB(DelegateExecution execution) {
92 List<ExecuteBuildingBlock> flowsToExecute =
93 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
94 execution.setVariable("MacroRollback", false);
96 flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
97 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
99 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
101 execution.setVariable("buildingBlock", ebb);
103 if (currentSequence >= flowsToExecute.size()) {
104 execution.setVariable(COMPLETED, true);
106 execution.setVariable(COMPLETED, false);
108 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
111 public void updateFlowStatistics(DelegateExecution execution) {
113 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
114 if (currentSequence > 1) {
115 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
116 requestDbclient.updateInfraActiveRequests(request);
118 } catch (Exception ex) {
120 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.",
125 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
126 List<ExecuteBuildingBlock> flowsToExecute =
127 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
128 String requestId = (String) execution.getVariable(G_REQUEST_ID);
129 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
130 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
131 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
132 int completedBBs = currentSequence - 1;
133 int totalBBs = flowsToExecute.size();
134 int remainingBBs = totalBBs - completedBBs;
135 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
136 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
137 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
138 request.setFlowStatus(statusMessage);
139 request.setProgress(percentProgress);
140 request.setLastModifiedBy("CamundaBPMN");
144 protected Long getPercentProgress(int completedBBs, int totalBBs) {
145 double ratio = (completedBBs / (totalBBs * 1.0));
146 int percentProgress = (int) (ratio * 95);
147 return new Long(percentProgress + 5);
150 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
151 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
152 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
156 public void sendSyncAck(DelegateExecution execution) {
157 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
158 final String resourceId = (String) execution.getVariable("resourceId");
159 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
160 RequestReferences requestRef = new RequestReferences();
161 requestRef.setInstanceId(resourceId);
162 requestRef.setRequestId(requestId);
163 serviceInstancesResponse.setRequestReferences(requestRef);
164 ObjectMapper mapper = new ObjectMapper();
165 String jsonRequest = "";
167 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
168 } catch (JsonProcessingException e) {
169 workflowAction.buildAndThrowException(execution,
170 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
172 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
173 callbackResponse.setStatusCode(200);
174 callbackResponse.setMessage("Success");
175 callbackResponse.setResponse(jsonRequest);
176 String processKey = execution.getProcessEngineServices().getRepositoryService()
177 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
178 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
180 logger.info("Successfully sent sync ack.");
181 updateInstanceId(execution);
184 public void sendErrorSyncAck(DelegateExecution execution) {
185 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
187 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
188 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
189 if (errorMsg == null) {
190 errorMsg = "WorkflowAction failed unexpectedly.";
192 String processKey = exceptionBuilder.getProcessKey(execution);
193 String buildworkflowException =
194 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
196 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
197 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
198 callbackResponse.setStatusCode(500);
199 callbackResponse.setMessage("Fail");
200 callbackResponse.setResponse(buildworkflowException);
201 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
203 execution.setVariable("sentSyncResponse", true);
204 } catch (Exception ex) {
205 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
209 public void updateRequestStatusToComplete(DelegateExecution execution) {
211 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
212 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
213 final String action = (String) execution.getVariable(G_ACTION);
214 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
215 final String resourceName = (String) execution.getVariable("resourceName");
216 String statusMessage = (String) execution.getVariable("StatusMessage");
217 String macroAction = "";
218 if (statusMessage == null) {
220 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
222 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
225 macroAction = statusMessage;
227 execution.setVariable("finalStatusMessage", macroAction);
228 Timestamp endTime = new Timestamp(System.currentTimeMillis());
229 request.setEndTime(endTime);
230 request.setFlowStatus("Successfully completed all Building Blocks");
231 request.setStatusMessage(macroAction);
232 request.setProgress(Long.valueOf(100));
233 request.setRequestStatus("COMPLETE");
234 request.setLastModifiedBy("CamundaBPMN");
235 requestsDbListener.post(request, new DelegateExecutionImpl(execution));
236 requestDbclient.updateInfraActiveRequests(request);
237 } catch (Exception ex) {
238 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
242 public void checkRetryStatus(DelegateExecution execution) {
243 String handlingCode = (String) execution.getVariable(HANDLINGCODE);
244 String requestId = (String) execution.getVariable(G_REQUEST_ID);
245 String retryDuration = (String) execution.getVariable("RetryDuration");
246 int retryCount = (int) execution.getVariable(RETRY_COUNT);
249 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
250 } catch (Exception ex) {
251 logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
254 int nextCount = retryCount + 1;
255 if ("Retry".equals(handlingCode)) {
256 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
258 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
259 request.setRetryStatusMessage(
260 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
261 requestDbclient.updateInfraActiveRequests(request);
262 } catch (Exception ex) {
263 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
265 if (retryCount < envMaxRetries) {
266 int currSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
267 execution.setVariable(G_CURRENT_SEQUENCE, currSequence - 1);
268 execution.setVariable(RETRY_COUNT, nextCount);
270 workflowAction.buildAndThrowException(execution,
271 "Exceeded maximum retries. Ending flow with status Abort");
274 execution.setVariable(RETRY_COUNT, 0);
279 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
282 public void rollbackExecutionPath(DelegateExecution execution) {
283 if (!(boolean) execution.getVariable("isRollback")) {
284 List<ExecuteBuildingBlock> flowsToExecute =
285 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
286 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
287 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
288 int listSize = flowsToExecute.size();
289 for (int i = listSize - 1; i >= 0; i--) {
290 if (i > currentSequence - 1) {
291 flowsToExecute.remove(i);
293 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
294 if (flowName.startsWith("Assign")) {
295 flowName = flowName.replaceFirst("Assign", "Unassign");
296 } else if (flowName.startsWith("Create")) {
297 flowName = flowName.replaceFirst("Create", "Delete");
298 } else if (flowName.startsWith("Activate")) {
299 flowName = flowName.replaceFirst("Activate", "Deactivate");
303 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
304 rollbackFlows.add(flowsToExecute.get(i));
308 String handlingCode = (String) execution.getVariable(HANDLINGCODE);
309 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
310 rollbackFlowsFiltered.addAll(rollbackFlows);
311 if ("RollbackToAssigned".equals(handlingCode) || ROLLBACKTOCREATED.equals(handlingCode)) {
312 for (int i = 0; i < rollbackFlows.size(); i++) {
313 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
314 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
315 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
316 && ROLLBACKTOCREATED.equals(handlingCode)) {
317 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
322 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
323 if (rollbackFlows.isEmpty())
324 execution.setVariable("isRollbackNeeded", false);
326 execution.setVariable("isRollbackNeeded", true);
327 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
328 execution.setVariable(HANDLINGCODE, "PreformingRollback");
329 execution.setVariable("isRollback", true);
330 execution.setVariable(G_CURRENT_SEQUENCE, 0);
331 execution.setVariable(RETRY_COUNT, 0);
333 workflowAction.buildAndThrowException(execution,
334 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
338 protected void updateInstanceId(DelegateExecution execution) {
340 String requestId = (String) execution.getVariable(G_REQUEST_ID);
341 String resourceId = (String) execution.getVariable("resourceId");
342 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
343 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
344 if (resourceType == WorkflowType.SERVICE) {
345 request.setServiceInstanceId(resourceId);
346 } else if (resourceType == WorkflowType.VNF) {
347 request.setVnfId(resourceId);
348 } else if (resourceType == WorkflowType.VFMODULE) {
349 request.setVfModuleId(resourceId);
350 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
351 request.setVolumeGroupId(resourceId);
352 } else if (resourceType == WorkflowType.NETWORK) {
353 request.setNetworkId(resourceId);
354 } else if (resourceType == WorkflowType.CONFIGURATION) {
355 request.setConfigurationId(resourceId);
356 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
357 request.setInstanceGroupId(resourceId);
359 requestDbclient.updateInfraActiveRequests(request);
360 } catch (Exception ex) {
361 logger.error("Exception in updateInstanceId", ex);
362 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
366 public void postProcessingExecuteBB(DelegateExecution execution) {
367 List<ExecuteBuildingBlock> flowsToExecute =
368 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
369 String handlingCode = (String) execution.getVariable(HANDLINGCODE);
370 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
371 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
372 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
373 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
374 if ("ActivateVfModuleBB".equalsIgnoreCase(bbFlowName) && aLaCarte && "Success".equalsIgnoreCase(handlingCode)) {
375 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
379 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
380 List<ExecuteBuildingBlock> flowsToExecute) {
382 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
383 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
384 String vfModuleId = ebb.getResourceId();
385 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
386 String serviceModelUUID =
387 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
388 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
389 String vfModuleCustomizationUUID =
390 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
392 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
393 logger.debug("Vnfc Size: {}", vnfcs.size());
394 for (Vnfc vnfc : vnfcs) {
395 String modelCustomizationId = vnfc.getModelCustomizationId();
396 logger.debug("Processing Vnfc: {}", modelCustomizationId);
397 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
398 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
399 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
400 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
401 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
402 String configurationId = getConfigurationId(vnfc);
403 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
404 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
405 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
406 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
407 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
408 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
409 configurationId, configurationResourceKeys);
410 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
411 configurationId, configurationResourceKeys);
412 flowsToExecute.add(assignConfigBB);
413 flowsToExecute.add(activateConfigBB);
414 flowsToExecute.stream()
415 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
416 executeBB.getBuildingBlock().getBpmnFlowName()));
417 execution.setVariable("flowsToExecute", flowsToExecute);
418 execution.setVariable(COMPLETED, false);
420 logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
423 } catch (EntityNotFoundException e) {
424 logger.debug("Will not be running Fabric Config Building Blocks", e);
425 } catch (Exception e) {
426 String errorMessage = "Error occurred in post processing of Vf Module create";
427 execution.setVariable(HANDLINGCODE, ROLLBACKTOCREATED);
428 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
429 logger.error(errorMessage, e);
433 protected String getConfigurationId(Vnfc vnfc) {
434 List<Configuration> configurations =
435 workflowAction.getRelatedResourcesInVnfc(vnfc, Configuration.class, AAIObjectType.CONFIGURATION);
436 if (!configurations.isEmpty()) {
437 Configuration configuration = configurations.get(0);
438 return configuration.getConfigurationId();
440 return UUID.randomUUID().toString();
444 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
445 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
446 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
447 BuildingBlock buildingBlock = new BuildingBlock();
448 buildingBlock.setBpmnFlowName(bbName);
449 buildingBlock.setMsoId(UUID.randomUUID().toString());
450 configBB.setaLaCarte(ebb.isaLaCarte());
451 configBB.setApiVersion(ebb.getApiVersion());
452 configBB.setRequestAction(ebb.getRequestAction());
453 configBB.setVnfType(ebb.getVnfType());
454 configBB.setRequestId(ebb.getRequestId());
455 configBB.setRequestDetails(ebb.getRequestDetails());
456 configBB.setBuildingBlock(buildingBlock);
457 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
458 workflowResourceIds.setConfigurationId(configurationId);
459 configBB.setWorkflowResourceIds(workflowResourceIds);
460 configBB.setConfigurationResourceKeys(configurationResourceKeys);