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.flowmanipulator.FlowManipulatorListenerRunner;
32 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
33 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
34 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
35 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
36 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
37 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
38 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
39 import org.onap.so.client.aai.AAIObjectType;
40 import org.onap.so.client.exception.ExceptionBuilder;
41 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
42 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
43 import org.onap.so.db.catalog.client.CatalogDbClient;
44 import org.onap.so.db.request.beans.InfraActiveRequests;
45 import org.onap.so.db.request.client.RequestsDbClient;
46 import org.onap.so.serviceinstancebeans.RequestReferences;
47 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.core.env.Environment;
52 import org.springframework.stereotype.Component;
53 import com.fasterxml.jackson.core.JsonProcessingException;
54 import com.fasterxml.jackson.databind.ObjectMapper;
57 public class WorkflowActionBBTasks {
59 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
60 private static final String G_REQUEST_ID = "mso-request-id";
61 private static final String G_ALACARTE = "aLaCarte";
62 private static final String G_ACTION = "requestAction";
63 private static final String RETRY_COUNT = "retryCount";
64 private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
65 private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
66 private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
67 protected String maxRetries = "mso.rainyDay.maxRetries";
68 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
71 private RequestsDbClient requestDbclient;
73 private WorkflowAction workflowAction;
75 private WorkflowActionBBFailure workflowActionBBFailure;
77 private Environment environment;
79 private BBInputSetupUtils bbInputSetupUtils;
81 private CatalogDbClient catalogDbClient;
83 private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
85 public void selectBB(DelegateExecution execution) {
86 List<ExecuteBuildingBlock> flowsToExecute =
87 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
88 execution.setVariable("MacroRollback", false);
90 flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
91 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
93 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
95 execution.setVariable("buildingBlock", ebb);
97 if (currentSequence >= flowsToExecute.size()) {
98 execution.setVariable("completed", true);
100 execution.setVariable("completed", false);
102 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
105 public void updateFlowStatistics(DelegateExecution execution) {
107 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
108 if (currentSequence > 1) {
109 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
110 requestDbclient.updateInfraActiveRequests(request);
112 } catch (Exception ex) {
114 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
118 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
119 List<ExecuteBuildingBlock> flowsToExecute =
120 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
121 String requestId = (String) execution.getVariable(G_REQUEST_ID);
122 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
123 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
124 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
125 int completedBBs = currentSequence - 1;
126 int totalBBs = flowsToExecute.size();
127 int remainingBBs = totalBBs - completedBBs;
128 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
129 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
130 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
131 request.setFlowStatus(statusMessage);
132 request.setProgress(percentProgress);
133 request.setLastModifiedBy("CamundaBPMN");
137 protected Long getPercentProgress(int completedBBs, int totalBBs) {
138 double ratio = (completedBBs / (totalBBs * 1.0));
139 int percentProgress = (int) (ratio * 95);
140 return new Long(percentProgress + 5);
143 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
144 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
145 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
149 public void sendSyncAck(DelegateExecution execution) {
150 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
151 final String resourceId = (String) execution.getVariable("resourceId");
152 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
153 RequestReferences requestRef = new RequestReferences();
154 requestRef.setInstanceId(resourceId);
155 requestRef.setRequestId(requestId);
156 serviceInstancesResponse.setRequestReferences(requestRef);
157 ObjectMapper mapper = new ObjectMapper();
158 String jsonRequest = "";
160 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
161 } catch (JsonProcessingException e) {
162 workflowAction.buildAndThrowException(execution,
163 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
165 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
166 callbackResponse.setStatusCode(200);
167 callbackResponse.setMessage("Success");
168 callbackResponse.setResponse(jsonRequest);
169 String processKey = execution.getProcessEngineServices().getRepositoryService()
170 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
171 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
173 logger.info("Successfully sent sync ack.");
174 updateInstanceId(execution);
177 public void sendErrorSyncAck(DelegateExecution execution) {
178 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
180 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
181 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
182 if (errorMsg == null) {
183 errorMsg = "WorkflowAction failed unexpectedly.";
185 String processKey = exceptionBuilder.getProcessKey(execution);
186 String buildworkflowException =
187 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
189 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
190 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
191 callbackResponse.setStatusCode(500);
192 callbackResponse.setMessage("Fail");
193 callbackResponse.setResponse(buildworkflowException);
194 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
196 execution.setVariable("sentSyncResponse", true);
197 } catch (Exception ex) {
198 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
202 public void updateRequestStatusToComplete(DelegateExecution execution) {
204 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
205 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
206 final String action = (String) execution.getVariable(G_ACTION);
207 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
208 final String resourceName = (String) execution.getVariable("resourceName");
209 String statusMessage = (String) execution.getVariable("StatusMessage");
210 String macroAction = "";
211 if (statusMessage == null) {
213 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
215 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
218 macroAction = statusMessage;
220 execution.setVariable("finalStatusMessage", macroAction);
221 Timestamp endTime = new Timestamp(System.currentTimeMillis());
222 request.setEndTime(endTime);
223 request.setFlowStatus("Successfully completed all Building Blocks");
224 request.setStatusMessage(macroAction);
225 request.setProgress(Long.valueOf(100));
226 request.setRequestStatus("COMPLETE");
227 request.setLastModifiedBy("CamundaBPMN");
228 requestDbclient.updateInfraActiveRequests(request);
229 } catch (Exception ex) {
230 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
234 public void checkRetryStatus(DelegateExecution execution) {
235 String handlingCode = (String) execution.getVariable("handlingCode");
236 String requestId = (String) execution.getVariable(G_REQUEST_ID);
237 String retryDuration = (String) execution.getVariable("RetryDuration");
238 int retryCount = (int) execution.getVariable(RETRY_COUNT);
241 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
242 } catch (Exception ex) {
243 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
246 int nextCount = retryCount + 1;
247 if (handlingCode.equals("Retry")) {
248 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
250 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
251 request.setRetryStatusMessage(
252 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
253 requestDbclient.updateInfraActiveRequests(request);
254 } catch (Exception ex) {
255 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
257 if (retryCount < envMaxRetries) {
258 int currSequence = (int) execution.getVariable("gCurrentSequence");
259 execution.setVariable("gCurrentSequence", currSequence - 1);
260 execution.setVariable(RETRY_COUNT, nextCount);
262 workflowAction.buildAndThrowException(execution,
263 "Exceeded maximum retries. Ending flow with status Abort");
266 execution.setVariable(RETRY_COUNT, 0);
271 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
274 public void rollbackExecutionPath(DelegateExecution execution) {
275 if (!(boolean) execution.getVariable("isRollback")) {
276 List<ExecuteBuildingBlock> flowsToExecute =
277 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
278 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
279 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
280 int listSize = flowsToExecute.size();
281 for (int i = listSize - 1; i >= 0; i--) {
282 if (i > currentSequence - 1) {
283 flowsToExecute.remove(i);
285 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
286 if (flowName.contains("Assign")) {
287 flowName = "Unassign" + flowName.substring(6, flowName.length());
288 } else if (flowName.contains("Create")) {
289 flowName = "Delete" + flowName.substring(6, flowName.length());
290 } else if (flowName.contains("Activate")) {
291 flowName = "Deactivate" + flowName.substring(8, flowName.length());
295 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
296 rollbackFlows.add(flowsToExecute.get(i));
300 String handlingCode = (String) execution.getVariable("handlingCode");
301 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
302 rollbackFlowsFiltered.addAll(rollbackFlows);
303 if (handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")) {
304 for (int i = 0; i < rollbackFlows.size(); i++) {
305 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
306 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
307 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
308 && handlingCode.equals("RollbackToCreated")) {
309 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
314 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
316 if (rollbackFlows.isEmpty())
317 execution.setVariable("isRollbackNeeded", false);
319 execution.setVariable("isRollbackNeeded", true);
320 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
321 execution.setVariable("handlingCode", "PreformingRollback");
322 execution.setVariable("isRollback", true);
323 execution.setVariable("gCurrentSequence", 0);
324 execution.setVariable(RETRY_COUNT, 0);
326 workflowAction.buildAndThrowException(execution,
327 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
331 protected void updateInstanceId(DelegateExecution execution) {
333 String requestId = (String) execution.getVariable(G_REQUEST_ID);
334 String resourceId = (String) execution.getVariable("resourceId");
335 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
336 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
337 if (resourceType == WorkflowType.SERVICE) {
338 request.setServiceInstanceId(resourceId);
339 } else if (resourceType == WorkflowType.VNF) {
340 request.setVnfId(resourceId);
341 } else if (resourceType == WorkflowType.VFMODULE) {
342 request.setVfModuleId(resourceId);
343 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
344 request.setVolumeGroupId(resourceId);
345 } else if (resourceType == WorkflowType.NETWORK) {
346 request.setNetworkId(resourceId);
347 } else if (resourceType == WorkflowType.CONFIGURATION) {
348 request.setConfigurationId(resourceId);
349 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
350 request.setInstanceGroupId(resourceId);
352 requestDbclient.updateInfraActiveRequests(request);
353 } catch (Exception ex) {
354 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
358 public void postProcessingExecuteBB(DelegateExecution execution) {
359 List<ExecuteBuildingBlock> flowsToExecute =
360 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
361 String handlingCode = (String) execution.getVariable("handlingCode");
362 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
363 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
364 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
365 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
366 if (bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
367 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
371 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
372 List<ExecuteBuildingBlock> flowsToExecute) {
374 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
375 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
376 String vfModuleId = ebb.getResourceId();
377 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
378 String serviceModelUUID =
379 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
380 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
381 String vfModuleCustomizationUUID =
382 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
384 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
385 logger.debug("Vnfc Size: {}", vnfcs.size());
386 for (Vnfc vnfc : vnfcs) {
387 String modelCustomizationId = vnfc.getModelCustomizationId();
388 logger.debug("Processing Vnfc: {}", modelCustomizationId);
389 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
390 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
391 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
392 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
393 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
394 String configurationId = UUID.randomUUID().toString();
395 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
396 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
397 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
398 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
399 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
400 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
401 configurationId, configurationResourceKeys);
402 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
403 configurationId, configurationResourceKeys);
404 flowsToExecute.add(assignConfigBB);
405 flowsToExecute.add(activateConfigBB);
406 flowsToExecute.stream()
407 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
408 executeBB.getBuildingBlock().getBpmnFlowName()));
409 execution.setVariable("flowsToExecute", flowsToExecute);
410 execution.setVariable("completed", false);
412 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
415 } catch (EntityNotFoundException e) {
416 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
417 } catch (Exception e) {
418 String errorMessage = "Error occurred in post processing of Vf Module create";
419 execution.setVariable("handlingCode", "RollbackToCreated");
420 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
421 logger.error(errorMessage, e);
425 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
426 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
427 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
428 BuildingBlock buildingBlock = new BuildingBlock();
429 buildingBlock.setBpmnFlowName(bbName);
430 buildingBlock.setMsoId(UUID.randomUUID().toString());
431 configBB.setaLaCarte(ebb.isaLaCarte());
432 configBB.setApiVersion(ebb.getApiVersion());
433 configBB.setRequestAction(ebb.getRequestAction());
434 configBB.setVnfType(ebb.getVnfType());
435 configBB.setRequestId(ebb.getRequestId());
436 configBB.setRequestDetails(ebb.getRequestDetails());
437 configBB.setBuildingBlock(buildingBlock);
438 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
439 workflowResourceIds.setConfigurationId(configurationId);
440 configBB.setWorkflowResourceIds(workflowResourceIds);
441 configBB.setConfigurationResourceKeys(configurationResourceKeys);