2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
23 import java.sql.Timestamp;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.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;
72 public class WorkflowActionBBTasks {
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);
91 private RequestsDbClient requestDbclient;
93 private WorkflowAction workflowAction;
95 private WorkflowActionBBFailure workflowActionBBFailure;
97 private Environment environment;
99 private BBInputSetupUtils bbInputSetupUtils;
101 private CatalogDbClient catalogDbClient;
103 private FlowManipulatorListenerRunner flowManipulatorListenerRunner;
105 private RequestsDbListenerRunner requestsDbListener;
107 public void selectBB(DelegateExecution execution) {
109 List<ExecuteBuildingBlock> flowsToExecute =
110 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
111 execution.setVariable("MacroRollback", false);
113 flowManipulatorListenerRunner.modifyFlows(flowsToExecute, new DelegateExecutionImpl(execution));
114 } catch (NullPointerException ex) {
115 workflowAction.buildAndThrowException(execution, "Error in FlowManipulator Modify Flows", ex);
117 int currentSequence = (int) execution.getVariable(BBConstants.G_CURRENT_SEQUENCE);
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);
127 execution.setVariable(COMPLETED, completed);
128 } catch (Exception e) {
129 workflowAction.buildAndThrowException(execution, "Internal Error occured during selectBB", e);
133 public void updateFlowStatistics(DelegateExecution execution) {
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);
140 } catch (Exception ex) {
142 "Bpmn Flow Statistics was unable to update Request Db with the new completion percentage. Competion percentage may be invalid.",
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");
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);
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
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 = "";
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);
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,
202 logger.info("Successfully sent sync ack.");
203 updateInstanceId(execution);
206 public void sendErrorSyncAck(DelegateExecution execution) {
207 final String requestId = (String) execution.getVariable(BBConstants.G_REQUEST_ID);
209 ExceptionBuilder exceptionBuilder = new ExceptionBuilder();
210 String errorMsg = (String) execution.getVariable("WorkflowActionErrorMessage");
211 if (errorMsg == null) {
212 errorMsg = "WorkflowAction failed unexpectedly.";
214 String processKey = exceptionBuilder.getProcessKey(execution);
215 String buildworkflowException =
216 "<aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>"
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,
225 execution.setVariable("sentSyncResponse", true);
226 } catch (Exception ex) {
227 logger.error(" Sending Sync Error Activity Failed. {}", ex.getMessage(), ex);
231 public void updateRequestStatusToComplete(DelegateExecution execution) {
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");
240 if (statusMessage == null) {
242 macroAction = "ALaCarte-" + resourceName + "-" + action + " request was executed correctly.";
244 macroAction = "Macro-" + resourceName + "-" + action + " request was executed correctly.";
247 macroAction = statusMessage;
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);
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);
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);
276 int nextCount = retryCount + 1;
277 if ("Retry".equals(handlingCode)) {
278 workflowActionBBFailure.updateRequestErrorStatusMessage(execution);
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);
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);
292 workflowAction.buildAndThrowException(execution,
293 "Exceeded maximum retries. Ending flow with status Abort");
296 execution.setVariable(RETRY_COUNT, 0);
301 * Rollback will only handle Create/Activate/Assign Macro flows. Execute layer will rollback the flow its currently
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.");
311 List<ExecuteBuildingBlock> flowsToExecute =
312 (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute");
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();
322 for (int i = listSize - 1; i >= 0; i--) {
323 if (i > currentSequence - 1) {
324 flowsToExecute.remove(i);
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");
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());
351 rollbackFlows.add(flowsToExecute.get(i));
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);
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);
382 rollbackFlowsFiltered.clear();
383 rollbackFlowsFiltered.addAll(flowsToExecuteChangeBBs);
384 rollbackFlowsFiltered.addAll(rollbackFlowsFilteredNonChangeBBs);
387 logger.info("List of BuildingBlocks to execute for rollback");
388 rollbackFlowsFiltered.forEach(item -> {
389 logger.info(item.getBuildingBlock().getBpmnFlowName());
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);
401 protected void updateInstanceId(DelegateExecution execution) {
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);
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");
431 public void postProcessingExecuteBB(DelegateExecution execution) {
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);
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);
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");
456 protected void postProcessingExecuteBBActivateVfModule(DelegateExecution execution, ExecuteBuildingBlock ebb,
457 List<ExecuteBuildingBlock> flowsToExecute) {
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();
474 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) {
475 serviceModelUUID = relatedInstance.getModelInfo().getModelVersionId();
478 vfModuleCustomizationUUID = ebb.getRequestDetails().getModelInfo().getModelCustomizationId();
480 serviceModelUUID = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId).getModelVersionId();
481 vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
482 vfModuleCustomizationUUID =
483 bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId();
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);
510 logger.debug("No cvnfcCustomization found for customizationId: {}", modelCustomizationId);
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);
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();
529 return UUID.randomUUID().toString();
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());
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);
546 protected void setInstanceName(String resourceId, WorkflowType resourceType, InfraActiveRequests request) {
547 logger.debug("Setting instanceName in infraActiveRequest");
549 if (resourceType == WorkflowType.SERVICE && request.getServiceInstanceName() == null) {
550 ServiceInstance service = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
551 if (service != null) {
552 request.setServiceInstanceName(service.getServiceInstanceName());
554 } else if (resourceType == WorkflowType.VNF && request.getVnfName() == null) {
555 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(resourceId);
557 request.setVnfName(vnf.getVnfName());
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());
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());
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());
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());
585 } catch (Exception ex) {
586 logger.error("Exception in setInstanceName", ex);