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;
28 import javax.persistence.EntityNotFoundException;
30 import org.camunda.bpm.engine.delegate.DelegateExecution;
31 import org.onap.aai.domain.yang.Vnfc;
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.client.CatalogDbClient;
43 import org.onap.so.db.request.beans.InfraActiveRequests;
44 import org.onap.so.db.request.client.RequestsDbClient;
45 import org.onap.so.serviceinstancebeans.RequestReferences;
46 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.core.env.Environment;
51 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 public void selectBB(DelegateExecution execution) {
84 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
85 .getVariable("flowsToExecute");
86 execution.setVariable("MacroRollback", false);
87 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
88 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
89 boolean homing = (boolean) execution.getVariable("homing");
90 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
91 if (homing && !calledHoming) {
92 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
94 execution.setVariable("calledHoming", true);
99 execution.setVariable("buildingBlock", ebb);
101 if (currentSequence >= flowsToExecute.size()) {
102 execution.setVariable("completed", true);
104 execution.setVariable("completed", false);
106 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
109 public void updateFlowStatistics(DelegateExecution execution) {
111 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
112 if(currentSequence > 1) {
113 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
114 requestDbclient.updateInfraActiveRequests(request);
116 }catch (Exception ex){
117 logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
121 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
122 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
123 .getVariable("flowsToExecute");
124 String requestId = (String) execution.getVariable(G_REQUEST_ID);
125 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
126 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
127 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
128 int completedBBs = currentSequence - 1;
129 int totalBBs = flowsToExecute.size();
130 int remainingBBs = totalBBs - completedBBs;
131 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
132 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
133 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
134 request.setFlowStatus(statusMessage);
135 request.setProgress(percentProgress);
136 request.setLastModifiedBy("CamundaBPMN");
140 protected Long getPercentProgress(int completedBBs, int totalBBs) {
141 double ratio = (completedBBs / (totalBBs * 1.0));
142 int percentProgress = (int) (ratio * 95);
143 return new Long(percentProgress + 5);
146 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
147 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
148 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
152 public void sendSyncAck(DelegateExecution execution) {
153 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
154 final String resourceId = (String) execution.getVariable("resourceId");
155 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
156 RequestReferences requestRef = new RequestReferences();
157 requestRef.setInstanceId(resourceId);
158 requestRef.setRequestId(requestId);
159 serviceInstancesResponse.setRequestReferences(requestRef);
160 ObjectMapper mapper = new ObjectMapper();
161 String jsonRequest = "";
163 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
164 } catch (JsonProcessingException e) {
165 workflowAction.buildAndThrowException(execution,
166 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
168 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
169 callbackResponse.setStatusCode(200);
170 callbackResponse.setMessage("Success");
171 callbackResponse.setResponse(jsonRequest);
172 String processKey = execution.getProcessEngineServices().getRepositoryService()
173 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
174 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
176 logger.info("Successfully sent sync ack.");
177 updateInstanceId(execution);
180 public void sendErrorSyncAck(DelegateExecution execution) {
181 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
183 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
184 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
185 if (errorMsg == null) {
186 errorMsg = "WorkflowAction failed unexpectedly.";
188 String processKey = exceptionBuilder.getProcessKey(execution);
189 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
191 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
192 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
193 callbackResponse.setStatusCode(500);
194 callbackResponse.setMessage("Fail");
195 callbackResponse.setResponse(buildworkflowException);
196 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
198 execution.setVariable("sentSyncResponse", true);
199 } catch (Exception ex) {
200 logger.error(" Sending Sync Error Activity Failed. {}" , ex.getMessage(), ex);
204 public void updateRequestStatusToComplete(DelegateExecution execution) {
206 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
207 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
208 final String action = (String) execution.getVariable(G_ACTION);
209 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
210 final String resourceName = (String) execution.getVariable("resourceName");
211 String macroAction = "";
213 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
215 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
217 execution.setVariable("finalStatusMessage", macroAction);
218 Timestamp endTime = new Timestamp(System.currentTimeMillis());
219 request.setEndTime(endTime);
220 request.setFlowStatus("Successfully completed all Building Blocks");
221 request.setStatusMessage(macroAction);
222 request.setProgress(Long.valueOf(100));
223 request.setRequestStatus("COMPLETE");
224 request.setLastModifiedBy("CamundaBPMN");
225 requestDbclient.updateInfraActiveRequests(request);
226 }catch (Exception ex) {
227 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
231 public void checkRetryStatus(DelegateExecution execution) {
232 String handlingCode = (String) execution.getVariable("handlingCode");
233 String requestId = (String) execution.getVariable(G_REQUEST_ID);
234 String retryDuration = (String) execution.getVariable("RetryDuration");
235 int retryCount = (int) execution.getVariable(RETRY_COUNT);
238 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
239 } catch (Exception ex) {
240 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
243 int nextCount = retryCount +1;
244 if (handlingCode.equals("Retry")){
245 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
247 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
248 request.setRetryStatusMessage("Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
249 requestDbclient.updateInfraActiveRequests(request);
250 } catch(Exception ex){
251 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
253 if(retryCount<envMaxRetries){
254 int currSequence = (int) execution.getVariable("gCurrentSequence");
255 execution.setVariable("gCurrentSequence", currSequence-1);
256 execution.setVariable(RETRY_COUNT, nextCount);
258 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
261 execution.setVariable(RETRY_COUNT, 0);
266 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
267 * layer will rollback the flow its currently working on.
269 public void rollbackExecutionPath(DelegateExecution execution) {
270 if(!(boolean)execution.getVariable("isRollback")){
271 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
272 .getVariable("flowsToExecute");
273 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
274 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
275 int listSize = flowsToExecute.size();
276 for (int i = listSize - 1; i >= 0; i--) {
277 if (i > currentSequence - 1) {
278 flowsToExecute.remove(i);
280 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
281 if (flowName.contains("Assign")) {
282 flowName = "Unassign" + flowName.substring(6, flowName.length());
283 } else if (flowName.contains("Create")) {
284 flowName = "Delete" + flowName.substring(6, flowName.length());
285 } else if (flowName.contains("Activate")) {
286 flowName = "Deactivate" + flowName.substring(8, flowName.length());
290 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
291 rollbackFlows.add(flowsToExecute.get(i));
295 String handlingCode = (String) execution.getVariable("handlingCode");
296 List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>();
297 rollbackFlowsFiltered.addAll(rollbackFlows);
298 if(handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")){
299 for(int i = 0; i<rollbackFlows.size(); i++){
300 if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
301 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
302 } else if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete") && handlingCode.equals("RollbackToCreated")) {
303 rollbackFlowsFiltered.remove(rollbackFlows.get(i));
308 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
310 if (rollbackFlows.isEmpty())
311 execution.setVariable("isRollbackNeeded", false);
313 execution.setVariable("isRollbackNeeded", true);
314 execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
315 execution.setVariable("handlingCode", "PreformingRollback");
316 execution.setVariable("isRollback", true);
317 execution.setVariable("gCurrentSequence", 0);
318 execution.setVariable(RETRY_COUNT, 0);
320 workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
324 protected void updateInstanceId(DelegateExecution execution){
326 String requestId = (String) execution.getVariable(G_REQUEST_ID);
327 String resourceId = (String) execution.getVariable("resourceId");
328 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
329 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
330 if(resourceType == WorkflowType.SERVICE){
331 request.setServiceInstanceId(resourceId);
332 }else if(resourceType == WorkflowType.VNF){
333 request.setVnfId(resourceId);
334 }else if(resourceType == WorkflowType.VFMODULE){
335 request.setVfModuleId(resourceId);
336 }else if(resourceType == WorkflowType.VOLUMEGROUP){
337 request.setVolumeGroupId(resourceId);
338 }else if(resourceType == WorkflowType.NETWORK){
339 request.setNetworkId(resourceId);
340 }else if(resourceType == WorkflowType.CONFIGURATION){
341 request.setConfigurationId(resourceId);
342 }else if(resourceType == WorkflowType.INSTANCE_GROUP){
343 request.setInstanceGroupId(resourceId);
345 requestDbclient.updateInfraActiveRequests(request);
346 }catch(Exception ex){
347 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
351 public void postProcessingExecuteBB(DelegateExecution execution) {
352 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
353 .getVariable("flowsToExecute");
354 String handlingCode = (String) execution.getVariable("handlingCode");
355 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
356 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
357 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
358 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
359 if(bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
360 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
364 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution,
365 ExecuteBuildingBlock ebb, List<ExecuteBuildingBlock> flowsToExecute) {
367 String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
368 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
369 String vfModuleId = ebb.getResourceId();
370 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
371 String serviceModelUUID = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
372 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
373 String vfModuleCustomizationUUID = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
374 List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
375 logger.debug("Vnfc Size: {}", vnfcs.size());
376 for(Vnfc vnfc : vnfcs) {
377 String modelCustomizationId = vnfc.getModelCustomizationId();
378 logger.debug("Processing Vnfc: {}", modelCustomizationId);
379 CvnfcConfigurationCustomization fabricConfig =
380 catalogDbClient.getCvnfcCustomization(serviceModelUUID,vnfCustomizationUUID,
381 vfModuleCustomizationUUID, modelCustomizationId);
382 if(fabricConfig != null && fabricConfig.getConfigurationResource() != null
383 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
384 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
385 String configurationId = UUID.randomUUID().toString();
386 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
387 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
388 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
389 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
390 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
391 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
392 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
393 flowsToExecute.add(assignConfigBB);
394 flowsToExecute.add(activateConfigBB);
395 flowsToExecute.stream().forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}", executeBB.getBuildingBlock().getBpmnFlowName()));
396 execution.setVariable("flowsToExecute", flowsToExecute);
397 execution.setVariable("completed", false);
399 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
402 } catch (EntityNotFoundException e) {
403 logger.debug(e.getMessage() + " Will not be running Fabric Config Building Blocks");
404 } catch (Exception e) {
405 String errorMessage = "Error occurred in post processing of Vf Module create";
406 execution.setVariable("handlingCode", "RollbackToCreated");
407 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
408 logger.error(errorMessage, e);
412 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb, String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
413 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
414 BuildingBlock buildingBlock = new BuildingBlock();
415 buildingBlock.setBpmnFlowName(bbName);
416 buildingBlock.setMsoId(UUID.randomUUID().toString());
417 configBB.setaLaCarte(ebb.isaLaCarte());
418 configBB.setApiVersion(ebb.getApiVersion());
419 configBB.setRequestAction(ebb.getRequestAction());
420 configBB.setVnfType(ebb.getVnfType());
421 configBB.setRequestId(ebb.getRequestId());
422 configBB.setRequestDetails(ebb.getRequestDetails());
423 configBB.setBuildingBlock(buildingBlock);
424 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
425 workflowResourceIds.setConfigurationId(configurationId);
426 configBB.setWorkflowResourceIds(workflowResourceIds);
427 configBB.setConfigurationResourceKeys(configurationResourceKeys);