2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020 Nordix Foundation
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 * SPDX-License-Identifier: Apache-2.0
17 * ============LICENSE_END=========================================================
20 package org.openecomp.sdc.be.plugins.etsi.nfv.nsd.generator;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import fj.data.Either;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.Optional;
34 import org.apache.commons.collections4.CollectionUtils;
35 import org.apache.commons.collections4.MapUtils;
36 import org.openecomp.sdc.be.config.ConfigurationManager;
37 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
38 import org.openecomp.sdc.be.model.Component;
39 import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType;
40 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.exception.NsdException;
41 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.model.Nsd;
42 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.model.VnfDescriptor;
43 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.tosca.yaml.ToscaTemplateYamlGenerator;
44 import org.openecomp.sdc.be.tosca.ToscaError;
45 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
46 import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
47 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
48 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
49 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
50 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraint;
51 import org.openecomp.sdc.be.tosca.model.ToscaPropertyConstraintValidValues;
52 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
53 import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.ObjectProvider;
58 @org.springframework.stereotype.Component("nsDescriptorGenerator")
59 public class NsDescriptorGeneratorImpl implements NsDescriptorGenerator {
61 private static final Logger LOGGER = LoggerFactory.getLogger(NsDescriptorGeneratorImpl.class);
62 private static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
63 private static final String NS_TOSCA_TYPE = "tosca.nodes.nfv.NS";
64 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS_ETSI_SOL_NSD =
66 ImmutableMap.of("etsi_nfv_sol001_nsd_2_7_1_types",
67 ImmutableMap.of("file", "etsi_nfv_sol001_nsd_2_7_1_types.yaml")
70 private static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
71 .getConfigurationManager().getConfiguration().getDefaultImports();
72 private static final List<String> PROPERTIES_TO_EXCLUDE_FROM_ETSI_SOL_NSD_NS_NODE_TYPE = Arrays
73 .asList("cds_model_name", "cds_model_version", "skip_post_instantiation_configuration", "controller_actor");
74 private static final List<String> PROPERTIES_TO_EXCLUDE_FROM_ETSI_SOL_NSD_NS_NODE_TEMPLATE = Arrays
75 .asList("nf_function", "nf_role", "nf_naming_code", "nf_type", "nf_naming", "availability_zone_max_count",
76 "min_instances", "max_instances", "multi_stage_design", "sdnc_model_name", "sdnc_model_version",
77 "sdnc_artifact_name", "skip_post_instantiation_configuration", "controller_actor");
79 private final ToscaExportHandler toscaExportHandler;
80 private final ObjectProvider<ToscaTemplateYamlGenerator> toscaTemplateYamlGeneratorProvider;
82 public NsDescriptorGeneratorImpl(final ToscaExportHandler toscaExportHandler,
83 final ObjectProvider<ToscaTemplateYamlGenerator> toscaTemplateYamlGeneratorProvider) {
84 this.toscaExportHandler = toscaExportHandler;
85 this.toscaTemplateYamlGeneratorProvider = toscaTemplateYamlGeneratorProvider;
88 public Optional<Nsd> generate(final Component component,
89 final List<VnfDescriptor> vnfDescriptorList) throws NsdException {
90 if (!ComponentTypeEnum.SERVICE.equals(component.getComponentType())) {
91 return Optional.empty();
94 final ToscaTemplate toscaTemplate = createNetworkServiceDescriptor(component, vnfDescriptorList);
95 final ToscaNodeType nsNodeType = toscaTemplate.getNode_types().values().stream()
96 .filter(toscaNodeType -> NS_TOSCA_TYPE.equals(toscaNodeType.getDerived_from())).findFirst().orElse(null);
97 if (nsNodeType == null) {
98 return Optional.empty();
101 return Optional.of(buildNsd(toscaTemplate, nsNodeType));
104 private Nsd buildNsd(final ToscaTemplate toscaTemplate, final ToscaNodeType nsNodeType) {
105 final Nsd nsd = new Nsd();
106 nsd.setDesigner(getProperty(nsNodeType, Nsd.DESIGNER_PROPERTY));
107 nsd.setVersion(getProperty(nsNodeType, Nsd.VERSION_PROPERTY));
108 nsd.setName(getProperty(nsNodeType, Nsd.NAME_PROPERTY));
109 nsd.setInvariantId(getProperty(nsNodeType, Nsd.INVARIANT_ID_PROPERTY));
110 final ToscaTemplateYamlGenerator yamlParserProvider =
111 toscaTemplateYamlGeneratorProvider.getObject(toscaTemplate);
112 final byte[] contents = yamlParserProvider.parseToYamlString().getBytes();
113 nsd.setContents(contents);
114 final List<String> interfaceImplementations = getInterfaceImplementations(toscaTemplate);
115 nsd.setArtifactReferences(interfaceImplementations);
119 private List<String> getInterfaceImplementations(final ToscaTemplate template) {
120 if (template.getTopology_template().getNode_templates() == null) {
121 return Collections.emptyList();
123 final List<String> interfaceImplementations = new ArrayList<>();
124 final Collection<ToscaNodeTemplate> nodeTemplates =
125 template.getTopology_template().getNode_templates().values();
126 nodeTemplates.stream()
127 .filter(toscaNodeTemplate -> toscaNodeTemplate.getInterfaces() != null)
128 .forEach(toscaNodeTemplate ->
129 toscaNodeTemplate.getInterfaces().values().forEach(interfaceInstance ->
130 interfaceImplementations.addAll(getInterfaceImplementations(interfaceInstance))
132 return interfaceImplementations;
135 private Collection<String> getInterfaceImplementations(final Object interfaceInstance) {
136 final Collection<String> interfaceImplementations = new ArrayList<>();
137 if (interfaceInstance instanceof Map) {
138 for (final Object value : ((Map<?, ?>) interfaceInstance).values()) {
139 if (value instanceof Map && ((Map<?, ?>) value).get("implementation") != null) {
140 interfaceImplementations.add(((Map<?, ?>) value).get("implementation").toString());
144 return interfaceImplementations;
147 private String getProperty(final ToscaNodeType nodeType, final String propertyName) {
148 final ToscaProperty toscaProperty = nodeType.getProperties().get(propertyName);
150 final String errorMsg =
151 String.format("Property '%s' must be defined and must have a valid values constraint", propertyName);
152 final String returnValueOnError = "unknown";
153 if (toscaProperty == null || CollectionUtils.isEmpty(toscaProperty.getConstraints())) {
154 LOGGER.error(errorMsg);
155 return returnValueOnError;
158 final ToscaPropertyConstraint toscaPropertyConstraint = toscaProperty.getConstraints().get(0);
159 if (ConstraintType.VALID_VALUES != toscaPropertyConstraint.getConstraintType()) {
160 LOGGER.error(errorMsg);
161 return returnValueOnError;
164 final ToscaPropertyConstraintValidValues validValuesConstraint =
165 (ToscaPropertyConstraintValidValues) toscaPropertyConstraint;
166 final List<String> validValues = validValuesConstraint.getValidValues();
167 if(CollectionUtils.isEmpty(validValues)) {
168 LOGGER.error(errorMsg);
169 return returnValueOnError;
172 return validValues.get(0);
175 private ToscaTemplate createNetworkServiceDescriptor(final Component component,
176 final List<VnfDescriptor> vnfDescriptorList)
177 throws NsdException {
179 final ToscaTemplate componentToscaTemplate = parseToToscaTemplate(component);
180 final ToscaTemplate componentToscaTemplateInterface = exportComponentInterfaceAsToscaTemplate(component);
182 final Entry<String, ToscaNodeType> firstNodeTypeEntry =
183 componentToscaTemplateInterface.getNode_types()
184 .entrySet().stream().findFirst().orElse(null);
185 if (firstNodeTypeEntry == null) {
186 throw new NsdException("Could not find abstract Service type");
189 final String nsNodeTypeName = firstNodeTypeEntry.getKey();
190 final ToscaNodeType nsNodeType = firstNodeTypeEntry.getValue();
192 final Map<String, ToscaNodeType> nodeTypeMap = new HashMap<>();
193 nodeTypeMap.put(nsNodeTypeName, createEtsiSolNsNodeType(nsNodeType));
195 if (componentToscaTemplate.getNode_types() == null) {
196 componentToscaTemplate.setNode_types(nodeTypeMap);
198 componentToscaTemplate.getNode_types().putAll(nodeTypeMap);
201 setPropertiesForNodeTemplates(componentToscaTemplate);
202 removeCapabilitiesFromNodeTemplates(componentToscaTemplate);
203 removeOnapPropertiesFromInputs(componentToscaTemplate);
204 handleSubstitutionMappings(componentToscaTemplate, nsNodeTypeName);
206 final Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
207 nodeTemplates.put(nsNodeTypeName, createNodeTemplateForNsNodeType(nsNodeTypeName,
208 componentToscaTemplateInterface.getNode_types().get(nsNodeTypeName)));
210 if (componentToscaTemplate.getTopology_template().getNode_templates() == null) {
211 componentToscaTemplate.getTopology_template().setNode_templates(nodeTemplates);
213 setNodeTemplateTypesForVnfs(componentToscaTemplate, vnfDescriptorList);
214 componentToscaTemplate.getTopology_template().getNode_templates().putAll(nodeTemplates);
217 removeOnapMetaData(componentToscaTemplate);
219 setDefaultImportsForEtsiSolNsNsd(componentToscaTemplate, vnfDescriptorList);
221 return componentToscaTemplate;
224 private void handleSubstitutionMappings(final ToscaTemplate componentToscaTemplate, final String nsNodeTypeName) {
225 final SubstitutionMapping substitutionMapping = new SubstitutionMapping();
226 substitutionMapping.setNode_type(nsNodeTypeName);
227 final SubstitutionMapping onapSubstitutionMapping = componentToscaTemplate.getTopology_template().getSubstitution_mappings();
228 if (onapSubstitutionMapping != null) {
229 substitutionMapping.setRequirements(onapSubstitutionMapping.getRequirements());
230 substitutionMapping.setCapabilities(onapSubstitutionMapping.getCapabilities());
232 componentToscaTemplate.getTopology_template().setSubstitution_mappings(substitutionMapping);
235 private void setNodeTemplateTypesForVnfs(final ToscaTemplate template,
236 final List<VnfDescriptor> vnfDescriptorList) {
237 if (CollectionUtils.isEmpty(vnfDescriptorList)) {
240 final Map<String, ToscaNodeTemplate> nodeTemplateMap = template.getTopology_template().getNode_templates();
241 if (MapUtils.isEmpty(nodeTemplateMap)) {
244 nodeTemplateMap.forEach((key, toscaNodeTemplate) ->
245 vnfDescriptorList.stream()
246 .filter(vnfDescriptor -> key.equals(vnfDescriptor.getName())).findFirst()
247 .ifPresent(vnfDescriptor -> toscaNodeTemplate.setType(vnfDescriptor.getNodeType()))
251 private void setPropertiesForNodeTemplates(final ToscaTemplate template) {
252 final Map<String, ToscaNodeTemplate> nodeTemplateMap = template.getTopology_template().getNode_templates();
253 if (MapUtils.isEmpty(nodeTemplateMap)) {
256 for (final Entry<String, ToscaNodeTemplate> nodeTemplate : nodeTemplateMap.entrySet()) {
257 final Map<String, Object> propertyMap = nodeTemplate.getValue().getProperties();
258 if (MapUtils.isEmpty(propertyMap)) {
259 nodeTemplate.getValue().setProperties(null);
262 final Map<String, Object> editedPropertyMap = new HashMap<>();
263 for (final Entry<String, Object> property : propertyMap.entrySet()) {
264 if (!PROPERTIES_TO_EXCLUDE_FROM_ETSI_SOL_NSD_NS_NODE_TEMPLATE.contains(property.getKey())
265 && propertyIsDefinedInNodeType(property.getKey())) {
267 .put(property.getKey().substring(property.getKey().indexOf('_') + 1), property.getValue());
270 if (editedPropertyMap.isEmpty()) {
271 nodeTemplate.getValue().setProperties(null);
273 nodeTemplate.getValue().setProperties(editedPropertyMap);
278 private void removeCapabilitiesFromNodeTemplates(final ToscaTemplate template) {
279 final Map<String, ToscaNodeTemplate> nodeTemplateMap = template.getTopology_template().getNode_templates();
280 if (MapUtils.isEmpty(nodeTemplateMap)) {
283 for (final Entry<String, ToscaNodeTemplate> nodeTemplate : nodeTemplateMap.entrySet()) {
284 nodeTemplate.getValue().setCapabilities(null);
288 private void removeOnapPropertiesFromInputs(final ToscaTemplate template) {
289 final ToscaTopolgyTemplate topologyTemplate = template.getTopology_template();
290 final Map<String, ToscaProperty> inputMap = topologyTemplate.getInputs();
291 if (MapUtils.isNotEmpty(inputMap)) {
293 .removeIf(entry -> PROPERTIES_TO_EXCLUDE_FROM_ETSI_SOL_NSD_NS_NODE_TYPE.contains(entry.getKey()));
295 if (MapUtils.isEmpty(inputMap)) {
296 topologyTemplate.setInputs(null);
300 private void removeOnapMetaData(final ToscaTemplate template) {
301 template.setMetadata(null);
302 final Map<String, ToscaNodeTemplate> nodeTemplateMap = template.getTopology_template().getNode_templates();
303 if (MapUtils.isEmpty(nodeTemplateMap)) {
306 nodeTemplateMap.values().forEach(toscaNodeTemplate -> toscaNodeTemplate.setMetadata(null));
309 private void setDefaultImportsForEtsiSolNsNsd(final ToscaTemplate template,
310 final List<VnfDescriptor> vnfDescriptorList) {
311 final List<Map<String, Map<String, String>>> importEntryMap = new ArrayList<>(DEFAULT_IMPORTS_ETSI_SOL_NSD);
312 if (CollectionUtils.isNotEmpty(vnfDescriptorList)) {
313 for (final VnfDescriptor vnfDescriptor : vnfDescriptorList) {
314 final Map<String, String> vnfImportChildEntry = new HashMap<>();
315 vnfImportChildEntry.put("file", vnfDescriptor.getVnfdFileName());
316 final Map<String, Map<String, String>> vnfdImportVnfdEntry = new HashMap<>();
317 vnfdImportVnfdEntry.put(vnfDescriptor.getName(), vnfImportChildEntry);
318 importEntryMap.add(vnfdImportVnfdEntry);
322 template.setImports(importEntryMap);
325 private ToscaNodeType createEtsiSolNsNodeType(final ToscaNodeType nsNodeType) {
326 final ToscaNodeType toscaNodeType = new ToscaNodeType();
327 toscaNodeType.setDerived_from(NS_TOSCA_TYPE);
329 final Map<String, ToscaProperty> propertiesInNsNodeType = nsNodeType.getProperties();
331 for (final Entry<String, ToscaProperty> property : propertiesInNsNodeType.entrySet()) {
332 final ToscaProperty toscaProperty = property.getValue();
333 if (toscaProperty.getDefaultp() != null) {
334 final ToscaPropertyConstraintValidValues constraint = new ToscaPropertyConstraintValidValues(
335 Collections.singletonList(toscaProperty.getDefaultp().toString()));
336 toscaProperty.setConstraints(Collections.singletonList(constraint));
340 propertiesInNsNodeType.entrySet()
341 .removeIf(entry -> PROPERTIES_TO_EXCLUDE_FROM_ETSI_SOL_NSD_NS_NODE_TYPE.contains(entry.getKey()));
342 toscaNodeType.setProperties(propertiesInNsNodeType);
344 return toscaNodeType;
347 private boolean propertyIsDefinedInNodeType(final String propertyName) {
348 // This will achieve what we want for now, but will look into a more generic solution which would involve
349 // checking the node_type definition in the VNFD
350 return !propertyName.equals("additional_parameters");
354 private ToscaNodeTemplate createNodeTemplateForNsNodeType(final String nodeType,
355 final ToscaNodeType toscaNodeType) {
356 final ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
357 nodeTemplate.setType(nodeType);
359 final Map<String, ToscaProperty> properties = toscaNodeType.getProperties();
360 final Map<String, Object> nodeTemplateProperties = new HashMap<>();
361 for (final Entry<String, ToscaProperty> property : properties.entrySet()) {
362 nodeTemplateProperties.put(property.getKey(), property.getValue().getDefaultp());
365 if (!nodeTemplateProperties.isEmpty()) {
366 nodeTemplate.setProperties(nodeTemplateProperties);
369 final Map<String, Object> interfaces = toscaNodeType.getInterfaces();
370 if (interfaces != null) {
371 for (final Entry<String, Object> nodeInterface : interfaces.entrySet()) {
372 if ("Nslcm".equals(nodeInterface.getKey()) && nodeInterface.getValue() instanceof Map) {
373 ((Map<?, ?>) nodeInterface.getValue()).remove("type");
376 nodeTemplate.setInterfaces(interfaces);
382 private ToscaTemplate parseToToscaTemplate(final Component component) throws NsdException {
383 final Either<ToscaTemplate, ToscaError> toscaTemplateRes = toscaExportHandler.convertToToscaTemplate(component);
384 if (toscaTemplateRes.isRight()) {
385 String errorMsg = String.format("Could not parse component '%s' to tosca template. Error '%s'",
386 component.getName(), toscaTemplateRes.right().value().name());
387 throw new NsdException(errorMsg);
390 return toscaTemplateRes.left().value();
394 private ToscaTemplate exportComponentInterfaceAsToscaTemplate(final Component component) throws NsdException {
395 if (null == DEFAULT_IMPORTS) {
396 throw new NsdException("Could not load default CSAR imports from configuration");
399 final ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
400 toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
401 final Either<ToscaTemplate, ToscaError> toscaTemplateRes = toscaExportHandler
402 .convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, new HashMap<>(), false);
403 if (toscaTemplateRes.isRight()) {
404 throw new NsdException(String.format("Could not create abstract service from component '%s'",
405 component.getName()));
408 return toscaTemplateRes.left().value();