2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.aai.babel.parser;
24 import com.google.gson.Gson;
25 import java.io.BufferedReader;
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;
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;
54 * Wrapper for the sdc-tosca parser
57 public class ArtifactGeneratorToscaParser {
59 private static Logger log = LogHelper.INSTANCE;
61 public static final String PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE = "artifactgenerator.config";
62 public static final String PROPERTY_GROUP_FILTERS_CONFIG_FILE = "groupfilter.config";
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";
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";
79 private static final String VERSION = "version";
81 private ISdcCsarHelper csarHelper;
84 * Constructs using csarHelper
89 public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
90 this.csarHelper = csarHelper;
94 * Get or create the artifact description.
98 * @return the artifact model's description
100 public static String getArtifactDescription(Model model) {
101 switch (model.getModelType()) {
103 return "AAI Service Model";
105 return "AAI Resource Model";
107 return model.getModelDescription();
112 * Initialises the widget configuration.
114 * @throws IOException
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);
122 Properties properties = new Properties();
123 properties.load(new FileInputStream(file));
124 WidgetConfigurationUtil.setConfig(properties);
126 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
129 throw new IllegalArgumentException(
130 String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE));
135 * Initialises the group filtering and mapping configuration.
137 * @throws FileNotFoundException
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));
148 File file = new File(configLocation);
149 if (!file.exists()) {
150 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
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());
160 * Process groups for this service node, according to the defined filter.
162 * @param resourceModel
163 * @param serviceNodeTemplate
164 * @return resources for which XML Models should be generated
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()));
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.
185 * initial Map of String property values (e.g. from the TOSCA YAML metadata section)
187 * Map of TOSCA Property Type Object values to merge in (or overwrite)
188 * @return a Map of the property values converted to String
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()));
197 public Resource createInstanceGroupModel(Map<String, String> properties) {
198 Resource groupModel = new Resource(Type.INSTANCE_GROUP, true);
199 groupModel.populateModelIdentificationInformation(properties);
207 public void addRelatedModel(final Model model, final Resource relation) {
208 if (relation.isResource()) {
209 model.addResource(relation);
211 model.addWidget(Widget.getWidget(relation.getWidgetType()));
215 public boolean hasAllottedResource(Map<String, String> metadata) {
216 return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
219 public boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
220 return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
224 * Process TOSCA Group information for VF Modules.
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);
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);
245 * @param resourceModel
246 * @param resourceNodeTemplates
248 public void processResourceModels(Model resourceModel, List<NodeTemplate> resourceNodeTemplates) {
249 boolean foundProvidingService = false;
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);
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);
266 foundProvidingService |= processModel(resourceModel, metadata, model, resourceNodeTemplate.getProperties());
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));
277 * Create an Instance Group Model and populate it with the supplied data.
279 * @param resourceModel
280 * the Resource node template Model
282 * the Resources and Widgets belonging to the Group
283 * @param metaProperties
284 * the metadata of the Group
286 * the properties of the Group
287 * @return the Instance Group and Member resource models
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());
295 if (memberNodes != null && !memberNodes.isEmpty()) {
296 resources.addAll(generateResourcesAndWidgets(memberNodes, groupModel));
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()));
312 List<Resource> resources = new ArrayList<>();
314 for (NodeTemplate nodeTemplate : memberNodes) {
315 String nodeTypeName = nodeTemplate.getType();
316 final String metadataType = nodeTemplate.getMetaData().getValue("type");
318 log.debug(String.format("Get model for %s (metadata type %s)", nodeTypeName, metadataType));
319 Resource memberModel = Model.getModelFor(nodeTypeName, metadataType);
321 if (memberModel != null) {
322 memberModel.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
324 log.debug(String.format("Generating grouped %s (%s) from TOSCA type %s",
325 memberModel.getClass().getSuperclass().getSimpleName(), memberModel.getClass(), nodeTypeName));
327 addRelatedModel(groupModel, memberModel);
328 if (memberModel.isResource()) {
329 resources.add(memberModel);
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()));
341 processVfModuleGroup(groupModel, csarHelper.getMembersOfVfModule(serviceNode, groupDefinition));
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);
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);
362 * Process the Widget members of a VF Module Group
367 private void processGroupMembers(Resource group, NodeTemplate member) {
368 Resource resource = Model.getModelFor(member.getType());
370 if (resource.getWidgetType() == Type.L3_NET) {
371 // An l3-network inside a vf-module is treated as a Widget
372 resource.setIsResource(false);
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);
384 * Create a Map of property name against String property value from the input Map
388 * @return Map of property name against String property value
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()));
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.
399 * @param resourceModel
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
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);
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());
421 resourceModel.addResource((Resource) resourceNode);
423 return foundProvidingService;
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()));
433 Map<String, String> properties = populateStringProperties(nodeProperties);
434 properties.put(VERSION, "1.0");
435 resourceNode.populateModelIdentificationInformation(properties);
436 resourceModel.addResource(resourceNode);