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.core.env.Environment;
45 import org.springframework.stereotype.Component;
47 import com.fasterxml.jackson.core.JsonProcessingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
51 public class WorkflowActionBBTasks {
53 private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
54 private static final String G_REQUEST_ID = "mso-request-id";
55 private static final String G_ALACARTE = "aLaCarte";
56 private static final String G_ACTION = "requestAction";
57 private static final String RETRY_COUNT = "retryCount";
58 protected String maxRetries = "mso.rainyDay.maxRetries";
59 private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
62 private RequestsDbClient requestDbclient;
64 private WorkflowAction workflowAction;
66 private WorkflowActionBBFailure workflowActionBBFailure;
68 private Environment environment;
70 public void selectBB(DelegateExecution execution) {
71 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
72 .getVariable("flowsToExecute");
73 execution.setVariable("MacroRollback", false);
74 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
75 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
76 boolean homing = (boolean) execution.getVariable("homing");
77 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
78 if (homing && !calledHoming) {
79 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
81 execution.setVariable("calledHoming", true);
86 execution.setVariable("buildingBlock", ebb);
88 if (currentSequence >= flowsToExecute.size()) {
89 execution.setVariable("completed", true);
91 execution.setVariable("completed", false);
93 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
96 public void updateFlowStatistics(DelegateExecution execution) {
98 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
99 if(currentSequence > 1) {
100 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
101 requestDbclient.updateInfraActiveRequests(request);
103 }catch (Exception ex){
104 logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
108 protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
109 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
110 .getVariable("flowsToExecute");
111 String requestId = (String) execution.getVariable(G_REQUEST_ID);
112 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
113 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
114 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
115 int completedBBs = currentSequence - 1;
116 int totalBBs = flowsToExecute.size();
117 int remainingBBs = totalBBs - completedBBs;
118 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
119 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
120 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
121 request.setFlowStatus(statusMessage);
122 request.setProgress(percentProgress);
123 request.setLastModifiedBy("CamundaBPMN");
127 protected Long getPercentProgress(int completedBBs, int totalBBs) {
128 double ratio = (completedBBs / (totalBBs * 1.0));
129 int percentProgress = (int) (ratio * 95);
130 return new Long(percentProgress + 5);
133 protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
134 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
135 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
139 public void sendSyncAck(DelegateExecution execution) {
140 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
141 final String resourceId = (String) execution.getVariable("resourceId");
142 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
143 RequestReferences requestRef = new RequestReferences();
144 requestRef.setInstanceId(resourceId);
145 requestRef.setRequestId(requestId);
146 serviceInstancesResponse.setRequestReferences(requestRef);
147 ObjectMapper mapper = new ObjectMapper();
148 String jsonRequest = "";
150 jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
151 } catch (JsonProcessingException e) {
152 workflowAction.buildAndThrowException(execution,
153 "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
155 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
156 callbackResponse.setStatusCode(200);
157 callbackResponse.setMessage("Success");
158 callbackResponse.setResponse(jsonRequest);
159 String processKey = execution.getProcessEngineServices().getRepositoryService()
160 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
161 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
163 logger.info("Successfully sent sync ack.");
166 public void sendErrorSyncAck(DelegateExecution execution) {
167 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
169 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
170 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
171 if (errorMsg == null) {
172 errorMsg = "WorkflowAction failed unexpectedly.";
174 String processKey = exceptionBuilder.getProcessKey(execution);
175 String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
177 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
178 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
179 callbackResponse.setStatusCode(500);
180 callbackResponse.setMessage("Fail");
181 callbackResponse.setResponse(buildworkflowException);
182 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
184 execution.setVariable("sentSyncResponse", true);
185 } catch (Exception ex) {
186 logger.error(" Sending Sync Error Activity Failed. {}" , ex.getMessage(), ex);
190 public void updateRequestStatusToComplete(DelegateExecution execution) {
192 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
193 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
194 final String action = (String) execution.getVariable(G_ACTION);
195 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
196 final String resourceName = (String) execution.getVariable("resourceName");
197 String macroAction = "";
199 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
201 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
203 execution.setVariable("finalStatusMessage", macroAction);
204 Timestamp endTime = new Timestamp(System.currentTimeMillis());
205 request.setEndTime(endTime);
206 request.setFlowStatus("Successfully completed all Building Blocks");
207 request.setStatusMessage(macroAction);
208 request.setProgress(Long.valueOf(100));
209 request.setRequestStatus("COMPLETE");
210 request.setLastModifiedBy("CamundaBPMN");
211 requestDbclient.updateInfraActiveRequests(request);
212 }catch (Exception ex) {
213 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
217 public void checkRetryStatus(DelegateExecution execution) {
218 String handlingCode = (String) execution.getVariable("handlingCode");
219 String requestId = (String) execution.getVariable(G_REQUEST_ID);
220 String retryDuration = (String) execution.getVariable("RetryDuration");
221 int retryCount = (int) execution.getVariable(RETRY_COUNT);
224 envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
225 } catch (Exception ex) {
226 logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
229 int nextCount = retryCount +1;
230 if (handlingCode.equals("Retry")){
231 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
233 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
234 request.setRetryStatusMessage("Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
235 requestDbclient.updateInfraActiveRequests(request);
236 } catch(Exception ex){
237 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
239 if(retryCount<envMaxRetries){
240 int currSequence = (int) execution.getVariable("gCurrentSequence");
241 execution.setVariable("gCurrentSequence", currSequence-1);
242 execution.setVariable(RETRY_COUNT, nextCount);
244 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
247 execution.setVariable(RETRY_COUNT, 0);
252 * Rollback will only handle Create/Activate/Assign Macro flows. Execute
253 * layer will rollback the flow its currently working on.
255 public void rollbackExecutionPath(DelegateExecution execution) {
256 if(!(boolean)execution.getVariable("isRollback")){
257 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
258 .getVariable("flowsToExecute");
259 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
260 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
261 int listSize = flowsToExecute.size();
262 for (int i = listSize - 1; i >= 0; i--) {
263 if (i > currentSequence - 1) {
264 flowsToExecute.remove(i);
266 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
267 if (flowName.contains("Assign")) {
268 flowName = "Unassign" + flowName.substring(6, flowName.length());
269 } else if (flowName.contains("Create")) {
270 flowName = "Delete" + flowName.substring(6, flowName.length());
271 } else if (flowName.contains("Activate")) {
272 flowName = "Deactivate" + flowName.substring(8, flowName.length());
276 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
277 rollbackFlows.add(flowsToExecute.get(i));
281 int flowSize = rollbackFlows.size();
282 String handlingCode = (String) execution.getVariable("handlingCode");
283 if(handlingCode.equals("RollbackToAssigned")){
284 for(int i = 0; i<flowSize; i++){
285 if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
286 rollbackFlows.remove(i);
291 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
293 if (rollbackFlows.isEmpty())
294 execution.setVariable("isRollbackNeeded", false);
296 execution.setVariable("isRollbackNeeded", true);
297 execution.setVariable("flowsToExecute", rollbackFlows);
298 execution.setVariable("handlingCode", "PreformingRollback");
299 execution.setVariable("isRollback", true);
300 execution.setVariable("gCurrentSequence", 0);
301 execution.setVariable(RETRY_COUNT, 0);
303 workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
307 protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
309 String requestId = (String) execution.getVariable(G_REQUEST_ID);
310 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
311 String errorMsg = retrieveErrorMessage(execution);
312 if(errorMsg == null || errorMsg.equals("")){
313 errorMsg = "Failed to determine error message";
315 request.setStatusMessage(errorMsg);
316 logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
317 requestDbclient.updateInfraActiveRequests(request);
318 } catch (Exception e) {
319 logger.error("Failed to update Request db with the status message after retry or rollback has been initialized.",e);
323 public void abortCallErrorHandling(DelegateExecution execution) {
324 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
326 throw new BpmnError(msg);
329 public void updateRequestStatusToFailed(DelegateExecution execution) {
331 String requestId = (String) execution.getVariable(G_REQUEST_ID);
332 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
333 String errorMsg = null;
334 String rollbackErrorMsg = null;
335 boolean rollbackCompleted = (boolean) execution.getVariable("isRollbackComplete");
336 boolean isRollbackFailure = (boolean) execution.getVariable("isRollback");
337 ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock");
339 if(rollbackCompleted){
340 rollbackErrorMsg = "Rollback has been completed successfully.";
341 request.setRollbackStatusMessage(rollbackErrorMsg);
342 logger.debug("Updating RequestDB to failed: Rollback has been completed successfully");
344 if(isRollbackFailure){
345 rollbackErrorMsg = retrieveErrorMessage(execution);
346 if(rollbackErrorMsg == null || rollbackErrorMsg.equals("")){
347 rollbackErrorMsg = "Failed to determine rollback error message.";
349 request.setRollbackStatusMessage(rollbackErrorMsg);
350 logger.debug("Updating RequestDB to failed: rollbackErrorMsg = " + rollbackErrorMsg);
352 errorMsg = retrieveErrorMessage(execution);
353 if(errorMsg == null || errorMsg.equals("")){
354 errorMsg = "Failed to determine error message";
356 request.setStatusMessage(errorMsg);
357 logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
360 if(ebb!=null && ebb.getBuildingBlock()!=null){
361 String flowStatus = ebb.getBuildingBlock().getBpmnFlowName() + " has failed.";
362 request.setFlowStatus(flowStatus);
363 execution.setVariable("flowStatus", flowStatus);
366 request.setProgress(Long.valueOf(100));
367 request.setRequestStatus("FAILED");
368 request.setLastModifiedBy("CamundaBPMN");
369 requestDbclient.updateInfraActiveRequests(request);
370 } catch (Exception e) {
371 workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
375 private String retrieveErrorMessage (DelegateExecution execution){
376 String errorMsg = "";
378 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
379 if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
380 errorMsg = exception.getErrorMessage();
382 } catch (Exception ex) {
383 //log error and attempt to extact WorkflowExceptionMessage
384 logger.error("Failed to extract workflow exception from execution.",ex);
387 if (errorMsg == null || errorMsg.equals("")){
389 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
390 } catch (Exception ex) {
391 logger.error("Failed to extract workflow exception message from WorkflowException",ex);
392 errorMsg = "Unexpected Error in BPMN.";
398 public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
399 execution.setVariable("isRollbackComplete", true);
400 updateRequestStatusToFailed(execution);