Correct totalConnections metric
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-core / src / main / kotlin / org / onap / dcae / collectors / veshv / impl / socket / NettyTcpServer.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.impl.socket
21
22 import arrow.core.Try
23 import arrow.core.getOrElse
24 import arrow.effects.IO
25 import org.onap.dcae.collectors.veshv.boundary.Collector
26 import org.onap.dcae.collectors.veshv.boundary.CollectorProvider
27 import org.onap.dcae.collectors.veshv.boundary.Metrics
28 import org.onap.dcae.collectors.veshv.boundary.Server
29 import org.onap.dcae.collectors.veshv.impl.adapters.ClientContextLogging.debug
30 import org.onap.dcae.collectors.veshv.impl.adapters.ClientContextLogging.info
31 import org.onap.dcae.collectors.veshv.model.ClientContext
32 import org.onap.dcae.collectors.veshv.model.ServerConfiguration
33 import org.onap.dcae.collectors.veshv.model.ServiceContext
34 import org.onap.dcae.collectors.veshv.ssl.boundary.ServerSslContextFactory
35 import org.onap.dcae.collectors.veshv.utils.NettyServerHandle
36 import org.onap.dcae.collectors.veshv.utils.ServerHandle
37 import org.onap.dcae.collectors.veshv.utils.logging.Logger
38 import org.onap.dcae.collectors.veshv.utils.logging.Marker
39 import reactor.core.publisher.Mono
40 import reactor.netty.Connection
41 import reactor.netty.NettyInbound
42 import reactor.netty.NettyOutbound
43 import reactor.netty.tcp.TcpServer
44 import java.net.InetAddress
45 import java.time.Duration
46
47
48 /**
49  * @author Piotr Jaszczyk <piotr.jaszczyk@nokia.com>
50  * @since May 2018
51  */
52 internal class NettyTcpServer(private val serverConfig: ServerConfiguration,
53                               private val sslContextFactory: ServerSslContextFactory,
54                               private val collectorProvider: CollectorProvider,
55                               private val metrics: Metrics) : Server {
56
57     override fun start(): IO<ServerHandle> = IO {
58         TcpServer.create()
59                 .addressSupplier { serverConfig.serverListenAddress }
60                 .configureSsl()
61                 .handle(this::handleConnection)
62                 .doOnUnbound {
63                     logger.info(ServiceContext::mdc) { "Netty TCP Server closed" }
64                     collectorProvider.close().unsafeRunSync()
65                 }
66                 .let { NettyServerHandle(it.bindNow()) }
67     }
68
69     private fun TcpServer.configureSsl() =
70             sslContextFactory
71                     .createSslContext(serverConfig.securityConfiguration)
72                     .map { sslContext ->
73                         logger.info { "Collector configured with SSL enabled" }
74                         this.secure { b -> b.sslContext(sslContext) }
75                     }.getOrElse {
76                         logger.info { "Collector configured with SSL disabled" }
77                         this
78                     }
79
80     private fun handleConnection(nettyInbound: NettyInbound, nettyOutbound: NettyOutbound): Mono<Void> =
81             messageHandlingStream(nettyInbound, nettyOutbound).run {
82                 subscribe()
83                 nettyOutbound.neverComplete()
84             }
85
86     private fun messageHandlingStream(nettyInbound: NettyInbound, nettyOutbound: NettyOutbound): Mono<Void> =
87             withNewClientContextFrom(nettyInbound, nettyOutbound)
88             { clientContext ->
89                 logger.debug(clientContext::fullMdc, Marker.Entry) { "Client connection request received" }
90
91                 clientContext.clientAddress
92                         .map { acceptIfNotLocalConnection(it, clientContext, nettyInbound) }
93                         .getOrElse {
94                             logger.warn(clientContext::fullMdc) {
95                                 "Client address could not be resolved. Discarding connection"
96                             }
97                             nettyInbound.closeConnectionAndReturn(Mono.empty())
98                         }
99             }
100
101     private fun acceptIfNotLocalConnection(address: InetAddress,
102                                            clientContext: ClientContext,
103                                            nettyInbound: NettyInbound): Mono<Void> =
104             if (address.isLocalClientAddress()) {
105                 logger.debug(clientContext) {
106                     "Client address resolved to localhost. Discarding connection as suspected healthcheck"
107                 }
108                 nettyInbound.closeConnectionAndReturn(Mono.empty<Void>())
109             } else {
110                 acceptClientConnection(clientContext, nettyInbound)
111             }
112
113     private fun acceptClientConnection(clientContext: ClientContext, nettyInbound: NettyInbound): Mono<Void> {
114         metrics.notifyClientConnected()
115         logger.info(clientContext::fullMdc) { "Handling new client connection" }
116         return collectorProvider(clientContext).fold(
117                 {
118                     logger.warn(clientContext::fullMdc) { "Collector is not ready. Closing connection" }
119                     nettyInbound.closeConnectionAndReturn(Mono.empty<Void>())
120                 },
121                 handleClient(clientContext, nettyInbound)
122         )
123     }
124
125     private fun handleClient(clientContext: ClientContext,
126                              nettyInbound: NettyInbound): (Collector) -> Mono<Void> = { collector ->
127         withConnectionFrom(nettyInbound) { connection ->
128             connection
129                     .configureIdleTimeout(clientContext, serverConfig.idleTimeout)
130                     .logConnectionClosed(clientContext)
131         }.run {
132             collector.handleConnection(nettyInbound.createDataStream())
133         }
134     }
135
136     private fun Connection.configureIdleTimeout(ctx: ClientContext, timeout: Duration): Connection =
137             onReadIdle(timeout.toMillis()) {
138                 logger.info(ctx) {
139                     "Idle timeout of ${timeout.seconds} s reached. Closing connection from ${address()}..."
140                 }
141                 disconnectClient(ctx)
142             }
143
144     private fun Connection.disconnectClient(ctx: ClientContext) =
145             closeChannelAndThen {
146                 if (it.isSuccess)
147                     logger.debug(ctx::fullMdc, Marker.Exit) { "Channel closed successfully." }
148                 else
149                     logger.warn(ctx::fullMdc, Marker.Exit, { "Channel close failed" }, it.cause())
150             }
151
152     private fun Connection.logConnectionClosed(ctx: ClientContext): Connection =
153             onDispose {
154                 metrics.notifyClientDisconnected()
155                 logger.info(ctx::fullMdc, Marker.Exit) { "Connection has been closed" }
156             }
157
158     companion object {
159         private val logger = Logger(NettyTcpServer::class)
160     }
161 }