6fe7f9dd0a6c4d528b36e039e4ef9fc64ad92e67
[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.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST;
32 import static org.openecomp.sdc.common.errors.Messages.PACKAGE_PROCESS_ERROR;
33 import static org.openecomp.sdc.common.errors.Messages.UNEXPECTED_PROBLEM_HAPPENED_WHILE_GETTING;
34
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.util.ArrayList;
41 import java.util.Collections;
42 import java.util.HashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Optional;
46 import java.util.UUID;
47 import javax.activation.DataHandler;
48 import javax.inject.Named;
49 import javax.ws.rs.core.Response;
50 import org.apache.commons.lang3.tuple.Pair;
51 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
52 import org.openecomp.sdc.activitylog.ActivityLogManager;
53 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
54 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
55 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
56 import org.openecomp.sdc.be.csar.storage.ArtifactInfo;
57 import org.openecomp.sdc.be.csar.storage.ArtifactStorageConfig;
58 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
59 import org.openecomp.sdc.be.csar.storage.PackageSizeReducer;
60 import org.openecomp.sdc.be.csar.storage.StorageFactory;
61 import org.openecomp.sdc.common.util.ValidationUtils;
62 import org.openecomp.sdc.common.utils.SdcCommon;
63 import org.openecomp.sdc.datatypes.error.ErrorLevel;
64 import org.openecomp.sdc.datatypes.error.ErrorMessage;
65 import org.openecomp.sdc.logging.api.Logger;
66 import org.openecomp.sdc.logging.api.LoggerFactory;
67 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
68 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
69 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
70 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
71 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
72 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.OnboardingPackageProcessor;
73 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.validation.CnfPackageValidator;
74 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
75 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
76 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
77 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
79 import org.openecomp.sdc.versioning.dao.types.Version;
80 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
81 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
82 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
83 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
84 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
85 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
86 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
87 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
88 import org.springframework.context.annotation.Scope;
89 import org.springframework.stereotype.Service;
90
91 @Named
92 @Service("orchestrationTemplateCandidate")
93 @Scope(value = "prototype")
94 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
95
96     private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
97     private final OrchestrationTemplateCandidateManager candidateManager;
98     private final VendorSoftwareProductManager vendorSoftwareProductManager;
99     private final ActivityLogManager activityLogManager;
100     private final ArtifactStorageManager artifactStorageManager;
101     private final PackageSizeReducer packageSizeReducer;
102
103     public OrchestrationTemplateCandidateImpl() {
104         this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
105         this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
106         this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
107         LOGGER.info("Instantiating artifactStorageManager");
108         final StorageFactory storageFactory = new StorageFactory();
109         this.artifactStorageManager = storageFactory.createArtifactStorageManager();
110         LOGGER.info("Instantiating packageSizeReducer");
111         this.packageSizeReducer = storageFactory.createPackageSizeReducer().orElse(null);
112     }
113
114     // Constructor used in test to avoid mock static
115     public OrchestrationTemplateCandidateImpl(final OrchestrationTemplateCandidateManager candidateManager,
116                                               final VendorSoftwareProductManager vendorSoftwareProductManager,
117                                               final ActivityLogManager activityLogManager,
118                                               final ArtifactStorageManager artifactStorageManager,
119                                               final PackageSizeReducer packageSizeReducer) {
120         this.candidateManager = candidateManager;
121         this.vendorSoftwareProductManager = vendorSoftwareProductManager;
122         this.activityLogManager = activityLogManager;
123         this.artifactStorageManager = artifactStorageManager;
124         this.packageSizeReducer = packageSizeReducer;
125     }
126
127     @Override
128     public Response upload(String vspId, String versionId, final Attachment fileToUpload, final String user) {
129         vspId = ValidationUtils.sanitizeInputString(vspId);
130         versionId = ValidationUtils.sanitizeInputString(versionId);
131         final byte[] fileToUploadBytes;
132         final DataHandler dataHandler = fileToUpload.getDataHandler();
133         final var filename = ValidationUtils.sanitizeInputString(dataHandler.getName());
134         ArtifactInfo artifactInfo = null;
135         if (artifactStorageManager.isEnabled()) {
136             final Path tempArtifactPath;
137             try {
138                 final ArtifactStorageConfig storageConfiguration = artifactStorageManager.getStorageConfiguration();
139
140                 final Path folder = Path.of(storageConfiguration.getTempPath()).resolve(vspId).resolve(versionId);
141                 tempArtifactPath = folder.resolve(UUID.randomUUID().toString());
142                 Files.createDirectories(folder);
143                 try (final InputStream packageInputStream = dataHandler.getInputStream();
144                     final var fileOutputStream = new FileOutputStream(tempArtifactPath.toFile())) {
145                     packageInputStream.transferTo(fileOutputStream);
146                 }
147             } catch (final Exception e) {
148                 return Response.status(INTERNAL_SERVER_ERROR).entity(buildUploadResponseWithError(
149                     new ErrorMessage(ErrorLevel.ERROR, UNEXPECTED_PROBLEM_HAPPENED_WHILE_GETTING.formatMessage(filename)))).build();
150             }
151             try (final InputStream inputStream = Files.newInputStream(tempArtifactPath)) {
152                 artifactInfo = artifactStorageManager.upload(vspId, versionId, inputStream);
153             } catch (final Exception e) {
154                 LOGGER.error("Package Size Reducer not configured", e);
155                 return Response.status(INTERNAL_SERVER_ERROR).entity(buildUploadResponseWithError(
156                     new ErrorMessage(ErrorLevel.ERROR, ERROR_HAS_OCCURRED_WHILE_PERSISTING_THE_ARTIFACT.formatMessage(filename)))).build();
157             }
158             try {
159                 fileToUploadBytes = packageSizeReducer.reduce(tempArtifactPath);
160                 Files.delete(tempArtifactPath);
161             } catch (final Exception e) {
162                 LOGGER.error("Package Size Reducer not configured", e);
163                 return Response.status(INTERNAL_SERVER_ERROR).entity(buildUploadResponseWithError(
164                     new ErrorMessage(ErrorLevel.ERROR,
165                         ERROR_HAS_OCCURRED_WHILE_REDUCING_THE_ARTIFACT_SIZE.formatMessage(tempArtifactPath.toString())))).build();
166             }
167         } else {
168             fileToUploadBytes = fileToUpload.getObject(byte[].class);
169         }
170
171         final var onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes, new CnfPackageValidator(), artifactInfo);
172         final ErrorMessage[] errorMessages = onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0]);
173         if (onboardingPackageProcessor.hasErrors()) {
174             return Response.status(NOT_ACCEPTABLE).entity(buildUploadResponseWithError(errorMessages)).build();
175         }
176         final var onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null);
177         if (onboardPackageInfo == null) {
178             final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
179                 new ErrorMessage(ErrorLevel.ERROR, PACKAGE_PROCESS_ERROR.formatMessage(filename)));
180             return Response.ok(uploadFileResponseDto).build();
181         }
182         final var version = new Version(versionId);
183         final var vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
184         final Response response = processOnboardPackage(onboardPackageInfo, vspDetails, errorMessages);
185         final UploadFileResponseDto entity = (UploadFileResponseDto) response.getEntity();
186         if (artifactStorageManager.isEnabled() && !entity.getErrors().isEmpty()) {
187             artifactStorageManager.delete(artifactInfo);
188         }
189         return response;
190     }
191
192     private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails,
193                                            final ErrorMessage... errorMessages) {
194         final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo);
195         final UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
196             .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
197         if (errorMessages.length > 0) {
198             uploadFileResponseDto.setErrors(getErrorMap(errorMessages));
199         }
200         return Response.ok(uploadFileResponseDto).build();
201     }
202
203     private Map<String, List<ErrorMessage>> getErrorMap(ErrorMessage[] errorMessages) {
204         final Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
205         final List<ErrorMessage> errorMessageList = new ArrayList<>();
206         Collections.addAll(errorMessageList, errorMessages);
207         errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList);
208         return errorMap;
209     }
210
211     private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) {
212         final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
213         uploadFileResponseDto.setErrors(getErrorMap(errorMessages));
214         return uploadFileResponseDto;
215     }
216
217     @Override
218     public Response get(String vspId, String versionId, String user) throws IOException {
219         Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
220         String fileName;
221         if (zipFile.isPresent()) {
222             fileName = "Candidate." + zipFile.get().getLeft();
223         } else {
224             zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
225             if (!zipFile.isPresent()) {
226                 ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
227                     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))
259                 .build();
260         }
261         return Response.ok(fileDataStructureDto).build();
262     }
263
264     @Override
265     public Response getFilesDataStructure(String vspId, String versionId, String user) {
266         Optional<FilesDataStructure> filesDataStructure = candidateManager.getFilesDataStructure(vspId, new Version(versionId));
267         if (!filesDataStructure.isPresent()) {
268             filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId, new Version(versionId));
269         }
270         FileDataStructureDto fileDataStructureDto = filesDataStructure
271             .map(dataStructure -> new MapFilesDataStructureToDto().applyMapping(dataStructure, FileDataStructureDto.class))
272             .orElse(new FileDataStructureDto());
273         return Response.ok(fileDataStructureDto).build();
274     }
275
276     private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response) {
277         OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
278         result.setErrors(response.getErrors());
279         result.setFileNames(response.getFileNames());
280         result.setStatus(response.getStatus());
281         return result;
282     }
283
284     private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto) {
285         FilesDataStructure filesDataStructure = new FilesDataStructure();
286         filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
287         filesDataStructure.setModules(fileDataStructureDto.getModules());
288         filesDataStructure.setNested(fileDataStructureDto.getNested());
289         filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
290         return filesDataStructure;
291     }
292 }