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.Date;
26 import java.util.List;
27 import java.util.Optional;
29 import org.camunda.bpm.engine.delegate.BpmnError;
30 import org.camunda.bpm.engine.delegate.DelegateExecution;
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.core.WorkflowException;
34 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
35 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
36 import org.onap.so.client.exception.ExceptionBuilder;
37 import org.onap.so.db.request.beans.InfraActiveRequests;
38 import org.onap.so.db.request.client.RequestsDbClient;
39 import org.onap.so.serviceinstancebeans.RequestReferences;
40 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.stereotype.Component;
46 import com.fasterxml.jackson.core.JsonProcessingException;
47 import com.fasterxml.jackson.databind.ObjectMapper;
50 public class WorkflowActionBBTasks {
52 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
53 private static final String G_REQUEST_ID = "mso-request-id";
54 private static final String G_ALACARTE = "aLaCarte";
55 private static final String G_ACTION = "requestAction";
56 private static final String RETRY_COUNT = "retryCount";
57 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
60 private RequestsDbClient requestDbclient;
62 private WorkflowAction workflowAction;
64 private WorkflowActionBBFailure workflowActionBBFailure;
66 public void selectBB(DelegateExecution execution) {
67 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
68 .getVariable("flowsToExecute");
69 execution.setVariable("MacroRollback", false);
70 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
71 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
72 boolean homing = (boolean) execution.getVariable("homing");
73 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
74 if (homing && !calledHoming) {
75 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
77 execution.setVariable("calledHoming", true);
82 execution.setVariable("buildingBlock", ebb);
84 if (currentSequence >= flowsToExecute.size()) {
85 execution.setVariable("completed", true);
87 execution.setVariable("completed", false);
88 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
92 public void updateFlowStatistics(DelegateExecution execution) {
94 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
95 if(currentSequence > 1) {
96 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
97 requestDbclient.updateInfraActiveRequests(request);
99 }catch (Exception ex){
100 logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
104 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
105 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
106 .getVariable("flowsToExecute");
107 String requestId = (String) execution.getVariable(G_REQUEST_ID);
108 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
109 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
110 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
111 int completedBBs = currentSequence - 1;
112 int totalBBs = flowsToExecute.size();
113 int remainingBBs = totalBBs - completedBBs;
114 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
115 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
116 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
117 request.setFlowStatus(statusMessage);
118 request.setProgress(percentProgress);
119 request.setLastModifiedBy("CamundaBPMN");
123 protected Long getPercentProgress(int completedBBs, int totalBBs) {
124 double ratio = (completedBBs / (totalBBs * 1.0));
125 int percentProgress = (int) (ratio * 95);
126 return new Long(percentProgress + 5);
129 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
130 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
131 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
135 public void sendSyncAck(DelegateExecution execution) {
136 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
137 final String resourceId = (String) execution.getVariable("resourceId");
138 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
139 RequestReferences requestRef = new RequestReferences();
140 requestRef.setInstanceId(resourceId);
141 requestRef.setRequestId(requestId);
142 serviceInstancesResponse.setRequestReferences(requestRef);
143 ObjectMapper mapper = new ObjectMapper();
144 String jsonRequest = "";
146 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
147 } catch (JsonProcessingException e) {
148 workflowAction.buildAndThrowException(execution,
149 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
151 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
152 callbackResponse.setStatusCode(200);
153 callbackResponse.setMessage("Success");
154 callbackResponse.setResponse(jsonRequest);
155 String processKey = execution.getProcessEngineServices().getRepositoryService()
156 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
157 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
159 logger.info("Successfully sent sync ack.");
162 public void sendErrorSyncAck(DelegateExecution execution) {
163 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
165 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
166 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
167 if (errorMsg == null) {
168 errorMsg = "WorkflowAction failed unexpectedly.";
170 String processKey = exceptionBuilder.getProcessKey(execution);
171 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
173 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
174 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
175 callbackResponse.setStatusCode(500);
176 callbackResponse.setMessage("Fail");
177 callbackResponse.setResponse(buildworkflowException);
178 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
180 execution.setVariable("sentSyncResponse", true);
181 } catch (Exception ex) {
182 logger.error(" Sending Sync Error Activity Failed. {}" , ex.getMessage(), ex);
186 public void updateRequestStatusToComplete(DelegateExecution execution) {
188 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
189 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
190 final String action = (String) execution.getVariable(G_ACTION);
191 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
192 final String resourceName = (String) execution.getVariable("resourceName");
193 String macroAction = "";
195 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
197 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
199 execution.setVariable("finalStatusMessage", macroAction);
200 Timestamp endTime = new Timestamp(System.currentTimeMillis());
201 request.setEndTime(endTime);
202 request.setFlowStatus("Successfully completed all Building Blocks");
203 request.setStatusMessage(macroAction);
204 request.setProgress(Long.valueOf(100));
205 request.setRequestStatus("COMPLETE");
206 request.setLastModifiedBy("CamundaBPMN");
207 requestDbclient.updateInfraActiveRequests(request);
208 }catch (Exception ex) {
209 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
213 public void checkRetryStatus(DelegateExecution execution) {
214 String handlingCode = (String) execution.getVariable("handlingCode");
215 String requestId = (String) execution.getVariable(G_REQUEST_ID);
216 String retryDuration = (String) execution.getVariable("RetryDuration");
217 int retryCount = (int) execution.getVariable(RETRY_COUNT);
218 int nextCount = retryCount +1;
219 if (handlingCode.equals("Retry")){
220 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
222 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
223 request.setRetryStatusMessage("Retry " + nextCount + "/5 will be started in " + retryDuration);
224 requestDbclient.updateInfraActiveRequests(request);
225 } catch(Exception ex){
226 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
229 int currSequence = (int) execution.getVariable("gCurrentSequence");
230 execution.setVariable("gCurrentSequence", currSequence-1);
231 execution.setVariable(RETRY_COUNT, nextCount);
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));
270 int flowSize = rollbackFlows.size();
271 String handlingCode = (String) execution.getVariable("handlingCode");
272 if(handlingCode.equals("RollbackToAssigned")){
273 for(int i = 0; i<flowSize; i++){
274 if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
275 rollbackFlows.remove(i);
280 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
282 if (rollbackFlows.isEmpty())
283 execution.setVariable("isRollbackNeeded", false);
285 execution.setVariable("isRollbackNeeded", true);
286 execution.setVariable("flowsToExecute", rollbackFlows);
287 execution.setVariable("handlingCode", "PreformingRollback");
288 execution.setVariable("isRollback", true);
289 execution.setVariable("gCurrentSequence", 0);
290 execution.setVariable(RETRY_COUNT, 0);
292 workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
296 protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
298 String requestId = (String) execution.getVariable(G_REQUEST_ID);
299 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
300 String errorMsg = retrieveErrorMessage(execution);
301 if(errorMsg == null || errorMsg.equals("")){
302 errorMsg = "Failed to determine error message";
304 request.setStatusMessage(errorMsg);
305 logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
306 requestDbclient.updateInfraActiveRequests(request);
307 } catch (Exception e) {
308 logger.error("Failed to update Request db with the status message after retry or rollback has been initialized.",e);
312 public void abortCallErrorHandling(DelegateExecution execution) {
313 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
315 throw new BpmnError(msg);
318 public void updateRequestStatusToFailed(DelegateExecution execution) {
320 String requestId = (String) execution.getVariable(G_REQUEST_ID);
321 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
322 String errorMsg = null;
323 String rollbackErrorMsg = null;
324 boolean rollbackCompleted = (boolean) execution.getVariable("isRollbackComplete");
325 boolean isRollbackFailure = (boolean) execution.getVariable("isRollback");
326 ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
328 if(rollbackCompleted){
329 rollbackErrorMsg = "Rollback has been completed successfully.";
330 request.setRollbackStatusMessage(rollbackErrorMsg);
331 logger.debug("Updating RequestDB to failed: Rollback has been completed successfully");
333 if(isRollbackFailure){
334 rollbackErrorMsg = retrieveErrorMessage(execution);
335 if(rollbackErrorMsg == null || rollbackErrorMsg.equals("")){
336 rollbackErrorMsg = "Failed to determine rollback error message.";
338 request.setRollbackStatusMessage(rollbackErrorMsg);
339 logger.debug("Updating RequestDB to failed: rollbackErrorMsg = " + rollbackErrorMsg);
341 errorMsg = retrieveErrorMessage(execution);
342 if(errorMsg == null || errorMsg.equals("")){
343 errorMsg = "Failed to determine error message";
345 request.setStatusMessage(errorMsg);
346 logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
349 if(ebb!=null && ebb.getBuildingBlock()!=null){
350 String flowStatus = ebb.getBuildingBlock().getBpmnFlowName() + " has failed.";
351 request.setFlowStatus(flowStatus);
352 execution.setVariable("flowStatus", flowStatus);
355 request.setProgress(Long.valueOf(100));
356 request.setRequestStatus("FAILED");
357 request.setLastModifiedBy("CamundaBPMN");
358 requestDbclient.updateInfraActiveRequests(request);
359 } catch (Exception e) {
360 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
364 private String retrieveErrorMessage (DelegateExecution execution){
365 String errorMsg = "";
367 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
368 if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
369 errorMsg = exception.getErrorMessage();
371 } catch (Exception ex) {
372 //log error and attempt to extact WorkflowExceptionMessage
373 logger.error("Failed to extract workflow exception from execution.",ex);
376 if (errorMsg == null || errorMsg.equals("")){
378 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
379 } catch (Exception ex) {
380 logger.error("Failed to extract workflow exception message from WorkflowException",ex);
381 errorMsg = "Unexpected Error in BPMN.";
387 public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
388 execution.setVariable("isRollbackComplete", true);
389 updateRequestStatusToFailed(execution);