439fd1475ff88be31c1ed7744a604508ef23ac01
[sdc.git] /
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdcrests.vsp.rest.services;
18
19 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
20 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
21 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
22
23 import java.io.BufferedInputStream;
24 import java.io.ByteArrayInputStream;
25 import java.io.InputStream;
26 import java.nio.charset.StandardCharsets;
27
28 import javax.inject.Named;
29 import javax.ws.rs.core.Response;
30
31 import org.apache.http.HttpStatus;
32 import org.openecomp.config.api.Configuration;
33 import org.openecomp.config.api.ConfigurationManager;
34 import org.openecomp.sdc.common.http.client.api.HttpRequest;
35 import org.openecomp.sdc.common.http.client.api.HttpResponse;
36 import org.openecomp.sdc.logging.api.Logger;
37 import org.openecomp.sdc.logging.api.LoggerFactory;
38 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
39 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
40 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
41 import org.openecomp.sdc.versioning.VersioningManager;
42 import org.openecomp.sdc.versioning.VersioningManagerFactory;
43 import org.openecomp.sdc.versioning.dao.types.Version;
44 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
45 import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
46 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
47 import org.springframework.context.annotation.Scope;
48 import org.springframework.stereotype.Service;
49
50 /**
51  * The class implements the API interface with VNF Repository (VNFSDK) such as
52  * i) Get all the VNF Package Meta-data ii) Download the VNF Package iii) Import
53  * VNF package to SDC catalog (Download & validate)
54  * 
55  * @version Amsterdam release (ONAP 1.0)
56  */
57 @Named
58 @Service("vnfPackageRepository")
59 @Scope(value = "prototype")
60 public class VnfPackageRepositoryImpl implements VnfPackageRepository {
61
62     private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
63
64     private static boolean initFlag = false;
65
66     // Default VNF Repository configuration
67     private static final String CONFIG_NAMESPACE = "vnfrepo";
68
69     // Default address for VNF repository docker
70     private static final String DEF_DOCKER_COMPOSE_ADDR = "127.0.0.1";
71
72     private static String ipAddress = DEF_DOCKER_COMPOSE_ADDR;
73
74     // Default Download package URI and Get VNF package meta-data URI -
75     // configurable
76     private static String getVnfPkgUri = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
77
78     private static String downldPkgUri = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars/%s/files";
79
80     // Default port for VNF Repository
81     private static String port = "8702";
82
83     @Override
84     public Response getVnfPackages(String vspId, String versionId, String user) throws Exception {
85
86         LOGGER.debug("Get VNF Packages from Repository:{}", vspId);
87
88         // Step 1: Create REST client and configuration and prepare URI
89         init();
90
91         // Step 2: Build URI based on the IP address and port allocated
92         HttpResponse<String> rsp = HttpRequest.get(getVnfPkgUri);
93         if(HttpStatus.SC_OK != rsp.getStatusCode()) {
94             LOGGER.error("Failed to query VNF package metadata:uri={}, Response={}", getVnfPkgUri, rsp);
95             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
96         }
97
98         // Step 3: Send the response to the client
99         LOGGER.debug("Response from VNF Repository: {}", rsp.getResponse());
100
101         return Response.ok(rsp.getResponse()).build();
102     }
103
104     @Override
105     public Response importVnfPackage(String vspId, String versionId, String csarId, String user) throws Exception {
106
107         LOGGER.debug("Import VNF Packages from Repository:{}", csarId);
108
109         // Step 1: Create REST client and configuration and prepare URI
110         init();
111
112         // Step 2: Build URI based on the IP address and port allocated
113         String uri = String.format(downldPkgUri, csarId);
114         HttpResponse<String> rsp = HttpRequest.get(uri);
115         if(HttpStatus.SC_OK != rsp.getStatusCode()) {
116             LOGGER.error("Failed to download package from VNF Repository:uri={}, Response={}", uri, rsp);
117             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
118         }
119         LOGGER.debug("Response from VNF Repository for download package is success ");
120
121         // Step 3: Import the file to SDC and validate and send the response
122         try (InputStream fileStream = new BufferedInputStream(
123                 new ByteArrayInputStream(rsp.getResponse().getBytes(StandardCharsets.ISO_8859_1)))) {
124
125             String filename = "temp_" + csarId + ".csar";
126             OrchestrationTemplateCandidateManager candidateManager =
127                     OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
128             UploadFileResponse uploadFileResponse = candidateManager.upload(vspId, getVersion(vspId, versionId),
129                     fileStream, getFileExtension(filename), getNetworkPackageName(filename));
130
131             UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
132                     .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
133
134             return Response.ok(uploadFileResponseDto).build();
135         } catch(Exception e) {
136             // Exception while uploading file
137
138             LOGGER.error("Exception while uploading VNF package received from VNF Repository:", e);
139             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
140         }
141     }
142
143     @Override
144     public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) throws Exception {
145
146         LOGGER.debug("Download VNF Packages from Repository:csarId={}", csarId);
147
148         // Step 1: Create REST client and configuration and prepare URI
149         init();
150
151         // Step 2: Build URI based on the IP address and port allocated
152         String uri = String.format(downldPkgUri, csarId);
153         HttpResponse<String> rsp = HttpRequest.get(uri);
154         if(HttpStatus.SC_OK != rsp.getStatusCode()) {
155             LOGGER.error("Failed to download package from VNF Repository:uri={}, Response={}", uri, rsp);
156             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
157         }
158
159         // Step 3:Send response to the client
160         String filename = "temp_" + csarId + ".csar";
161         Response.ResponseBuilder response = Response.ok(rsp.getResponse().getBytes(StandardCharsets.ISO_8859_1));
162         response.header(CONTENT_DISPOSITION, "attachment; filename=" + filename);
163
164         LOGGER.debug("Response from VNF Repository for download package is success ");
165
166         return response.build();
167     }
168
169     private Version getVersion(String vspId, String versionId) {
170         // Get list of Versions from the rest call
171         VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
172
173         // Find the corresponding version from versionId
174         return versioningManager.list(vspId).stream().filter(ver -> ver.getId() != versionId).findAny()
175                 .orElse(new Version(versionId));
176     }
177
178     private static void setVnfRepoConfig() {
179
180         try {
181             // Step 1: Fetch the on-boarding configuration
182             Configuration config = ConfigurationManager.lookup();
183
184             String vnfRepoHost = config.getAsString(CONFIG_NAMESPACE, "vnfRepoHost");
185             if(null != vnfRepoHost) {
186                 ipAddress = vnfRepoHost;
187             }
188
189             String vnfRepoPort = config.getAsString(CONFIG_NAMESPACE, "vnfRepoPort");
190             if(null != vnfRepoPort) {
191                 port = vnfRepoPort;
192             }
193
194             String getVnfUri = config.getAsString(CONFIG_NAMESPACE, "getVnfUri");
195             if(null != getVnfUri) {
196                 getVnfPkgUri = getVnfUri;
197             }
198
199             String downloadVnfUri = config.getAsString(CONFIG_NAMESPACE, "downloadVnfUri");
200             if(null != downloadVnfUri) {
201                 downldPkgUri = downloadVnfUri;
202             }
203
204         } catch(Exception e) {
205             LOGGER.error("Failed to load configuration, Exception caught, using default configuration", e);
206         }
207
208         getVnfPkgUri =
209                 new StringBuilder("http://").append(ipAddress).append(":").append(port).append(getVnfPkgUri).toString();
210
211         downldPkgUri =
212                 new StringBuilder("http://").append(ipAddress).append(":").append(port).append(downldPkgUri).toString();
213     }
214
215     private static synchronized void init() throws Exception {
216         if(!initFlag) {
217             // Step 1: Initialize configuration
218             setVnfRepoConfig();
219
220             initFlag = true;
221         }
222     }
223 }