Replace Resource sub-classes with configuration
[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-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2019 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 com.google.gson.Gson;
25 import java.io.BufferedReader;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Optional;
36 import java.util.Properties;
37 import java.util.stream.Collectors;
38 import java.util.stream.Stream;
39 import org.onap.aai.babel.logging.LogHelper;
40 import org.onap.aai.babel.xml.generator.data.GroupConfiguration;
41 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
42 import org.onap.aai.babel.xml.generator.model.Model;
43 import org.onap.aai.babel.xml.generator.model.Resource;
44 import org.onap.aai.babel.xml.generator.model.Widget;
45 import org.onap.aai.babel.xml.generator.model.Widget.Type;
46 import org.onap.aai.cl.api.Logger;
47 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
48 import org.onap.sdc.toscaparser.api.Group;
49 import org.onap.sdc.toscaparser.api.NodeTemplate;
50 import org.onap.sdc.toscaparser.api.Property;
51 import org.onap.sdc.toscaparser.api.elements.Metadata;
52
53 /**
54  * Wrapper for the sdc-tosca parser
55  *
56  */
57 public class ArtifactGeneratorToscaParser {
58
59     private static Logger log = LogHelper.INSTANCE;
60
61     public static final String PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE = "artifactgenerator.config";
62     public static final String PROPERTY_GROUP_FILTERS_CONFIG_FILE = "groupfilter.config";
63
64     private static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND =
65             "Cannot generate artifacts. Artifact Generator Configuration file not found at %s";
66     private static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND =
67             "Cannot generate artifacts. System property %s not configured";
68     private static final String GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING =
69             "Cannot generate artifacts. Providing Service Metadata is missing for allotted resource %s";
70     private static final String GENERATOR_AAI_PROVIDING_SERVICE_MISSING =
71             "Cannot generate artifacts. Providing Service is missing for allotted resource %s";
72
73     // Metadata properties
74     private static final String CATEGORY = "category";
75     private static final String ALLOTTED_RESOURCE = "Allotted Resource";
76     private static final String SUBCATEGORY = "subcategory";
77     private static final String TUNNEL_XCONNECT = "Tunnel XConnect";
78
79     private static final String VERSION = "version";
80
81     private ISdcCsarHelper csarHelper;
82
83     /**
84      * Constructs using csarHelper
85      *
86      * @param csarHelper
87      *     The csar helper
88      */
89     public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
90         this.csarHelper = csarHelper;
91     }
92
93     /**
94      * Get or create the artifact description.
95      *
96      * @param model
97      *     the artifact model
98      * @return the artifact model's description
99      */
100     public static String getArtifactDescription(Model model) {
101         switch (model.getModelType()) {
102             case SERVICE:
103                 return "AAI Service Model";
104             case RESOURCE:
105                 return "AAI Resource Model";
106             default:
107                 return model.getModelDescription();
108         }
109     }
110
111     /**
112      * Initialises the widget configuration.
113      *
114      * @throws IOException
115      */
116     public static void initWidgetConfiguration() throws IOException {
117         log.debug("Getting Widget Configuration");
118         String configLocation = System.getProperty(PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE);
119         if (configLocation != null) {
120             File file = new File(configLocation);
121             if (file.exists()) {
122                 Properties properties = new Properties();
123                 properties.load(new FileInputStream(file));
124                 WidgetConfigurationUtil.setConfig(properties);
125             } else {
126                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
127             }
128         } else {
129             throw new IllegalArgumentException(
130                     String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE));
131         }
132     }
133
134     /**
135      * Initialises the group filtering and mapping configuration.
136      * 
137      * @throws FileNotFoundException
138      *
139      */
140     public static void initGroupFilterConfiguration() throws FileNotFoundException {
141         log.debug("Getting Filter Types Configuration");
142         String configLocation = System.getProperty(PROPERTY_GROUP_FILTERS_CONFIG_FILE);
143         if (configLocation == null) {
144             throw new IllegalArgumentException(
145                     String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_GROUP_FILTERS_CONFIG_FILE));
146         }
147
148         File file = new File(configLocation);
149         if (!file.exists()) {
150             throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
151         }
152
153         BufferedReader bufferedReader = new BufferedReader(new FileReader(configLocation));
154         GroupConfiguration config = new Gson().fromJson(bufferedReader, GroupConfiguration.class);
155         WidgetConfigurationUtil.setSupportedInstanceGroups(config.getInstanceGroupTypes());
156         WidgetConfigurationUtil.setWidgetMappings(config.getWidgetMappings());
157     }
158
159     /**
160      * Process groups for this service node, according to the defined filter.
161      *
162      * @param resourceModel
163      * @param serviceNodeTemplate
164      * @return resources for which XML Models should be generated
165      */
166     public List<Resource> processInstanceGroups(Model resourceModel, NodeTemplate serviceNodeTemplate) {
167         List<Resource> resources = new ArrayList<>();
168         if (serviceNodeTemplate.getSubMappingToscaTemplate() != null) {
169             List<Group> serviceGroups = csarHelper.getGroupsOfOriginOfNodeTemplate(serviceNodeTemplate);
170             for (Group group : serviceGroups) {
171                 if (WidgetConfigurationUtil.isSupportedInstanceGroup(group.getType())) {
172                     resources.addAll(processInstanceGroup(resourceModel, group.getMemberNodes(),
173                             group.getMetadata().getAllProperties(), group.getProperties()));
174                 }
175             }
176         }
177         return resources;
178     }
179
180     /**
181      * Merge a Map of String values with a Map of TOSCA Property Objects to create a combined Map. If there are
182      * duplicate keys then the TOSCA Property value takes precedence.
183      *
184      * @param stringProps
185      *     initial Map of String property values (e.g. from the TOSCA YAML metadata section)
186      * @param toscaProps
187      *     Map of TOSCA Property Type Object values to merge in (or overwrite)
188      * @return a Map of the property values converted to String
189      */
190     public Map<String, String> mergeProperties(Map<String, String> stringProps, Map<String, Property> toscaProps) {
191         Map<String, String> props = new HashMap<>(stringProps);
192         toscaProps.forEach((key, toscaProp) -> props.put(key,
193                 toscaProp.getValue() == null ? "" : toscaProp.getValue().toString()));
194         return props;
195     }
196
197     public Resource createInstanceGroupModel(Map<String, String> properties) {
198         Resource groupModel = new Resource(Type.INSTANCE_GROUP, true);
199         groupModel.populateModelIdentificationInformation(properties);
200         return groupModel;
201     }
202
203     /**
204      * @param model
205      * @param relation
206      */
207     public void addRelatedModel(final Model model, final Resource relation) {
208         if (relation.isResource()) {
209             model.addResource(relation);
210         } else {
211             model.addWidget(Widget.getWidget(relation.getWidgetType()));
212         }
213     }
214
215     public boolean hasAllottedResource(Map<String, String> metadata) {
216         return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
217     }
218
219     public boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
220         return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
221     }
222
223     /**
224      * Process TOSCA Group information for VF Modules.
225      *
226      * @param resources
227      * @param model
228      * @param serviceNode
229      */
230     public void processVfModules(List<Resource> resources, Model resourceModel, NodeTemplate serviceNode) {
231         // Get the customisation UUID for each VF node and use it to get its Groups
232         String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNode);
233         List<Group> serviceGroups = csarHelper.getVfModulesByVf(uuid);
234
235         // Process each VF Group
236         for (Group serviceGroup : serviceGroups) {
237             Model groupModel = Model.getModelFor(serviceGroup.getType());
238             if (groupModel.getWidgetType() == Type.VFMODULE) {
239                 processVfModule(resources, resourceModel, serviceGroup, serviceNode, (Resource) groupModel);
240             }
241         }
242     }
243
244     /**
245      * @param resourceModel
246      * @param resourceNodeTemplates
247      */
248     public void processResourceModels(Model resourceModel, List<NodeTemplate> resourceNodeTemplates) {
249         boolean foundProvidingService = false;
250
251         for (NodeTemplate resourceNodeTemplate : resourceNodeTemplates) {
252             String nodeTypeName = resourceNodeTemplate.getType();
253             Metadata metadata = resourceNodeTemplate.getMetaData();
254             String metaDataType = Optional.ofNullable(metadata).map(m -> m.getValue("type")).orElse(nodeTypeName);
255             Resource model = Model.getModelFor(nodeTypeName, metaDataType);
256
257             if (metadata != null && hasAllottedResource(metadata.getAllProperties())) {
258                 if (model.getWidgetType() == Type.VSERVER) {
259                     model = new Resource(Type.ALLOTTED_RESOURCE, false);
260                     Map<String, Object> props = new HashMap<>();
261                     props.put("providingService", true);
262                     model.setProperties(props);
263                 }
264             }
265
266             foundProvidingService |= processModel(resourceModel, metadata, model, resourceNodeTemplate.getProperties());
267         }
268
269         if (resourceModel.getWidgetType() == Type.ALLOTTED_RESOURCE && !foundProvidingService) {
270             final String modelInvariantId = resourceModel.getModelId();
271             throw new IllegalArgumentException(String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING,
272                     modelInvariantId == null ? "<null ID>" : modelInvariantId));
273         }
274     }
275
276     /**
277      * Create an Instance Group Model and populate it with the supplied data.
278      *
279      * @param resourceModel
280      *     the Resource node template Model
281      * @param memberNodes
282      *     the Resources and Widgets belonging to the Group
283      * @param metaProperties
284      *     the metadata of the Group
285      * @param properties
286      *     the properties of the Group
287      * @return the Instance Group and Member resource models
288      */
289     private List<Resource> processInstanceGroup(Model resourceModel, ArrayList<NodeTemplate> memberNodes,
290             Map<String, String> metaProperties, Map<String, Property> properties) {
291         Resource groupModel = createInstanceGroupModel(mergeProperties(metaProperties, properties));
292         resourceModel.addResource(groupModel);
293         List<Resource> resources = Stream.of(groupModel).collect(Collectors.toList());
294
295         if (memberNodes != null && !memberNodes.isEmpty()) {
296             resources.addAll(generateResourcesAndWidgets(memberNodes, groupModel));
297         }
298
299         return resources;
300     }
301
302     /**
303      * @param memberNodes
304      * @param groupModel
305      * @return
306      */
307     private List<Resource> generateResourcesAndWidgets(final ArrayList<NodeTemplate> memberNodes,
308             final Resource groupModel) {
309         log.debug(String.format("Processing member nodes for Group %s (invariant UUID %s)", //
310                 groupModel.getModelName(), groupModel.getModelId()));
311
312         List<Resource> resources = new ArrayList<>();
313
314         for (NodeTemplate nodeTemplate : memberNodes) {
315             String nodeTypeName = nodeTemplate.getType();
316             final String metadataType = nodeTemplate.getMetaData().getValue("type");
317
318             log.debug(String.format("Get model for %s (metadata type %s)", nodeTypeName, metadataType));
319             Resource memberModel = Model.getModelFor(nodeTypeName, metadataType);
320
321             if (memberModel != null) {
322                 memberModel.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
323
324                 log.debug(String.format("Generating grouped %s (%s) from TOSCA type %s",
325                         memberModel.getClass().getSuperclass().getSimpleName(), memberModel.getClass(), nodeTypeName));
326
327                 addRelatedModel(groupModel, memberModel);
328                 if (memberModel.isResource()) {
329                     resources.add(memberModel);
330                 }
331             }
332         }
333         return resources;
334     }
335
336     private void processVfModule(List<Resource> resources, Model vfModel, Group groupDefinition,
337             NodeTemplate serviceNode, Resource groupModel) {
338         groupModel.populateModelIdentificationInformation(
339                 mergeProperties(groupDefinition.getMetadata().getAllProperties(), groupDefinition.getProperties()));
340
341         processVfModuleGroup(groupModel, csarHelper.getMembersOfVfModule(serviceNode, groupDefinition));
342
343         vfModel.addResource(groupModel); // Add group (VfModule) to the (VF) model
344         // Check if we have already encountered the same VfModule across all the artifacts
345         if (!resources.contains(groupModel)) {
346             resources.add(groupModel);
347         }
348     }
349
350     private void processVfModuleGroup(Resource groupModel, List<NodeTemplate> members) {
351         if (members != null && !members.isEmpty()) {
352             // Get names of the members of the service group
353             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
354             groupModel.setMembers(memberNames);
355             for (NodeTemplate member : members) {
356                 processGroupMembers(groupModel, member);
357             }
358         }
359     }
360
361     /**
362      * Process the Widget members of a VF Module Group
363      * 
364      * @param group
365      * @param member
366      */
367     private void processGroupMembers(Resource group, NodeTemplate member) {
368         Resource resource = Model.getModelFor(member.getType());
369
370         if (resource.getWidgetType() == Type.L3_NET) {
371             // An l3-network inside a vf-module is treated as a Widget
372             resource.setIsResource(false);
373         }
374
375         if (!resource.isResource()) {
376             Widget widget = Widget.getWidget(resource.getWidgetType());
377             widget.addKey(member.getName());
378             // Add the widget element encountered to the Group model
379             group.addWidget(widget);
380         }
381     }
382
383     /**
384      * Create a Map of property name against String property value from the input Map
385      *
386      * @param inputMap
387      *     The input Map
388      * @return Map of property name against String property value
389      */
390     private Map<String, String> populateStringProperties(Map<String, Property> inputMap) {
391         return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
392                 e -> e.getValue().getValue() == null ? "" : e.getValue().getValue().toString()));
393     }
394
395     /**
396      * If the specified resourceNode is a type of Resource, add it to the specified resourceModel. If the Resource type
397      * is ProvidingService then return true, otherwise return false.
398      *
399      * @param resourceModel
400      *     parent Resource
401      * @param metaData
402      *     for populating the Resource IDs
403      * @param resourceNode
404      *     any Model (will be ignored if not a Resource)
405      * @param nodeProperties
406      *     the node properties
407      * @return whether or not a ProvidingService was processed
408      */
409     private boolean processModel(Model resourceModel, Metadata metaData, Resource resourceNode,
410             Map<String, Property> nodeProperties) {
411         boolean foundProvidingService = resourceNode != null
412                 && (boolean) Optional.ofNullable(resourceNode.getProperties().get("providingService")).orElse(false);
413
414         if (foundProvidingService) {
415             processProvidingService(resourceModel, resourceNode, nodeProperties);
416         } else if (resourceNode != null && resourceNode.isResource()
417                 && resourceNode.getWidgetType() != Widget.Type.L3_NET) {
418             if (metaData != null) {
419                 resourceNode.populateModelIdentificationInformation(metaData.getAllProperties());
420             }
421             resourceModel.addResource((Resource) resourceNode);
422         }
423         return foundProvidingService;
424     }
425
426     private void processProvidingService(Model resourceModel, Resource resourceNode,
427             Map<String, Property> nodeProperties) {
428         if (nodeProperties == null || nodeProperties.get("providing_service_uuid") == null
429                 || nodeProperties.get("providing_service_invariant_uuid") == null) {
430             throw new IllegalArgumentException(
431                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING, resourceModel.getModelId()));
432         }
433         Map<String, String> properties = populateStringProperties(nodeProperties);
434         properties.put(VERSION, "1.0");
435         resourceNode.populateModelIdentificationInformation(properties);
436         resourceModel.addResource(resourceNode);
437     }
438 }