Fix consul configuration delay
[dcaegen2/collectors/hv-ves.git] / hv-collector-xnf-simulator / src / main / kotlin / org / onap / dcae / collectors / veshv / simulators / xnf / impl / XnfSimulator.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
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.SimulatorConfiguration
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 internal class XnfSimulator(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))
52             }
53             .build()
54
55     fun sendIo(messages: Flux<WireFrame>) = IO<Unit> {
56         sendRx(messages).block()
57     }
58
59     fun sendRx(messages: Flux<WireFrame>): 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>, messages: Flux<WireFrame>, nettyOutbound: NettyOutbound):
75             Publisher<Void> {
76         val encoder = WireFrameEncoder(nettyOutbound.alloc())
77         val context = nettyOutbound.context()
78
79         context.onClose {
80             logger.info { "Connection to ${context.address()} has been closed" }
81         }
82
83         // TODO: Close channel after all messages have been sent
84         // The code bellow doesn't work because it closes the channel earlier and not all are consumed...
85 //        complete.subscribe {
86 //            context.channel().disconnect().addListener {
87 //                if (it.isSuccess)
88 //                    logger.info { "Connection closed" }
89 //                else
90 //                    logger.warn("Failed to close the connection", it.cause())
91 //            }
92 //        }
93
94         val frames = messages
95                 .map(encoder::encode)
96                 .window(MAX_BATCH_SIZE)
97
98         return nettyOutbound
99                 .options { it.flushOnBoundary() }
100                 .sendGroups(frames)
101                 .send(Mono.just(Unpooled.EMPTY_BUFFER))
102                 .then {
103                     logger.info("Messages have been sent")
104                     complete.onComplete()
105                 }
106                 .then()
107     }
108
109     private fun createSslContext(config: SecurityConfiguration): SslContext =
110             SslContextBuilder.forClient()
111                     .keyManager(config.cert.toFile(), config.privateKey.toFile())
112                     .trustManager(config.trustedCert.toFile())
113                     .sslProvider(SslProvider.OPENSSL)
114                     .clientAuth(ClientAuth.REQUIRE)
115                     .build()
116
117     companion object {
118         private const val MAX_BATCH_SIZE = 128
119         private val logger = Logger(XnfSimulator::class)
120     }
121 }