Check getMetaData() return value for null
[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.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Properties;
31 import java.util.stream.Collectors;
32 import org.onap.aai.babel.logging.ApplicationMsgs;
33 import org.onap.aai.babel.logging.LogHelper;
34 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
35 import org.onap.aai.babel.xml.generator.model.AllotedResource;
36 import org.onap.aai.babel.xml.generator.model.L3NetworkWidget;
37 import org.onap.aai.babel.xml.generator.model.Model;
38 import org.onap.aai.babel.xml.generator.model.ProvidingService;
39 import org.onap.aai.babel.xml.generator.model.Resource;
40 import org.onap.aai.babel.xml.generator.model.Service;
41 import org.onap.aai.babel.xml.generator.model.TunnelXconnectWidget;
42 import org.onap.aai.babel.xml.generator.model.VfModule;
43 import org.onap.aai.babel.xml.generator.model.Widget;
44 import org.onap.aai.babel.xml.generator.types.ModelType;
45 import org.onap.aai.cl.api.Logger;
46 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
47 import org.onap.sdc.toscaparser.api.Group;
48 import org.onap.sdc.toscaparser.api.NodeTemplate;
49 import org.onap.sdc.toscaparser.api.Property;
50 import org.onap.sdc.toscaparser.api.elements.Metadata;
51
52 public class ArtifactGeneratorToscaParser {
53
54     private static Logger log = LogHelper.INSTANCE;
55
56     public static final String PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE = "artifactgenerator.config";
57
58     private static final String GENERATOR_AAI_CONFIGFILE_NOT_FOUND =
59             "Cannot generate artifacts. Artifact Generator Configuration file not found at %s";
60     private static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND =
61             "Cannot generate artifacts. artifactgenerator.config system property not configured";
62     private static final String GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING =
63             "Cannot generate artifacts. Providing Service Metadata is missing for allotted resource %s";
64     private static final String GENERATOR_AAI_PROVIDING_SERVICE_MISSING =
65             "Cannot generate artifacts. Providing Service is missing for allotted resource %s";
66
67     // Metadata properties
68     private static final String CATEGORY = "category";
69     private static final String ALLOTTED_RESOURCE = "Allotted Resource";
70     private static final String SUBCATEGORY = "subcategory";
71     private static final String TUNNEL_XCONNECT = "Tunnel XConnect";
72
73     private static final String VERSION = "version";
74
75     private ISdcCsarHelper csarHelper;
76
77     /**
78      * Constructs using csarHelper
79      *
80      * @param csarHelper The csar helper
81      */
82     public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
83         this.csarHelper = csarHelper;
84     }
85
86     /**
87      * Returns the artifact description
88      *
89      * @param model the artifact model
90      * @return the artifact model's description
91      */
92     public static String getArtifactDescription(Model model) {
93         String artifactDesc = model.getModelDescription();
94         if (model.getModelType().equals(ModelType.SERVICE)) {
95             artifactDesc = "AAI Service Model";
96         } else if (model.getModelType().equals(ModelType.RESOURCE)) {
97             artifactDesc = "AAI Resource Model";
98         }
99         return artifactDesc;
100     }
101
102     /**
103      * Initialises the widget configuration.
104      *
105      * @throws IOException
106      */
107     public static void initWidgetConfiguration() throws IOException {
108         log.debug("Getting Widget Configuration");
109         String configLocation = System.getProperty(PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE);
110         if (configLocation != null) {
111             File file = new File(configLocation);
112             if (file.exists()) {
113                 Properties properties = new Properties();
114                 properties.load(new FileInputStream(file));
115                 WidgetConfigurationUtil.setConfig(properties);
116             } else {
117                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
118             }
119         } else {
120             throw new IllegalArgumentException(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND);
121         }
122     }
123
124     /**
125      * Process the service TOSCA.
126      *
127      * @param service model of the service artifact
128      * @param idTypeStore ID->Type mapping
129      * @param nodeTemplates a list of service nodes
130      *
131      */
132     public void processServiceTosca(Service service, Map<String, String> idTypeStore,
133             List<NodeTemplate> nodeTemplates) {
134         log.debug("Inside Service Tosca ");
135
136         // Get the resource/widgets in the service according to the node-template types
137         for (NodeTemplate node : nodeTemplates) {
138             if (node.getMetaData() != null) {
139                 Model model = Model.getModelFor(correctNodeType(node));
140                 if (model != null) {
141                     model.populateModelIdentificationInformation(node.getMetaData().getAllProperties());
142                     if (model instanceof Resource) {
143                         // Keeping track of resource types and
144                         // their uuid for identification during resource tosca processing
145                         idTypeStore.put(model.getModelNameVersionId(), correctNodeType(node));
146                         service.addResource((Resource) model);
147                     } else {
148                         service.addWidget((Widget) model);
149                     }
150                 }
151             } else {
152                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, node.getName());
153             }
154         }
155     }
156
157     /**
158      * Generates a Resource List using input Service Node Templates.
159      *
160      * @param serviceNodes input Service Node Templates
161      * @param idTypeStore ID->Type mapping
162      * @return the processed resource models
163      */
164     public List<Resource> processResourceToscas(List<NodeTemplate> serviceNodes, Map<String, String> idTypeStore) {
165         List<Resource> resources = new LinkedList<>();
166         for (NodeTemplate serviceNode : serviceNodes) {
167             if (serviceNode.getMetaData() != null) {
168                 List<NodeTemplate> resourceNodes = csarHelper.getNodeTemplateChildren(serviceNode);
169                 processResourceTosca(idTypeStore, resources, serviceNode, resourceNodes);
170             } else {
171                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, serviceNode.getName());
172             }
173         }
174         return resources;
175     }
176
177     private void processResourceTosca(Map<String, String> idTypeStore, List<Resource> resources,
178             NodeTemplate serviceNode, List<NodeTemplate> resourceNodes) {
179         String resourceUuId = serviceNode.getMetaData().getValue("UUID");
180         String resourceType = idTypeStore.get(resourceUuId);
181         if (resourceType != null) {
182             Model model = Model.getModelFor(resourceType);
183
184             log.debug("Inside Resource artifact generation for resource");
185             Map<String, String> serviceMetadata = serviceNode.getMetaData().getAllProperties();
186             model.populateModelIdentificationInformation(serviceMetadata);
187
188             // Found model from the type store so removing the same
189             idTypeStore.remove(model.getModelNameVersionId());
190             processVfTosca(idTypeStore, model, resourceNodes);
191
192             // Process group information from tosca for vfModules
193             if (csarHelper.getServiceVfList() != null) {
194                 processVfModules(resources, model, serviceNode);
195             }
196
197             if (hasSubCategoryTunnelXConnect(serviceMetadata) && hasAllottedResource(serviceMetadata)) {
198                 model.addWidget(new TunnelXconnectWidget());
199             }
200             resources.add((Resource) model);
201         }
202     }
203
204     private void processVfModules(List<Resource> resources, Model resourceModel, NodeTemplate serviceNode) {
205         // Get the customisation UUID for each VF node and use it to get its Groups
206         String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNode);
207         List<Group> serviceGroups = csarHelper.getVfModulesByVf(uuid);
208
209         // Process each VF Group
210         for (Group serviceGroup : serviceGroups) {
211             Model groupModel = Model.getModelFor(serviceGroup.getType());
212             if (groupModel instanceof VfModule) {
213                 processVfModule(resources, resourceModel, serviceGroup, serviceNode, (VfModule) groupModel);
214             }
215         }
216     }
217
218     private void processVfModule(List<Resource> resources, Model model, Group groupDefinition, NodeTemplate serviceNode,
219             VfModule groupModel) {
220         // Populate group with metadata properties
221         groupModel.populateModelIdentificationInformation(groupDefinition.getMetadata().getAllProperties());
222         // Populate group with non-metadata properties
223         Map<String, Property> groupProperties = groupDefinition.getProperties();
224         Map<String, String> properties = populateStringProperties(groupProperties);
225         groupModel.populateModelIdentificationInformation(properties);
226
227         // Get names of the members of the service group
228         List<NodeTemplate> members = csarHelper.getMembersOfVfModule(serviceNode, groupDefinition);
229         if (members != null && !members.isEmpty()) {
230             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
231             groupModel.setMembers(memberNames);
232             for (NodeTemplate member : members) {
233                 processGroupMembers(groupModel, member);
234             }
235         }
236
237         model.addResource(groupModel); // Added group (VfModule) to the (VF) model
238         // Check if we have already encountered the same VfModule across all the artifacts
239         if (!resources.contains(groupModel)) {
240             resources.add(groupModel);
241         }
242     }
243
244     private void processGroupMembers(Model group, NodeTemplate member) {
245         Model resourceNode;
246         // L3-network inside vf-module to be generated as Widget a special handling.
247         if (member.getType().contains("org.openecomp.resource.vl")) {
248             resourceNode = new L3NetworkWidget();
249         } else {
250             resourceNode = Model.getModelFor(member.getType());
251         }
252         if (resourceNode != null && !(resourceNode instanceof Resource)) {
253             Widget widget = (Widget) resourceNode;
254             widget.addKey(member.getName());
255             // Add the widget element encountered to the Group model
256             group.addWidget(widget);
257         }
258     }
259
260     private String correctNodeType(NodeTemplate nodeType) {
261         String correctedNodeType = nodeType.getType();
262         Metadata metadata = nodeType.getMetaData();
263         if (metadata != null && hasAllottedResource(metadata.getAllProperties())) {
264             if (nodeType.getType().contains("org.openecomp.resource.vf.")) {
265                 correctedNodeType = "org.openecomp.resource.vf.allottedResource";
266             }
267             if (nodeType.getType().contains("org.openecomp.resource.vfc.")) {
268                 correctedNodeType = "org.openecomp.resource.vfc.AllottedResource";
269             }
270         }
271         return correctedNodeType;
272     }
273
274     private boolean hasAllottedResource(Map<String, String> metadata) {
275         return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
276     }
277
278     private boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
279         return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
280     }
281
282     /**
283      * Create a Map of property name against String property value from the input Map
284      *
285      * @param inputMap The input Map
286      * @return Map of property name against String property value
287      */
288     private Map<String, String> populateStringProperties(Map<String, Property> inputMap) {
289         return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
290                 e -> e.getValue().getValue() == null ? "" : e.getValue().getValue().toString()));
291     }
292
293     private void processVfTosca(Map<String, String> idTypeStore, Model resourceModel,
294             List<NodeTemplate> resourceNodes) {
295         boolean providingServiceFound = false;
296
297         for (NodeTemplate resourceNodeTemplate : resourceNodes) {
298             Model resourceNode = Model.getModelFor(correctNodeType(resourceNodeTemplate));
299             if (resourceNode instanceof ProvidingService) {
300                 providingServiceFound = true;
301                 Map<String, Property> nodeProperties = resourceNodeTemplate.getProperties();
302                 if (nodeProperties.get("providing_service_uuid") == null
303                         || nodeProperties.get("providing_service_invariant_uuid") == null) {
304                     throw new IllegalArgumentException(String.format(GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING,
305                             resourceModel.getModelId()));
306                 }
307                 Map<String, String> properties = populateStringProperties(nodeProperties);
308                 properties.put(VERSION, "1.0");
309                 resourceNode.populateModelIdentificationInformation(properties);
310                 resourceModel.addResource((Resource) resourceNode);
311             } else if (resourceNode instanceof Resource && !(resourceNode.getWidgetType().equals(Widget.Type.L3_NET))) {
312                 idTypeStore.put(resourceNode.getModelNameVersionId(), correctNodeType(resourceNodeTemplate));
313                 resourceModel.addResource((Resource) resourceNode);
314             }
315         }
316
317         if (resourceModel instanceof AllotedResource && !providingServiceFound) {
318             throw new IllegalArgumentException(
319                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING, resourceModel.getModelId()));
320         }
321     }
322 }