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