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