Skip to content

Commit 0bf886d

Browse files
committed
Add keepalive ping on gateway websocket
1 parent 1e0b93d commit 0bf886d

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

notebook/gateway/handlers.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from tornado import gen, web
1212
from tornado.concurrent import Future
13-
from tornado.ioloop import IOLoop
13+
from tornado.ioloop import IOLoop, PeriodicCallback
1414
from tornado.websocket import WebSocketHandler, websocket_connect
1515
from tornado.httpclient import HTTPRequest
1616
from tornado.escape import url_escape, json_decode, utf8
@@ -21,12 +21,16 @@
2121

2222
from .managers import GatewayClient
2323

24+
# Keepalive ping interval (default: 30 seconds)
25+
GATEWAY_WS_PING_INTERVAL_SECS = int(os.getenv('GATEWAY_WS_PING_INTERVAL_SECS', 30))
26+
2427

2528
class WebSocketChannelsHandler(WebSocketHandler, IPythonHandler):
2629

2730
session = None
2831
gateway = None
2932
kernel_id = None
33+
ping_callback = None
3034

3135
def set_default_headers(self):
3236
"""Undo the set_default_headers in IPythonHandler which doesn't make sense for websockets"""
@@ -63,8 +67,18 @@ def get(self, kernel_id, *args, **kwargs):
6367
self.kernel_id = cast_unicode(kernel_id, 'ascii')
6468
super(WebSocketChannelsHandler, self).get(kernel_id=kernel_id, *args, **kwargs)
6569

70+
def send_ping(self):
71+
if self.ws_connection is None and self.ping_callback is not None:
72+
self.ping_callback.stop()
73+
return
74+
75+
self.ping(b'')
76+
6677
def open(self, kernel_id, *args, **kwargs):
6778
"""Handle web socket connection open to notebook server and delegate to gateway web socket handler """
79+
self.ping_callback = PeriodicCallback(self.send_ping, GATEWAY_WS_PING_INTERVAL_SECS * 1000)
80+
self.ping_callback.start()
81+
6882
self.gateway.on_open(
6983
kernel_id=kernel_id,
7084
message_callback=self.write_message,

notebook/gateway/managers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ def gateway_enabled(self):
226226

227227
# Ensure KERNEL_LAUNCH_TIMEOUT has a default value.
228228
KERNEL_LAUNCH_TIMEOUT = int(os.environ.get('KERNEL_LAUNCH_TIMEOUT', 40))
229-
os.environ['KERNEL_LAUNCH_TIMEOUT'] = KERNEL_LAUNCH_TIMEOUT
229+
os.environ['KERNEL_LAUNCH_TIMEOUT'] = str(KERNEL_LAUNCH_TIMEOUT)
230230

231231
LAUNCH_TIMEOUT_PAD = int(os.environ.get('LAUNCH_TIMEOUT_PAD', 2))
232232

0 commit comments

Comments
 (0)