Add log diagnostic context
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-xnf-simulator / src / main / kotlin / org / onap / dcae / collectors / veshv / simulators / xnf / impl / adapters / VesHvClient.kt
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 arrow.core.getOrElse
24 import io.netty.handler.ssl.SslContext
25 import org.onap.dcae.collectors.veshv.domain.WireFrameMessage
26 import org.onap.dcae.collectors.veshv.domain.SecurityConfiguration
27 import org.onap.dcae.collectors.veshv.domain.WireFrameEncoder
28 import org.onap.dcae.collectors.veshv.simulators.xnf.impl.config.SimulatorConfiguration
29 import org.onap.dcae.collectors.veshv.ssl.boundary.ClientSslContextFactory
30 import org.onap.dcae.collectors.veshv.utils.arrow.asIo
31 import org.onap.dcae.collectors.veshv.utils.logging.Logger
32 import org.reactivestreams.Publisher
33 import reactor.core.publisher.Flux
34 import reactor.core.publisher.Mono
35 import reactor.core.publisher.ReplayProcessor
36 import reactor.netty.NettyOutbound
37 import reactor.netty.tcp.TcpClient
38
39 /**
40  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
41  * @since June 2018
42  */
43 class VesHvClient(private val configuration: SimulatorConfiguration) {
44
45     private val client: TcpClient = TcpClient.create()
46             .host(configuration.vesHost)
47             .port(configuration.vesPort)
48             .configureSsl()
49
50     private fun TcpClient.configureSsl() =
51             createSslContext(configuration.security)
52                     .map { sslContext -> this.secure(sslContext) }
53                     .getOrElse { this }
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                 .handle { _, output -> handler(complete, messages, output) }
62                 .connect()
63                 .doOnError {
64                     logger.info {
65                         "Failed to connect to VesHvCollector on ${configuration.vesHost}:${configuration.vesPort}"
66                     }
67                 }
68                 .subscribe {
69                     logger.info {
70                         "Connected to VesHvCollector on ${configuration.vesHost}:${configuration.vesPort}"
71                     }
72                 }
73         return complete.then()
74     }
75
76     private fun handler(complete: ReplayProcessor<Void>,
77                         messages: Flux<WireFrameMessage>,
78                         nettyOutbound: NettyOutbound): Publisher<Void> {
79
80         val allocator = nettyOutbound.alloc()
81         val encoder = WireFrameEncoder(allocator)
82         val frames = messages
83                 .map(encoder::encode)
84                 .window(MAX_BATCH_SIZE)
85
86         return nettyOutbound
87                 .logConnectionClosed()
88                 .options { it.flushOnBoundary() }
89                 .sendGroups(frames)
90                 .then {
91                     logger.info { "Messages have been sent" }
92                     complete.onComplete()
93                 }
94                 .then()
95     }
96
97     private fun createSslContext(config: SecurityConfiguration): Option<SslContext> =
98             ClientSslContextFactory().createSslContext(config)
99
100     private fun NettyOutbound.logConnectionClosed() =
101             withConnection { conn ->
102                 conn.onTerminate().subscribe {
103                     logger.info { "Connection to ${conn.address()} has been closed" }
104                 }
105             }
106
107     companion object {
108         private val logger = Logger(VesHvClient::class)
109         private const val MAX_BATCH_SIZE = 128
110     }
111 }