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