Update to sdc-tosca 1.4.5
[aai/babel.git] / src / main / java / org / onap / aai / babel / csar / vnfcatalog / VnfVendorImageExtractor.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.aai.babel.csar.vnfcatalog;
23
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;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Objects;
32 import java.util.function.Consumer;
33 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.enums.SdcTypes;
43 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
44 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
45 import org.onap.sdc.toscaparser.api.NodeTemplate;
46 import org.onap.sdc.toscaparser.api.SubstitutionMappings;
47
48 /**
49  * This class is responsible for extracting Virtual Network Function (VNF) information from a TOSCA 1.1 CSAR package.
50  *
51  * <p>
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.
54  * </p>
55  *
56  * <p>
57  * A VNF is a virtualized functional capability (e.g. a Router) that may be defined by an external Vendor. Within the
58  * model defined by the TOSCA files the VNF is considered to be a Resource (part of a Service).
59  * </p>
60  *
61  * <p>
62  * A VNF is specified by a Topology Template. Because this TOSCA construct does not allow properties to be defined
63  * directly, Node Templates are defined (identified by a VNF type value) storing the VNF metadata and properties.
64  * </p>
65  *
66  * <p>
67  * A VNF may be composed of multiple images, each running on its own Virtual Machine. The function of a deployed image
68  * is designated the Virtual Function Component (VFC). A VFC is a sub-component of the VNF. A VFC may have different
69  * "Flavors" (see the Deployment Flavors description below).
70  * </p>
71  *
72  * <p>
73  * An individual VNF (template) may be deployed with varying configuration values, according to
74  * environment/customer/business needs. For example, a VNF deployed in a testing environment would typically use fewer
75  * computational resources than in a production setting.
76  * </p>
77  *
78  * <p>
79  * A Vendor may define one or more "Deployment Flavors". A Deployment Flavor describes a set of pre-determined
80  * parameterised values for a specific aspect of the model. Within the TOSCA model there is a DeploymentFlavor
81  * definition, which has its own data types, and also an ImageInfo definition.
82  * </p>
83  */
84 public class VnfVendorImageExtractor {
85
86     private static LogHelper applicationLogger = LogHelper.INSTANCE;
87
88     // The following constants describe the expected naming conventions for TOSCA Node Templates which
89     // store the VNF configuration and the VFC data items.
90
91     // The name of the property (for a VNF Configuration type) storing the Images Information
92     private static final String IMAGES = "images";
93
94     // Name of property key that contains the value of the software version
95     private static final String SOFTWARE_VERSION = "software_version";
96
97     // The name of the property (for a VNF Configuration type) storing the Vendor Information
98     private static final String VNF_CONF_TYPE_PROPERTY_VENDOR_INFO_CONTAINER = "allowed_flavors";
99
100     // Name of property key that contains the value of model of the Vendor application
101     private static final String VENDOR_MODEL = "vendor_model";
102
103     /**
104      * This method is responsible for parsing the vnfConfiguration entity in the same topology_template (there's an
105      * assumption that there's only one per file, awaiting verification).
106      *
107      * <p>
108      * It is possible that CSAR file does not contain a vnfConfiguration and this is valid.
109      * </p>
110      *
111      * <p>
112      * Where multiple vnfConfigurations are found an exception will be thrown.
113      * </p>
114      *
115      * <p>
116      * The ASDC model anticipates the following permutations of vnfConfiguration and multiflavorVFC:
117      *
118      * <pre>
119      * <ol>
120      * <li>Single vnfConfiguration, single multiFlavorVFC with multiple images.</li>
121      * <li>Single vnfConfiguration, multi multiFlavorVFC with single images.</li>
122      * </ol>
123      * </pre>
124      *
125      * All ImageInfo sections found apply to all "Deployment Flavors", therefore we can apply a cross product of
126      * "Deployment Flavors" x "ImageInfo"
127      * </p>
128      *
129      * @param csar compressed format that stores multiple TOSCA files and in particular a vnfConfiguration
130      * @return BabelArtifact VendorImageConfiguration objects created during processing represented as the Babel service
131      *         public data structure
132      * @throws ToscaToCatalogException if the CSAR content is not valid
133      */
134     public BabelArtifact extract(byte[] csar) throws ToscaToCatalogException {
135         StopWatch stopwatch = new StopWatch();
136         stopwatch.start();
137
138         Objects.requireNonNull(csar, "A CSAR file must be supplied");
139         applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Extracting VNF Configuration data");
140
141         List<VendorImageConfiguration> vendorImageConfigurations;
142         Path path = null;
143
144         try {
145             path = createTempFile(csar);
146             vendorImageConfigurations = createVendorImageConfigurations(path.toAbsolutePath().toString());
147         } catch (InvalidNumberOfNodesException | IOException | SdcToscaParserException e) {
148             throw new ToscaToCatalogException(
149                     "An error occurred trying to get the VNF Catalog from a CSAR file. " + e.getLocalizedMessage(), e);
150         } finally {
151             if (path != null) {
152                 FileUtils.deleteQuietly(path.toFile());
153             }
154         }
155
156         applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT, vendorImageConfigurations.toString());
157         applicationLogger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0));
158
159         return ConfigurationsToBabelArtifactConverter.convert(vendorImageConfigurations);
160     }
161
162     /**
163      * Creates a temporary file to store the CSAR content.
164      *
165      * @param bytes the CSAR content
166      * @return Path to a temporary file containing the CSAR bytes
167      * @throws IOException if an I/O error occurs or the temporary-file directory does not exist
168      */
169     private Path createTempFile(byte[] bytes) throws IOException {
170         Path path = Files.createTempFile("temp", ".csar");
171         applicationLogger.debug("Created temp file " + path);
172         Files.write(path, bytes);
173         return path;
174     }
175
176     /**
177      * Build VNF Vendor Image Configurations for the VNF Configuration node (if present) in the CSAR file referenced by
178      * the supplied Path.
179      *
180      * @param csarFilepath the path to the CSAR file
181      * @return a List of Vendor Image Configurations
182      * @throws SdcToscaParserException
183      * @throws ToscaToCatalogException
184      * @throws InvalidNumberOfNodesException
185      */
186     private List<VendorImageConfiguration> createVendorImageConfigurations(String csarFilepath)
187             throws SdcToscaParserException, ToscaToCatalogException, InvalidNumberOfNodesException {
188         List<VendorImageConfiguration> vendorImageConfigurations = new ArrayList<>();
189
190         ISdcCsarHelper csarHelper = SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarFilepath);
191         NodeTemplate vnfConfigurationNode = findVnfConfigurationNode(csarHelper);
192
193         applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
194                 String.format("Found VNF Configuration node \"%s\"", vnfConfigurationNode));
195
196         if (vnfConfigurationNode != null) {
197             for (NodeTemplate node : csarHelper.getServiceVfList()) {
198                 vendorImageConfigurations.addAll(buildVendorImageConfigurations(vnfConfigurationNode, node));
199             }
200         }
201
202         return vendorImageConfigurations;
203     }
204
205     /**
206      * Find VNF configuration node.
207      *
208      * @param csarHelper the csar helper
209      * @return the node template
210      * @throws InvalidNumberOfNodesException
211      */
212     private NodeTemplate findVnfConfigurationNode(ISdcCsarHelper csarHelper) throws InvalidNumberOfNodesException {
213         List<NodeTemplate> nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.VF);
214         applicationLogger.debug(nodeTemplates.toString());
215
216         List<NodeTemplate> configNodes = nodeTemplates.stream() //
217                 .map(serviceNodeTemplate -> {
218                     String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNodeTemplate);
219                     applicationLogger.debug(serviceNodeTemplate + " Customization UUID is " + uuid);
220                     return csarHelper.getVnfConfig(uuid);
221                 }) //
222                 .filter(Objects::nonNull) //
223                 .collect(Collectors.toList());
224
225         if (configNodes.size() > 1) {
226             throw new InvalidNumberOfNodesException("Only one vnf configuration node is allowed however "
227                     + configNodes.size() + " nodes were found in the csar.");
228         }
229
230         return configNodes.size() == 1 ? configNodes.get(0) : null;
231     }
232
233     /**
234      * Builds the Vendor image configurations.
235      *
236      * @param vendorInfoNode the vendor info node
237      * @param node the node
238      * @return the list
239      * @throws ToscaToCatalogException if there are no software versions
240      */
241     private List<VendorImageConfiguration> buildVendorImageConfigurations(NodeTemplate vendorInfoNode,
242             NodeTemplate node) throws ToscaToCatalogException {
243         List<VendorImageConfiguration> vendorImageConfigurations = new ArrayList<>();
244
245         List<String> softwareVersions = extractSoftwareVersions(node.getSubMappingToscaTemplate());
246
247         Consumer<? super Pair<String, String>> buildConfigurations =
248                 vi -> vendorImageConfigurations.addAll(softwareVersions.stream() //
249                         .map(sv -> (new VendorImageConfiguration(vi.getRight(), vi.getLeft(), sv)))
250                         .collect(Collectors.toList()));
251
252         String resourceVendor = node.getMetaData().getValue("resourceVendor");
253
254         applicationLogger.debug("Resource Vendor " + resourceVendor);
255
256         buildVendorInfo(resourceVendor, vendorInfoNode).forEach(buildConfigurations);
257
258         applicationLogger.info(ApplicationMsgs.DISTRIBUTION_EVENT,
259                 "Built " + vendorImageConfigurations.size() + " Vendor Image Configurations");
260
261         return vendorImageConfigurations;
262     }
263
264     /**
265      * Builds the Vendor info.
266      *
267      * @param resourceVendor the resource vendor
268      * @param vendorInfoNode the vendor info node
269      * @return the list
270      */
271     @SuppressWarnings("unchecked")
272     private List<Pair<String, String>> buildVendorInfo(String resourceVendor, NodeTemplate vendorInfoNode) {
273         Map<String, Object> otherFlavorProperties =
274                 (Map<String, Object>) vendorInfoNode.getPropertyValue(VNF_CONF_TYPE_PROPERTY_VENDOR_INFO_CONTAINER);
275
276         return otherFlavorProperties.keySet().stream()
277                 .map(key -> createVendorInfoPair((Map<String, Object>) otherFlavorProperties.get(key), resourceVendor))
278                 .collect(Collectors.toList());
279     }
280
281     /**
282      * Creates the Vendor info pair.
283      *
284      * @param otherFlavor the other flavor
285      * @param resourceVendor the resource Vendor
286      * @return the pair
287      */
288     private Pair<String, String> createVendorInfoPair(Map<String, Object> otherFlavor, String resourceVendor) {
289         @SuppressWarnings("unchecked")
290         String vendorModel = otherFlavor.entrySet().stream() //
291                 .filter(entry -> "vendor_info".equals(entry.getKey()))
292                 .map(e -> ((Map<String, String>) e.getValue()).get(VENDOR_MODEL)) //
293                 .findFirst().orElse(null);
294
295         applicationLogger.debug("Creating Vendor info pair object for vendorModel = " + vendorModel
296                 + " and resourceVendor = " + resourceVendor);
297
298         return new ImmutablePair<>(resourceVendor, vendorModel);
299     }
300
301     /**
302      * Extract software versions.
303      *
304      * @param sm the substitution mappings
305      * @return a List of Software Version Strings
306      * @throws ToscaToCatalogException the tosca to catalog exception
307      */
308     @SuppressWarnings("unchecked")
309     List<String> extractSoftwareVersions(SubstitutionMappings sm) throws ToscaToCatalogException {
310         applicationLogger.debug("Extracting software versions from " + sm);
311
312         List<NodeTemplate> imagesNodes = sm.getNodeTemplates().stream()
313                 .filter(nodeTemplate -> nodeTemplate.getPropertyValue(IMAGES) != null).collect(Collectors.toList());
314
315         if (imagesNodes != null && !imagesNodes.isEmpty()) {
316             return imagesNodes.stream()
317                     .flatMap(imagesNode -> ((Map<String, Object>) imagesNode.getPropertyValue(IMAGES)) //
318                             .entrySet().stream())
319                     .map(property -> findSoftwareVersion((Map<String, Object>) property.getValue()))
320                     .collect(Collectors.toList());
321         } else {
322             throw new ToscaToCatalogException("No software versions could be found for this CSAR file");
323         }
324     }
325
326     /**
327      * Get the first software version value from the properties Map.
328      *
329      * @param image the properties Map
330      * @return the software version value as a String
331      */
332     private String findSoftwareVersion(Map<String, Object> image) {
333         applicationLogger.debug("Finding " + SOFTWARE_VERSION + " from " + image);
334
335         return (String) image.entrySet().stream()//
336                 .filter(entry -> SOFTWARE_VERSION.equals(entry.getKey())) //
337                 .map(Entry::getValue).findFirst().orElse(null);
338     }
339 }