2  * ============LICENSE_START=======================================================
 
   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
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
 
  23 import java.sql.Timestamp;
 
  24 import java.util.ArrayList;
 
  25 import java.util.List;
 
  26 import java.util.Optional;
 
  27 import java.util.UUID;
 
  28 import java.util.stream.Collectors;
 
  29 import javax.persistence.EntityNotFoundException;
 
  30 import org.camunda.bpm.engine.delegate.DelegateExecution;
 
  31 import org.onap.aai.domain.yang.GenericVnf;
 
  32 import org.onap.aai.domain.yang.InstanceGroup;
 
  33 import org.onap.aai.domain.yang.L3Network;
 
  34 import org.onap.aai.domain.yang.ServiceInstance;
 
  35 import org.onap.aai.domain.yang.VfModule;
 
  36 import org.onap.aai.domain.yang.Vnfc;
 
  37 import org.onap.aai.domain.yang.VolumeGroup;
 
  38 import org.onap.aaiclient.client.aai.entities.Configuration;
 
  39 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types;
 
  40 import org.onap.so.bpmn.common.DelegateExecutionImpl;
 
  41 import org.onap.so.bpmn.common.listener.db.RequestsDbListenerRunner;
 
  42 import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner;
 
  43 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
 
  44 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
 
  45 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
 
  46 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
 
  47 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
 
  48 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
 
  49 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
 
  50 import org.onap.so.client.exception.ExceptionBuilder;
 
  51 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
 
  52 import org.onap.so.db.catalog.client.CatalogDbClient;
 
  53 import org.onap.so.db.request.beans.InfraActiveRequests;
 
  54 import org.onap.so.db.request.client.RequestsDbClient;
 
  55 import org.onap.so.serviceinstancebeans.ModelType;
 
  56 import org.onap.so.serviceinstancebeans.RelatedInstance;
 
  57 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
 
  58 import org.onap.so.serviceinstancebeans.RequestReferences;
 
  59 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
 
  60 import org.slf4j.Logger;
 
  61 import org.slf4j.LoggerFactory;
 
  62 import org.springframework.beans.factory.annotation.Autowired;
 
  63 import org.springframework.core.env.Environment;
 
  64 import org.springframework.stereotype.Component;
 
  65 import com.fasterxml.jackson.core.JsonProcessingException;
 
  66 import com.fasterxml.jackson.databind.ObjectMapper;
 
  69 public class WorkflowActionBBTasks {
 
  71     private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
 
  72     private static final String G_REQUEST_ID = "mso-request-id";
 
  73     private static final String G_ALACARTE = "aLaCarte";
 
  74     private static final String G_ACTION = "requestAction";
 
  75     private static final String RETRY_COUNT = "retryCount";
 
  76     private static final String FABRIC_CONFIGURATION = "FabricConfiguration";
 
  77     private static final String ADD_FABRIC_CONFIGURATION_BB = "AddFabricConfigurationBB";
 
  78     private static final String COMPLETED = "completed";
 
  79     private static final String HANDLINGCODE = "handlingCode";
 
  80     private static final String ROLLBACKTOCREATED = "RollbackToCreated";
 
  81     private static final String ROLLBACKTOCREATEDNOCONFIGURATION = "RollbackToCreatedNoConfiguration";
 
  82     private static final String REPLACEINSTANCE = "replaceInstance";
 
  83     private static final String VFMODULE = "VfModule";
 
  84     private static final String CONFIGURATION_PATTERN = "(Ad|De)(.*)FabricConfiguration(.*)";
 
  85     protected String maxRetries = "mso.rainyDay.maxRetries";
 
  86     private static final Logger logger = LoggerFactory.getLogger(WorkflowActionBBTasks.class);
 
  89     private RequestsDbClient requestDbclient;
 
  91     private WorkflowAction workflowAction;
 
  93     private WorkflowActionBBFailure workflowActionBBFailure;
 
  95     private Environment environment;
 
  97     private BBInputSetupUtils bbInputSetupUtils;
 
  99     private CatalogDbClient catalogDbClient;
 
 101     private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
 
 103     private RequestsDbListenerRunner requestsDbListener;
 
 105     public void selectBB(DelegateExecution execution) {
 
 107             List<ExecuteBuildingBlock> flowsToExecute =
 
 108                     (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
 
 109             execution.setVariable("MacroRollback", false);
 
 111                 flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
 
 112             } catch (NullPointerException ex) {
 
 113                 workflowAction.buildAndThrowException(execution, "Error in FlowManipulator Modify Flows", ex);
 
 115             int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
 
 117             ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence);
 
 119             execution.setVariable("buildingBlock", ebb);
 
 121             execution.setVariable(COMPLETED, currentSequence >= flowsToExecute.size());
 
 122             execution.setVariable(G_CURRENT_SEQUENCE, currentSequence);
 
 123         } catch (Exception e) {
 
 124             workflowAction.buildAndThrowException(execution, "Internal Error occured during selectBB", e);
 
 128     public void updateFlowStatistics(DelegateExecution execution) {
 
 130             int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
 
 131             if (currentSequence > 1) {
 
 132                 InfraActiveRequests request = this.getUpdatedRequest(execution, currentSequence);
 
 133                 requestDbclient.updateInfraActiveRequests(request);
 
 135         } catch (Exception ex) {
 
 137                     "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.",
 
 142     protected InfraActiveRequests getUpdatedRequest(DelegateExecution execution, int currentSequence) {
 
 143         List<ExecuteBuildingBlock> flowsToExecute =
 
 144                 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
 
 145         String requestId = (String) execution.getVariable(G_REQUEST_ID);
 
 146         InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
 
 147         ExecuteBuildingBlock completedBB = flowsToExecute.get(currentSequence - 2);
 
 148         ExecuteBuildingBlock nextBB = flowsToExecute.get(currentSequence - 1);
 
 149         int completedBBs = currentSequence - 1;
 
 150         int totalBBs = flowsToExecute.size();
 
 151         int remainingBBs = totalBBs - completedBBs;
 
 152         String statusMessage = this.getStatusMessage(completedBB.getBuildingBlock().getBpmnFlowName(),
 
 153                 nextBB.getBuildingBlock().getBpmnFlowName(), completedBBs, remainingBBs);
 
 154         Long percentProgress = this.getPercentProgress(completedBBs, totalBBs);
 
 155         request.setFlowStatus(statusMessage);
 
 156         request.setProgress(percentProgress);
 
 157         request.setLastModifiedBy("CamundaBPMN");
 
 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);
 
 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
 
 173     public void sendSyncAck(DelegateExecution execution) {
 
 174         final String requestId = (String) execution.getVariable(G_REQUEST_ID);
 
 175         final String resourceId = (String) execution.getVariable("resourceId");
 
 176         ServiceInstancesResponse serviceInstancesResponse = new ServiceInstancesResponse();
 
 177         RequestReferences requestRef = new RequestReferences();
 
 178         requestRef.setInstanceId(resourceId);
 
 179         requestRef.setRequestId(requestId);
 
 180         serviceInstancesResponse.setRequestReferences(requestRef);
 
 181         ObjectMapper mapper = new ObjectMapper();
 
 182         String jsonRequest = "";
 
 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);
 
 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,
 
 197         logger.info("Successfully sent sync ack.");
 
 198         updateInstanceId(execution);
 
 201     public void sendErrorSyncAck(DelegateExecution execution) {
 
 202         final String requestId = (String) execution.getVariable(G_REQUEST_ID);
 
 204             ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
 
 205             String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
 
 206             if (errorMsg == null) {
 
 207                 errorMsg = "WorkflowAction failed unexpectedly.";
 
 209             String processKey = exceptionBuilder.getProcessKey(execution);
 
 210             String buildworkflowException =
 
 211                     "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
 
 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,
 
 220             execution.setVariable("sentSyncResponse", true);
 
 221         } catch (Exception ex) {
 
 222             logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
 
 226     public void updateRequestStatusToComplete(DelegateExecution execution) {
 
 228             final String requestId = (String) execution.getVariable(G_REQUEST_ID);
 
 229             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
 
 230             final String action = (String) execution.getVariable(G_ACTION);
 
 231             final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
 
 232             final String resourceName = (String) execution.getVariable("resourceName");
 
 233             String statusMessage = (String) execution.getVariable("StatusMessage");
 
 235             if (statusMessage == null) {
 
 237                     macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
 
 239                     macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
 
 242                 macroAction = statusMessage;
 
 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);
 
 259     public void checkRetryStatus(DelegateExecution execution) {
 
 260         String handlingCode = (String) execution.getVariable(HANDLINGCODE);
 
 261         String requestId = (String) execution.getVariable(G_REQUEST_ID);
 
 262         String retryDuration = (String) execution.getVariable("RetryDuration");
 
 263         int retryCount = (int) execution.getVariable(RETRY_COUNT);
 
 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);
 
 271         int nextCount = retryCount + 1;
 
 272         if ("Retry".equals(handlingCode)) {
 
 273             workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
 
 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);
 
 282             if (retryCount < envMaxRetries) {
 
 283                 int currSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
 
 284                 execution.setVariable(G_CURRENT_SEQUENCE, currSequence - 1);
 
 285                 execution.setVariable(RETRY_COUNT, nextCount);
 
 287                 workflowAction.buildAndThrowException(execution,
 
 288                         "Exceeded maximum retries. Ending flow with status Abort");
 
 291             execution.setVariable(RETRY_COUNT, 0);
 
 296      * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
 
 299     public void rollbackExecutionPath(DelegateExecution execution) {
 
 300         final String action = (String) execution.getVariable(G_ACTION);
 
 301         final String resourceName = (String) execution.getVariable("resourceName");
 
 302         if (!(boolean) execution.getVariable("isRollback")) {
 
 303             List<ExecuteBuildingBlock> flowsToExecute =
 
 304                     (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
 
 306             List<ExecuteBuildingBlock> flowsToExecuteChangeBBs = flowsToExecute.stream()
 
 307                     .filter(buildingBlock -> buildingBlock.getBuildingBlock().getBpmnFlowName().startsWith("Change"))
 
 308                     .collect(Collectors.toList());
 
 310             List<ExecuteBuildingBlock> rollbackFlows = new ArrayList<>();
 
 311             int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
 
 312             int listSize = flowsToExecute.size();
 
 314             for (int i = listSize - 1; i >= 0; i--) {
 
 315                 if (i > currentSequence - 1) {
 
 316                     flowsToExecute.remove(i);
 
 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");
 
 342                     flowsToExecute.get(i).getBuildingBlock().setBpmnFlowName(flowName);
 
 343                     rollbackFlows.add(flowsToExecute.get(i));
 
 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);
 
 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);
 
 374                 rollbackFlowsFiltered.clear();
 
 375                 rollbackFlowsFiltered.addAll(flowsToExecuteChangeBBs);
 
 376                 rollbackFlowsFiltered.addAll(rollbackFlowsFilteredNonChangeBBs);
 
 379             workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
 
 380             execution.setVariable("isRollbackNeeded", !rollbackFlows.isEmpty());
 
 381             execution.setVariable("flowsToExecute", rollbackFlowsFiltered);
 
 382             execution.setVariable(HANDLINGCODE, "PreformingRollback");
 
 383             execution.setVariable("isRollback", true);
 
 384             execution.setVariable(G_CURRENT_SEQUENCE, 0);
 
 385             execution.setVariable(RETRY_COUNT, 0);
 
 387             workflowAction.buildAndThrowException(execution,
 
 388                     "Rollback has already been called. Cannot rollback a request that is currently in the rollback state.");
 
 392     protected void updateInstanceId(DelegateExecution execution) {
 
 394             String requestId = (String) execution.getVariable(G_REQUEST_ID);
 
 395             String resourceId = (String) execution.getVariable("resourceId");
 
 396             WorkflowType resourceType = (WorkflowType) execution.getVariable("resourceType");
 
 397             InfraActiveRequests request = requestDbclient.getInfraActiveRequestbyRequestId(requestId);
 
 398             if (resourceType == WorkflowType.SERVICE) {
 
 399                 request.setServiceInstanceId(resourceId);
 
 400             } else if (resourceType == WorkflowType.VNF) {
 
 401                 request.setVnfId(resourceId);
 
 402             } else if (resourceType == WorkflowType.VFMODULE) {
 
 403                 request.setVfModuleId(resourceId);
 
 404             } else if (resourceType == WorkflowType.VOLUMEGROUP) {
 
 405                 request.setVolumeGroupId(resourceId);
 
 406             } else if (resourceType == WorkflowType.NETWORK) {
 
 407                 request.setNetworkId(resourceId);
 
 408             } else if (resourceType == WorkflowType.CONFIGURATION) {
 
 409                 request.setConfigurationId(resourceId);
 
 410             } else if (resourceType == WorkflowType.INSTANCE_GROUP) {
 
 411                 request.setInstanceGroupId(resourceId);
 
 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");
 
 422     public void postProcessingExecuteBB(DelegateExecution execution) {
 
 423         List<ExecuteBuildingBlock> flowsToExecute =
 
 424                 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
 
 425         String handlingCode = (String) execution.getVariable(HANDLINGCODE);
 
 426         final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
 
 427         int currentSequence = (int) execution.getVariable(G_CURRENT_SEQUENCE);
 
 428         ExecuteBuildingBlock ebb = flowsToExecute.get(currentSequence - 1);
 
 429         String bbFlowName = ebb.getBuildingBlock().getBpmnFlowName();
 
 430         if ("ActivateVfModuleBB".equalsIgnoreCase(bbFlowName) && aLaCarte && "Success".equalsIgnoreCase(handlingCode)) {
 
 431             postProcessingExecuteBBActivateVfModule(execution, ebb, flowsToExecute);
 
 434         flowManipulatorListenerRunner.postModifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
 
 437     protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
 
 438             List<ExecuteBuildingBlock> flowsToExecute) {
 
 440             String requestAction = (String) execution.getVariable(G_ACTION);
 
 441             String serviceInstanceId = ebb.getWorkflowResourceIds().getServiceInstanceId();
 
 442             String vnfId = ebb.getWorkflowResourceIds().getVnfId();
 
 443             String vfModuleId = ebb.getResourceId();
 
 444             ebb.getWorkflowResourceIds().setVfModuleId(vfModuleId);
 
 445             String serviceModelUUID = "";
 
 446             String vnfCustomizationUUID = "";
 
 447             String vfModuleCustomizationUUID = "";
 
 448             if (requestAction.equalsIgnoreCase("replaceInstance")
 
 449                     || requestAction.equalsIgnoreCase("replaceInstanceRetainAssignments")) {
 
 450                 for (RelatedInstanceList relatedInstList : ebb.getRequestDetails().getRelatedInstanceList()) {
 
 451                     RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
 
 452                     if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
 
 453                         vnfCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
 
 455                     if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) {
 
 456                         serviceModelUUID = relatedInstance.getModelInfo().getModelVersionId();
 
 459                 vfModuleCustomizationUUID = ebb.getRequestDetails().getModelInfo().getModelCustomizationId();
 
 461                 serviceModelUUID = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
 
 462                 vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
 
 463                 vfModuleCustomizationUUID =
 
 464                         bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
 
 466             List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, Types.VNFC);
 
 467             logger.debug("Vnfc Size: {}", vnfcs.size());
 
 468             for (Vnfc vnfc : vnfcs) {
 
 469                 String modelCustomizationId = vnfc.getModelCustomizationId();
 
 470                 logger.debug("Processing Vnfc: {}", modelCustomizationId);
 
 471                 CvnfcConfigurationCustomization fabricConfig = catalogDbClient.getCvnfcCustomization(serviceModelUUID,
 
 472                         vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId);
 
 473                 if (fabricConfig != null && fabricConfig.getConfigurationResource() != null
 
 474                         && fabricConfig.getConfigurationResource().getToscaNodeType() != null
 
 475                         && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) {
 
 476                     String configurationId = getConfigurationId(vnfc);
 
 477                     ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
 
 478                     configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId);
 
 479                     configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID);
 
 480                     configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID);
 
 481                     configurationResourceKeys.setVnfcName(vnfc.getVnfcName());
 
 482                     ExecuteBuildingBlock addConfigBB = getExecuteBBForConfig(ADD_FABRIC_CONFIGURATION_BB, ebb,
 
 483                             configurationId, configurationResourceKeys);
 
 484                     flowsToExecute.add(addConfigBB);
 
 485                     flowsToExecute.stream()
 
 486                             .forEach(executeBB -> logger.info("Flows to Execute After Post Processing: {}",
 
 487                                     executeBB.getBuildingBlock().getBpmnFlowName()));
 
 488                     execution.setVariable("flowsToExecute", flowsToExecute);
 
 489                     execution.setVariable(COMPLETED, false);
 
 491                     logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
 
 494         } catch (EntityNotFoundException e) {
 
 495             logger.debug("Will not be running Fabric Config Building Blocks", e);
 
 496         } catch (Exception e) {
 
 497             String errorMessage = "Error occurred in post processing of Vf Module create";
 
 498             execution.setVariable(HANDLINGCODE, ROLLBACKTOCREATED);
 
 499             execution.setVariable("WorkflowActionErrorMessage", errorMessage);
 
 500             logger.error(errorMessage, e);
 
 504     protected String getConfigurationId(Vnfc vnfc) throws Exception {
 
 505         Configuration configuration =
 
 506                 workflowAction.getRelatedResourcesInVnfc(vnfc, Configuration.class, Types.CONFIGURATION);
 
 507         if (configuration != null) {
 
 508             return configuration.getConfigurationId();
 
 510             return UUID.randomUUID().toString();
 
 514     protected ExecuteBuildingBlock getExecuteBBForConfig(String bbName, ExecuteBuildingBlock ebb,
 
 515             String configurationId, ConfigurationResourceKeys configurationResourceKeys) {
 
 516         BuildingBlock buildingBlock =
 
 517                 new BuildingBlock().setBpmnFlowName(bbName).setMsoId(UUID.randomUUID().toString());
 
 519         WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(ebb.getWorkflowResourceIds());
 
 520         workflowResourceIds.setConfigurationId(configurationId);
 
 521         return new ExecuteBuildingBlock().setaLaCarte(ebb.isaLaCarte()).setApiVersion(ebb.getApiVersion())
 
 522                 .setRequestAction(ebb.getRequestAction()).setVnfType(ebb.getVnfType()).setRequestId(ebb.getRequestId())
 
 523                 .setRequestDetails(ebb.getRequestDetails()).setBuildingBlock(buildingBlock)
 
 524                 .setWorkflowResourceIds(workflowResourceIds).setConfigurationResourceKeys(configurationResourceKeys);
 
 527     protected void setInstanceName(String resourceId, WorkflowType resourceType, InfraActiveRequests request) {
 
 528         logger.debug("Setting instanceName in infraActiveRequest");
 
 530             if (resourceType == WorkflowType.SERVICE && request.getServiceInstanceName() == null) {
 
 531                 ServiceInstance service = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
 
 532                 if (service != null) {
 
 533                     request.setServiceInstanceName(service.getServiceInstanceName());
 
 535             } else if (resourceType == WorkflowType.VNF && request.getVnfName() == null) {
 
 536                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(resourceId);
 
 538                     request.setVnfName(vnf.getVnfName());
 
 540             } else if (resourceType == WorkflowType.VFMODULE && request.getVfModuleName() == null) {
 
 541                 VfModule vfModule = bbInputSetupUtils.getAAIVfModule(request.getVnfId(), resourceId);
 
 542                 if (vfModule != null) {
 
 543                     request.setVfModuleName(vfModule.getVfModuleName());
 
 545             } else if (resourceType == WorkflowType.VOLUMEGROUP && request.getVolumeGroupName() == null) {
 
 546                 Optional<VolumeGroup> volumeGroup =
 
 547                         bbInputSetupUtils.getRelatedVolumeGroupByIdFromVnf(request.getVnfId(), resourceId);
 
 548                 volumeGroup.ifPresent(group -> request.setVolumeGroupName(group.getVolumeGroupName()));
 
 549             } else if (resourceType == WorkflowType.NETWORK && request.getNetworkName() == null) {
 
 550                 L3Network network = bbInputSetupUtils.getAAIL3Network(resourceId);
 
 551                 if (network != null) {
 
 552                     request.setNetworkName(network.getNetworkName());
 
 554             } else if (resourceType == WorkflowType.CONFIGURATION && request.getConfigurationName() == null) {
 
 555                 org.onap.aai.domain.yang.Configuration configuration =
 
 556                         bbInputSetupUtils.getAAIConfiguration(resourceId);
 
 557                 if (configuration != null) {
 
 558                     request.setConfigurationName(configuration.getConfigurationName());
 
 560             } else if (resourceType == WorkflowType.INSTANCE_GROUP && request.getInstanceGroupName() == null) {
 
 561                 InstanceGroup instanceGroup = bbInputSetupUtils.getAAIInstanceGroup(resourceId);
 
 562                 if (instanceGroup != null) {
 
 563                     request.setInstanceGroupName(instanceGroup.getInstanceGroupName());
 
 566         } catch (Exception ex) {
 
 567             logger.error("Exception in setInstanceName", ex);