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