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