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