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