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