6f76bf4527a4f1b4fc148000e6446a7845f20d76
[sdc.git] /
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  * Modifications Copyright 2018 European Support Limited
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.openecomp.sdcrests.vsp.rest.services;
19
20 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
21 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
22 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
23
24 import java.io.BufferedInputStream;
25 import java.io.ByteArrayInputStream;
26 import java.io.InputStream;
27 import java.net.URI;
28 import java.nio.charset.StandardCharsets;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Objects;
32 import java.util.Optional;
33 import javax.inject.Named;
34 import javax.net.ssl.HostnameVerifier;
35 import javax.net.ssl.SSLContext;
36 import javax.ws.rs.client.Client;
37 import javax.ws.rs.client.ClientBuilder;
38 import javax.ws.rs.client.Invocation;
39 import javax.ws.rs.client.WebTarget;
40 import javax.ws.rs.core.Link;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriBuilder;
43 import org.onap.config.api.ConfigurationManager;
44 import org.openecomp.sdc.common.errors.CoreException;
45 import org.openecomp.sdc.common.errors.ErrorCode;
46 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
47 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
48 import org.openecomp.sdc.logging.api.Logger;
49 import org.openecomp.sdc.logging.api.LoggerFactory;
50 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
51 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
52 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
53 import org.openecomp.sdc.versioning.VersioningManager;
54 import org.openecomp.sdc.versioning.VersioningManagerFactory;
55 import org.openecomp.sdc.versioning.dao.types.Version;
56 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
57 import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
58 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
59 import org.springframework.context.annotation.Scope;
60 import org.springframework.stereotype.Service;
61
62 /**
63  * Enables integration API interface with VNF Repository (VNFSDK).
64  * <ol>
65  *     <li>Get all the VNF Package Meta-data.</li>
66  *     <li>Download a VNF Package.</li>
67  *     <li>Import a VNF package to SDC catalog (Download & validate).</li>
68  * </ol>
69  *
70  * @version Amsterdam release (ONAP 1.0)
71  */
72 @Named
73 @Service("vnfPackageRepository")
74 @Scope(value = "prototype")
75 public class VnfPackageRepositoryImpl implements VnfPackageRepository {
76
77     private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
78
79     private final Configuration config;
80
81     public VnfPackageRepositoryImpl(Configuration config) {
82         this.config = config;
83     }
84
85     public VnfPackageRepositoryImpl() {
86         this(new FileConfiguration());
87     }
88
89     @Override
90     public Response getVnfPackages(String vspId, String versionId, String user) {
91
92         LOGGER.debug("Get VNF Packages from Repository: {}", vspId);
93
94         Client client = new SharedClient();
95
96         final String getVnfPackageUri = config.getGetUri();
97
98         try {
99
100             Response remoteResponse = client.target(getVnfPackageUri).request().get();
101             if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
102                 return handleUnexpectedStatus("querying VNF package metadata", getVnfPackageUri, remoteResponse);
103             }
104
105             LOGGER.debug("Response from VNF Repository: {}", remoteResponse);
106             return Response.ok(remoteResponse.readEntity(String.class)).build();
107
108         } finally {
109             client.close();
110         }
111     }
112
113     @Override
114     public Response importVnfPackage(String vspId, String versionId, String csarId, String user) {
115
116         LOGGER.debug("Import VNF Packages from Repository: {}", csarId);
117
118         final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);
119
120         Client client = new SharedClient();
121
122         try {
123
124             Response remoteResponse = client.target(downloadPackageUri).request().get();
125             if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
126                 return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
127             }
128
129             LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
130             byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
131             return uploadVnfPackage(vspId, versionId, csarId, payload);
132
133         } finally {
134             client.close();
135         }
136     }
137
138     private Response uploadVnfPackage(String vspId, String versionId, String csarId, byte[] payload) {
139
140         try (InputStream fileStream = new BufferedInputStream(new ByteArrayInputStream(payload))) {
141
142             OrchestrationTemplateCandidateManager candidateManager =
143                     OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
144
145             String filename = formatFilename(csarId);
146             Version version = getVersion(vspId, versionId);
147             UploadFileResponse response = candidateManager.upload(vspId, version, fileStream,
148                     getFileExtension(filename), getNetworkPackageName(filename));
149
150             UploadFileResponseDto uploadFileResponse = new MapUploadFileResponseToUploadFileResponseDto()
151                                                                .applyMapping(response, UploadFileResponseDto.class);
152
153             return Response.ok(uploadFileResponse).build();
154
155         } catch (Exception e) {
156             ErrorCode error = new GeneralErrorBuilder().build();
157             LOGGER.error("Exception while uploading package received from VNF Repository", new CoreException(error, e));
158             return generateInternalServerError(error);
159         }
160     }
161
162     @Override
163     public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) {
164
165         LOGGER.debug("Download VNF package from repository: csarId={}", csarId);
166
167         final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);
168
169         Client client = new SharedClient();
170
171         try {
172
173             Response remoteResponse = client.target(downloadPackageUri).request().get();
174             if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
175                 return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
176             }
177
178             byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
179             Response.ResponseBuilder response = Response.ok(payload);
180             response.header(CONTENT_DISPOSITION, "attachment; filename=" + formatFilename(csarId));
181
182             LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
183             return response.build();
184
185         } finally {
186             client.close();
187         }
188     }
189
190     private Version getVersion(String vspId, String versionId) {
191         VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
192         return findVersion(versioningManager.list(vspId), versionId).orElse(new Version(versionId));
193     }
194
195     Optional<Version> findVersion(List<Version> versions, String requestedVersion) {
196         return versions.stream().filter(ver -> Objects.equals(ver.getId(), requestedVersion)).findAny();
197     }
198
199     private static Response handleUnexpectedStatus(String action, String uri, Response response) {
200
201         ErrorCode error = new GeneralErrorBuilder().build();
202
203         if (LOGGER.isErrorEnabled()) {
204             String body = response.hasEntity() ? response.readEntity(String.class) : "";
205             LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri,
206                     response.getStatus(), body, new CoreException(error));
207         }
208
209         return generateInternalServerError(error);
210     }
211
212     private static Response generateInternalServerError(ErrorCode error) {
213         ErrorCodeAndMessage payload = new ErrorCodeAndMessage(Response.Status.INTERNAL_SERVER_ERROR, error);
214         return Response.serverError().entity(payload).build();
215     }
216
217     private static String formatFilename(String csarId) {
218         return "temp_" + csarId + ".csar";
219     }
220
221     interface Configuration {
222
223         String getGetUri();
224
225         String getDownloadUri();
226     }
227
228     private static class SharedClient implements Client {
229
230         private static final Client CLIENT = ClientBuilder.newClient();
231
232         @Override
233         public void close() {
234             // do not close the shared client
235         }
236
237         @Override
238         public WebTarget target(String uri) {
239             return CLIENT.target(uri);
240         }
241
242         @Override
243         public WebTarget target(URI uri) {
244             return CLIENT.target(uri);
245         }
246
247         @Override
248         public WebTarget target(UriBuilder uriBuilder) {
249             return CLIENT.target(uriBuilder);
250         }
251
252         @Override
253         public WebTarget target(Link link) {
254             return CLIENT.target(link);
255         }
256
257         @Override
258         public Invocation.Builder invocation(Link link) {
259             return CLIENT.invocation(link);
260         }
261
262         @Override
263         public SSLContext getSslContext() {
264             return CLIENT.getSslContext();
265         }
266
267         @Override
268         public HostnameVerifier getHostnameVerifier() {
269             return CLIENT.getHostnameVerifier();
270         }
271
272         @Override
273         public javax.ws.rs.core.Configuration getConfiguration() {
274             return CLIENT.getConfiguration();
275         }
276
277         @Override
278         public Client property(String name, Object value) {
279             return CLIENT.property(name, value);
280         }
281
282         @Override
283         public Client register(Class<?> componentClass) {
284             return CLIENT.register(componentClass);
285         }
286
287         @Override
288         public Client register(Class<?> componentClass, int priority) {
289             return CLIENT.register(componentClass, priority);
290         }
291
292         @Override
293         public Client register(Class<?> componentClass, Class<?>... contracts) {
294             return CLIENT.register(componentClass, contracts);
295         }
296
297         @Override
298         public Client register(Class<?> componentClass, Map<Class<?>, Integer> contracts) {
299             return CLIENT.register(componentClass, contracts);
300         }
301
302         @Override
303         public Client register(Object component) {
304             return CLIENT.register(component);
305         }
306
307         @Override
308         public Client register(Object component, int priority) {
309             return CLIENT.register(component, priority);
310         }
311
312         @Override
313         public Client register(Object component, Class<?>... contracts) {
314             return CLIENT.register(component, contracts);
315         }
316
317         @Override
318         public Client register(Object component, Map<Class<?>, Integer> contracts) {
319             return CLIENT.register(component, contracts);
320         }
321     }
322
323     static class FileConfiguration implements Configuration {
324
325         @Override
326         public String getGetUri() {
327             return LazyFileConfiguration.INSTANCE.getGetUri();
328         }
329
330         @Override
331         public String getDownloadUri() {
332             return LazyFileConfiguration.INSTANCE.getDownloadUri();
333         }
334
335         private static class LazyFileConfiguration implements Configuration {
336
337             private static final String CONFIG_NAMESPACE = "vnfrepo";
338
339             private static final String DEFAULT_HOST = "localhost";
340             private static final String DEFAULT_PORT = "8702";
341
342             private static final String DEFAULT_URI_PREFIX = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
343             private static final String DEFAULT_LIST_URI = DEFAULT_URI_PREFIX + "/";
344             private static final String DEFAULT_DOWNLOAD_URI = DEFAULT_URI_PREFIX + "/%s/files";
345
346             private static final LazyFileConfiguration INSTANCE = new LazyFileConfiguration();
347
348             private final String getUri;
349             private final String downloadUri;
350
351             private LazyFileConfiguration() {
352                 org.onap.config.api.Configuration config = ConfigurationManager.lookup();
353                 String host = readConfig(config, "vnfRepoHost", DEFAULT_HOST);
354                 String port = readConfig(config, "vnfRepoPort", DEFAULT_PORT);
355                 String listPackagesUri = readConfig(config, "getVnfUri", DEFAULT_LIST_URI);
356                 String downloadPackageUri = readConfig(config, "downloadVnfUri", DEFAULT_DOWNLOAD_URI);
357                 this.getUri = formatUri(host, port, listPackagesUri);
358                 this.downloadUri = formatUri(host, port, downloadPackageUri);
359             }
360
361             private String readConfig(org.onap.config.api.Configuration config, String key, String defaultValue) {
362
363                 try {
364                     String value = config.getAsString(CONFIG_NAMESPACE, key);
365                     return (value == null) ? defaultValue : value;
366                 } catch (Exception e) {
367                     LOGGER.error(
368                             "Failed to read VNF repository configuration key '{}', default value '{}' will be used",
369                             key, defaultValue, e);
370                     return defaultValue;
371                 }
372             }
373
374             private static String formatUri(String host, String port, String path) {
375                 return "http://" + host + ":" + port + (path.startsWith("/") ? path : "/" + path);
376             }
377
378             public String getGetUri() {
379                 return getUri;
380             }
381
382             public String getDownloadUri() {
383                 return downloadUri;
384             }
385         }
386     }
387 }