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.exception.ExceptionBuilder;
34 import org.onap.so.db.request.beans.InfraActiveRequests;
35 import org.onap.so.db.request.client.RequestsDbClient;
36 import org.onap.so.serviceinstancebeans.RequestReferences;
37 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
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 String RETRY_COUNT = "retryCount";
54 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
57 private RequestsDbClient requestDbclient;
59 private WorkflowAction workflowAction;
61 public void selectBB(DelegateExecution execution) {
62 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
63 .getVariable("flowsToExecute");
64 execution.setVariable("MacroRollback", false);
65 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
66 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
67 boolean homing = (boolean) execution.getVariable("homing");
68 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
69 if (homing && !calledHoming) {
70 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
72 execution.setVariable("calledHoming", true);
77 execution.setVariable("buildingBlock", ebb);
79 if (currentSequence >= flowsToExecute.size()) {
80 execution.setVariable("completed", true);
82 execution.setVariable("completed", false);
83 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
87 public void updateFlowStatistics(DelegateExecution execution) {
89 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
90 if(currentSequence > 1) {
91 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
92 requestDbclient.updateInfraActiveRequests(request);
94 }catch (Exception ex){
95 logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
99 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
100 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
101 .getVariable("flowsToExecute");
102 String requestId = (String) execution.getVariable(G_REQUEST_ID);
103 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
104 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
105 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
106 int completedBBs = currentSequence - 1;
107 int totalBBs = flowsToExecute.size();
108 int remainingBBs = totalBBs - completedBBs;
109 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
110 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
111 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
112 request.setStatusMessage(statusMessage);
113 request.setProgress(percentProgress);
114 request.setLastModifiedBy("CamundaBPMN");
118 protected Long getPercentProgress(int completedBBs, int totalBBs) {
119 double ratio = (completedBBs / (totalBBs * 1.0));
120 int percentProgress = (int) (ratio * 95);
121 return new Long(percentProgress + 5);
124 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
125 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
126 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
130 public void sendSyncAck(DelegateExecution execution) {
131 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
132 final String resourceId = (String) execution.getVariable("resourceId");
133 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
134 RequestReferences requestRef = new RequestReferences();
135 requestRef.setInstanceId(resourceId);
136 requestRef.setRequestId(requestId);
137 serviceInstancesResponse.setRequestReferences(requestRef);
138 ObjectMapper mapper = new ObjectMapper();
139 String jsonRequest = "";
141 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
142 } catch (JsonProcessingException e) {
143 workflowAction.buildAndThrowException(execution,
144 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
146 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
147 callbackResponse.setStatusCode(200);
148 callbackResponse.setMessage("Success");
149 callbackResponse.setResponse(jsonRequest);
150 String processKey = execution.getProcessEngineServices().getRepositoryService()
151 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
152 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
154 logger.info("Successfully sent sync ack.");
157 public void sendErrorSyncAck(DelegateExecution execution) {
158 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
160 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
161 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
162 if (errorMsg == null) {
163 errorMsg = "WorkflowAction failed unexpectedly.";
165 String processKey = exceptionBuilder.getProcessKey(execution);
166 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
168 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
169 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
170 callbackResponse.setStatusCode(500);
171 callbackResponse.setMessage("Fail");
172 callbackResponse.setResponse(buildworkflowException);
173 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
175 execution.setVariable("sentSyncResponse", true);
176 } catch (Exception ex) {
177 logger.error(" Sending Sync Error Activity Failed. {}" , ex.getMessage(), ex);
181 public void setupCompleteMsoProcess(DelegateExecution execution) {
182 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
183 final String action = (String) execution.getVariable(G_ACTION);
184 final String resourceId = (String) execution.getVariable("resourceId");
185 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
186 final String resourceName = (String) execution.getVariable("resourceName");
187 final String source = (String) execution.getVariable("source");
188 String macroAction = "";
190 macroAction = "ALaCarte-" + resourceName + "-" + action;
192 macroAction = "Macro-" + resourceName + "-" + action;
194 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>"
195 + requestId + "</request-id><action>" + action + "</action><source>" + source
196 + "</source></request-info><status-message>" + macroAction
197 + " request was executed correctly.</status-message><serviceInstanceId>" + resourceId
198 + "</serviceInstanceId><mso-bpel-name>WorkflowActionBB</mso-bpel-name></aetgt:MsoCompletionRequest>";
199 execution.setVariable("CompleteMsoProcessRequest", msoCompletionRequest);
200 execution.setVariable("mso-request-id", requestId);
201 execution.setVariable("mso-service-instance-id", resourceId);
204 public void setupFalloutHandler(DelegateExecution execution) {
205 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
206 final String action = (String) execution.getVariable(G_ACTION);
207 final String resourceId = (String) execution.getVariable("resourceId");
208 String exceptionMsg = "";
209 if (execution.getVariable("WorkflowActionErrorMessage") != null) {
210 exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
212 exceptionMsg = "Error in WorkflowAction";
214 execution.setVariable("mso-service-instance-id", resourceId);
215 execution.setVariable("mso-request-id", requestId);
216 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>"
217 + requestId + "</request-id><action>" + action
218 + "</action><source>VID</source></request-info><aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
220 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
221 execution.setVariable("falloutRequest", falloutRequest);
224 public void checkRetryStatus(DelegateExecution execution) {
225 String handlingCode = (String) execution.getVariable("handlingCode");
226 int retryCount = (int) execution.getVariable(RETRY_COUNT);
227 if (handlingCode.equals("Retry")){
229 int currSequence = (int) execution.getVariable("gCurrentSequence");
230 execution.setVariable("gCurrentSequence", currSequence-1);
231 execution.setVariable(RETRY_COUNT, retryCount + 1);
233 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
236 execution.setVariable(RETRY_COUNT, 0);
241 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
242 * layer will rollback the flow its currently working on.
244 public void rollbackExecutionPath(DelegateExecution execution) {
245 if(!(boolean)execution.getVariable("isRollback")){
246 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
247 .getVariable("flowsToExecute");
248 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
249 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
250 int listSize = flowsToExecute.size();
251 for (int i = listSize - 1; i >= 0; i--) {
252 if (i > currentSequence - 1) {
253 flowsToExecute.remove(i);
255 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
256 if (flowName.contains("Assign")) {
257 flowName = "Unassign" + flowName.substring(6, flowName.length());
258 } else if (flowName.contains("Create")) {
259 flowName = "Delete" + flowName.substring(6, flowName.length());
260 } else if (flowName.contains("Activate")) {
261 flowName = "Deactivate" + flowName.substring(8, flowName.length());
265 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
266 rollbackFlows.add(flowsToExecute.get(i));
269 if (rollbackFlows.isEmpty())
270 execution.setVariable("isRollbackNeeded", false);
272 execution.setVariable("isRollbackNeeded", true);
273 execution.setVariable("flowsToExecute", rollbackFlows);
274 execution.setVariable("handlingCode", "PreformingRollback");
275 execution.setVariable("isRollback", true);
276 execution.setVariable("gCurrentSequence", 0);
277 execution.setVariable(RETRY_COUNT, 0);
279 workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
283 public void abortCallErrorHandling(DelegateExecution execution) {
284 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
286 throw new BpmnError(msg);
289 public void updateRequestStatusToFailed(DelegateExecution execution) {
291 String requestId = (String) execution.getVariable(G_REQUEST_ID);
292 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
293 String errorMsg = null;
294 boolean rollback = (boolean) execution.getVariable("isRollbackComplete");
296 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
297 if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
298 errorMsg = exception.getErrorMessage();
300 } catch (Exception ex) {
301 //log error and attempt to extact WorkflowExceptionMessage
302 logger.error("Failed to extract workflow exception from execution.",ex);
304 if (errorMsg == null){
306 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
307 } catch (Exception ex) {
308 logger.error("Failed to extract workflow exception message from WorkflowException",ex);
309 errorMsg = "Unexpected Error in BPMN.";
313 errorMsg = errorMsg + " + Rollback has been completed successfully.";
315 request.setProgress(Long.valueOf(100));
316 request.setStatusMessage(errorMsg);
317 request.setRequestStatus("FAILED");
318 request.setLastModifiedBy("CamundaBPMN");
319 requestDbclient.updateInfraActiveRequests(request);
320 } catch (Exception e) {
321 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
325 public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
326 execution.setVariable("isRollbackComplete", true);
327 updateRequestStatusToFailed(execution);