Fix shutting down when new config received bug
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-utils / src / main / kotlin / org / onap / dcae / collectors / veshv / utils / server_handle.kt
index 5b582ed..670ab4a 100644 (file)
@@ -20,8 +20,9 @@
 package org.onap.dcae.collectors.veshv.utils
 
 import arrow.effects.IO
+import org.onap.dcae.collectors.veshv.utils.logging.Logger
+import reactor.core.publisher.Mono
 import reactor.netty.DisposableServer
-import java.time.Duration
 
 /**
  * @author Piotr Jaszczyk <piotr.jaszczyk@nokia.com>
@@ -35,16 +36,33 @@ abstract class ServerHandle(val host: String, val port: Int) : Closeable {
  * @author Piotr Jaszczyk <piotr.jaszczyk@nokia.com>
  * @since August 2018
  */
-class NettyServerHandle(private val ctx: DisposableServer) : ServerHandle(ctx.host(), ctx.port()) {
-    override fun close() = IO {
-        ctx.disposeNow(SHUTDOWN_TIMEOUT)
-    }
+class NettyServerHandle(private val ctx: DisposableServer,
+                        private val closeAction: Mono<Void> = Mono.empty())
+    : ServerHandle(ctx.host(), ctx.port()) {
+
+    override fun close(): Mono<Void> =
+            Mono.just(ctx)
+                    .filter { !it.isDisposed }
+                    .flatMap {
+                        closeAction.thenReturn(it)
+                    }
+                    .then(dispose())
+
+    private fun dispose(): Mono<Void> =
+            Mono.create { callback ->
+                logger.debug { "About to dispose NettyServer" }
+                ctx.dispose()
+                ctx.onDispose {
+                    logger.debug { "Netty server disposed" }
+                    callback.success()
+                }
+            }
 
     override fun await() = IO<Unit> {
         ctx.channel().closeFuture().sync()
     }
 
     companion object {
-        private val SHUTDOWN_TIMEOUT = Duration.ofSeconds(10)
+        private val logger = Logger(NettyServerHandle::class)
     }
 }