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