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 macroAction = "";
231 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
233 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
235 execution.setVariable("finalStatusMessage", macroAction);
236 Timestamp endTime = new Timestamp(System.currentTimeMillis());
237 request.setEndTime(endTime);
238 request.setFlowStatus("Successfully completed all Building Blocks");
239 request.setStatusMessage(macroAction);
240 request.setProgress(Long.valueOf(100));
241 request.setRequestStatus("COMPLETE");
242 request.setLastModifiedBy("CamundaBPMN");
243 requestDbclient.updateInfraActiveRequests(request);
244 } catch (Exception ex) {
245 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
249 public void checkRetryStatus(DelegateExecution execution) {
250 String handlingCode = (String) execution.getVariable("handlingCode");
251 String requestId = (String) execution.getVariable(G_REQUEST_ID);
252 String retryDuration = (String) execution.getVariable("RetryDuration");
253 int retryCount = (int) execution.getVariable(RETRY_COUNT);
256 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
257 } catch (Exception ex) {
258 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
261 int nextCount = retryCount + 1;
262 if (handlingCode.equals("Retry")) {
263 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
265 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
266 request.setRetryStatusMessage(
267 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
268 requestDbclient.updateInfraActiveRequests(request);
269 } catch (Exception ex) {
270 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
272 if (retryCount < envMaxRetries) {
273 int currSequence = (int) execution.getVariable("gCurrentSequence");
274 execution.setVariable("gCurrentSequence", currSequence - 1);
275 execution.setVariable(RETRY_COUNT, nextCount);
277 workflowAction.buildAndThrowException(execution,
278 "Exceeded maximum retries. Ending flow with status Abort");
281 execution.setVariable(RETRY_COUNT, 0);
286 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
289 public void rollbackExecutionPath(DelegateExecution execution) {
290 if (!(boolean) execution.getVariable("isRollback")) {
291 List<ExecuteBuildingBlock> flowsToExecute =
292 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
293 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
294 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
295 int listSize = flowsToExecute.size();
296 for (int i = listSize - 1; i >= 0; i--) {
297 if (i > currentSequence - 1) {
298 flowsToExecute.remove(i);
300 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
301 if (flowName.contains("Assign")) {
302 flowName = "Unassign" + flowName.substring(6, flowName.length());
303 } else if (flowName.contains("Create")) {
304 flowName = "Delete" + flowName.substring(6, flowName.length());
305 } else if (flowName.contains("Activate")) {
306 flowName = "Deactivate" + flowName.substring(8, flowName.length());
310 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
311 rollbackFlows.add(flowsToExecute.get(i));
315 String handlingCode = (String) execution.getVariable("handlingCode");
316 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
317 rollbackFlowsFiltered.addAll(rollbackFlows);
318 if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
319 for (int i = 0; i < rollbackFlows.size(); i++) {
320 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
321 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
322 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
323 && handlingCode.equals("RollbackToCreated")) {
324 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
329 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
331 if (rollbackFlows.isEmpty())
332 execution.setVariable("isRollbackNeeded", false);
334 execution.setVariable("isRollbackNeeded", true);
335 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
336 execution.setVariable("handlingCode", "PreformingRollback");
337 execution.setVariable("isRollback", true);
338 execution.setVariable("gCurrentSequence", 0);
339 execution.setVariable(RETRY_COUNT, 0);
341 workflowAction.buildAndThrowException(execution,
342 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
346 protected void updateInstanceId(DelegateExecution execution) {
348 String requestId = (String) execution.getVariable(G_REQUEST_ID);
349 String resourceId = (String) execution.getVariable("resourceId");
350 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
351 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
352 if (resourceType == WorkflowType.SERVICE) {
353 request.setServiceInstanceId(resourceId);
354 } else if (resourceType == WorkflowType.VNF) {
355 request.setVnfId(resourceId);
356 } else if (resourceType == WorkflowType.VFMODULE) {
357 request.setVfModuleId(resourceId);
358 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
359 request.setVolumeGroupId(resourceId);
360 } else if (resourceType == WorkflowType.NETWORK) {
361 request.setNetworkId(resourceId);
362 } else if (resourceType == WorkflowType.CONFIGURATION) {
363 request.setConfigurationId(resourceId);
364 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
365 request.setInstanceGroupId(resourceId);
367 requestDbclient.updateInfraActiveRequests(request);
368 } catch (Exception ex) {
369 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
373 public void postProcessingExecuteBB(DelegateExecution execution) {
374 List<ExecuteBuildingBlock> flowsToExecute =
375 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
376 String handlingCode = (String) execution.getVariable("handlingCode");
377 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
378 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
379 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
380 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
381 if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
382 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
386 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
387 List<ExecuteBuildingBlock> flowsToExecute) {
389 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
390 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
391 String vfModuleId = ebb.getResourceId();
392 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
393 String serviceModelUUID =
394 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
395 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
396 String vfModuleCustomizationUUID =
397 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
399 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
400 logger.debug("Vnfc Size: {}", vnfcs.size());
401 for (Vnfc vnfc : vnfcs) {
402 String modelCustomizationId = vnfc.getModelCustomizationId();
403 logger.debug("Processing Vnfc: {}", modelCustomizationId);
404 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
405 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
406 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
407 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
408 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
409 String configurationId = UUID.randomUUID().toString();
410 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
411 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
412 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
413 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
414 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
415 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
416 configurationId, configurationResourceKeys);
417 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
418 configurationId, configurationResourceKeys);
419 flowsToExecute.add(assignConfigBB);
420 flowsToExecute.add(activateConfigBB);
421 flowsToExecute.stream()
422 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
423 executeBB.getBuildingBlock().getBpmnFlowName()));
424 execution.setVariable("flowsToExecute", flowsToExecute);
425 execution.setVariable("completed", false);
427 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
430 } catch (EntityNotFoundException e) {
431 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
432 } catch (Exception e) {
433 String errorMessage = "Error occurred in post processing of Vf Module create";
434 execution.setVariable("handlingCode", "RollbackToCreated");
435 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
436 logger.error(errorMessage, e);
440 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
441 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
442 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
443 BuildingBlock buildingBlock = new BuildingBlock();
444 buildingBlock.setBpmnFlowName(bbName);
445 buildingBlock.setMsoId(UUID.randomUUID().toString());
446 configBB.setaLaCarte(ebb.isaLaCarte());
447 configBB.setApiVersion(ebb.getApiVersion());
448 configBB.setRequestAction(ebb.getRequestAction());
449 configBB.setVnfType(ebb.getVnfType());
450 configBB.setRequestId(ebb.getRequestId());
451 configBB.setRequestDetails(ebb.getRequestDetails());
452 configBB.setBuildingBlock(buildingBlock);
453 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
454 workflowResourceIds.setConfigurationId(configurationId);
455 configBB.setWorkflowResourceIds(workflowResourceIds);
456 configBB.setConfigurationResourceKeys(configurationResourceKeys);