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