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