| 1 |
"""Defines a KernelClient that provides thread-safe sockets with async callbacks on message |
| 2 |
replies. |
| 3 |
""" |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import atexit |
| 7 |
import time |
| 8 |
from concurrent.futures import Future |
| 9 |
from functools import partial |
| 10 |
from threading import Thread |
| 11 |
from typing import Any |
| 12 |
|
| 13 |
import zmq |
| 14 |
from tornado.ioloop import IOLoop |
| 15 |
from traitlets import Instance, Type |
| 16 |
from traitlets.log import get_logger |
| 17 |
from zmq.eventloop import zmqstream |
| 18 |
|
| 19 |
from .channels import HBChannel |
| 20 |
from .client import KernelClient |
| 21 |
from .session import Session |
| 22 |
|
| 23 |
# Local imports |
| 24 |
# import ZMQError in top-level namespace, to avoid ugly attribute-error messages |
| 25 |
# during garbage collection of threads at exit |
| 26 |
|
| 27 |
|
| 28 |
class ThreadedZMQSocketChannel: |
| 29 |
"""A ZMQ socket invoking a callback in the ioloop""" |
| 30 |
|
| 31 |
session = None |
| 32 |
socket = None |
| 33 |
ioloop = None |
| 34 |
stream = None |
| 35 |
_inspect = None |
| 36 |
|
| 37 |
def __init__( |
| 38 |
self, |
| 39 |
socket: zmq.Socket | None, |
| 40 |
session: Session | None, |
| 41 |
loop: IOLoop | None, |
| 42 |
) -> None: |
| 43 |
"""Create a channel. |
| 44 |
|
| 45 |
Parameters |
| 46 |
---------- |
| 47 |
socket : :class:`zmq.Socket` |
| 48 |
The ZMQ socket to use. |
| 49 |
session : :class:`session.Session` |
| 50 |
The session to use. |
| 51 |
loop |
| 52 |
A tornado ioloop to connect the socket to using a ZMQStream |
| 53 |
""" |
| 54 |
super().__init__() |
| 55 |
|
| 56 |
self.socket = socket |
| 57 |
self.session = session |
| 58 |
self.ioloop = loop |
| 59 |
f: Future = Future() |
| 60 |
|
| 61 |
def setup_stream() -> None: |
| 62 |
try: |
| 63 |
assert self.socket is not None |
| 64 |
self.stream = zmqstream.ZMQStream(self.socket, self.ioloop) |
| 65 |
self.stream.on_recv(self._handle_recv) |
| 66 |
except Exception as e: |
| 67 |
f.set_exception(e) |
| 68 |
else: |
| 69 |
f.set_result(None) |
| 70 |
|
| 71 |
assert self.ioloop is not None |
| 72 |
self.ioloop.add_callback(setup_stream) |
| 73 |
# don't wait forever, raise any errors |
| 74 |
f.result(timeout=10) |
| 75 |
|
| 76 |
_is_alive = False |
| 77 |
|
| 78 |
def is_alive(self) -> bool: |
| 79 |
"""Whether the channel is alive.""" |
| 80 |
return self._is_alive |
| 81 |
|
| 82 |
def start(self) -> None: |
| 83 |
"""Start the channel.""" |
| 84 |
self._is_alive = True |
| 85 |
|
| 86 |
def stop(self) -> None: |
| 87 |
"""Stop the channel.""" |
| 88 |
self._is_alive = False |
| 89 |
|
| 90 |
def close(self) -> None: |
| 91 |
"""Close the channel.""" |
| 92 |
if self.stream is not None and self.ioloop is not None: |
| 93 |
# c.f.Future for threadsafe results |
| 94 |
f: Future = Future() |
| 95 |
|
| 96 |
def close_stream() -> None: |
| 97 |
try: |
| 98 |
if self.stream is not None: |
| 99 |
self.stream.close(linger=0) |
| 100 |
self.stream = None |
| 101 |
except Exception as e: |
| 102 |
f.set_exception(e) |
| 103 |
else: |
| 104 |
f.set_result(None) |
| 105 |
|
| 106 |
self.ioloop.add_callback(close_stream) |
| 107 |
# wait for result |
| 108 |
try: |
| 109 |
f.result(timeout=5) |
| 110 |
except Exception as e: |
| 111 |
log = get_logger() |
| 112 |
msg = f"Error closing stream {self.stream}: {e}" |
| 113 |
log.warning(msg, RuntimeWarning, stacklevel=2) |
| 114 |
|
| 115 |
if self.socket is not None: |
| 116 |
try: |
| 117 |
self.socket.close(linger=0) |
| 118 |
except Exception: |
| 119 |
pass |
| 120 |
self.socket = None |
| 121 |
|
| 122 |
def send(self, msg: dict[str, Any]) -> None: |
| 123 |
"""Queue a message to be sent from the IOLoop's thread. |
| 124 |
|
| 125 |
Parameters |
| 126 |
---------- |
| 127 |
msg : message to send |
| 128 |
|
| 129 |
This is threadsafe, as it uses IOLoop.add_callback to give the loop's |
| 130 |
thread control of the action. |
| 131 |
""" |
| 132 |
|
| 133 |
def thread_send() -> None: |
| 134 |
assert self.session is not None |
| 135 |
self.session.send(self.stream, msg) |
| 136 |
|
| 137 |
assert self.ioloop is not None |
| 138 |
self.ioloop.add_callback(thread_send) |
| 139 |
|
| 140 |
def _handle_recv(self, msg_list: list) -> None: |
| 141 |
"""Callback for stream.on_recv. |
| 142 |
|
| 143 |
Unpacks message, and calls handlers with it. |
| 144 |
""" |
| 145 |
assert self.ioloop is not None |
| 146 |
assert self.session is not None |
| 147 |
_ident, smsg = self.session.feed_identities(msg_list) |
| 148 |
msg = self.session.deserialize(smsg) |
| 149 |
# let client inspect messages |
| 150 |
if self._inspect: |
| 151 |
self._inspect(msg) # type:ignore[unreachable] |
| 152 |
self.call_handlers(msg) |
| 153 |
|
| 154 |
def call_handlers(self, msg: dict[str, Any]) -> None: |
| 155 |
"""This method is called in the ioloop thread when a message arrives. |
| 156 |
|
| 157 |
Subclasses should override this method to handle incoming messages. |
| 158 |
It is important to remember that this method is called in the thread |
| 159 |
so that some logic must be done to ensure that the application level |
| 160 |
handlers are called in the application thread. |
| 161 |
""" |
| 162 |
pass |
| 163 |
|
| 164 |
def process_events(self) -> None: |
| 165 |
"""Subclasses should override this with a method |
| 166 |
processing any pending GUI events. |
| 167 |
""" |
| 168 |
pass |
| 169 |
|
| 170 |
def flush(self, timeout: float = 1.0) -> None: |
| 171 |
"""Immediately processes all pending messages on this channel. |
| 172 |
|
| 173 |
This is only used for the IOPub channel. |
| 174 |
|
| 175 |
Callers should use this method to ensure that :meth:`call_handlers` |
| 176 |
has been called for all messages that have been received on the |
| 177 |
0MQ SUB socket of this channel. |
| 178 |
|
| 179 |
This method is thread safe. |
| 180 |
|
| 181 |
Parameters |
| 182 |
---------- |
| 183 |
timeout : float, optional |
| 184 |
The maximum amount of time to spend flushing, in seconds. The |
| 185 |
default is one second. |
| 186 |
""" |
| 187 |
# We do the IOLoop callback process twice to ensure that the IOLoop |
| 188 |
# gets to perform at least one full poll. |
| 189 |
stop_time = time.monotonic() + timeout |
| 190 |
assert self.ioloop is not None |
| 191 |
if self.stream is None or self.stream.closed(): |
| 192 |
# don't bother scheduling flush on a thread if we're closed |
| 193 |
_msg = "Attempt to flush closed stream" |
| 194 |
raise OSError(_msg) |
| 195 |
|
| 196 |
def flush(f: Any) -> None: |
| 197 |
try: |
| 198 |
self._flush() |
| 199 |
except Exception as e: |
| 200 |
f.set_exception(e) |
| 201 |
else: |
| 202 |
f.set_result(None) |
| 203 |
|
| 204 |
for _ in range(2): |
| 205 |
f: Future = Future() |
| 206 |
self.ioloop.add_callback(partial(flush, f)) |
| 207 |
# wait for async flush, re-raise any errors |
| 208 |
timeout = max(stop_time - time.monotonic(), 0) |
| 209 |
try: |
| 210 |
f.result(max(stop_time - time.monotonic(), 0)) |
| 211 |
except TimeoutError: |
| 212 |
# flush with a timeout means stop waiting, not raise |
| 213 |
return |
| 214 |
|
| 215 |
def _flush(self) -> None: |
| 216 |
"""Callback for :method:`self.flush`.""" |
| 217 |
# Race condition: flush() checks stream validity then schedules this |
| 218 |
# callback on the ioloop thread. Between scheduling and execution, |
| 219 |
# stop_channels() may close the stream (e.g., during teardown). |
| 220 |
# Handle gracefully rather than asserting, since this is an expected |
| 221 |
# edge case during shutdown, not a programming error. |
| 222 |
if self.stream is None or self.stream.closed(): |
| 223 |
return |
| 224 |
self.stream.flush() |
| 225 |
self._flushed = True |
| 226 |
|
| 227 |
|
| 228 |
class IOLoopThread(Thread): |
| 229 |
"""Run a pyzmq ioloop in a thread to send and receive messages""" |
| 230 |
|
| 231 |
_exiting = False |
| 232 |
ioloop = None |
| 233 |
|
| 234 |
def __init__(self) -> None: |
| 235 |
"""Initialize an io loop thread.""" |
| 236 |
super().__init__() |
| 237 |
self.daemon = True |
| 238 |
|
| 239 |
# Instance variable to track exit state for this specific thread. |
| 240 |
# The class variable _exiting is used by _notice_exit for interpreter shutdown. |
| 241 |
# Without this instance variable, stopping one IOLoopThread sets the class-level |
| 242 |
# _exiting = True, causing all subsequent IOLoopThread instances to exit immediately |
| 243 |
# in _async_run(). This breaks sequential kernel usage (e.g., qtconsole tests). |
| 244 |
self._exiting = False |
| 245 |
|
| 246 |
@staticmethod |
| 247 |
@atexit.register |
| 248 |
def _notice_exit() -> None: |
| 249 |
# Class definitions can be torn down during interpreter shutdown. |
| 250 |
# We only need to set _exiting flag if this hasn't happened. |
| 251 |
if IOLoopThread is not None: |
| 252 |
IOLoopThread._exiting = True |
| 253 |
|
| 254 |
def start(self) -> None: |
| 255 |
"""Start the IOLoop thread |
| 256 |
|
| 257 |
Don't return until self.ioloop is defined, |
| 258 |
which is created in the thread |
| 259 |
""" |
| 260 |
self._start_future: Future = Future() |
| 261 |
Thread.start(self) |
| 262 |
# wait for start, re-raise any errors |
| 263 |
self._start_future.result(timeout=10) |
| 264 |
|
| 265 |
def run(self) -> None: |
| 266 |
"""Run my loop, ignoring EINTR events in the poller""" |
| 267 |
try: |
| 268 |
loop = asyncio.new_event_loop() |
| 269 |
asyncio.set_event_loop(loop) |
| 270 |
|
| 271 |
async def assign_ioloop() -> None: |
| 272 |
self.ioloop = IOLoop.current() |
| 273 |
|
| 274 |
loop.run_until_complete(assign_ioloop()) |
| 275 |
except Exception as e: |
| 276 |
self._start_future.set_exception(e) |
| 277 |
else: |
| 278 |
self._start_future.set_result(None) |
| 279 |
try: |
| 280 |
loop.run_until_complete(self._async_run()) |
| 281 |
finally: |
| 282 |
loop.close() |
| 283 |
|
| 284 |
async def _async_run(self) -> None: |
| 285 |
"""Run forever (until self._exiting is set)""" |
| 286 |
while not self._exiting: |
| 287 |
await asyncio.sleep(1) |
| 288 |
|
| 289 |
def stop(self) -> None: |
| 290 |
"""Stop the channel's event loop and join its thread. |
| 291 |
|
| 292 |
This calls :meth:`~threading.Thread.join` and returns when the thread |
| 293 |
terminates. :class:`RuntimeError` will be raised if |
| 294 |
:meth:`~threading.Thread.start` is called again. |
| 295 |
""" |
| 296 |
self._exiting = True |
| 297 |
self.join() |
| 298 |
self.close() |
| 299 |
self.ioloop = None |
| 300 |
|
| 301 |
def __del__(self) -> None: |
| 302 |
self.close() |
| 303 |
|
| 304 |
def close(self) -> None: |
| 305 |
"""Close the io loop thread.""" |
| 306 |
if self.ioloop is not None: |
| 307 |
try: |
| 308 |
self.ioloop.close(all_fds=True) |
| 309 |
except Exception: |
| 310 |
pass |
| 311 |
|
| 312 |
|
| 313 |
class ThreadedKernelClient(KernelClient): |
| 314 |
"""A KernelClient that provides thread-safe sockets with async callbacks on message replies.""" |
| 315 |
|
| 316 |
@property |
| 317 |
def ioloop(self) -> IOLoop | None: # type:ignore[override] |
| 318 |
if self.ioloop_thread: |
| 319 |
return self.ioloop_thread.ioloop |
| 320 |
return None |
| 321 |
|
| 322 |
ioloop_thread = Instance(IOLoopThread, allow_none=True) |
| 323 |
|
| 324 |
def start_channels( |
| 325 |
self, |
| 326 |
shell: bool = True, |
| 327 |
iopub: bool = True, |
| 328 |
stdin: bool = True, |
| 329 |
hb: bool = True, |
| 330 |
control: bool = True, |
| 331 |
) -> None: |
| 332 |
"""Start the channels on the client.""" |
| 333 |
self.ioloop_thread = IOLoopThread() |
| 334 |
self.ioloop_thread.start() |
| 335 |
|
| 336 |
if shell: |
| 337 |
self.shell_channel._inspect = self._check_kernel_info_reply |
| 338 |
|
| 339 |
super().start_channels(shell, iopub, stdin, hb, control) |
| 340 |
|
| 341 |
def _check_kernel_info_reply(self, msg: dict[str, Any]) -> None: |
| 342 |
"""This is run in the ioloop thread when the kernel info reply is received""" |
| 343 |
if msg["msg_type"] == "kernel_info_reply": |
| 344 |
self._handle_kernel_info_reply(msg) |
| 345 |
self.shell_channel._inspect = None |
| 346 |
|
| 347 |
def stop_channels(self) -> None: |
| 348 |
"""Stop the channels on the client.""" |
| 349 |
# Close channel streams while ioloop is still running |
| 350 |
# This must happen before stopping the ioloop thread, otherwise |
| 351 |
# the ZMQ streams can't be properly unregistered from the event loop |
| 352 |
if self.ioloop_thread and self.ioloop_thread.is_alive(): |
| 353 |
if self._shell_channel is not None: |
| 354 |
self._shell_channel.close() |
| 355 |
if self._iopub_channel is not None: |
| 356 |
self._iopub_channel.close() |
| 357 |
if self._stdin_channel is not None: |
| 358 |
self._stdin_channel.close() |
| 359 |
if self._control_channel is not None: |
| 360 |
self._control_channel.close() |
| 361 |
|
| 362 |
super().stop_channels() |
| 363 |
if self.ioloop_thread and self.ioloop_thread.is_alive(): |
| 364 |
self.ioloop_thread.stop() |
| 365 |
|
| 366 |
iopub_channel_class = Type(ThreadedZMQSocketChannel) # type:ignore[assignment] |
| 367 |
shell_channel_class = Type(ThreadedZMQSocketChannel) # type:ignore[assignment] |
| 368 |
stdin_channel_class = Type(ThreadedZMQSocketChannel) # type:ignore[assignment] |
| 369 |
hb_channel_class = Type(HBChannel) # type:ignore[assignment] |
| 370 |
control_channel_class = Type(ThreadedZMQSocketChannel) # type:ignore[assignment] |
| 371 |
|
| 372 |
def is_alive(self) -> bool: |
| 373 |
"""Is the kernel process still running?""" |
| 374 |
if self._hb_channel is not None: |
| 375 |
# We don't have access to the KernelManager, |
| 376 |
# so we use the heartbeat. |
| 377 |
return self._hb_channel.is_beating() |
| 378 |
# no heartbeat and not local, we can't tell if it's running, |
| 379 |
# so naively return True |
| 380 |
return True |