2 * ============LICENSE_START=======================================================
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
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.csar.vnfcatalog;
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.util.ArrayList;
28 import java.util.List;
30 import java.util.Map.Entry;
31 import java.util.Objects;
32 import java.util.function.Consumer;
33 import java.util.stream.Collectors;
35 import org.apache.commons.io.FileUtils;
36 import org.apache.commons.lang3.time.StopWatch;
37 import org.apache.commons.lang3.tuple.ImmutablePair;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.onap.aai.babel.logging.ApplicationMsgs;
40 import org.onap.aai.babel.logging.LogHelper;
41 import org.onap.aai.babel.service.data.BabelArtifact;
42 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
43 import org.onap.sdc.tosca.parser.enums.SdcTypes;
44 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
45 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
46 import org.onap.sdc.toscaparser.api.NodeTemplate;
47 import org.onap.sdc.toscaparser.api.SubstitutionMappings;
50 * This class is responsible for extracting Virtual Network Function (VNF) information from a TOSCA 1.1 CSAR package.
53 * CSAR is a compressed format that stores multiple TOSCA files. Each TOSCA file may define Topology Templates and/or
54 * Node Templates along with other model data.
58 * A VNF is a virtualized functional capability (e.g. a Router) that may be defined by an external Vendor. Within the
59 * model defined by the TOSCA files the VNF is considered to be a Resource (part of a Service).
63 * A VNF is specified by a Topology Template. Because this TOSCA construct does not allow properties to be defined
64 * directly, Node Templates are defined (identified by a VNF type value) storing the VNF metadata and properties.
68 * A VNF may be composed of multiple images, each running on its own Virtual Machine. The function of a deployed image
69 * is designated the Virtual Function Component (VFC). A VFC is a sub-component of the VNF. A VFC may have different
70 * "Flavors" (see the Deployment Flavors description below).
74 * An individual VNF (template) may be deployed with varying configuration values, according to
75 * environment/customer/business needs. For example, a VNF deployed in a testing environment would typically use fewer
76 * computational resources than in a production setting.
80 * A Vendor may define one or more "Deployment Flavors". A Deployment Flavor describes a set of pre-determined
81 * parameterised values for a specific aspect of the model. Within the TOSCA model there is a DeploymentFlavor
82 * definition, which has its own data types, and also an ImageInfo definition.
85 public class VnfVendorImageExtractor {
87 private static LogHelper applicationLogger = LogHelper.INSTANCE;
89 // The following constants describe the expected naming conventions for TOSCA Node Templates which
90 // store the VNF configuration and the VFC data items.
92 // The name of the property (for a VNF Configuration type) storing the Images Information
93 private static final String IMAGES = "images";
95 // Name of property key that contains the value of the software version
96 private static final String SOFTWARE_VERSION = "software_version";
98 // The name of the property (for a VNF Configuration type) storing the Vendor Information
99 private static final String VNF_CONF_TYPE_PROPERTY_VENDOR_INFO_CONTAINER = "allowed_flavors";
101 // Name of property key that contains the value of model of the Vendor application
102 private static final String VENDOR_MODEL = "vendor_model";
105 * This method is responsible for parsing the vnfConfiguration entity in the same topology_template (there's an
106 * assumption that there's only one per file, awaiting verification).
109 * It is possible that CSAR file does not contain a vnfConfiguration and this is valid.
113 * Where multiple vnfConfigurations are found an exception will be thrown.
117 * The ASDC model anticipates the following permutations of vnfConfiguration and multiflavorVFC:
121 * <li>Single vnfConfiguration, single multiFlavorVFC with multiple images.</li>
122 * <li>Single vnfConfiguration, multi multiFlavorVFC with single images.</li>
126 * All ImageInfo sections found apply to all "Deployment Flavors", therefore we can apply a cross product of
127 * "Deployment Flavors" x "ImageInfo"
130 * @param csar compressed format that stores multiple TOSCA files and in particular a vnfConfiguration
131 * @return BabelArtifact VendorImageConfiguration objects created during processing represented as the Babel service
132 * public data structure
133 * @throws ToscaToCatalogException if the CSAR content is not valid
135 public BabelArtifact extract(byte[] csar) throws ToscaToCatalogException {
136 StopWatch stopwatch = new StopWatch();
139 Objects.requireNonNull(csar, "A CSAR file must be supplied");
140 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Extracting VNF Configuration data");
142 List<VendorImageConfiguration> vendorImageConfigurations;
146 path = createTempFile(csar);
147 vendorImageConfigurations = createVendorImageConfigurations(path.toAbsolutePath().toString());
148 } catch (InvalidNumberOfNodesException | IOException | SdcToscaParserException e) {
149 throw new ToscaToCatalogException(
150 "An error occurred trying to get the VNF Catalog from a CSAR file. " + e.getLocalizedMessage(), e);
153 FileUtils.deleteQuietly(path.toFile());
157 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT, vendorImageConfigurations.toString());
158 applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
160 return ConfigurationsToBabelArtifactConverter.convert(vendorImageConfigurations);
164 * Creates a temporary file to store the CSAR content.
166 * @param bytes the CSAR content
167 * @return Path to a temporary file containing the CSAR bytes
168 * @throws IOException if an I/O error occurs or the temporary-file directory does not exist
170 private Path createTempFile(byte[] bytes) throws IOException {
171 Path path = Files.createTempFile("temp", ".csar");
172 applicationLogger.debug("Created temp file " + path);
173 Files.write(path, bytes);
178 * Build VNF Vendor Image Configurations for the VNF Configuration node (if present) in the CSAR file referenced by
181 * @param csarFilepath the path to the CSAR file
182 * @return a List of Vendor Image Configurations
183 * @throws SdcToscaParserException
184 * @throws ToscaToCatalogException
185 * @throws InvalidNumberOfNodesException
187 private List<VendorImageConfiguration> createVendorImageConfigurations(String csarFilepath)
188 throws SdcToscaParserException, ToscaToCatalogException, InvalidNumberOfNodesException {
189 List<VendorImageConfiguration> vendorImageConfigurations = new ArrayList<>();
191 ISdcCsarHelper csarHelper = SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarFilepath);
192 NodeTemplate vnfConfigurationNode = findVnfConfigurationNode(csarHelper);
194 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
195 String.format("Found VNF Configuration node \"%s\"", vnfConfigurationNode));
197 if (vnfConfigurationNode != null) {
198 for (NodeTemplate node : csarHelper.getServiceVfList()) {
199 vendorImageConfigurations.addAll(buildVendorImageConfigurations(vnfConfigurationNode, node));
203 return vendorImageConfigurations;
207 * Find VNF configuration node.
209 * @param csarHelper the csar helper
210 * @return the node template
211 * @throws InvalidNumberOfNodesException
213 private NodeTemplate findVnfConfigurationNode(ISdcCsarHelper csarHelper) throws InvalidNumberOfNodesException {
214 List<NodeTemplate> nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.VF);
215 applicationLogger.debug(nodeTemplates.toString());
217 List<NodeTemplate> configNodes = nodeTemplates.stream() //
218 .map(serviceNodeTemplate -> {
219 String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNodeTemplate);
220 applicationLogger.debug(serviceNodeTemplate + " Customization UUID is " + uuid);
221 return csarHelper.getVnfConfig(uuid);
223 .filter(Objects::nonNull) //
224 .collect(Collectors.toList());
226 if (configNodes.size() > 1) {
227 throw new InvalidNumberOfNodesException("Only one vnf configuration node is allowed however "
228 + configNodes.size() + " nodes were found in the csar.");
231 return configNodes.size() == 1 ? configNodes.get(0) : null;
235 * Builds the Vendor image configurations.
237 * @param vendorInfoNode the vendor info node
238 * @param node the node
240 * @throws ToscaToCatalogException if there are no software versions
242 private List<VendorImageConfiguration> buildVendorImageConfigurations(NodeTemplate vendorInfoNode,
243 NodeTemplate node) throws ToscaToCatalogException {
244 List<VendorImageConfiguration> vendorImageConfigurations = new ArrayList<>();
246 List<String> softwareVersions = extractSoftwareVersions(node.getSubMappingToscaTemplate());
248 Consumer<? super Pair<String, String>> buildConfigurations =
249 vi -> vendorImageConfigurations.addAll(softwareVersions.stream() //
250 .map(sv -> (new VendorImageConfiguration(vi.getRight(), vi.getLeft(), sv)))
251 .collect(Collectors.toList()));
253 String resourceVendor = node.getMetaData().getValue("resourceVendor");
255 applicationLogger.debug("Resource Vendor " + resourceVendor);
257 buildVendorInfo(resourceVendor, vendorInfoNode).forEach(buildConfigurations);
259 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
260 "Built " + vendorImageConfigurations.size() + " Vendor Image Configurations");
262 return vendorImageConfigurations;
266 * Builds the Vendor info.
268 * @param resourceVendor the resource vendor
269 * @param vendorInfoNode the vendor info node
272 @SuppressWarnings("unchecked")
273 private List<Pair<String, String>> buildVendorInfo(String resourceVendor, NodeTemplate vendorInfoNode) {
274 Map<String, Object> otherFlavorProperties =
275 (Map<String, Object>) vendorInfoNode.getPropertyValue(VNF_CONF_TYPE_PROPERTY_VENDOR_INFO_CONTAINER);
277 return otherFlavorProperties.keySet().stream()
278 .map(key -> createVendorInfoPair((Map<String, Object>) otherFlavorProperties.get(key), resourceVendor))
279 .collect(Collectors.toList());
283 * Creates the Vendor info pair.
285 * @param otherFlavor the other flavor
286 * @param resourceVendor the resource Vendor
289 private Pair<String, String> createVendorInfoPair(Map<String, Object> otherFlavor, String resourceVendor) {
290 @SuppressWarnings("unchecked")
291 String vendorModel = otherFlavor.entrySet().stream() //
292 .filter(entry -> "vendor_info".equals(entry.getKey()))
293 .map(e -> ((Map<String, String>) e.getValue()).get(VENDOR_MODEL)) //
294 .findFirst().orElse(null);
296 applicationLogger.debug("Creating Vendor info pair object for vendorModel = " + vendorModel
297 + " and resourceVendor = " + resourceVendor);
299 return new ImmutablePair<>(resourceVendor, vendorModel);
303 * Extract software versions.
305 * @param sm the substitution mappings
306 * @return a List of Software Version Strings
307 * @throws ToscaToCatalogException the tosca to catalog exception
309 @SuppressWarnings("unchecked")
310 List<String> extractSoftwareVersions(SubstitutionMappings sm) throws ToscaToCatalogException {
311 applicationLogger.debug("Extracting software versions from " + sm);
313 List<NodeTemplate> imagesNodes = sm.getNodeTemplates().stream()
314 .filter(nodeTemplate -> nodeTemplate.getPropertyValue(IMAGES) != null).collect(Collectors.toList());
316 if (imagesNodes != null && !imagesNodes.isEmpty()) {
317 return imagesNodes.stream()
318 .flatMap(imagesNode -> ((Map<String, Object>) imagesNode.getPropertyValue(IMAGES)) //
319 .entrySet().stream())
320 .map(property -> findSoftwareVersion((Map<String, Object>) property.getValue()))
321 .collect(Collectors.toList());
323 throw new ToscaToCatalogException("No software versions could be found for this CSAR file");
328 * Get the first software version value from the properties Map.
330 * @param image the properties Map
331 * @return the software version value as a String
333 private String findSoftwareVersion(Map<String, Object> image) {
334 applicationLogger.debug("Finding " + SOFTWARE_VERSION + " from " + image);
336 return (String) image.entrySet().stream()//
337 .filter(entry -> SOFTWARE_VERSION.equals(entry.getKey())) //
338 .map(Entry::getValue).findFirst().orElse(null);