Merge "Execute building block uses wrong config id"
[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 com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import org.camunda.bpm.engine.delegate.DelegateExecution;
26 import org.onap.aai.domain.yang.*;
27 import org.onap.aaiclient.client.aai.AAIObjectType;
28 import org.onap.aaiclient.client.aai.entities.Configuration;
29 import org.onap.so.bpmn.common.DelegateExecutionImpl;
30 import org.onap.so.bpmn.common.listener.db.RequestsDbListenerRunner;
31 import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner;
32 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
33 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
34 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
35 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
36 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
37 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
38 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
39 import org.onap.so.client.exception.ExceptionBuilder;
40 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
41 import org.onap.so.db.catalog.client.CatalogDbClient;
42 import org.onap.so.db.request.beans.InfraActiveRequests;
43 import org.onap.so.db.request.client.RequestsDbClient;
44 import org.onap.so.serviceinstancebeans.RequestReferences;
45 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.core.env.Environment;
50 import org.springframework.stereotype.Component;
51 import javax.persistence.EntityNotFoundException;
52 import java.sql.Timestamp;
53 import java.util.ArrayList;
54 import java.util.List;
55 import java.util.Optional;
56 import java.util.UUID;
57 import java.util.stream.Collectors;
58
59 @Component
60 public class WorkflowActionBBTasks {
61
62     private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
63     private static final String G_REQUEST_ID = "mso-request-id";
64     private static final String G_ALACARTE = "aLaCarte";
65     private static final String G_ACTION = "requestAction";
66     private static final String RETRY_COUNT = "retryCount";
67     private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
68     private static final String ADD_FABRIC_CONFIGURATION_BB = "AddFabricConfigurationBB";
69     private static final String COMPLETED = "completed";
70     private static final String HANDLINGCODE = "handlingCode";
71     private static final String ROLLBACKTOCREATED = "RollbackToCreated";
72     private static final String REPLACEINSTANCE = "replaceInstance";
73     private static final String VFMODULE = "VfModule";
74     protected String maxRetries = "mso.rainyDay.maxRetries";
75     private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
76
77     @Autowired
78     private RequestsDbClient requestDbclient;
79     @Autowired
80     private WorkflowAction workflowAction;
81     @Autowired
82     private WorkflowActionBBFailure workflowActionBBFailure;
83     @Autowired
84     private Environment environment;
85     @Autowired
86     private BBInputSetupUtils bbInputSetupUtils;
87     @Autowired
88     private CatalogDbClient catalogDbClient;
89     @Autowired
90     private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
91     @Autowired
92     private RequestsDbListenerRunner requestsDbListener;
93
94     public void selectBB(DelegateExecution execution) {
95         List<ExecuteBuildingBlock> flowsToExecute =
96                 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
97         execution.setVariable("MacroRollback", false);
98
99         flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
100         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
101
102         ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
103
104         execution.setVariable("buildingBlock", ebb);
105         currentSequence++;
106         execution.setVariable(COMPLETED, currentSequence >= flowsToExecute.size());
107         execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
108     }
109
110     public void updateFlowStatistics(DelegateExecution execution) {
111         try {
112             int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
113             if (currentSequence > 1) {
114                 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
115                 requestDbclient.updateInfraActiveRequests(request);
116             }
117         } catch (Exception ex) {
118             logger.warn(
119                     "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.",
120                     ex);
121         }
122     }
123
124     protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
125         List<ExecuteBuildingBlock> flowsToExecute =
126                 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
127         String requestId = (String) execution.getVariable(G_REQUEST_ID);
128         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
129         ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
130         ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
131         int completedBBs = currentSequence - 1;
132         int totalBBs = flowsToExecute.size();
133         int remainingBBs = totalBBs - completedBBs;
134         String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
135                 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
136         Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
137         request.setFlowStatus(statusMessage);
138         request.setProgress(percentProgress);
139         request.setLastModifiedBy("CamundaBPMN");
140         return request;
141     }
142
143     protected Long getPercentProgress(int completedBBs, int totalBBs) {
144         double ratio = (completedBBs / (totalBBs * 1.0));
145         int percentProgress = (int) (ratio * 95);
146         return (long) (percentProgress + 5);
147     }
148
149     protected String getStatusMessage(String completedBB, String nextBB, int completedBBs, int remainingBBs) {
150         return "Execution of " + completedBB + " has completed successfully, next invoking " + nextBB
151                 + " (Execution Path progress: BBs completed = " + completedBBs + "; BBs remaining = " + remainingBBs
152                 + ").";
153     }
154
155     public void sendSyncAck(DelegateExecution execution) {
156         final String requestId = (String) execution.getVariable(G_REQUEST_ID);
157         final String resourceId = (String) execution.getVariable("resourceId");
158         ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
159         RequestReferences requestRef = new RequestReferences();
160         requestRef.setInstanceId(resourceId);
161         requestRef.setRequestId(requestId);
162         serviceInstancesResponse.setRequestReferences(requestRef);
163         ObjectMapper mapper = new ObjectMapper();
164         String jsonRequest = "";
165         try {
166             jsonRequest = mapper.writeValueAsString(serviceInstancesResponse);
167         } catch (JsonProcessingException e) {
168             workflowAction.buildAndThrowException(execution,
169                     "Could not marshall ServiceInstancesRequest to Json string to respond to API Handler.", e);
170         }
171         WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
172         callbackResponse.setStatusCode(200);
173         callbackResponse.setMessage("Success");
174         callbackResponse.setResponse(jsonRequest);
175         String processKey = execution.getProcessEngineServices().getRepositoryService()
176                 .getProcessDefinition(execution.getProcessDefinitionId()).getKey();
177         WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
178                 callbackResponse);
179         logger.info("Successfully sent sync ack.");
180         updateInstanceId(execution);
181     }
182
183     public void sendErrorSyncAck(DelegateExecution execution) {
184         final String requestId = (String) execution.getVariable(G_REQUEST_ID);
185         try {
186             ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
187             String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
188             if (errorMsg == null) {
189                 errorMsg = "WorkflowAction failed unexpectedly.";
190             }
191             String processKey = exceptionBuilder.getProcessKey(execution);
192             String buildworkflowException =
193                     "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
194                             + errorMsg
195                             + "</aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>";
196             WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
197             callbackResponse.setStatusCode(500);
198             callbackResponse.setMessage("Fail");
199             callbackResponse.setResponse(buildworkflowException);
200             WorkflowContextHolder.getInstance().processCallback(processKey, execution.getProcessInstanceId(), requestId,
201                     callbackResponse);
202             execution.setVariable("sentSyncResponse", true);
203         } catch (Exception ex) {
204             logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
205         }
206     }
207
208     public void updateRequestStatusToComplete(DelegateExecution execution) {
209         try {
210             final String requestId = (String) execution.getVariable(G_REQUEST_ID);
211             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
212             final String action = (String) execution.getVariable(G_ACTION);
213             final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
214             final String resourceName = (String) execution.getVariable("resourceName");
215             String statusMessage = (String) execution.getVariable("StatusMessage");
216             String macroAction;
217             if (statusMessage == null) {
218                 if (aLaCarte) {
219                     macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
220                 } else {
221                     macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
222                 }
223             } else {
224                 macroAction = statusMessage;
225             }
226             execution.setVariable("finalStatusMessage", macroAction);
227             Timestamp endTime = new Timestamp(System.currentTimeMillis());
228             request.setEndTime(endTime);
229             request.setFlowStatus("Successfully completed all Building Blocks");
230             request.setStatusMessage(macroAction);
231             request.setProgress(100L);
232             request.setRequestStatus("COMPLETE");
233             request.setLastModifiedBy("CamundaBPMN");
234             requestsDbListener.post(request, new DelegateExecutionImpl(execution));
235             requestDbclient.updateInfraActiveRequests(request);
236         } catch (Exception ex) {
237             workflowAction.buildAndThrowException(execution, "Error Updating Request Database", ex);
238         }
239     }
240
241     public void checkRetryStatus(DelegateExecution execution) {
242         String handlingCode = (String) execution.getVariable(HANDLINGCODE);
243         String requestId = (String) execution.getVariable(G_REQUEST_ID);
244         String retryDuration = (String) execution.getVariable("RetryDuration");
245         int retryCount = (int) execution.getVariable(RETRY_COUNT);
246         int envMaxRetries;
247         try {
248             envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
249         } catch (Exception ex) {
250             logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
251             envMaxRetries = 5;
252         }
253         int nextCount = retryCount + 1;
254         if ("Retry".equals(handlingCode)) {
255             workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
256             try {
257                 InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
258                 request.setRetryStatusMessage(
259                         "Retry " + nextCount + "/" + envMaxRetries + " will be started in " + retryDuration);
260                 requestDbclient.updateInfraActiveRequests(request);
261             } catch (Exception ex) {
262                 logger.warn("Failed to update Request Db Infra Active Requests with Retry Status", ex);
263             }
264             if (retryCount < envMaxRetries) {
265                 int currSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
266                 execution.setVariable(G_CURRENT_SEQUENCE, currSequence - 1);
267                 execution.setVariable(RETRY_COUNT, nextCount);
268             } else {
269                 workflowAction.buildAndThrowException(execution,
270                         "Exceeded maximum retries. Ending flow with status Abort");
271             }
272         } else {
273             execution.setVariable(RETRY_COUNT, 0);
274         }
275     }
276
277     /**
278      * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
279      * working on.
280      */
281     public void rollbackExecutionPath(DelegateExecution execution) {
282         final String action = (String) execution.getVariable(G_ACTION);
283         final String resourceName = (String) execution.getVariable("resourceName");
284         if (!(boolean) execution.getVariable("isRollback")) {
285             List<ExecuteBuildingBlock> flowsToExecute =
286                     (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
287
288             List<ExecuteBuildingBlock> flowsToExecuteChangeBBs = flowsToExecute.stream()
289                     .filter(buildingBlock -> buildingBlock.getBuildingBlock().getBpmnFlowName().startsWith("Change"))
290                     .collect(Collectors.toList());
291
292             List<ExecuteBuildingBlock> rollbackFlows = new ArrayList<>();
293             int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
294             int listSize = flowsToExecute.size();
295
296             for (int i = listSize - 1; i >= 0; i--) {
297                 if (i > currentSequence - 1) {
298                     flowsToExecute.remove(i);
299                 } else {
300                     String flowName = flowsToExecute.get(i).getBuildingBlock().getBpmnFlowName();
301                     if (flowName.startsWith("Assign")) {
302                         flowName = flowName.replaceFirst("Assign", "Unassign");
303                     } else if (flowName.startsWith("Create")) {
304                         flowName = flowName.replaceFirst("Create", "Delete");
305                     } else if (flowName.startsWith("Activate")) {
306                         flowName = flowName.replaceFirst("Activate", "Deactivate");
307                     } else if (flowName.startsWith("Add")) {
308                         flowName = flowName.replaceFirst("Add", "Delete");
309                     } else if (flowName.startsWith("VNF")) {
310                         if (flowName.startsWith("VNFSet")) {
311                             flowName = flowName.replaceFirst("VNFSet", "VNFUnset");
312                         } else if (flowName.startsWith("VNFLock")) {
313                             flowName = flowName.replaceFirst("VNFLock", "VNFUnlock");
314                         } else if (flowName.startsWith("VNFStop")) {
315                             flowName = flowName.replaceFirst("VNFStop", "VNFStart");
316                         } else if (flowName.startsWith("VNFQuiesce")) {
317                             flowName = flowName.replaceFirst("VNFQuiesce", "VNFResume");
318                         } else {
319                             continue;
320                         }
321                     } else {
322                         continue;
323                     }
324                     flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
325                     rollbackFlows.add(flowsToExecute.get(i));
326                 }
327             }
328
329             String handlingCode = (String) execution.getVariable(HANDLINGCODE);
330             List<ExecuteBuildingBlock> rollbackFlowsFiltered = new ArrayList<>(rollbackFlows);
331             if ("RollbackToAssigned".equals(handlingCode) || ROLLBACKTOCREATED.equals(handlingCode)) {
332                 for (ExecuteBuildingBlock rollbackFlow : rollbackFlows) {
333                     if (rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("Unassign")
334                             && !rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("FabricConfiguration")) {
335                         rollbackFlowsFiltered.remove(rollbackFlow);
336                     } else if (rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("Delete")
337                             && !rollbackFlow.getBuildingBlock().getBpmnFlowName().contains("FabricConfiguration")
338                             && ROLLBACKTOCREATED.equals(handlingCode)) {
339                         rollbackFlowsFiltered.remove(rollbackFlow);
340                     }
341                 }
342             }
343
344             List<ExecuteBuildingBlock> rollbackFlowsFilteredNonChangeBBs = new ArrayList<>();
345             if (action.equals(REPLACEINSTANCE) && resourceName.equals(VFMODULE)) {
346                 for (ExecuteBuildingBlock executeBuildingBlock : rollbackFlowsFiltered) {
347                     if (!executeBuildingBlock.getBuildingBlock().getBpmnFlowName().startsWith("Change")) {
348                         rollbackFlowsFilteredNonChangeBBs.add(executeBuildingBlock);
349                     }
350                 }
351                 rollbackFlowsFiltered.clear();
352                 rollbackFlowsFiltered.addAll(flowsToExecuteChangeBBs);
353                 rollbackFlowsFiltered.addAll(rollbackFlowsFilteredNonChangeBBs);
354             }
355
356             workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
357             execution.setVariable("isRollbackNeeded", !rollbackFlows.isEmpty());
358             execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
359             execution.setVariable(HANDLINGCODE, "PreformingRollback");
360             execution.setVariable("isRollback", true);
361             execution.setVariable(G_CURRENT_SEQUENCE, 0);
362             execution.setVariable(RETRY_COUNT, 0);
363         } else {
364             workflowAction.buildAndThrowException(execution,
365                     "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
366         }
367     }
368
369     protected void updateInstanceId(DelegateExecution execution) {
370         try {
371             String requestId = (String) execution.getVariable(G_REQUEST_ID);
372             String resourceId = (String) execution.getVariable("resourceId");
373             WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
374             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
375             if (resourceType == WorkflowType.SERVICE) {
376                 request.setServiceInstanceId(resourceId);
377             } else if (resourceType == WorkflowType.VNF) {
378                 request.setVnfId(resourceId);
379             } else if (resourceType == WorkflowType.VFMODULE) {
380                 request.setVfModuleId(resourceId);
381             } else if (resourceType == WorkflowType.VOLUMEGROUP) {
382                 request.setVolumeGroupId(resourceId);
383             } else if (resourceType == WorkflowType.NETWORK) {
384                 request.setNetworkId(resourceId);
385             } else if (resourceType == WorkflowType.CONFIGURATION) {
386                 request.setConfigurationId(resourceId);
387             } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
388                 request.setInstanceGroupId(resourceId);
389             }
390             setInstanceName(resourceId, resourceType, request);
391             request.setLastModifiedBy("CamundaBPMN");
392             requestDbclient.updateInfraActiveRequests(request);
393         } catch (Exception ex) {
394             logger.error("Exception in updateInstanceId", ex);
395             workflowAction.buildAndThrowException(execution, "Failed to update Request db with instanceId");
396         }
397     }
398
399     public void postProcessingExecuteBB(DelegateExecution execution) {
400         List<ExecuteBuildingBlock> flowsToExecute =
401                 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
402         String handlingCode = (String) execution.getVariable(HANDLINGCODE);
403         final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
404         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
405         ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
406         String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
407         if ("ActivateVfModuleBB".equalsIgnoreCase(bbFlowName) && aLaCarte && "Success".equalsIgnoreCase(handlingCode)) {
408             postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
409         }
410     }
411
412     protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
413             List<ExecuteBuildingBlock> flowsToExecute) {
414         try {
415             String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
416             String vnfId = ebb.getWorkflowResourceIds().getVnfId();
417             String vfModuleId = ebb.getResourceId();
418             ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
419             String serviceModelUUID =
420                     bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
421             String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
422             String vfModuleCustomizationUUID =
423                     bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
424             List<Vnfc> vnfcs =
425                     workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC);
426             logger.debug("Vnfc Size: {}", vnfcs.size());
427             for (Vnfc vnfc : vnfcs) {
428                 String modelCustomizationId = vnfc.getModelCustomizationId();
429                 logger.debug("Processing Vnfc: {}", modelCustomizationId);
430                 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
431                         vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
432                 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
433                         && fabricConfig.getConfigurationResource().getToscaNodeType() != null
434                         && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
435                     String configurationId = getConfigurationId(vnfc);
436                     ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
437                     configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
438                     configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
439                     configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
440                     configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
441                     ExecuteBuildingBlock addConfigBB = getExecuteBBForConfig(ADD_FABRIC_CONFIGURATION_BB, ebb,
442                             configurationId, configurationResourceKeys);
443                     flowsToExecute.add(addConfigBB);
444                     flowsToExecute.forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
445                             executeBB.getBuildingBlock().getBpmnFlowName()));
446                     execution.setVariable("flowsToExecute", flowsToExecute);
447                     execution.setVariable(COMPLETED, false);
448                 } else {
449                     logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
450                 }
451             }
452         } catch (EntityNotFoundException e) {
453             logger.debug("Will not be running Fabric Config Building Blocks", e);
454         } catch (Exception e) {
455             String errorMessage = "Error occurred in post processing of Vf Module create";
456             execution.setVariable(HANDLINGCODE, ROLLBACKTOCREATED);
457             execution.setVariable("WorkflowActionErrorMessage", errorMessage);
458             logger.error(errorMessage, e);
459         }
460     }
461
462     protected String getConfigurationId(Vnfc vnfc) throws Exception {
463         Configuration configuration =
464                 workflowAction.getRelatedResourcesInVnfc(vnfc, Configuration.class, AAIObjectType.CONFIGURATION);
465         if (configuration != null) {
466             return configuration.getConfigurationId();
467         } else {
468             return UUID.randomUUID().toString();
469         }
470     }
471
472     protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
473             String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
474         BuildingBlock buildingBlock =
475                 new BuildingBlock().setBpmnFlowName(bbName).setMsoId(UUID.randomUUID().toString());
476
477         WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(ebb.getWorkflowResourceIds());
478         workflowResourceIds.setConfigurationId(configurationId);
479         return new ExecuteBuildingBlock().setaLaCarte(ebb.isaLaCarte()).setApiVersion(ebb.getApiVersion())
480                 .setRequestAction(ebb.getRequestAction()).setVnfType(ebb.getVnfType()).setRequestId(ebb.getRequestId())
481                 .setRequestDetails(ebb.getRequestDetails()).setBuildingBlock(buildingBlock)
482                 .setWorkflowResourceIds(workflowResourceIds).setConfigurationResourceKeys(configurationResourceKeys);
483     }
484
485     protected void setInstanceName(String resourceId, WorkflowType resourceType, InfraActiveRequests request) {
486         logger.debug("Setting instanceName in infraActiveRequest");
487         try {
488             if (resourceType == WorkflowType.SERVICE && request.getServiceInstanceName() == null) {
489                 ServiceInstance service = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
490                 if (service != null) {
491                     request.setServiceInstanceName(service.getServiceInstanceName());
492                 }
493             } else if (resourceType == WorkflowType.VNF && request.getVnfName() == null) {
494                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(resourceId);
495                 if (vnf != null) {
496                     request.setVnfName(vnf.getVnfName());
497                 }
498             } else if (resourceType == WorkflowType.VFMODULE && request.getVfModuleName() == null) {
499                 VfModule vfModule = bbInputSetupUtils.getAAIVfModule(request.getVnfId(), resourceId);
500                 if (vfModule != null) {
501                     request.setVfModuleName(vfModule.getVfModuleName());
502                 }
503             } else if (resourceType == WorkflowType.VOLUMEGROUP && request.getVolumeGroupName() == null) {
504                 Optional<VolumeGroup> volumeGroup =
505                         bbInputSetupUtils.getRelatedVolumeGroupByIdFromVnf(request.getVnfId(), resourceId);
506                 volumeGroup.ifPresent(group -> request.setVolumeGroupName(group.getVolumeGroupName()));
507             } else if (resourceType == WorkflowType.NETWORK && request.getNetworkName() == null) {
508                 L3Network network = bbInputSetupUtils.getAAIL3Network(resourceId);
509                 if (network != null) {
510                     request.setNetworkName(network.getNetworkName());
511                 }
512             } else if (resourceType == WorkflowType.CONFIGURATION && request.getConfigurationName() == null) {
513                 org.onap.aai.domain.yang.Configuration configuration =
514                         bbInputSetupUtils.getAAIConfiguration(resourceId);
515                 if (configuration != null) {
516                     request.setConfigurationName(configuration.getConfigurationName());
517                 }
518             } else if (resourceType == WorkflowType.INSTANCE_GROUP && request.getInstanceGroupName() == null) {
519                 InstanceGroup instanceGroup = bbInputSetupUtils.getAAIInstanceGroup(resourceId);
520                 if (instanceGroup != null) {
521                     request.setInstanceGroupName(instanceGroup.getInstanceGroupName());
522                 }
523             }
524         } catch (Exception ex) {
525             logger.error("Exception in setInstanceName", ex);
526         }
527     }
528 }