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