404793705995e830427c34f9a474dbff28dd65c6
[sdc.git] /
1 /*
2
3  * Copyright (c) 2018 AT&T Intellectual Property.
4
5   * Modifications Copyright (c) 2018 Verizon Property.
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  *     http://www.apache.org/licenses/LICENSE-2.0
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
15  * See the License for the specific language governing permissions and
16
17  * limitations under the License.
18
19  */
20
21 package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration;
22
23 import org.apache.commons.lang3.tuple.Pair;
24 import org.openecomp.core.utilities.file.FileContentHandler;
25 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
26 import org.openecomp.sdc.common.errors.CoreException;
27 import org.openecomp.sdc.common.errors.Messages;
28 import org.openecomp.sdc.common.utils.CommonUtil;
29 import org.openecomp.sdc.common.utils.SdcCommon;
30 import org.openecomp.sdc.datatypes.error.ErrorLevel;
31 import org.openecomp.sdc.datatypes.error.ErrorMessage;
32 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
33 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
34 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.OnboardingManifest;
35 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.OnboardingToscaMetadata;
36 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
37 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
38
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.nio.ByteBuffer;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Optional;
45 import java.util.stream.Collectors;
46
47 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
48 import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.*;
49
50 public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler
51     implements OrchestrationTemplateFileHandler {
52
53
54   @Override
55   public Optional<FileContentHandler> getFileContentMap(UploadFileResponse uploadFileResponse,
56                                                         byte[] uploadedFileData) {
57     FileContentHandler contentMap = null;
58     List<String> folderList = new ArrayList<>();
59     try {
60       Pair<FileContentHandler, List<String>> fileContentMapFromOrchestrationCandidateZip =
61           CommonUtil.getFileContentMapFromOrchestrationCandidateZip(uploadedFileData);
62       contentMap = fileContentMapFromOrchestrationCandidateZip.getKey();
63       folderList = fileContentMapFromOrchestrationCandidateZip.getRight();
64     } catch (IOException exception) {
65       uploadFileResponse.addStructureError(
66           SdcCommon.UPLOAD_FILE,
67           new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage()));
68     } catch (CoreException coreException) {
69       uploadFileResponse.addStructureError(
70           SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage()));
71     }
72     validateContent(uploadFileResponse, contentMap, folderList);
73     return Optional.ofNullable(contentMap);
74   }
75
76   private void validateContent(UploadFileResponse uploadFileResponse, FileContentHandler contentMap,
77                                List<String> folderList) {
78     validateManifest(uploadFileResponse, contentMap);
79     validateMetadata(uploadFileResponse, contentMap);
80     validateNoExtraFiles(uploadFileResponse, contentMap);
81     validateFolders(uploadFileResponse, folderList);
82   }
83   
84   private void validateMetadata(UploadFileResponse uploadFileResponse,
85                                 FileContentHandler contentMap){
86     if (!validateTOSCAYamlFileInRootExist(contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME)) {
87       try (InputStream metaFileContent = contentMap.getFileContent(TOSCA_META_PATH_FILE_NAME)) {
88
89         OnboardingToscaMetadata onboardingToscaMetadata = new OnboardingToscaMetadata(metaFileContent);
90         String entryDefinitionsPath = onboardingToscaMetadata.getEntryDefinitionsPath();
91         if (entryDefinitionsPath != null) {
92         validateFileExist(uploadFileResponse, contentMap, entryDefinitionsPath);
93         } else {
94         uploadFileResponse.addStructureError(
95             SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
96                 Messages.METADATA_NO_ENTRY_DEFINITIONS.getErrorMessage()));
97         }
98       } catch (IOException exception) {
99         uploadFileResponse.addStructureError(
100             SdcCommon.UPLOAD_FILE,
101             new ErrorMessage(ErrorLevel.ERROR, Messages.FAILED_TO_VALIDATE_METADATA.getErrorMessage()));
102       }
103     } else {
104     validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME);
105     }  
106   }
107
108   private void validateManifest(UploadFileResponse uploadFileResponse,
109                                 FileContentHandler contentMap) {
110
111     if (!validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) {
112       return;
113     }
114
115     try (InputStream fileContent = contentMap.getFileContent(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) {
116
117       OnboardingManifest onboardingManifest = new OnboardingManifest(fileContent);
118       if (!onboardingManifest.isValid()) {
119         onboardingManifest.getErrors().forEach(error -> uploadFileResponse.addStructureError(
120             SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, error)));
121       }
122
123     } catch (IOException e) {
124       // convert to runtime to keep the throws unchanged
125       throw new RuntimeException("Failed to validate manifest", e);
126     }
127   }
128
129   private void validateNoExtraFiles(UploadFileResponse uploadFileResponse,
130                                     FileContentHandler contentMap) {
131     List<String> unwantedFiles = contentMap.getFileList().stream()
132         .filter(this::filterFiles).collect(Collectors.toList());
133     if (!unwantedFiles.isEmpty()) {
134       unwantedFiles.stream().filter(this::filterFiles).forEach(unwantedFile ->
135           uploadFileResponse.addStructureError(
136               SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
137                   getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(),
138                       unwantedFile))));
139     }
140   }
141
142   private void validateFolders(UploadFileResponse uploadFileResponse, List<String> folderList) {
143     List<String> filterResult =
144         folderList.stream().filter(this::filterFolders).collect(Collectors.toList());
145     if (!filterResult.isEmpty()) {
146       folderList.stream().filter(this::filterFolders).forEach(unwantedFolder ->
147           uploadFileResponse.addStructureError(
148               SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
149                   getErrorWithParameters(Messages.CSAR_DIRECTORIES_NOT_ALLOWED.getErrorMessage(),
150                       unwantedFolder))));
151
152     }
153   }
154
155   private boolean filterFiles(String inFileName) {
156     boolean valid = ELIGIBLE_FILES.stream().anyMatch(fileName -> fileName.equals(inFileName));
157     return !valid && filterFolders(inFileName);
158   }
159
160   private boolean filterFolders(String fileName) {
161     return ELIGBLE_FOLDERS.stream().noneMatch(fileName::startsWith);
162   }
163   
164   private boolean validateTOSCAYamlFileInRootExist(FileContentHandler contentMap, String fileName) {
165     return contentMap.containsFile(fileName);
166   }
167
168   private boolean validateFileExist(UploadFileResponse uploadFileResponse,
169                                     FileContentHandler contentMap, String fileName) {
170
171     boolean containsFile = contentMap.containsFile(fileName);
172     if (!containsFile) {
173       uploadFileResponse.addStructureError(
174           SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
175               getErrorWithParameters(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage(), fileName)));
176     }
177     return containsFile;
178   }
179
180   @Override
181   protected boolean updateCandidateData(VspDetails vspDetails, byte[] uploadedFileData,
182                                         FileContentHandler contentMap,
183                                         String fileSuffix, String networkPackageName,
184                                         CandidateService candidateService,
185                                         UploadFileResponse uploadFileResponse) {
186     try {
187       candidateService.updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(),
188           new OrchestrationTemplateCandidateData(ByteBuffer.wrap(uploadedFileData), "", fileSuffix,
189               networkPackageName));
190     } catch (Exception exception) {
191       logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(),
192           getHandlerType().toString()), exception);
193       uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE,
194           new ErrorMessage(ErrorLevel.ERROR, exception.getMessage()));
195       return true;
196     }
197     return false;
198   }
199
200
201   @Override
202   protected OnboardingTypesEnum getHandlerType() {
203     return OnboardingTypesEnum.CSAR;
204   }
205
206   @Override
207   protected boolean isInvalidRawZipData(String fileSuffix,
208                                         UploadFileResponse uploadFileResponse,
209                                         byte[] uploadedFileData,
210                                         CandidateService candidateService) {
211     return super.isInvalidRawZipData(fileSuffix, uploadFileResponse, uploadedFileData, candidateService);
212   }
213 }