Fix setting vendor release for VSP with model
[sdc.git] / openecomp-be / lib / openecomp-sdc-vendor-software-product-lib / openecomp-sdc-vendor-software-product-core / src / main / java / org / openecomp / sdc / vendorsoftwareproduct / services / impl / etsi / ETSIServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019, Nordix Foundation. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi;
21
22 import static org.openecomp.sdc.tosca.csar.CSARConstants.ARTIFACTS_FOLDER;
23 import static org.openecomp.sdc.tosca.csar.CSARConstants.ETSI_VERSION_2_6_1;
24 import static org.openecomp.sdc.tosca.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_MF_FILE_NAME;
25 import static org.openecomp.sdc.tosca.csar.CSARConstants.MANIFEST_PNF_METADATA;
26 import static org.openecomp.sdc.tosca.csar.CSARConstants.TOSCA_META_ORIG_PATH_FILE_NAME;
27 import static org.openecomp.sdc.tosca.csar.ManifestTokenType.COMPATIBLE_SPECIFICATION_VERSIONS;
28 import static org.openecomp.sdc.tosca.csar.ToscaMetaEntryVersion261.ENTRY_DEFINITIONS;
29 import static org.openecomp.sdc.tosca.csar.ToscaMetaEntryVersion261.ETSI_ENTRY_CHANGE_LOG;
30 import static org.openecomp.sdc.tosca.csar.ToscaMetaEntryVersion261.ETSI_ENTRY_MANIFEST;
31 import static org.openecomp.sdc.tosca.csar.ToscaMetadataFileInfo.TOSCA_META_PATH_FILE_NAME;
32
33 import com.vdurmont.semver4j.Semver;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.Arrays;
39 import java.util.Comparator;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Objects;
44 import java.util.Optional;
45 import java.util.stream.Collectors;
46 import org.apache.commons.collections.MapUtils;
47 import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
48 import org.onap.sdc.tosca.services.YamlUtil;
49 import org.openecomp.core.utilities.file.FileContentHandler;
50 import org.openecomp.sdc.be.config.NonManoArtifactType;
51 import org.openecomp.sdc.be.config.NonManoConfiguration;
52 import org.openecomp.sdc.be.config.NonManoConfigurationManager;
53 import org.openecomp.sdc.be.config.NonManoFolderType;
54 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
55 import org.openecomp.sdc.logging.api.Logger;
56 import org.openecomp.sdc.logging.api.LoggerFactory;
57 import org.openecomp.sdc.tosca.csar.Manifest;
58 import org.openecomp.sdc.tosca.csar.OnboardingToscaMetadata;
59 import org.openecomp.sdc.tosca.csar.SOL004ManifestOnboarding;
60 import org.openecomp.sdc.tosca.csar.ToscaMetadata;
61 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
62
63 public class ETSIServiceImpl implements ETSIService {
64
65     private static final Logger LOGGER = LoggerFactory.getLogger(ETSIServiceImpl.class);
66     private final NonManoConfiguration nonManoConfiguration;
67
68     public ETSIServiceImpl() {
69         nonManoConfiguration = NonManoConfigurationManager.getInstance().getNonManoConfiguration();
70     }
71
72     public ETSIServiceImpl(final NonManoConfiguration nonManoConfiguration) {
73         this.nonManoConfiguration = nonManoConfiguration;
74     }
75
76     @Override
77     public boolean isSol004WithToscaMetaDirectory(FileContentHandler handler) throws IOException {
78         final Map<String, byte[]> templates = handler.getFiles();
79         return isMetaFilePresent(templates) && hasMetaMandatoryEntries(getMetadata(handler));
80     }
81
82     @Override
83     public Optional<Map<String, Path>> moveNonManoFileToArtifactFolder(final FileContentHandler handler) throws IOException {
84         final Manifest manifest = loadManifest(handler);
85         final Path originalManifestPath;
86         try {
87             originalManifestPath = getOriginalManifestPath(handler);
88         } catch (final IOException ex) {
89             if (LOGGER.isErrorEnabled()) {
90                 LOGGER.error("An error occurred while getting the original manifest path", ex);
91             }
92             throw ex;
93         }
94         final Map<String, Path> fromToPathMap = new HashMap<>();
95         final Map<String, NonManoFolderType> nonManoKeyFolderMapping = nonManoConfiguration.getNonManoKeyFolderMapping();
96         manifest.getNonManoSources().entrySet().stream()
97             .filter(manifestNonManoSourceEntry -> nonManoKeyFolderMapping.containsKey(manifestNonManoSourceEntry.getKey()))
98             .forEach(manifestNonManoSourceEntry -> {
99                 final NonManoFolderType nonManoFolderType = nonManoKeyFolderMapping.get(manifestNonManoSourceEntry.getKey());
100                 final List<String> nonManoFileList = manifestNonManoSourceEntry.getValue();
101                 final Map<String, Path> actualFromToPathMap = nonManoFileList.stream().map(nonManoFilePath -> {
102                     final Path normalizedFilePath = resolveNonManoFilePath(originalManifestPath, nonManoFilePath);
103                     final Optional<Path> changedPath = updateNonManoPathInHandler(handler, nonManoFolderType, normalizedFilePath);
104                     if (changedPath.isPresent()) {
105                         final Map<String, Path> fromAndToPathMap = new HashMap<>();
106                         fromAndToPathMap.put(nonManoFilePath, Paths.get(ARTIFACTS_FOLDER).resolve(changedPath.get()));
107                         return fromAndToPathMap;
108                     }
109                     return null;
110                 }).filter(Objects::nonNull).collect(Collectors.toMap(fromToPathEntry -> fromToPathEntry.keySet().iterator().next(),
111                     fromToPathEntry -> fromToPathEntry.values().iterator().next()));
112                 fromToPathMap.putAll(actualFromToPathMap);
113             });
114         return MapUtils.isEmpty(fromToPathMap) ? Optional.empty() : Optional.of(fromToPathMap);
115     }
116
117     /**
118      * Resolves the non mano file path based on the original manifest path of the onboarded package.
119      *
120      * @param originalManifestPath The original path from the onboarded package manifest
121      * @param nonManoFilePath      The non mano file path defined in the manifest
122      * @return The resolved and normalized non mano path.
123      */
124     private Path resolveNonManoFilePath(final Path originalManifestPath, final String nonManoFilePath) {
125         return originalManifestPath.resolve(Paths.get(nonManoFilePath)).normalize();
126     }
127
128     /**
129      * Updates the non mano file path in the package file handler based on the non mano type.
130      *
131      * @param handler                 The package file handler
132      * @param nonManoFolderType       The Non Mano type of the file to update
133      * @param nonManoOriginalFilePath The Non Mano file original path
134      * @return The new file path if it was updated in the package file handler, otherwise empty.
135      */
136     private Optional<Path> updateNonManoPathInHandler(final FileContentHandler handler, final NonManoFolderType nonManoFolderType,
137                                                       final Path nonManoOriginalFilePath) {
138         final Path fixedSourcePath = fixNonManoPath(nonManoOriginalFilePath);
139         if (handler.containsFile(fixedSourcePath.toString())) {
140             final Path newNonManoPath = Paths
141                 .get(nonManoFolderType.getType(), nonManoFolderType.getLocation(), fixedSourcePath.getFileName().toString());
142             if (!handler.containsFile(newNonManoPath.toString())) {
143                 handler.addFile(newNonManoPath.toString(), handler.remove(fixedSourcePath.toString()));
144                 return Optional.of(newNonManoPath);
145             }
146         }
147         return Optional.empty();
148     }
149
150     /**
151      * Fix the original non mano file path to the ONAP package file path.
152      * <p>
153      * Non mano artifacts that were inside the {@link org.openecomp.sdc.tosca.csar.CSARConstants#ARTIFACTS_FOLDER} path are not moved when parsed to
154      * ONAP package, but the Manifest declaration can still have the {@link org.openecomp.sdc.tosca.csar.CSARConstants#ARTIFACTS_FOLDER} reference in
155      * it. If so, that reference is removed.
156      *
157      * @param nonManoOriginalFilePath The original non mano file path
158      * @return The non mano fixed path to ONAP package structure.
159      */
160     private Path fixNonManoPath(final Path nonManoOriginalFilePath) {
161         final Path rootArtifactsPath = Paths.get("/", ARTIFACTS_FOLDER);
162         if (nonManoOriginalFilePath.startsWith(rootArtifactsPath)) {
163             return rootArtifactsPath.relativize(nonManoOriginalFilePath);
164         }
165         final Path relativeArtifactsPath = Paths.get(ARTIFACTS_FOLDER);
166         if (nonManoOriginalFilePath.startsWith(relativeArtifactsPath)) {
167             return relativeArtifactsPath.relativize(nonManoOriginalFilePath);
168         }
169         return nonManoOriginalFilePath;
170     }
171
172     @Override
173     public void updateMainDescriptorPaths(final ToscaServiceModel toscaServiceModel, final Map<String, Path> fromToMovedArtifactMap) {
174         final ServiceTemplate entryDefinition = toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate());
175         final YamlUtil yamlUtil = new YamlUtil();
176         final String[] entryDefinitionYaml = {yamlUtil.objectToYaml(entryDefinition)};
177         fromToMovedArtifactMap.forEach((fromPath, toPath) -> entryDefinitionYaml[0] = entryDefinitionYaml[0].replaceAll(fromPath, toPath.toString()));
178         toscaServiceModel.addServiceTemplate(toscaServiceModel.getEntryDefinitionServiceTemplate(),
179             yamlUtil.yamlToObject(entryDefinitionYaml[0], ServiceTemplate.class));
180     }
181
182     private boolean hasMetaMandatoryEntries(final ToscaMetadata toscaMetadata) {
183         final Map<String, String> metaDataEntries = toscaMetadata.getMetaEntries();
184         return metaDataEntries.containsKey(ENTRY_DEFINITIONS.getName()) && metaDataEntries.containsKey(ETSI_ENTRY_MANIFEST.getName())
185             && metaDataEntries.containsKey(ETSI_ENTRY_CHANGE_LOG.getName());
186     }
187
188     @Override
189     public Semver getHighestCompatibleSpecificationVersion(final FileContentHandler handler) {
190         try {
191             Map<String, String> metadata = getManifest(handler).getMetadata();
192             if (metadata.containsKey(COMPATIBLE_SPECIFICATION_VERSIONS.getToken())) {
193                 return Arrays.stream(metadata.get(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()).split(",")).map(String::trim).map(Semver::new)
194                     .max(Comparator.naturalOrder()).orElse(new Semver(ETSI_VERSION_2_6_1));
195             }
196         } catch (Exception ex) {
197             LOGGER.error("An error occurred while getting highest compatible version from manifest file", ex);
198         }
199         return new Semver(ETSI_VERSION_2_6_1);
200     }
201
202     @Override
203     public boolean hasCnfEnhancements(final FileContentHandler fileContentHandler) throws IOException {
204         final Manifest manifest = loadManifest(fileContentHandler);
205         return manifest.getNonManoSources().entrySet().stream()
206             .filter(manifestNonManoSourceEntry -> NonManoArtifactType.ONAP_CNF_HELM.getType().equalsIgnoreCase(manifestNonManoSourceEntry.getKey()))
207             .findFirst().isPresent();
208     }
209
210     private Manifest loadManifest(final FileContentHandler handler) throws IOException {
211         final Manifest manifest;
212         try {
213             manifest = getManifest(handler);
214         } catch (final IOException ex) {
215             if (LOGGER.isErrorEnabled()) {
216                 LOGGER.error("An error occurred while getting the manifest file", ex);
217             }
218             throw ex;
219         }
220         return manifest;
221     }
222
223     private boolean isMetaFilePresent(Map<String, byte[]> handler) {
224         return handler.containsKey(TOSCA_META_PATH_FILE_NAME) || handler.containsKey(TOSCA_META_ORIG_PATH_FILE_NAME);
225     }
226
227     public ResourceTypeEnum getResourceType(FileContentHandler handler) throws IOException {
228         ToscaMetadata metadata = getMetadata(handler);
229         Manifest manifest = getManifest(handler, metadata.getMetaEntries().get(ETSI_ENTRY_MANIFEST.getName()));
230         return getResourceType(manifest);
231     }
232
233     public ResourceTypeEnum getResourceType(Manifest manifest) {
234         // Valid manifest should contain whether vnf or pnf related metadata data exclusively in SOL004 standard,
235
236         // validation of manifest done during package upload stage
237         if (manifest != null && !manifest.getMetadata().isEmpty() && MANIFEST_PNF_METADATA.stream()
238             .anyMatch(e -> manifest.getMetadata().containsKey(e))) {
239             return ResourceTypeEnum.PNF;
240         }
241         // VNF is default resource type
242         return ResourceTypeEnum.VF;
243     }
244
245     public Manifest getManifest(FileContentHandler handler) throws IOException {
246         ToscaMetadata metadata = getMetadata(handler);
247         return getManifest(handler, metadata.getMetaEntries().get(ETSI_ENTRY_MANIFEST.getName()));
248     }
249
250     private Manifest getManifest(FileContentHandler handler, String manifestLocation) throws IOException {
251         try (InputStream manifestInputStream = getManifestInputStream(handler, manifestLocation)) {
252             Manifest onboardingManifest = new SOL004ManifestOnboarding();
253             onboardingManifest.parse(manifestInputStream);
254             return onboardingManifest;
255         }
256     }
257
258     public Path getOriginalManifestPath(final FileContentHandler handler) throws IOException {
259         final ToscaMetadata metadata = getOriginalMetadata(handler);
260         final String originalMetadataPath = metadata.getMetaEntries().get(ETSI_ENTRY_MANIFEST.getName());
261         final Path path = Paths.get(originalMetadataPath);
262         return path.getParent() == null ? Paths.get("") : path.getParent();
263     }
264
265     private ToscaMetadata getMetadata(FileContentHandler handler) throws IOException {
266         ToscaMetadata metadata;
267         if (handler.containsFile(TOSCA_META_PATH_FILE_NAME)) {
268             metadata = OnboardingToscaMetadata.parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME));
269         } else if (handler.containsFile(TOSCA_META_ORIG_PATH_FILE_NAME)) {
270             metadata = OnboardingToscaMetadata.parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_ORIG_PATH_FILE_NAME));
271         } else {
272             throw new IOException("TOSCA.meta file not found!");
273         }
274         return metadata;
275     }
276
277     private ToscaMetadata getOriginalMetadata(final FileContentHandler handler) throws IOException {
278         if (handler.containsFile(TOSCA_META_ORIG_PATH_FILE_NAME)) {
279             return OnboardingToscaMetadata.parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_ORIG_PATH_FILE_NAME));
280         } else {
281             throw new IOException(String.format("%s file not found", TOSCA_META_ORIG_PATH_FILE_NAME));
282         }
283     }
284
285     private InputStream getManifestInputStream(FileContentHandler handler, String manifestLocation) throws IOException {
286         InputStream io;
287         if (manifestLocation == null || !handler.containsFile(manifestLocation)) {
288             io = handler.getFileContentAsStream(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME);
289         } else {
290             io = handler.getFileContentAsStream(manifestLocation);
291         }
292         if (io == null) {
293             throw new IOException("Manifest file not found!");
294         }
295         return io;
296     }
297
298     public NonManoConfiguration getConfiguration() {
299         return nonManoConfiguration;
300     }
301 }