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_TOSCA_MAPPING_FILE = "tosca.mappings.config";
64 public static final String GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND =
65 "Cannot generate artifacts. System property %s not configured";
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";
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";
80 private static final String VERSION = "version";
82 private ISdcCsarHelper csarHelper;
85 * Constructs using csarHelper
90 public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
91 this.csarHelper = csarHelper;
95 * Get or create the artifact description.
99 * @return the artifact model's description
101 public static String getArtifactDescription(Model model) {
102 switch (model.getModelType()) {
104 return "AAI Service Model";
106 return "AAI Resource Model";
108 return model.getModelDescription();
113 * Initialises the widget configuration.
115 * @throws IOException
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);
123 Properties properties = new Properties();
124 properties.load(new FileInputStream(file));
125 WidgetConfigurationUtil.setConfig(properties);
127 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
130 throw new IllegalArgumentException(
131 String.format(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND, PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE));
136 * Initialises the group filtering and TOSCA mapping configuration.
138 * @param configLocation
139 * the pathname to the JSON config file
140 * @throws FileNotFoundException
141 * if the file cannot be opened for reading
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));
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());
159 * Process groups for this service node, according to the defined filter.
161 * @param resourceModel
162 * @param serviceNodeTemplate
163 * @return resources for which XML Models should be generated
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()));
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.
184 * initial Map of String property values (e.g. from the TOSCA YAML metadata section)
186 * Map of TOSCA Property Type Object values to merge in (or overwrite)
187 * @return a Map of the property values converted to String
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()));
196 public Resource createInstanceGroupModel(Map<String, String> properties) {
197 Resource groupModel = new Resource(Type.INSTANCE_GROUP, true);
198 groupModel.populateModelIdentificationInformation(properties);
206 public void addRelatedModel(final Model model, final Resource relation) {
207 if (relation.isResource()) {
208 model.addResource(relation);
210 model.addWidget(Widget.getWidget(relation.getWidgetType()));
214 public boolean hasAllottedResource(Map<String, String> metadata) {
215 return ALLOTTED_RESOURCE.equals(metadata.get(CATEGORY));
218 public boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
219 return TUNNEL_XCONNECT.equals(metadata.get(SUBCATEGORY));
223 * Process TOSCA Group information for VF Modules.
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);
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);
244 * @param resourceModel
245 * @param resourceNodeTemplates
247 public void processResourceModels(Model resourceModel, List<NodeTemplate> resourceNodeTemplates) {
248 boolean foundProvidingService = false;
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);
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);
264 foundProvidingService |= processModel(resourceModel, metadata, model, resourceNodeTemplate.getProperties());
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));
275 * Create an Instance Group Model and populate it with the supplied data.
277 * @param resourceModel
278 * the Resource node template Model
280 * the Resources and Widgets belonging to the Group
281 * @param metaProperties
282 * the metadata of the Group
284 * the properties of the Group
285 * @return the Instance Group and Member resource models
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());
293 if (memberNodes != null && !memberNodes.isEmpty()) {
294 resources.addAll(generateResourcesAndWidgets(memberNodes, groupModel));
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()));
310 List<Resource> resources = new ArrayList<>();
312 for (NodeTemplate nodeTemplate : memberNodes) {
313 String nodeTypeName = nodeTemplate.getType();
314 final String metadataType = nodeTemplate.getMetaData().getValue("type");
316 log.debug(String.format("Get model for %s (metadata type %s)", nodeTypeName, metadataType));
317 Resource memberModel = Model.getModelFor(nodeTypeName, metadataType);
319 if (memberModel != null) {
320 memberModel.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
322 log.debug(String.format("Generating grouped %s (%s) from TOSCA type %s",
323 memberModel.getClass().getSuperclass().getSimpleName(), memberModel.getClass(), nodeTypeName));
325 addRelatedModel(groupModel, memberModel);
326 if (memberModel.isResource()) {
327 resources.add(memberModel);
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()));
339 processVfModuleGroup(groupModel, csarHelper.getMembersOfVfModule(serviceNode, groupDefinition));
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);
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);
360 * Process the Widget members of a VF Module Group
365 private void processGroupMembers(Resource group, NodeTemplate member) {
366 Resource resource = Model.getModelFor(member.getType());
368 log.debug(member.getType() + " mapped to " + resource);
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);