7670e0245da5323ec171d9829dc052a7af4708dd
[so.git] /
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.setFlowStatus(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 checkRetryStatus(DelegateExecution execution) {
205                 String handlingCode = (String) execution.getVariable("handlingCode");
206                 String requestId = (String) execution.getVariable(G_REQUEST_ID);
207                 String retryDuration = (String) execution.getVariable("RetryDuration");
208                 int retryCount = (int) execution.getVariable(RETRY_COUNT);
209                 if (handlingCode.equals("Retry")){
210                         updateRequestErrorStatusMessage(execution);
211                         try{
212                                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
213                                 request.setRetryStatusMessage("Retry " + retryCount+1 + "/5 will be started in " + retryDuration);
214                                 requestDbclient.updateInfraActiveRequests(request); 
215                         } catch(Exception ex){
216                                 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
217                         }
218                         if(retryCount<5){
219                                 int currSequence = (int) execution.getVariable("gCurrentSequence");
220                                 execution.setVariable("gCurrentSequence", currSequence-1);
221                                 execution.setVariable(RETRY_COUNT, retryCount + 1);
222                         }else{
223                                 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
224                         }
225                 }else{
226                         execution.setVariable(RETRY_COUNT, 0);
227                 }
228         }
229
230         /**
231          * Rollback will only handle Create/Activate/Assign Macro flows. Execute
232          * layer will rollback the flow its currently working on.
233          */
234         public void rollbackExecutionPath(DelegateExecution execution) {
235                 if(!(boolean)execution.getVariable("isRollback")){
236                         List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
237                                         .getVariable("flowsToExecute");
238                         List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
239                         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
240                         int listSize = flowsToExecute.size();
241                         for (int i = listSize - 1; i >= 0; i--) {
242                                 if (i > currentSequence - 1) {
243                                         flowsToExecute.remove(i);
244                                 } else {
245                                         String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
246                                         if (flowName.contains("Assign")) {
247                                                 flowName = "Unassign" + flowName.substring(6, flowName.length());
248                                         } else if (flowName.contains("Create")) {
249                                                 flowName = "Delete" + flowName.substring(6, flowName.length());
250                                         } else if (flowName.contains("Activate")) {
251                                                 flowName = "Deactivate" + flowName.substring(8, flowName.length());
252                                         }else{
253                                                 continue;
254                                         }
255                                         flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
256                                         rollbackFlows.add(flowsToExecute.get(i));
257                                 }
258                         }
259                         
260                         int flowSize = rollbackFlows.size();
261                         String handlingCode = (String) execution.getVariable("handlingCode");
262                         if(handlingCode.equals("RollbackToAssigned")){
263                                 for(int i = 0; i<flowSize -1; i++){
264                                         if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
265                                                 rollbackFlows.remove(i);
266                                         }
267                                 }
268                         }
269                         
270                         updateRequestErrorStatusMessage(execution);
271                         
272                         if (rollbackFlows.isEmpty())
273                                 execution.setVariable("isRollbackNeeded", false);
274                         else
275                                 execution.setVariable("isRollbackNeeded", true);
276                         execution.setVariable("flowsToExecute", rollbackFlows);
277                         execution.setVariable("handlingCode", "PreformingRollback");
278                         execution.setVariable("isRollback", true);
279                         execution.setVariable("gCurrentSequence", 0);
280                         execution.setVariable(RETRY_COUNT, 0);
281                 }else{
282                         workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
283                 }
284         }
285
286         protected void updateRequestErrorStatusMessage(DelegateExecution execution) {
287                 try {
288                         String requestId = (String) execution.getVariable(G_REQUEST_ID);
289                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
290                         String errorMsg = retrieveErrorMessage(execution);
291                         if(errorMsg == null || errorMsg.equals("")){
292                                 errorMsg = "Failed to determine error message";
293                         }
294                         request.setStatusMessage(errorMsg);
295                         logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
296                         requestDbclient.updateInfraActiveRequests(request);
297                 } catch (Exception e) {
298                         logger.error("Failed to update Request db with the status message after retry or rollback has been initialized.",e);
299                 }
300         }
301
302         public void abortCallErrorHandling(DelegateExecution execution) {
303                 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
304                 logger.error(msg);
305                 throw new BpmnError(msg);
306         }
307         
308         public void updateRequestStatusToFailed(DelegateExecution execution) {
309                 try {
310                         String requestId = (String) execution.getVariable(G_REQUEST_ID);
311                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
312                         String errorMsg = null;
313                         String rollbackErrorMsg = null;
314                         Boolean rollbackCompleted = (Boolean) execution.getVariable("isRollbackComplete");
315                         Boolean isRollbackFailure = (Boolean) execution.getVariable("isRollback");
316                         
317                         if(rollbackCompleted==null)
318                                 rollbackCompleted = false;
319                         
320                         if(isRollbackFailure==null)
321                                 isRollbackFailure = false;
322                         
323                         if(rollbackCompleted){
324                                 rollbackErrorMsg = "Rollback has been completed successfully.";
325                                 request.setRollbackStatusMessage(rollbackErrorMsg);
326                                 logger.debug("Updating RequestDB to failed: Rollback has been completed successfully");
327                         }else{
328                                 if(isRollbackFailure){
329                                         rollbackErrorMsg = retrieveErrorMessage(execution);
330                                         if(rollbackErrorMsg == null || rollbackErrorMsg.equals("")){
331                                                 rollbackErrorMsg = "Failed to determine rollback error message.";
332                                         }
333                                         request.setRollbackStatusMessage(rollbackErrorMsg);
334                                         logger.debug("Updating RequestDB to failed: rollbackErrorMsg = " + rollbackErrorMsg);
335                                 }else{
336                                         errorMsg = retrieveErrorMessage(execution);
337                                         if(errorMsg == null || errorMsg.equals("")){
338                                                 errorMsg = "Failed to determine error message";
339                                         }
340                                         request.setStatusMessage(errorMsg);
341                                         logger.debug("Updating RequestDB to failed: errorMsg = " + errorMsg);
342                                 }
343                         }
344                         request.setProgress(Long.valueOf(100));
345                         request.setRequestStatus("FAILED");
346                         request.setLastModifiedBy("CamundaBPMN");
347                         requestDbclient.updateInfraActiveRequests(request);
348                 } catch (Exception e) {
349                         workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
350                 }
351         }
352         
353         private String retrieveErrorMessage (DelegateExecution execution){
354                 String errorMsg = "";
355                 try {
356                         WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
357                         if(exception != null && (exception.getErrorMessage()!=null || !exception.getErrorMessage().equals(""))){
358                                 errorMsg = exception.getErrorMessage();
359                         }
360                 } catch (Exception ex) {
361                         //log error and attempt to extact WorkflowExceptionMessage
362                         logger.error("Failed to extract workflow exception from execution.",ex);
363                 }
364                 
365                 if (errorMsg == null){
366                         try {
367                                 errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
368                         } catch (Exception ex) {
369                                 logger.error("Failed to extract workflow exception message from WorkflowException",ex);
370                                 errorMsg = "Unexpected Error in BPMN.";
371                         }
372                 }
373                 return errorMsg;
374         }
375         
376         public void updateRequestStatusToFailedWithRollback(DelegateExecution execution) {
377                 execution.setVariable("isRollbackComplete", true);
378                 updateRequestStatusToFailed(execution);
379         }
380 }