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