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.Optional;
27 import java.util.UUID;
29 import org.camunda.bpm.engine.delegate.DelegateExecution;
30 import org.onap.aai.domain.yang.Vnfc;
31 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
32 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
33 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
34 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
35 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
36 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
37 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
38 import org.onap.so.client.aai.AAIObjectType;
39 import org.onap.so.client.aai.entities.AAIResultWrapper;
40 import org.onap.so.client.aai.entities.Relationships;
41 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
42 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
43 import org.onap.so.client.exception.ExceptionBuilder;
44 import org.onap.so.db.catalog.beans.CvnfcCustomization;
45 import org.onap.so.db.catalog.beans.VnfVfmoduleCvnfcConfigurationCustomization;
46 import org.onap.so.db.catalog.client.CatalogDbClient;
47 import org.onap.so.db.request.beans.InfraActiveRequests;
48 import org.onap.so.db.request.client.RequestsDbClient;
49 import org.onap.so.serviceinstancebeans.RequestReferences;
50 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.core.env.Environment;
55 import org.springframework.stereotype.Component;
57 import com.fasterxml.jackson.core.JsonProcessingException;
58 import com.fasterxml.jackson.databind.ObjectMapper;
61 public class WorkflowActionBBTasks {
63 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
64 private static final String G_REQUEST_ID = "mso-request-id";
65 private static final String G_ALACARTE = "aLaCarte";
66 private static final String G_ACTION = "requestAction";
67 private static final String RETRY_COUNT = "retryCount";
68 private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
69 private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
70 private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
71 protected String maxRetries = "mso.rainyDay.maxRetries";
72 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
75 private RequestsDbClient requestDbclient;
77 private WorkflowAction workflowAction;
79 private WorkflowActionBBFailure workflowActionBBFailure;
81 private Environment environment;
83 private BBInputSetupUtils bbInputSetupUtils;
85 private CatalogDbClient catalogDbClient;
87 public void selectBB(DelegateExecution execution) {
88 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
89 .getVariable("flowsToExecute");
90 execution.setVariable("MacroRollback", false);
91 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
92 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
93 boolean homing = (boolean) execution.getVariable("homing");
94 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
95 if (homing && !calledHoming) {
96 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
98 execution.setVariable("calledHoming", true);
101 ebb.setHoming(false);
103 execution.setVariable("buildingBlock", ebb);
105 if (currentSequence >= flowsToExecute.size()) {
106 execution.setVariable("completed", true);
108 execution.setVariable("completed", false);
110 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
113 public void updateFlowStatistics(DelegateExecution execution) {
115 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
116 if(currentSequence > 1) {
117 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
118 requestDbclient.updateInfraActiveRequests(request);
120 }catch (Exception ex){
121 logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
125 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
126 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
127 .getVariable("flowsToExecute");
128 String requestId = (String) execution.getVariable(G_REQUEST_ID);
129 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
130 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
131 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
132 int completedBBs = currentSequence - 1;
133 int totalBBs = flowsToExecute.size();
134 int remainingBBs = totalBBs - completedBBs;
135 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
136 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
137 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
138 request.setFlowStatus(statusMessage);
139 request.setProgress(percentProgress);
140 request.setLastModifiedBy("CamundaBPMN");
144 protected Long getPercentProgress(int completedBBs, int totalBBs) {
145 double ratio = (completedBBs / (totalBBs * 1.0));
146 int percentProgress = (int) (ratio * 95);
147 return new Long(percentProgress + 5);
150 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
151 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
152 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
156 public void sendSyncAck(DelegateExecution execution) {
157 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
158 final String resourceId = (String) execution.getVariable("resourceId");
159 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
160 RequestReferences requestRef = new RequestReferences();
161 requestRef.setInstanceId(resourceId);
162 requestRef.setRequestId(requestId);
163 serviceInstancesResponse.setRequestReferences(requestRef);
164 ObjectMapper mapper = new ObjectMapper();
165 String jsonRequest = "";
167 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
168 } catch (JsonProcessingException e) {
169 workflowAction.buildAndThrowException(execution,
170 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
172 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
173 callbackResponse.setStatusCode(200);
174 callbackResponse.setMessage("Success");
175 callbackResponse.setResponse(jsonRequest);
176 String processKey = execution.getProcessEngineServices().getRepositoryService()
177 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
178 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
180 logger.info("Successfully sent sync ack.");
181 updateInstanceId(execution);
184 public void sendErrorSyncAck(DelegateExecution execution) {
185 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
187 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
188 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
189 if (errorMsg == null) {
190 errorMsg = "WorkflowAction failed unexpectedly.";
192 String processKey = exceptionBuilder.getProcessKey(execution);
193 String buildworkflowException = "<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 macroAction = "";
217 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
219 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
221 execution.setVariable("finalStatusMessage", macroAction);
222 Timestamp endTime = new Timestamp(System.currentTimeMillis());
223 request.setEndTime(endTime);
224 request.setFlowStatus("Successfully completed all Building Blocks");
225 request.setStatusMessage(macroAction);
226 request.setProgress(Long.valueOf(100));
227 request.setRequestStatus("COMPLETE");
228 request.setLastModifiedBy("CamundaBPMN");
229 requestDbclient.updateInfraActiveRequests(request);
230 }catch (Exception ex) {
231 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
235 public void checkRetryStatus(DelegateExecution execution) {
236 String handlingCode = (String) execution.getVariable("handlingCode");
237 String requestId = (String) execution.getVariable(G_REQUEST_ID);
238 String retryDuration = (String) execution.getVariable("RetryDuration");
239 int retryCount = (int) execution.getVariable(RETRY_COUNT);
242 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
243 } catch (Exception ex) {
244 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
247 int nextCount = retryCount +1;
248 if (handlingCode.equals("Retry")){
249 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
251 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
252 request.setRetryStatusMessage("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, "Exceeded maximum retries. Ending flow with status Abort");
265 execution.setVariable(RETRY_COUNT, 0);
270 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
271 * layer will rollback the flow its currently working on.
273 public void rollbackExecutionPath(DelegateExecution execution) {
274 if(!(boolean)execution.getVariable("isRollback")){
275 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
276 .getVariable("flowsToExecute");
277 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
278 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
279 int listSize = flowsToExecute.size();
280 for (int i = listSize - 1; i >= 0; i--) {
281 if (i > currentSequence - 1) {
282 flowsToExecute.remove(i);
284 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
285 if (flowName.contains("Assign")) {
286 flowName = "Unassign" + flowName.substring(6, flowName.length());
287 } else if (flowName.contains("Create")) {
288 flowName = "Delete" + flowName.substring(6, flowName.length());
289 } else if (flowName.contains("Activate")) {
290 flowName = "Deactivate" + flowName.substring(8, flowName.length());
294 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
295 rollbackFlows.add(flowsToExecute.get(i));
299 int flowSize = rollbackFlows.size();
300 String handlingCode = (String) execution.getVariable("handlingCode");
301 if(handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")){
302 for(int i = 0; i<flowSize; i++){
303 if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
304 rollbackFlows.remove(i);
305 } else if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete") && handlingCode.equals("RollbackToCreated")) {
306 rollbackFlows.remove(i);
311 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
313 if (rollbackFlows.isEmpty())
314 execution.setVariable("isRollbackNeeded", false);
316 execution.setVariable("isRollbackNeeded", true);
317 execution.setVariable("flowsToExecute", rollbackFlows);
318 execution.setVariable("handlingCode", "PreformingRollback");
319 execution.setVariable("isRollback", true);
320 execution.setVariable("gCurrentSequence", 0);
321 execution.setVariable(RETRY_COUNT, 0);
323 workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
327 protected void updateInstanceId(DelegateExecution execution){
329 String requestId = (String) execution.getVariable(G_REQUEST_ID);
330 String resourceId = (String) execution.getVariable("resourceId");
331 WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
332 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
333 if(resourceType == WorkflowType.SERVICE){
334 request.setServiceInstanceId(resourceId);
335 }else if(resourceType == WorkflowType.VNF){
336 request.setVnfId(resourceId);
337 }else if(resourceType == WorkflowType.VFMODULE){
338 request.setVfModuleId(resourceId);
339 }else if(resourceType == WorkflowType.VOLUMEGROUP){
340 request.setVolumeGroupId(resourceId);
341 }else if(resourceType == WorkflowType.NETWORK){
342 request.setNetworkId(resourceId);
343 }else if(resourceType == WorkflowType.CONFIGURATION){
344 request.setConfigurationId(resourceId);
345 }else if(resourceType == WorkflowType.INSTANCE_GROUP){
346 request.setInstanceGroupId(resourceId);
348 requestDbclient.updateInfraActiveRequests(request);
349 }catch(Exception ex){
350 workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
354 public void postProcessingExecuteBB(DelegateExecution execution) {
355 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
356 .getVariable("flowsToExecute");
357 String handlingCode = (String) execution.getVariable("handlingCode");
358 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
359 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
360 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
361 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
362 if(bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
363 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
367 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution,
368 ExecuteBuildingBlock ebb, List<ExecuteBuildingBlock> flowsToExecute) {
370 String vnfId = ebb.getWorkflowResourceIds().getVnfId();
371 String vfModuleId = ebb.getResourceId();
372 ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
373 String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
374 String vfModuleCustomizationUUID = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
375 List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
376 for(Vnfc vnfc : vnfcs) {
377 String modelCustomizationId = vnfc.getModelCustomizationId();
378 VnfVfmoduleCvnfcConfigurationCustomization fabricConfig =
379 catalogDbClient.getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid(vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
380 if(fabricConfig != null && fabricConfig.getConfigurationResource() != null
381 && fabricConfig.getConfigurationResource().getToscaNodeType() != null
382 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
383 String configurationId = UUID.randomUUID().toString();
384 ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
385 configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
386 configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
387 configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
388 configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
389 ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
390 ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
391 flowsToExecute.add(assignConfigBB);
392 flowsToExecute.add(activateConfigBB);
393 execution.setVariable("flowsToExecute", flowsToExecute);
394 execution.setVariable("completed", false);
396 logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
399 } catch (Exception e) {
400 String errorMessage = "Error occurred in post processing of Vf Module create";
401 execution.setVariable("handlingCode", "RollbackToCreated");
402 execution.setVariable("WorkflowActionErrorMessage", errorMessage);
403 logger.error(errorMessage, e);
407 protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb, String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
408 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
409 BuildingBlock buildingBlock = new BuildingBlock();
410 buildingBlock.setBpmnFlowName(bbName);
411 buildingBlock.setMsoId(UUID.randomUUID().toString());
412 configBB.setaLaCarte(ebb.isaLaCarte());
413 configBB.setApiVersion(ebb.getApiVersion());
414 configBB.setRequestAction(ebb.getRequestAction());
415 configBB.setVnfType(ebb.getVnfType());
416 configBB.setRequestId(ebb.getRequestId());
417 configBB.setRequestDetails(ebb.getRequestDetails());
418 configBB.setBuildingBlock(buildingBlock);
419 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
420 workflowResourceIds.setConfigurationId(configurationId);
421 configBB.setWorkflowResourceIds(workflowResourceIds);
422 configBB.setConfigurationResourceKeys(configurationResourceKeys);