vnf resource uuid null
[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.List;
26 import java.util.UUID;
27
28 import org.camunda.bpm.engine.delegate.DelegateExecution;
29 import org.onap.aai.domain.yang.Vnfc;
30 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
31 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
32 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
33 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
34 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
35 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
36 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
37 import org.onap.so.client.aai.AAIObjectType;
38 import org.onap.so.client.exception.ExceptionBuilder;
39 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
40 import org.onap.so.db.catalog.client.CatalogDbClient;
41 import org.onap.so.db.request.beans.InfraActiveRequests;
42 import org.onap.so.db.request.client.RequestsDbClient;
43 import org.onap.so.serviceinstancebeans.RequestReferences;
44 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.core.env.Environment;
49 import org.springframework.stereotype.Component;
50
51 import com.fasterxml.jackson.core.JsonProcessingException;
52 import com.fasterxml.jackson.databind.ObjectMapper;
53
54 @Component
55 public class WorkflowActionBBTasks {
56
57         private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
58         private static final String G_REQUEST_ID = "mso-request-id";
59         private static final String G_ALACARTE = "aLaCarte";
60         private static final String G_ACTION = "requestAction";
61         private static final String RETRY_COUNT = "retryCount";
62         private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
63         private static final String ASSIGN_FABRIC_CONFIGURATION_BB = "AssignFabricConfigurationBB";
64         private static final String ACTIVATE_FABRIC_CONFIGURATION_BB = "ActivateFabricConfigurationBB";
65         protected String maxRetries = "mso.rainyDay.maxRetries";
66         private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
67
68         @Autowired
69         private RequestsDbClient requestDbclient;
70         @Autowired
71         private WorkflowAction workflowAction;
72         @Autowired
73         private WorkflowActionBBFailure workflowActionBBFailure;
74         @Autowired
75         private Environment environment;
76         @Autowired
77         private BBInputSetupUtils bbInputSetupUtils;
78         @Autowired
79         private CatalogDbClient catalogDbClient;
80         
81         public void selectBB(DelegateExecution execution) {
82                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
83                                 .getVariable("flowsToExecute");
84                 execution.setVariable("MacroRollback", false);
85                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
86                 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
87                 boolean homing = (boolean) execution.getVariable("homing");
88                 boolean calledHoming = (boolean) execution.getVariable("calledHoming");
89                 if (homing && !calledHoming) {
90                         if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignVnfBB")) {
91                                 ebb.setHoming(true);
92                                 execution.setVariable("calledHoming", true);
93                         }
94                 } else {
95                         ebb.setHoming(false);
96                 }
97                 execution.setVariable("buildingBlock", ebb);
98                 currentSequence++;
99                 if (currentSequence >= flowsToExecute.size()) {
100                         execution.setVariable("completed", true);
101                 } else {
102                         execution.setVariable("completed", false);
103                 }
104                 execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
105         }
106         
107         public void updateFlowStatistics(DelegateExecution execution) {
108                 try{
109                         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
110                         if(currentSequence > 1) {
111                                 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
112                                 requestDbclient.updateInfraActiveRequests(request);
113                         }
114                 }catch (Exception ex){
115                         logger.warn("Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.");
116                 }
117         }
118
119         protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
120                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
121                                 .getVariable("flowsToExecute");
122                 String requestId = (String) execution.getVariable(G_REQUEST_ID);
123                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
124                 ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
125                 ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
126                 int completedBBs = currentSequence - 1;
127                 int totalBBs = flowsToExecute.size();
128                 int remainingBBs = totalBBs - completedBBs;
129                 String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(), 
130                                 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
131                 Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
132                 request.setFlowStatus(statusMessage);
133                 request.setProgress(percentProgress);
134                 request.setLastModifiedBy("CamundaBPMN");
135                 return request;
136         }
137         
138         protected Long getPercentProgress(int completedBBs, int totalBBs) {
139                 double ratio = (completedBBs / (totalBBs * 1.0));
140                 int percentProgress = (int) (ratio * 95);
141                 return new Long(percentProgress + 5);
142         }
143         
144         protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
145                 return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
146                                 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
147                                 + ").";
148         }
149
150         public void sendSyncAck(DelegateExecution execution) {
151                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
152                 final String resourceId = (String) execution.getVariable("resourceId");
153                 ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
154                 RequestReferences requestRef = new RequestReferences();
155                 requestRef.setInstanceId(resourceId);
156                 requestRef.setRequestId(requestId);
157                 serviceInstancesResponse.setRequestReferences(requestRef);
158                 ObjectMapper mapper = new ObjectMapper();
159                 String jsonRequest = "";
160                 try {
161                         jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
162                 } catch (JsonProcessingException e) {
163                         workflowAction.buildAndThrowException(execution,
164                                         "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
165                 }
166                 WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
167                 callbackResponse.setStatusCode(200);
168                 callbackResponse.setMessage("Success");
169                 callbackResponse.setResponse(jsonRequest);
170                 String processKey = execution.getProcessEngineServices().getRepositoryService()
171                                 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
172                 WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
173                                 callbackResponse);
174                 logger.info("Successfully sent sync ack.");
175                 updateInstanceId(execution);
176         }
177
178         public void sendErrorSyncAck(DelegateExecution execution) {
179                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
180                 try {
181                         ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
182                         String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
183                         if (errorMsg == null) {
184                                 errorMsg = "WorkflowAction failed unexpectedly.";
185                         }
186                         String processKey = exceptionBuilder.getProcessKey(execution);
187                         String buildworkflowException = "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
188                                         + errorMsg
189                                         + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
190                         WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
191                         callbackResponse.setStatusCode(500);
192                         callbackResponse.setMessage("Fail");
193                         callbackResponse.setResponse(buildworkflowException);
194                         WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
195                                         callbackResponse);
196                         execution.setVariable("sentSyncResponse", true);
197                 } catch (Exception ex) {
198                         logger.error(" Sending Sync Error Activity Failed. {}"  , ex.getMessage(), ex);
199                 }
200         }
201
202         public void updateRequestStatusToComplete(DelegateExecution execution) {
203                 try{
204                         final String requestId = (String) execution.getVariable(G_REQUEST_ID);
205                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
206                         final String action = (String) execution.getVariable(G_ACTION);
207                         final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
208                         final String resourceName = (String) execution.getVariable("resourceName");
209                         String macroAction = "";
210                         if (aLaCarte) {
211                                 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
212                         } else {
213                                 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
214                         }
215                         execution.setVariable("finalStatusMessage", macroAction);
216                         Timestamp endTime = new Timestamp(System.currentTimeMillis());
217                         request.setEndTime(endTime);
218                         request.setFlowStatus("Successfully completed all Building Blocks");
219                         request.setStatusMessage(macroAction);
220                         request.setProgress(Long.valueOf(100));
221                         request.setRequestStatus("COMPLETE");
222                         request.setLastModifiedBy("CamundaBPMN");
223                         requestDbclient.updateInfraActiveRequests(request);
224                 }catch (Exception ex) {
225                         workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
226                 }
227         }
228
229         public void checkRetryStatus(DelegateExecution execution) {
230                 String handlingCode = (String) execution.getVariable("handlingCode");
231                 String requestId = (String) execution.getVariable(G_REQUEST_ID);
232                 String retryDuration = (String) execution.getVariable("RetryDuration");
233                 int retryCount = (int) execution.getVariable(RETRY_COUNT);
234                 int envMaxRetries;
235                 try{
236                         envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));     
237                 } catch (Exception ex) {
238                         logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
239                         envMaxRetries = 5;
240                 }
241                 int nextCount = retryCount +1;
242                 if (handlingCode.equals("Retry")){
243                         workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
244                         try{
245                                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
246                                 request.setRetryStatusMessage("Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
247                                 requestDbclient.updateInfraActiveRequests(request); 
248                         } catch(Exception ex){
249                                 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status",ex);
250                         }
251                         if(retryCount<envMaxRetries){
252                                 int currSequence = (int) execution.getVariable("gCurrentSequence");
253                                 execution.setVariable("gCurrentSequence", currSequence-1);
254                                 execution.setVariable(RETRY_COUNT, nextCount);
255                         }else{
256                                 workflowAction.buildAndThrowException(execution, "Exceeded maximum retries. Ending flow with status Abort");
257                         }
258                 }else{
259                         execution.setVariable(RETRY_COUNT, 0);
260                 }
261         }
262
263         /**
264          * Rollback will only handle Create/Activate/Assign Macro flows. Execute
265          * layer will rollback the flow its currently working on.
266          */
267         public void rollbackExecutionPath(DelegateExecution execution) {
268                 if(!(boolean)execution.getVariable("isRollback")){
269                         List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
270                                         .getVariable("flowsToExecute");
271                         List<ExecuteBuildingBlock> rollbackFlows = new ArrayList();
272                         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
273                         int listSize = flowsToExecute.size();
274                         for (int i = listSize - 1; i >= 0; i--) {
275                                 if (i > currentSequence - 1) {
276                                         flowsToExecute.remove(i);
277                                 } else {
278                                         String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
279                                         if (flowName.contains("Assign")) {
280                                                 flowName = "Unassign" + flowName.substring(6, flowName.length());
281                                         } else if (flowName.contains("Create")) {
282                                                 flowName = "Delete" + flowName.substring(6, flowName.length());
283                                         } else if (flowName.contains("Activate")) {
284                                                 flowName = "Deactivate" + flowName.substring(8, flowName.length());
285                                         }else{
286                                                 continue;
287                                         }
288                                         flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
289                                         rollbackFlows.add(flowsToExecute.get(i));
290                                 }
291                         }
292                         
293                         int flowSize = rollbackFlows.size();
294                         String handlingCode = (String) execution.getVariable("handlingCode");
295                         if(handlingCode.equals("RollbackToAssigned") || handlingCode.equals("RollbackToCreated")){
296                                 for(int i = 0; i<flowSize; i++){
297                                         if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Unassign")){
298                                                 rollbackFlows.remove(i);
299                                         } else if(rollbackFlows.get(i).getBuildingBlock().getBpmnFlowName().contains("Delete") && handlingCode.equals("RollbackToCreated")) {
300                                                 rollbackFlows.remove(i);
301                                         }
302                                 }
303                         }
304                         
305                         workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
306                         
307                         if (rollbackFlows.isEmpty())
308                                 execution.setVariable("isRollbackNeeded", false);
309                         else
310                                 execution.setVariable("isRollbackNeeded", true);
311                         execution.setVariable("flowsToExecute", rollbackFlows);
312                         execution.setVariable("handlingCode", "PreformingRollback");
313                         execution.setVariable("isRollback", true);
314                         execution.setVariable("gCurrentSequence", 0);
315                         execution.setVariable(RETRY_COUNT, 0);
316                 }else{
317                         workflowAction.buildAndThrowException(execution, "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
318                 }
319         }
320         
321         protected void updateInstanceId(DelegateExecution execution){
322                 try{
323                         String requestId = (String) execution.getVariable(G_REQUEST_ID);
324                         String resourceId = (String) execution.getVariable("resourceId");
325                         WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
326                         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
327                         if(resourceType == WorkflowType.SERVICE){
328                                 request.setServiceInstanceId(resourceId);
329                         }else if(resourceType == WorkflowType.VNF){
330                                 request.setVnfId(resourceId);
331                         }else if(resourceType == WorkflowType.VFMODULE){
332                                 request.setVfModuleId(resourceId);
333                         }else if(resourceType == WorkflowType.VOLUMEGROUP){
334                                 request.setVolumeGroupId(resourceId);
335                         }else if(resourceType == WorkflowType.NETWORK){
336                                 request.setNetworkId(resourceId);
337                         }else if(resourceType == WorkflowType.CONFIGURATION){
338                                 request.setConfigurationId(resourceId);
339                         }else if(resourceType == WorkflowType.INSTANCE_GROUP){
340                                 request.setInstanceGroupId(resourceId);
341                         }
342                         requestDbclient.updateInfraActiveRequests(request);
343                 }catch(Exception ex){
344                         workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
345                 }
346         }
347         
348         public void postProcessingExecuteBB(DelegateExecution execution) {
349                 List<ExecuteBuildingBlock> flowsToExecute = (List<ExecuteBuildingBlock>) execution
350                                 .getVariable("flowsToExecute");
351                 String handlingCode = (String) execution.getVariable("handlingCode");
352                 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
353                 int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
354                 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
355                 String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
356                 if(bbFlowName.equalsIgnoreCase("ActivateVfModuleBB") && aLaCarte && handlingCode.equalsIgnoreCase("Success")) {
357                         postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
358                 }
359         }
360         
361         protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, 
362                         ExecuteBuildingBlock ebb, List<ExecuteBuildingBlock> flowsToExecute) {
363                 try {
364                         String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
365                         String vnfId = ebb.getWorkflowResourceIds().getVnfId();
366                         String vfModuleId = ebb.getResourceId();
367                         ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
368                         String serviceModelUUID = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
369                         String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
370                         String vfModuleCustomizationUUID = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
371                         List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
372                         logger.debug("Vnfc Size: {}", vnfcs.size());
373                         for(Vnfc vnfc : vnfcs) {
374                                 String modelCustomizationId = vnfc.getModelCustomizationId();
375                                 logger.debug("Processing Vnfc: {}", modelCustomizationId);
376                                 CvnfcConfigurationCustomization fabricConfig = 
377                                                 catalogDbClient.getCvnfcCustomization(serviceModelUUID,vnfCustomizationUUID,
378                                                                 vfModuleCustomizationUUID, modelCustomizationId);
379                                 if(fabricConfig != null && fabricConfig.getConfigurationResource() != null 
380                                                 && fabricConfig.getConfigurationResource().getToscaNodeType() != null 
381                                                 && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
382                                         String configurationId = UUID.randomUUID().toString();
383                                         ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
384                                         configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
385                                         configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
386                                         configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
387                                         configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
388                                         ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
389                                         ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys);
390                                         flowsToExecute.add(assignConfigBB);
391                                         flowsToExecute.add(activateConfigBB);
392                                         flowsToExecute.stream().forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}", executeBB.getBuildingBlock().getBpmnFlowName()));
393                                         execution.setVariable("flowsToExecute", flowsToExecute);
394                                         execution.setVariable("completed", false);
395                                 } else {
396                                         logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId);
397                                 }
398                         }
399                 } catch (Exception e) {
400                         String errorMessage = "Error occurred in post processing of Vf Module create";
401                         execution.setVariable("handlingCode", "RollbackToCreated");
402                         execution.setVariable("WorkflowActionErrorMessage", errorMessage);
403                         logger.error(errorMessage, e);
404                 }
405         }
406         
407         protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb, String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
408                 ExecuteBuildingBlock configBB = new ExecuteBuildingBlock();
409                 BuildingBlock buildingBlock = new BuildingBlock();
410                 buildingBlock.setBpmnFlowName(bbName);
411                 buildingBlock.setMsoId(UUID.randomUUID().toString());
412                 configBB.setaLaCarte(ebb.isaLaCarte());
413                 configBB.setApiVersion(ebb.getApiVersion());
414                 configBB.setRequestAction(ebb.getRequestAction());
415                 configBB.setVnfType(ebb.getVnfType());
416                 configBB.setRequestId(ebb.getRequestId());
417                 configBB.setRequestDetails(ebb.getRequestDetails());
418                 configBB.setBuildingBlock(buildingBlock);
419                 WorkflowResourceIds workflowResourceIds = ebb.getWorkflowResourceIds();
420                 workflowResourceIds.setConfigurationId(configurationId);
421                 configBB.setWorkflowResourceIds(workflowResourceIds);
422                 configBB.setConfigurationResourceKeys(configurationResourceKeys);
423                 return configBB;
424         }
425 }