b76cf1eb5f84576705c10af442605534fe709013
[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.BBConstants;
41 import org.onap.so.bpmn.common.DelegateExecutionImpl;
42 import org.onap.so.bpmn.common.listener.db.RequestsDbListenerRunner;
43 import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner;
44 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
45 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
46 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
47 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
48 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
49 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
50 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
51 import org.onap.so.client.exception.ExceptionBuilder;
52 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
53 import org.onap.so.db.catalog.client.CatalogDbClient;
54 import org.onap.so.db.request.beans.InfraActiveRequests;
55 import org.onap.so.db.request.client.RequestsDbClient;
56 import org.onap.so.serviceinstancebeans.ModelType;
57 import org.onap.so.serviceinstancebeans.RelatedInstance;
58 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
59 import org.onap.so.serviceinstancebeans.RequestReferences;
60 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.core.env.Environment;
65 import org.springframework.stereotype.Component;
66 import com.fasterxml.jackson.core.JsonProcessingException;
67 import com.fasterxml.jackson.databind.ObjectMapper;
68
69 @Component
70 public class WorkflowActionBBTasks {
71
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(BBConstants.G_CURRENT_SEQUENCE);
113
114             boolean completed = false;
115             if (currentSequence < flowsToExecute.size()) {
116                 ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
117                 execution.setVariable("buildingBlock", ebb);
118                 execution.setVariable(BBConstants.G_CURRENT_SEQUENCE, currentSequence + 1);
119             } else {
120                 completed = true;
121             }
122             execution.setVariable(COMPLETED, completed);
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(BBConstants.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(BBConstants.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(BBConstants.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(BBConstants.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(BBConstants.G_REQUEST_ID);
229             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
230             final String action = (String) execution.getVariable(BBConstants.G_ACTION);
231             final boolean aLaCarte = (boolean) execution.getVariable(BBConstants.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(BBConstants.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(BBConstants.G_CURRENT_SEQUENCE);
284                 execution.setVariable(BBConstants.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(BBConstants.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(BBConstants.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(BBConstants.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(BBConstants.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(BBConstants.G_ALACARTE);
428             int currentSequence = (int) execution.getVariable(BBConstants.G_CURRENT_SEQUENCE);
429             logger.debug("Current Sequence: {}", currentSequence);
430             if (currentSequence >= flowsToExecute.size()) {
431                 execution.setVariable(COMPLETED, true);
432             }
433             ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
434             String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
435             if ("ActivateVfModuleBB".equalsIgnoreCase(bbFlowName) && aLaCarte
436                     && "Success".equalsIgnoreCase(handlingCode)) {
437                 postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
438             }
439
440             flowManipulatorListenerRunner.postModifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
441         } catch (Exception ex) {
442             logger.error("Exception in postProcessingExecuteBB", ex);
443             workflowAction.buildAndThrowException(execution, "Failed to post process Execute BB");
444         }
445     }
446
447     protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
448             List<ExecuteBuildingBlock> flowsToExecute) {
449         try {
450             String requestAction = (String) execution.getVariable(BBConstants.G_ACTION);
451             String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
452             String vnfId = ebb.getWorkflowResourceIds().getVnfId();
453             String vfModuleId = ebb.getResourceId();
454             ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
455             String serviceModelUUID = "";
456             String vnfCustomizationUUID = "";
457             String vfModuleCustomizationUUID = "";
458             if (requestAction.equalsIgnoreCase("replaceInstance")
459                     || requestAction.equalsIgnoreCase("replaceInstanceRetainAssignments")) {
460                 for (RelatedInstanceList relatedInstList : ebb.getRequestDetails().getRelatedInstanceList()) {
461                     RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
462                     if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
463                         vnfCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
464                     }
465                     if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) {
466                         serviceModelUUID = relatedInstance.getModelInfo().getModelVersionId();
467                     }
468                 }
469                 vfModuleCustomizationUUID = ebb.getRequestDetails().getModelInfo().getModelCustomizationId();
470             } else {
471                 serviceModelUUID = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
472                 vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
473                 vfModuleCustomizationUUID =
474                         bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
475             }
476             List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, Types.VNFC);
477             logger.debug("Vnfc Size: {}", vnfcs.size());
478             for (Vnfc vnfc : vnfcs) {
479                 String modelCustomizationId = vnfc.getModelCustomizationId();
480                 logger.debug("Processing Vnfc: {}", modelCustomizationId);
481                 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
482                         vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
483                 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
484                         && fabricConfig.getConfigurationResource().getToscaNodeType() != null
485                         && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
486                     String configurationId = getConfigurationId(vnfc);
487                     ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
488                     configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
489                     configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
490                     configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
491                     configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
492                     ExecuteBuildingBlock addConfigBB = getExecuteBBForConfig(ADD_FABRIC_CONFIGURATION_BB, ebb,
493                             configurationId, configurationResourceKeys);
494                     flowsToExecute.add(addConfigBB);
495                     flowsToExecute.stream()
496                             .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
497                                     executeBB.getBuildingBlock().getBpmnFlowName()));
498                     execution.setVariable("flowsToExecute", flowsToExecute);
499                     execution.setVariable(COMPLETED, false);
500                 } else {
501                     logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
502                 }
503             }
504         } catch (EntityNotFoundException e) {
505             logger.debug("Will not be running Fabric Config Building Blocks", e);
506         } catch (Exception e) {
507             String errorMessage = "Error occurred in post processing of Vf Module create";
508             execution.setVariable(HANDLINGCODE, ROLLBACKTOCREATED);
509             execution.setVariable("WorkflowActionErrorMessage", errorMessage);
510             logger.error(errorMessage, e);
511         }
512     }
513
514     protected String getConfigurationId(Vnfc vnfc) throws Exception {
515         Configuration configuration =
516                 workflowAction.getRelatedResourcesInVnfc(vnfc, Configuration.class, Types.CONFIGURATION);
517         if (configuration != null) {
518             return configuration.getConfigurationId();
519         } else {
520             return UUID.randomUUID().toString();
521         }
522     }
523
524     protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
525             String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
526         BuildingBlock buildingBlock =
527                 new BuildingBlock().setBpmnFlowName(bbName).setMsoId(UUID.randomUUID().toString());
528
529         WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(ebb.getWorkflowResourceIds());
530         workflowResourceIds.setConfigurationId(configurationId);
531         return new ExecuteBuildingBlock().setaLaCarte(ebb.isaLaCarte()).setApiVersion(ebb.getApiVersion())
532                 .setRequestAction(ebb.getRequestAction()).setVnfType(ebb.getVnfType()).setRequestId(ebb.getRequestId())
533                 .setRequestDetails(ebb.getRequestDetails()).setBuildingBlock(buildingBlock)
534                 .setWorkflowResourceIds(workflowResourceIds).setConfigurationResourceKeys(configurationResourceKeys);
535     }
536
537     protected void setInstanceName(String resourceId, WorkflowType resourceType, InfraActiveRequests request) {
538         logger.debug("Setting instanceName in infraActiveRequest");
539         try {
540             if (resourceType == WorkflowType.SERVICE && request.getServiceInstanceName() == null) {
541                 ServiceInstance service = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
542                 if (service != null) {
543                     request.setServiceInstanceName(service.getServiceInstanceName());
544                 }
545             } else if (resourceType == WorkflowType.VNF && request.getVnfName() == null) {
546                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(resourceId);
547                 if (vnf != null) {
548                     request.setVnfName(vnf.getVnfName());
549                 }
550             } else if (resourceType == WorkflowType.VFMODULE && request.getVfModuleName() == null) {
551                 VfModule vfModule = bbInputSetupUtils.getAAIVfModule(request.getVnfId(), resourceId);
552                 if (vfModule != null) {
553                     request.setVfModuleName(vfModule.getVfModuleName());
554                 }
555             } else if (resourceType == WorkflowType.VOLUMEGROUP && request.getVolumeGroupName() == null) {
556                 Optional<VolumeGroup> volumeGroup =
557                         bbInputSetupUtils.getRelatedVolumeGroupByIdFromVnf(request.getVnfId(), resourceId);
558                 volumeGroup.ifPresent(group -> request.setVolumeGroupName(group.getVolumeGroupName()));
559             } else if (resourceType == WorkflowType.NETWORK && request.getNetworkName() == null) {
560                 L3Network network = bbInputSetupUtils.getAAIL3Network(resourceId);
561                 if (network != null) {
562                     request.setNetworkName(network.getNetworkName());
563                 }
564             } else if (resourceType == WorkflowType.CONFIGURATION && request.getConfigurationName() == null) {
565                 org.onap.aai.domain.yang.Configuration configuration =
566                         bbInputSetupUtils.getAAIConfiguration(resourceId);
567                 if (configuration != null) {
568                     request.setConfigurationName(configuration.getConfigurationName());
569                 }
570             } else if (resourceType == WorkflowType.INSTANCE_GROUP && request.getInstanceGroupName() == null) {
571                 InstanceGroup instanceGroup = bbInputSetupUtils.getAAIInstanceGroup(resourceId);
572                 if (instanceGroup != null) {
573                     request.setInstanceGroupName(instanceGroup.getInstanceGroupName());
574                 }
575             }
576         } catch (Exception ex) {
577             logger.error("Exception in setInstanceName", ex);
578         }
579     }
580 }