OVSDB library: Close conneciton when peer is down
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / jsonrpc / ExceptionHandler.java
index 8a932d3ddcc76060f4f5d8227086d153d368d301..ed21a3f93c12717ff1ba4404054c5764bfc8589d 100644 (file)
@@ -8,15 +8,23 @@
 
 package org.opendaylight.ovsdb.lib.jsonrpc;
 
-import io.netty.channel.ChannelHandlerAdapter;
+import io.netty.channel.ChannelDuplexHandler;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.TooLongFrameException;
+import io.netty.handler.timeout.IdleState;
+import io.netty.handler.timeout.IdleStateEvent;
+import io.netty.handler.timeout.ReadTimeoutException;
+
+import org.opendaylight.ovsdb.lib.OvsdbClient;
 import org.opendaylight.ovsdb.lib.error.InvalidEncodingException;
+import org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 
-public class ExceptionHandler extends ChannelHandlerAdapter {
-
+public class ExceptionHandler extends ChannelDuplexHandler {
+    private static final Logger LOG = LoggerFactory.getLogger(ExceptionHandler.class);
     @Override
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
         if ((cause instanceof InvalidEncodingException)
@@ -29,5 +37,27 @@ public class ExceptionHandler extends ChannelHandlerAdapter {
         if (cause instanceof IOException) {
             ctx.channel().close();
         }
+        /* In cases where the peer is power off
+         * Catch the read time out exception and close the channel
+         */
+        if (cause instanceof ReadTimeoutException) {
+            LOG.debug("Read timeout exception: close connection {}", ctx.channel());
+            ctx.channel().close();
+        }
+    }
+
+    @Override
+    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
+        if (evt instanceof IdleStateEvent) {
+            LOG.debug("Get idle state event");
+            IdleStateEvent event = (IdleStateEvent) evt;
+            if (event.state() == IdleState.READER_IDLE) {
+                LOG.debug("Reader idle state. Send echo message to peer");
+                //Send echo message to peer
+                OvsdbClient client =
+                             OvsdbConnectionService.getService().getClient(ctx.channel());
+                client.echo();
+            }
+        }
     }
 }