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 java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.nio.charset.StandardCharsets;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Optional;
31 import java.util.stream.Collectors;
32 import org.apache.commons.collections.MapUtils;
33 import org.apache.commons.io.FilenameUtils;
34 import org.apache.commons.io.IOUtils;
35 import org.onap.sdc.tosca.services.YamlUtil;
36 import org.openecomp.core.utilities.file.FileContentHandler;
37 import org.openecomp.core.utilities.file.FileUtils;
38 import org.openecomp.sdc.be.model.ArtifactDefinition;
39 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.builder.NsdToscaMetadataBuilder;
40 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.exception.VnfDescriptorException;
41 import org.openecomp.sdc.be.plugins.etsi.nfv.nsd.model.VnfDescriptor;
42 import org.openecomp.sdc.common.zip.exception.ZipException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.stereotype.Component;
46 import org.yaml.snakeyaml.Yaml;
49 * Implementation of a VNF Descriptor Generator
51 @Component("vnfPackageGenerator")
52 public class VnfDescriptorGeneratorImpl implements VnfDescriptorGenerator {
54 private static final Logger LOGGER = LoggerFactory.getLogger(VnfDescriptorGeneratorImpl.class);
55 private static final String SPACE_REGEX = "\\s+";
56 private static final String CSAR = "csar";
57 private static final String COLON = ":";
58 private static final String EMPTY_STRING = "";
59 private static final String SLASH = "/";
60 private static final String DEFINITIONS_DIRECTORY = "Definitions";
61 private static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
63 public Optional<VnfDescriptor> generate(final String name,
64 final ArtifactDefinition onboardedPackageArtifact)
65 throws VnfDescriptorException {
66 if (!isACsarArtifact(onboardedPackageArtifact)) {
67 return Optional.empty();
70 final FileContentHandler fileContentHandler;
72 fileContentHandler = FileUtils.getFileContentMapFromZip(onboardedPackageArtifact.getPayloadData());
73 } catch (final ZipException e) {
74 final String errorMsg = String
75 .format("Could not unzip artifact '%s' content", onboardedPackageArtifact.getArtifactName());
76 throw new VnfDescriptorException(errorMsg, e);
79 if (MapUtils.isEmpty(fileContentHandler.getFiles())) {
80 return Optional.empty();
82 final String mainDefinitionFile;
84 mainDefinitionFile = getMainFilePathFromMetaFile(fileContentHandler).orElse(null);
85 } catch (final IOException e) {
86 final String errorMsg = String
87 .format("Could not read main definition file of artifact '%s'",
88 onboardedPackageArtifact.getArtifactName());
89 throw new VnfDescriptorException(errorMsg, e);
91 LOGGER.debug("found main file: {}", mainDefinitionFile);
92 if (mainDefinitionFile == null) {
93 return Optional.empty();
95 final VnfDescriptor vnfDescriptor = new VnfDescriptor();
96 vnfDescriptor.setName(name);
97 final String vnfdFileName = FilenameUtils.getName(mainDefinitionFile);
99 vnfDescriptor.setVnfdFileName(vnfdFileName);
100 vnfDescriptor.setDefinitionFiles(getFiles(fileContentHandler, mainDefinitionFile));
101 vnfDescriptor.setNodeType(getNodeType(getFileContent(fileContentHandler, mainDefinitionFile)));
103 return Optional.of(vnfDescriptor);
106 private static boolean isACsarArtifact(final ArtifactDefinition definition) {
107 return definition.getPayloadData() != null && definition.getArtifactName() != null && CSAR
108 .equalsIgnoreCase(FilenameUtils.getExtension(definition.getArtifactName()));
111 private Map<String, byte[]> getFiles(final FileContentHandler fileContentHandler, final String filePath) {
112 final Map<String, byte[]> files = new HashMap<>();
114 final byte[] fileContent = fileContentHandler.getFileContent(filePath);
116 if (fileContent != null) {
117 final String mainYmlFile = new String(fileContent);
118 LOGGER.debug("file content: {}", mainYmlFile);
120 files.put(appendDefinitionDirPath(filePath.substring(filePath.lastIndexOf(SLASH) + 1)),
121 getVnfdWithoutTopologyTemplate(fileContent));
122 final List<Object> imports = getImportFilesPath(mainYmlFile);
123 LOGGER.info("found imports {}", imports);
124 for (final Object importObject : imports) {
125 if (importObject != null) {
126 final String importFilename = importObject.toString();
127 final String importFileFullPath = appendDefinitionDirPath(importFilename);
128 final byte[] importFileContent = fileContentHandler.getFileContent(importFileFullPath);
129 files.put(appendDefinitionDirPath(importFilename), importFileContent);
136 private String getFileContent(final FileContentHandler fileContentHandler, final String filePath) {
137 final byte[] fileContent = fileContentHandler.getFileContent(filePath);
139 if (fileContent != null) {
140 return new String(fileContent);
145 private Optional<String> getMainFilePathFromMetaFile(final FileContentHandler fileContentHandler)
147 final Map<String, String> metaFileContent = getMetaFileContent(fileContentHandler);
148 final String mainFile = metaFileContent.get(NsdToscaMetadataBuilder.ENTRY_DEFINITIONS);
149 if (mainFile != null) {
150 return Optional.of(mainFile.replaceAll(SPACE_REGEX, EMPTY_STRING));
152 LOGGER.error("{} entry not found in {}", NsdToscaMetadataBuilder.ENTRY_DEFINITIONS, TOSCA_META_PATH);
153 return Optional.empty();
156 private Map<String, String> getMetaFileContent(final FileContentHandler fileContentHandler)
158 final InputStream inputStream = fileContentHandler.getFileContentAsStream(TOSCA_META_PATH);
159 if (inputStream == null) {
160 throw new FileNotFoundException("Unable find " + TOSCA_META_PATH + " file");
162 final List<String> lines = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
164 return lines.stream().map(str -> str.split(COLON))
165 .collect(Collectors.toMap(str -> str[0], str -> str.length > 1 ? str[1] : EMPTY_STRING));
168 private String appendDefinitionDirPath(final String filename) {
169 return DEFINITIONS_DIRECTORY + SLASH + filename;
172 private List<Object> getImportFilesPath(final String mainYmlFile) {
173 final Map<Object, Object> fileContentMap = new YamlUtil().yamlToObject(mainYmlFile, Map.class);
175 final Object importsObject = fileContentMap.get("imports");
177 if (importsObject instanceof List) {
178 return (List<Object>) importsObject;
180 return Collections.emptyList();
183 private byte[] getVnfdWithoutTopologyTemplate(final byte[] vnfdFileContent) {
184 final Yaml yaml = new Yaml();
185 final Map<String, Object> toscaFileContent = (Map<String, Object>) yaml.load(new String(vnfdFileContent));
186 toscaFileContent.remove("topology_template");
188 return yaml.dumpAsMap(toscaFileContent).getBytes();
191 private String getNodeType(final String mainYmlFile) {
192 final Map<Object, Object> fileContentMap = new YamlUtil().yamlToObject(mainYmlFile, Map.class);
194 final Object nodeTypesObject = fileContentMap.get("node_types");
195 if (nodeTypesObject instanceof Map
196 && ((Map<String, Object>) nodeTypesObject).size() == 1) {
197 return ((Map<String, Object>) nodeTypesObject).keySet().iterator().next();