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