be351b50656a2a25d40a62b0cd866b41005d0a43
[dcaegen2/collectors/hv-ves.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * dcaegen2-collectors-veshv
4  * ================================================================================
5  * Copyright (C) 2018 NOKIA
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 package org.onap.dcae.collectors.veshv.simulators.xnf.impl
21
22 import arrow.effects.IO
23 import io.netty.buffer.Unpooled
24 import io.netty.handler.ssl.ClientAuth
25 import io.netty.handler.ssl.SslContext
26 import io.netty.handler.ssl.SslContextBuilder
27 import io.netty.handler.ssl.SslProvider
28 import org.onap.dcae.collectors.veshv.domain.SecurityConfiguration
29 import org.onap.dcae.collectors.veshv.domain.WireFrame
30 import org.onap.dcae.collectors.veshv.domain.WireFrameEncoder
31 import org.onap.dcae.collectors.veshv.simulators.xnf.config.ClientConfiguration
32 import org.onap.dcae.collectors.veshv.utils.logging.Logger
33 import org.reactivestreams.Publisher
34 import reactor.core.publisher.EmitterProcessor
35 import reactor.core.publisher.Flux
36 import reactor.core.publisher.Mono
37 import reactor.core.publisher.ReplayProcessor
38 import reactor.ipc.netty.NettyOutbound
39 import reactor.ipc.netty.tcp.TcpClient
40
41
42 /**
43  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
44  * @since June 2018
45  */
46 class VesHvClient(private val configuration: ClientConfiguration) {
47
48     private val client: TcpClient = TcpClient.builder()
49             .options { opts ->
50                 opts.host(configuration.vesHost)
51                         .port(configuration.vesPort)
52                         .sslContext(createSslContext(configuration.security))
53             }
54             .build()
55
56     fun sendIo(messages: Flux<WireFrame>) = IO<Unit> {
57         sendRx(messages).block()
58     }
59
60     fun sendRx(messages: Flux<WireFrame>): Mono<Void> {
61         val complete = ReplayProcessor.create<Void>(1)
62         client
63                 .newHandler { _, output -> handler(complete, messages, output) }
64                 .doOnError {
65                     logger.info("Failed to connect to VesHvCollector on " +
66                             "${configuration.vesHost}:${configuration.vesPort}")
67                 }
68                 .subscribe {
69                     logger.info("Connected to VesHvCollector on " +
70                             "${configuration.vesHost}:${configuration.vesPort}")
71                 }
72         return complete.then()
73     }
74
75     private fun handler(complete: ReplayProcessor<Void>, messages: Flux<WireFrame>, nettyOutbound: NettyOutbound):
76             Publisher<Void> {
77         val encoder = WireFrameEncoder(nettyOutbound.alloc())
78         val context = nettyOutbound.context()
79
80         context.onClose {
81             logger.info { "Connection to ${context.address()} has been closed" }
82         }
83
84         // TODO: Close channel after all messages have been sent
85         // The code bellow doesn't work because it closes the channel earlier and not all are consumed...
86 //        complete.subscribe {
87 //            context.channel().disconnect().addListener {
88 //                if (it.isSuccess)
89 //                    logger.info { "Connection closed" }
90 //                else
91 //                    logger.warn("Failed to close the connection", it.cause())
92 //            }
93 //        }
94
95         val frames = messages
96                 .map(encoder::encode)
97                 .window(MAX_BATCH_SIZE)
98
99         return nettyOutbound
100                 .options { it.flushOnBoundary() }
101                 .sendGroups(frames)
102                 .send(Mono.just(Unpooled.EMPTY_BUFFER))
103                 .then {
104                     logger.info("Messages have been sent")
105                     complete.onComplete()
106                 }
107                 .then()
108     }
109
110     private fun createSslContext(config: SecurityConfiguration): SslContext =
111             SslContextBuilder.forClient()
112                     .keyManager(config.cert.toFile(), config.privateKey.toFile())
113                     .trustManager(config.trustedCert.toFile())
114                     .sslProvider(SslProvider.OPENSSL)
115                     .clientAuth(ClientAuth.REQUIRE)
116                     .build()
117
118     companion object {
119         private const val MAX_BATCH_SIZE = 128
120         private val logger = Logger(VesHvClient::class)
121     }
122 }