Fix outstanding Sonar issues
[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_TOSCA_MAPPING_FILE = "tosca.mappings.config";
63
64     public static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND =
65             "Cannot generate artifacts. System property %s not configured";
66
67     private static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND =
68             "Cannot generate artifacts. Artifact Generator Configuration file not found at %s";
69     private static final String GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING =
70             "Cannot generate artifacts. Providing Service Metadata is missing for allotted resource %s";
71     private static final String GENERATOR_AAI_PROVIDING_SERVICE_MISSING =
72             "Cannot generate artifacts. Providing Service is missing for allotted resource %s";
73
74     // Metadata properties
75     private static final String CATEGORY = "category";
76     private static final String ALLOTTED_RESOURCE = "Allotted Resource";
77     private static final String SUBCATEGORY = "subcategory";
78     private static final String TUNNEL_XCONNECT = "Tunnel XConnect";
79
80     private static final String VERSION = "version";
81
82     private ISdcCsarHelper csarHelper;
83
84     /**
85      * Constructs using csarHelper
86      *
87      * @param csarHelper
88      *     The csar helper
89      */
90     public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
91         this.csarHelper = csarHelper;
92     }
93
94     /**
95      * Get or create the artifact description.
96      *
97      * @param model
98      *     the artifact model
99      * @return the artifact model's description
100      */
101     public static String getArtifactDescription(Model model) {
102         switch (model.getModelType()) {
103             case SERVICE:
104                 return "AAI Service Model";
105             case RESOURCE:
106                 return "AAI Resource Model";
107             default:
108                 return model.getModelDescription();
109         }
110     }
111
112     /**
113      * Initialises the widget configuration.
114      *
115      * @throws IOException
116      */
117     public static void initWidgetConfiguration() throws IOException {
118         log.debug("Getting Widget Configuration");
119         String configLocation = System.getProperty(PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE);
120         if (configLocation != null) {
121             File file = new File(configLocation);
122             if (file.exists()) {
123                 Properties properties = new Properties();
124                 properties.load(new FileInputStream(file));
125                 WidgetConfigurationUtil.setConfig(properties);
126             } else {
127                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
128             }
129         } else {
130             throw new IllegalArgumentException(
131                     String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE));
132         }
133     }
134
135     /**
136      * Initialises the group filtering and TOSCA mapping configuration.
137      * 
138      * @param configLocation
139      *     the pathname to the JSON config file
140      * @throws FileNotFoundException
141      *     if the file cannot be opened for reading
142      */
143     public static void initToscaMappingsConfiguration(String configLocation) throws FileNotFoundException {
144         log.debug("Getting TOSCA Mappings Configuration");
145         File file = new File(configLocation);
146         if (!file.exists()) {
147             throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
148         }
149
150         BufferedReader bufferedReader = new BufferedReader(new FileReader(configLocation));
151         GroupConfiguration config = new Gson().fromJson(bufferedReader, GroupConfiguration.class);
152         if (config != null) {
153             WidgetConfigurationUtil.setSupportedInstanceGroups(config.getInstanceGroupTypes());
154             WidgetConfigurationUtil.setWidgetMappings(config.getWidgetMappings());
155         }
156     }
157
158     /**
159      * Process groups for this service node, according to the defined filter.
160      *
161      * @param resourceModel
162      * @param serviceNodeTemplate
163      * @return resources for which XML Models should be generated
164      */
165     public List<Resource> processInstanceGroups(Model resourceModel, NodeTemplate serviceNodeTemplate) {
166         List<Resource> resources = new ArrayList<>();
167         if (serviceNodeTemplate.getSubMappingToscaTemplate() != null) {
168             List<Group> serviceGroups = csarHelper.getGroupsOfOriginOfNodeTemplate(serviceNodeTemplate);
169             for (Group group : serviceGroups) {
170                 if (WidgetConfigurationUtil.isSupportedInstanceGroup(group.getType())) {
171                     resources.addAll(processInstanceGroup(resourceModel, group.getMemberNodes(),
172                             group.getMetadata().getAllProperties(), group.getProperties()));
173                 }
174             }
175         }
176         return resources;
177     }
178
179     /**
180      * Merge a Map of String values with a Map of TOSCA Property Objects to create a combined Map. If there are
181      * duplicate keys then the TOSCA Property value takes precedence.
182      *
183      * @param stringProps
184      *     initial Map of String property values (e.g. from the TOSCA YAML metadata section)
185      * @param toscaProps
186      *     Map of TOSCA Property Type Object values to merge in (or overwrite)
187      * @return a Map of the property values converted to String
188      */
189     public Map<String, String> mergeProperties(Map<String, String> stringProps, Map<String, Property> toscaProps) {
190         Map<String, String> props = new HashMap<>(stringProps);
191         toscaProps.forEach((key, toscaProp) -> props.put(key,
192                 toscaProp.getValue() == null ? "" : toscaProp.getValue().toString()));
193         return props;
194     }
195
196     public Resource createInstanceGroupModel(Map<String, String> properties) {
197         Resource groupModel = new Resource(Type.INSTANCE_GROUP, true);
198         groupModel.populateModelIdentificationInformation(properties);
199         return groupModel;
200     }
201
202     /**
203      * @param model
204      * @param relation
205      */
206     public void addRelatedModel(final Model model, final Resource relation) {
207         if (relation.isResource()) {
208             model.addResource(relation);
209         } else {
210             model.addWidget(Widget.getWidget(relation.getWidgetType()));
211         }
212     }
213
214     public boolean hasAllottedResource(Map<String, String> metadata) {
215         return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
216     }
217
218     public boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
219         return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
220     }
221
222     /**
223      * Process TOSCA Group information for VF Modules.
224      *
225      * @param resources
226      * @param model
227      * @param serviceNode
228      */
229     public void processVfModules(List<Resource> resources, Model resourceModel, NodeTemplate serviceNode) {
230         // Get the customisation UUID for each VF node and use it to get its Groups
231         String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNode);
232         List<Group> serviceGroups = csarHelper.getVfModulesByVf(uuid);
233
234         // Process each VF Group
235         for (Group serviceGroup : serviceGroups) {
236             Model groupModel = Model.getModelFor(serviceGroup.getType());
237             if (groupModel.getWidgetType() == Type.VFMODULE) {
238                 processVfModule(resources, resourceModel, serviceGroup, serviceNode, (Resource) groupModel);
239             }
240         }
241     }
242
243     /**
244      * @param resourceModel
245      * @param resourceNodeTemplates
246      */
247     public void processResourceModels(Model resourceModel, List<NodeTemplate> resourceNodeTemplates) {
248         boolean foundProvidingService = false;
249
250         for (NodeTemplate resourceNodeTemplate : resourceNodeTemplates) {
251             String nodeTypeName = resourceNodeTemplate.getType();
252             Metadata metadata = resourceNodeTemplate.getMetaData();
253             String metaDataType = Optional.ofNullable(metadata).map(m -> m.getValue("type")).orElse(nodeTypeName);
254             Resource model = Model.getModelFor(nodeTypeName, metaDataType);
255
256             if (metadata != null && hasAllottedResource(metadata.getAllProperties())
257                     && model.getWidgetType() == Type.VSERVER) {
258                 model = new Resource(Type.ALLOTTED_RESOURCE, false);
259                 Map<String, Object> props = new HashMap<>();
260                 props.put("providingService", true);
261                 model.setProperties(props);
262             }
263
264             foundProvidingService |= processModel(resourceModel, metadata, model, resourceNodeTemplate.getProperties());
265         }
266
267         if (resourceModel.getWidgetType() == Type.ALLOTTED_RESOURCE && !foundProvidingService) {
268             final String modelInvariantId = resourceModel.getModelId();
269             throw new IllegalArgumentException(String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING,
270                     modelInvariantId == null ? "<null ID>" : modelInvariantId));
271         }
272     }
273
274     /**
275      * Create an Instance Group Model and populate it with the supplied data.
276      *
277      * @param resourceModel
278      *     the Resource node template Model
279      * @param memberNodes
280      *     the Resources and Widgets belonging to the Group
281      * @param metaProperties
282      *     the metadata of the Group
283      * @param properties
284      *     the properties of the Group
285      * @return the Instance Group and Member resource models
286      */
287     private List<Resource> processInstanceGroup(Model resourceModel, ArrayList<NodeTemplate> memberNodes,
288             Map<String, String> metaProperties, Map<String, Property> properties) {
289         Resource groupModel = createInstanceGroupModel(mergeProperties(metaProperties, properties));
290         resourceModel.addResource(groupModel);
291         List<Resource> resources = Stream.of(groupModel).collect(Collectors.toList());
292
293         if (memberNodes != null && !memberNodes.isEmpty()) {
294             resources.addAll(generateResourcesAndWidgets(memberNodes, groupModel));
295         }
296
297         return resources;
298     }
299
300     /**
301      * @param memberNodes
302      * @param groupModel
303      * @return
304      */
305     private List<Resource> generateResourcesAndWidgets(final ArrayList<NodeTemplate> memberNodes,
306             final Resource groupModel) {
307         log.debug(String.format("Processing member nodes for Group %s (invariant UUID %s)", //
308                 groupModel.getModelName(), groupModel.getModelId()));
309
310         List<Resource> resources = new ArrayList<>();
311
312         for (NodeTemplate nodeTemplate : memberNodes) {
313             String nodeTypeName = nodeTemplate.getType();
314             final String metadataType = nodeTemplate.getMetaData().getValue("type");
315
316             log.debug(String.format("Get model for %s (metadata type %s)", nodeTypeName, metadataType));
317             Resource memberModel = Model.getModelFor(nodeTypeName, metadataType);
318
319             if (memberModel != null) {
320                 memberModel.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
321
322                 log.debug(String.format("Generating grouped %s (%s) from TOSCA type %s",
323                         memberModel.getClass().getSuperclass().getSimpleName(), memberModel.getClass(), nodeTypeName));
324
325                 addRelatedModel(groupModel, memberModel);
326                 if (memberModel.isResource()) {
327                     resources.add(memberModel);
328                 }
329             }
330         }
331         return resources;
332     }
333
334     private void processVfModule(List<Resource> resources, Model vfModel, Group groupDefinition,
335             NodeTemplate serviceNode, Resource groupModel) {
336         groupModel.populateModelIdentificationInformation(
337                 mergeProperties(groupDefinition.getMetadata().getAllProperties(), groupDefinition.getProperties()));
338
339         processVfModuleGroup(groupModel, csarHelper.getMembersOfVfModule(serviceNode, groupDefinition));
340
341         vfModel.addResource(groupModel); // Add group (VfModule) to the (VF) model
342         // Check if we have already encountered the same VfModule across all the artifacts
343         if (!resources.contains(groupModel)) {
344             resources.add(groupModel);
345         }
346     }
347
348     private void processVfModuleGroup(Resource groupModel, List<NodeTemplate> members) {
349         if (members != null && !members.isEmpty()) {
350             // Get names of the members of the service group
351             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
352             groupModel.setMembers(memberNames);
353             for (NodeTemplate member : members) {
354                 processGroupMembers(groupModel, member);
355             }
356         }
357     }
358
359     /**
360      * Process the Widget members of a VF Module Group
361      * 
362      * @param group
363      * @param member
364      */
365     private void processGroupMembers(Resource group, NodeTemplate member) {
366         Resource resource = Model.getModelFor(member.getType());
367
368         log.debug(member.getType() + " mapped to " + resource);
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 }