Rename the groupfilter.config System Property
[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                 if (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
265             foundProvidingService |= processModel(resourceModel, metadata, model, resourceNodeTemplate.getProperties());
266         }
267
268         if (resourceModel.getWidgetType() == Type.ALLOTTED_RESOURCE && !foundProvidingService) {
269             final String modelInvariantId = resourceModel.getModelId();
270             throw new IllegalArgumentException(String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING,
271                     modelInvariantId == null ? "<null ID>" : modelInvariantId));
272         }
273     }
274
275     /**
276      * Create an Instance Group Model and populate it with the supplied data.
277      *
278      * @param resourceModel
279      *            the Resource node template Model
280      * @param memberNodes
281      *            the Resources and Widgets belonging to the Group
282      * @param metaProperties
283      *            the metadata of the Group
284      * @param properties
285      *            the properties of the Group
286      * @return the Instance Group and Member resource models
287      */
288     private List<Resource> processInstanceGroup(Model resourceModel, ArrayList<NodeTemplate> memberNodes,
289             Map<String, String> metaProperties, Map<String, Property> properties) {
290         Resource groupModel = createInstanceGroupModel(mergeProperties(metaProperties, properties));
291         resourceModel.addResource(groupModel);
292         List<Resource> resources = Stream.of(groupModel).collect(Collectors.toList());
293
294         if (memberNodes != null && !memberNodes.isEmpty()) {
295             resources.addAll(generateResourcesAndWidgets(memberNodes, groupModel));
296         }
297
298         return resources;
299     }
300
301     /**
302      * @param memberNodes
303      * @param groupModel
304      * @return
305      */
306     private List<Resource> generateResourcesAndWidgets(final ArrayList<NodeTemplate> memberNodes,
307             final Resource groupModel) {
308         log.debug(String.format("Processing member nodes for Group %s (invariant UUID %s)", //
309                 groupModel.getModelName(), groupModel.getModelId()));
310
311         List<Resource> resources = new ArrayList<>();
312
313         for (NodeTemplate nodeTemplate : memberNodes) {
314             String nodeTypeName = nodeTemplate.getType();
315             final String metadataType = nodeTemplate.getMetaData().getValue("type");
316
317             log.debug(String.format("Get model for %s (metadata type %s)", nodeTypeName, metadataType));
318             Resource memberModel = Model.getModelFor(nodeTypeName, metadataType);
319
320             if (memberModel != null) {
321                 memberModel.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
322
323                 log.debug(String.format("Generating grouped %s (%s) from TOSCA type %s",
324                         memberModel.getClass().getSuperclass().getSimpleName(), memberModel.getClass(), nodeTypeName));
325
326                 addRelatedModel(groupModel, memberModel);
327                 if (memberModel.isResource()) {
328                     resources.add(memberModel);
329                 }
330             }
331         }
332         return resources;
333     }
334
335     private void processVfModule(List<Resource> resources, Model vfModel, Group groupDefinition,
336             NodeTemplate serviceNode, Resource groupModel) {
337         groupModel.populateModelIdentificationInformation(
338                 mergeProperties(groupDefinition.getMetadata().getAllProperties(), groupDefinition.getProperties()));
339
340         processVfModuleGroup(groupModel, csarHelper.getMembersOfVfModule(serviceNode, groupDefinition));
341
342         vfModel.addResource(groupModel); // Add group (VfModule) to the (VF) model
343         // Check if we have already encountered the same VfModule across all the artifacts
344         if (!resources.contains(groupModel)) {
345             resources.add(groupModel);
346         }
347     }
348
349     private void processVfModuleGroup(Resource groupModel, List<NodeTemplate> members) {
350         if (members != null && !members.isEmpty()) {
351             // Get names of the members of the service group
352             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
353             groupModel.setMembers(memberNames);
354             for (NodeTemplate member : members) {
355                 processGroupMembers(groupModel, member);
356             }
357         }
358     }
359
360     /**
361      * Process the Widget members of a VF Module Group
362      * 
363      * @param group
364      * @param member
365      */
366     private void processGroupMembers(Resource group, NodeTemplate member) {
367         Resource resource = Model.getModelFor(member.getType());
368
369         log.debug(member.getType() + " mapped to " + resource);
370
371         if (resource.getWidgetType() == Type.L3_NET) {
372             // An l3-network inside a vf-module is treated as a Widget
373             resource.setIsResource(false);
374         }
375
376         if (!resource.isResource()) {
377             Widget widget = Widget.getWidget(resource.getWidgetType());
378             widget.addKey(member.getName());
379             // Add the widget element encountered to the Group model
380             group.addWidget(widget);
381         }
382     }
383
384     /**
385      * Create a Map of property name against String property value from the input Map
386      *
387      * @param inputMap
388      *            The input Map
389      * @return Map of property name against String property value
390      */
391     private Map<String, String> populateStringProperties(Map<String, Property> inputMap) {
392         return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
393                 e -> e.getValue().getValue() == null ? "" : e.getValue().getValue().toString()));
394     }
395
396     /**
397      * If the specified resourceNode is a type of Resource, add it to the specified resourceModel. If the Resource type
398      * is ProvidingService then return true, otherwise return false.
399      *
400      * @param resourceModel
401      *            parent Resource
402      * @param metaData
403      *            for populating the Resource IDs
404      * @param resourceNode
405      *            any Model (will be ignored if not a Resource)
406      * @param nodeProperties
407      *            the node properties
408      * @return whether or not a ProvidingService was processed
409      */
410     private boolean processModel(Model resourceModel, Metadata metaData, Resource resourceNode,
411             Map<String, Property> nodeProperties) {
412         boolean foundProvidingService = resourceNode != null
413                 && (boolean) Optional.ofNullable(resourceNode.getProperties().get("providingService")).orElse(false);
414
415         if (foundProvidingService) {
416             processProvidingService(resourceModel, resourceNode, nodeProperties);
417         } else if (resourceNode != null && resourceNode.isResource()
418                 && resourceNode.getWidgetType() != Widget.Type.L3_NET) {
419             if (metaData != null) {
420                 resourceNode.populateModelIdentificationInformation(metaData.getAllProperties());
421             }
422             resourceModel.addResource((Resource) resourceNode);
423         }
424         return foundProvidingService;
425     }
426
427     private void processProvidingService(Model resourceModel, Resource resourceNode,
428             Map<String, Property> nodeProperties) {
429         if (nodeProperties == null || nodeProperties.get("providing_service_uuid") == null
430                 || nodeProperties.get("providing_service_invariant_uuid") == null) {
431             throw new IllegalArgumentException(
432                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING, resourceModel.getModelId()));
433         }
434         Map<String, String> properties = populateStringProperties(nodeProperties);
435         properties.put(VERSION, "1.0");
436         resourceNode.populateModelIdentificationInformation(properties);
437         resourceModel.addResource(resourceNode);
438     }
439 }