Merge "Step version for release"
[portal/nonrtric-controlpanel.git] / webapp-backend / src / main / java / org / oransc / portal / nonrtric / controlpanel / util / AsyncRestClient.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.portal.nonrtric.controlpanel.util;
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.lang.invoke.MethodHandles;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.cert.Certificate;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
39 import java.util.Collections;
40 import java.util.List;
41 import java.util.concurrent.atomic.AtomicInteger;
42 import java.util.stream.Collectors;
43
44 import org.immutables.value.Value;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.http.MediaType;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
50 import org.springframework.lang.Nullable;
51 import org.springframework.util.ResourceUtils;
52 import org.springframework.web.reactive.function.client.ExchangeStrategies;
53 import org.springframework.web.reactive.function.client.WebClient;
54 import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
55 import org.springframework.web.reactive.function.client.WebClientResponseException;
56
57 import reactor.core.publisher.Mono;
58 import reactor.netty.http.client.HttpClient;
59 import reactor.netty.resources.ConnectionProvider;
60 import reactor.netty.tcp.TcpClient;
61
62 /**
63  * Generic reactive REST client.
64  */
65 public class AsyncRestClient {
66
67     @Value.Immutable
68     @Value.Style(redactedMask = "####")
69     public interface WebClientConfig {
70         public boolean isTrustStoreUsed();
71
72         @Value.Redacted
73         public String trustStorePassword();
74
75         public String trustStore();
76     }
77
78     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
79     private WebClient webClient = null;
80     private final String baseUrl;
81     private static final AtomicInteger sequenceNumber = new AtomicInteger();
82     private final WebClientConfig clientConfig;
83     static KeyStore clientTrustStore = null;
84
85     public AsyncRestClient(String baseUrl) {
86         this(baseUrl,
87             ImmutableWebClientConfig.builder().isTrustStoreUsed(false).trustStore("").trustStorePassword("").build());
88     }
89
90     public AsyncRestClient(String baseUrl, WebClientConfig config) {
91         this.baseUrl = baseUrl;
92         this.clientConfig = config;
93     }
94
95     public Mono<ResponseEntity<String>> postForEntity(String uri, @Nullable String body) {
96         Object traceTag = createTraceTag();
97         logger.debug("{} POST uri = '{}{}''", traceTag, baseUrl, uri);
98         logger.trace("{} POST body: {}", traceTag, body);
99         Mono<String> bodyProducer = body != null ? Mono.just(body) : Mono.empty();
100         return getWebClient() //
101             .flatMap(client -> {
102                 RequestHeadersSpec<?> request = client.post() //
103                     .uri(uri) //
104                     .contentType(MediaType.APPLICATION_JSON) //
105                     .body(bodyProducer, String.class);
106                 return retrieve(traceTag, request);
107             });
108     }
109
110     public Mono<String> post(String uri, @Nullable String body) {
111         return postForEntity(uri, body) //
112             .flatMap(this::toBody);
113     }
114
115     public Mono<String> postWithAuthHeader(String uri, String body, String username, String password) {
116         Object traceTag = createTraceTag();
117         logger.debug("{} POST (auth) uri = '{}{}''", traceTag, baseUrl, uri);
118         logger.trace("{} POST body: {}", traceTag, body);
119         return getWebClient() //
120             .flatMap(client -> {
121                 RequestHeadersSpec<?> request = client.post() //
122                     .uri(uri) //
123                     .headers(headers -> headers.setBasicAuth(username, password)) //
124                     .contentType(MediaType.APPLICATION_JSON) //
125                     .bodyValue(body);
126                 return retrieve(traceTag, request) //
127                     .flatMap(this::toBody);
128             });
129     }
130
131     public Mono<ResponseEntity<String>> putForEntity(String uri, String body) {
132         Object traceTag = createTraceTag();
133         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
134         logger.trace("{} PUT body: {}", traceTag, body);
135         return getWebClient() //
136             .flatMap(client -> {
137                 RequestHeadersSpec<?> request = client.put() //
138                     .uri(uri) //
139                     .contentType(MediaType.APPLICATION_JSON) //
140                     .bodyValue(body);
141                 return retrieve(traceTag, request);
142             });
143     }
144
145     public Mono<ResponseEntity<String>> putForEntity(String uri) {
146         Object traceTag = createTraceTag();
147         logger.debug("{} PUT uri = '{}{}''", traceTag, baseUrl, uri);
148         logger.trace("{} PUT body: <empty>", traceTag);
149         return getWebClient() //
150             .flatMap(client -> {
151                 RequestHeadersSpec<?> request = client.put() //
152                     .uri(uri);
153                 return retrieve(traceTag, request);
154             });
155     }
156
157     public Mono<String> put(String uri, String body) {
158         return putForEntity(uri, body) //
159             .flatMap(this::toBody);
160     }
161
162     public Mono<ResponseEntity<String>> getForEntity(String uri) {
163         Object traceTag = createTraceTag();
164         logger.debug("{} GET uri = '{}{}''", traceTag, baseUrl, uri);
165         return getWebClient() //
166             .flatMap(client -> {
167                 RequestHeadersSpec<?> request = client.get().uri(uri);
168                 return retrieve(traceTag, request);
169             });
170     }
171
172     public Mono<String> get(String uri) {
173         return getForEntity(uri) //
174             .flatMap(this::toBody);
175     }
176
177     public Mono<ResponseEntity<String>> deleteForEntity(String uri) {
178         Object traceTag = createTraceTag();
179         logger.debug("{} DELETE uri = '{}{}''", traceTag, baseUrl, uri);
180         return getWebClient() //
181             .flatMap(client -> {
182                 RequestHeadersSpec<?> request = client.delete().uri(uri);
183                 return retrieve(traceTag, request);
184             });
185     }
186
187     public Mono<String> delete(String uri) {
188         return deleteForEntity(uri) //
189             .flatMap(this::toBody);
190     }
191
192     private Mono<ResponseEntity<String>> retrieve(Object traceTag, RequestHeadersSpec<?> request) {
193         final Class<String> clazz = String.class;
194         return request.retrieve() //
195             .toEntity(clazz) //
196             .doOnNext(entity -> logger.trace("{} Received: {}", traceTag, entity.getBody())) //
197             .doOnError(throwable -> onHttpError(traceTag, throwable));
198     }
199
200     private static Object createTraceTag() {
201         return sequenceNumber.incrementAndGet();
202     }
203
204     private void onHttpError(Object traceTag, Throwable t) {
205         if (t instanceof WebClientResponseException) {
206             WebClientResponseException exception = (WebClientResponseException) t;
207             logger.debug("{} HTTP error status = '{}', body '{}'", traceTag, exception.getStatusCode(),
208                 exception.getResponseBodyAsString());
209         } else {
210             logger.debug("{} HTTP error: {}", traceTag, t.getMessage());
211         }
212     }
213
214     private Mono<String> toBody(ResponseEntity<String> entity) {
215         if (entity.getBody() == null) {
216             return Mono.just("");
217         } else {
218             return Mono.just(entity.getBody());
219         }
220     }
221
222     private boolean isCertificateEntry(KeyStore trustStore, String alias) {
223         try {
224             return trustStore.isCertificateEntry(alias);
225         } catch (KeyStoreException e) {
226             logger.error("Error reading truststore {}", e.getMessage());
227             return false;
228         }
229     }
230
231     private Certificate getCertificate(KeyStore trustStore, String alias) {
232         try {
233             return trustStore.getCertificate(alias);
234         } catch (KeyStoreException e) {
235             logger.error("Error reading truststore {}", e.getMessage());
236             return null;
237         }
238     }
239
240     private static synchronized KeyStore getTrustStore(String trustStorePath, String trustStorePass)
241         throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
242         if (clientTrustStore == null) {
243             KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
244             store.load(new FileInputStream(ResourceUtils.getFile(trustStorePath)), trustStorePass.toCharArray());
245             clientTrustStore = store;
246         }
247         return clientTrustStore;
248     }
249
250     private SslContext createSslContextRejectingUntrustedPeers(String trustStorePath, String trustStorePass)
251         throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
252
253         final KeyStore trustStore = getTrustStore(trustStorePath, trustStorePass);
254         List<Certificate> certificateList = Collections.list(trustStore.aliases()).stream() //
255             .filter(alias -> isCertificateEntry(trustStore, alias)) //
256             .map(alias -> getCertificate(trustStore, alias)) //
257             .collect(Collectors.toList());
258         final X509Certificate[] certificates = certificateList.toArray(new X509Certificate[certificateList.size()]);
259
260         return SslContextBuilder.forClient() //
261             .trustManager(certificates) //
262             .build();
263     }
264
265     private SslContext createSslContext()
266         throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
267         if (this.clientConfig.isTrustStoreUsed()) {
268             return createSslContextRejectingUntrustedPeers(this.clientConfig.trustStore(),
269                 this.clientConfig.trustStorePassword());
270         } else {
271             // Trust anyone
272             return SslContextBuilder.forClient() //
273                 .trustManager(InsecureTrustManagerFactory.INSTANCE) //
274                 .build();
275         }
276     }
277
278     private WebClient createWebClient(String baseUrl, SslContext sslContext) {
279         ConnectionProvider connectionProvider = ConnectionProvider.newConnection();
280         TcpClient tcpClient = TcpClient.create(connectionProvider) //
281             .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10_000) //
282             .secure(c -> c.sslContext(sslContext)) //
283
284             .doOnConnected(connection -> {
285                 connection.addHandlerLast(new ReadTimeoutHandler(30));
286                 connection.addHandlerLast(new WriteTimeoutHandler(30));
287             });
288         HttpClient httpClient = HttpClient.from(tcpClient);
289         ReactorClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
290
291         ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder() //
292             .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) //
293             .build();
294
295         return WebClient.builder() //
296             .clientConnector(connector) //
297             .baseUrl(baseUrl) //
298             .exchangeStrategies(exchangeStrategies) //
299             .build();
300     }
301
302     private Mono<WebClient> getWebClient() {
303         if (this.webClient == null) {
304             try {
305                 SslContext sslContext = createSslContext();
306                 this.webClient = createWebClient(this.baseUrl, sslContext);
307             } catch (Exception e) {
308                 logger.error("Could not create WebClient {}", e.getMessage());
309                 return Mono.error(e);
310             }
311         }
312         return Mono.just(this.webClient);
313     }
314
315 }