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