2e91a52f658452acfa5909084481466c90462d8c
[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.sql.Timestamp;
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.List;
27 import java.util.Optional;
28
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;
46
47 import com.fasterxml.jackson.core.JsonProcessingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 @Component
51 public class WorkflowActionBBTasks {
52
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);
60
61         @Autowired
62         private RequestsDbClient requestDbclient;
63         @Autowired
64         private WorkflowAction workflowAction;
65         @Autowired
66         private WorkflowActionBBFailure workflowActionBBFailure;
67         @Autowired
68         private Environment environment;
69         
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")) {
80                                 ebb.setHoming(true);
81                                 execution.setVariable("calledHoming", true);
82                         }
83                 } else {
84                         ebb.setHoming(false);
85                 }
86                 execution.setVariable("buildingBlock", ebb);
87                 currentSequence++;
88                 if (currentSequence >= flowsToExecute.size()) {
89                         execution.setVariable("completed", true);
90                 } else {
91                         execution.setVariable("completed", false);
92                 }
93                 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
94         }
95         
96         public void updateFlowStatistics(DelegateExecution execution) {
97                 try{
98                         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
99                         if(currentSequence > 1) {
100                                 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
101                                 requestDbclient.updateInfraActiveRequests(request);
102                         }
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.");
105                 }
106         }
107
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");
124                 return request;
125         }
126         
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);
131         }
132         
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
136                                 + ").";
137         }
138
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 = "";
149                 try {
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);
154                 }
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,
162                                 callbackResponse);
163                 logger.info("Successfully sent sync ack.");
164         }
165
166         public void sendErrorSyncAck(DelegateExecution execution) {
167                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
168                 try {
169                         ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
170                         String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
171                         if (errorMsg == null) {
172                                 errorMsg = "WorkflowAction failed unexpectedly.";
173                         }
174                         String processKey = exceptionBuilder.getProcessKey(execution);
175                         String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
176                                         + errorMsg
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,
183                                         callbackResponse);
184                         execution.setVariable("sentSyncResponse", true);
185                 } catch (Exception ex) {
186                         logger.error(" Sending Sync Error Activity Failed. {}"  , ex.getMessage(), ex);
187                 }
188         }
189
190         public void updateRequestStatusToComplete(DelegateExecution execution) {
191                 try{
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 = "";
198                         if (aLaCarte) {
199                                 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
200                         } else {
201                                 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
202                         }
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);
214                 }
215         }
216
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);
222                 int envMaxRetries;
223                 try{
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");
227                         envMaxRetries = 5;
228                 }
229                 int nextCount = retryCount +1;
230                 if (handlingCode.equals("Retry")){
231                         workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
232                         try{
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);
238                         }
239                         if(retryCount<envMaxRetries){
240                                 int currSequence = (int) execution.getVariable("gCurrentSequence");
241                                 execution.setVariable("gCurrentSequence", currSequence-1);
242                                 execution.setVariable(RETRY_COUNT, nextCount);
243                         }else{
244                                 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
245                         }
246                 }else{
247                         execution.setVariable(RETRY_COUNT, 0);
248                 }
249         }
250
251         /**
252          * Rollback will only handle Create/Activate/Assign Macro flows. Execute
253          * layer will rollback the flow its currently working on.
254          */
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);
265                                 } else {
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());
273                                         }else{
274                                                 continue;
275                                         }
276                                         flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
277                                         rollbackFlows.add(flowsToExecute.get(i));
278                                 }
279                         }
280                         
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);
287                                         }
288                                 }
289                         }
290                         
291                         workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
292                         
293                         if (rollbackFlows.isEmpty())
294                                 execution.setVariable("isRollbackNeeded", false);
295                         else
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);
302                 }else{
303                         workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
304                 }
305         }
306
307         protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
308                 try {
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";
314                         }
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);
320                 }
321         }
322
323         public void abortCallErrorHandling(DelegateExecution execution) {
324                 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
325                 logger.error(msg);
326                 throw new BpmnError(msg);
327         }
328         
329         public void updateRequestStatusToFailed(DelegateExecution execution) {
330                 try {
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");
338                         
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");
343                         }else{
344                                 if(isRollbackFailure){
345                                         rollbackErrorMsg = retrieveErrorMessage(execution);
346                                         if(rollbackErrorMsg == null || rollbackErrorMsg.equals("")){
347                                                 rollbackErrorMsg = "Failed to determine rollback error message.";
348                                         }
349                                         request.setRollbackStatusMessage(rollbackErrorMsg);
350                                         logger.debug("Updating RequestDB to failed: rollbackErrorMsg = " + rollbackErrorMsg);
351                                 }else{
352                                         errorMsg = retrieveErrorMessage(execution);
353                                         if(errorMsg == null || errorMsg.equals("")){
354                                                 errorMsg = "Failed to determine error message";
355                                         }
356                                         request.setStatusMessage(errorMsg);
357                                         logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
358                                 }
359                         }
360                         if(ebb!=null && ebb.getBuildingBlock()!=null){
361                                 String flowStatus = ebb.getBuildingBlock().getBpmnFlowName() + " has failed.";
362                                 request.setFlowStatus(flowStatus);
363                                 execution.setVariable("flowStatus", flowStatus);
364                         }
365
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);
372                 }
373         }
374         
375         private String retrieveErrorMessage (DelegateExecution execution){
376                 String errorMsg = "";
377                 try {
378                         WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
379                         if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
380                                 errorMsg = exception.getErrorMessage();
381                         }
382                 } catch (Exception ex) {
383                         //log error and attempt to extact WorkflowExceptionMessage
384                         logger.error("Failed to extract workflow exception from execution.",ex);
385                 }
386                 
387                 if (errorMsg == null || errorMsg.equals("")){
388                         try {
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.";
393                         }
394                 }
395                 return errorMsg;
396         }
397         
398         public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
399                 execution.setVariable("isRollbackComplete", true);
400                 updateRequestStatusToFailed(execution);
401         }
402 }