d1a5296a692c98b2eef5b009c48ea040091570fd
[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.EndOfTransmissionMessage
28 import org.onap.dcae.collectors.veshv.domain.PayloadWireFrameMessage
29 import org.onap.dcae.collectors.veshv.domain.SecurityConfiguration
30 import org.onap.dcae.collectors.veshv.domain.WireFrameEncoder
31 import org.onap.dcae.collectors.veshv.simulators.xnf.impl.config.SimulatorConfiguration
32 import org.onap.dcae.collectors.veshv.utils.arrow.asIo
33 import org.onap.dcae.collectors.veshv.utils.logging.Logger
34 import org.reactivestreams.Publisher
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: SimulatorConfiguration) {
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).orNull())
53             }
54             .build()
55
56     fun sendIo(messages: Flux<PayloadWireFrameMessage>) =
57             sendRx(messages).then(Mono.just(Unit)).asIo()
58
59     private fun sendRx(messages: Flux<PayloadWireFrameMessage>): Mono<Void> {
60         val complete = ReplayProcessor.create<Void>(1)
61         client
62                 .newHandler { _, output -> handler(complete, messages, output) }
63                 .doOnError {
64                     logger.info("Failed to connect to VesHvCollector on " +
65                             "${configuration.vesHost}:${configuration.vesPort}")
66                 }
67                 .subscribe {
68                     logger.info("Connected to VesHvCollector on " +
69                             "${configuration.vesHost}:${configuration.vesPort}")
70                 }
71         return complete.then()
72     }
73
74     private fun handler(complete: ReplayProcessor<Void>,
75                         messages: Flux<PayloadWireFrameMessage>,
76                         nettyOutbound: NettyOutbound): Publisher<Void> {
77
78         val allocator = nettyOutbound.alloc()
79         val encoder = WireFrameEncoder(allocator)
80         val frames = messages
81                 .map(encoder::encode)
82                 .window(MAX_BATCH_SIZE)
83
84         return nettyOutbound
85                 .logConnectionClosed()
86                 .options { it.flushOnBoundary() }
87                 .sendGroups(frames)
88                 .send(Mono.just(allocator.buffer().writeByte(eotMessageByte.toInt())))
89                 .then {
90                     logger.info("Messages have been sent")
91                     complete.onComplete()
92                 }
93                 .then()
94     }
95
96     private fun createSslContext(config: SecurityConfiguration): Option<SslContext> =
97             if (config.sslDisable) {
98                 Option.empty()
99             } else {
100                 Option.just(
101                         SslContextBuilder.forClient()
102                                 .keyManager(config.cert.toFile(), config.privateKey.toFile())
103                                 .trustManager(config.trustedCert.toFile())
104                                 .sslProvider(SslProvider.OPENSSL)
105                                 .clientAuth(ClientAuth.REQUIRE)
106                                 .build()
107                 )
108             }
109
110     private fun NettyOutbound.logConnectionClosed(): NettyOutbound {
111         context().onClose {
112             logger.info { "Connection to ${context().address()} has been closed" }
113         }
114         return this
115     }
116
117     companion object {
118         private val logger = Logger(VesHvClient::class)
119         private const val MAX_BATCH_SIZE = 128
120         private const val eotMessageByte = EndOfTransmissionMessage.MARKER_BYTE
121     }
122 }