Springboot 2.0 upgrade
[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 String RETRY_COUNT = "retryCount";
54         private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
55
56         @Autowired
57         private RequestsDbClient requestDbclient;
58         @Autowired
59         private WorkflowAction workflowAction;
60         
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")) {
71                                 ebb.setHoming(true);
72                                 execution.setVariable("calledHoming", true);
73                         }
74                 } else {
75                         ebb.setHoming(false);
76                 }
77                 execution.setVariable("buildingBlock", ebb);
78                 currentSequence++;
79                 if (currentSequence >= flowsToExecute.size()) {
80                         execution.setVariable("completed", true);
81                 } else {
82                         execution.setVariable("completed", false);
83                         execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
84                 }
85         }
86         
87         public void updateFlowStatistics(DelegateExecution execution) {
88                 try{
89                         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
90                         if(currentSequence > 1) {
91                                 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
92                                 requestDbclient.updateInfraActiveRequests(request);
93                         }
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.");
96                 }
97         }
98
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");
115                 return request;
116         }
117         
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);
122         }
123         
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
127                                 + ").";
128         }
129
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 = "";
140                 try {
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);
145                 }
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,
153                                 callbackResponse);
154                 logger.info("Successfully sent sync ack.");
155         }
156
157         public void sendErrorSyncAck(DelegateExecution execution) {
158                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
159                 try {
160                         ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
161                         String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
162                         if (errorMsg == null) {
163                                 errorMsg = "WorkflowAction failed unexpectedly.";
164                         }
165                         String processKey = exceptionBuilder.getProcessKey(execution);
166                         String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
167                                         + errorMsg
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,
174                                         callbackResponse);
175                         execution.setVariable("sentSyncResponse", true);
176                 } catch (Exception ex) {
177                         logger.error(" Sending Sync Error Activity Failed. {}"  , ex.getMessage(), ex);
178                 }
179         }
180
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 = "";
189                 if (aLaCarte) {
190                         macroAction = "ALaCarte-" + resourceName + "-" + action;
191                 } else {
192                         macroAction = "Macro-" + resourceName + "-" + action;
193                 }
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);
202         }
203
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");
211                 } else {
212                         exceptionMsg = "Error in WorkflowAction";
213                 }
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>"
219                                 + exceptionMsg
220                                 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
221                 execution.setVariable("falloutRequest", falloutRequest);
222         }
223
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")){
228                         if(retryCount<5){
229                                 int currSequence = (int) execution.getVariable("gCurrentSequence");
230                                 execution.setVariable("gCurrentSequence", currSequence-1);
231                                 execution.setVariable(RETRY_COUNT, retryCount + 1);
232                         }else{
233                                 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
234                         }
235                 }else{
236                         execution.setVariable(RETRY_COUNT, 0);
237                 }
238         }
239
240         /**
241          * Rollback will only handle Create/Activate/Assign Macro flows. Execute
242          * layer will rollback the flow its currently working on.
243          */
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);
254                                 } else {
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());
262                                         }else{
263                                                 continue;
264                                         }
265                                         flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
266                                         rollbackFlows.add(flowsToExecute.get(i));
267                                 }
268                         }
269                         if (rollbackFlows.isEmpty())
270                                 execution.setVariable("isRollbackNeeded", false);
271                         else
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);
278                 }else{
279                         workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
280                 }
281         }
282
283         public void abortCallErrorHandling(DelegateExecution execution) {
284                 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
285                 logger.error(msg);
286                 throw new BpmnError(msg);
287         }
288
289         public void updateRequestStatusToFailed(DelegateExecution execution) {
290                 try {
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");
295                         try {
296                                 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
297                                 if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
298                                         errorMsg = exception.getErrorMessage();
299                                 }
300                         } catch (Exception ex) {
301                                 //log error and attempt to extact WorkflowExceptionMessage
302                                 logger.error("Failed to extract workflow exception from execution.",ex);
303                         }
304                         if (errorMsg == null){
305                                 try {
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.";
310                                 }
311                         }
312                         if(rollback){
313                                 errorMsg = errorMsg + " + Rollback has been completed successfully.";
314                         }
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);
322                 }
323         }
324         
325         public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
326                 execution.setVariable("isRollbackComplete", true);
327                 updateRequestStatusToFailed(execution);
328         }
329 }