aboutsummaryrefslogtreecommitdiffstats
path: root/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
blob: 9ee86889f5edee7da4b28782012b2a0c364f9247 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * Copyright 2017 Huawei Technologies Co., Ltd.
 * Modifications Copyright 2018 European Support Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openecomp.sdcrests.vsp.rest.services;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.inject.Named;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.onap.config.api.ConfigurationManager;
import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.errors.ErrorCode;
import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
import org.openecomp.sdc.versioning.VersioningManager;
import org.openecomp.sdc.versioning.VersioningManagerFactory;
import org.openecomp.sdc.versioning.dao.types.Version;
import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;

/**
 * Enables integration API interface with VNF Repository (VNFSDK).
 * <ol>
 *     <li>Get all the VNF Package Meta-data.</li>
 *     <li>Download a VNF Package.</li>
 *     <li>Import a VNF package to SDC catalog (Download & validate).</li>
 * </ol>
 *
 * @version Amsterdam release (ONAP 1.0)
 */
@Named
@Service("vnfPackageRepository")
@Scope(value = "prototype")
public class VnfPackageRepositoryImpl implements VnfPackageRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
    private static final Client CLIENT = ignoreSSLClient();

    private static Client ignoreSSLClient() {
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] c, String s) {}
                public void checkServerTrusted(X509Certificate[] c, String s) {}
                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
            }}, new java.security.SecureRandom());

            return ClientBuilder.newBuilder()
                    .sslContext(sslcontext)
                    .hostnameVerifier((a, b) -> true)
                    .build();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            LOGGER.error("Failed to initialize SSL unsecure context", e);
        }
        return ClientBuilder.newClient();
    }
    private final Configuration config;

    public VnfPackageRepositoryImpl(Configuration config) {
        this.config = config;
    }

    public VnfPackageRepositoryImpl() {
        this(new FileConfiguration());
    }

    @Override
    public Response getVnfPackages(String vspId, String versionId, String user) {
        LOGGER.debug("Get VNF Packages from Repository: {}", vspId);
        final String getVnfPackageUri = config.getGetUri();
        Response remoteResponse = CLIENT.target(getVnfPackageUri).request().get();
        if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
            return handleUnexpectedStatus("querying VNF package metadata", getVnfPackageUri, remoteResponse);
        }
        LOGGER.debug("Response from VNF Repository: {}", remoteResponse);
        return Response.ok(remoteResponse.readEntity(String.class)).build();
    }

    @Override
    public Response importVnfPackage(String vspId, String versionId, String csarId, String user) {
        LOGGER.debug("Import VNF Packages from Repository: {}", csarId);
        final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);

        Response remoteResponse = CLIENT.target(downloadPackageUri).request().get();
        if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
            return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
        }

        LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
        byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
        return uploadVnfPackage(vspId, versionId, csarId, payload);
    }

    private Response uploadVnfPackage(final String vspId, final String versionId,
                                      final String csarId, final byte[] payload) {
        try {
            final OrchestrationTemplateCandidateManager candidateManager =
                    OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
            final String filename = formatFilename(csarId);
            final String fileExtension = getFileExtension(filename);
            final OnboardPackageInfo onboardPackageInfo =
                new OnboardPackageInfo(getNetworkPackageName(filename), fileExtension, ByteBuffer.wrap(payload),
                    OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension));
            final VspDetails vspDetails = new VspDetails(vspId, getVersion(vspId, versionId));
            final UploadFileResponse response = candidateManager.upload(vspDetails, onboardPackageInfo);
            final UploadFileResponseDto uploadFileResponse =
                new MapUploadFileResponseToUploadFileResponseDto()
                    .applyMapping(response, UploadFileResponseDto.class);

            return Response.ok(uploadFileResponse).build();

        } catch (final Exception e) {
            ErrorCode error = new GeneralErrorBuilder().build();
            LOGGER.error("Exception while uploading package received from VNF Repository", new CoreException(error, e));
            return generateInternalServerError(error);
        }
    }

    @Override
    public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) {
        LOGGER.debug("Download VNF package from repository: csarId={}", csarId);
        final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);

        Response remoteResponse = CLIENT.target(downloadPackageUri).request().get();
        if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
            return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
        }

        byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
        Response.ResponseBuilder response = Response.ok(payload);
        response.header(CONTENT_DISPOSITION, "attachment; filename=" + formatFilename(csarId));

        LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
        return response.build();
    }

    private Version getVersion(String vspId, String versionId) {
        VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
        return findVersion(versioningManager.list(vspId), versionId).orElse(new Version(versionId));
    }

    Optional<Version> findVersion(List<Version> versions, String requestedVersion) {
        return versions.stream().filter(ver -> Objects.equals(ver.getId(), requestedVersion)).findAny();
    }

    private static Response handleUnexpectedStatus(String action, String uri, Response response) {

        ErrorCode error = new GeneralErrorBuilder().build();

        if (LOGGER.isErrorEnabled()) {
            String body = response.hasEntity() ? response.readEntity(String.class) : "";
            LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri,
                    response.getStatus(), body, new CoreException(error));
        }

        return generateInternalServerError(error);
    }

    private static Response generateInternalServerError(ErrorCode error) {
        ErrorCodeAndMessage payload = new ErrorCodeAndMessage(Response.Status.INTERNAL_SERVER_ERROR, error);
        return Response.serverError().entity(payload).build();
    }

    private static String formatFilename(String csarId) {
        return "temp_" + csarId + ".csar";
    }

    interface Configuration {
        String getGetUri();
        String getDownloadUri();
    }

    static class FileConfiguration implements Configuration {

        @Override
        public String getGetUri() {
            return LazyFileConfiguration.INSTANCE.getGetUri();
        }

        @Override
        public String getDownloadUri() {
            return LazyFileConfiguration.INSTANCE.getDownloadUri();
        }

        private static class LazyFileConfiguration implements Configuration {

            private static final String CONFIG_NAMESPACE = "vnfrepo";

            private static final String DEFAULT_HOST = "localhost";
            private static final String DEFAULT_PORT = "8702";

            private static final String DEFAULT_URI_PREFIX = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
            private static final String DEFAULT_LIST_URI = DEFAULT_URI_PREFIX + "/";
            private static final String DEFAULT_DOWNLOAD_URI = DEFAULT_URI_PREFIX + "/%s/files";

            private static final LazyFileConfiguration INSTANCE = new LazyFileConfiguration();

            private final String getUri;
            private final String downloadUri;

            private LazyFileConfiguration() {
                org.onap.config.api.Configuration config = ConfigurationManager.lookup();
                String host = readConfig(config, "vnfRepoHost", DEFAULT_HOST);
                String port = readConfig(config, "vnfRepoPort", DEFAULT_PORT);
                String listPackagesUri = readConfig(config, "getVnfUri", DEFAULT_LIST_URI);
                String downloadPackageUri = readConfig(config, "downloadVnfUri", DEFAULT_DOWNLOAD_URI);
                this.getUri = formatUri(host, port, listPackagesUri);
                this.downloadUri = formatUri(host, port, downloadPackageUri);
            }

            private String readConfig(org.onap.config.api.Configuration config, String key, String defaultValue) {
                try {
                    String value = config.getAsString(CONFIG_NAMESPACE, key);
                    return (value == null) ? defaultValue : value;
                } catch (Exception e) {
                    LOGGER.error("Failed to read VNF repository configuration key '{}', default value '{}' will be used",
                            key, defaultValue, e);
                    return defaultValue;
                }
            }

            private static String formatUri(String host, String port, String path) {
                return "https://" + host + ":" + port + (path.startsWith("/") ? path : "/" + path);
            }

            public String getGetUri() {
                return getUri;
            }

            public String getDownloadUri() {
                return downloadUri;
            }
        }
    }
}