Skip to content
This repository has been archived by the owner on Dec 8, 2022. It is now read-only.

Commit

Permalink
Add keepalive websocket ping
Browse files Browse the repository at this point in the history
When nb2kg server is behind the proxy closing idle stream connection such as nginx and envoy websocket is closed and reconnected.
This behavior updates kernel `last_activity` so that it keeps `kernel_gateway` from culling kernels.

This change is from `WebsocketMixin` in jupyter/notebook.

Signed-off-by: Eunsoo Park <esevan.park@gmail.com>
  • Loading branch information
esevan committed Apr 4, 2019
1 parent c515b3c commit 41fa726
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion nb2kg/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from tornado import gen, web
from tornado.concurrent import Future
from tornado.ioloop import IOLoop
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.websocket import WebSocketHandler, websocket_connect
from tornado.httpclient import HTTPRequest
from tornado.escape import url_escape, json_decode, utf8
Expand Down Expand Up @@ -40,6 +40,9 @@
KG_CONNECT_TIMEOUT = float(os.getenv('KG_CONNECT_TIMEOUT', 20.0))
KG_REQUEST_TIMEOUT = float(os.getenv('KG_REQUEST_TIMEOUT', 20.0))

# Keepalive ping interval (30 seconds)
WS_PING_INTERVAL_MS = 30000


class WebSocketChannelsHandler(WebSocketHandler, IPythonHandler):

Expand Down Expand Up @@ -86,8 +89,23 @@ def get(self, kernel_id, *args, **kwargs):
self.kernel_id = cast_unicode(kernel_id, 'ascii')
yield gen.maybe_future(super(WebSocketChannelsHandler, self).get(kernel_id=kernel_id, *args, **kwargs))

def send_ping(self):
if self.stream.closed() and self.ping_callback is not None:
self.ping_callback.stop()
return

self.ping(b'')

def on_pong(self, data):
self.log.debug('Client has sent pong')

def open(self, kernel_id, *args, **kwargs):
"""Handle web socket connection open to notebook server and delegate to gateway web socket handler """
loop = IOLoop.current()

self.ping_callback = PeriodicCallback(self.send_ping, WS_PING_INTERVAL_MS, io_loop=loop)
self.ping_callback.start()

self.gateway.on_open(
kernel_id=kernel_id,
message_callback=self.write_message,
Expand Down

0 comments on commit 41fa726

Please sign in to comment.