9e4b01eea5db1c6bce136aace878be1eae96fdf5
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / workflow / tasks / WorkflowActionBBTasks.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
22
23 import java.util.ArrayList;
24 import java.util.List;
25
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;
42
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45
46 @Component
47 public class WorkflowActionBBTasks {
48
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 Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
54
55         @Autowired
56         private RequestsDbClient requestDbclient;
57         @Autowired
58         private WorkflowAction workflowAction;
59         
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")) {
70                                 ebb.setHoming(true);
71                                 execution.setVariable("calledHoming", true);
72                         }
73                 } else {
74                         ebb.setHoming(false);
75                 }
76                 execution.setVariable("buildingBlock", ebb);
77                 currentSequence++;
78                 if (currentSequence >= flowsToExecute.size()) {
79                         execution.setVariable("completed", true);
80                 } else {
81                         execution.setVariable("completed", false);
82                         execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
83                 }
84         }
85         
86         public void updateFlowStatistics(DelegateExecution execution) {
87                 try{
88                         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
89                         if(currentSequence > 1) {
90                                 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
91                                 requestDbclient.updateInfraActiveRequests(request);
92                         }
93                 }catch (Exception ex){
94                         logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
95                 }
96         }
97
98         protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
99                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
100                                 .getVariable("flowsToExecute");
101                 String requestId = (String) execution.getVariable(G_REQUEST_ID);
102                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
103                 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
104                 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
105                 int completedBBs = currentSequence - 1;
106                 int totalBBs = flowsToExecute.size();
107                 int remainingBBs = totalBBs - completedBBs;
108                 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(), 
109                                 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
110                 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
111                 request.setStatusMessage(statusMessage);
112                 request.setProgress(percentProgress);
113                 request.setLastModifiedBy("CamundaBPMN");
114                 return request;
115         }
116         
117         protected Long getPercentProgress(int completedBBs, int totalBBs) {
118                 double ratio = (completedBBs / (totalBBs * 1.0));
119                 int percentProgress = (int) (ratio * 95);
120                 return new Long(percentProgress + 5);
121         }
122         
123         protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
124                 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
125                                 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
126                                 + ").";
127         }
128
129         public void sendSyncAck(DelegateExecution execution) {
130                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
131                 final String resourceId = (String) execution.getVariable("resourceId");
132                 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
133                 RequestReferences requestRef = new RequestReferences();
134                 requestRef.setInstanceId(resourceId);
135                 requestRef.setRequestId(requestId);
136                 serviceInstancesResponse.setRequestReferences(requestRef);
137                 ObjectMapper mapper = new ObjectMapper();
138                 String jsonRequest = "";
139                 try {
140                         jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
141                 } catch (JsonProcessingException e) {
142                         workflowAction.buildAndThrowException(execution,
143                                         "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
144                 }
145                 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
146                 callbackResponse.setStatusCode(200);
147                 callbackResponse.setMessage("Success");
148                 callbackResponse.setResponse(jsonRequest);
149                 String processKey = execution.getProcessEngineServices().getRepositoryService()
150                                 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
151                 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
152                                 callbackResponse);
153                 logger.info("Successfully sent sync ack.");
154         }
155
156         public void sendErrorSyncAck(DelegateExecution execution) {
157                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
158                 try {
159                         ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
160                         String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
161                         if (errorMsg == null) {
162                                 errorMsg = "WorkflowAction failed unexpectedly.";
163                         }
164                         String processKey = exceptionBuilder.getProcessKey(execution);
165                         String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
166                                         + errorMsg
167                                         + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
168                         WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
169                         callbackResponse.setStatusCode(500);
170                         callbackResponse.setMessage("Fail");
171                         callbackResponse.setResponse(buildworkflowException);
172                         WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
173                                         callbackResponse);
174                         execution.setVariable("sentSyncResponse", true);
175                 } catch (Exception ex) {
176                         logger.error(" Sending Sync Error Activity Failed. {}"  , ex.getMessage(), ex);
177                 }
178         }
179
180         public void setupCompleteMsoProcess(DelegateExecution execution) {
181                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
182                 final String action = (String) execution.getVariable(G_ACTION);
183                 final String resourceId = (String) execution.getVariable("resourceId");
184                 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
185                 final String resourceName = (String) execution.getVariable("resourceName");
186                 final String source = (String) execution.getVariable("source");
187                 String macroAction = "";
188                 if (aLaCarte) {
189                         macroAction = "ALaCarte-" + resourceName + "-" + action;
190                 } else {
191                         macroAction = "Macro-" + resourceName + "-" + action;
192                 }
193                 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>"
194                                 + requestId + "</request-id><action>" + action + "</action><source>" + source
195                                 + "</source></request-info><status-message>" + macroAction
196                                 + " request was executed correctly.</status-message><serviceInstanceId>" + resourceId
197                                 + "</serviceInstanceId><mso-bpel-name>WorkflowActionBB</mso-bpel-name></aetgt:MsoCompletionRequest>";
198                 execution.setVariable("CompleteMsoProcessRequest", msoCompletionRequest);
199                 execution.setVariable("mso-request-id", requestId);
200                 execution.setVariable("mso-service-instance-id", resourceId);
201         }
202
203         public void setupFalloutHandler(DelegateExecution execution) {
204                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
205                 final String action = (String) execution.getVariable(G_ACTION);
206                 final String resourceId = (String) execution.getVariable("resourceId");
207                 String exceptionMsg = "";
208                 if (execution.getVariable("WorkflowActionErrorMessage") != null) {
209                         exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
210                 } else {
211                         exceptionMsg = "Error in WorkflowAction";
212                 }
213                 execution.setVariable("mso-service-instance-id", resourceId);
214                 execution.setVariable("mso-request-id", requestId);
215                 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>"
216                                 + requestId + "</request-id><action>" + action
217                                 + "</action><source>VID</source></request-info><aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
218                                 + exceptionMsg
219                                 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
220                 execution.setVariable("falloutRequest", falloutRequest);
221         }
222
223         public void checkRetryStatus(DelegateExecution execution) {
224                 if (execution.getVariable("handlingCode") == "Retry") {
225                         int currSequence = (int) execution.getVariable("gCurrentSequence");
226                         currSequence--;
227                         execution.setVariable("gCurrentSequence", currSequence);
228                         int currRetryCount = (int) execution.getVariable("retryCount");
229                         currRetryCount++;
230                         execution.setVariable("retryCount", currRetryCount);
231                 }
232         }
233
234         /**
235          * Rollback will only handle Create/Activate/Assign Macro flows. Execute
236          * layer will rollback the flow its currently working on.
237          */
238         public void rollbackExecutionPath(DelegateExecution execution) {
239                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
240                                 .getVariable("flowsToExecute");
241                 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
242                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE) - 1;
243                 for (int i = flowsToExecute.size() - 1; i >= 0; i--) {
244                         if (i >= currentSequence) {
245                                 flowsToExecute.remove(i);
246                         } else {
247                                 ExecuteBuildingBlock ebb = flowsToExecute.get(i);
248                                 BuildingBlock bb = flowsToExecute.get(i).getBuildingBlock();
249                                 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
250                                 if (flowName.contains("Assign")) {
251                                         flowName = "Unassign" + flowName.substring(7, flowName.length());
252                                 } else if (flowName.contains("Create")) {
253                                         flowName = "Delete" + flowName.substring(6, flowName.length());
254                                 } else if (flowName.contains("Activate")) {
255                                         flowName = "Deactivate" + flowName.substring(8, flowName.length());
256                                 }
257                                 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
258                                 rollbackFlows.add(flowsToExecute.get(i));
259                         }
260                 }
261                 if (rollbackFlows.isEmpty())
262                         execution.setVariable("isRollbackNeeded", false);
263                 else
264                         execution.setVariable("isRollbackNeeded", true);
265
266                 execution.setVariable("flowsToExecute", rollbackFlows);
267                 execution.setVariable("handlingCode", "PreformingRollback");
268         }
269
270         public void abortCallErrorHandling(DelegateExecution execution) {
271                 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
272                 logger.error(msg);
273                 throw new BpmnError(msg);
274         }
275
276         public void updateRequestStatusToFailed(DelegateExecution execution) {
277                 try {
278                         String requestId = (String) execution.getVariable(G_REQUEST_ID);
279                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
280                         String errorMsg = null;
281                         try {
282                                 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
283                                 request.setStatusMessage(exception.getErrorMessage());
284                         } catch (Exception ex) {
285                                 //log error and attempt to extact WorkflowExceptionMessage
286                                 logger.error("Failed to extract workflow exception from execution.",ex);
287                         }
288                         if (errorMsg == null){
289                                 try {
290                                         errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
291                                         request.setStatusMessage(errorMsg);
292                                 } catch (Exception ex) {
293                                         logger.error("Failed to extract workflow exception message from WorkflowException",ex);
294                                         request.setStatusMessage("Unexpected Error in BPMN");
295                                 }
296                         }
297                         request.setRequestStatus("FAILED");
298                         request.setLastModifiedBy("CamundaBPMN");
299                         requestDbclient.updateInfraActiveRequests(request);
300                 } catch (Exception e) {
301                         workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
302                 }
303         }
304 }