10f6012a765dc7658e9545bdee14e153e194a7a1
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  * Copyright © 2021 Nokia
4  * Copyright © 2021 Nordix Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  * Modifications copyright (c) 2019 Nokia
19  * Modifications copyright (c) 2021 Nordix Foundation
20  * ================================================================================
21  */
22 package org.openecomp.sdcrests.vsp.rest.services;
23
24 import static javax.ws.rs.core.Response.Status.EXPECTATION_FAILED;
25 import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
26 import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE;
27 import static javax.ws.rs.core.Response.Status.NOT_FOUND;
28 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
29 import static org.openecomp.sdc.common.errors.Messages.ERROR_HAS_OCCURRED_WHILE_PERSISTING_THE_ARTIFACT;
30 import static org.openecomp.sdc.common.errors.Messages.ERROR_HAS_OCCURRED_WHILE_REDUCING_THE_ARTIFACT_SIZE;
31 import static org.openecomp.sdc.common.errors.Messages.EXTERNAL_CSAR_STORE_CONFIGURATION_FAILURE_MISSING_FULL_PATH;
32 import static org.openecomp.sdc.common.errors.Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST;
33 import static org.openecomp.sdc.common.errors.Messages.PACKAGE_PROCESS_ERROR;
34 import static org.openecomp.sdc.common.errors.Messages.UNEXPECTED_PROBLEM_HAPPENED_WHILE_GETTING;
35
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.nio.file.Path;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Optional;
45 import java.util.Set;
46 import java.util.stream.Collectors;
47 import javax.inject.Named;
48 import javax.ws.rs.core.Response;
49 import org.apache.commons.lang3.tuple.Pair;
50 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
51 import org.openecomp.sdc.activitylog.ActivityLogManager;
52 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
53 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
54 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
55 import org.openecomp.sdc.be.csar.storage.ArtifactInfo;
56 import org.openecomp.sdc.be.csar.storage.ArtifactStorageConfig;
57 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
58 import org.openecomp.sdc.be.csar.storage.CsarPackageReducerConfiguration;
59 import org.openecomp.sdc.be.csar.storage.CsarSizeReducer;
60 import org.openecomp.sdc.be.csar.storage.PackageSizeReducer;
61 import org.openecomp.sdc.be.csar.storage.PersistentVolumeArtifactStorageConfig;
62 import org.openecomp.sdc.be.csar.storage.PersistentVolumeArtifactStorageManager;
63 import org.openecomp.sdc.be.exception.BusinessException;
64 import org.openecomp.sdc.common.CommonConfigurationManager;
65 import org.openecomp.sdc.common.util.ValidationUtils;
66 import org.openecomp.sdc.common.utils.SdcCommon;
67 import org.openecomp.sdc.datatypes.error.ErrorLevel;
68 import org.openecomp.sdc.datatypes.error.ErrorMessage;
69 import org.openecomp.sdc.logging.api.Logger;
70 import org.openecomp.sdc.logging.api.LoggerFactory;
71 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
72 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
73 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
74 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
75 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
76 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.OnboardingPackageProcessor;
77 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.validation.CnfPackageValidator;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
79 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
80 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
81 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
82 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
83 import org.openecomp.sdc.versioning.dao.types.Version;
84 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
85 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
86 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
87 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
88 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
89 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
90 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
91 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
92 import org.springframework.context.annotation.Scope;
93 import org.springframework.stereotype.Service;
94
95 @Named
96 @Service("orchestrationTemplateCandidate")
97 @Scope(value = "prototype")
98 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
99
100     private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
101     private static final String EXTERNAL_CSAR_STORE = "externalCsarStore";
102     private final OrchestrationTemplateCandidateManager candidateManager;
103     private final VendorSoftwareProductManager vendorSoftwareProductManager;
104     private final ActivityLogManager activityLogManager;
105     private final ArtifactStorageManager artifactStorageManager;
106     private final PackageSizeReducer packageSizeReducer;
107
108     public OrchestrationTemplateCandidateImpl() {
109         this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
110         this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
111         this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
112         LOGGER.info("Instantiating artifactStorageManager");
113         this.artifactStorageManager = new PersistentVolumeArtifactStorageManager(readArtifactStorageConfiguration());
114         LOGGER.info("Instantiating packageSizeReducer");
115         this.packageSizeReducer = new CsarSizeReducer(readPackageReducerConfiguration());
116     }
117
118     // Constructor used in test to avoid mock static
119     public OrchestrationTemplateCandidateImpl(final OrchestrationTemplateCandidateManager candidateManager,
120                                               final VendorSoftwareProductManager vendorSoftwareProductManager,
121                                               final ActivityLogManager activityLogManager,
122                                               final ArtifactStorageManager artifactStorageManager,
123                                               final PackageSizeReducer packageSizeReducer) {
124         this.candidateManager = candidateManager;
125         this.vendorSoftwareProductManager = vendorSoftwareProductManager;
126         this.activityLogManager = activityLogManager;
127         this.artifactStorageManager = artifactStorageManager;
128         this.packageSizeReducer = packageSizeReducer;
129     }
130
131     private CsarPackageReducerConfiguration readPackageReducerConfiguration() {
132         final var commonConfigurationManager = CommonConfigurationManager.getInstance();
133         final List<String> foldersToStrip = commonConfigurationManager.getConfigValue(EXTERNAL_CSAR_STORE, "foldersToStrip", new ArrayList<>());
134         final int sizeLimit = commonConfigurationManager.getConfigValue(EXTERNAL_CSAR_STORE, "sizeLimit", 1000000);
135         LOGGER.info("Folders to strip: '{}'", String.join(", ", foldersToStrip));
136         final Set<Path> foldersToStripPathSet = foldersToStrip.stream().map(Path::of).collect(Collectors.toSet());
137         return new CsarPackageReducerConfiguration(foldersToStripPathSet, sizeLimit);
138     }
139
140     private ArtifactStorageConfig readArtifactStorageConfiguration() {
141         final var commonConfigurationManager = CommonConfigurationManager.getInstance();
142         final boolean isEnabled = commonConfigurationManager.getConfigValue(EXTERNAL_CSAR_STORE, "storeCsarsExternally", false);
143         LOGGER.info("ArtifactConfig.isEnabled: '{}'", isEnabled);
144         final String storagePathString = commonConfigurationManager.getConfigValue(EXTERNAL_CSAR_STORE, "fullPath", null);
145         LOGGER.info("ArtifactConfig.storagePath: '{}'", storagePathString);
146         if (isEnabled && storagePathString == null) {
147             throw new OrchestrationTemplateCandidateException(EXTERNAL_CSAR_STORE_CONFIGURATION_FAILURE_MISSING_FULL_PATH.getErrorMessage());
148         }
149         final var storagePath = storagePathString == null ? null : Path.of(storagePathString);
150         return new PersistentVolumeArtifactStorageConfig(isEnabled, storagePath);
151     }
152
153     @Override
154     public Response upload(final String vspId, final String versionId, final Attachment fileToUpload, final String user) {
155         final byte[] fileToUploadBytes;
156         final var filename = ValidationUtils.sanitizeInputString(fileToUpload.getDataHandler().getName());
157         ArtifactInfo artifactInfo = null;
158         if (artifactStorageManager.isEnabled()) {
159             final InputStream packageInputStream;
160             try {
161                 packageInputStream = fileToUpload.getDataHandler().getInputStream();
162             } catch (final IOException e) {
163                 return Response.status(INTERNAL_SERVER_ERROR).entity(buildUploadResponseWithError(new ErrorMessage(ErrorLevel.ERROR, UNEXPECTED_PROBLEM_HAPPENED_WHILE_GETTING.formatMessage(filename)))).build();
164             }
165             try {
166                 artifactInfo = artifactStorageManager.upload(vspId, versionId, packageInputStream);
167             } catch (final BusinessException e) {
168                 return Response.status(INTERNAL_SERVER_ERROR).entity(buildUploadResponseWithError(new ErrorMessage(ErrorLevel.ERROR, ERROR_HAS_OCCURRED_WHILE_PERSISTING_THE_ARTIFACT.formatMessage(filename)))).build();
169             }
170             try {
171                 fileToUploadBytes = packageSizeReducer.reduce(artifactInfo.getPath());
172             } catch (final BusinessException e) {
173                 return Response.status(INTERNAL_SERVER_ERROR).entity(buildUploadResponseWithError(new ErrorMessage(ErrorLevel.ERROR, ERROR_HAS_OCCURRED_WHILE_REDUCING_THE_ARTIFACT_SIZE.formatMessage(artifactInfo.getPath())))).build();
174             }
175         } else {
176             fileToUploadBytes = fileToUpload.getObject(byte[].class);
177         }
178
179         final var onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes, new CnfPackageValidator(), artifactInfo);
180         final ErrorMessage[] errorMessages = onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0]);
181         if (onboardingPackageProcessor.hasErrors()) {
182             return Response.status(NOT_ACCEPTABLE).entity(buildUploadResponseWithError(errorMessages)).build();
183         }
184         final var onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null);
185         if (onboardPackageInfo == null) {
186             return Response.ok(buildUploadResponseWithError(new ErrorMessage(ErrorLevel.ERROR, PACKAGE_PROCESS_ERROR.formatMessage(filename)))).build();
187         }
188         final var vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId),
189             new Version(ValidationUtils.sanitizeInputString(versionId)));
190         return processOnboardPackage(onboardPackageInfo, vspDetails, errorMessages);
191     }
192
193     private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails,
194                                            final ErrorMessage... errorMessages) {
195         final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo);
196         final UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
197             .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
198         if (errorMessages.length > 0) {
199             uploadFileResponseDto.setErrors(getErrorMap(errorMessages));
200         }
201         return Response.ok(uploadFileResponseDto).build();
202     }
203
204     private Map<String, List<ErrorMessage>> getErrorMap(ErrorMessage[] errorMessages) {
205         final Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
206         final List<ErrorMessage> errorMessageList = new ArrayList<>();
207         Collections.addAll(errorMessageList, errorMessages);
208         errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList);
209         return errorMap;
210     }
211
212     private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) {
213         final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
214         uploadFileResponseDto.setErrors(getErrorMap(errorMessages));
215         return uploadFileResponseDto;
216     }
217
218     @Override
219     public Response get(String vspId, String versionId, String user) throws IOException {
220         Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
221         String fileName;
222         if (zipFile.isPresent()) {
223             fileName = "Candidate." + zipFile.get().getLeft();
224         } else {
225             zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
226             if (!zipFile.isPresent()) {
227                 ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), ""));
228                 LOGGER.error(errorMessage.getMessage());
229                 return Response.status(NOT_FOUND).build();
230             }
231             fileName = "Processed." + zipFile.get().getLeft();
232         }
233         Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
234         response.header("Content-Disposition", "attachment; filename=" + fileName);
235         return response.build();
236     }
237
238     @Override
239     public Response abort(String vspId, String versionId) {
240         candidateManager.abort(vspId, new Version(versionId));
241         return Response.ok().build();
242     }
243
244     @Override
245     public Response process(String vspId, String versionId, String user) {
246         Version version = new Version(versionId);
247         OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
248         activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Upload_Network_Package, user, true, "", ""));
249         OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
250         return Response.ok(responseDto).build();
251     }
252
253     @Override
254     public Response updateFilesDataStructure(String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
255         FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
256         ValidationResponse response = candidateManager.updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
257         if (!response.isValid()) {
258             return Response.status(EXPECTATION_FAILED).entity(new MapValidationResponseToDto().applyMapping(response, ValidationResponseDto.class)).build();
259         }
260         return Response.ok(fileDataStructureDto).build();
261     }
262
263     @Override
264     public Response getFilesDataStructure(String vspId, String versionId, String user) {
265         Optional<FilesDataStructure> filesDataStructure = candidateManager.getFilesDataStructure(vspId, new Version(versionId));
266         if (!filesDataStructure.isPresent()) {
267             filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId, new Version(versionId));
268         }
269         FileDataStructureDto fileDataStructureDto = filesDataStructure
270             .map(dataStructure -> new MapFilesDataStructureToDto().applyMapping(dataStructure, FileDataStructureDto.class))
271             .orElse(new FileDataStructureDto());
272         return Response.ok(fileDataStructureDto).build();
273     }
274
275     private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response) {
276         OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
277         result.setErrors(response.getErrors());
278         result.setFileNames(response.getFileNames());
279         result.setStatus(response.getStatus());
280         return result;
281     }
282
283     private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto) {
284         FilesDataStructure filesDataStructure = new FilesDataStructure();
285         filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
286         filesDataStructure.setModules(fileDataStructureDto.getModules());
287         filesDataStructure.setNested(fileDataStructureDto.getNested());
288         filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
289         return filesDataStructure;
290     }
291 }