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