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