Support instantiation of same model vnfs/vf-modules
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / workflow / tasks / WorkflowAction.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Modifications Copyright (c) 2021 Nokia
10  * ================================================================================
11  * Modifications Copyright (c) 2020 Tech Mahindra
12  * ================================================================================
13  * Modifications Copyright (c) 2021 Orange
14  * ================================================================================
15  * Licensed under the Apache License, Version 2.0 (the "License");
16  * you may not use this file except in compliance with the License.
17  * You may obtain a copy of the License at
18  *
19  *      http://www.apache.org/licenses/LICENSE-2.0
20  *
21  * Unless required by applicable law or agreed to in writing, software
22  * distributed under the License is distributed on an "AS IS" BASIS,
23  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24  * See the License for the specific language governing permissions and
25  * limitations under the License.
26  * ============LICENSE_END=========================================================
27  */
28
29 package org.onap.so.bpmn.infrastructure.workflow.tasks;
30
31 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.ASSIGN_INSTANCE;
32 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.CONTROLLER;
33 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.CREATE_INSTANCE;
34 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.DELETE_INSTANCE;
35 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.FABRIC_CONFIGURATION;
36 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.RECREATE_INSTANCE;
37 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.REPLACEINSTANCE;
38 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.REPLACEINSTANCERETAINASSIGNMENTS;
39 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.SERVICE;
40 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.UPDATE_INSTANCE;
41 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.WORKFLOW_ACTION_ERROR_MESSAGE;
42 import java.io.IOException;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Comparator;
46 import java.util.HashMap;
47 import java.util.LinkedHashSet;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Optional;
51 import java.util.Set;
52 import java.util.UUID;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55 import java.util.stream.Collectors;
56 import org.apache.commons.lang3.SerializationUtils;
57 import org.apache.commons.lang3.StringUtils;
58 import org.camunda.bpm.engine.delegate.DelegateExecution;
59 import org.javatuples.Pair;
60 import org.onap.aai.domain.yang.Vnfc;
61 import org.onap.aai.domain.yang.VolumeGroup;
62 import org.onap.aaiclient.client.aai.AAIObjectName;
63 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
64 import org.onap.aaiclient.client.aai.entities.Relationships;
65 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
66 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
67 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder;
68 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types;
69 import org.onap.so.bpmn.common.BBConstants;
70 import org.onap.so.bpmn.infrastructure.workflow.tasks.ebb.loader.ServiceEBBLoader;
71 import org.onap.so.bpmn.infrastructure.workflow.tasks.ebb.loader.VnfEBBLoader;
72 import org.onap.so.bpmn.infrastructure.workflow.tasks.excpetion.VnfcMultipleRelationshipException;
73 import org.onap.so.bpmn.infrastructure.workflow.tasks.utils.WorkflowResourceIdsUtils;
74 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
75 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
76 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup;
77 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
78 import org.onap.so.client.exception.ExceptionBuilder;
79 import org.onap.so.client.orchestration.AAIEntityNotFoundException;
80 import org.onap.so.db.catalog.beans.VfModuleCustomization;
81 import org.onap.so.db.catalog.beans.macro.NorthBoundRequest;
82 import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
83 import org.onap.so.db.catalog.client.CatalogDbClient;
84 import org.onap.so.serviceinstancebeans.CloudConfiguration;
85 import org.onap.so.serviceinstancebeans.ModelInfo;
86 import org.onap.so.serviceinstancebeans.ModelType;
87 import org.onap.so.serviceinstancebeans.RelatedInstance;
88 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
89 import org.onap.so.serviceinstancebeans.RequestDetails;
90 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.springframework.beans.factory.annotation.Autowired;
94 import org.springframework.core.env.Environment;
95 import org.springframework.stereotype.Component;
96 import org.springframework.util.CollectionUtils;
97 import com.fasterxml.jackson.databind.ObjectMapper;
98
99 @Component
100 public class WorkflowAction {
101
102     private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class);
103
104     private static final String SERVICE_INSTANCES = "serviceInstances";
105     private static final String VF_MODULES = "vfModules";
106     private static final String VNF_TYPE = "vnfType";
107     private static final String CONFIGURATION = "Configuration";
108     private static final String SUPPORTEDTYPES =
109             "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups";
110     private static final String HOMINGSOLUTION = "Homing_Solution";
111     private static final String SERVICE_TYPE_TRANSPORT = "TRANSPORT";
112     private static final String SERVICE_TYPE_BONDING = "BONDING";
113     private static final String CLOUD_OWNER = "DEFAULT";
114     private static final String CREATENETWORKBB = "CreateNetworkBB";
115     private static final String ACTIVATENETWORKBB = "ActivateNetworkBB";
116     private static final String VOLUMEGROUP_DELETE_PATTERN = "(Un|De)(.*)Volume(.*)";
117     private static final String VOLUMEGROUP_CREATE_PATTERN = "(A|C)(.*)Volume(.*)";
118     private static final String DEFAULT_CLOUD_OWNER = "org.onap.so.cloud-owner";
119     private static final String HOMING = "homing";
120
121     @Autowired
122     protected BBInputSetup bbInputSetup;
123     @Autowired
124     protected BBInputSetupUtils bbInputSetupUtils;
125     @Autowired
126     private ExceptionBuilder exceptionBuilder;
127     @Autowired
128     private CatalogDbClient catalogDbClient;
129     @Autowired
130     private Environment environment;
131     @Autowired
132     private AaiResourceIdValidator aaiResourceIdValidator;
133     @Autowired
134     private ExecuteBuildingBlockBuilder executeBuildingBlockBuilder;
135     @Autowired
136     private VnfEBBLoader vnfEBBLoader;
137     @Autowired
138     private ServiceEBBLoader serviceEBBLoader;
139
140     public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
141         this.bbInputSetupUtils = bbInputSetupUtils;
142     }
143
144     public void setBbInputSetup(BBInputSetup bbInputSetup) {
145         this.bbInputSetup = bbInputSetup;
146     }
147
148     public void selectExecutionList(DelegateExecution execution) throws Exception {
149         try {
150             fillExecutionDefault(execution);
151             final String bpmnRequest = (String) execution.getVariable(BBConstants.G_BPMN_REQUEST);
152             ServiceInstancesRequest sIRequest =
153                     new ObjectMapper().readValue(bpmnRequest, ServiceInstancesRequest.class);
154
155             final String requestId = (String) execution.getVariable(BBConstants.G_REQUEST_ID);
156
157             String uri = (String) execution.getVariable(BBConstants.G_URI);
158             boolean isResume = isUriResume(uri);
159
160             final boolean isALaCarte = (boolean) execution.getVariable(BBConstants.G_ALACARTE);
161             Resource resource = getResource(bbInputSetupUtils, isResume, isALaCarte, uri, requestId);
162
163             WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution);
164             RequestDetails requestDetails = sIRequest.getRequestDetails();
165             String requestAction = (String) execution.getVariable(BBConstants.G_ACTION);
166             String resourceId = getResourceId(resource, requestAction, requestDetails, workflowResourceIds);
167             WorkflowType resourceType = resource.getResourceType();
168
169             String serviceInstanceId = getServiceInstanceId(execution, resourceId, resourceType);
170
171             fillExecution(execution, requestDetails.getRequestInfo().getSuppressRollback(), resourceId, resourceType);
172             List<ExecuteBuildingBlock> flowsToExecute;
173             if (isRequestMacroServiceResume(isALaCarte, resourceType, requestAction, serviceInstanceId)) {
174                 String errorMessage = "Could not resume Macro flow. Error loading execution path.";
175                 flowsToExecute = loadExecuteBuildingBlocks(execution, requestId, errorMessage);
176             } else if (isALaCarte && isResume) {
177                 String errorMessage =
178                         "Could not resume request with request Id: " + requestId + ". No flowsToExecute was found";
179                 flowsToExecute = loadExecuteBuildingBlocks(execution, requestId, errorMessage);
180             } else {
181                 String vnfType = (String) execution.getVariable(VNF_TYPE);
182                 String cloudOwner = getCloudOwner(requestDetails.getCloudConfiguration());
183                 List<OrchestrationFlow> orchFlows =
184                         (List<OrchestrationFlow>) execution.getVariable(BBConstants.G_ORCHESTRATION_FLOW);
185                 final String apiVersion = (String) execution.getVariable(BBConstants.G_APIVERSION);
186                 final String serviceType =
187                         Optional.ofNullable((String) execution.getVariable(BBConstants.G_SERVICE_TYPE)).orElse("");
188                 if (isALaCarte) {
189                     flowsToExecute = loadExecuteBuildingBlocksForAlaCarte(orchFlows, execution, requestAction,
190                             resourceType, cloudOwner, serviceType, sIRequest, requestId, workflowResourceIds,
191                             requestDetails, resourceId, vnfType, apiVersion);
192                 } else {
193                     flowsToExecute = loadExecuteBuildingBlocksForMacro(sIRequest, resourceType, requestAction,
194                             execution, serviceInstanceId, resourceId, workflowResourceIds, orchFlows, cloudOwner,
195                             serviceType, requestId, apiVersion, vnfType, requestDetails);
196                 }
197             }
198             // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified,
199             // enable it.
200             if (sIRequest.getRequestDetails().getRequestParameters() != null
201                     && sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
202                 List<Map<String, Object>> userParams =
203                         sIRequest.getRequestDetails().getRequestParameters().getUserParams();
204                 for (Map<String, Object> params : userParams) {
205                     if (params.containsKey(HOMINGSOLUTION)) {
206                         execution.setVariable(HOMING, !"none".equals(params.get(HOMINGSOLUTION)));
207                     }
208                 }
209             }
210
211             if (CollectionUtils.isEmpty(flowsToExecute)) {
212                 throw new IllegalStateException("Macro did not come up with a valid execution path.");
213             }
214
215             List<String> flowNames = new ArrayList<>();
216             logger.info("List of BuildingBlocks to execute:");
217
218             flowsToExecute.forEach(ebb -> {
219                 logger.info(ebb.getBuildingBlock().getBpmnFlowName());
220                 flowNames.add(ebb.getBuildingBlock().getBpmnFlowName());
221             });
222
223             if (!isResume) {
224                 bbInputSetupUtils.persistFlowExecutionPath(requestId, flowsToExecute);
225             }
226             setExecutionVariables(execution, flowsToExecute, flowNames);
227
228         } catch (Exception ex) {
229             if (!(execution.hasVariable("WorkflowException")
230                     || execution.hasVariable("WorkflowExceptionExceptionMessage"))) {
231                 buildAndThrowException(execution, "Exception while setting execution list. ", ex);
232             } else {
233                 throw ex;
234             }
235         }
236     }
237
238     private List<ExecuteBuildingBlock> loadExecuteBuildingBlocksForAlaCarte(List<OrchestrationFlow> orchFlows,
239             DelegateExecution execution, String requestAction, WorkflowType resourceType, String cloudOwner,
240             String serviceType, ServiceInstancesRequest sIRequest, String requestId,
241             WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, String resourceId, String vnfType,
242             String apiVersion) throws Exception {
243         List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
244         if (orchFlows == null || orchFlows.isEmpty()) {
245             orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, true, cloudOwner,
246                     serviceType);
247         }
248         Resource resourceKey = getResourceKey(sIRequest, resourceType);
249
250         ReplaceInstanceRelatedInformation replaceInfo = new ReplaceInstanceRelatedInformation();
251         if ((requestAction.equalsIgnoreCase(REPLACEINSTANCE)
252                 || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS))
253                 && resourceType.equals(WorkflowType.VFMODULE)) {
254             logger.debug("Build a BB list for replacing BB modules");
255             ConfigBuildingBlocksDataObject cbbdo = createConfigBuildingBlocksDataObject(execution, sIRequest, requestId,
256                     workflowResourceIds, requestDetails, requestAction, resourceId, vnfType, orchFlows, apiVersion,
257                     resourceKey, replaceInfo);
258             orchFlows = getVfModuleReplaceBuildingBlocks(cbbdo);
259
260             createBuildingBlocksForOrchFlows(execution, sIRequest, requestId, workflowResourceIds, requestDetails,
261                     requestAction, resourceId, flowsToExecute, vnfType, orchFlows, apiVersion, resourceKey,
262                     replaceInfo);
263         } else {
264             if (isConfiguration(orchFlows) && !requestAction.equalsIgnoreCase(CREATE_INSTANCE)) {
265                 addConfigBuildingBlocksToFlowsToExecuteList(execution, sIRequest, requestId, workflowResourceIds,
266                         requestDetails, requestAction, resourceId, flowsToExecute, vnfType, apiVersion, resourceKey,
267                         replaceInfo, orchFlows);
268             }
269             orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION))
270                     .collect(Collectors.toList());
271
272             for (OrchestrationFlow orchFlow : orchFlows) {
273                 ExecuteBuildingBlock ebb = executeBuildingBlockBuilder.buildExecuteBuildingBlock(orchFlow, requestId,
274                         resourceKey, apiVersion, resourceId, requestAction, true, vnfType, workflowResourceIds,
275                         requestDetails, false, null, null, false, replaceInfo);
276                 flowsToExecute.add(ebb);
277             }
278         }
279         return flowsToExecute;
280     }
281
282     private List<ExecuteBuildingBlock> loadExecuteBuildingBlocksForMacro(ServiceInstancesRequest sIRequest,
283             WorkflowType resourceType, String requestAction, DelegateExecution execution, String serviceInstanceId,
284             String resourceId, WorkflowResourceIds workflowResourceIds, List<OrchestrationFlow> orchFlows,
285             String cloudOwner, String serviceType, String requestId, String apiVersion, String vnfType,
286             RequestDetails requestDetails) throws IOException, VrfBondingServiceException {
287         List<ExecuteBuildingBlock> flowsToExecute;
288         List<Resource> resourceList = new ArrayList<>();
289         List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>();
290
291         if (resourceType == WorkflowType.SERVICE || isVNFCreateOrDelete(resourceType, requestAction)) {
292             resourceList = serviceEBBLoader.getResourceListForService(sIRequest, requestAction, execution,
293                     serviceInstanceId, resourceId, aaiResourceIds);
294         } else if (resourceType == WorkflowType.VNF && (REPLACEINSTANCE.equalsIgnoreCase(requestAction)
295                 || (RECREATE_INSTANCE.equalsIgnoreCase(requestAction)))) {
296             vnfEBBLoader.traverseAAIVnf(execution, resourceList, workflowResourceIds.getServiceInstanceId(),
297                     workflowResourceIds.getVnfId(), aaiResourceIds);
298         } else if (resourceType == WorkflowType.VNF && UPDATE_INSTANCE.equalsIgnoreCase(requestAction)) {
299             vnfEBBLoader.customTraverseAAIVnf(execution, resourceList, workflowResourceIds.getServiceInstanceId(),
300                     workflowResourceIds.getVnfId(), aaiResourceIds);
301         } else {
302             buildAndThrowException(execution, "Current Macro Request is not supported");
303         }
304         StringBuilder foundObjects = new StringBuilder();
305         for (WorkflowType type : WorkflowType.values()) {
306             foundObjects.append(type).append(" - ")
307                     .append((int) resourceList.stream().filter(x -> type.equals(x.getResourceType())).count())
308                     .append("    ");
309         }
310         logger.info("Found {}", foundObjects);
311
312         if (orchFlows == null || orchFlows.isEmpty()) {
313             orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, false, cloudOwner,
314                     serviceType);
315         }
316         boolean vnfReplace = false;
317         if (resourceType.equals(WorkflowType.VNF) && (REPLACEINSTANCE.equalsIgnoreCase(requestAction)
318                 || REPLACEINSTANCERETAINASSIGNMENTS.equalsIgnoreCase(requestAction))) {
319             vnfReplace = true;
320         }
321         flowsToExecute = executeBuildingBlockBuilder.buildExecuteBuildingBlockList(orchFlows, resourceList, requestId,
322                 apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, vnfReplace);
323         if (serviceEBBLoader.isNetworkCollectionInTheResourceList(resourceList)) {
324             logger.info("Sorting for Vlan Tagging");
325             flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction);
326         }
327         logger.info("Building Block Execution Order");
328         for (ExecuteBuildingBlock block : flowsToExecute) {
329             Resource res = resourceList.stream()
330                     .filter(resource -> resource.getResourceId() == block.getBuildingBlock().getKey()).findAny()
331                     .orElse(null);
332             String log = "Block: " + block.getBuildingBlock().getBpmnFlowName();
333             if (res != null) {
334                 log += ", Resource: " + res.getResourceType() + "[" + res.getResourceId() + "]";
335                 log += ", Priority: " + res.getProcessingPriority();
336                 if (res.getResourceType() == WorkflowType.VFMODULE)
337                     log += ", Base: " + res.isBaseVfModule();
338             }
339             if (block.getBuildingBlock().getBpmnScope() != null)
340                 log += ", Scope: " + block.getBuildingBlock().getBpmnScope();
341             if (block.getBuildingBlock().getBpmnAction() != null)
342                 log += ", Action: " + block.getBuildingBlock().getBpmnAction();
343             logger.info(log);
344         }
345         // By default, enable homing at VNF level for CREATE_INSTANCE and ASSIGNINSTANCE
346         if (resourceType == WorkflowType.SERVICE
347                 && (requestAction.equals(CREATE_INSTANCE) || requestAction.equals(ASSIGN_INSTANCE))
348                 && resourceList.stream().anyMatch(x -> WorkflowType.VNF.equals(x.getResourceType()))) {
349             execution.setVariable(HOMING, true);
350             execution.setVariable("calledHoming", false);
351         }
352         if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGN_INSTANCE)
353                 || requestAction.equalsIgnoreCase(CREATE_INSTANCE))) {
354             generateResourceIds(flowsToExecute, resourceList, serviceInstanceId);
355         } else {
356             updateResourceIdsFromAAITraversal(flowsToExecute, resourceList, aaiResourceIds, serviceInstanceId);
357         }
358         return flowsToExecute;
359     }
360
361     private boolean isVNFCreateOrDelete(WorkflowType resourceType, String requestAction) {
362         return resourceType == WorkflowType.VNF
363                 && (CREATE_INSTANCE.equalsIgnoreCase(requestAction) || DELETE_INSTANCE.equalsIgnoreCase(requestAction));
364     }
365
366     private void setExecutionVariables(DelegateExecution execution, List<ExecuteBuildingBlock> flowsToExecute,
367             List<String> flowNames) {
368         execution.setVariable("flowNames", flowNames);
369         execution.setVariable(BBConstants.G_CURRENT_SEQUENCE, 0);
370         execution.setVariable("retryCount", 0);
371         execution.setVariable("isRollback", false);
372         execution.setVariable("flowsToExecute", flowsToExecute);
373         execution.setVariable("isRollbackComplete", false);
374     }
375
376     private List<ExecuteBuildingBlock> loadExecuteBuildingBlocks(DelegateExecution execution, String requestId,
377             String errorMessage) {
378         List<ExecuteBuildingBlock> flowsToExecute;
379         flowsToExecute = bbInputSetupUtils.loadOriginalFlowExecutionPath(requestId);
380         if (flowsToExecute == null) {
381             buildAndThrowException(execution, errorMessage);
382         }
383         return flowsToExecute;
384     }
385
386     private ConfigBuildingBlocksDataObject createConfigBuildingBlocksDataObject(DelegateExecution execution,
387             ServiceInstancesRequest sIRequest, String requestId, WorkflowResourceIds workflowResourceIds,
388             RequestDetails requestDetails, String requestAction, String resourceId, String vnfType,
389             List<OrchestrationFlow> orchFlows, String apiVersion, Resource resourceKey,
390             ReplaceInstanceRelatedInformation replaceInfo) {
391
392         return new ConfigBuildingBlocksDataObject().setsIRequest(sIRequest).setOrchFlows(orchFlows)
393                 .setRequestId(requestId).setResourceKey(resourceKey).setApiVersion(apiVersion).setResourceId(resourceId)
394                 .setRequestAction(requestAction).setaLaCarte(true).setVnfType(vnfType)
395                 .setWorkflowResourceIds(workflowResourceIds).setRequestDetails(requestDetails).setExecution(execution)
396                 .setReplaceInformation(replaceInfo);
397     }
398
399     private void createBuildingBlocksForOrchFlows(DelegateExecution execution, ServiceInstancesRequest sIRequest,
400             String requestId, WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails,
401             String requestAction, String resourceId, List<ExecuteBuildingBlock> flowsToExecute, String vnfType,
402             List<OrchestrationFlow> orchFlows, String apiVersion, Resource resourceKey,
403             ReplaceInstanceRelatedInformation replaceInfo) throws Exception {
404
405         for (OrchestrationFlow orchFlow : orchFlows) {
406             if (orchFlow.getFlowName().contains(CONFIGURATION)) {
407                 List<OrchestrationFlow> configOrchFlows = new ArrayList<>();
408                 configOrchFlows.add(orchFlow);
409                 addConfigBuildingBlocksToFlowsToExecuteList(execution, sIRequest, requestId, workflowResourceIds,
410                         requestDetails, requestAction, resourceId, flowsToExecute, vnfType, apiVersion, resourceKey,
411                         replaceInfo, configOrchFlows);
412             } else {
413                 ExecuteBuildingBlock ebb = executeBuildingBlockBuilder.buildExecuteBuildingBlock(orchFlow, requestId,
414                         resourceKey, apiVersion, resourceId, requestAction, true, vnfType, workflowResourceIds,
415                         requestDetails, false, null, null, false, replaceInfo);
416                 flowsToExecute.add(ebb);
417             }
418         }
419     }
420
421     private void addConfigBuildingBlocksToFlowsToExecuteList(DelegateExecution execution,
422             ServiceInstancesRequest sIRequest, String requestId, WorkflowResourceIds workflowResourceIds,
423             RequestDetails requestDetails, String requestAction, String resourceId,
424             List<ExecuteBuildingBlock> flowsToExecute, String vnfType, String apiVersion, Resource resourceKey,
425             ReplaceInstanceRelatedInformation replaceInfo, List<OrchestrationFlow> configOrchFlows) throws Exception {
426
427         ConfigBuildingBlocksDataObject cbbdo = createConfigBuildingBlocksDataObject(execution, sIRequest, requestId,
428                 workflowResourceIds, requestDetails, requestAction, resourceId, vnfType, configOrchFlows, apiVersion,
429                 resourceKey, replaceInfo);
430         List<ExecuteBuildingBlock> configBuildingBlocks = getConfigBuildingBlocks(cbbdo);
431         flowsToExecute.addAll(configBuildingBlocks);
432     }
433
434     private Resource getResourceKey(ServiceInstancesRequest sIRequest, WorkflowType resourceType) {
435         String resourceId = "";
436         ModelInfo modelInfo = sIRequest.getRequestDetails().getModelInfo();
437         if (modelInfo != null) {
438             if (modelInfo.getModelType().equals(ModelType.service)) {
439                 resourceId = modelInfo.getModelVersionId();
440             } else {
441                 resourceId = modelInfo.getModelCustomizationId();
442             }
443         }
444         return new Resource(resourceType, resourceId, true, null);
445     }
446
447     private String getCloudOwner(CloudConfiguration cloudConfiguration) {
448         if (cloudConfiguration != null && cloudConfiguration.getCloudOwner() != null) {
449             return cloudConfiguration.getCloudOwner();
450         }
451         logger.warn("cloud owner value not found in request details, it will be set as default");
452         return environment.getProperty(DEFAULT_CLOUD_OWNER);
453     }
454
455     protected <T> List<T> getRelatedResourcesInVfModule(String vnfId, String vfModuleId, Class<T> resultClass,
456             AAIObjectName name) {
457         List<T> vnfcs = new ArrayList<>();
458         AAIResourceUri uri =
459                 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId).vfModule(vfModuleId));
460         AAIResultWrapper vfModuleResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
461         Optional<Relationships> relationshipsOp = vfModuleResultsWrapper.getRelationships();
462         if (relationshipsOp.isEmpty()) {
463             logger.debug("No relationships were found for vfModule in AAI");
464         } else {
465             Relationships relationships = relationshipsOp.get();
466             List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(name);
467             for (AAIResultWrapper vnfcResultWrapper : vnfcResultWrappers) {
468                 Optional<T> vnfcOp = vnfcResultWrapper.asBean(resultClass);
469                 vnfcOp.ifPresent(vnfcs::add);
470             }
471         }
472         return vnfcs;
473     }
474
475     protected <T> T getRelatedResourcesInVnfc(Vnfc vnfc, Class<T> resultClass, AAIObjectName name)
476             throws VnfcMultipleRelationshipException {
477         T configuration = null;
478         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().vnfc(vnfc.getVnfcName()));
479         AAIResultWrapper vnfcResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
480         Optional<Relationships> relationshipsOp = vnfcResultsWrapper.getRelationships();
481         if (relationshipsOp.isEmpty()) {
482             logger.debug("No relationships were found for VNFC in AAI");
483         } else {
484             Relationships relationships = relationshipsOp.get();
485             List<AAIResultWrapper> configurationResultWrappers =
486                     this.getResultWrappersFromRelationships(relationships, name);
487             if (configurationResultWrappers.size() > 1) {
488                 throw new VnfcMultipleRelationshipException(vnfc.getVnfcName());
489             }
490             if (!configurationResultWrappers.isEmpty()) {
491                 Optional<T> configurationOp = configurationResultWrappers.get(0).asBean(resultClass);
492                 if (configurationOp.isPresent()) {
493                     configuration = configurationOp.get();
494                 }
495             }
496         }
497         return configuration;
498     }
499
500     protected List<AAIResultWrapper> getResultWrappersFromRelationships(Relationships relationships,
501             AAIObjectName name) {
502         return relationships.getByType(name);
503     }
504
505     protected boolean isConfiguration(List<OrchestrationFlow> orchFlows) {
506         for (OrchestrationFlow flow : orchFlows) {
507             if (flow.getFlowName().contains(CONFIGURATION) && !"ConfigurationScaleOutBB".equals(flow.getFlowName())) {
508                 return true;
509             }
510         }
511         return false;
512     }
513
514     protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ConfigBuildingBlocksDataObject dataObj)
515             throws AAIEntityNotFoundException, VnfcMultipleRelationshipException {
516
517         List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>();
518         List<OrchestrationFlow> result = dataObj.getOrchFlows().stream()
519                 .filter(item -> item.getFlowName().contains(FABRIC_CONFIGURATION)).collect(Collectors.toList());
520         String vnfId = dataObj.getWorkflowResourceIds().getVnfId();
521         String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId();
522
523         String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
524         String vfModuleCustomizationUUID;
525         org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
526
527         if (aaiVfModule == null) {
528             logger.error("No matching VfModule is found in Generic-Vnf in AAI for vnfId: {} and vfModuleId : {}", vnfId,
529                     vfModuleId);
530             throw new AAIEntityNotFoundException("No matching VfModule is found in Generic-Vnf in AAI for vnfId: "
531                     + vnfId + " and vfModuleId : " + vfModuleId);
532         } else {
533             vfModuleCustomizationUUID = aaiVfModule.getModelCustomizationId();
534         }
535         String replaceVfModuleCustomizationUUID = "";
536         String replaceVnfModuleCustomizationUUID = "";
537         boolean isReplace = false;
538         if (dataObj.getRequestAction().equalsIgnoreCase("replaceInstance")
539                 || dataObj.getRequestAction().equalsIgnoreCase("replaceInstanceRetainAssignments")) {
540             for (RelatedInstanceList relatedInstList : dataObj.getRequestDetails().getRelatedInstanceList()) {
541                 RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
542                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
543                     replaceVnfModuleCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
544                 }
545             }
546             replaceVfModuleCustomizationUUID = dataObj.getRequestDetails().getModelInfo().getModelCustomizationId();
547             isReplace = true;
548         }
549
550         List<org.onap.aai.domain.yang.Vnfc> vnfcs =
551                 getRelatedResourcesInVfModule(vnfId, vfModuleId, org.onap.aai.domain.yang.Vnfc.class, Types.VNFC);
552         for (org.onap.aai.domain.yang.Vnfc vnfc : vnfcs) {
553             WorkflowResourceIds workflowIdsCopy = SerializationUtils.clone(dataObj.getWorkflowResourceIds());
554             org.onap.aai.domain.yang.Configuration configuration =
555                     getRelatedResourcesInVnfc(vnfc, org.onap.aai.domain.yang.Configuration.class, Types.CONFIGURATION);
556             if (configuration == null) {
557                 logger.warn(String.format("No configuration found for VNFC %s in AAI", vnfc.getVnfcName()));
558                 continue;
559             }
560             workflowIdsCopy.setConfigurationId(configuration.getConfigurationId());
561             for (OrchestrationFlow orchFlow : result) {
562                 if (!isReplace || (isReplace && (orchFlow.getFlowName().contains("Delete")))) {
563                     if (!isReplace) {
564                         dataObj.getResourceKey().setVfModuleCustomizationId(vfModuleCustomizationUUID);
565                         dataObj.getResourceKey().setVnfCustomizationId(vnfCustomizationUUID);
566                     } else {
567                         if (orchFlow.getFlowName().contains("Delete")) {
568                             dataObj.getResourceKey().setVfModuleCustomizationId(vfModuleCustomizationUUID);
569                             dataObj.getResourceKey().setVnfCustomizationId(vnfCustomizationUUID);
570                         } else {
571                             dataObj.getResourceKey().setVfModuleCustomizationId(replaceVfModuleCustomizationUUID);
572                             dataObj.getResourceKey().setVnfCustomizationId(replaceVnfModuleCustomizationUUID);
573                         }
574                     }
575                     dataObj.getResourceKey().setCvnfModuleCustomizationId(vnfc.getModelCustomizationId());
576                     String vnfcName = vnfc.getVnfcName();
577                     if (vnfcName == null || vnfcName.isEmpty()) {
578                         buildAndThrowException(dataObj.getExecution(), "Exception in create execution list "
579                                 + ": VnfcName does not exist or is null while there is a configuration for the vfModule",
580                                 new Exception("Vnfc and Configuration do not match"));
581                     }
582                     ExecuteBuildingBlock ebb =
583                             executeBuildingBlockBuilder.buildExecuteBuildingBlock(orchFlow, dataObj.getRequestId(),
584                                     dataObj.getResourceKey(), dataObj.getApiVersion(), dataObj.getResourceId(),
585                                     dataObj.getRequestAction(), dataObj.isaLaCarte(), dataObj.getVnfType(),
586                                     workflowIdsCopy, dataObj.getRequestDetails(), false, null, vnfcName, true, null);
587                     flowsToExecuteConfigs.add(ebb);
588                 }
589             }
590         }
591         return flowsToExecuteConfigs;
592     }
593
594     protected void buildAndThrowException(DelegateExecution execution, String msg) {
595         logger.error(msg);
596         execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
597         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
598     }
599
600     protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
601         logger.error(msg, ex);
602         execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg + ex.getMessage());
603         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg + ex.getMessage());
604     }
605
606     protected List<OrchestrationFlow> getVfModuleReplaceBuildingBlocks(ConfigBuildingBlocksDataObject dataObj)
607             throws Exception {
608
609         String vnfId = dataObj.getWorkflowResourceIds().getVnfId();
610         String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId();
611
612         logger.debug("BUILDING REPLACE LIST");
613
614         boolean volumeGroupExisted = false;
615         boolean volumeGroupWillExist = false;
616         boolean keepVolumeGroup = false;
617
618         boolean rebuildVolumeGroups = false;
619         if (dataObj.getRequestDetails().getRequestParameters() != null
620                 && dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups() != null) {
621             rebuildVolumeGroups = dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups();
622         }
623         String volumeGroupName = "";
624         Optional<VolumeGroup> volumeGroupFromVfModule =
625                 bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, vfModuleId);
626         if (volumeGroupFromVfModule.isPresent()) {
627             String volumeGroupId = volumeGroupFromVfModule.get().getVolumeGroupId();
628             volumeGroupName = volumeGroupFromVfModule.get().getVolumeGroupName();
629             logger.debug("Volume group id of the existing volume group is: {}", volumeGroupId);
630             volumeGroupExisted = true;
631             dataObj.getWorkflowResourceIds().setVolumeGroupId(volumeGroupId);
632             dataObj.getReplaceInformation().setOldVolumeGroupName(volumeGroupName);
633         }
634
635         List<OrchestrationFlow> orchFlows = dataObj.getOrchFlows();
636         VfModuleCustomization vfModuleCustomization = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(
637                 dataObj.getRequestDetails().getModelInfo().getModelCustomizationUuid());
638         if (vfModuleCustomization != null && vfModuleCustomization.getVfModule() != null
639                 && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null
640                 && vfModuleCustomization.getVolumeHeatEnv() != null) {
641             volumeGroupWillExist = true;
642             if (!volumeGroupExisted) {
643                 String newVolumeGroupId = UUID.randomUUID().toString();
644                 dataObj.getWorkflowResourceIds().setVolumeGroupId(newVolumeGroupId);
645                 dataObj.getReplaceInformation().setOldVolumeGroupName(volumeGroupName);
646                 logger.debug("newVolumeGroupId: {}", newVolumeGroupId);
647             }
648         }
649
650         if (volumeGroupExisted && volumeGroupWillExist && !rebuildVolumeGroups) {
651             keepVolumeGroup = true;
652         }
653
654         if (!volumeGroupExisted || keepVolumeGroup) {
655             logger.debug("Filtering out deletion of volume groups");
656             orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_DELETE_PATTERN))
657                     .collect(Collectors.toList());
658         }
659         if (!volumeGroupWillExist || keepVolumeGroup) {
660             logger.debug("Filtering out creation of volume groups");
661             orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_CREATE_PATTERN))
662                     .collect(Collectors.toList());
663         }
664
665         return orchFlows;
666     }
667
668     private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute,
669             List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) {
670         for (Pair<WorkflowType, String> pair : aaiResourceIds) {
671             logger.debug("{}, {}", pair.getValue0(), pair.getValue1());
672         }
673         Map<Resource, String> resourceInstanceIds = new HashMap<>();
674         Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE))
675                 .forEach(type -> resourceList.stream().filter(resource -> type.equals(resource.getResourceType()))
676                         .forEach(resource -> updateWorkflowResourceIds(flowsToExecute, type, resource,
677                                 retrieveAAIResourceId(aaiResourceIds, type), null, serviceInstanceId,
678                                 resourceInstanceIds)));
679     }
680
681     private String retrieveAAIResourceId(List<Pair<WorkflowType, String>> aaiResourceIds, WorkflowType resource) {
682         String id = null;
683         for (int i = 0; i < aaiResourceIds.size(); i++) {
684             if (aaiResourceIds.get(i).getValue0() == resource) {
685                 id = aaiResourceIds.get(i).getValue1();
686                 aaiResourceIds.remove(i);
687                 break;
688             }
689         }
690         return id;
691     }
692
693     private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceList,
694             String serviceInstanceId) {
695         Map<Resource, String> resourceInstanceIds = new HashMap<>();
696         Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE))
697                 .forEach(type -> resourceList.stream().filter(resource -> type.equals(resource.getResourceType()))
698                         .forEach(resource -> updateWorkflowResourceIds(flowsToExecute, type, resource, null,
699                                 resource.getVirtualLinkKey(), serviceInstanceId, resourceInstanceIds)));
700     }
701
702     protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resourceType,
703             Resource resource, String id, String virtualLinkKey, String serviceInstanceId,
704             Map<Resource, String> resourceInstanceIds) {
705         String key = resource.getResourceId();
706         String resourceId = id;
707         if (resourceId == null) {
708             resourceId = UUID.randomUUID().toString();
709         }
710         resourceInstanceIds.put(resource, resourceId);
711         Set<String> assignedFlows = new LinkedHashSet<>();
712         for (ExecuteBuildingBlock ebb : flowsToExecute) {
713             String resourceTypeStr = resourceType.toString();
714             String flowName = ebb.getBuildingBlock().getBpmnFlowName();
715             String scope = StringUtils.defaultString(ebb.getBuildingBlock().getBpmnScope());
716             String action = StringUtils.defaultString(ebb.getBuildingBlock().getBpmnAction());
717
718             if (key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey())
719                     && isFlowAssignable(assignedFlows, ebb, resourceType, flowName + action)
720                     && (flowName.contains(resourceTypeStr)
721                             || (flowName.contains(CONTROLLER) && resourceTypeStr.equalsIgnoreCase(scope)))) {
722                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
723                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
724                 Resource parent = resource.getParent();
725                 if (parent != null && resourceInstanceIds.containsKey(parent)) {
726                     WorkflowResourceIdsUtils.setResourceIdByWorkflowType(workflowResourceIds, parent.getResourceType(),
727                             resourceInstanceIds.get(parent));
728                 }
729                 WorkflowResourceIdsUtils.setInstanceNameByWorkflowType(workflowResourceIds, resourceType,
730                         resource.getInstanceName());
731                 WorkflowResourceIdsUtils.setResourceIdByWorkflowType(workflowResourceIds, resourceType, resourceId);
732                 ebb.setWorkflowResourceIds(workflowResourceIds);
733                 assignedFlows.add(flowName + action);
734             }
735             if (virtualLinkKey != null && ebb.getBuildingBlock().isVirtualLink()
736                     && virtualLinkKey.equalsIgnoreCase(ebb.getBuildingBlock().getVirtualLinkKey())) {
737                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
738                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
739                 workflowResourceIds.setNetworkId(resourceId);
740                 ebb.setWorkflowResourceIds(workflowResourceIds);
741             }
742         }
743     }
744
745     private boolean isFlowAssignable(Set<String> assignedFlows, ExecuteBuildingBlock ebb, WorkflowType resourceType,
746             String assignedFlowName) {
747         String id = WorkflowResourceIdsUtils.getResourceIdByWorkflowType(ebb.getWorkflowResourceIds(), resourceType);
748         return !assignedFlows.contains(assignedFlowName) && id.isEmpty();
749     }
750
751     protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) {
752         return WorkflowResourceIdsUtils.getWorkflowResourceIdsFromExecution(execution);
753     }
754
755     protected Resource extractResourceIdAndTypeFromUri(String uri) {
756         Pattern patt = Pattern.compile("[vV]\\d+.*?(?:(?:/(?<type>" + SUPPORTEDTYPES
757                 + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?(?:/resume)?)?$");
758         Matcher m = patt.matcher(uri);
759         boolean generated = false;
760
761         if (m.find()) {
762             logger.debug("found match on {} : {} ", uri, m);
763             String type = m.group("type");
764             String id = m.group("id");
765             String action = m.group("action");
766             if (type == null) {
767                 throw new IllegalArgumentException("Uri could not be parsed. No type found. " + uri);
768             }
769             if (action == null) {
770                 if (type.equals(SERVICE_INSTANCES) && (id == null || "assign".equals(id))) {
771                     id = UUID.randomUUID().toString();
772                     generated = true;
773                 } else if (type.equals(VF_MODULES) && "scaleOut".equals(id)) {
774                     id = UUID.randomUUID().toString();
775                     generated = true;
776                 }
777             } else {
778                 if (action.matches(SUPPORTEDTYPES)) {
779                     id = UUID.randomUUID().toString();
780                     generated = true;
781                     type = action;
782                 }
783             }
784             return new Resource(WorkflowType.fromString(convertTypeFromPlural(type)), id, generated, null);
785         } else {
786             throw new IllegalArgumentException("Uri could not be parsed: " + uri);
787         }
788     }
789
790     protected String convertTypeFromPlural(String type) {
791         if (!type.matches(SUPPORTEDTYPES)) {
792             return type;
793         } else {
794             if (type.equals(SERVICE_INSTANCES)) {
795                 return SERVICE;
796             } else {
797                 return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
798             }
799         }
800     }
801
802     protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
803             String requestAction) {
804         List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
805         if (requestAction.equals(CREATE_INSTANCE)) {
806             for (ExecuteBuildingBlock ebb : orchFlows) {
807                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
808                     String key = ebb.getBuildingBlock().getKey();
809                     boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().isVirtualLink());
810                     String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
811                     sortedOrchFlows.add(ebb);
812                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
813                         if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB)
814                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
815                             sortedOrchFlows.add(ebb2);
816                             break;
817                         }
818                         if (isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB)
819                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
820                             sortedOrchFlows.add(ebb2);
821                             break;
822                         }
823                     }
824                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
825                         if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)
826                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
827                             sortedOrchFlows.add(ebb2);
828                             break;
829                         }
830                         if (isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)
831                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
832                             sortedOrchFlows.add(ebb2);
833                             break;
834                         }
835                     }
836                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB)
837                         || ebb.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)) {
838                     continue;
839                 } else if (!"".equals(ebb.getBuildingBlock().getBpmnFlowName())) {
840                     sortedOrchFlows.add(ebb);
841                 }
842             }
843         } else if (requestAction.equals("deleteInstance")) {
844             for (ExecuteBuildingBlock ebb : orchFlows) {
845                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
846                     sortedOrchFlows.add(ebb);
847                     String key = ebb.getBuildingBlock().getKey();
848                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
849                         if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
850                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
851                             sortedOrchFlows.add(ebb2);
852                             break;
853                         }
854                     }
855                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
856                         if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
857                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
858                             sortedOrchFlows.add(ebb2);
859                             break;
860                         }
861                     }
862                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
863                         || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
864                     continue;
865                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
866                     sortedOrchFlows.add(ebb);
867                 }
868             }
869         }
870         return sortedOrchFlows;
871     }
872
873     protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
874             WorkflowType resourceName, boolean aLaCarte, String cloudOwner) {
875         return this.queryNorthBoundRequestCatalogDb(execution, requestAction, resourceName, aLaCarte, cloudOwner, "");
876     }
877
878     protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
879             WorkflowType resourceName, boolean aLaCarte, String cloudOwner, String serviceType) {
880         List<OrchestrationFlow> listToExecute = new ArrayList<>();
881         NorthBoundRequest northBoundRequest;
882         if (serviceType.equalsIgnoreCase(SERVICE_TYPE_TRANSPORT)
883                 || serviceType.equalsIgnoreCase(SERVICE_TYPE_BONDING)) {
884             northBoundRequest =
885                     catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(
886                             requestAction, resourceName.toString(), aLaCarte, cloudOwner, serviceType);
887         } else {
888             northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(
889                     requestAction, resourceName.toString(), aLaCarte, cloudOwner);
890         }
891         if (northBoundRequest == null) {
892             northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(
893                     requestAction, resourceName.toString(), aLaCarte, CLOUD_OWNER);
894         }
895         if (northBoundRequest == null) {
896             buildAndThrowException(execution, String.format("The request: %s %s %s is not supported by GR_API.",
897                     (aLaCarte ? "AlaCarte" : "Macro"), resourceName, requestAction));
898         } else {
899             if (northBoundRequest.getIsToplevelflow() != null) {
900                 execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
901             }
902             List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
903             if (flows == null) {
904                 flows = new ArrayList<>();
905             } else {
906                 flows.sort(Comparator.comparingInt(OrchestrationFlow::getSequenceNumber));
907             }
908             for (OrchestrationFlow flow : flows) {
909                 if (!flow.getFlowName().contains("BB") && !flow.getFlowName().contains("Activity")) {
910                     List<OrchestrationFlow> macroQueryFlows =
911                             catalogDbClient.getOrchestrationFlowByAction(flow.getFlowName());
912                     listToExecute.addAll(macroQueryFlows);
913                 } else {
914                     listToExecute.add(flow);
915                 }
916             }
917         }
918         return listToExecute;
919     }
920
921     public void handleRuntimeException(DelegateExecution execution) {
922         StringBuilder wfeExpMsg = new StringBuilder("Runtime error ");
923         String runtimeErrorMessage;
924         try {
925             String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
926             if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
927                 wfeExpMsg.append(": ").append(javaExpMsg);
928             }
929             runtimeErrorMessage = wfeExpMsg.toString();
930             logger.error(runtimeErrorMessage);
931             execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, runtimeErrorMessage);
932         } catch (Exception e) {
933             logger.error("Runtime error", e);
934             // if runtime message was mulformed
935             runtimeErrorMessage = "Runtime error";
936         }
937         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
938     }
939
940     protected boolean isUriResume(String uri) {
941         return uri.endsWith("/resume");
942     }
943
944     protected boolean isRequestMacroServiceResume(boolean aLaCarte, WorkflowType resourceType, String requestAction,
945             String serviceInstanceId) {
946         return (!aLaCarte && resourceType == WorkflowType.SERVICE
947                 && (requestAction.equalsIgnoreCase(ASSIGN_INSTANCE) || requestAction.equalsIgnoreCase(CREATE_INSTANCE))
948                 && (serviceInstanceId != null && serviceInstanceId.trim().length() > 1)
949                 && (bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId) != null));
950     }
951
952     private void fillExecutionDefault(DelegateExecution execution) {
953         execution.setVariable("sentSyncResponse", false);
954         execution.setVariable(HOMING, false);
955         execution.setVariable("calledHoming", false);
956         execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, true);
957     }
958
959     private void fillExecution(DelegateExecution execution, boolean suppressRollback, String resourceId,
960             WorkflowType resourceType) {
961         execution.setVariable("suppressRollback", suppressRollback);
962         execution.setVariable("resourceId", resourceId);
963         execution.setVariable("resourceType", resourceType);
964         execution.setVariable("resourceName", resourceType.toString());
965     }
966
967     private Resource getResource(BBInputSetupUtils bbInputSetupUtils, boolean isResume, boolean alaCarte, String uri,
968             String requestId) {
969         if (!alaCarte && isResume) {
970             logger.debug("replacing URI {}", uri);
971             uri = bbInputSetupUtils.loadOriginalInfraActiveRequestById(requestId).getRequestUrl();
972             logger.debug("for RESUME with original value {}", uri);
973         }
974         return extractResourceIdAndTypeFromUri(uri);
975     }
976
977     private String getResourceId(Resource resource, String requestAction, RequestDetails requestDetails,
978             WorkflowResourceIds workflowResourceIds) throws Exception {
979         if (resource.isGenerated() && requestAction.equalsIgnoreCase("createInstance")
980                 && requestDetails.getRequestInfo().getInstanceName() != null) {
981             return aaiResourceIdValidator.validateResourceIdInAAI(resource.getResourceId(), resource.getResourceType(),
982                     requestDetails.getRequestInfo().getInstanceName(), requestDetails, workflowResourceIds);
983         } else {
984             return resource.getResourceId();
985         }
986     }
987
988     private String getServiceInstanceId(DelegateExecution execution, String resourceId, WorkflowType resourceType) {
989         String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
990         if ((serviceInstanceId == null || serviceInstanceId.isEmpty()) && WorkflowType.SERVICE.equals(resourceType)) {
991             serviceInstanceId = resourceId;
992         }
993         return serviceInstanceId;
994     }
995
996 }