Make rest-client request timeout in model-loader configurable
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / restclient / HttpsBabelServiceClient.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2019 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.modelloader.restclient;
23
24 import com.google.gson.Gson;
25 import com.google.gson.reflect.TypeToken;
26 import com.google.json.JsonSanitizer;
27 import com.sun.jersey.api.client.Client; // NOSONAR
28 import com.sun.jersey.api.client.ClientResponse;
29 import com.sun.jersey.api.client.WebResource;
30 import com.sun.jersey.api.client.config.DefaultClientConfig;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.security.KeyManagementException;
36 import java.security.KeyStore;
37 import java.security.KeyStoreException;
38 import java.security.NoSuchAlgorithmException;
39 import java.security.UnrecoverableKeyException;
40 import java.security.cert.CertificateException;
41 import java.security.cert.X509Certificate;
42 import java.time.ZonedDateTime;
43 import java.time.format.DateTimeFormatter;
44 import java.util.Base64;
45 import java.util.Collections;
46 import java.util.List;
47 import java.util.Objects;
48 import javax.net.ssl.HttpsURLConnection;
49 import javax.net.ssl.KeyManagerFactory;
50 import javax.net.ssl.SSLContext;
51 import javax.net.ssl.TrustManager;
52 import javax.net.ssl.TrustManagerFactory;
53 import javax.net.ssl.X509TrustManager;
54 import javax.ws.rs.core.Response;
55 import org.json.JSONException;
56 import org.json.JSONObject;
57 import org.onap.aai.babel.service.data.BabelArtifact;
58 import org.onap.aai.cl.api.LogFields;
59 import org.onap.aai.cl.api.LogLine;
60 import org.onap.aai.cl.api.Logger;
61 import org.onap.aai.cl.eelf.LoggerFactory;
62 import org.onap.aai.cl.mdc.MdcContext;
63 import org.onap.aai.cl.mdc.MdcOverride;
64 import org.onap.aai.modelloader.config.ModelLoaderConfig;
65 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
66
67 /**
68  * HTTPS Client for interfacing with Babel.
69  *
70  */
71 public class HttpsBabelServiceClient implements BabelServiceClient {
72
73     private static final Logger logger = LoggerFactory.getInstance().getLogger(HttpsBabelServiceClient.class);
74     private static final Logger metricsLogger =
75             LoggerFactory.getInstance().getMetricsLogger(HttpsBabelServiceClient.class);
76     private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
77
78     private static final String SSL_PROTOCOL = "TLS";
79     private static final String KEYSTORE_ALGORITHM = "SunX509";
80     private static final String KEYSTORE_TYPE = "PKCS12";
81
82     private final ModelLoaderConfig config;
83     private final Client client;
84
85     /**
86      * @param config
87      * @throws NoSuchAlgorithmException
88      * @throws KeyStoreException
89      * @throws CertificateException
90      * @throws IOException
91      * @throws UnrecoverableKeyException
92      * @throws KeyManagementException
93      * @throws BabelServiceClientException
94      */
95     public HttpsBabelServiceClient(ModelLoaderConfig config)
96             throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
97             UnrecoverableKeyException, KeyManagementException, BabelServiceClientException {
98         this.config = config;
99
100         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Creating Babel Service client");
101         //Initialize SSL Context only if SSL is enabled
102         if (config.useHttpsWithBabel()) {
103             SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
104             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
105             KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
106
107             String clientCertPassword = config.getBabelKeyStorePassword();
108
109             char[] pwd = null;
110             if (clientCertPassword != null) {
111                 pwd = clientCertPassword.toCharArray();
112             }
113
114             TrustManager[] trustManagers = getTrustManagers();
115
116             String clientCertFileName = config.getBabelKeyStorePath();
117             if (clientCertFileName == null) {
118                 ctx.init(null, trustManagers, null);
119             } else {
120                 InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
121                 keyStore.load(fin, pwd);
122                 kmf.init(keyStore, pwd);
123                 ctx.init(kmf.getKeyManagers(), trustManagers, null);
124             }
125
126             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Initialised context");
127
128             HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
129             HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> true);
130         }
131
132         client = Client.create(new DefaultClientConfig());
133         client.setConnectTimeout(config.getClientConnectTimeoutMs());
134         client.setReadTimeout(config.getClientReadTimeoutMs());
135
136         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Jersey client created");
137     }
138
139     private TrustManager[] getTrustManagers() throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
140             IOException, BabelServiceClientException {
141         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
142         // Using null here initializes the TMF with the default trust store.
143         tmf.init((KeyStore) null);
144
145         // Create a new Trust Manager from the local trust store.
146         String trustStoreFile = config.getBabelTrustStorePath();
147         if (trustStoreFile == null) {
148             throw new BabelServiceClientException("No Babel trust store defined");
149         }
150         try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
151             KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
152             myTrustStore.load(myKeys, config.getBabelTrustStorePassword().toCharArray());
153             tmf.init(myTrustStore);
154         }
155         X509TrustManager localTm = findX509TrustManager(tmf);
156
157         // Create a custom trust manager that wraps both our trust store and the default.
158         final X509TrustManager finalLocalTm = localTm;
159
160         // Find the default trust manager.
161         final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
162
163         return new TrustManager[] {new X509TrustManager() {
164             @Override
165             public X509Certificate[] getAcceptedIssuers() {
166                 return defaultTrustManager.getAcceptedIssuers();
167             }
168
169             @Override
170             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
171                 try {
172                     finalLocalTm.checkServerTrusted(chain, authType);
173                 } catch (CertificateException e) { // NOSONAR
174                     defaultTrustManager.checkServerTrusted(chain, authType);
175                 }
176             }
177
178             @Override
179             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
180                 defaultTrustManager.checkClientTrusted(chain, authType);
181             }
182         }};
183     }
184
185     private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
186         X509TrustManager trustManager = null;
187         for (TrustManager tm : tmf.getTrustManagers()) {
188             if (tm instanceof X509TrustManager) {
189                 trustManager = (X509TrustManager) tm;
190                 break;
191             }
192         }
193         return trustManager;
194     }
195
196     /**
197      * @param artifactPayload
198      * @param artifactName
199      * @param artifactVersion
200      * @param transactionId
201      * @return
202      * @throws BabelServiceClientException
203      * @throws JSONException
204      */
205     @Override
206     public List<BabelArtifact> postArtifact(byte[] artifactPayload, String artifactName, String artifactVersion,
207             String transactionId) throws BabelServiceClientException {
208         Objects.requireNonNull(artifactPayload);
209
210         String encodedPayload = Base64.getEncoder().encodeToString(artifactPayload);
211
212         JSONObject obj = new JSONObject();
213         try {
214             obj.put("csar", encodedPayload);
215             obj.put("artifactVersion", artifactVersion);
216             obj.put("artifactName", artifactName);
217         } catch (JSONException ex) {
218             throw new BabelServiceClientException(ex);
219         }
220
221         if (logger.isInfoEnabled()) {
222             logger.info(ModelLoaderMsgs.BABEL_REST_REQUEST_PAYLOAD, " Artifact Name: " + artifactName
223                     + " Artifact version: " + artifactVersion + " Artifact payload: " + encodedPayload);
224         }
225
226         MdcOverride override = new MdcOverride();
227         override.addAttribute(MdcContext.MDC_START_TIME, ZonedDateTime.now().format(formatter));
228
229         String resourceUrl = config.getBabelBaseUrl() + config.getBabelGenerateArtifactsUrl();
230         WebResource webResource = client.resource(resourceUrl);
231         ClientResponse response = webResource.type("application/json")
232                 .header(AaiRestClient.HEADER_TRANS_ID, Collections.singletonList(transactionId))
233                 .header(AaiRestClient.HEADER_FROM_APP_ID, Collections.singletonList(AaiRestClient.ML_APP_NAME))
234                 .post(ClientResponse.class, obj.toString());
235         String sanitizedJson = JsonSanitizer.sanitize(response.getEntity(String.class));
236
237         if (logger.isDebugEnabled()) {
238             logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT,
239                     "Babel response " + response.getStatus() + " " + sanitizedJson);
240         }
241
242         metricsLogger.info(ModelLoaderMsgs.BABEL_REST_REQUEST, new LogFields() //
243                 .setField(LogLine.DefinedFields.TARGET_ENTITY, "Babel")
244                 .setField(LogLine.DefinedFields.STATUS_CODE,
245                         Response.Status.fromStatusCode(response.getStatus()).getFamily()
246                                 .equals(Response.Status.Family.SUCCESSFUL) ? "COMPLETE" : "ERROR")
247                 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
248                 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusInfo().toString()), //
249                 override, response.toString());
250
251         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
252             throw new BabelServiceClientException(sanitizedJson);
253         }
254
255         return new Gson().fromJson(sanitizedJson, new TypeToken<List<BabelArtifact>>() {}.getType());
256     }
257 }