bfe602b3adede5e57b10013dbab64c806f5e979b
[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.tosca.csar.Manifest;
35 import org.openecomp.sdc.tosca.csar.OnboardingManifest;
36 import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.OnboardingToscaMetadata;
37 import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService;
38 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
39
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.nio.ByteBuffer;
43 import java.util.ArrayList;
44 import java.util.List;
45 import java.util.Optional;
46 import java.util.stream.Collectors;
47
48 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
49 import static org.openecomp.sdc.tosca.csar.CSARConstants.ELIGBLE_FOLDERS;
50 import static org.openecomp.sdc.tosca.csar.CSARConstants.ELIGIBLE_FILES;
51 import static org.openecomp.sdc.tosca.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_MF_FILE_NAME;
52 import static org.openecomp.sdc.tosca.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME;
53 import static org.openecomp.sdc.tosca.csar.CSARConstants.TOSCA_META_PATH_FILE_NAME;
54
55 public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler
56     implements OrchestrationTemplateFileHandler {
57
58
59   @Override
60   public Optional<FileContentHandler> getFileContentMap(UploadFileResponse uploadFileResponse,
61                                                         byte[] uploadedFileData) {
62     FileContentHandler contentMap = null;
63     List<String> folderList = new ArrayList<>();
64     try {
65       Pair<FileContentHandler, List<String>> fileContentMapFromOrchestrationCandidateZip =
66           CommonUtil.getFileContentMapFromOrchestrationCandidateZip(uploadedFileData);
67       contentMap = fileContentMapFromOrchestrationCandidateZip.getKey();
68       folderList = fileContentMapFromOrchestrationCandidateZip.getRight();
69     } catch (IOException exception) {
70       uploadFileResponse.addStructureError(
71           SdcCommon.UPLOAD_FILE,
72           new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage()));
73     } catch (CoreException coreException) {
74       uploadFileResponse.addStructureError(
75           SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage()));
76     }
77     validateContent(uploadFileResponse, contentMap, folderList);
78     return Optional.ofNullable(contentMap);
79   }
80
81   private void validateContent(UploadFileResponse uploadFileResponse, FileContentHandler contentMap,
82                                List<String> folderList) {
83     validateManifest(uploadFileResponse, contentMap);
84     validateMetadata(uploadFileResponse, contentMap);
85     validateNoExtraFiles(uploadFileResponse, contentMap);
86     validateFolders(uploadFileResponse, folderList);
87   }
88   
89   private void validateMetadata(UploadFileResponse uploadFileResponse,
90                                 FileContentHandler contentMap){
91     if (!validateTOSCAYamlFileInRootExist(contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME)) {
92       try (InputStream metaFileContent = contentMap.getFileContent(TOSCA_META_PATH_FILE_NAME)) {
93
94         OnboardingToscaMetadata onboardingToscaMetadata = new OnboardingToscaMetadata(metaFileContent);
95         String entryDefinitionsPath = onboardingToscaMetadata.getEntryDefinitionsPath();
96         if (entryDefinitionsPath != null) {
97         validateFileExist(uploadFileResponse, contentMap, entryDefinitionsPath);
98         } else {
99         uploadFileResponse.addStructureError(
100             SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
101                 Messages.METADATA_NO_ENTRY_DEFINITIONS.getErrorMessage()));
102         }
103       } catch (IOException exception) {
104         uploadFileResponse.addStructureError(
105             SdcCommon.UPLOAD_FILE,
106             new ErrorMessage(ErrorLevel.ERROR, Messages.FAILED_TO_VALIDATE_METADATA.getErrorMessage()));
107       }
108     } else {
109     validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME);
110     }  
111   }
112
113   private void validateManifest(UploadFileResponse uploadFileResponse,
114                                 FileContentHandler contentMap) {
115
116     if (!validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) {
117       return;
118     }
119
120     try (InputStream fileContent = contentMap.getFileContent(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) {
121
122       Manifest onboardingManifest = OnboardingManifest.parse(fileContent);
123       if (!onboardingManifest.isValid()) {
124         onboardingManifest.getErrors().forEach(error -> uploadFileResponse.addStructureError(
125             SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, error)));
126       }
127
128     } catch (IOException e) {
129       // convert to runtime to keep the throws unchanged
130       throw new RuntimeException("Failed to validate manifest", e);
131     }
132   }
133
134   private void validateNoExtraFiles(UploadFileResponse uploadFileResponse,
135                                     FileContentHandler contentMap) {
136     List<String> unwantedFiles = contentMap.getFileList().stream()
137         .filter(this::filterFiles).collect(Collectors.toList());
138     if (!unwantedFiles.isEmpty()) {
139       unwantedFiles.stream().filter(this::filterFiles).forEach(unwantedFile ->
140           uploadFileResponse.addStructureError(
141               SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
142                   getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(),
143                       unwantedFile))));
144     }
145   }
146
147   private void validateFolders(UploadFileResponse uploadFileResponse, List<String> folderList) {
148     List<String> filterResult =
149         folderList.stream().filter(this::filterFolders).collect(Collectors.toList());
150     if (!filterResult.isEmpty()) {
151       folderList.stream().filter(this::filterFolders).forEach(unwantedFolder ->
152           uploadFileResponse.addStructureError(
153               SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
154                   getErrorWithParameters(Messages.CSAR_DIRECTORIES_NOT_ALLOWED.getErrorMessage(),
155                       unwantedFolder))));
156
157     }
158   }
159
160   private boolean filterFiles(String inFileName) {
161     boolean valid = ELIGIBLE_FILES.stream().anyMatch(fileName -> fileName.equals(inFileName));
162     return !valid && filterFolders(inFileName);
163   }
164
165   private boolean filterFolders(String fileName) {
166     return ELIGBLE_FOLDERS.stream().noneMatch(fileName::startsWith);
167   }
168   
169   private boolean validateTOSCAYamlFileInRootExist(FileContentHandler contentMap, String fileName) {
170     return contentMap.containsFile(fileName);
171   }
172
173   private boolean validateFileExist(UploadFileResponse uploadFileResponse,
174                                     FileContentHandler contentMap, String fileName) {
175
176     boolean containsFile = contentMap.containsFile(fileName);
177     if (!containsFile) {
178       uploadFileResponse.addStructureError(
179           SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR,
180               getErrorWithParameters(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage(), fileName)));
181     }
182     return containsFile;
183   }
184
185   @Override
186   protected boolean updateCandidateData(VspDetails vspDetails, byte[] uploadedFileData,
187                                         FileContentHandler contentMap,
188                                         String fileSuffix, String networkPackageName,
189                                         CandidateService candidateService,
190                                         UploadFileResponse uploadFileResponse) {
191     try {
192       candidateService.updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(),
193           new OrchestrationTemplateCandidateData(ByteBuffer.wrap(uploadedFileData), "", fileSuffix,
194               networkPackageName));
195     } catch (Exception exception) {
196       logger.error(getErrorWithParameters(Messages.FILE_CONTENT_MAP.getErrorMessage(),
197           getHandlerType().toString()), exception);
198       uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE,
199           new ErrorMessage(ErrorLevel.ERROR, exception.getMessage()));
200       return true;
201     }
202     return false;
203   }
204
205
206   @Override
207   protected OnboardingTypesEnum getHandlerType() {
208     return OnboardingTypesEnum.CSAR;
209   }
210
211   @Override
212   protected boolean isInvalidRawZipData(String fileSuffix,
213                                         UploadFileResponse uploadFileResponse,
214                                         byte[] uploadedFileData,
215                                         CandidateService candidateService) {
216     return super.isInvalidRawZipData(fileSuffix, uploadFileResponse, uploadedFileData, candidateService);
217   }
218 }