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