added generic fabric support to SO
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / workflow / tasks / WorkflowActionBBTasks.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
22
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.camunda.bpm.engine.delegate.BpmnError;
27 import org.camunda.bpm.engine.delegate.DelegateExecution;
28 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
29 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
30 import org.onap.so.bpmn.core.WorkflowException;
31 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
32 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
33
34 import org.onap.so.client.exception.ExceptionBuilder;
35 import org.onap.so.db.request.beans.InfraActiveRequests;
36 import org.onap.so.db.request.client.RequestsDbClient;
37 import org.onap.so.logger.MsoLogger;
38 import org.onap.so.serviceinstancebeans.RequestReferences;
39 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
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 MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, WorkflowActionBBTasks.class);
54
55         @Autowired
56         private RequestsDbClient requestDbclient;
57         @Autowired
58         private WorkflowAction workflowAction;
59         
60         public void selectBB(DelegateExecution execution) {
61                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
62                                 .getVariable("flowsToExecute");
63                 execution.setVariable("MacroRollback", false);
64                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
65                 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
66                 boolean homing = (boolean) execution.getVariable("homing");
67                 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
68                 if (homing && !calledHoming) {
69                         if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
70                                 ebb.setHoming(true);
71                                 execution.setVariable("calledHoming", true);
72                         }
73                 } else {
74                         ebb.setHoming(false);
75                 }
76                 execution.setVariable("buildingBlock", ebb);
77                 currentSequence++;
78                 if (currentSequence >= flowsToExecute.size()) {
79                         execution.setVariable("completed", true);
80                 } else {
81                         execution.setVariable("completed", false);
82                         execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
83                 }
84         }
85         
86         public void updateFlowStatistics(DelegateExecution execution) {
87                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
88                 if(currentSequence > 1) {
89                         InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
90                         requestDbclient.updateInfraActiveRequests(request);
91                 }
92         }
93
94         protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
95                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
96                                 .getVariable("flowsToExecute");
97                 String requestId = (String) execution.getVariable(G_REQUEST_ID);
98                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
99                 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
100                 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
101                 int completedBBs = currentSequence - 1;
102                 int totalBBs = flowsToExecute.size();
103                 int remainingBBs = totalBBs - completedBBs;
104                 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(), 
105                                 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
106                 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
107                 request.setStatusMessage(statusMessage);
108                 request.setProgress(percentProgress);
109                 request.setLastModifiedBy("CamundaBPMN");
110                 return request;
111         }
112         
113         protected Long getPercentProgress(int completedBBs, int totalBBs) {
114                 double ratio = (completedBBs / (totalBBs * 1.0));
115                 int percentProgress = (int) (ratio * 95);
116                 return new Long(percentProgress + 5);
117         }
118         
119         protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
120                 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
121                                 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
122                                 + ").";
123         }
124
125         public void sendSyncAck(DelegateExecution execution) {
126                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
127                 final String resourceId = (String) execution.getVariable("resourceId");
128                 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
129                 RequestReferences requestRef = new RequestReferences();
130                 requestRef.setInstanceId(resourceId);
131                 requestRef.setRequestId(requestId);
132                 serviceInstancesResponse.setRequestReferences(requestRef);
133                 ObjectMapper mapper = new ObjectMapper();
134                 String jsonRequest = "";
135                 try {
136                         jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
137                 } catch (JsonProcessingException e) {
138                         workflowAction.buildAndThrowException(execution,
139                                         "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
140                 }
141                 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
142                 callbackResponse.setStatusCode(200);
143                 callbackResponse.setMessage("Success");
144                 callbackResponse.setResponse(jsonRequest);
145                 String processKey = execution.getProcessEngineServices().getRepositoryService()
146                                 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
147                 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
148                                 callbackResponse);
149                 msoLogger.info("Successfully sent sync ack.");
150         }
151
152         public void sendErrorSyncAck(DelegateExecution execution) {
153                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
154                 try {
155                         ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
156                         String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
157                         if (errorMsg == null) {
158                                 errorMsg = "WorkflowAction failed unexpectedly.";
159                         }
160                         String processKey = exceptionBuilder.getProcessKey(execution);
161                         String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
162                                         + errorMsg
163                                         + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
164                         WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
165                         callbackResponse.setStatusCode(500);
166                         callbackResponse.setMessage("Fail");
167                         callbackResponse.setResponse(buildworkflowException);
168                         WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
169                                         callbackResponse);
170                         execution.setVariable("sentSyncResponse", true);
171                 } catch (Exception ex) {
172                         msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage());
173                 }
174         }
175
176         public void setupCompleteMsoProcess(DelegateExecution execution) {
177                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
178                 final String action = (String) execution.getVariable(G_ACTION);
179                 final String resourceId = (String) execution.getVariable("resourceId");
180                 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
181                 final String resourceName = (String) execution.getVariable("resourceName");
182                 final String source = (String) execution.getVariable("source");
183                 String macroAction = "";
184                 if (aLaCarte) {
185                         macroAction = "ALaCarte-" + resourceName + "-" + action;
186                 } else {
187                         macroAction = "Macro-" + resourceName + "-" + action;
188                 }
189                 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>"
190                                 + requestId + "</request-id><action>" + action + "</action><source>" + source
191                                 + "</source></request-info><status-message>" + macroAction
192                                 + " request was executed correctly.</status-message><serviceInstanceId>" + resourceId
193                                 + "</serviceInstanceId><mso-bpel-name>WorkflowActionBB</mso-bpel-name></aetgt:MsoCompletionRequest>";
194                 execution.setVariable("CompleteMsoProcessRequest", msoCompletionRequest);
195                 execution.setVariable("mso-request-id", requestId);
196                 execution.setVariable("mso-service-instance-id", resourceId);
197         }
198
199         public void setupFalloutHandler(DelegateExecution execution) {
200                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
201                 final String action = (String) execution.getVariable(G_ACTION);
202                 final String resourceId = (String) execution.getVariable("resourceId");
203                 String exceptionMsg = "";
204                 if (execution.getVariable("WorkflowActionErrorMessage") != null) {
205                         exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
206                 } else {
207                         exceptionMsg = "Error in WorkflowAction";
208                 }
209                 execution.setVariable("mso-service-instance-id", resourceId);
210                 execution.setVariable("mso-request-id", requestId);
211                 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>"
212                                 + requestId + "</request-id><action>" + action
213                                 + "</action><source>VID</source></request-info><aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
214                                 + exceptionMsg
215                                 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
216                 execution.setVariable("falloutRequest", falloutRequest);
217         }
218
219         public void checkRetryStatus(DelegateExecution execution) {
220                 if (execution.getVariable("handlingCode") == "Retry") {
221                         int currSequence = (int) execution.getVariable("gCurrentSequence");
222                         currSequence--;
223                         execution.setVariable("gCurrentSequence", currSequence);
224                         int currRetryCount = (int) execution.getVariable("retryCount");
225                         currRetryCount++;
226                         execution.setVariable("retryCount", currRetryCount);
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                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
236                                 .getVariable("flowsToExecute");
237                 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
238                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE) - 1;
239                 for (int i = flowsToExecute.size() - 1; i >= 0; i--) {
240                         if (i >= currentSequence) {
241                                 flowsToExecute.remove(i);
242                         } else {
243                                 ExecuteBuildingBlock ebb = flowsToExecute.get(i);
244                                 BuildingBlock bb = flowsToExecute.get(i).getBuildingBlock();
245                                 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
246                                 if (flowName.contains("Assign")) {
247                                         flowName = "Unassign" + flowName.substring(7, 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                                 }
253                                 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
254                                 rollbackFlows.add(flowsToExecute.get(i));
255                         }
256                 }
257                 if (rollbackFlows.isEmpty())
258                         execution.setVariable("isRollbackNeeded", false);
259                 else
260                         execution.setVariable("isRollbackNeeded", true);
261
262                 execution.setVariable("flowsToExecute", rollbackFlows);
263                 execution.setVariable("handlingCode", "PreformingRollback");
264         }
265
266         public void abortCallErrorHandling(DelegateExecution execution) {
267                 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
268                 Exception exception = new Exception(msg);
269                 msoLogger.error(exception);
270                 throw new BpmnError(msg);
271         }
272
273         public void updateRequestStatusToFailed(DelegateExecution execution) {
274                 try {
275                         String requestId = (String) execution.getVariable(G_REQUEST_ID);
276                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
277                         String errorMsg = null;
278                         try {
279                                 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
280                                 request.setStatusMessage(exception.getErrorMessage());
281                         } catch (Exception ex) {
282                                 //log error and attempt to extact WorkflowExceptionMessage
283                                 msoLogger.error(ex);
284                         }
285                         if (errorMsg == null){
286                                 try {
287                                         errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
288                                         request.setStatusMessage(errorMsg);
289                                 } catch (Exception ex) {
290                                         msoLogger.error(ex);
291                                         request.setStatusMessage("Unexpected Error in BPMN");
292                                 }
293                         }
294                         request.setRequestStatus("FAILED");
295                         request.setLastModifiedBy("CamundaBPMN");
296                         requestDbclient.updateInfraActiveRequests(request);
297                 } catch (Exception e) {
298                         workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
299                 }
300         }
301 }