c3de6b2cd4a66f451ae00983a6d292fbd0f6a0cb
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.clients;
22
23 import io.netty.channel.ChannelOption;
24 import io.netty.handler.ssl.SslContext;
25 import io.netty.handler.ssl.SslContextBuilder;
26 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
27 import io.netty.handler.timeout.ReadTimeoutHandler;
28 import io.netty.handler.timeout.WriteTimeoutHandler;
29
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.lang.invoke.MethodHandles;
34 import java.security.KeyStore;
35 import java.security.KeyStoreException;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.cert.Certificate;
38 import java.security.cert.CertificateException;
39 import java.security.cert.X509Certificate;
40 import java.util.Collections;
41 import java.util.List;
42 import java.util.concurrent.atomic.AtomicInteger;
43 import java.util.stream.Collectors;
44
45 import javax.net.ssl.KeyManagerFactory;
46
47 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.http.MediaType;
51 import org.springframework.http.ResponseEntity;
52 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
53 import org.springframework.lang.Nullable;
54 import org.springframework.util.ResourceUtils;
55 import org.springframework.web.reactive.function.client.ExchangeStrategies;
56 import org.springframework.web.reactive.function.client.WebClient;
57 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
58 import org.springframework.web.reactive.function.client.WebClientResponseException;
59
60 import reactor.core.publisher.Mono;
61 import reactor.netty.http.client.HttpClient;
62 import reactor.netty.resources.ConnectionProvider;
63 import reactor.netty.tcp.TcpClient;
64
65 /**
66  * Generic reactive REST client.
67  */
68 public class AsyncRestClient {
69     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
70     private WebClient webClient = null;
71     private final String baseUrl;
72     private static final AtomicInteger sequenceNumber = new AtomicInteger();
73     private final WebClientConfig clientConfig;
74     static KeyStore clientTrustStore = null;
75     private boolean sslEnabled = true;
76
77     public AsyncRestClient(String baseUrl) {
78         this(baseUrl, null);
79         this.sslEnabled = false;
80     }
81
82     public AsyncRestClient(String baseUrl, WebClientConfig config) {
83         this.baseUrl = baseUrl;
84         this.clientConfig = config;
85     }
86
87     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
88         Object traceTag = createTraceTag();
89         logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
90         logger.trace("{} POST body: {}", traceTag, body);
91         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
92         return getWebClient() //
93             .flatMap(client -> {
94                 RequestHeadersSpec<?> request = client.post() //
95                     .uri(uri) //
96                     .contentType(MediaType.APPLICATION_JSON) //
97                     .body(bodyProducer, String.class);
98                 return retrieve(traceTag, request);
99             });
100     }
101
102     public Mono<String> post(String uri, @Nullable String body) {
103         return postForEntity(uri, body) //
104             .flatMap(this::toBody);
105     }
106
107     public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
108         Object traceTag = createTraceTag();
109         logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
110         logger.trace("{} POST body: {}", traceTag, body);
111         return getWebClient() //
112             .flatMap(client -> {
113                 RequestHeadersSpec<?> request = client.post() //
114                     .uri(uri) //
115                     .headers(headers -> headers.setBasicAuth(username, password)) //
116                     .contentType(MediaType.APPLICATION_JSON) //
117                     .bodyValue(body);
118                 return retrieve(traceTag, request) //
119                     .flatMap(this::toBody);
120             });
121     }
122
123     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
124         Object traceTag = createTraceTag();
125         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
126         logger.trace("{} PUT body: {}", traceTag, body);
127         return getWebClient() //
128             .flatMap(client -> {
129                 RequestHeadersSpec<?> request = client.put() //
130                     .uri(uri) //
131                     .contentType(MediaType.APPLICATION_JSON) //
132                     .bodyValue(body);
133                 return retrieve(traceTag, request);
134             });
135     }
136
137     public Mono<ResponseEntity<String>> putForEntity(String uri) {
138         Object traceTag = createTraceTag();
139         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
140         logger.trace("{} PUT body: <empty>", traceTag);
141         return getWebClient() //
142             .flatMap(client -> {
143                 RequestHeadersSpec<?> request = client.put() //
144                     .uri(uri);
145                 return retrieve(traceTag, request);
146             });
147     }
148
149     public Mono<String> put(String uri, String body) {
150         return putForEntity(uri, body) //
151             .flatMap(this::toBody);
152     }
153
154     public Mono<ResponseEntity<String>> getForEntity(String uri) {
155         Object traceTag = createTraceTag();
156         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
157         return getWebClient() //
158             .flatMap(client -> {
159                 RequestHeadersSpec<?> request = client.get().uri(uri);
160                 return retrieve(traceTag, request);
161             });
162     }
163
164     public Mono<String> get(String uri) {
165         return getForEntity(uri) //
166             .flatMap(this::toBody);
167     }
168
169     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
170         Object traceTag = createTraceTag();
171         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
172         return getWebClient() //
173             .flatMap(client -> {
174                 RequestHeadersSpec<?> request = client.delete().uri(uri);
175                 return retrieve(traceTag, request);
176             });
177     }
178
179     public Mono<String> delete(String uri) {
180         return deleteForEntity(uri) //
181             .flatMap(this::toBody);
182     }
183
184     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
185         final Class<String> clazz = String.class;
186         return request.retrieve() //
187             .toEntity(clazz) //
188             .doOnNext(entity -> logReceivedData(traceTag, entity)) //
189             .doOnError(throwable -> onHttpError(traceTag, throwable));
190     }
191
192     private void logReceivedData(Object traceTag, ResponseEntity<String> entity) {
193         logger.trace("{} Received: {} {}", traceTag, entity.getBody(), entity.getHeaders().getContentType());
194     }
195
196     private static Object createTraceTag() {
197         return sequenceNumber.incrementAndGet();
198     }
199
200     private void onHttpError(Object traceTag, Throwable t) {
201         if (t instanceof WebClientResponseException) {
202             WebClientResponseException exception = (WebClientResponseException) t;
203             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
204                 exception.getResponseBodyAsString());
205         } else {
206             logger.debug("{} HTTP error", traceTag, t);
207         }
208     }
209
210     private Mono<String> toBody(ResponseEntity<String> entity) {
211         if (entity.getBody() == null) {
212             return Mono.just("");
213         } else {
214             return Mono.just(entity.getBody());
215         }
216     }
217
218     private boolean isCertificateEntry(KeyStore trustStore, String alias) {
219         try {
220             return trustStore.isCertificateEntry(alias);
221         } catch (KeyStoreException e) {
222             logger.error("Error reading truststore {}", e.getMessage());
223             return false;
224         }
225     }
226
227     private Certificate getCertificate(KeyStore trustStore, String alias) {
228         try {
229             return trustStore.getCertificate(alias);
230         } catch (KeyStoreException e) {
231             logger.error("Error reading truststore {}", e.getMessage());
232             return null;
233         }
234     }
235
236     private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
237         throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
238         if (clientTrustStore == null) {
239             KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
240             store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
241             clientTrustStore = store;
242         }
243         return clientTrustStore;
244     }
245
246     private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass,
247         KeyManagerFactory keyManager)
248         throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
249
250         final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
251         List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
252             .filter(alias -> isCertificateEntry(trustStore, alias)) //
253             .map(alias -> getCertificate(trustStore, alias)) //
254             .collect(Collectors.toList());
255         final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
256
257         return SslContextBuilder.forClient() //
258             .keyManager(keyManager) //
259             .trustManager(certificates) //
260             .build();
261     }
262
263     private SslContext createSslContext(KeyManagerFactory keyManager)
264         throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
265         if (this.clientConfig.isTrustStoreUsed()) {
266             return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
267                 this.clientConfig.trustStorePassword(), keyManager);
268         } else {
269             // Trust anyone
270             return SslContextBuilder.forClient() //
271                 .keyManager(keyManager) //
272                 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
273                 .build();
274         }
275     }
276
277     private TcpClient createTcpClientSecure(SslContext sslContext) {
278         return TcpClient.create(ConnectionProvider.newConnection()) //
279             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
280             .secure(c -> c.sslContext(sslContext)) //
281             .doOnConnected(connection -> {
282                 connection.addHandlerLast(new ReadTimeoutHandler(30));
283                 connection.addHandlerLast(new WriteTimeoutHandler(30));
284             });
285     }
286
287     private TcpClient createTcpClientInsecure() {
288         return TcpClient.create(ConnectionProvider.newConnection()) //
289             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
290             .doOnConnected(connection -> {
291                 connection.addHandlerLast(new ReadTimeoutHandler(30));
292                 connection.addHandlerLast(new WriteTimeoutHandler(30));
293             });
294     }
295
296     private WebClient createWebClient(String baseUrl, TcpClient tcpClient) {
297         HttpClient httpClient = HttpClient.from(tcpClient);
298         ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
299         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
300             .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
301             .build();
302         return WebClient.builder() //
303             .clientConnector(connector) //
304             .baseUrl(baseUrl) //
305             .exchangeStrategies(exchangeStrategies) //
306             .build();
307     }
308
309     private Mono<WebClient> getWebClient() {
310         if (this.webClient == null) {
311             try {
312                 if (this.sslEnabled) {
313                     final KeyManagerFactory keyManager =
314                         KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
315                     final KeyStore keyStore = KeyStore.getInstance(this.clientConfig.keyStoreType());
316                     final String keyStoreFile = this.clientConfig.keyStore();
317                     final String keyStorePassword = this.clientConfig.keyStorePassword();
318                     final String keyPassword = this.clientConfig.keyPassword();
319                     try (final InputStream inputStream = new FileInputStream(keyStoreFile)) {
320                         keyStore.load(inputStream, keyStorePassword.toCharArray());
321                     }
322                     keyManager.init(keyStore, keyPassword.toCharArray());
323                     SslContext sslContext = createSslContext(keyManager);
324                     TcpClient tcpClient = createTcpClientSecure(sslContext);
325                     this.webClient = createWebClient(this.baseUrl, tcpClient);
326                 } else {
327                     TcpClient tcpClient = createTcpClientInsecure();
328                     this.webClient = createWebClient(this.baseUrl, tcpClient);
329                 }
330             } catch (Exception e) {
331                 logger.error("Could not create WebClient {}", e.getMessage());
332                 return Mono.error(e);
333             }
334         }
335         return Mono.just(this.webClient);
336     }
337
338 }