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.util.ArrayList;
24 import java.util.List;
26 import org.camunda.bpm.engine.delegate.BpmnError;
27 import org.camunda.bpm.engine.delegate.DelegateExecution;
28 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
29 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
30 import org.onap.so.bpmn.core.WorkflowException;
31 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
32 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
34 import org.onap.so.client.exception.ExceptionBuilder;
35 import org.onap.so.db.request.beans.InfraActiveRequests;
36 import org.onap.so.db.request.client.RequestsDbClient;
37 import org.onap.so.logger.MsoLogger;
38 import org.onap.so.serviceinstancebeans.RequestReferences;
39 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.stereotype.Component;
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.ObjectMapper;
47 public class WorkflowActionBBTasks {
49 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
50 private static final String G_REQUEST_ID = "mso-request-id";
51 private static final String G_ALACARTE = "aLaCarte";
52 private static final String G_ACTION = "requestAction";
53 private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, WorkflowActionBBTasks.class);
56 private RequestsDbClient requestDbclient;
58 private WorkflowAction workflowAction;
60 public void selectBB(DelegateExecution execution) {
61 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
62 .getVariable("flowsToExecute");
63 execution.setVariable("MacroRollback", false);
64 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
65 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
66 boolean homing = (boolean) execution.getVariable("homing");
67 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
68 if (homing && !calledHoming) {
69 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
71 execution.setVariable("calledHoming", true);
76 execution.setVariable("buildingBlock", ebb);
78 if (currentSequence >= flowsToExecute.size()) {
79 execution.setVariable("completed", true);
81 execution.setVariable("completed", false);
82 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
86 public void updateFlowStatistics(DelegateExecution execution) {
87 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
88 if(currentSequence > 1) {
89 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
90 requestDbclient.updateInfraActiveRequests(request);
94 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
95 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
96 .getVariable("flowsToExecute");
97 String requestId = (String) execution.getVariable(G_REQUEST_ID);
98 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
99 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
100 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
101 int completedBBs = currentSequence - 1;
102 int totalBBs = flowsToExecute.size();
103 int remainingBBs = totalBBs - completedBBs;
104 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
105 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
106 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
107 request.setStatusMessage(statusMessage);
108 request.setProgress(percentProgress);
109 request.setLastModifiedBy("CamundaBPMN");
113 protected Long getPercentProgress(int completedBBs, int totalBBs) {
114 double ratio = (completedBBs / (totalBBs * 1.0));
115 int percentProgress = (int) (ratio * 95);
116 return new Long(percentProgress + 5);
119 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
120 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
121 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
125 public void sendSyncAck(DelegateExecution execution) {
126 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
127 final String resourceId = (String) execution.getVariable("resourceId");
128 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
129 RequestReferences requestRef = new RequestReferences();
130 requestRef.setInstanceId(resourceId);
131 requestRef.setRequestId(requestId);
132 serviceInstancesResponse.setRequestReferences(requestRef);
133 ObjectMapper mapper = new ObjectMapper();
134 String jsonRequest = "";
136 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
137 } catch (JsonProcessingException e) {
138 workflowAction.buildAndThrowException(execution,
139 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
141 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
142 callbackResponse.setStatusCode(200);
143 callbackResponse.setMessage("Success");
144 callbackResponse.setResponse(jsonRequest);
145 String processKey = execution.getProcessEngineServices().getRepositoryService()
146 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
147 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
149 msoLogger.info("Successfully sent sync ack.");
152 public void sendErrorSyncAck(DelegateExecution execution) {
153 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
155 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
156 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
157 if (errorMsg == null) {
158 errorMsg = "WorkflowAction failed unexpectedly.";
160 String processKey = exceptionBuilder.getProcessKey(execution);
161 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
163 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
164 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
165 callbackResponse.setStatusCode(500);
166 callbackResponse.setMessage("Fail");
167 callbackResponse.setResponse(buildworkflowException);
168 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
170 execution.setVariable("sentSyncResponse", true);
171 } catch (Exception ex) {
172 msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage());
176 public void setupCompleteMsoProcess(DelegateExecution execution) {
177 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
178 final String action = (String) execution.getVariable(G_ACTION);
179 final String resourceId = (String) execution.getVariable("resourceId");
180 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
181 final String resourceName = (String) execution.getVariable("resourceName");
182 final String source = (String) execution.getVariable("source");
183 String macroAction = "";
185 macroAction = "ALaCarte-" + resourceName + "-" + action;
187 macroAction = "Macro-" + resourceName + "-" + action;
189 String msoCompletionRequest = "<aetgt:MsoCompletionRequest xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\" xmlns:ns=\"http://org.onap/so/request/types/v1\"><request-info xmlns=\"http://org.onap/so/infra/vnf-request/v1\"><request-id>"
190 + requestId + "</request-id><action>" + action + "</action><source>" + source
191 + "</source></request-info><status-message>" + macroAction
192 + " request was executed correctly.</status-message><serviceInstanceId>" + resourceId
193 + "</serviceInstanceId><mso-bpel-name>WorkflowActionBB</mso-bpel-name></aetgt:MsoCompletionRequest>";
194 execution.setVariable("CompleteMsoProcessRequest", msoCompletionRequest);
195 execution.setVariable("mso-request-id", requestId);
196 execution.setVariable("mso-service-instance-id", resourceId);
199 public void setupFalloutHandler(DelegateExecution execution) {
200 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
201 final String action = (String) execution.getVariable(G_ACTION);
202 final String resourceId = (String) execution.getVariable("resourceId");
203 String exceptionMsg = "";
204 if (execution.getVariable("WorkflowActionErrorMessage") != null) {
205 exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
207 exceptionMsg = "Error in WorkflowAction";
209 execution.setVariable("mso-service-instance-id", resourceId);
210 execution.setVariable("mso-request-id", requestId);
211 String falloutRequest = "<aetgt:FalloutHandlerRequest xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"xmlns:ns=\"http://org.onap/so/request/types/v1\"xmlns:wfsch=\"http://org.onap/so/workflow/schema/v1\"><request-info xmlns=\"http://org.onap/so/infra/vnf-request/v1\"><request-id>"
212 + requestId + "</request-id><action>" + action
213 + "</action><source>VID</source></request-info><aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
215 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
216 execution.setVariable("falloutRequest", falloutRequest);
219 public void checkRetryStatus(DelegateExecution execution) {
220 if (execution.getVariable("handlingCode") == "Retry") {
221 int currSequence = (int) execution.getVariable("gCurrentSequence");
223 execution.setVariable("gCurrentSequence", currSequence);
224 int currRetryCount = (int) execution.getVariable("retryCount");
226 execution.setVariable("retryCount", currRetryCount);
231 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
232 * layer will rollback the flow its currently working on.
234 public void rollbackExecutionPath(DelegateExecution execution) {
235 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
236 .getVariable("flowsToExecute");
237 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
238 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE) - 1;
239 for (int i = flowsToExecute.size() - 1; i >= 0; i--) {
240 if (i >= currentSequence) {
241 flowsToExecute.remove(i);
243 ExecuteBuildingBlock ebb = flowsToExecute.get(i);
244 BuildingBlock bb = flowsToExecute.get(i).getBuildingBlock();
245 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
246 if (flowName.contains("Assign")) {
247 flowName = "Unassign" + flowName.substring(7, flowName.length());
248 } else if (flowName.contains("Create")) {
249 flowName = "Delete" + flowName.substring(6, flowName.length());
250 } else if (flowName.contains("Activate")) {
251 flowName = "Deactivate" + flowName.substring(8, flowName.length());
253 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
254 rollbackFlows.add(flowsToExecute.get(i));
257 if (rollbackFlows.isEmpty())
258 execution.setVariable("isRollbackNeeded", false);
260 execution.setVariable("isRollbackNeeded", true);
262 execution.setVariable("flowsToExecute", rollbackFlows);
263 execution.setVariable("handlingCode", "PreformingRollback");
266 public void abortCallErrorHandling(DelegateExecution execution) {
267 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
268 Exception exception = new Exception(msg);
269 msoLogger.error(exception);
270 throw new BpmnError(msg);
273 public void updateRequestStatusToFailed(DelegateExecution execution) {
275 String requestId = (String) execution.getVariable(G_REQUEST_ID);
276 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
277 String errorMsg = null;
279 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
280 request.setStatusMessage(exception.getErrorMessage());
281 } catch (Exception ex) {
282 //log error and attempt to extact WorkflowExceptionMessage
285 if (errorMsg == null){
287 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
288 request.setStatusMessage(errorMsg);
289 } catch (Exception ex) {
291 request.setStatusMessage("Unexpected Error in BPMN");
294 request.setRequestStatus("FAILED");
295 request.setLastModifiedBy("CamundaBPMN");
296 requestDbclient.updateInfraActiveRequests(request);
297 } catch (Exception e) {
298 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);