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