e40b936daa45b3dfc6d02170c8baa088e67e3330
[so.git] / common / src / main / java / org / onap / so / client / cds / CDSProcessingClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 Bell Canada, Deutsche Telekom.
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.so.client.cds;
22
23 import io.grpc.ManagedChannel;
24 import io.grpc.internal.DnsNameResolverProvider;
25 import io.grpc.netty.GrpcSslContexts;
26 import io.grpc.netty.NettyChannelBuilder;
27 import java.security.KeyStore;
28 import java.security.KeyStoreException;
29 import java.security.NoSuchAlgorithmException;
30 import java.util.concurrent.CountDownLatch;
31 import javax.net.ssl.SSLException;
32 import javax.net.ssl.TrustManagerFactory;
33 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
34 import org.onap.so.client.KeyStoreLoader;
35 import org.onap.so.client.PreconditionFailedException;
36 import org.onap.so.client.RestPropertiesLoader;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * <p>
42  * The CDS processing client is using gRPC for communication between SO and CDS. That communication is configured to use
43  * a streaming approach, meaning that client can send an event to which server can reply will multiple sub-responses,
44  * until full completion of the processing.
45  * </p>
46  * <p>
47  * In order for the caller to manage the callback, it is the responsibility of the caller to implement and provide a
48  * {@link CDSProcessingListener} so received messages can be handled appropriately.
49  * </p>
50  *
51  * Here is an example of implementation of such listener:
52  * 
53  * <pre>
54  * new CDSProcessingListener {
55  *
56  *     &#64;Override
57  *     public void onMessage(ExecutionServiceOutput message) {
58  *         log.info("Received notification from CDS: {}", message);
59  *     }
60  *
61  *     &#64;Override
62  *     public void onError(Throwable t) {
63  *         Status status = Status.fromThrowable(t);
64  *         log.error("Failed processing blueprint {}", status, t);
65  *     }
66  * }
67  * </pre>
68  */
69 public class CDSProcessingClient implements AutoCloseable {
70
71     private static final Logger log = LoggerFactory.getLogger(CDSProcessingClient.class);
72
73     private ManagedChannel channel;
74     private CDSProcessingHandler handler;
75
76     public CDSProcessingClient(final CDSProcessingListener listener) {
77         CDSProperties props = RestPropertiesLoader.getInstance().getNewImpl(CDSProperties.class);
78         if (props == null) {
79             throw new PreconditionFailedException(
80                     "No RestProperty.CDSProperties implementation found on classpath, can't create client.");
81         }
82         NettyChannelBuilder builder = NettyChannelBuilder.forAddress(props.getHost(), props.getPort())
83                 .nameResolverFactory(new DnsNameResolverProvider());
84         if (props.getUseSSL()) {
85             log.info("Configure SSL connection");
86             KeyStore ks = KeyStoreLoader.getKeyStore();
87             if (ks == null) {
88                 log.error("Can't load KeyStore");
89                 throw new RuntimeException("Can't load KeyStore to create secure channel");
90             }
91             try {
92                 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
93                 tmf.init(ks);
94                 builder.sslContext(GrpcSslContexts.forClient().trustManager(tmf).build());
95             } catch (NoSuchAlgorithmException e) {
96                 log.error("Can't get default TrustManager algorithm");
97                 throw new RuntimeException(e);
98             } catch (KeyStoreException e) {
99                 log.error("TrustManagerFactory initialization failed");
100                 throw new RuntimeException(e);
101             } catch (SSLException e) {
102                 log.error("SslContext build error");
103                 throw new RuntimeException(e);
104             }
105         }
106         if (props.getUseBasicAuth()) {
107             log.info("Configure Basic authentication");
108             builder.intercept(new BasicAuthClientInterceptor(props)).usePlaintext();
109         }
110         this.channel = builder.build();
111         this.handler = new CDSProcessingHandler(listener);
112         log.info("CDSProcessingClient started");
113     }
114
115     CDSProcessingClient(final ManagedChannel channel, final CDSProcessingHandler handler) {
116         this.channel = channel;
117         this.handler = handler;
118     }
119
120     /**
121      * Sends a request to the CDS backend micro-service.
122      *
123      * The caller will be returned a CountDownLatch that can be used to define how long the processing can wait. The
124      * CountDownLatch is initiated with just 1 count. When the client receives an #onCompleted callback, the counter
125      * will decrement.
126      *
127      * It is the user responsibility to close the client.
128      *
129      * @param input request to send
130      * @return CountDownLatch instance that can be use to #await for completeness of processing
131      */
132     public CountDownLatch sendRequest(ExecutionServiceInput input) {
133         return handler.process(input, channel);
134     }
135
136     @Override
137     public void close() {
138         if (channel != null) {
139             channel.shutdown();
140         }
141         log.info("CDSProcessingClient stopped");
142     }
143 }