Containerization feature of 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 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 sendSyncAck(DelegateExecution execution) {
86                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
87                 final String resourceId = (String) execution.getVariable("resourceId");
88                 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
89                 RequestReferences requestRef = new RequestReferences();
90                 requestRef.setInstanceId(resourceId);
91                 requestRef.setRequestId(requestId);
92                 serviceInstancesResponse.setRequestReferences(requestRef);
93                 ObjectMapper mapper = new ObjectMapper();
94                 String jsonRequest = "";
95                 try {
96                         jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
97                 } catch (JsonProcessingException e) {
98                         workflowAction.buildAndThrowException(execution,
99                                         "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
100                 }
101                 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
102                 callbackResponse.setStatusCode(200);
103                 callbackResponse.setMessage("Success");
104                 callbackResponse.setResponse(jsonRequest);
105                 String processKey = execution.getProcessEngineServices().getRepositoryService()
106                                 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
107                 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
108                                 callbackResponse);
109                 msoLogger.info("Successfully sent sync ack.");
110         }
111
112         public void sendErrorSyncAck(DelegateExecution execution) {
113                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
114                 try {
115                         ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
116                         String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
117                         if (errorMsg == null) {
118                                 errorMsg = "WorkflowAction failed unexpectedly.";
119                         }
120                         String processKey = exceptionBuilder.getProcessKey(execution);
121                         String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
122                                         + errorMsg
123                                         + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
124                         WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
125                         callbackResponse.setStatusCode(500);
126                         callbackResponse.setMessage("Fail");
127                         callbackResponse.setResponse(buildworkflowException);
128                         WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
129                                         callbackResponse);
130                         execution.setVariable("sentSyncResponse", true);
131                 } catch (Exception ex) {
132                         msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage());
133                 }
134         }
135
136         public void setupCompleteMsoProcess(DelegateExecution execution) {
137                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
138                 final String action = (String) execution.getVariable(G_ACTION);
139                 final String resourceId = (String) execution.getVariable("resourceId");
140                 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
141                 final String resourceName = (String) execution.getVariable("resourceName");
142                 final String source = (String) execution.getVariable("source");
143                 String macroAction = "";
144                 if (aLaCarte) {
145                         macroAction = "ALaCarte-" + resourceName + "-" + action;
146                 } else {
147                         macroAction = "Macro-" + resourceName + "-" + action;
148                 }
149                 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>"
150                                 + requestId + "</request-id><action>" + action + "</action><source>" + source
151                                 + "</source></request-info><status-message>" + macroAction
152                                 + " request was executed correctly.</status-message><serviceInstanceId>" + resourceId
153                                 + "</serviceInstanceId><mso-bpel-name>WorkflowActionBB</mso-bpel-name></aetgt:MsoCompletionRequest>";
154                 execution.setVariable("CompleteMsoProcessRequest", msoCompletionRequest);
155                 execution.setVariable("mso-request-id", requestId);
156                 execution.setVariable("mso-service-instance-id", resourceId);
157         }
158
159         public void setupFalloutHandler(DelegateExecution execution) {
160                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
161                 final String action = (String) execution.getVariable(G_ACTION);
162                 final String resourceId = (String) execution.getVariable("resourceId");
163                 String exceptionMsg = "";
164                 if (execution.getVariable("WorkflowActionErrorMessage") != null) {
165                         exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
166                 } else {
167                         exceptionMsg = "Error in WorkflowAction";
168                 }
169                 execution.setVariable("mso-service-instance-id", resourceId);
170                 execution.setVariable("mso-request-id", requestId);
171                 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>"
172                                 + requestId + "</request-id><action>" + action
173                                 + "</action><source>VID</source></request-info><aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
174                                 + exceptionMsg
175                                 + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException></aetgt:FalloutHandlerRequest>";
176                 execution.setVariable("falloutRequest", falloutRequest);
177         }
178
179         public void checkRetryStatus(DelegateExecution execution) {
180                 if (execution.getVariable("handlingCode") == "Retry") {
181                         int currSequence = (int) execution.getVariable("gCurrentSequence");
182                         currSequence--;
183                         execution.setVariable("gCurrentSequence", currSequence);
184                         int currRetryCount = (int) execution.getVariable("retryCount");
185                         currRetryCount++;
186                         execution.setVariable("retryCount", currRetryCount);
187                 }
188         }
189
190         /**
191          * Rollback will only handle Create/Activate/Assign Macro flows. Execute
192          * layer will rollback the flow its currently working on.
193          */
194         public void rollbackExecutionPath(DelegateExecution execution) {
195                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
196                                 .getVariable("flowsToExecute");
197                 List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
198                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE) - 1;
199                 for (int i = flowsToExecute.size() - 1; i >= 0; i--) {
200                         if (i >= currentSequence) {
201                                 flowsToExecute.remove(i);
202                         } else {
203                                 ExecuteBuildingBlock ebb = flowsToExecute.get(i);
204                                 BuildingBlock bb = flowsToExecute.get(i).getBuildingBlock();
205                                 String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
206                                 if (flowName.contains("Assign")) {
207                                         flowName = "Unassign" + flowName.substring(7, flowName.length());
208                                 } else if (flowName.contains("Create")) {
209                                         flowName = "Delete" + flowName.substring(6, flowName.length());
210                                 } else if (flowName.contains("Activate")) {
211                                         flowName = "Deactivate" + flowName.substring(8, flowName.length());
212                                 }
213                                 flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
214                                 rollbackFlows.add(flowsToExecute.get(i));
215                         }
216                 }
217                 if (rollbackFlows.isEmpty())
218                         execution.setVariable("isRollbackNeeded", false);
219                 else
220                         execution.setVariable("isRollbackNeeded", true);
221
222                 execution.setVariable("flowsToExecute", rollbackFlows);
223                 execution.setVariable("handlingCode", "PreformingRollback");
224         }
225
226         public void abortCallErrorHandling(DelegateExecution execution) {
227                 String msg = "Flow has failed. Rainy day handler has decided to abort the process.";
228                 Exception exception = new Exception(msg);
229                 msoLogger.error(exception);
230                 throw new BpmnError(msg);
231         }
232
233         public void updateRequestStatusToFailed(DelegateExecution execution) {
234                 try {
235                         String requestId = (String) execution.getVariable(G_REQUEST_ID);
236                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
237                         String errorMsg = null;
238                         try {
239                                 WorkflowException exception = (WorkflowException) execution.getVariable("WorkflowException");
240                                 request.setStatusMessage(exception.getErrorMessage());
241                         } catch (Exception ex) {
242                                 //log error and attempt to extact WorkflowExceptionMessage
243                                 msoLogger.error(ex);
244                         }
245                         if (errorMsg == null){
246                                 try {
247                                         errorMsg = (String) execution.getVariable("WorkflowExceptionErrorMessage");
248                                         request.setStatusMessage(errorMsg);
249                                 } catch (Exception ex) {
250                                         msoLogger.error(ex);
251                                         request.setStatusMessage("Unexpected Error in BPMN");
252                                 }
253                         }
254                         request.setRequestStatus("FAILED");
255                         request.setLastModifiedBy("CamundaBPMN");
256                         requestDbclient.updateInfraActiveRequests(request);
257                 } catch (Exception e) {
258                         workflowAction.buildAndThrowException(execution, "Error Updating Request Database", e);
259                 }
260         }
261 }