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;
33 import org.onap.so.client.db.request.RequestsDbClient;
34 import org.onap.so.client.exception.ExceptionBuilder;
35 import org.onap.so.db.request.beans.InfraActiveRequests;
36 import org.onap.so.logger.MsoLogger;
37 import org.onap.so.serviceinstancebeans.RequestReferences;
38 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.stereotype.Component;
42 import com.fasterxml.jackson.core.JsonProcessingException;
43 import com.fasterxml.jackson.databind.ObjectMapper;
46 public class WorkflowActionBBTasks {
48 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
49 private static final String G_REQUEST_ID = "mso-request-id";
50 private static final String G_ALACARTE = "aLaCarte";
51 private static final String G_ACTION = "requestAction";
52 private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, WorkflowActionBBTasks.class);
55 private RequestsDbClient requestDbclient;
57 private WorkflowAction workflowAction;
59 public void selectBB(DelegateExecution execution) {
60 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
61 .getVariable("flowsToExecute");
62 execution.setVariable("MacroRollback", false);
63 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
64 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
65 boolean homing = (boolean) execution.getVariable("homing");
66 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
67 if (homing && !calledHoming) {
68 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
70 execution.setVariable("calledHoming", true);
75 execution.setVariable("buildingBlock", ebb);
77 if (currentSequence >= flowsToExecute.size()) {
78 execution.setVariable("completed", true);
80 execution.setVariable("completed", false);
81 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
85 public void updateFlowStatistics(DelegateExecution execution) {
86 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
87 if(currentSequence > 1) {
88 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
89 requestDbclient.updateInfraActiveRequests(request);
93 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
94 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
95 .getVariable("flowsToExecute");
96 String requestId = (String) execution.getVariable(G_REQUEST_ID);
97 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
98 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
99 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
100 int completedBBs = currentSequence - 1;
101 int totalBBs = flowsToExecute.size();
102 int remainingBBs = totalBBs - completedBBs;
103 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
104 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
105 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
106 request.setStatusMessage(statusMessage);
107 request.setProgress(percentProgress);
108 request.setLastModifiedBy("CamundaBPMN");
112 protected Long getPercentProgress(int completedBBs, int totalBBs) {
113 double ratio = (completedBBs / (totalBBs * 1.0));
114 int percentProgress = (int) (ratio * 95);
115 return new Long(percentProgress + 5);
118 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
119 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
120 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
124 public void sendSyncAck(DelegateExecution execution) {
125 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
126 final String resourceId = (String) execution.getVariable("resourceId");
127 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
128 RequestReferences requestRef = new RequestReferences();
129 requestRef.setInstanceId(resourceId);
130 requestRef.setRequestId(requestId);
131 serviceInstancesResponse.setRequestReferences(requestRef);
132 ObjectMapper mapper = new ObjectMapper();
133 String jsonRequest = "";
135 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
136 } catch (JsonProcessingException e) {
137 workflowAction.buildAndThrowException(execution,
138 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
140 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
141 callbackResponse.setStatusCode(200);
142 callbackResponse.setMessage("Success");
143 callbackResponse.setResponse(jsonRequest);
144 String processKey = execution.getProcessEngineServices().getRepositoryService()
145 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
146 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
148 msoLogger.info("Successfully sent sync ack.");
151 public void sendErrorSyncAck(DelegateExecution execution) {
152 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
154 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
155 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
156 if (errorMsg == null) {
157 errorMsg = "WorkflowAction failed unexpectedly.";
159 String processKey = exceptionBuilder.getProcessKey(execution);
160 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
162 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
163 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
164 callbackResponse.setStatusCode(500);
165 callbackResponse.setMessage("Fail");
166 callbackResponse.setResponse(buildworkflowException);
167 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
169 execution.setVariable("sentSyncResponse", true);
170 } catch (Exception ex) {
171 msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage());
175 public void setupCompleteMsoProcess(DelegateExecution execution) {
176 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
177 final String action = (String) execution.getVariable(G_ACTION);
178 final String resourceId = (String) execution.getVariable("resourceId");
179 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
180 final String resourceName = (String) execution.getVariable("resourceName");
181 final String source = (String) execution.getVariable("source");
182 String macroAction = "";
184 macroAction = "ALaCarte-" + resourceName + "-" + action;
186 macroAction = "Macro-" + resourceName + "-" + action;
188 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>"
189 + requestId + "</request-id><action>" + action + "</action><source>" + source
190 + "</source></request-info><status-message>" + macroAction
191 + " request was executed correctly.</status-message><serviceInstanceId>" + resourceId
192 + "</serviceInstanceId><mso-bpel-name>WorkflowActionBB</mso-bpel-name></aetgt:MsoCompletionRequest>";
193 execution.setVariable("CompleteMsoProcessRequest", msoCompletionRequest);
194 execution.setVariable("mso-request-id", requestId);
195 execution.setVariable("mso-service-instance-id", resourceId);
198 public void setupFalloutHandler(DelegateExecution execution) {
199 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
200 final String action = (String) execution.getVariable(G_ACTION);
201 final String resourceId = (String) execution.getVariable("resourceId");
202 String exceptionMsg = "";
203 if (execution.getVariable("WorkflowActionErrorMessage") != null) {
204 exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
206 exceptionMsg = "Error in WorkflowAction";
208 execution.setVariable("mso-service-instance-id", resourceId);
209 execution.setVariable("mso-request-id", requestId);
210 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>"
211 + requestId + "</request-id><action>" + action
212 + "</action><source>VID</source></request-info><aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
214 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
215 execution.setVariable("falloutRequest", falloutRequest);
218 public void checkRetryStatus(DelegateExecution execution) {
219 if (execution.getVariable("handlingCode") == "Retry") {
220 int currSequence = (int) execution.getVariable("gCurrentSequence");
222 execution.setVariable("gCurrentSequence", currSequence);
223 int currRetryCount = (int) execution.getVariable("retryCount");
225 execution.setVariable("retryCount", currRetryCount);
230 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
231 * layer will rollback the flow its currently working on.
233 public void rollbackExecutionPath(DelegateExecution execution) {
234 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
235 .getVariable("flowsToExecute");
236 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
237 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE) - 1;
238 for (int i = flowsToExecute.size() - 1; i >= 0; i--) {
239 if (i >= currentSequence) {
240 flowsToExecute.remove(i);
242 ExecuteBuildingBlock ebb = flowsToExecute.get(i);
243 BuildingBlock bb = flowsToExecute.get(i).getBuildingBlock();
244 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
245 if (flowName.contains("Assign")) {
246 flowName = "Unassign" + flowName.substring(7, flowName.length());
247 } else if (flowName.contains("Create")) {
248 flowName = "Delete" + flowName.substring(6, flowName.length());
249 } else if (flowName.contains("Activate")) {
250 flowName = "Deactivate" + flowName.substring(8, flowName.length());
252 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
253 rollbackFlows.add(flowsToExecute.get(i));
256 if (rollbackFlows.isEmpty())
257 execution.setVariable("isRollbackNeeded", false);
259 execution.setVariable("isRollbackNeeded", true);
261 execution.setVariable("flowsToExecute", rollbackFlows);
262 execution.setVariable("handlingCode", "PreformingRollback");
265 public void abortCallErrorHandling(DelegateExecution execution) {
266 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
267 Exception exception = new Exception(msg);
268 msoLogger.error(exception);
269 throw new BpmnError(msg);
272 public void updateRequestStatusToFailed(DelegateExecution execution) {
274 String requestId = (String) execution.getVariable(G_REQUEST_ID);
275 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
276 String errorMsg = null;
278 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
279 request.setStatusMessage(exception.getErrorMessage());
280 } catch (Exception ex) {
281 //log error and attempt to extact WorkflowExceptionMessage
284 if (errorMsg == null){
286 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
287 request.setStatusMessage(errorMsg);
288 } catch (Exception ex) {
290 request.setStatusMessage("Unexpected Error in BPMN");
293 request.setRequestStatus("FAILED");
294 request.setLastModifiedBy("CamundaBPMN");
295 requestDbclient.updateInfraActiveRequests(request);
296 } catch (Exception e) {
297 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);