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