af71e9ce56a977342551e36e542e68e38cf75513
[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.adapters
21
22 import arrow.core.Option
23 import io.netty.handler.ssl.ClientAuth
24 import io.netty.handler.ssl.SslContext
25 import io.netty.handler.ssl.SslContextBuilder
26 import io.netty.handler.ssl.SslProvider
27 import org.onap.dcae.collectors.veshv.domain.WireFrameMessage
28 import org.onap.dcae.collectors.veshv.domain.SecurityConfiguration
29 import org.onap.dcae.collectors.veshv.domain.WireFrameEncoder
30 import org.onap.dcae.collectors.veshv.simulators.xnf.impl.config.SimulatorConfiguration
31 import org.onap.dcae.collectors.veshv.utils.arrow.asIo
32 import org.onap.dcae.collectors.veshv.utils.logging.Logger
33 import org.reactivestreams.Publisher
34 import reactor.core.publisher.Flux
35 import reactor.core.publisher.Mono
36 import reactor.core.publisher.ReplayProcessor
37 import reactor.ipc.netty.NettyOutbound
38 import reactor.ipc.netty.tcp.TcpClient
39
40
41 /**
42  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
43  * @since June 2018
44  */
45 class VesHvClient(private val configuration: SimulatorConfiguration) {
46
47     private val client: TcpClient = TcpClient.builder()
48             .options { opts ->
49                 opts.host(configuration.vesHost)
50                         .port(configuration.vesPort)
51                         .sslContext(createSslContext(configuration.security).orNull())
52             }
53             .build()
54
55     fun sendIo(messages: Flux<WireFrameMessage>) =
56             sendRx(messages).then(Mono.just(Unit)).asIo()
57
58     private fun sendRx(messages: Flux<WireFrameMessage>): Mono<Void> {
59         val complete = ReplayProcessor.create<Void>(1)
60         client
61                 .newHandler { _, output -> handler(complete, messages, output) }
62                 .doOnError {
63                     logger.info("Failed to connect to VesHvCollector on " +
64                             "${configuration.vesHost}:${configuration.vesPort}")
65                 }
66                 .subscribe {
67                     logger.info("Connected to VesHvCollector on " +
68                             "${configuration.vesHost}:${configuration.vesPort}")
69                 }
70         return complete.then()
71     }
72
73     private fun handler(complete: ReplayProcessor<Void>,
74                         messages: Flux<WireFrameMessage>,
75                         nettyOutbound: NettyOutbound): Publisher<Void> {
76
77         val allocator = nettyOutbound.alloc()
78         val encoder = WireFrameEncoder(allocator)
79         val frames = messages
80                 .map(encoder::encode)
81                 .window(MAX_BATCH_SIZE)
82
83         return nettyOutbound
84                 .logConnectionClosed()
85                 .options { it.flushOnBoundary() }
86                 .sendGroups(frames)
87                 .then {
88                     logger.info("Messages have been sent")
89                     complete.onComplete()
90                 }
91                 .then()
92     }
93
94     private fun createSslContext(config: SecurityConfiguration): Option<SslContext> =
95             if (config.sslDisable) {
96                 Option.empty()
97             } else {
98                 Option.just(
99                         SslContextBuilder.forClient()
100                                 .keyManager(config.cert.toFile(), config.privateKey.toFile())
101                                 .trustManager(config.trustedCert.toFile())
102                                 .sslProvider(SslProvider.OPENSSL)
103                                 .clientAuth(ClientAuth.REQUIRE)
104                                 .build()
105                 )
106             }
107
108     private fun NettyOutbound.logConnectionClosed(): NettyOutbound {
109         context().onClose {
110             logger.info { "Connection to ${context().address()} has been closed" }
111         }
112         return this
113     }
114
115     companion object {
116         private val logger = Logger(VesHvClient::class)
117         private const val MAX_BATCH_SIZE = 128
118     }
119 }