Add support for ResourceInstanceGroup
[aai/babel.git] / src / main / java / org / onap / aai / babel / parser / ArtifactGeneratorToscaParser.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.babel.parser;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.Properties;
33 import java.util.stream.Collectors;
34 import org.onap.aai.babel.logging.ApplicationMsgs;
35 import org.onap.aai.babel.logging.LogHelper;
36 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
37 import org.onap.aai.babel.xml.generator.model.AllotedResource;
38 import org.onap.aai.babel.xml.generator.model.InstanceGroup;
39 import org.onap.aai.babel.xml.generator.model.L3NetworkWidget;
40 import org.onap.aai.babel.xml.generator.model.Model;
41 import org.onap.aai.babel.xml.generator.model.ProvidingService;
42 import org.onap.aai.babel.xml.generator.model.Resource;
43 import org.onap.aai.babel.xml.generator.model.Service;
44 import org.onap.aai.babel.xml.generator.model.TunnelXconnectWidget;
45 import org.onap.aai.babel.xml.generator.model.VfModule;
46 import org.onap.aai.babel.xml.generator.model.Widget;
47 import org.onap.aai.babel.xml.generator.types.ModelType;
48 import org.onap.aai.cl.api.Logger;
49 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
50 import org.onap.sdc.toscaparser.api.Group;
51 import org.onap.sdc.toscaparser.api.NodeTemplate;
52 import org.onap.sdc.toscaparser.api.Property;
53 import org.onap.sdc.toscaparser.api.elements.Metadata;
54
55 public class ArtifactGeneratorToscaParser {
56
57     private static Logger log = LogHelper.INSTANCE;
58
59     public static final String PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE = "artifactgenerator.config";
60     public static final String PROPERTY_GROUP_FILTERS_CONFIG_FILE = "groupfilter.config";
61
62     private static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND =
63             "Cannot generate artifacts. Artifact Generator Configuration file not found at %s";
64     private static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND =
65             "Cannot generate artifacts. System property %s not configured";
66     private static final String GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING =
67             "Cannot generate artifacts. Providing Service Metadata is missing for allotted resource %s";
68     private static final String GENERATOR_AAI_PROVIDING_SERVICE_MISSING =
69             "Cannot generate artifacts. Providing Service is missing for allotted resource %s";
70
71     // Metadata properties
72     private static final String CATEGORY = "category";
73     private static final String ALLOTTED_RESOURCE = "Allotted Resource";
74     private static final String SUBCATEGORY = "subcategory";
75     private static final String TUNNEL_XCONNECT = "Tunnel XConnect";
76
77     private static final String VERSION = "version";
78
79     private ISdcCsarHelper csarHelper;
80
81     /**
82      * Constructs using csarHelper
83      *
84      * @param csarHelper The csar helper
85      */
86     public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
87         this.csarHelper = csarHelper;
88     }
89
90     /**
91      * Returns the artifact description
92      *
93      * @param model the artifact model
94      * @return the artifact model's description
95      */
96     public static String getArtifactDescription(Model model) {
97         String artifactDesc = model.getModelDescription();
98         if (model.getModelType().equals(ModelType.SERVICE)) {
99             artifactDesc = "AAI Service Model";
100         } else if (model.getModelType().equals(ModelType.RESOURCE)) {
101             artifactDesc = "AAI Resource Model";
102         }
103         return artifactDesc;
104     }
105
106     /**
107      * Initialises the widget configuration.
108      *
109      * @throws IOException
110      */
111     public static void initWidgetConfiguration() throws IOException {
112         log.debug("Getting Widget Configuration");
113         String configLocation = System.getProperty(PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE);
114         if (configLocation != null) {
115             File file = new File(configLocation);
116             if (file.exists()) {
117                 Properties properties = new Properties();
118                 properties.load(new FileInputStream(file));
119                 WidgetConfigurationUtil.setConfig(properties);
120             } else {
121                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
122             }
123         } else {
124             throw new IllegalArgumentException(
125                     String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE));
126         }
127     }
128
129     /**
130      * Initialises the group filter configuration.
131      *
132      * @throws IOException
133      */
134     public static void initGroupFilterConfiguration() throws IOException {
135         log.debug("Getting Filter Tyoes Configuration");
136         String configLocation = System.getProperty(PROPERTY_GROUP_FILTERS_CONFIG_FILE);
137         if (configLocation != null) {
138             File file = new File(configLocation);
139             if (file.exists()) {
140                 Properties properties = new Properties();
141                 properties.load(new FileInputStream(file));
142                 WidgetConfigurationUtil.setFilterConfig(properties);
143             } else {
144                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
145             }
146         } else {
147             throw new IllegalArgumentException(
148                     String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_GROUP_FILTERS_CONFIG_FILE));
149         }
150     }
151
152     /**
153      * Process the service TOSCA.
154      *
155      * @param service model of the service artifact
156      * @param idTypeStore ID->Type mapping
157      * @param nodeTemplates a list of service nodes
158      *
159      */
160     public void processServiceTosca(Service service, Map<String, String> idTypeStore,
161             List<NodeTemplate> nodeTemplates) {
162         log.debug("Processing (TOSCA) Service object");
163
164         for (NodeTemplate nodeTemplate : nodeTemplates) {
165             if (nodeTemplate.getMetaData() != null) {
166                 addNodeToService(idTypeStore, service, nodeTemplate);
167             } else {
168                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, nodeTemplate.getName());
169             }
170         }
171     }
172
173     /**
174      * Generates a Resource List using input Service Node Templates.
175      *
176      * @param serviceNodes input Service Node Templates
177      * @param idTypeStore ID->Type mapping
178      *
179      * @return the processed resource models
180      */
181     public List<Resource> processResourceToscas(List<NodeTemplate> serviceNodes, Map<String, String> idTypeStore) {
182         List<Resource> resources = new LinkedList<>();
183         for (NodeTemplate serviceNode : serviceNodes) {
184             if (serviceNode.getMetaData() != null) {
185                 resources.addAll(processResourceTosca(idTypeStore, serviceNode,
186                         csarHelper.getNodeTemplateChildren(serviceNode)));
187             } else {
188                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, serviceNode.getName());
189             }
190         }
191         return resources;
192     }
193
194     /**
195      * @param idTypeStore ID->Type mapping
196      * @param serviceNode
197      * @param resourceNodes
198      * @return the processed resource models
199      */
200     private List<Resource> processResourceTosca(Map<String, String> idTypeStore, NodeTemplate serviceNode,
201             List<NodeTemplate> resourceNodes) {
202         List<Resource> resources = new LinkedList<>();
203         String resourceUuId = serviceNode.getMetaData().getValue("UUID");
204         String nodeTypeName = idTypeStore.get(resourceUuId);
205         if (nodeTypeName != null) {
206             Model resourceModel = Model.getModelFor(nodeTypeName, serviceNode.getMetaData().getValue("type"));
207
208             log.debug("Processing resource " + nodeTypeName + ": " + resourceUuId);
209             Map<String, String> serviceMetadata = serviceNode.getMetaData().getAllProperties();
210             resourceModel.populateModelIdentificationInformation(serviceMetadata);
211
212             idTypeStore.remove(resourceModel.getModelNameVersionId());
213             processResourceModels(idTypeStore, resourceModel, resourceNodes);
214
215             if (csarHelper.getServiceVfList() != null) {
216                 processVfModules(resources, resourceModel, serviceNode);
217             }
218
219             if (hasSubCategoryTunnelXConnect(serviceMetadata) && hasAllottedResource(serviceMetadata)) {
220                 resourceModel.addWidget(new TunnelXconnectWidget());
221             }
222
223             resources.addAll(processInstanceGroups(resourceModel, serviceNode));
224             resources.add((Resource) resourceModel);
225         }
226         return resources;
227     }
228
229     /**
230      * Process groups for this service node, according to the defined filter.
231      *
232      * @param resourceModel
233      * @param serviceNode
234      * @return resources for which XML Models should be generated
235      */
236     List<Resource> processInstanceGroups(Model resourceModel, NodeTemplate serviceNode) {
237         List<Resource> resources = new ArrayList<>();
238         if (csarHelper.getNodeTemplateByName(serviceNode.getName()).getSubMappingToscaTemplate() != null) {
239             List<Group> serviceGroups = csarHelper.getGroupsOfOriginOfNodeTemplate(serviceNode);
240             for (Group group : serviceGroups) {
241                 if (WidgetConfigurationUtil.isSupportedInstanceGroup(group.getType())) {
242                     resources.addAll(processInstanceGroup(resourceModel, group.getMemberNodes(),
243                             group.getMetadata().getAllProperties(), group.getProperties()));
244                 }
245             }
246         }
247         return resources;
248     }
249
250     /**
251      * Create an Instance Group Model and populate it with the supplied data.
252      *
253      * @param resourceModel the Resource node template Model
254      * @param memberNodes the Resources and Widgets belonging to the Group
255      * @param metaProperties the metadata of the Group
256      * @param properties the properties of the Group
257      * @return the Instance Group and Member resource models
258      */
259     private List<Resource> processInstanceGroup(Model resourceModel, ArrayList<NodeTemplate> memberNodes,
260             Map<String, String> metaProperties, Map<String, Property> properties) {
261         List<Resource> resources = new ArrayList<>();
262
263         Resource groupModel = new InstanceGroup();
264         groupModel.populateModelIdentificationInformation(metaProperties);
265         groupModel.populateModelIdentificationInformation(populateStringProperties(properties));
266
267         resourceModel.addResource(groupModel);
268         resources.add(groupModel);
269
270         if (memberNodes != null && !memberNodes.isEmpty()) {
271             resources.addAll(generateResourcesAndWidgets(memberNodes, groupModel));
272         }
273
274         return resources;
275     }
276
277     /**
278      * @param memberNodes
279      * @param groupModel
280      * @return
281      */
282     private List<Resource> generateResourcesAndWidgets(final ArrayList<NodeTemplate> memberNodes,
283             final Resource groupModel) {
284         List<Resource> resources = new ArrayList<>();
285         for (NodeTemplate nodeTemplate : memberNodes) {
286             String nodeTypeName = normaliseNodeTypeName(nodeTemplate);
287             Model memberModel = Model.getModelFor(nodeTypeName, nodeTemplate.getMetaData().getValue("type"));
288             memberModel.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
289
290             log.debug(String.format("Generating grouped %s (%s) from TOSCA type %s",
291                     memberModel.getClass().getSuperclass().getSimpleName(), memberModel.getClass(), nodeTypeName));
292
293             addRelatedModel(groupModel, memberModel);
294             if (memberModel instanceof Resource) {
295                 resources.add((Resource) memberModel);
296             }
297         }
298         return resources;
299     }
300
301     /**
302      * Add the supplied Node Template to the Service, provided that it is a valid Resource or Widget. If the Node
303      * Template is a Resource type, this is also recorded in the supplied nodesById Map.
304      *
305      * @param nodesById a map of Resource node type names, keyed by UUID
306      * @param service the Service to which the Node Template should be added
307      * @param nodeTemplate the Node Template to add (only if this is a Resource or Widget type)
308      */
309     private void addNodeToService(Map<String, String> nodesById, Service service, NodeTemplate nodeTemplate) {
310         String nodeTypeName = normaliseNodeTypeName(nodeTemplate);
311         Model model = Model.getModelFor(nodeTypeName, nodeTemplate.getMetaData().getValue("type"));
312         if (model != null) {
313             if (nodeTemplate.getMetaData() != null) {
314                 model.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
315             }
316
317             addRelatedModel(service, model);
318             if (model instanceof Resource) {
319                 nodesById.put(model.getModelNameVersionId(), nodeTypeName);
320             }
321         }
322     }
323
324     /**
325      * @param model
326      * @param relation
327      */
328     private void addRelatedModel(final Model model, final Model relation) {
329         if (relation instanceof Resource) {
330             model.addResource((Resource) relation);
331         } else {
332             model.addWidget((Widget) relation);
333         }
334     }
335
336     /**
337      * Process TOSCA Group information for VF Modules.
338      *
339      * @param resources
340      * @param model
341      * @param serviceNode
342      */
343     private void processVfModules(List<Resource> resources, Model resourceModel, NodeTemplate serviceNode) {
344         // Get the customisation UUID for each VF node and use it to get its Groups
345         String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNode);
346         List<Group> serviceGroups = csarHelper.getVfModulesByVf(uuid);
347
348         // Process each VF Group
349         for (Group serviceGroup : serviceGroups) {
350             Model groupModel = Model.getModelFor(serviceGroup.getType());
351             if (groupModel instanceof VfModule) {
352                 processVfModule(resources, resourceModel, serviceGroup, serviceNode, (VfModule) groupModel);
353             }
354         }
355     }
356
357     private void processVfModule(List<Resource> resources, Model model, Group groupDefinition, NodeTemplate serviceNode,
358             VfModule groupModel) {
359         // Populate group with metadata properties
360         groupModel.populateModelIdentificationInformation(groupDefinition.getMetadata().getAllProperties());
361         // Populate group with non-metadata properties
362         Map<String, Property> groupProperties = groupDefinition.getProperties();
363         Map<String, String> properties = populateStringProperties(groupProperties);
364         groupModel.populateModelIdentificationInformation(properties);
365         processVfModuleGroup(resources, model, groupDefinition, serviceNode, groupModel);
366     }
367
368     private void processVfModuleGroup(List<Resource> resources, Model model, Group groupDefinition,
369             NodeTemplate serviceNode, VfModule groupModel) {
370         // Get names of the members of the service group
371         List<NodeTemplate> members = csarHelper.getMembersOfVfModule(serviceNode, groupDefinition);
372         if (members != null && !members.isEmpty()) {
373             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
374             groupModel.setMembers(memberNames);
375             for (NodeTemplate member : members) {
376                 processGroupMembers(groupModel, member);
377             }
378         }
379
380         model.addResource(groupModel); // Added group (VfModule) to the (VF) model
381         // Check if we have already encountered the same VfModule across all the artifacts
382         if (!resources.contains(groupModel)) {
383             resources.add(groupModel);
384         }
385     }
386
387     private void processGroupMembers(Model group, NodeTemplate member) {
388         Model resourceNode;
389         // L3-network inside vf-module to be generated as Widget a special handling.
390         if (member.getType().contains("org.openecomp.resource.vl")) {
391             resourceNode = new L3NetworkWidget();
392         } else {
393             resourceNode = Model.getModelFor(member.getType());
394         }
395         if (resourceNode != null && !(resourceNode instanceof Resource)) {
396             Widget widget = (Widget) resourceNode;
397             widget.addKey(member.getName());
398             // Add the widget element encountered to the Group model
399             group.addWidget(widget);
400         }
401     }
402
403     private String normaliseNodeTypeName(NodeTemplate nodeType) {
404         String nodeTypeName = nodeType.getType();
405         Metadata metadata = nodeType.getMetaData();
406         if (metadata != null && hasAllottedResource(metadata.getAllProperties())) {
407             if (nodeType.getType().contains("org.openecomp.resource.vf.")) {
408                 nodeTypeName = "org.openecomp.resource.vf.allottedResource";
409             }
410             if (nodeType.getType().contains("org.openecomp.resource.vfc.")) {
411                 nodeTypeName = "org.openecomp.resource.vfc.AllottedResource";
412             }
413         }
414         return nodeTypeName;
415     }
416
417     private boolean hasAllottedResource(Map<String, String> metadata) {
418         return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
419     }
420
421     private boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
422         return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
423     }
424
425     /**
426      * Create a Map of property name against String property value from the input Map
427      *
428      * @param inputMap The input Map
429      * @return Map of property name against String property value
430      */
431     private Map<String, String> populateStringProperties(Map<String, Property> inputMap) {
432         return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
433                 e -> e.getValue().getValue() == null ? "" : e.getValue().getValue().toString()));
434     }
435
436     private void processResourceModels(Map<String, String> idTypeStore, Model resourceModel,
437             List<NodeTemplate> resourceNodes) {
438         boolean foundProvidingService = false;
439
440         for (NodeTemplate resourceNodeTemplate : resourceNodes) {
441             String nodeTypeName = normaliseNodeTypeName(resourceNodeTemplate);
442             Metadata metaData = resourceNodeTemplate.getMetaData();
443             String metaDataType = Optional.ofNullable(metaData).map(m -> m.getValue("type")).orElse(nodeTypeName);
444             Model resourceNode = Model.getModelFor(nodeTypeName, metaDataType);
445             foundProvidingService |= processModel(idTypeStore, resourceModel, resourceNodeTemplate, nodeTypeName,
446                     metaData, resourceNode);
447         }
448
449         if (resourceModel instanceof AllotedResource && !foundProvidingService) {
450             throw new IllegalArgumentException(
451                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING, resourceModel.getModelId()));
452         }
453     }
454
455     private boolean processModel(Map<String, String> idTypeStore, Model resourceModel,
456             NodeTemplate resourceNodeTemplate, String nodeTypeName, Metadata metaData, Model resourceNode) {
457         boolean foundProvidingService = false;
458         if (resourceNode instanceof ProvidingService) {
459             foundProvidingService = true;
460             processProvidingService(resourceModel, resourceNodeTemplate, resourceNode);
461         } else if (resourceNode instanceof Resource && !(resourceNode.getWidgetType().equals(Widget.Type.L3_NET))) {
462             if (metaData != null) {
463                 resourceNode.populateModelIdentificationInformation(metaData.getAllProperties());
464             }
465             idTypeStore.put(resourceNode.getModelNameVersionId(), nodeTypeName);
466             resourceModel.addResource((Resource) resourceNode);
467         }
468         return foundProvidingService;
469     }
470
471     private void processProvidingService(Model resourceModel, NodeTemplate resourceNodeTemplate, Model resourceNode) {
472         Map<String, Property> nodeProperties = resourceNodeTemplate.getProperties();
473         if (nodeProperties.get("providing_service_uuid") == null
474                 || nodeProperties.get("providing_service_invariant_uuid") == null) {
475             throw new IllegalArgumentException(
476                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING, resourceModel.getModelId()));
477         }
478         Map<String, String> properties = populateStringProperties(nodeProperties);
479         properties.put(VERSION, "1.0");
480         resourceNode.populateModelIdentificationInformation(properties);
481         resourceModel.addResource((Resource) resourceNode);
482     }
483
484 }