channels.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. """An implementation of a kernel connection."""
  2. from __future__ import annotations
  3. import asyncio
  4. import json
  5. import time
  6. import typing as t
  7. import weakref
  8. from concurrent.futures import Future
  9. from textwrap import dedent
  10. from jupyter_client import protocol_version as client_protocol_version # type:ignore[attr-defined]
  11. from tornado import gen, web
  12. from tornado.ioloop import IOLoop
  13. from tornado.websocket import WebSocketClosedError
  14. from traitlets import Any, Bool, Dict, Float, Instance, Int, List, Unicode, default
  15. try:
  16. from jupyter_client.jsonutil import json_default
  17. except ImportError:
  18. from jupyter_client.jsonutil import date_default as json_default
  19. from jupyter_core.utils import ensure_async
  20. from jupyter_server.transutils import _i18n
  21. from ..websocket import KernelWebsocketHandler
  22. from .abc import KernelWebsocketConnectionABC
  23. from .base import (
  24. BaseKernelWebsocketConnection,
  25. deserialize_binary_message,
  26. deserialize_msg_from_ws_v1,
  27. serialize_binary_message,
  28. serialize_msg_to_ws_v1,
  29. )
  30. def _ensure_future(f):
  31. """Wrap a concurrent future as an asyncio future if there is a running loop."""
  32. try:
  33. asyncio.get_running_loop()
  34. return asyncio.wrap_future(f)
  35. except RuntimeError:
  36. return f
  37. class ZMQChannelsWebsocketConnection(BaseKernelWebsocketConnection):
  38. """A Jupyter Server Websocket Connection"""
  39. limit_rate = Bool(
  40. True,
  41. config=True,
  42. help=_i18n(
  43. "Whether to limit the rate of IOPub messages (default: True). "
  44. "If True, use iopub_msg_rate_limit, iopub_data_rate_limit and/or rate_limit_window "
  45. "to tune the rate."
  46. ),
  47. )
  48. iopub_msg_rate_limit = Float(
  49. 1000,
  50. config=True,
  51. help=_i18n(
  52. """(msgs/sec)
  53. Maximum rate at which messages can be sent on iopub before they are
  54. limited."""
  55. ),
  56. )
  57. iopub_data_rate_limit = Float(
  58. 1000000,
  59. config=True,
  60. help=_i18n(
  61. """(bytes/sec)
  62. Maximum rate at which stream output can be sent on iopub before they are
  63. limited."""
  64. ),
  65. )
  66. rate_limit_window = Float(
  67. 3,
  68. config=True,
  69. help=_i18n(
  70. """(sec) Time window used to
  71. check the message and data rate limits."""
  72. ),
  73. )
  74. websocket_handler = Instance(KernelWebsocketHandler)
  75. @property
  76. def write_message(self):
  77. """Alias to the websocket handler's write_message method."""
  78. return self.websocket_handler.write_message
  79. # class-level registry of open sessions
  80. # allows checking for conflict on session-id,
  81. # which is used as a zmq identity and must be unique.
  82. _open_sessions: dict[str, KernelWebsocketHandler] = {}
  83. _open_sockets: t.MutableSet[ZMQChannelsWebsocketConnection] = weakref.WeakSet()
  84. _kernel_info_future: Future[t.Any]
  85. _close_future: Future[t.Any]
  86. channels = Dict({})
  87. kernel_info_channel = Any(allow_none=True)
  88. _kernel_info_future = Instance(klass=Future) # type:ignore[assignment]
  89. @default("_kernel_info_future")
  90. def _default_kernel_info_future(self):
  91. """The default kernel info future."""
  92. return Future()
  93. _close_future = Instance(klass=Future) # type:ignore[assignment]
  94. @default("_close_future")
  95. def _default_close_future(self):
  96. """The default close future."""
  97. return Future()
  98. session_key = Unicode("")
  99. _iopub_window_msg_count = Int()
  100. _iopub_window_byte_count = Int()
  101. _iopub_msgs_exceeded = Bool(False)
  102. _iopub_data_exceeded = Bool(False)
  103. # Queue of (time stamp, byte count)
  104. # Allows you to specify that the byte count should be lowered
  105. # by a delta amount at some point in the future.
  106. _iopub_window_byte_queue: List[t.Any] = List([])
  107. @classmethod
  108. async def close_all(cls):
  109. """Tornado does not provide a way to close open sockets, so add one."""
  110. for connection in list(cls._open_sockets):
  111. connection.disconnect()
  112. await _ensure_future(connection._close_future)
  113. @property
  114. def subprotocol(self):
  115. """The sub protocol."""
  116. try:
  117. protocol = self.websocket_handler.selected_subprotocol
  118. except Exception:
  119. protocol = None
  120. return protocol
  121. def create_stream(self):
  122. """Create a stream."""
  123. identity = self.session.bsession
  124. for channel in ("iopub", "shell", "control", "stdin"):
  125. meth = getattr(self.kernel_manager, "connect_" + channel)
  126. self.channels[channel] = stream = meth(identity=identity)
  127. stream.channel = channel
  128. def nudge(self):
  129. """Nudge the zmq connections with kernel_info_requests
  130. Returns a Future that will resolve when we have received
  131. a shell or control reply and at least one iopub message,
  132. ensuring that zmq subscriptions are established,
  133. sockets are fully connected, and kernel is responsive.
  134. Keeps retrying kernel_info_request until these are both received.
  135. """
  136. # Do not nudge busy kernels as kernel info requests sent to shell are
  137. # queued behind execution requests.
  138. # nudging in this case would cause a potentially very long wait
  139. # before connections are opened,
  140. # plus it is *very* unlikely that a busy kernel will not finish
  141. # establishing its zmq subscriptions before processing the next request.
  142. if getattr(self.kernel_manager, "execution_state", None) == "busy":
  143. self.log.debug("Nudge: not nudging busy kernel %s", self.kernel_id)
  144. f: Future[t.Any] = Future()
  145. f.set_result(None)
  146. return _ensure_future(f)
  147. # Use a transient shell channel to prevent leaking
  148. # shell responses to the front-end.
  149. shell_channel = self.kernel_manager.connect_shell()
  150. # Use a transient control channel to prevent leaking
  151. # control responses to the front-end.
  152. control_channel = self.kernel_manager.connect_control()
  153. # The IOPub used by the client, whose subscriptions we are verifying.
  154. iopub_channel = self.channels["iopub"]
  155. info_future: Future[t.Any] = Future()
  156. iopub_future: Future[t.Any] = Future()
  157. both_done = gen.multi([info_future, iopub_future])
  158. def finish(_=None):
  159. """Ensure all futures are resolved
  160. which in turn triggers cleanup
  161. """
  162. for f in (info_future, iopub_future):
  163. if not f.done():
  164. f.set_result(None)
  165. def cleanup(_=None):
  166. """Common cleanup"""
  167. loop.remove_timeout(nudge_handle)
  168. iopub_channel.stop_on_recv()
  169. if not shell_channel.closed():
  170. shell_channel.close()
  171. if not control_channel.closed():
  172. control_channel.close()
  173. # trigger cleanup when both message futures are resolved
  174. both_done.add_done_callback(cleanup)
  175. def on_shell_reply(msg):
  176. """Handle nudge shell replies."""
  177. self.log.debug("Nudge: shell info reply received: %s", self.kernel_id)
  178. if not info_future.done():
  179. self.log.debug("Nudge: resolving shell future: %s", self.kernel_id)
  180. info_future.set_result(None)
  181. def on_control_reply(msg):
  182. """Handle nudge control replies."""
  183. self.log.debug("Nudge: control info reply received: %s", self.kernel_id)
  184. if not info_future.done():
  185. self.log.debug("Nudge: resolving control future: %s", self.kernel_id)
  186. info_future.set_result(None)
  187. def on_iopub(msg):
  188. """Handle nudge iopub replies."""
  189. self.log.debug("Nudge: IOPub received: %s", self.kernel_id)
  190. if not iopub_future.done():
  191. iopub_channel.stop_on_recv()
  192. self.log.debug("Nudge: resolving iopub future: %s", self.kernel_id)
  193. iopub_future.set_result(None)
  194. iopub_channel.on_recv(on_iopub)
  195. shell_channel.on_recv(on_shell_reply)
  196. control_channel.on_recv(on_control_reply)
  197. loop = IOLoop.current()
  198. # Nudge the kernel with kernel info requests until we get an IOPub message
  199. def nudge(count):
  200. """Nudge the kernel."""
  201. count += 1
  202. # check for stopped kernel
  203. if self.kernel_id not in self.multi_kernel_manager:
  204. self.log.debug("Nudge: cancelling on stopped kernel: %s", self.kernel_id)
  205. finish()
  206. return
  207. # check for closed zmq socket
  208. if shell_channel.closed():
  209. self.log.debug("Nudge: cancelling on closed zmq socket: %s", self.kernel_id)
  210. finish()
  211. return
  212. # check for closed zmq socket
  213. if control_channel.closed():
  214. self.log.debug("Nudge: cancelling on closed zmq socket: %s", self.kernel_id)
  215. finish()
  216. return
  217. if not both_done.done():
  218. log = self.log.warning if count % 10 == 0 else self.log.debug
  219. log(f"Nudge: attempt {count} on kernel {self.kernel_id}")
  220. self.session.send(shell_channel, "kernel_info_request")
  221. self.session.send(control_channel, "kernel_info_request")
  222. nonlocal nudge_handle # type: ignore[misc]
  223. nudge_handle = loop.call_later(0.5, nudge, count)
  224. nudge_handle = loop.call_later(0, nudge, count=0)
  225. # resolve with a timeout if we get no response
  226. future = gen.with_timeout(loop.time() + self.kernel_info_timeout, both_done)
  227. # ensure we have no dangling resources or unresolved Futures in case of timeout
  228. future.add_done_callback(finish)
  229. return _ensure_future(future)
  230. async def _register_session(self):
  231. """Ensure we aren't creating a duplicate session.
  232. If a previous identical session is still open, close it to avoid collisions.
  233. This is likely due to a client reconnecting from a lost network connection,
  234. where the socket on our side has not been cleaned up yet.
  235. """
  236. self.session_key = f"{self.kernel_id}:{self.session.session}"
  237. stale_handler = self._open_sessions.get(self.session_key)
  238. if stale_handler:
  239. self.log.warning("Replacing stale connection: %s", self.session_key)
  240. stale_handler.close()
  241. if (
  242. self.kernel_id in self.multi_kernel_manager
  243. ): # only update open sessions if kernel is actively managed
  244. self._open_sessions[self.session_key] = t.cast(
  245. KernelWebsocketHandler, self.websocket_handler
  246. )
  247. async def prepare(self):
  248. """Prepare a kernel connection."""
  249. # check session collision:
  250. await self._register_session()
  251. # then request kernel info, waiting up to a certain time before giving up.
  252. # We don't want to wait forever, because browsers don't take it well when
  253. # servers never respond to websocket connection requests.
  254. if hasattr(self.kernel_manager, "ready"):
  255. ready = self.kernel_manager.ready
  256. if not isinstance(ready, asyncio.Future):
  257. ready = asyncio.wrap_future(ready)
  258. try:
  259. await ready
  260. except Exception as e:
  261. self.kernel_manager.execution_state = "dead"
  262. self.kernel_manager.reason = str(e)
  263. raise web.HTTPError(500, str(e)) from e
  264. t0 = time.time()
  265. while not await ensure_async(self.kernel_manager.is_alive()):
  266. await asyncio.sleep(0.1)
  267. if (time.time() - t0) > self.multi_kernel_manager.kernel_info_timeout:
  268. msg = "Kernel never reached an 'alive' state."
  269. raise TimeoutError(msg)
  270. self.session.key = self.kernel_manager.session.key
  271. future = self.request_kernel_info()
  272. def give_up():
  273. """Don't wait forever for the kernel to reply"""
  274. if future.done():
  275. return
  276. self.log.warning("Timeout waiting for kernel_info reply from %s", self.kernel_id)
  277. future.set_result({})
  278. loop = IOLoop.current()
  279. loop.add_timeout(loop.time() + self.kernel_info_timeout, give_up)
  280. # actually wait for it
  281. await asyncio.wrap_future(future)
  282. def connect(self):
  283. """Handle a connection."""
  284. self.multi_kernel_manager.notify_connect(self.kernel_id)
  285. # on new connections, flush the message buffer
  286. buffer_info = self.multi_kernel_manager.get_buffer(self.kernel_id, self.session_key)
  287. if buffer_info and buffer_info["session_key"] == self.session_key:
  288. self.log.info("Restoring connection for %s", self.session_key)
  289. if self.multi_kernel_manager.ports_changed(self.kernel_id):
  290. # If the kernel's ports have changed (some restarts trigger this)
  291. # then reset the channels so nudge() is using the correct iopub channel
  292. self.create_stream()
  293. else:
  294. # The kernel's ports have not changed; use the channels captured in the buffer
  295. self.channels = buffer_info["channels"]
  296. connected = self.nudge()
  297. def replay(value):
  298. replay_buffer = buffer_info["buffer"]
  299. if replay_buffer:
  300. self.log.info("Replaying %s buffered messages", len(replay_buffer))
  301. for channel, msg_list in replay_buffer:
  302. stream = self.channels[channel]
  303. self.handle_outgoing_message(stream, msg_list)
  304. connected.add_done_callback(replay)
  305. else:
  306. try:
  307. self.create_stream()
  308. connected = self.nudge()
  309. except web.HTTPError as e:
  310. # Do not log error if the kernel is already shutdown,
  311. # as it's normal that it's not responding
  312. try:
  313. self.multi_kernel_manager.get_kernel(self.kernel_id)
  314. self.log.error("Error opening stream: %s", e)
  315. except KeyError:
  316. pass
  317. # WebSockets don't respond to traditional error codes so we
  318. # close the connection.
  319. for stream in self.channels.values():
  320. if not stream.closed():
  321. stream.close()
  322. self.disconnect()
  323. return None
  324. self.multi_kernel_manager.add_restart_callback(self.kernel_id, self.on_kernel_restarted)
  325. self.multi_kernel_manager.add_restart_callback(
  326. self.kernel_id, self.on_restart_failed, "dead"
  327. )
  328. def subscribe(value):
  329. for stream in self.channels.values():
  330. stream.on_recv_stream(self.handle_outgoing_message)
  331. connected.add_done_callback(subscribe)
  332. ZMQChannelsWebsocketConnection._open_sockets.add(self)
  333. return connected
  334. def close(self):
  335. """Close the connection."""
  336. return self.disconnect()
  337. def disconnect(self):
  338. """Handle a disconnect."""
  339. self.log.debug("Websocket closed %s", self.session_key)
  340. # unregister myself as an open session (only if it's really me)
  341. if self._open_sessions.get(self.session_key) is self.websocket_handler:
  342. self._open_sessions.pop(self.session_key)
  343. if self.kernel_id in self.multi_kernel_manager:
  344. self.multi_kernel_manager.notify_disconnect(self.kernel_id)
  345. self.multi_kernel_manager.remove_restart_callback(
  346. self.kernel_id,
  347. self.on_kernel_restarted,
  348. )
  349. self.multi_kernel_manager.remove_restart_callback(
  350. self.kernel_id,
  351. self.on_restart_failed,
  352. "dead",
  353. )
  354. # start buffering instead of closing if this was the last connection
  355. if (
  356. self.kernel_id in self.multi_kernel_manager._kernel_connections
  357. and self.multi_kernel_manager._kernel_connections[self.kernel_id] == 0
  358. ):
  359. self.multi_kernel_manager.start_buffering(
  360. self.kernel_id, self.session_key, self.channels
  361. )
  362. ZMQChannelsWebsocketConnection._open_sockets.remove(self)
  363. self._close_future.set_result(None)
  364. return
  365. # This method can be called twice, once by self.kernel_died and once
  366. # from the WebSocket close event. If the WebSocket connection is
  367. # closed before the ZMQ streams are setup, they could be None.
  368. for stream in self.channels.values():
  369. if stream is not None and not stream.closed():
  370. stream.on_recv(None)
  371. stream.close()
  372. self.channels = {}
  373. try:
  374. ZMQChannelsWebsocketConnection._open_sockets.remove(self)
  375. self._close_future.set_result(None)
  376. except Exception:
  377. pass
  378. def handle_incoming_message(self, incoming_msg: str) -> None:
  379. """Handle incoming messages from Websocket to ZMQ Sockets."""
  380. ws_msg = incoming_msg
  381. if not self.channels:
  382. # already closed, ignore the message
  383. self.log.debug("Received message on closed websocket %r", ws_msg)
  384. return
  385. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  386. channel, msg_list = deserialize_msg_from_ws_v1(ws_msg)
  387. msg = {
  388. "header": None,
  389. }
  390. else:
  391. if isinstance(ws_msg, bytes): # type:ignore[unreachable]
  392. msg = deserialize_binary_message(ws_msg) # type:ignore[unreachable]
  393. else:
  394. msg = json.loads(ws_msg)
  395. msg_list = []
  396. channel = msg.pop("channel", None)
  397. if channel is None:
  398. self.log.warning("No channel specified, assuming shell: %s", msg)
  399. channel = "shell"
  400. if channel not in self.channels:
  401. self.log.warning("No such channel: %r", channel)
  402. return
  403. am = self.multi_kernel_manager.allowed_message_types
  404. ignore_msg = False
  405. if am:
  406. msg["header"] = self.get_part("header", msg["header"], msg_list)
  407. assert msg["header"] is not None
  408. if msg["header"]["msg_type"] not in am: # type:ignore[unreachable]
  409. self.log.warning(
  410. 'Received message of type "%s", which is not allowed. Ignoring.'
  411. % msg["header"]["msg_type"]
  412. )
  413. ignore_msg = True
  414. if not ignore_msg:
  415. stream = self.channels[channel]
  416. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  417. self.session.send_raw(stream, msg_list)
  418. else:
  419. self.session.send(stream, msg)
  420. def handle_outgoing_message(self, stream: str, outgoing_msg: list[t.Any]) -> None:
  421. """Handle the outgoing messages from ZMQ sockets to Websocket."""
  422. msg_list = outgoing_msg
  423. _, fed_msg_list = self.session.feed_identities(msg_list)
  424. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  425. msg = {"header": None, "parent_header": None, "content": None}
  426. else:
  427. msg = self.session.deserialize(fed_msg_list)
  428. if isinstance(stream, str):
  429. stream = self.channels[stream]
  430. channel = getattr(stream, "channel", None)
  431. parts = fed_msg_list[1:]
  432. self._on_error(channel, msg, parts)
  433. if self._limit_rate(channel, msg, parts):
  434. return
  435. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  436. self._on_zmq_reply(stream, parts)
  437. else:
  438. self._on_zmq_reply(stream, msg)
  439. def get_part(self, field, value, msg_list):
  440. """Get a part of a message."""
  441. if value is None:
  442. field2idx = {
  443. "header": 0,
  444. "parent_header": 1,
  445. "content": 3,
  446. }
  447. value = self.session.unpack(msg_list[field2idx[field]])
  448. return value
  449. def _reserialize_reply(self, msg_or_list, channel=None):
  450. """Reserialize a reply message using JSON.
  451. msg_or_list can be an already-deserialized msg dict or the zmq buffer list.
  452. If it is the zmq list, it will be deserialized with self.session.
  453. This takes the msg list from the ZMQ socket and serializes the result for the websocket.
  454. This method should be used by self._on_zmq_reply to build messages that can
  455. be sent back to the browser.
  456. """
  457. if isinstance(msg_or_list, dict):
  458. # already unpacked
  459. msg = msg_or_list
  460. else:
  461. _, msg_list = self.session.feed_identities(msg_or_list)
  462. msg = self.session.deserialize(msg_list)
  463. if channel:
  464. msg["channel"] = channel
  465. if msg["buffers"]:
  466. buf = serialize_binary_message(msg)
  467. return buf
  468. else:
  469. return json.dumps(msg, default=json_default)
  470. def _on_zmq_reply(self, stream, msg_list):
  471. """Handle a zmq reply."""
  472. # Sometimes this gets triggered when the on_close method is scheduled in the
  473. # eventloop but hasn't been called.
  474. if stream.closed():
  475. self.log.warning("zmq message arrived on closed channel")
  476. self.disconnect()
  477. return
  478. channel = getattr(stream, "channel", None)
  479. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  480. bin_msg = serialize_msg_to_ws_v1(msg_list, channel)
  481. self.write_message(bin_msg, binary=True)
  482. else:
  483. try:
  484. msg = self._reserialize_reply(msg_list, channel=channel)
  485. except Exception:
  486. self.log.critical("Malformed message: %r" % msg_list, exc_info=True)
  487. else:
  488. try:
  489. self.write_message(msg, binary=isinstance(msg, bytes))
  490. except WebSocketClosedError as e:
  491. self.log.warning(str(e))
  492. def request_kernel_info(self):
  493. """send a request for kernel_info"""
  494. try:
  495. # check for previous request
  496. future = self.kernel_manager._kernel_info_future
  497. except AttributeError:
  498. self.log.debug("Requesting kernel info from %s", self.kernel_id)
  499. # Create a kernel_info channel to query the kernel protocol version.
  500. # This channel will be closed after the kernel_info reply is received.
  501. if self.kernel_info_channel is None:
  502. self.kernel_info_channel = self.multi_kernel_manager.connect_shell(self.kernel_id)
  503. assert self.kernel_info_channel is not None
  504. self.kernel_info_channel.on_recv(self._handle_kernel_info_reply)
  505. self.session.send(self.kernel_info_channel, "kernel_info_request")
  506. # store the future on the kernel, so only one request is sent
  507. self.kernel_manager._kernel_info_future = self._kernel_info_future
  508. else:
  509. if not future.done():
  510. self.log.debug("Waiting for pending kernel_info request")
  511. future.add_done_callback(lambda f: self._finish_kernel_info(f.result()))
  512. return _ensure_future(self._kernel_info_future)
  513. def _handle_kernel_info_reply(self, msg):
  514. """process the kernel_info_reply
  515. enabling msg spec adaptation, if necessary
  516. """
  517. idents, msg = self.session.feed_identities(msg)
  518. try:
  519. msg = self.session.deserialize(msg)
  520. except BaseException:
  521. self.log.error("Bad kernel_info reply", exc_info=True)
  522. self._kernel_info_future.set_result({})
  523. return
  524. else:
  525. info = msg["content"]
  526. self.log.debug("Received kernel info: %s", info)
  527. if msg["msg_type"] != "kernel_info_reply" or "protocol_version" not in info:
  528. self.log.error("Kernel info request failed, assuming current %s", info)
  529. info = {}
  530. self._finish_kernel_info(info)
  531. # close the kernel_info channel, we don't need it anymore
  532. if self.kernel_info_channel:
  533. self.kernel_info_channel.close()
  534. self.kernel_info_channel = None
  535. def _finish_kernel_info(self, info):
  536. """Finish handling kernel_info reply
  537. Set up protocol adaptation, if needed,
  538. and signal that connection can continue.
  539. """
  540. protocol_version = info.get("protocol_version", client_protocol_version)
  541. if protocol_version != client_protocol_version:
  542. self.session.adapt_version = int(protocol_version.split(".")[0])
  543. self.log.info(
  544. f"Adapting from protocol version {protocol_version} (kernel {self.kernel_id}) to {client_protocol_version} (client)."
  545. )
  546. if not self._kernel_info_future.done():
  547. self._kernel_info_future.set_result(info)
  548. def write_stderr(self, error_message, parent_header):
  549. """Write a message to stderr."""
  550. self.log.warning(error_message)
  551. err_msg = self.session.msg(
  552. "stream",
  553. content={"text": error_message + "\n", "name": "stderr"},
  554. parent=parent_header,
  555. )
  556. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  557. bin_msg = serialize_msg_to_ws_v1(err_msg, "iopub", self.session.pack)
  558. self.write_message(bin_msg, binary=True)
  559. else:
  560. err_msg["channel"] = "iopub"
  561. self.write_message(json.dumps(err_msg, default=json_default))
  562. def _limit_rate(self, channel, msg, msg_list):
  563. """Limit the message rate on a channel."""
  564. if not (self.limit_rate and channel == "iopub"):
  565. return False
  566. msg["header"] = self.get_part("header", msg["header"], msg_list)
  567. msg_type = msg["header"]["msg_type"]
  568. if msg_type == "status":
  569. msg["content"] = self.get_part("content", msg["content"], msg_list)
  570. if msg["content"].get("execution_state") == "idle":
  571. # reset rate limit counter on status=idle,
  572. # to avoid 'Run All' hitting limits prematurely.
  573. self._iopub_window_byte_queue = []
  574. self._iopub_window_msg_count = 0
  575. self._iopub_window_byte_count = 0
  576. self._iopub_msgs_exceeded = False
  577. self._iopub_data_exceeded = False
  578. if msg_type not in {"status", "comm_open", "execute_input"}:
  579. # Remove the counts queued for removal.
  580. now = IOLoop.current().time()
  581. while len(self._iopub_window_byte_queue) > 0:
  582. queued = self._iopub_window_byte_queue[0]
  583. if now >= queued[0]:
  584. self._iopub_window_byte_count -= queued[1]
  585. self._iopub_window_msg_count -= 1
  586. del self._iopub_window_byte_queue[0]
  587. else:
  588. # This part of the queue hasn't be reached yet, so we can
  589. # abort the loop.
  590. break
  591. # Increment the bytes and message count
  592. self._iopub_window_msg_count += 1
  593. byte_count = sum(len(x) for x in msg_list) if msg_type == "stream" else 0
  594. self._iopub_window_byte_count += byte_count
  595. # Queue a removal of the byte and message count for a time in the
  596. # future, when we are no longer interested in it.
  597. self._iopub_window_byte_queue.append((now + self.rate_limit_window, byte_count))
  598. # Check the limits, set the limit flags, and reset the
  599. # message and data counts.
  600. msg_rate = float(self._iopub_window_msg_count) / self.rate_limit_window
  601. data_rate = float(self._iopub_window_byte_count) / self.rate_limit_window
  602. # Check the msg rate
  603. if self.iopub_msg_rate_limit > 0 and msg_rate > self.iopub_msg_rate_limit:
  604. if not self._iopub_msgs_exceeded:
  605. self._iopub_msgs_exceeded = True
  606. msg["parent_header"] = self.get_part(
  607. "parent_header", msg["parent_header"], msg_list
  608. )
  609. self.write_stderr(
  610. dedent(
  611. f"""\
  612. IOPub message rate exceeded.
  613. The Jupyter server will temporarily stop sending output
  614. to the client in order to avoid crashing it.
  615. To change this limit, set the config variable
  616. `--ServerApp.iopub_msg_rate_limit`.
  617. Current values:
  618. ServerApp.iopub_msg_rate_limit={self.iopub_msg_rate_limit} (msgs/sec)
  619. ServerApp.rate_limit_window={self.rate_limit_window} (secs)
  620. """
  621. ),
  622. msg["parent_header"],
  623. )
  624. # resume once we've got some headroom below the limit
  625. elif self._iopub_msgs_exceeded and msg_rate < (0.8 * self.iopub_msg_rate_limit):
  626. self._iopub_msgs_exceeded = False
  627. if not self._iopub_data_exceeded:
  628. self.log.warning("iopub messages resumed")
  629. # Check the data rate
  630. if self.iopub_data_rate_limit > 0 and data_rate > self.iopub_data_rate_limit:
  631. if not self._iopub_data_exceeded:
  632. self._iopub_data_exceeded = True
  633. msg["parent_header"] = self.get_part(
  634. "parent_header", msg["parent_header"], msg_list
  635. )
  636. self.write_stderr(
  637. dedent(
  638. f"""\
  639. IOPub data rate exceeded.
  640. The Jupyter server will temporarily stop sending output
  641. to the client in order to avoid crashing it.
  642. To change this limit, set the config variable
  643. `--ServerApp.iopub_data_rate_limit`.
  644. Current values:
  645. ServerApp.iopub_data_rate_limit={self.iopub_data_rate_limit} (bytes/sec)
  646. ServerApp.rate_limit_window={self.rate_limit_window} (secs)
  647. """
  648. ),
  649. msg["parent_header"],
  650. )
  651. # resume once we've got some headroom below the limit
  652. elif self._iopub_data_exceeded and data_rate < (0.8 * self.iopub_data_rate_limit):
  653. self._iopub_data_exceeded = False
  654. if not self._iopub_msgs_exceeded:
  655. self.log.warning("iopub messages resumed")
  656. # If either of the limit flags are set, do not send the message.
  657. if self._iopub_msgs_exceeded or self._iopub_data_exceeded:
  658. # we didn't send it, remove the current message from the calculus
  659. self._iopub_window_msg_count -= 1
  660. self._iopub_window_byte_count -= byte_count
  661. self._iopub_window_byte_queue.pop(-1)
  662. return True
  663. return False
  664. def _send_status_message(self, status):
  665. """Send a status message."""
  666. iopub = self.channels.get("iopub", None)
  667. if iopub and not iopub.closed():
  668. # flush IOPub before sending a restarting/dead status message
  669. # ensures proper ordering on the IOPub channel
  670. # that all messages from the stopped kernel have been delivered
  671. iopub.flush()
  672. msg = self.session.msg("status", {"execution_state": status})
  673. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  674. bin_msg = serialize_msg_to_ws_v1(msg, "iopub", self.session.pack)
  675. self.write_message(bin_msg, binary=True)
  676. else:
  677. msg["channel"] = "iopub"
  678. self.write_message(json.dumps(msg, default=json_default))
  679. def on_kernel_restarted(self):
  680. """Handle a kernel restart."""
  681. self.log.warning("kernel %s restarted", self.kernel_id)
  682. self._send_status_message("restarting")
  683. def on_restart_failed(self):
  684. """Handle a kernel restart failure."""
  685. self.log.error("kernel %s restarted failed!", self.kernel_id)
  686. self._send_status_message("dead")
  687. def _on_error(self, channel, msg, msg_list):
  688. """Handle an error message."""
  689. if self.multi_kernel_manager.allow_tracebacks:
  690. return
  691. if channel == "iopub":
  692. msg["header"] = self.get_part("header", msg["header"], msg_list)
  693. if msg["header"]["msg_type"] == "error":
  694. msg["content"] = self.get_part("content", msg["content"], msg_list)
  695. msg["content"]["ename"] = "ExecutionError"
  696. msg["content"]["evalue"] = "Execution error"
  697. msg["content"]["traceback"] = [self.kernel_manager.traceback_replacement_message]
  698. if self.subprotocol == "v1.kernel.websocket.jupyter.org":
  699. msg_list[3] = self.session.pack(msg["content"])
  700. KernelWebsocketConnectionABC.register(ZMQChannelsWebsocketConnection)