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 serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
91 String vnfCustomizationUUID = ebb.getBuildingBlock().getKey();
93 List<VnfResourceCustomization> vnfResourceCustomizations =
94 catalogDbClient.getVnfResourceCustomizationByModelUuid(serviceInstanceId);
95 if (vnfResourceCustomizations != null && vnfResourceCustomizations.size() >= 1) {
96 VnfResourceCustomization vrc = catalogDbClient.findVnfResourceCustomizationInList(vnfCustomizationUUID,
97 vnfResourceCustomizations);
98 boolean skipConfigVNF = vrc.isSkipPostInstConf();
101 ebb = flowsToExecute.get(currentSequence);
106 boolean homing = (boolean) execution.getVariable("homing");
107 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
108 if (homing && !calledHoming) {
109 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
111 execution.setVariable("calledHoming", true);
114 ebb.setHoming(false);
116 execution.setVariable("buildingBlock", ebb);
118 if (currentSequence >= flowsToExecute.size()) {
119 execution.setVariable("completed", true);
121 execution.setVariable("completed", false);
123 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
126 public void updateFlowStatistics(DelegateExecution execution) {
128 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
129 if (currentSequence > 1) {
130 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
131 requestDbclient.updateInfraActiveRequests(request);
133 } catch (Exception ex) {
135 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
139 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
140 List<ExecuteBuildingBlock> flowsToExecute =
141 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
142 String requestId = (String) execution.getVariable(G_REQUEST_ID);
143 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
144 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
145 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
146 int completedBBs = currentSequence - 1;
147 int totalBBs = flowsToExecute.size();
148 int remainingBBs = totalBBs - completedBBs;
149 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
150 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
151 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
152 request.setFlowStatus(statusMessage);
153 request.setProgress(percentProgress);
154 request.setLastModifiedBy("CamundaBPMN");
158 protected Long getPercentProgress(int completedBBs, int totalBBs) {
159 double ratio = (completedBBs / (totalBBs * 1.0));
160 int percentProgress = (int) (ratio * 95);
161 return new Long(percentProgress + 5);
164 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
165 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
166 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
170 public void sendSyncAck(DelegateExecution execution) {
171 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
172 final String resourceId = (String) execution.getVariable("resourceId");
173 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
174 RequestReferences requestRef = new RequestReferences();
175 requestRef.setInstanceId(resourceId);
176 requestRef.setRequestId(requestId);
177 serviceInstancesResponse.setRequestReferences(requestRef);
178 ObjectMapper mapper = new ObjectMapper();
179 String jsonRequest = "";
181 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
182 } catch (JsonProcessingException e) {
183 workflowAction.buildAndThrowException(execution,
184 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
186 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
187 callbackResponse.setStatusCode(200);
188 callbackResponse.setMessage("Success");
189 callbackResponse.setResponse(jsonRequest);
190 String processKey = execution.getProcessEngineServices().getRepositoryService()
191 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
192 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
194 logger.info("Successfully sent sync ack.");
195 updateInstanceId(execution);
198 public void sendErrorSyncAck(DelegateExecution execution) {
199 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
201 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
202 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
203 if (errorMsg == null) {
204 errorMsg = "WorkflowAction failed unexpectedly.";
206 String processKey = exceptionBuilder.getProcessKey(execution);
207 String buildworkflowException =
208 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
210 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
211 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
212 callbackResponse.setStatusCode(500);
213 callbackResponse.setMessage("Fail");
214 callbackResponse.setResponse(buildworkflowException);
215 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
217 execution.setVariable("sentSyncResponse", true);
218 } catch (Exception ex) {
219 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
223 public void updateRequestStatusToComplete(DelegateExecution execution) {
225 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
226 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
227 final String action = (String) execution.getVariable(G_ACTION);
228 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
229 final String resourceName = (String) execution.getVariable("resourceName");
230 String macroAction = "";
232 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
234 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
236 execution.setVariable("finalStatusMessage", macroAction);
237 Timestamp endTime = new Timestamp(System.currentTimeMillis());
238 request.setEndTime(endTime);
239 request.setFlowStatus("Successfully completed all Building Blocks");
240 request.setStatusMessage(macroAction);
241 request.setProgress(Long.valueOf(100));
242 request.setRequestStatus("COMPLETE");
243 request.setLastModifiedBy("CamundaBPMN");
244 requestDbclient.updateInfraActiveRequests(request);
245 } catch (Exception ex) {
246 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
250 public void checkRetryStatus(DelegateExecution execution) {
251 String handlingCode = (String) execution.getVariable("handlingCode");
252 String requestId = (String) execution.getVariable(G_REQUEST_ID);
253 String retryDuration = (String) execution.getVariable("RetryDuration");
254 int retryCount = (int) execution.getVariable(RETRY_COUNT);
257 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
258 } catch (Exception ex) {
259 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
262 int nextCount = retryCount + 1;
263 if (handlingCode.equals("Retry")) {
264 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
266 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
267 request.setRetryStatusMessage(
268 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
269 requestDbclient.updateInfraActiveRequests(request);
270 } catch (Exception ex) {
271 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
273 if (retryCount < envMaxRetries) {
274 int currSequence = (int) execution.getVariable("gCurrentSequence");
275 execution.setVariable("gCurrentSequence", currSequence - 1);
276 execution.setVariable(RETRY_COUNT, nextCount);
278 workflowAction.buildAndThrowException(execution,
279 "Exceeded maximum retries. Ending flow with status Abort");
282 execution.setVariable(RETRY_COUNT, 0);
287 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
290 public void rollbackExecutionPath(DelegateExecution execution) {
291 if (!(boolean) execution.getVariable("isRollback")) {
292 List<ExecuteBuildingBlock> flowsToExecute =
293 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
294 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
295 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
296 int listSize = flowsToExecute.size();
297 for (int i = listSize - 1; i >= 0; i--) {
298 if (i > currentSequence - 1) {
299 flowsToExecute.remove(i);
301 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
302 if (flowName.contains("Assign")) {
303 flowName = "Unassign" + flowName.substring(6, flowName.length());
304 } else if (flowName.contains("Create")) {
305 flowName = "Delete" + flowName.substring(6, flowName.length());
306 } else if (flowName.contains("Activate")) {
307 flowName = "Deactivate" + flowName.substring(8, flowName.length());
311 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
312 rollbackFlows.add(flowsToExecute.get(i));
316 String handlingCode = (String) execution.getVariable("handlingCode");
317 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
318 rollbackFlowsFiltered.addAll(rollbackFlows);
319 if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
320 for (int i = 0; i < rollbackFlows.size(); i++) {
321 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
322 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
323 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
324 && handlingCode.equals("RollbackToCreated")) {
325 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
330 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
332 if (rollbackFlows.isEmpty())
333 execution.setVariable("isRollbackNeeded", false);
335 execution.setVariable("isRollbackNeeded", true);
336 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
337 execution.setVariable("handlingCode", "PreformingRollback");
338 execution.setVariable("isRollback", true);
339 execution.setVariable("gCurrentSequence", 0);
340 execution.setVariable(RETRY_COUNT, 0);
342 workflowAction.buildAndThrowException(execution,
343 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
347 protected void updateInstanceId(DelegateExecution execution) {
349 String requestId = (String) execution.getVariable(G_REQUEST_ID);
350 String resourceId = (String) execution.getVariable("resourceId");
351 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
352 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
353 if (resourceType == WorkflowType.SERVICE) {
354 request.setServiceInstanceId(resourceId);
355 } else if (resourceType == WorkflowType.VNF) {
356 request.setVnfId(resourceId);
357 } else if (resourceType == WorkflowType.VFMODULE) {
358 request.setVfModuleId(resourceId);
359 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
360 request.setVolumeGroupId(resourceId);
361 } else if (resourceType == WorkflowType.NETWORK) {
362 request.setNetworkId(resourceId);
363 } else if (resourceType == WorkflowType.CONFIGURATION) {
364 request.setConfigurationId(resourceId);
365 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
366 request.setInstanceGroupId(resourceId);
368 requestDbclient.updateInfraActiveRequests(request);
369 } catch (Exception ex) {
370 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
374 public void postProcessingExecuteBB(DelegateExecution execution) {
375 List<ExecuteBuildingBlock> flowsToExecute =
376 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
377 String handlingCode = (String) execution.getVariable("handlingCode");
378 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
379 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
380 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
381 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
382 if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
383 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
387 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
388 List<ExecuteBuildingBlock> flowsToExecute) {
390 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
391 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
392 String vfModuleId = ebb.getResourceId();
393 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
394 String serviceModelUUID =
395 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
396 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
397 String vfModuleCustomizationUUID =
398 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
400 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
401 logger.debug("Vnfc Size: {}", vnfcs.size());
402 for (Vnfc vnfc : vnfcs) {
403 String modelCustomizationId = vnfc.getModelCustomizationId();
404 logger.debug("Processing Vnfc: {}", modelCustomizationId);
405 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
406 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
407 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
408 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
409 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
410 String configurationId = UUID.randomUUID().toString();
411 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
412 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
413 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
414 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
415 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
416 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
417 configurationId, configurationResourceKeys);
418 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
419 configurationId, configurationResourceKeys);
420 flowsToExecute.add(assignConfigBB);
421 flowsToExecute.add(activateConfigBB);
422 flowsToExecute.stream()
423 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
424 executeBB.getBuildingBlock().getBpmnFlowName()));
425 execution.setVariable("flowsToExecute", flowsToExecute);
426 execution.setVariable("completed", false);
428 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
431 } catch (EntityNotFoundException e) {
432 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
433 } catch (Exception e) {
434 String errorMessage = "Error occurred in post processing of Vf Module create";
435 execution.setVariable("handlingCode", "RollbackToCreated");
436 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
437 logger.error(errorMessage, e);
441 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
442 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
443 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
444 BuildingBlock buildingBlock = new BuildingBlock();
445 buildingBlock.setBpmnFlowName(bbName);
446 buildingBlock.setMsoId(UUID.randomUUID().toString());
447 configBB.setaLaCarte(ebb.isaLaCarte());
448 configBB.setApiVersion(ebb.getApiVersion());
449 configBB.setRequestAction(ebb.getRequestAction());
450 configBB.setVnfType(ebb.getVnfType());
451 configBB.setRequestId(ebb.getRequestId());
452 configBB.setRequestDetails(ebb.getRequestDetails());
453 configBB.setBuildingBlock(buildingBlock);
454 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
455 workflowResourceIds.setConfigurationId(configurationId);
456 configBB.setWorkflowResourceIds(workflowResourceIds);
457 configBB.setConfigurationResourceKeys(configurationResourceKeys);