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.exception.ExceptionBuilder;
42 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
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 private static final String COMPLETED = "completed";
68 private static final String HANDLINGCODE = "handlingCode";
69 private static final String ROLLBACKTOCREATED = "RollbackToCreated";
70 protected String maxRetries = "mso.rainyDay.maxRetries";
71 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
74 private RequestsDbClient requestDbclient;
76 private WorkflowAction workflowAction;
78 private WorkflowActionBBFailure workflowActionBBFailure;
80 private Environment environment;
82 private BBInputSetupUtils bbInputSetupUtils;
84 private CatalogDbClient catalogDbClient;
86 private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
88 private RequestsDbListenerRunner requestsDbListener;
90 public void selectBB(DelegateExecution execution) {
91 List<ExecuteBuildingBlock> flowsToExecute =
92 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
93 execution.setVariable("MacroRollback", false);
95 flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
96 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
98 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
100 execution.setVariable("buildingBlock", ebb);
102 if (currentSequence >= flowsToExecute.size()) {
103 execution.setVariable(COMPLETED, true);
105 execution.setVariable(COMPLETED, false);
107 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
110 public void updateFlowStatistics(DelegateExecution execution) {
112 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
113 if (currentSequence > 1) {
114 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
115 requestDbclient.updateInfraActiveRequests(request);
117 } catch (Exception ex) {
119 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.",
124 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
125 List<ExecuteBuildingBlock> flowsToExecute =
126 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
127 String requestId = (String) execution.getVariable(G_REQUEST_ID);
128 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
129 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
130 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
131 int completedBBs = currentSequence - 1;
132 int totalBBs = flowsToExecute.size();
133 int remainingBBs = totalBBs - completedBBs;
134 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
135 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
136 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
137 request.setFlowStatus(statusMessage);
138 request.setProgress(percentProgress);
139 request.setLastModifiedBy("CamundaBPMN");
143 protected Long getPercentProgress(int completedBBs, int totalBBs) {
144 double ratio = (completedBBs / (totalBBs * 1.0));
145 int percentProgress = (int) (ratio * 95);
146 return new Long(percentProgress + 5);
149 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
150 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
151 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
155 public void sendSyncAck(DelegateExecution execution) {
156 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
157 final String resourceId = (String) execution.getVariable("resourceId");
158 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
159 RequestReferences requestRef = new RequestReferences();
160 requestRef.setInstanceId(resourceId);
161 requestRef.setRequestId(requestId);
162 serviceInstancesResponse.setRequestReferences(requestRef);
163 ObjectMapper mapper = new ObjectMapper();
164 String jsonRequest = "";
166 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
167 } catch (JsonProcessingException e) {
168 workflowAction.buildAndThrowException(execution,
169 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
171 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
172 callbackResponse.setStatusCode(200);
173 callbackResponse.setMessage("Success");
174 callbackResponse.setResponse(jsonRequest);
175 String processKey = execution.getProcessEngineServices().getRepositoryService()
176 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
177 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
179 logger.info("Successfully sent sync ack.");
180 updateInstanceId(execution);
183 public void sendErrorSyncAck(DelegateExecution execution) {
184 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
186 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
187 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
188 if (errorMsg == null) {
189 errorMsg = "WorkflowAction failed unexpectedly.";
191 String processKey = exceptionBuilder.getProcessKey(execution);
192 String buildworkflowException =
193 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
195 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
196 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
197 callbackResponse.setStatusCode(500);
198 callbackResponse.setMessage("Fail");
199 callbackResponse.setResponse(buildworkflowException);
200 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
202 execution.setVariable("sentSyncResponse", true);
203 } catch (Exception ex) {
204 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
208 public void updateRequestStatusToComplete(DelegateExecution execution) {
210 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
211 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
212 final String action = (String) execution.getVariable(G_ACTION);
213 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
214 final String resourceName = (String) execution.getVariable("resourceName");
215 String statusMessage = (String) execution.getVariable("StatusMessage");
216 String macroAction = "";
217 if (statusMessage == null) {
219 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
221 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
224 macroAction = statusMessage;
226 execution.setVariable("finalStatusMessage", macroAction);
227 Timestamp endTime = new Timestamp(System.currentTimeMillis());
228 request.setEndTime(endTime);
229 request.setFlowStatus("Successfully completed all Building Blocks");
230 request.setStatusMessage(macroAction);
231 request.setProgress(Long.valueOf(100));
232 request.setRequestStatus("COMPLETE");
233 request.setLastModifiedBy("CamundaBPMN");
234 requestsDbListener.post(request, new DelegateExecutionImpl(execution));
235 requestDbclient.updateInfraActiveRequests(request);
236 } catch (Exception ex) {
237 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
241 public void checkRetryStatus(DelegateExecution execution) {
242 String handlingCode = (String) execution.getVariable(HANDLINGCODE);
243 String requestId = (String) execution.getVariable(G_REQUEST_ID);
244 String retryDuration = (String) execution.getVariable("RetryDuration");
245 int retryCount = (int) execution.getVariable(RETRY_COUNT);
248 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
249 } catch (Exception ex) {
250 logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
253 int nextCount = retryCount + 1;
254 if ("Retry".equals(handlingCode)) {
255 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
257 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
258 request.setRetryStatusMessage(
259 "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
260 requestDbclient.updateInfraActiveRequests(request);
261 } catch (Exception ex) {
262 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
264 if (retryCount < envMaxRetries) {
265 int currSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
266 execution.setVariable(G_CURRENT_SEQUENCE, currSequence - 1);
267 execution.setVariable(RETRY_COUNT, nextCount);
269 workflowAction.buildAndThrowException(execution,
270 "Exceeded maximum retries. Ending flow with status Abort");
273 execution.setVariable(RETRY_COUNT, 0);
278 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
281 public void rollbackExecutionPath(DelegateExecution execution) {
282 if (!(boolean) execution.getVariable("isRollback")) {
283 List<ExecuteBuildingBlock> flowsToExecute =
284 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
285 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
286 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
287 int listSize = flowsToExecute.size();
288 for (int i = listSize - 1; i >= 0; i--) {
289 if (i > currentSequence - 1) {
290 flowsToExecute.remove(i);
292 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
293 if (flowName.startsWith("Assign")) {
294 flowName = flowName.replaceFirst("Assign", "Unassign");
295 } else if (flowName.startsWith("Create")) {
296 flowName = flowName.replaceFirst("Create", "Delete");
297 } else if (flowName.startsWith("Activate")) {
298 flowName = flowName.replaceFirst("Activate", "Deactivate");
302 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
303 rollbackFlows.add(flowsToExecute.get(i));
307 String handlingCode = (String) execution.getVariable(HANDLINGCODE);
308 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
309 rollbackFlowsFiltered.addAll(rollbackFlows);
310 if ("RollbackToAssigned".equals(handlingCode) || ROLLBACKTOCREATED.equals(handlingCode)) {
311 for (int i = 0; i < rollbackFlows.size(); i++) {
312 if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")) {
313 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
314 } else if (rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete")
315 && ROLLBACKTOCREATED.equals(handlingCode)) {
316 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
321 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
322 if (rollbackFlows.isEmpty())
323 execution.setVariable("isRollbackNeeded", false);
325 execution.setVariable("isRollbackNeeded", true);
326 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
327 execution.setVariable(HANDLINGCODE, "PreformingRollback");
328 execution.setVariable("isRollback", true);
329 execution.setVariable(G_CURRENT_SEQUENCE, 0);
330 execution.setVariable(RETRY_COUNT, 0);
332 workflowAction.buildAndThrowException(execution,
333 "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
337 protected void updateInstanceId(DelegateExecution execution) {
339 String requestId = (String) execution.getVariable(G_REQUEST_ID);
340 String resourceId = (String) execution.getVariable("resourceId");
341 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
342 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
343 if (resourceType == WorkflowType.SERVICE) {
344 request.setServiceInstanceId(resourceId);
345 } else if (resourceType == WorkflowType.VNF) {
346 request.setVnfId(resourceId);
347 } else if (resourceType == WorkflowType.VFMODULE) {
348 request.setVfModuleId(resourceId);
349 } else if (resourceType == WorkflowType.VOLUMEGROUP) {
350 request.setVolumeGroupId(resourceId);
351 } else if (resourceType == WorkflowType.NETWORK) {
352 request.setNetworkId(resourceId);
353 } else if (resourceType == WorkflowType.CONFIGURATION) {
354 request.setConfigurationId(resourceId);
355 } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
356 request.setInstanceGroupId(resourceId);
358 requestDbclient.updateInfraActiveRequests(request);
359 } catch (Exception ex) {
360 logger.error("Exception in updateInstanceId", ex);
361 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
365 public void postProcessingExecuteBB(DelegateExecution execution) {
366 List<ExecuteBuildingBlock> flowsToExecute =
367 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
368 String handlingCode = (String) execution.getVariable(HANDLINGCODE);
369 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
370 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
371 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
372 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
373 if ("ActivateVfModuleBB".equalsIgnoreCase(bbFlowName) && aLaCarte && "Success".equalsIgnoreCase(handlingCode)) {
374 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
378 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
379 List<ExecuteBuildingBlock> flowsToExecute) {
381 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
382 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
383 String vfModuleId = ebb.getResourceId();
384 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
385 String serviceModelUUID =
386 bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
387 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
388 String vfModuleCustomizationUUID =
389 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
391 workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
392 logger.debug("Vnfc Size: {}", vnfcs.size());
393 for (Vnfc vnfc : vnfcs) {
394 String modelCustomizationId = vnfc.getModelCustomizationId();
395 logger.debug("Processing Vnfc: {}", modelCustomizationId);
396 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
397 vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
398 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
399 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
400 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
401 String configurationId = UUID.randomUUID().toString();
402 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
403 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
404 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
405 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
406 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
407 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb,
408 configurationId, configurationResourceKeys);
409 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb,
410 configurationId, configurationResourceKeys);
411 flowsToExecute.add(assignConfigBB);
412 flowsToExecute.add(activateConfigBB);
413 flowsToExecute.stream()
414 .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
415 executeBB.getBuildingBlock().getBpmnFlowName()));
416 execution.setVariable("flowsToExecute", flowsToExecute);
417 execution.setVariable(COMPLETED, false);
419 logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
422 } catch (EntityNotFoundException e) {
423 logger.debug("Will not be running Fabric Config Building Blocks", e);
424 } catch (Exception e) {
425 String errorMessage = "Error occurred in post processing of Vf Module create";
426 execution.setVariable(HANDLINGCODE, ROLLBACKTOCREATED);
427 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
428 logger.error(errorMessage, e);
432 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
433 String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
434 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
435 BuildingBlock buildingBlock = new BuildingBlock();
436 buildingBlock.setBpmnFlowName(bbName);
437 buildingBlock.setMsoId(UUID.randomUUID().toString());
438 configBB.setaLaCarte(ebb.isaLaCarte());
439 configBB.setApiVersion(ebb.getApiVersion());
440 configBB.setRequestAction(ebb.getRequestAction());
441 configBB.setVnfType(ebb.getVnfType());
442 configBB.setRequestId(ebb.getRequestId());
443 configBB.setRequestDetails(ebb.getRequestDetails());
444 configBB.setBuildingBlock(buildingBlock);
445 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
446 workflowResourceIds.setConfigurationId(configurationId);
447 configBB.setWorkflowResourceIds(workflowResourceIds);
448 configBB.setConfigurationResourceKeys(configurationResourceKeys);