Bugfixes for December 2018
[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  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.UUID;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import java.util.stream.Collectors;
34
35 import org.camunda.bpm.engine.delegate.DelegateExecution;
36 import org.javatuples.Pair;
37 import org.slf4j.LoggerFactory;
38 import org.onap.aai.domain.yang.GenericVnf;
39 import org.onap.aai.domain.yang.L3Network;
40 import org.onap.aai.domain.yang.Relationship;
41 import org.onap.aai.domain.yang.ServiceInstance;
42 import org.onap.aai.domain.yang.VolumeGroup;
43 import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration;
44 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
45 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
46 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
47 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
48 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
49 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup;
50 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
51 import org.onap.so.bpmn.infrastructure.workflow.tasks.Resource;
52 import org.onap.so.client.aai.AAICommonObjectMapperProvider;
53 import org.onap.so.client.aai.entities.AAIResultWrapper;
54 import org.onap.so.client.aai.entities.Relationships;
55 import org.onap.so.client.exception.ExceptionBuilder;
56 import org.onap.so.client.orchestration.AAIConfigurationResources;
57 import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
58 import org.onap.so.db.catalog.beans.CollectionResourceCustomization;
59 import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
60 import org.onap.so.db.catalog.beans.CvnfcCustomization;
61 import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
62 import org.onap.so.db.catalog.beans.VfModuleCustomization;
63 import org.onap.so.db.catalog.beans.VnfVfmoduleCvnfcConfigurationCustomization;
64 import org.onap.so.db.catalog.beans.macro.NorthBoundRequest;
65 import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
66 import org.onap.so.db.catalog.client.CatalogDbClient;
67 import org.onap.so.logger.MsoLogger;
68 import org.onap.so.serviceinstancebeans.ModelInfo;
69 import org.onap.so.serviceinstancebeans.ModelType;
70 import org.onap.so.serviceinstancebeans.Networks;
71 import org.onap.so.serviceinstancebeans.RequestDetails;
72 import org.onap.so.serviceinstancebeans.Service;
73 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
74 import org.onap.so.serviceinstancebeans.VfModules;
75 import org.onap.so.serviceinstancebeans.Vnfs;
76 import org.slf4j.Logger;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.core.env.Environment;
79 import org.springframework.stereotype.Component;
80
81 import com.fasterxml.jackson.databind.ObjectMapper;
82
83 @Component
84 public class WorkflowAction {
85
86         private static final String WORKFLOW_ACTION_ERROR_MESSAGE = "WorkflowActionErrorMessage";
87         private static final String SERVICE_INSTANCES = "serviceInstances";
88         private static final String VF_MODULES = "vfModules";
89         private static final String WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI = "WorkflowAction was unable to verify if the instance name already exist in AAI.";
90         private static final String G_ORCHESTRATION_FLOW = "gOrchestrationFlow";
91         private static final String G_ACTION = "requestAction";
92         private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
93         private static final String G_REQUEST_ID = "mso-request-id";
94         private static final String G_BPMN_REQUEST = "bpmnRequest";
95         private static final String G_ALACARTE = "aLaCarte";
96         private static final String G_APIVERSION = "apiVersion";
97         private static final String G_URI = "requestUri";
98         private static final String G_ISTOPLEVELFLOW = "isTopLevelFlow";
99         private static final String VNF_TYPE = "vnfType";
100         private static final String SERVICE = "Service";
101         private static final String VNF = "Vnf";
102         private static final String VFMODULE = "VfModule";
103         private static final String VOLUMEGROUP = "VolumeGroup";
104         private static final String NETWORK = "Network";
105         private static final String NETWORKCOLLECTION = "NetworkCollection";
106         private static final String CONFIGURATION = "Configuration";
107         private static final String ASSIGNINSTANCE = "assignInstance";
108         private static final String CREATEINSTANCE = "createInstance";
109         private static final String USERPARAMSERVICE = "service";
110         private static final String supportedTypes = "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances";
111         private static final String HOMINGSOLUTION = "Homing_Solution";
112         private static final String FABRIC_CONFIGURATION = "FabricConfiguration";       
113         private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class);
114         
115         @Autowired
116         protected BBInputSetup bbInputSetup;
117         @Autowired
118         protected BBInputSetupUtils bbInputSetupUtils;
119         @Autowired
120         private ExceptionBuilder exceptionBuilder;
121         @Autowired
122         private CatalogDbClient catalogDbClient;
123         @Autowired
124         private AAIConfigurationResources aaiConfigurationResources;
125         @Autowired
126         private WorkflowActionExtractResourcesAAI workflowActionUtils;
127
128         @Autowired
129         private Environment environment;
130         private String defaultCloudOwner = "org.onap.so.cloud-owner";
131
132         public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
133                 this.bbInputSetupUtils = bbInputSetupUtils;
134         }
135
136         public void setBbInputSetup(BBInputSetup bbInputSetup) {
137                 this.bbInputSetup = bbInputSetup;
138         }
139
140         public void selectExecutionList(DelegateExecution execution) throws Exception {
141                 final String requestAction = (String) execution.getVariable(G_ACTION);
142                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
143                 final String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST);
144                 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
145                 final String apiVersion = (String) execution.getVariable(G_APIVERSION);
146                 final String uri = (String) execution.getVariable(G_URI);
147                 final String vnfType = (String) execution.getVariable(VNF_TYPE);
148                 String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
149                 List<OrchestrationFlow> orchFlows = (List<OrchestrationFlow>) execution.getVariable(G_ORCHESTRATION_FLOW);
150                 List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
151                 WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution);
152                 List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>();
153                 List<Resource> resourceCounter = new ArrayList<>();
154                 execution.setVariable("sentSyncResponse", false);
155                 execution.setVariable("homing", false);
156                 execution.setVariable("calledHoming", false);
157
158                 try {
159                         ObjectMapper mapper = new ObjectMapper();
160                         execution.setVariable(G_ISTOPLEVELFLOW, true);
161                         ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
162                         RequestDetails requestDetails = sIRequest.getRequestDetails();
163                         String cloudOwner = "";
164                         try{
165                                 cloudOwner = requestDetails.getCloudConfiguration().getCloudOwner();
166                         } catch (Exception ex) {
167                                 cloudOwner = environment.getProperty(defaultCloudOwner);
168                         }
169                         boolean suppressRollback = false;
170                         try{
171                                 suppressRollback = requestDetails.getRequestInfo().getSuppressRollback();
172                         } catch (Exception ex) {
173                                 suppressRollback = false;
174                         }
175                         execution.setVariable("suppressRollback", suppressRollback);
176                         Resource resource = extractResourceIdAndTypeFromUri(uri);
177                         WorkflowType resourceType = resource.getResourceType();
178                         execution.setVariable("resourceName", resourceType.toString());
179                         String resourceId = "";
180                         if (resource.isGenerated()) {
181                                 resourceId = validateResourceIdInAAI(resource.getResourceId(), resourceType,
182                                                 sIRequest.getRequestDetails().getRequestInfo().getInstanceName(), sIRequest.getRequestDetails(),
183                                                 workflowResourceIds);
184                         } else {
185                                 resourceId = resource.getResourceId();
186                         }
187                         if((serviceInstanceId == null || serviceInstanceId.equals("")) && resourceType == WorkflowType.SERVICE){
188                                 serviceInstanceId = resourceId;
189                         }
190                         execution.setVariable("resourceId", resourceId);
191                         execution.setVariable("resourceType", resourceType);
192
193                         if (aLaCarte) {
194                                 if (orchFlows == null || orchFlows.isEmpty()) {
195                                         orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner);
196                                 }
197                                 orchFlows = filterOrchFlows(orchFlows, resourceType, execution);
198                                 String key = "";
199                                 ModelInfo modelInfo = sIRequest.getRequestDetails().getModelInfo();
200                                 if(modelInfo.getModelType().equals(ModelType.service)) {
201                                         key = modelInfo.getModelVersionId();
202                                 } else {
203                                         key = modelInfo.getModelCustomizationId();
204                                 }
205                                 Resource resourceKey = new Resource(resourceType, key, aLaCarte);
206                                 for (OrchestrationFlow orchFlow : orchFlows) {
207                                         ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion, resourceId,
208                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false);
209                                         flowsToExecute.add(ebb);
210                                 }
211                         } else {
212                                 boolean foundRelated = false;
213                                 boolean containsService = false;
214                                 if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) {
215                                         // SERVICE-MACRO-ASSIGN will always get user params with a
216                                         // service.
217                                         if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
218                                                 List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters()
219                                                                 .getUserParams();
220                                                 for (Map<String, Object> params : userParams) {
221                                                         if (params.containsKey(USERPARAMSERVICE)) {
222                                                                 containsService = true;
223                                                         }
224                                                 }
225                                                 if (containsService) {
226                                                         traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
227                                                 }
228                                         } else {
229                                                 buildAndThrowException(execution,
230                                                                 "Service-Macro-Assign request details must contain user params with a service");
231                                         }
232                                 } else if (resourceType == WorkflowType.SERVICE
233                                                 && requestAction.equalsIgnoreCase(CREATEINSTANCE)) {
234                                         // SERVICE-MACRO-CREATE will get user params with a service,
235                                         // a service with a network, a service with a
236                                         // networkcollection, OR an empty service.
237                                         // If user params is just a service or null and macro
238                                         // queries the SI and finds a VNF, macro fails.
239
240                                         if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
241                                                 List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters()
242                                                                 .getUserParams();
243                                                 for (Map<String, Object> params : userParams) {
244                                                         if (params.containsKey(USERPARAMSERVICE)) {
245                                                                 containsService = true;
246                                                         }
247                                                 }
248                                         }
249                                         if (containsService) {
250                                                 foundRelated = traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
251                                         }
252                                         if (!foundRelated) {
253                                                 traverseCatalogDbService(execution, sIRequest, resourceCounter);
254                                         }
255                                 } else if (resourceType == WorkflowType.SERVICE
256                                                 && (requestAction.equalsIgnoreCase("activateInstance")
257                                                                 || requestAction.equalsIgnoreCase("unassignInstance")
258                                                                 || requestAction.equalsIgnoreCase("deleteInstance")
259                                                                 || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) {
260                                         // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and
261                                         // SERVICE-MACRO-DELETE
262                                         // Will never get user params with service, macro will have
263                                         // to query the SI in AAI to find related instances.
264                                         traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds);
265                                 } else if (resourceType == WorkflowType.SERVICE
266                                                 && requestAction.equalsIgnoreCase("deactivateInstance")) {
267                                         resourceCounter.add(new Resource(WorkflowType.SERVICE,"",false));
268                                 } else if (resourceType == WorkflowType.VNF && (requestAction.equalsIgnoreCase("replaceInstance") || (requestAction.equalsIgnoreCase("recreateInstance")))) {
269                                         traverseAAIVnf(execution, resourceCounter, workflowResourceIds.getServiceInstanceId(), workflowResourceIds.getVnfId(), aaiResourceIds);
270                                 } else {
271                                         buildAndThrowException(execution, "Current Macro Request is not supported");
272                                 }
273                                 String foundObjects = "";
274                                 for(WorkflowType type : WorkflowType.values()){
275                                         foundObjects = foundObjects + type + " - " + resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()).size() + "    ";
276                                 }
277                                 logger.info("Found {}", foundObjects);
278
279                                 if (orchFlows == null || orchFlows.isEmpty()) {
280                                         orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner);
281                                 }
282                                 flowsToExecute = buildExecuteBuildingBlockList(orchFlows, resourceCounter, requestId, apiVersion, resourceId,
283                                                 resourceType, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails);
284                                 if (!resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).isEmpty()) {
285                                         logger.info("Sorting for Vlan Tagging");
286                                         flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction);
287                                 }
288                                 // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE
289                                 if (resourceType == WorkflowType.SERVICE
290                                         && (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE))
291                                         && !resourceCounter.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType())).collect(Collectors.toList()).isEmpty()) {
292                                         execution.setVariable("homing", true);
293                                         execution.setVariable("calledHoming", false);
294                                 }
295                                 if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE) || requestAction.equalsIgnoreCase(CREATEINSTANCE))){
296                                         generateResourceIds(flowsToExecute, resourceCounter, serviceInstanceId);
297                                 }else{
298                                         updateResourceIdsFromAAITraversal(flowsToExecute, resourceCounter, aaiResourceIds, serviceInstanceId);
299                                 }
300                         }
301
302                         // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified, enable it.
303                         if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
304                                 List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
305                                 for (Map<String, Object> params : userParams) {
306                                         if (params.containsKey(HOMINGSOLUTION)) {
307                                                 if (params.get(HOMINGSOLUTION).equals("none")) {
308                                                         execution.setVariable("homing", false);
309                                                 } else {
310                                                         execution.setVariable("homing", true);
311                                                 }
312                                         }
313                                 }
314                         }
315
316                         if (flowsToExecute.isEmpty()) {
317                                 throw new IllegalStateException("Macro did not come up with a valid execution path.");
318                         }
319
320                         logger.info("List of BuildingBlocks to execute:");
321                         for (ExecuteBuildingBlock ebb : flowsToExecute) {
322                                 logger.info(ebb.getBuildingBlock().getBpmnFlowName());
323                         }
324
325                         execution.setVariable(G_CURRENT_SEQUENCE, 0);
326                         execution.setVariable("retryCount", 0);
327                         execution.setVariable("isRollback", false);
328                         execution.setVariable("flowsToExecute", flowsToExecute);
329                         execution.setVariable("isRollbackComplete", false);
330
331                 } catch (Exception ex) {
332                         buildAndThrowException(execution, "Exception in create execution list " + ex.getMessage(), ex);
333                 }
334         }
335
336         protected List<Resource> sortVfModulesByBaseFirst(List<Resource> vfModuleResources) {
337                 int count = 0;
338                 for(Resource resource : vfModuleResources){
339                         if(resource.isBaseVfModule()){
340                                 Collections.swap(vfModuleResources, 0, count);
341                                 break;
342                 }
343                         count++;
344                 }
345                 return vfModuleResources;
346         }
347
348         private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute,
349                         List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) {
350                 for(Pair<WorkflowType,String> pair : aaiResourceIds){
351                         logger.debug(pair.getValue0() + ", " + pair.getValue1());
352                 }
353                 
354                 Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
355                         List<Resource> resources = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
356                         for(int i = 0; i < resources.size(); i++){
357                                 updateWorkflowResourceIds(flowsToExecute, type, resources.get(i).getResourceId(), retrieveAAIResourceId(aaiResourceIds,type), null, serviceInstanceId);
358                 }
359                 });
360         }
361
362         private String retrieveAAIResourceId(List<Pair<WorkflowType, String>> aaiResourceIds, WorkflowType resource){
363                 String id = null;
364                 for(int i = 0; i<aaiResourceIds.size();i++){
365                         if(aaiResourceIds.get(i).getValue0() == resource){
366                                 id = aaiResourceIds.get(i).getValue1();
367                                 aaiResourceIds.remove(i);
368                                 break;
369                         }
370                 }
371                 return id;
372         }
373         private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceCounter, String serviceInstanceId) {
374                 Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
375                         List<Resource> resources = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
376                         for(int i = 0; i < resources.size(); i++){
377                                 Resource resource = resourceCounter.stream().filter(x -> type.equals(x.getResourceType()))
378                                                 .collect(Collectors.toList()).get(i);
379                                 updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), null, resource.getVirtualLinkKey(),serviceInstanceId);
380                         }
381                 });
382         }       
383         
384         protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resource, String key, String id, String virtualLinkKey, String serviceInstanceId){
385                 String resourceId = id;
386                 if(resourceId==null){
387                         resourceId = UUID.randomUUID().toString();
388                 }
389                 for(ExecuteBuildingBlock ebb : flowsToExecute){
390                         if(key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey()) && ebb.getBuildingBlock().getBpmnFlowName().contains(resource.toString())){
391                                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
392                                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
393                                 if(resource == WorkflowType.VNF){
394                                         workflowResourceIds.setVnfId(resourceId);
395                                 }else if(resource == WorkflowType.VFMODULE){
396                                         workflowResourceIds.setVfModuleId(resourceId);
397                                 }else if(resource == WorkflowType.VOLUMEGROUP){
398                                         workflowResourceIds.setVolumeGroupId(resourceId);
399                                 }else if(resource == WorkflowType.NETWORK){
400                                         workflowResourceIds.setNetworkId(resourceId);
401                                 }else if(resource == WorkflowType.NETWORKCOLLECTION){
402                                         workflowResourceIds.setNetworkCollectionId(resourceId);
403                                 }else if(resource == WorkflowType.CONFIGURATION){
404                                         workflowResourceIds.setConfigurationId(resourceId);
405                                 }
406                                 ebb.setWorkflowResourceIds(workflowResourceIds);
407                         }
408                         if(virtualLinkKey != null && ebb.getBuildingBlock().getIsVirtualLink() 
409                                         && virtualLinkKey.equalsIgnoreCase(ebb.getBuildingBlock().getVirtualLinkKey())) {
410                                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
411                                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
412                                 workflowResourceIds.setNetworkId(resourceId);
413                                 ebb.setWorkflowResourceIds(workflowResourceIds);
414                         }
415                 }
416         }
417
418         protected CollectionResourceCustomization findCatalogNetworkCollection(DelegateExecution execution, org.onap.so.db.catalog.beans.Service service) {
419                 CollectionResourceCustomization networkCollection = null;
420                 int count = 0;
421                 for(CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()){
422                         if(catalogDbClient.getNetworkCollectionResourceCustomizationByID(collectionCust.getModelCustomizationUUID()) 
423                                         instanceof NetworkCollectionResourceCustomization) {
424                                 networkCollection = collectionCust;
425                                 count++;
426                         }
427                 }
428                 if(count == 0){
429                         return null;
430                 }else if(count > 1) {
431                         buildAndThrowException(execution, "Found multiple Network Collections in the Service model, only one per Service is supported.");
432                 }
433                 return networkCollection;
434         }
435         
436         protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest,
437                         List<Resource> resourceCounter) {
438                 String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId();
439                 org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID);
440                 if (service == null) {
441                         buildAndThrowException(execution, "Could not find the service model in catalog db.");
442                 } else {
443                         resourceCounter.add(new Resource(WorkflowType.SERVICE,service.getModelUUID(),false));
444                         if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) {
445                                 List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
446                                 if(customizations.isEmpty()) {
447                                         logger.debug("No Collections found. CollectionResourceCustomization list is empty.");
448                                 }else{
449                                         CollectionResourceCustomization collectionResourceCustomization = findCatalogNetworkCollection(execution, service);
450                                         if(collectionResourceCustomization!=null){
451                                                 resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,collectionResourceCustomization.getModelCustomizationUUID(),false));
452                                                 logger.debug("Found a network collection");
453                                                 if(collectionResourceCustomization.getCollectionResource()!=null){
454                                                         if(collectionResourceCustomization.getCollectionResource().getInstanceGroup() != null){
455                                                                 String toscaNodeType = collectionResourceCustomization.getCollectionResource().getInstanceGroup().getToscaNodeType();
456                                                                 if (toscaNodeType != null && toscaNodeType.contains("NetworkCollection")) {
457                                                                         int minNetworks = 0;
458                                                                         org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = collectionResourceCustomization.getCollectionResource().getInstanceGroup();
459                                                                         CollectionResourceInstanceGroupCustomization collectionInstCust = null;
460                                                                         if(!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) {
461                                                                                 for(CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup.getCollectionInstanceGroupCustomizations()) {
462                                                                                         if(collectionInstanceGroupTemp.getModelCustomizationUUID().equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
463                                                                                                 collectionInstCust = collectionInstanceGroupTemp;
464                                                                                                 break;
465                                                                                         }
466                                                                                 }
467                                                                                 if(collectionInstCust != null && collectionInstCust.getSubInterfaceNetworkQuantity() != null) {
468                                                                                         minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity();
469                                                                                 }
470                                                                         }
471                                                                         logger.debug("minNetworks: {}" , minNetworks);
472                                                                         CollectionNetworkResourceCustomization collectionNetworkResourceCust = null;
473                                                                         for(CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup.getCollectionNetworkResourceCustomizations()) {
474                                                                                 if(collectionNetworkTemp.getNetworkResourceCustomization().getModelCustomizationUUID().equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
475                                                                                         collectionNetworkResourceCust = collectionNetworkTemp;
476                                                                                         break;
477                                                                                 }
478                                                                         }
479                                                                         for (int i = 0; i < minNetworks; i++) {
480                                                                                 if(collectionNetworkResourceCust != null && collectionInstCust != null) {
481                                                                                         Resource resource = new Resource(WorkflowType.VIRTUAL_LINK,collectionNetworkResourceCust.getModelCustomizationUUID(),false);
482                                                                                         resource.setVirtualLinkKey(Integer.toString(i));
483                                                                                         resourceCounter.add(resource);
484                                                                                 }
485                                                                         }
486                                                                 } else {
487                                                                         logger.debug("Instance Group tosca node type does not contain NetworkCollection:  {}" , toscaNodeType);
488                                                                 }
489                                                         }else{
490                                                                 logger.debug("No Instance Group found for network collection.");
491                                                         }
492                                                 }else{
493                                                         logger.debug("No Network Collection found. collectionResource is null");
494                                                 }
495                                         } else {
496                                                 logger.debug("No Network Collection Customization found");
497                                         }
498                                 }
499                                 if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).isEmpty()) {
500                                         if (service.getNetworkCustomizations() == null) {
501                                                 logger.debug("No networks were found on this service model");
502                                         } else {
503                                                 for (int i = 0; i < service.getNetworkCustomizations().size(); i++) {
504                                                         resourceCounter.add(new Resource(WorkflowType.NETWORK,service.getNetworkCustomizations().get(i).getModelCustomizationUUID(),false));
505                                                 }
506                                         }
507                                 }
508                         } else {
509                                 buildAndThrowException(execution,
510                                                 "Cannot orchestrate Service-Macro-Create without user params with a vnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows");
511                         }
512                 }
513         }
514
515         protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceCounter, String resourceId, List<Pair<WorkflowType, String>> aaiResourceIds) {
516                 try {
517                         ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
518                         org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup
519                                         .getExistingServiceInstance(serviceInstanceAAI);
520                         resourceCounter.add(new Resource(WorkflowType.SERVICE,serviceInstanceMSO.getServiceInstanceId(),false));
521                         if (serviceInstanceMSO.getVnfs() != null) {
522                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO
523                                                 .getVnfs()) {
524                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
525                                         resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getVnfId(),false));
526                                         if (vnf.getVfModules() != null) {
527                                                 for (VfModule vfModule : vnf.getVfModules()) {
528                                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
529                                                         resourceCounter.add(new Resource(WorkflowType.VFMODULE,vfModule.getVfModuleId(),false));
530                                                 }
531                                         }
532                                         if (vnf.getVolumeGroups() != null) {
533                                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
534                                                                 .getVolumeGroups()) {
535                                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
536                                                         resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,volumeGroup.getVolumeGroupId(),false));
537                                                 }
538                                         }
539                                 }
540                         }
541                         if (serviceInstanceMSO.getNetworks() != null) {
542                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network : serviceInstanceMSO
543                                                 .getNetworks()) {
544                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORK, network.getNetworkId()));
545                                         resourceCounter.add(new Resource(WorkflowType.NETWORK,network.getNetworkId(),false));
546                                 }
547                         }
548                         if (serviceInstanceMSO.getCollection() != null) {
549                                 logger.debug("found networkcollection");
550                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORKCOLLECTION, serviceInstanceMSO.getCollection().getId()));
551                                 resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,serviceInstanceMSO.getCollection().getId(),false));
552                         }
553                         if (serviceInstanceMSO.getConfigurations() !=null) {
554                                 for(Configuration config : serviceInstanceMSO.getConfigurations()){
555                                         Optional<org.onap.aai.domain.yang.Configuration> aaiConfig = aaiConfigurationResources.getConfiguration(config.getConfigurationId());
556                                         if(aaiConfig.isPresent() && aaiConfig.get().getRelationshipList()!=null){
557                                                 for(Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()){
558                                                         if(relationship.getRelatedTo().contains("vnfc")){
559                                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.getConfigurationId()));
560                                                                 resourceCounter.add(new Resource(WorkflowType.CONFIGURATION,config.getConfigurationId(),false));
561                                                                 break;
562                                                         }
563                                                 }
564                                         }
565                                 }
566                         }
567                 } catch (Exception ex) {
568                         buildAndThrowException(execution,
569                                         "Could not find existing Service Instance or related Instances to execute the request on.");
570                 }
571         }
572
573         private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceCounter, String serviceId, String vnfId,
574                         List<Pair<WorkflowType, String>> aaiResourceIds) {
575                 try{
576                         ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId);
577                         org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup
578                                         .getExistingServiceInstance(serviceInstanceAAI);
579                         resourceCounter.add(new Resource(WorkflowType.SERVICE,serviceInstanceMSO.getServiceInstanceId(),false));
580                         if (serviceInstanceMSO.getVnfs() != null) {
581                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO
582                                                 .getVnfs()) {
583                                         if(vnf.getVnfId().equals(vnfId)){
584                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
585                                                 resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getVnfId(),false));
586                                                 if (vnf.getVfModules() != null) {
587                                                         for (VfModule vfModule : vnf.getVfModules()) {
588                                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
589                                                                 resourceCounter.add(new Resource(WorkflowType.VFMODULE,vfModule.getVfModuleId(),false));        
590                                                                 findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(), resourceCounter, aaiResourceIds);
591                                                         }
592                                                 }
593                                                 if (vnf.getVolumeGroups() != null) {
594                                                         for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
595                                                                         .getVolumeGroups()) {
596                                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
597                                                                 resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,volumeGroup.getVolumeGroupId(),false));
598                                                         }
599                                                 }
600                                                 break;
601                                         }
602                                 }
603                         }
604                 } catch (Exception ex) {
605                         buildAndThrowException(execution,
606                                         "Could not find existing Vnf or related Instances to execute the request on.");
607                 }
608         }
609
610         private void findConfigurationsInsideVfModule(DelegateExecution execution, String vnfId, String vfModuleId, List<Resource> resourceCounter, 
611                         List<Pair<WorkflowType, String>> aaiResourceIds) {
612                 try{
613                         org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
614                         AAIResultWrapper vfModuleWrapper = new AAIResultWrapper(
615                                         new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVfModule));
616                         Optional<Relationships> relationshipsOp;
617                         relationshipsOp = vfModuleWrapper.getRelationships();
618                         if(relationshipsOp.isPresent()) {
619                                 relationshipsOp = workflowActionUtils.extractRelationshipsVnfc(relationshipsOp.get());
620                                 if(relationshipsOp.isPresent()){
621                                         Optional<Configuration> config = workflowActionUtils.extractRelationshipsConfiguration(relationshipsOp.get());
622                                         if(config.isPresent()){
623                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.get().getConfigurationId()));
624                                                 resourceCounter.add(new Resource(WorkflowType.CONFIGURATION, config.get().getConfigurationId(), false));
625                                         }
626                                 }
627                         }
628                 }catch (Exception ex){
629                         buildAndThrowException(execution,
630                                         "Failed to find Configuration object from the vfModule.");
631                 }
632         }
633         
634         protected boolean traverseUserParamsService(DelegateExecution execution, List<Resource> resourceCounter,
635                         ServiceInstancesRequest sIRequest, String requestAction)
636                         throws IOException {
637                 boolean foundRelated = false;
638                 boolean foundVfModuleOrVG = false;
639                 String vnfCustomizationUUID = "";
640                 String vfModuleCustomizationUUID = "";
641                 if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
642                         List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
643                         for (Map<String, Object> params : userParams) {
644                                 if (params.containsKey(USERPARAMSERVICE)) {
645                                         ObjectMapper obj = new ObjectMapper();
646                                         String input = obj.writeValueAsString(params.get(USERPARAMSERVICE));
647                                         Service validate = obj.readValue(input, Service.class);
648                                         resourceCounter.add(new Resource(WorkflowType.SERVICE,validate.getModelInfo().getModelVersionId(),false));
649                                         if (validate.getResources().getVnfs() != null) {
650                                                 for (Vnfs vnf : validate.getResources().getVnfs()) {
651                                                         resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getModelInfo().getModelCustomizationId(),false));
652                                                         foundRelated = true;
653                                                         if(vnf.getModelInfo()!=null && vnf.getModelInfo().getModelCustomizationUuid()!=null){
654                                                                 vnfCustomizationUUID = vnf.getModelInfo().getModelCustomizationUuid();
655                                                         }
656                                                         if (vnf.getVfModules() != null) {
657                                                                 for (VfModules vfModule : vnf.getVfModules()) {
658                                                                         VfModuleCustomization vfModuleCustomization = catalogDbClient
659                                                                                         .getVfModuleCustomizationByModelCuztomizationUUID(
660                                                                                                         vfModule.getModelInfo().getModelCustomizationUuid());
661                                                                         if (vfModuleCustomization != null) {
662
663                                                                                 if(vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null && vfModuleCustomization.getVolumeHeatEnv() != null) {
664                                                                                         resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,vfModuleCustomization.getModelCustomizationUUID(),false));
665                                                                                         foundRelated = true;
666                                                                                         foundVfModuleOrVG = true;
667                                                                                 }
668
669                                                                                 if(vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getModuleHeatTemplate() != null && vfModuleCustomization.getHeatEnvironment() != null){
670                                                                                         foundRelated = true;
671                                                                                         foundVfModuleOrVG = true;
672                                                                                         Resource resource = new Resource(WorkflowType.VFMODULE,vfModuleCustomization.getModelCustomizationUUID(),false);
673                                                                                         if(vfModuleCustomization.getVfModule().getIsBase()!=null && vfModuleCustomization.getVfModule().getIsBase()){
674                                                                                                 resource.setBaseVfModule(true);
675                                                                                         }else{
676                                                                                                 resource.setBaseVfModule(false);
677                                                                                         }
678                                                                                         resourceCounter.add(resource);
679                                                                                         if(vfModule.getModelInfo()!=null && vfModule.getModelInfo().getModelCustomizationUuid()!=null){
680                                                                                                 vfModuleCustomizationUUID = vfModule.getModelInfo().getModelCustomizationUuid();
681                                                                                         }
682                                                                                         if(!vnfCustomizationUUID.equals("")&&!vfModuleCustomizationUUID.equals("")){
683                                                                                                 List<String> configs = traverseCatalogDbForConfiguration(vnfCustomizationUUID,vfModuleCustomizationUUID);
684                                                                                                 for(String config : configs){
685                                                                                                         Resource configResource = new Resource(WorkflowType.CONFIGURATION,config,false);
686                                                                                                         resource.setVnfCustomizationId(vnf.getModelInfo().getModelCustomizationId());
687                                                                                                         resource.setVfModuleCustomizationId(vfModule.getModelInfo().getModelCustomizationId());
688                                                                                                         resourceCounter.add(configResource);
689                                                                                                 }
690                                                                                         }
691                                                                                 }
692                                                                                 if(!foundVfModuleOrVG){
693                                                                                         buildAndThrowException(execution, "Could not determine if vfModule was a vfModule or volume group. Heat template and Heat env are null");
694                                                                                 }
695                                                                         }
696                                                                 }
697                                                         }
698                                                 }
699                                         }
700                                         if (validate.getResources().getNetworks() != null) {
701                                                 for (Networks network : validate.getResources().getNetworks()) {
702                                                         resourceCounter.add(new Resource(WorkflowType.NETWORK,network.getModelInfo().getModelCustomizationId(),false));
703                                                         foundRelated = true;
704                                                 }
705                                                 if (requestAction.equals(CREATEINSTANCE)) {
706                                                         String networkColCustId = queryCatalogDBforNetworkCollection(execution, sIRequest);
707                                                         if (networkColCustId != null) {
708                                                                 resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,networkColCustId,false));
709                                                                 foundRelated = true;
710                                                         }
711                                                 }
712                                         }
713                                         break;
714                                 }
715                         }
716                 }
717                 return foundRelated;
718         }
719         
720
721         protected List<String> traverseCatalogDbForConfiguration(String vnfCustomizationUUID, String vfModuleCustomizationUUID) {
722                 List<String> configurations = new ArrayList<>();
723                 try{
724                         List<CvnfcCustomization> cvnfcCustomizations = catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID(vnfCustomizationUUID, vfModuleCustomizationUUID);
725                         for(CvnfcCustomization cvnfc : cvnfcCustomizations){
726                                 for(VnfVfmoduleCvnfcConfigurationCustomization customization : cvnfc.getVnfVfmoduleCvnfcConfigurationCustomization()){
727                                         if(customization.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)){
728                                                 configurations.add(customization.getConfigurationResource().getModelUUID());
729                                         }
730                                 }
731                         }
732                         logger.debug("found {} configurations" , configurations.size() );
733                         return configurations;
734                 } catch (Exception ex){
735                         logger.error("Error in finding configurations", ex);
736                         return configurations;
737                 }
738         }
739
740         protected String queryCatalogDBforNetworkCollection(DelegateExecution execution, ServiceInstancesRequest sIRequest) {
741                 org.onap.so.db.catalog.beans.Service service = catalogDbClient
742                                 .getServiceByID(sIRequest.getRequestDetails().getModelInfo().getModelVersionId());
743                 if (service != null) {
744                         CollectionResourceCustomization networkCollection = this.findCatalogNetworkCollection(execution, service);
745                         if(networkCollection != null) {
746                                 return networkCollection.getModelCustomizationUUID();
747                         }
748                 }
749                 return null;
750         }
751
752         protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) {
753                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
754                 workflowResourceIds.setServiceInstanceId((String) execution.getVariable("serviceInstanceId"));
755                 workflowResourceIds.setNetworkId((String) execution.getVariable("networkId"));
756                 workflowResourceIds.setVfModuleId((String) execution.getVariable("vfModuleId"));
757                 workflowResourceIds.setVnfId((String) execution.getVariable("vnfId"));
758                 workflowResourceIds.setVolumeGroupId((String) execution.getVariable("volumeGroupId"));
759                 return workflowResourceIds;
760         }
761
762         protected Resource extractResourceIdAndTypeFromUri(String uri) {
763             Pattern patt = Pattern.compile(
764                     "[vV]\\d+.*?(?:(?:/(?<type>" + supportedTypes + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?)?$");
765             Matcher m = patt.matcher(uri);
766             Boolean generated = false;
767
768             if (m.find()) {
769                 logger.debug("found match on {} : {} " , uri ,  m);
770                 String type = m.group("type");
771                 String id = m.group("id");
772                 String action = m.group("action");
773                 if (type == null) {
774                     throw new IllegalArgumentException("Uri could not be parsed. No type found. " + uri);
775                 }
776                 if (action == null) {
777                     if (type.equals(SERVICE_INSTANCES) && (id == null || id.equals("assign"))) {
778                         id = UUID.randomUUID().toString();
779                         generated = true;
780                     }else if (type.equals(VF_MODULES) && id.equals("scaleOut")) {
781                         id = UUID.randomUUID().toString();
782                         generated = true;
783                     }
784                 } else {
785                     if (action.matches(supportedTypes)) {
786                         id = UUID.randomUUID().toString();
787                         generated = true;
788                         type = action;
789                     }
790                 }
791                 return new Resource(WorkflowType.fromString(convertTypeFromPlural(type)), id, generated);
792             } else {
793                 throw new IllegalArgumentException("Uri could not be parsed: " + uri);
794             }
795         }
796
797         protected String validateResourceIdInAAI(String generatedResourceId, WorkflowType type, String instanceName,
798                         RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws Exception {
799                 try {
800                         if ("SERVICE".equalsIgnoreCase(type.toString())) {
801                                 String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId();
802                                 String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType();
803                                 if (instanceName != null) {
804                                         Optional<ServiceInstance> serviceInstanceAAI = bbInputSetupUtils
805                                                         .getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName);
806                                         if (serviceInstanceAAI.isPresent()) {
807                                                 return serviceInstanceAAI.get().getServiceInstanceId();
808                                         }
809                                 }
810                         } else if ("NETWORK".equalsIgnoreCase(type.toString())) {
811                                 Optional<L3Network> network = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(
812                                                 workflowResourceIds.getServiceInstanceId(), instanceName);
813                                 if (network.isPresent()) {
814                                         return network.get().getNetworkId();
815                                 }
816                         } else if ("VNF".equalsIgnoreCase(type.toString())) {
817                                 Optional<GenericVnf> vnf = bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(
818                                                 workflowResourceIds.getServiceInstanceId(), instanceName);
819                                 if (vnf.isPresent()) {
820                                         return vnf.get().getVnfId();
821                                 }
822                         } else if ("VFMODULE".equalsIgnoreCase(type.toString())) {
823                                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
824                                 if (vnf != null && vnf.getVfModules() != null) {
825                                         for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
826                                                 if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) {
827                                                         return vfModule.getVfModuleId();
828                                                 }
829                                         }
830                                 }
831                         } else if ("VOLUMEGROUP".equalsIgnoreCase(type.toString())) {
832                                 Optional<VolumeGroup> volumeGroup = bbInputSetupUtils
833                                                 .getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName);
834                                 if (volumeGroup.isPresent()) {
835                                         return volumeGroup.get().getVolumeGroupId();
836                                 }
837                                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
838                                 if (vnf != null && vnf.getVfModules() != null) {
839                                         for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
840                                                 Optional<VolumeGroup> volumeGroupFromVfModule = bbInputSetupUtils
841                                                                 .getRelatedVolumeGroupByNameFromVfModule(vnf.getVnfId(), vfModule.getVfModuleId(), instanceName);
842                                                 if (volumeGroupFromVfModule.isPresent()) {
843                                                         return volumeGroupFromVfModule.get().getVolumeGroupId();
844                                                 }
845                                         }
846                                 }
847                         }
848                         return generatedResourceId;
849                 } catch (Exception ex) {
850                         logger.error(WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI, ex);
851                         throw new IllegalStateException(
852                                         WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI);
853                 }
854         }
855
856         protected String convertTypeFromPlural(String type) {
857                 if (!type.matches(supportedTypes)) {
858                         return type;
859                 } else {
860                         if (type.equals(SERVICE_INSTANCES)) {
861                                 return SERVICE;
862                         } else {
863                                 return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
864                         }
865                 }
866         }
867
868         protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
869                         String requestAction) {
870                 List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
871                 if (requestAction.equals(CREATEINSTANCE)) {
872                         for (ExecuteBuildingBlock ebb : orchFlows) {
873                                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
874                                         String key = ebb.getBuildingBlock().getKey();
875                                         boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().getIsVirtualLink());
876                                         String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
877                                         sortedOrchFlows.add(ebb);
878                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
879                                                 if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
880                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
881                                                         sortedOrchFlows.add(ebb2);
882                                                         break;
883                                                 }
884                                                 if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
885                                                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
886                                                         sortedOrchFlows.add(ebb2);
887                                                         break;
888                                                 }
889                                         }
890                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
891                                                 if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
892                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
893                                                         sortedOrchFlows.add(ebb2);
894                                                         break;
895                                                 }
896                                                 if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
897                                                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
898                                                         sortedOrchFlows.add(ebb2);
899                                                         break;
900                                                 }
901                                         }
902                                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
903                                                 || ebb.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")) {
904                                         continue;
905                                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
906                                         sortedOrchFlows.add(ebb);
907                                 }
908                         }
909                 } else if (requestAction.equals("deleteInstance")) {
910                         for (ExecuteBuildingBlock ebb : orchFlows) {
911                                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
912                                         sortedOrchFlows.add(ebb);
913                                         String key = ebb.getBuildingBlock().getKey();
914                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
915                                                 if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
916                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
917                                                         sortedOrchFlows.add(ebb2);
918                                                         break;
919                                                 }
920                                         }
921                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
922                                                 if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
923                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
924                                                         sortedOrchFlows.add(ebb2);
925                                                         break;
926                                                 }
927                                         }
928                                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
929                                                 || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
930                                         continue;
931                                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
932                                         sortedOrchFlows.add(ebb);
933                                 }
934                         }
935                 }
936                 return sortedOrchFlows;
937         }
938
939         protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows,
940                         List<Resource> resourceCounter, String requestId, String apiVersion, String resourceId, WorkflowType resourceType,
941                         String requestAction, boolean aLaCarte, String vnfType,
942                         WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails) {
943                 List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
944                 for (OrchestrationFlow orchFlow : orchFlows) {
945                         if (orchFlow.getFlowName().contains(SERVICE)) {
946                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
947                                         workflowResourceIds.setServiceInstanceId(resourceId);
948                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType())
949                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
950                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
951                                 }
952                         } else if (orchFlow.getFlowName().contains(VNF)) {
953                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
954                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType())
955                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
956                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
957                                 }
958                         } else if (orchFlow.getFlowName().contains(NETWORK)
959                                         && !orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
960                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
961                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType())
962                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
963                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
964                                 }
965                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
966                                         Resource resource = resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType())
967                                                         .collect(Collectors.toList()).get(i);
968                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, apiVersion, resourceId,
969                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, true, resource.getVirtualLinkKey(), false));
970                                 }
971                         } else if (orchFlow.getFlowName().contains(VFMODULE)) {
972                                 List<Resource> vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceCounter.stream().filter(x -> WorkflowType.VFMODULE == x.getResourceType())
973                                                 .collect(Collectors.toList()));
974                                 for (int i = 0; i < vfModuleResourcesSorted.size(); i++) {
975                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, vfModuleResourcesSorted.get(i), apiVersion, resourceId,
976                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
977                                 }
978                         } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) {
979                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
980                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType())
981                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
982                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
983                                 }
984                         } else if (orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
985                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
986                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
987                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
988                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
989                                 }
990                         } else if (orchFlow.getFlowName().contains(CONFIGURATION)) {
991                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
992                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType())
993                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
994                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, true));
995                                 }
996                         }else {
997                                 flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, null, apiVersion, resourceId,
998                                                 requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
999                         }
1000                 }
1001                 return flowsToExecute;
1002         }
1003
1004         protected ExecuteBuildingBlock buildExecuteBuildingBlock(OrchestrationFlow orchFlow, String requestId, Resource resource,
1005                         String apiVersion, String resourceId, String requestAction, boolean aLaCarte, String vnfType,
1006                         WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, boolean isVirtualLink, String virtualLinkKey, boolean isConfiguration) {
1007                 ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
1008                 BuildingBlock buildingBlock = new BuildingBlock();
1009                 buildingBlock.setBpmnFlowName(orchFlow.getFlowName());
1010                 buildingBlock.setMsoId(UUID.randomUUID().toString());
1011                 if(resource == null){
1012                         buildingBlock.setKey("");
1013                 }else{
1014                         buildingBlock.setKey(resource.getResourceId());
1015                 }
1016                 buildingBlock.setIsVirtualLink(isVirtualLink);
1017                 buildingBlock.setVirtualLinkKey(virtualLinkKey);
1018                 executeBuildingBlock.setApiVersion(apiVersion);
1019                 executeBuildingBlock.setaLaCarte(aLaCarte);
1020                 executeBuildingBlock.setRequestAction(requestAction);
1021                 executeBuildingBlock.setResourceId(resourceId);
1022                 executeBuildingBlock.setVnfType(vnfType);
1023                 executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
1024                 executeBuildingBlock.setRequestId(requestId);
1025                 executeBuildingBlock.setBuildingBlock(buildingBlock);
1026                 executeBuildingBlock.setRequestDetails(requestDetails);
1027                 if(isConfiguration){
1028                         ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
1029                         configurationResourceKeys.setCvnfcCustomizationUUID(resource.getCvnfModuleCustomizationId());
1030                         configurationResourceKeys.setVfModuleCustomizationUUID(resource.getVfModuleCustomizationId());
1031                         configurationResourceKeys.setVnfResourceCustomizationUUID(resource.getVnfCustomizationId());
1032                         executeBuildingBlock.setConfigurationResourceKeys(configurationResourceKeys);
1033                 }
1034                 return executeBuildingBlock;
1035         }
1036
1037         protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
1038                         WorkflowType resourceName, boolean aLaCarte, String cloudOwner) {
1039                 List<OrchestrationFlow> listToExecute = new ArrayList<>();
1040                 NorthBoundRequest northBoundRequest = catalogDbClient
1041                                 .getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(requestAction, resourceName.toString(), aLaCarte, cloudOwner);
1042                 if(northBoundRequest == null){
1043                         if(aLaCarte){
1044                                 buildAndThrowException(execution,"The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API.");
1045                         }else{
1046                                 buildAndThrowException(execution,"The request: Macro " + resourceName + " " + requestAction + " is not supported by GR_API.");
1047                         }
1048                 } else {
1049                 if(northBoundRequest.getIsToplevelflow()!=null){
1050                         execution.setVariable(G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
1051                 }
1052                 List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
1053                 if (flows == null)
1054                         flows = new ArrayList<>();
1055                 for (OrchestrationFlow flow : flows) {
1056                         if (!flow.getFlowName().contains("BB")) {
1057                                 List<OrchestrationFlow> macroQueryFlows = catalogDbClient
1058                                                 .getOrchestrationFlowByAction(flow.getFlowName());
1059                                 for (OrchestrationFlow macroFlow : macroQueryFlows) {
1060                                         listToExecute.add(macroFlow);
1061                                 }
1062                         } else {
1063                                 listToExecute.add(flow);
1064                         }
1065                 }
1066                 }
1067                 return listToExecute;
1068         }
1069         
1070         protected List<OrchestrationFlow> filterOrchFlows(List<OrchestrationFlow> orchFlows, WorkflowType resourceType, DelegateExecution execution) {
1071                 List<OrchestrationFlow> result = new ArrayList<>(orchFlows);
1072                 if (resourceType.equals(WorkflowType.VFMODULE)) {
1073                         List<String> fabricCustomizations = traverseCatalogDbForConfiguration((String)execution.getVariable("vnfId"), (String)execution.getVariable("vfModuleId"));
1074                         if (fabricCustomizations.isEmpty()) {
1075                                 result = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION)).collect(Collectors.toList());
1076                         }
1077                 }
1078                 return result;
1079         }
1080
1081         protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
1082                 logger.error(msg, ex);
1083                 execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
1084                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
1085         }
1086
1087         protected void buildAndThrowException(DelegateExecution execution, String msg) {
1088                 logger.error(msg);
1089                 execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
1090                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
1091         }
1092         
1093         public void handleRuntimeException (DelegateExecution execution){
1094                 StringBuilder wfeExpMsg = new StringBuilder("Runtime error ");
1095                 String runtimeErrorMessage = null;
1096                 try{
1097                         String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
1098                         if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
1099                                 wfeExpMsg = wfeExpMsg.append(": ").append(javaExpMsg);
1100                         }
1101                         runtimeErrorMessage = wfeExpMsg.toString();
1102                         logger.error(runtimeErrorMessage);
1103                         execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, runtimeErrorMessage);
1104                 } catch (Exception e){
1105                         logger.error("Runtime error", e);
1106                         //if runtime message was mulformed
1107                         runtimeErrorMessage = "Runtime error";
1108                 }
1109                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
1110         }
1111 }