acbfb328f1b4670a05b3132964db2275b20e7550
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vnf-repository-rest-services / src / main / java / org / openecomp / sdcrests / vsp / rest / services / VnfPackageRepositoryImpl.java
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 package org.openecomp.sdcrests.vsp.rest.services;
17
18 import org.apache.http.HttpStatus;
19 import org.openecomp.sdc.logging.api.Logger;
20 import org.openecomp.sdc.logging.api.LoggerFactory;
21 import org.openecomp.sdc.logging.messages.AuditMessages;
22 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
23 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
24 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
25 import org.openecomp.sdc.versioning.types.VersionableEntityAction;
26 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
27 import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
28 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
29 import org.springframework.context.annotation.Scope;
30 import org.springframework.stereotype.Service;
31 import org.openecomp.sdc.common.rest.api.IRestClient;
32 import org.openecomp.sdc.common.rest.api.RestConfigurationInfo;
33 import org.openecomp.sdc.common.rest.api.RestResponse;
34 import org.openecomp.sdc.common.rest.impl.RestClientServiceFactory;
35 import org.openecomp.config.api.Configuration;
36 import org.openecomp.config.api.ConfigurationManager;
37
38 import java.io.BufferedInputStream;
39 import java.io.ByteArrayInputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.nio.charset.StandardCharsets;
43
44 import javax.inject.Named;
45 import javax.ws.rs.core.Response;
46
47 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
48 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
49
50 /**
51  * 
52  * The class implements the API interface with VNF Repository (VNFSDK) such as
53  * i) Get all the VNF Package Meta-data ii) Download the VNF Package iii) Import
54  * VNF package to SDC catalog (Download & validate)
55  * 
56  * @version Amsterdam release (ONAP 1.0)
57  * 
58  */
59 @Named
60 @Service("vnfPackageRepository")
61 @Scope(value = "prototype")
62 public class VnfPackageRepositoryImpl implements VnfPackageRepository {
63
64         private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
65         private static IRestClient iRestClnt = null;
66         private static boolean initFlag = false;
67
68         // Default VNF Repository configuration
69         private static final String CONFIG_NAMESPACE = "vnfsdk";
70
71         // Default address for VNF repository docker
72         private static final String DEF_DOCKER_COMPOSE_ADDR = "172.18.0.1";
73         private static String ipAddress = DEF_DOCKER_COMPOSE_ADDR;
74
75         // Default Download package URI and Get VNF package meta-data URI -
76         // configurable
77         private static String getVnfPkgUri = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
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.audit(AuditMessages.AUDIT_MSG, "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                 RestResponse rsp = iRestClnt.doGET(getVnfPkgUri, null);
93                 if (HttpStatus.SC_OK != rsp.getHttpStatusCode()) {
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.audit(AuditMessages.AUDIT_MSG, "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                 RestResponse rsp = iRestClnt.doGET(getVnfPkgUri, null);
115                 if (HttpStatus.SC_OK != rsp.getHttpStatusCode()) {
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(AuditMessages.AUDIT_MSG, "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 = OrchestrationTemplateCandidateManagerFactory
127                                         .getInstance().createInterface();
128                         UploadFileResponse uploadFileResponse = candidateManager.upload(vspId,
129                                         resolveVspVersion(vspId, null, user, VersionableEntityAction.Write), fileStream, user,
130                                         getFileExtension(filename), getNetworkPackageName(filename));
131
132                         UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
133                                         .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
134
135                         return Response.ok(uploadFileResponseDto).build();
136                 } catch (IOException e) {
137                         // Exception while uploading file
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.audit(AuditMessages.AUDIT_MSG + "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                 RestResponse rsp = iRestClnt.doGET(uri, null);
154                 if (HttpStatus.SC_OK != rsp.getHttpStatusCode()) {
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(AuditMessages.AUDIT_MSG, "Response from VNF Repository for download package is success ");
165
166                 return response.build();
167         }
168
169         private static void setRestClient() {
170
171                 if (null == iRestClnt) {
172                         RestConfigurationInfo restInfo = new RestConfigurationInfo();
173                         iRestClnt = RestClientServiceFactory.createRestClientService(restInfo);
174                         if (null == iRestClnt) {
175                                 return;
176                         }
177                 }
178         }
179
180         private static void setVnfRepoConfig() {
181
182                 try {
183                         // Step 1: Fetch the on-boarding configuration
184                         Configuration config = ConfigurationManager.lookup();
185
186                         String vnfRepoHost = config.getAsString(CONFIG_NAMESPACE, "vnfRepoHost");
187                         if (null != vnfRepoHost) {
188                                 ipAddress = vnfRepoHost;
189                         }
190
191                         String vnfRepoPort = config.getAsString(CONFIG_NAMESPACE, "vnfRepoPort");
192                         if (null != vnfRepoPort) {
193                                 port = vnfRepoPort;
194                         }
195
196                         String getVnfUri = config.getAsString(CONFIG_NAMESPACE, "getVnfUri");
197                         if (null != getVnfUri) {
198                                 getVnfPkgUri = getVnfUri;
199                         }
200
201                         String downloadVnfUri = config.getAsString(CONFIG_NAMESPACE, "downloadVnfUri");
202                         if (null != downloadVnfUri) {
203                                 downldPkgUri = downloadVnfUri;
204                         }
205
206                 } catch (Exception e) {
207                         LOGGER.error("Failed to load configuration, Exception caught, using default configuration", e);
208                 }
209
210                 getVnfPkgUri = new StringBuilder("http://").append(ipAddress).append(":").append(port).append(getVnfPkgUri)
211                                 .toString();
212
213                 downldPkgUri = new StringBuilder("http://").append(ipAddress).append(":").append(port).append(downldPkgUri)
214                                 .toString();
215         }
216
217         private static synchronized void init() throws Exception {
218                 if (!initFlag) {
219                         // Step 1: Initialize configuration
220                         setVnfRepoConfig();
221
222                         // Step 2: Initialize rest client
223                         setRestClient();
224                         if (null == iRestClnt) {
225                                 LOGGER.error("REST initialization error, Rest client is null");
226                                 throw new Exception("Rest Initializer error, Rest client is null");
227                         }
228
229                         initFlag = true;
230                 }
231         }
232 }