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