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=========================================================
21 package org.onap.aai.babel.csar.vnfcatalog;
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.util.ArrayList;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Objects;
31 import java.util.function.Consumer;
32 import java.util.stream.Collectors;
34 import org.apache.commons.io.FileUtils;
35 import org.apache.commons.lang3.time.StopWatch;
36 import org.apache.commons.lang3.tuple.ImmutablePair;
37 import org.apache.commons.lang3.tuple.Pair;
38 import org.onap.aai.babel.logging.ApplicationMsgs;
39 import org.onap.aai.babel.logging.LogHelper;
40 import org.onap.aai.babel.service.data.BabelArtifact;
41 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
42 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
43 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
44 import org.onap.sdc.tosca.parser.impl.SdcTypes;
45 import org.onap.sdc.toscaparser.api.NodeTemplate;
46 import org.onap.sdc.toscaparser.api.SubstitutionMappings;
49 * This class is responsible for extracting Virtual Network Function (VNF) information from a TOSCA 1.1 CSAR package.
52 * CSAR is a compressed format that stores multiple TOSCA files. Each TOSCA file may define Topology Templates and/or
53 * Node Templates along with other model data.
56 * A VNF is a virtualized functional capability (e.g. a Router) that may be defined by an external Vendor. Within the
57 * model defined by the TOSCA files the VNF is considered to be a Resource (part of a Service).
60 * A VNF is specified by a Topology Template. Because this TOSCA construct does not allow properties to be defined
61 * directly, Node Templates are defined (identified by a VNF type value) storing the VNF metadata and properties.
64 * A VNF may be composed of multiple images, each running on its own Virtual Machine. The function of a deployed image
65 * is designated the Virtual Function Component (VFC). A VFC is a sub-component of the VNF. A VFC may have different
66 * "Flavors" (see the Deployment Flavors description below).
69 * An individual VNF (template) may be deployed with varying configuration values, according to
70 * environment/customer/business needs. For example, a VNF deployed in a testing environment would typically use fewer
71 * computational resources than in a production setting.
74 * A Vendor may define one or more "Deployment Flavors". A Deployment Flavor describes a set of pre-determined
75 * parameterised values for a specific aspect of the model. Within the TOSCA model there is a DeploymentFlavor
76 * definition, which has its own data types, and also an ImageInfo definition.
78 public class VnfVendorImageExtractor {
79 private static LogHelper applicationLogger = LogHelper.INSTANCE;
81 private static final String AN_ERROR_OCCURRED = "An error occurred trying to get the vnf catalog from a csar file.";
83 // The following constants describe the expected naming conventions for TOSCA Node Templates which
85 // configuration and the VFC data items.
87 // The name of the property (for a VNF Configuration type) storing the Images Information
88 private static final String IMAGES = "images";
90 // Name of property key that contains the value of the software version
91 private static final String SOFTWARE_VERSION = "software_version";
93 // The name of the property (for a VNF Configuration type) storing the Vendor Information
94 private static final String VNF_CONF_TYPE_PROPERTY_VENDOR_INFO_CONTAINER = "allowed_flavors";
96 // Name of property key that contains the value of model of the vendor application
97 private static final String VENDOR_MODEL = "vendor_model";
100 * This method is responsible for parsing the vnfConfiguration entity in the same topology_template (there's an
101 * assumption that there's only one per file, awaiting verification).
104 * It is possible that csar file does not contain a vnfConfiguration and this is valid.
107 * Where multiple vnfConfigurations are found an exception will be thrown.
110 * The ASDC model anticipates the following permutations of vnfConfiguration and multiflavorVFC:
114 * <li>Single vnfConfiguration, single multiFlavorVFC with multiple images.</li>
115 * <li>Single vnfConfiguration, multi multiFlavorVFC with single images.</li>
119 * All ImageInfo sections found apply to all "Deployment Flavors", therefore we can apply a cross product of
120 * "Deployment Flavors" x "ImageInfo" - concretely
122 * @param csar compressed format that stores multiple TOSCA files and in particular a vnfConfiguration
123 * @return BabelArtifact VendorImageConfiguration objects created during processing represented as the Babel service
124 * public data structure
126 public BabelArtifact extract(byte[] csar) throws ToscaToCatalogException {
127 StopWatch stopwatch = new StopWatch();
130 Objects.requireNonNull(csar, "A CSAR file must be supplied");
132 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
133 "Starting to find and extract any vnf configuration data");
135 List<VendorImageConfiguration> vendorImageConfigurations;
139 path = createTempFile(csar);
140 vendorImageConfigurations = createVendorImageConfigurations(path.toAbsolutePath().toString());
141 } catch (InvalidNumberOfNodesException | IOException | SdcToscaParserException e) {
142 throw new ToscaToCatalogException(AN_ERROR_OCCURRED + " " + e.getLocalizedMessage(), e);
145 FileUtils.deleteQuietly(path.toFile());
149 String msg = vendorImageConfigurations.isEmpty() ? "No Vnf Configuration has been found in the csar"
150 : "Vnf Configuration has been found in the csar";
151 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT, msg);
152 applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
154 return ConfigurationsToBabelArtifactConverter.convert(vendorImageConfigurations);
157 private Path createTempFile(byte[] bytes) throws IOException {
158 applicationLogger.debug("Creating temp file on file system for the csar");
159 Path path = Files.createTempFile("temp", ".csar");
160 Files.write(path, bytes);
164 private List<VendorImageConfiguration> createVendorImageConfigurations(String csarFilepath)
165 throws SdcToscaParserException, ToscaToCatalogException, InvalidNumberOfNodesException {
166 applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
167 "Getting instance of ISdcCsarHelper to use in finding vnf configuration data");
168 ISdcCsarHelper csarHelper = SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarFilepath);
170 List<VendorImageConfiguration> vendorImageConfigurations = new ArrayList<>();
171 NodeTemplate vnfConfigurationNode = findVnfConfigurationNode(csarHelper);
173 if (vnfConfigurationNode != null) {
174 List<NodeTemplate> serviceVfNodes = csarHelper.getServiceVfList();
176 for (NodeTemplate node : serviceVfNodes) {
177 vendorImageConfigurations.addAll(buildVendorImageConfigurations(vnfConfigurationNode, node));
181 return vendorImageConfigurations;
184 private NodeTemplate findVnfConfigurationNode(ISdcCsarHelper csarHelper) throws InvalidNumberOfNodesException {
185 applicationLogger.debug("Tryng to find the vnf configuration node");
187 List<NodeTemplate> configNodes =
188 csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.VF).stream().map(serviceNodeTemplate -> {
189 String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNodeTemplate);
190 applicationLogger.debug("Node Template Customization Uuid is " + uuid);
191 return csarHelper.getVnfConfig(uuid);
192 }).filter(Objects::nonNull).collect(Collectors.toList());
194 if (configNodes.size() > 1) {
195 throw new InvalidNumberOfNodesException("Only one vnf configuration node is allowed however "
196 + configNodes.size() + " nodes were found in the csar.");
199 return configNodes.size() == 1 ? configNodes.get(0) : null;
202 private List<VendorImageConfiguration> buildVendorImageConfigurations(NodeTemplate vendorInfoNode,
203 NodeTemplate node) throws ToscaToCatalogException {
204 List<VendorImageConfiguration> vendorImageConfigurations = new ArrayList<>();
206 List<String> softwareVersions = extractSoftwareVersions(node.getSubMappingToscaTemplate());
208 Consumer<? super Pair<String, String>> buildConfigurations = vi -> vendorImageConfigurations.addAll(
209 softwareVersions.stream().map(sv -> (new VendorImageConfiguration(vi.getRight(), vi.getLeft(), sv)))
210 .collect(Collectors.toList()));
212 String resourceVendor = node.getMetaData().getValue("resourceVendor");
213 buildVendorInfo(resourceVendor, vendorInfoNode).forEach(buildConfigurations);
215 return vendorImageConfigurations;
218 @SuppressWarnings("unchecked")
219 private List<Pair<String, String>> buildVendorInfo(String resourceVendor, NodeTemplate vendorInfoNode) {
220 Map<String, Object> otherFlavorProperties =
221 (Map<String, Object>) vendorInfoNode.getPropertyValue(VNF_CONF_TYPE_PROPERTY_VENDOR_INFO_CONTAINER);
223 return otherFlavorProperties.keySet().stream()
224 .map(key -> createVendorInfoPair((Map<String, Object>) otherFlavorProperties.get(key), resourceVendor))
225 .collect(Collectors.toList());
228 private Pair<String, String> createVendorInfoPair(Map<String, Object> otherFlavor, String resourceVendor) {
229 @SuppressWarnings("unchecked")
230 String vendorModel = otherFlavor.entrySet().stream() //
231 .filter(entry -> "vendor_info".equals(entry.getKey()))
232 .map(e -> ((Map<String, String>) e.getValue()).get(VENDOR_MODEL)) //
233 .findFirst().orElse(null);
235 applicationLogger.debug("Creating vendor info pair object for vendorModel = " + vendorModel
236 + " and resourceVendor = " + resourceVendor);
238 return new ImmutablePair<>(resourceVendor, vendorModel);
241 @SuppressWarnings("unchecked")
242 private List<String> extractSoftwareVersions(SubstitutionMappings sm) throws ToscaToCatalogException {
243 applicationLogger.debug("Trying to extract the software versions for the vnf configuration");
245 List<NodeTemplate> imagesNodes = sm.getNodeTemplates().stream()
246 .filter(nodeTemplate -> nodeTemplate.getPropertyValue(IMAGES) != null).collect(Collectors.toList());
248 if (imagesNodes != null && !imagesNodes.isEmpty()) {
249 applicationLogger.debug("Found NodeTemplates containing properties with a key called 'images'");
250 return imagesNodes.stream()
251 .flatMap(imagesNode -> ((Map<String, Object>) imagesNode.getPropertyValue(IMAGES)) //
252 .entrySet().stream())
253 .map(property -> findSoftwareVersion((Map<String, Object>) property.getValue()))
254 .collect(Collectors.toList());
256 throw new ToscaToCatalogException("No software versions could be found for this csar file");
260 private String findSoftwareVersion(Map<String, Object> image) {
261 applicationLogger.debug("Getting the software version value from the map of image properties");
263 return (String) image.entrySet().stream().filter(entry -> SOFTWARE_VERSION.equals(entry.getKey()))
264 .map(Entry::getValue).findFirst().orElse(null);