kernelbase.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. """Base class for a kernel that talks to frontends over 0MQ."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import asyncio
  6. import inspect
  7. import logging
  8. import os
  9. import socket
  10. import sys
  11. import threading
  12. import time
  13. import typing as t
  14. import uuid
  15. import warnings
  16. from collections.abc import Mapping
  17. from contextvars import Context, ContextVar, copy_context
  18. from datetime import datetime
  19. from functools import partial
  20. from signal import SIGINT, SIGTERM, Signals, default_int_handler, signal
  21. from .thread import CONTROL_THREAD_NAME
  22. if sys.platform != "win32":
  23. from signal import SIGKILL
  24. else:
  25. SIGKILL = "windown-SIGKILL-sentinel"
  26. try:
  27. # jupyter_client >= 5, use tz-aware now
  28. from jupyter_client.session import utcnow as now
  29. except ImportError:
  30. # jupyter_client < 5, use local now()
  31. now = datetime.now
  32. import psutil
  33. import zmq
  34. from IPython.core.error import StdinNotImplementedError
  35. from jupyter_client.session import Session
  36. from tornado import ioloop
  37. from traitlets.config.configurable import SingletonConfigurable
  38. from traitlets.traitlets import (
  39. Any,
  40. Bool,
  41. Dict,
  42. Float,
  43. Instance,
  44. Integer,
  45. List,
  46. Unicode,
  47. default,
  48. observe,
  49. )
  50. from zmq.eventloop.zmqstream import ZMQStream
  51. from ipykernel.jsonutil import json_clean
  52. from ._version import kernel_protocol_version
  53. from .iostream import OutStream
  54. from .utils import LazyDict, _async_in_context
  55. _AWAITABLE_MESSAGE: str = (
  56. "For consistency across implementations, it is recommended that `{func_name}`"
  57. " either be a coroutine function (`async def`) or return an awaitable object"
  58. " (like an `asyncio.Future`). It might become a requirement in the future."
  59. " Coroutine functions and awaitables have been supported since"
  60. " ipykernel 6.0 (2021). {target} does not seem to return an awaitable"
  61. )
  62. T = t.TypeVar("T")
  63. def _accepts_parameters(meth, param_names):
  64. parameters = inspect.signature(meth).parameters
  65. accepts = dict.fromkeys(param_names, False)
  66. for param in param_names:
  67. param_spec = parameters.get(param)
  68. accepts[param] = (
  69. param_spec
  70. and param_spec.kind in [param_spec.KEYWORD_ONLY, param_spec.POSITIONAL_OR_KEYWORD]
  71. ) or any(p.kind == p.VAR_KEYWORD for p in parameters.values())
  72. return accepts
  73. class Kernel(SingletonConfigurable):
  74. """The base kernel class."""
  75. # ---------------------------------------------------------------------------
  76. # Kernel interface
  77. # ---------------------------------------------------------------------------
  78. # attribute to override with a GUI
  79. eventloop = Any(None)
  80. processes: dict[str, psutil.Process] = {}
  81. @observe("eventloop")
  82. def _update_eventloop(self, change):
  83. """schedule call to eventloop from IOLoop"""
  84. loop = ioloop.IOLoop.current()
  85. if change.new is not None:
  86. loop.add_callback(self.enter_eventloop)
  87. session = Instance(Session, allow_none=True)
  88. profile_dir = Instance("IPython.core.profiledir.ProfileDir", allow_none=True)
  89. shell_stream = Instance(ZMQStream, allow_none=True)
  90. shell_streams: List[t.Any] = List(
  91. help="""Deprecated shell_streams alias. Use shell_stream
  92. .. versionchanged:: 6.0
  93. shell_streams is deprecated. Use shell_stream.
  94. """
  95. )
  96. implementation: str
  97. implementation_version: str
  98. banner: str
  99. @default("shell_streams")
  100. def _shell_streams_default(self): # pragma: no cover
  101. warnings.warn(
  102. "Kernel.shell_streams is deprecated in ipykernel 6.0. Use Kernel.shell_stream",
  103. DeprecationWarning,
  104. stacklevel=2,
  105. )
  106. if self.shell_stream is not None:
  107. return [self.shell_stream]
  108. return []
  109. @observe("shell_streams")
  110. def _shell_streams_changed(self, change): # pragma: no cover
  111. warnings.warn(
  112. "Kernel.shell_streams is deprecated in ipykernel 6.0. Use Kernel.shell_stream",
  113. DeprecationWarning,
  114. stacklevel=2,
  115. )
  116. if len(change.new) > 1:
  117. warnings.warn(
  118. "Kernel only supports one shell stream. Additional streams will be ignored.",
  119. RuntimeWarning,
  120. stacklevel=2,
  121. )
  122. if change.new:
  123. self.shell_stream = change.new[0]
  124. control_stream = Instance(ZMQStream, allow_none=True)
  125. debug_shell_socket = Any()
  126. control_thread = Any()
  127. shell_channel_thread = Any()
  128. iopub_socket = Any()
  129. iopub_thread = Any()
  130. stdin_socket = Any()
  131. log: logging.Logger = Instance(logging.Logger, allow_none=True) # type:ignore[assignment]
  132. # identities:
  133. int_id = Integer(-1)
  134. ident = Unicode()
  135. @default("ident")
  136. def _default_ident(self):
  137. return str(uuid.uuid4())
  138. # This should be overridden by wrapper kernels that implement any real
  139. # language.
  140. language_info: dict[str, object] = {}
  141. # any links that should go in the help menu
  142. help_links: List[dict[str, str]] = List()
  143. # Experimental option to break in non-user code.
  144. # The ipykernel source is in the call stack, so the user
  145. # has to manipulate the step-over and step-into in a wize way.
  146. debug_just_my_code = Bool(
  147. False,
  148. help="""Set to False if you want to debug python standard and dependent libraries.
  149. """,
  150. ).tag(config=True)
  151. # Experimental option to filter internal frames from the stack trace and stepping.
  152. filter_internal_frames = Bool(
  153. True,
  154. help="""Set to False if you want to debug kernel modules.
  155. """,
  156. ).tag(config=True)
  157. # track associations with current request
  158. # Private interface
  159. _darwin_app_nap = Bool(
  160. True,
  161. help="""Whether to use appnope for compatibility with OS X App Nap.
  162. Only affects OS X >= 10.9.
  163. """,
  164. ).tag(config=True)
  165. # track associations with current request
  166. _allow_stdin = Bool(False)
  167. _control_parent: Dict[str, t.Any] = Dict({})
  168. _control_parent_ident: bytes = b""
  169. _shell_parent: ContextVar[dict[str, Any]]
  170. _shell_parent_ident: ContextVar[bytes]
  171. _shell_context: Context
  172. # Kept for backward-compatibility, accesses _control_parent_ident and _shell_parent_ident,
  173. # see https://github.com/jupyterlab/jupyterlab/issues/17785
  174. _parent_ident: Mapping[str, bytes]
  175. # Asyncio lock for main shell thread.
  176. _main_asyncio_lock: asyncio.Lock
  177. @property
  178. def _parent_header(self):
  179. warnings.warn(
  180. "Kernel._parent_header is deprecated in ipykernel 6. Use .get_parent()",
  181. DeprecationWarning,
  182. stacklevel=2,
  183. )
  184. return self.get_parent()
  185. # Time to sleep after flushing the stdout/err buffers in each execute
  186. # cycle. While this introduces a hard limit on the minimal latency of the
  187. # execute cycle, it helps prevent output synchronization problems for
  188. # clients.
  189. # Units are in seconds. The minimum zmq latency on local host is probably
  190. # ~150 microseconds, set this to 500us for now. We may need to increase it
  191. # a little if it's not enough after more interactive testing.
  192. _execute_sleep = Float(0.0005).tag(config=True)
  193. # Frequency of the kernel's event loop.
  194. # Units are in seconds, kernel subclasses for GUI toolkits may need to
  195. # adapt to milliseconds.
  196. _poll_interval = Float(0.01).tag(config=True)
  197. stop_on_error_timeout = Float(
  198. 0.0,
  199. config=True,
  200. help="""time (in seconds) to wait for messages to arrive
  201. when aborting queued requests after an error.
  202. Requests that arrive within this window after an error
  203. will be cancelled.
  204. Increase in the event of unusually slow network
  205. causing significant delays,
  206. which can manifest as e.g. "Run all" in a notebook
  207. aborting some, but not all, messages after an error.
  208. """,
  209. )
  210. # If the shutdown was requested over the network, we leave here the
  211. # necessary reply message so it can be sent by our registered atexit
  212. # handler. This ensures that the reply is only sent to clients truly at
  213. # the end of our shutdown process (which happens after the underlying
  214. # IPython shell's own shutdown).
  215. _shutdown_message = None
  216. # This is a dict of port number that the kernel is listening on. It is set
  217. # by record_ports and used by connect_request.
  218. _recorded_ports = Dict()
  219. # Track execution count here. For IPython, we override this to use the
  220. # execution count we store in the shell.
  221. execution_count = 0
  222. # Asyncio lock to ensure only one control queue message is processed at a time.
  223. _control_lock = Instance(asyncio.Lock)
  224. msg_types = [
  225. "execute_request",
  226. "complete_request",
  227. "inspect_request",
  228. "history_request",
  229. "comm_info_request",
  230. "kernel_info_request",
  231. "connect_request",
  232. "shutdown_request",
  233. "is_complete_request",
  234. "interrupt_request",
  235. ]
  236. # control channel accepts all shell messages
  237. # and some of its own
  238. control_msg_types = [
  239. *msg_types,
  240. "debug_request",
  241. "usage_request",
  242. "create_subshell_request",
  243. "delete_subshell_request",
  244. "list_subshell_request",
  245. ]
  246. def __init__(self, **kwargs):
  247. """Initialize the kernel."""
  248. super().__init__(**kwargs)
  249. # Kernel application may swap stdout and stderr to OutStream,
  250. # which is the case in `IPKernelApp.init_io`, hence `sys.stdout`
  251. # can already by different from TextIO at initialization time.
  252. self._stdout: OutStream | t.TextIO = sys.stdout
  253. self._stderr: OutStream | t.TextIO = sys.stderr
  254. # Build dict of handlers for message types
  255. self.shell_handlers = {}
  256. for msg_type in self.msg_types:
  257. self.shell_handlers[msg_type] = getattr(self, msg_type)
  258. self.control_handlers = {}
  259. for msg_type in self.control_msg_types:
  260. self.control_handlers[msg_type] = getattr(self, msg_type)
  261. # Storing the accepted parameters for do_execute, used in execute_request
  262. self._do_exec_accepted_params = _accepts_parameters(
  263. self.do_execute, ["cell_meta", "cell_id"]
  264. )
  265. self._control_parent = {}
  266. self._control_parent_ident = b""
  267. self._shell_parent = ContextVar("shell_parent")
  268. self._shell_parent.set({})
  269. self._shell_parent_ident = ContextVar("shell_parent_ident")
  270. self._shell_parent_ident.set(b"")
  271. self._shell_context = copy_context()
  272. # For backward compatibility so that _parent_ident["shell"] and _parent_ident["control"]
  273. # work as they used to for ipykernel >= 7
  274. self._parent_ident = LazyDict(
  275. {
  276. "control": lambda: self._control_parent_ident,
  277. "shell": lambda: self._get_shell_context_var(self._shell_parent_ident),
  278. }
  279. )
  280. self._main_asyncio_lock = asyncio.Lock()
  281. async def dispatch_control(self, msg):
  282. """Dispatch a control request, ensuring only one message is processed at a time."""
  283. # Ensure only one control message is processed at a time
  284. async with self._control_lock:
  285. await self.process_control(msg)
  286. async def process_control(self, msg):
  287. """dispatch control requests"""
  288. if not self.session:
  289. return
  290. idents, msg = self.session.feed_identities(msg, copy=False)
  291. try:
  292. msg = self.session.deserialize(msg, content=True, copy=False)
  293. except Exception:
  294. self.log.error("Invalid Control Message", exc_info=True) # noqa: G201
  295. return
  296. self.log.debug("Control received: %s", msg)
  297. # Set the parent message for side effects.
  298. self.set_parent(idents, msg, channel="control")
  299. self._publish_status("busy", "control")
  300. header = msg["header"]
  301. msg_type = header["msg_type"]
  302. handler = self.control_handlers.get(msg_type, None)
  303. if handler is None:
  304. self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type)
  305. else:
  306. try:
  307. result = handler(self.control_stream, idents, msg)
  308. if inspect.isawaitable(result):
  309. await result
  310. except Exception:
  311. self.log.error("Exception in control handler:", exc_info=True) # noqa: G201
  312. if sys.stdout is not None:
  313. sys.stdout.flush()
  314. if sys.stderr is not None:
  315. sys.stderr.flush()
  316. self._publish_status_and_flush("idle", "control", self.control_stream)
  317. def should_handle(self, stream, msg, idents):
  318. """Check whether a shell-channel message should be handled
  319. Allows subclasses to prevent handling of certain messages (e.g. aborted requests).
  320. .. versionchanged:: 7
  321. Subclass should_handle _may_ be async.
  322. Base class implementation is not async.
  323. """
  324. return True
  325. async def dispatch_shell(self, msg, /, subshell_id: str | None = None):
  326. """dispatch shell requests"""
  327. if len(msg) == 1 and msg[0].buffer == b"stop aborting":
  328. # Dummy "stop aborting" message to stop aborting execute requests on this subshell.
  329. # This dummy message implementation allows the subshell to abort messages that are
  330. # already queued in the zmq sockets/streams without having to know any of their
  331. # details in advance.
  332. if subshell_id is None:
  333. self._aborting = False
  334. else:
  335. self.shell_channel_thread.manager.set_subshell_aborting(subshell_id, False)
  336. return
  337. if not self.session:
  338. return
  339. if self._supports_kernel_subshells:
  340. assert threading.current_thread() not in (
  341. self.control_thread,
  342. self.shell_channel_thread,
  343. )
  344. idents, msg = self.session.feed_identities(msg, copy=False)
  345. try:
  346. msg = self.session.deserialize(msg, content=True, copy=False)
  347. except Exception:
  348. self.log.error("Invalid Message", exc_info=True) # noqa: G201
  349. return
  350. # Set the parent message for side effects.
  351. self.set_parent(idents, msg, channel="shell")
  352. self._publish_status("busy", "shell")
  353. msg_type = msg["header"]["msg_type"]
  354. assert msg["header"].get("subshell_id") == subshell_id
  355. if self._supports_kernel_subshells:
  356. stream = self.shell_channel_thread.manager.get_subshell_to_shell_channel_socket(
  357. subshell_id
  358. )
  359. else:
  360. stream = self.shell_stream
  361. # Only abort execute requests
  362. if msg_type == "execute_request":
  363. if subshell_id is None:
  364. aborting = self._aborting # type:ignore[unreachable]
  365. else:
  366. aborting = self.shell_channel_thread.manager.get_subshell_aborting(subshell_id)
  367. if aborting:
  368. self._send_abort_reply(stream, msg, idents)
  369. self._publish_status_and_flush("idle", "shell", stream)
  370. return
  371. # Print some info about this message and leave a '--->' marker, so it's
  372. # easier to trace visually the message chain when debugging. Each
  373. # handler prints its message at the end.
  374. self.log.debug("\n*** MESSAGE TYPE:%s***", msg_type)
  375. self.log.debug(" Content: %s\n --->\n ", msg["content"])
  376. should_handle: bool | t.Awaitable[bool] = self.should_handle(stream, msg, idents)
  377. if inspect.isawaitable(should_handle):
  378. should_handle = await should_handle
  379. if not should_handle:
  380. self._publish_status_and_flush("idle", "shell", stream)
  381. self.log.debug("Not handling %s:%s", msg_type, msg["header"].get("msg_id"))
  382. return
  383. handler = self.shell_handlers.get(msg_type, None)
  384. if handler is None:
  385. self.log.warning("Unknown message type: %r", msg_type)
  386. else:
  387. self.log.debug("%s: %s", msg_type, msg)
  388. try:
  389. self.pre_handler_hook()
  390. except Exception:
  391. self.log.debug("Unable to signal in pre_handler_hook:", exc_info=True)
  392. try:
  393. result = handler(stream, idents, msg)
  394. if inspect.isawaitable(result):
  395. await result
  396. except Exception:
  397. self.log.error("Exception in message handler:", exc_info=True) # noqa: G201
  398. except KeyboardInterrupt:
  399. # Ctrl-c shouldn't crash the kernel here.
  400. self.log.error("KeyboardInterrupt caught in kernel.")
  401. finally:
  402. try:
  403. self.post_handler_hook()
  404. except Exception:
  405. self.log.debug("Unable to signal in post_handler_hook:", exc_info=True)
  406. if sys.stdout is not None:
  407. sys.stdout.flush()
  408. if sys.stderr is not None:
  409. sys.stderr.flush()
  410. self._publish_status_and_flush("idle", "shell", stream)
  411. def pre_handler_hook(self):
  412. """Hook to execute before calling message handler"""
  413. # ensure default_int_handler during handler call
  414. self.saved_sigint_handler = signal(SIGINT, default_int_handler)
  415. def post_handler_hook(self):
  416. """Hook to execute after calling message handler"""
  417. signal(SIGINT, self.saved_sigint_handler)
  418. def enter_eventloop(self):
  419. """enter eventloop"""
  420. self.log.info("Entering eventloop %s", self.eventloop)
  421. # record handle, so we can check when this changes
  422. eventloop = self.eventloop
  423. if eventloop is None:
  424. self.log.info("Exiting as there is no eventloop")
  425. return
  426. async def advance_eventloop():
  427. # check if eventloop changed:
  428. if self.eventloop is not eventloop:
  429. self.log.info("exiting eventloop %s", eventloop)
  430. return
  431. self.log.debug("Advancing eventloop %s", eventloop)
  432. try:
  433. eventloop(self)
  434. except KeyboardInterrupt:
  435. # Ctrl-C shouldn't crash the kernel
  436. self.log.error("KeyboardInterrupt caught in kernel")
  437. if self.eventloop is eventloop:
  438. # schedule advance again
  439. schedule_next()
  440. def schedule_next():
  441. """Schedule the next advance of the eventloop"""
  442. # call_later allows the io_loop to process other events if needed.
  443. # Going through schedule_dispatch ensures all other dispatches on msg_queue
  444. # are processed before we enter the eventloop, even if the previous dispatch was
  445. # already consumed from the queue by process_one and the queue is
  446. # technically empty.
  447. self.log.debug("Scheduling eventloop advance")
  448. self.io_loop.call_later(0.001, advance_eventloop)
  449. # begin polling the eventloop
  450. schedule_next()
  451. async def _create_control_lock(self):
  452. # This can be removed when minimum python increases to 3.10
  453. self._control_lock = asyncio.Lock()
  454. def start(self):
  455. """register dispatchers for streams"""
  456. self.io_loop = ioloop.IOLoop.current()
  457. if self.control_stream:
  458. self.control_stream.on_recv(self.dispatch_control, copy=False)
  459. if self.control_thread and sys.version_info < (3, 10):
  460. # Before Python 3.10 we need to ensure the _control_lock is created in the
  461. # thread that uses it. When our minimum python is 3.10 we can remove this
  462. # and always use the else below, or just assign it where it is declared.
  463. self.control_thread.io_loop.add_callback(self._create_control_lock)
  464. else:
  465. self._control_lock = asyncio.Lock()
  466. if self.shell_stream:
  467. if self.shell_channel_thread:
  468. self.shell_channel_thread.manager.set_on_recv_callback(self.shell_main)
  469. self.shell_stream.on_recv(self.shell_channel_thread_main, copy=False)
  470. else:
  471. self.shell_stream.on_recv(
  472. _async_in_context(partial(self.shell_main, None)),
  473. copy=False,
  474. )
  475. # publish idle status
  476. self._publish_status("starting", "shell")
  477. async def shell_channel_thread_main(self, msg):
  478. """Handler for shell messages received on shell_channel_thread"""
  479. assert threading.current_thread() == self.shell_channel_thread
  480. async with self.shell_channel_thread.asyncio_lock:
  481. if self.session is None:
  482. return
  483. # deserialize only the header to get subshell_id
  484. # Keep original message to send to subshell_id unmodified.
  485. _, msg2 = self.session.feed_identities(msg, copy=False)
  486. try:
  487. msg3 = self.session.deserialize(msg2, content=False, copy=False)
  488. subshell_id = msg3["header"].get("subshell_id")
  489. # Find inproc pair socket to use to send message to correct subshell.
  490. subshell_manager = self.shell_channel_thread.manager
  491. socket = subshell_manager.get_shell_channel_to_subshell_socket(subshell_id)
  492. assert socket is not None
  493. socket.send_multipart(msg, copy=False)
  494. except Exception:
  495. self.log.error("Invalid message", exc_info=True) # noqa: G201
  496. async def shell_main(self, subshell_id: str | None, msg):
  497. """Handler of shell messages for a single subshell"""
  498. if self._supports_kernel_subshells:
  499. if subshell_id is None:
  500. assert threading.current_thread() == self.shell_channel_thread.parent_thread
  501. asyncio_lock = self._main_asyncio_lock
  502. else:
  503. assert threading.current_thread() not in (
  504. self.shell_channel_thread,
  505. self.shell_channel_thread.parent_thread,
  506. )
  507. asyncio_lock = self.shell_channel_thread.manager.get_subshell_asyncio_lock(
  508. subshell_id
  509. )
  510. else:
  511. assert subshell_id is None
  512. asyncio_lock = self._main_asyncio_lock
  513. # Whilst executing a shell message, do not accept any other shell messages on the
  514. # same subshell, so that cells are run sequentially. Without this we can run multiple
  515. # async cells at the same time which would be a nice feature to have but is an API
  516. # change.
  517. assert asyncio_lock is not None
  518. async with asyncio_lock:
  519. await self.dispatch_shell(msg, subshell_id=subshell_id)
  520. def record_ports(self, ports):
  521. """Record the ports that this kernel is using.
  522. The creator of the Kernel instance must call this methods if they
  523. want the :meth:`connect_request` method to return the port numbers.
  524. """
  525. self._recorded_ports = ports
  526. # ---------------------------------------------------------------------------
  527. # Kernel request handlers
  528. # ---------------------------------------------------------------------------
  529. def _publish_execute_input(self, code, parent, execution_count):
  530. """Publish the code request on the iopub stream."""
  531. if not self.session:
  532. return
  533. self.session.send(
  534. self.iopub_socket,
  535. "execute_input",
  536. {"code": code, "execution_count": execution_count},
  537. parent=parent,
  538. ident=self._topic("execute_input"),
  539. )
  540. def _publish_status(self, status, channel, parent=None):
  541. """send status (busy/idle) on IOPub"""
  542. if not self.session:
  543. return
  544. self.session.send(
  545. self.iopub_socket,
  546. "status",
  547. {"execution_state": status},
  548. parent=parent or self.get_parent(channel),
  549. ident=self._topic("status"),
  550. )
  551. def _publish_status_and_flush(self, status, channel, stream, parent=None):
  552. """send status on IOPub and flush specified stream to ensure reply is sent before handling the next reply"""
  553. self._publish_status(status, channel, parent)
  554. if stream and hasattr(stream, "flush") and not self._supports_kernel_subshells:
  555. stream.flush(zmq.POLLOUT)
  556. def _publish_debug_event(self, event):
  557. if not self.session:
  558. return
  559. self.session.send(
  560. self.iopub_socket,
  561. "debug_event",
  562. event,
  563. parent=self.get_parent(),
  564. ident=self._topic("debug_event"),
  565. )
  566. def set_parent(self, ident, parent, channel="shell"):
  567. """Set the current parent request
  568. Side effects (IOPub messages) and replies are associated with
  569. the request that caused them via the parent_header.
  570. The parent identity is used to route input_request messages
  571. on the stdin channel.
  572. """
  573. if channel == "control":
  574. self._control_parent_ident = ident
  575. self._control_parent = parent
  576. else:
  577. self._shell_parent_ident.set(ident)
  578. self._shell_parent.set(parent)
  579. # preserve the last call to set_parent
  580. self._shell_context = copy_context()
  581. def get_parent(self, channel=None):
  582. """Get the parent request associated with a channel.
  583. .. versionadded:: 6
  584. Parameters
  585. ----------
  586. channel : str
  587. the name of the channel ('shell' or 'control')
  588. Returns
  589. -------
  590. message : dict
  591. the parent message for the most recent request on the channel.
  592. """
  593. if channel is None:
  594. # If a channel is not specified, get information from current thread
  595. if threading.current_thread().name == CONTROL_THREAD_NAME:
  596. channel = "control"
  597. else:
  598. channel = "shell"
  599. if channel == "control":
  600. return self._control_parent
  601. return self._get_shell_context_var(self._shell_parent)
  602. def _get_shell_context_var(self, var: ContextVar[T]) -> T:
  603. """Lookup a ContextVar, falling back on the shell context
  604. Allows for user-launched Threads to still resolve to the shell's main context
  605. necessary for e.g. display from threads.
  606. """
  607. try:
  608. return var.get()
  609. except LookupError:
  610. return self._shell_context[var]
  611. def send_response(
  612. self,
  613. stream,
  614. msg_or_type,
  615. content=None,
  616. ident=None,
  617. buffers=None,
  618. track=False,
  619. header=None,
  620. metadata=None,
  621. channel=None,
  622. ):
  623. """Send a response to the message we're currently processing.
  624. This accepts all the parameters of :meth:`jupyter_client.session.Session.send`
  625. except ``parent``.
  626. This relies on :meth:`set_parent` having been called for the current
  627. message.
  628. """
  629. if not self.session:
  630. return None
  631. return self.session.send(
  632. stream,
  633. msg_or_type,
  634. content,
  635. self.get_parent(channel),
  636. ident,
  637. buffers,
  638. track,
  639. header,
  640. metadata,
  641. )
  642. def init_metadata(self, parent):
  643. """Initialize metadata.
  644. Run at the beginning of execution requests.
  645. """
  646. # FIXME: `started` is part of ipyparallel
  647. # Remove for ipykernel 5.0
  648. return {
  649. "started": now(),
  650. }
  651. def finish_metadata(self, parent, metadata, reply_content):
  652. """Finish populating metadata.
  653. Run after completing an execution request.
  654. """
  655. return metadata
  656. async def execute_request(self, stream, ident, parent):
  657. """handle an execute_request"""
  658. if not self.session:
  659. return
  660. try:
  661. content = parent["content"]
  662. code = content["code"]
  663. silent = content.get("silent", False)
  664. store_history = content.get("store_history", not silent)
  665. user_expressions = content.get("user_expressions", {})
  666. allow_stdin = content.get("allow_stdin", False)
  667. cell_meta = parent.get("metadata", {})
  668. cell_id = cell_meta.get("cellId")
  669. except Exception:
  670. self.log.error("Got bad msg: ")
  671. self.log.error("%s", parent)
  672. return
  673. stop_on_error = content.get("stop_on_error", True)
  674. metadata = self.init_metadata(parent)
  675. # Re-broadcast our input for the benefit of listening clients, and
  676. # start computing output
  677. if not silent:
  678. self.execution_count += 1
  679. self._publish_execute_input(code, parent, self.execution_count)
  680. # Arguments based on the do_execute signature
  681. do_execute_args = {
  682. "code": code,
  683. "silent": silent,
  684. "store_history": store_history,
  685. "user_expressions": user_expressions,
  686. "allow_stdin": allow_stdin,
  687. }
  688. if self._do_exec_accepted_params["cell_meta"]:
  689. do_execute_args["cell_meta"] = cell_meta
  690. if self._do_exec_accepted_params["cell_id"]:
  691. do_execute_args["cell_id"] = cell_id
  692. subshell_id = parent["header"].get("subshell_id")
  693. # Call do_execute with the appropriate arguments
  694. reply_content = self.do_execute(**do_execute_args)
  695. if inspect.isawaitable(reply_content):
  696. reply_content = await reply_content
  697. else:
  698. warnings.warn(
  699. _AWAITABLE_MESSAGE.format(func_name="do_execute", target=self.do_execute),
  700. PendingDeprecationWarning,
  701. stacklevel=1,
  702. )
  703. # Flush output before sending the reply.
  704. if sys.stdout is not None:
  705. sys.stdout.flush()
  706. if sys.stderr is not None:
  707. sys.stderr.flush()
  708. # FIXME: on rare occasions, the flush doesn't seem to make it to the
  709. # clients... This seems to mitigate the problem, but we definitely need
  710. # to better understand what's going on.
  711. if self._execute_sleep:
  712. time.sleep(self._execute_sleep)
  713. # Send the reply.
  714. reply_content = json_clean(reply_content)
  715. metadata = self.finish_metadata(parent, metadata, reply_content)
  716. reply_msg: dict[str, t.Any] = self.session.send( # type:ignore[assignment]
  717. stream,
  718. "execute_reply",
  719. reply_content,
  720. parent,
  721. metadata=metadata,
  722. ident=ident,
  723. )
  724. self.log.debug("%s", reply_msg)
  725. if not silent and reply_msg["content"]["status"] == "error" and stop_on_error:
  726. subshell_id = parent["header"].get("subshell_id")
  727. self._abort_queues(subshell_id)
  728. def do_execute(
  729. self,
  730. code,
  731. silent,
  732. store_history=True,
  733. user_expressions=None,
  734. allow_stdin=False,
  735. *,
  736. cell_meta=None,
  737. cell_id=None,
  738. ):
  739. """Execute user code. Must be overridden by subclasses."""
  740. raise NotImplementedError
  741. async def complete_request(self, stream, ident, parent):
  742. """Handle a completion request."""
  743. if not self.session:
  744. return
  745. content = parent["content"]
  746. code = content["code"]
  747. cursor_pos = content["cursor_pos"]
  748. matches = self.do_complete(code, cursor_pos)
  749. if inspect.isawaitable(matches):
  750. matches = await matches
  751. else:
  752. warnings.warn(
  753. _AWAITABLE_MESSAGE.format(func_name="do_complete", target=self.do_complete),
  754. PendingDeprecationWarning,
  755. stacklevel=1,
  756. )
  757. matches = json_clean(matches)
  758. self.session.send(stream, "complete_reply", matches, parent, ident)
  759. def do_complete(self, code, cursor_pos):
  760. """Override in subclasses to find completions."""
  761. return {
  762. "matches": [],
  763. "cursor_end": cursor_pos,
  764. "cursor_start": cursor_pos,
  765. "metadata": {},
  766. "status": "ok",
  767. }
  768. async def inspect_request(self, stream, ident, parent):
  769. """Handle an inspect request."""
  770. if not self.session:
  771. return
  772. content = parent["content"]
  773. reply_content = self.do_inspect(
  774. content["code"],
  775. content["cursor_pos"],
  776. content.get("detail_level", 0),
  777. set(content.get("omit_sections", [])),
  778. )
  779. if inspect.isawaitable(reply_content):
  780. reply_content = await reply_content
  781. else:
  782. warnings.warn(
  783. _AWAITABLE_MESSAGE.format(func_name="do_inspect", target=self.do_inspect),
  784. PendingDeprecationWarning,
  785. stacklevel=1,
  786. )
  787. # Before we send this object over, we scrub it for JSON usage
  788. reply_content = json_clean(reply_content)
  789. msg = self.session.send(stream, "inspect_reply", reply_content, parent, ident)
  790. self.log.debug("%s", msg)
  791. def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
  792. """Override in subclasses to allow introspection."""
  793. return {"status": "ok", "data": {}, "metadata": {}, "found": False}
  794. async def history_request(self, stream, ident, parent):
  795. """Handle a history request."""
  796. if not self.session:
  797. return
  798. content = parent["content"]
  799. reply_content = self.do_history(**content)
  800. if inspect.isawaitable(reply_content):
  801. reply_content = await reply_content
  802. else:
  803. warnings.warn(
  804. _AWAITABLE_MESSAGE.format(func_name="do_history", target=self.do_history),
  805. PendingDeprecationWarning,
  806. stacklevel=1,
  807. )
  808. reply_content = json_clean(reply_content)
  809. msg = self.session.send(stream, "history_reply", reply_content, parent, ident)
  810. self.log.debug("%s", msg)
  811. def do_history(
  812. self,
  813. hist_access_type,
  814. output,
  815. raw,
  816. session=None,
  817. start=None,
  818. stop=None,
  819. n=None,
  820. pattern=None,
  821. unique=False,
  822. ):
  823. """Override in subclasses to access history."""
  824. return {"status": "ok", "history": []}
  825. async def connect_request(self, stream, ident, parent):
  826. """Handle a connect request."""
  827. if not self.session:
  828. return
  829. content = self._recorded_ports.copy() if self._recorded_ports else {}
  830. content["status"] = "ok"
  831. msg = self.session.send(stream, "connect_reply", content, parent, ident)
  832. self.log.debug("%s", msg)
  833. @property
  834. def kernel_info(self):
  835. from .debugger import _is_debugpy_available
  836. supported_features: list[str] = []
  837. if self._supports_kernel_subshells:
  838. supported_features.append("kernel subshells")
  839. if _is_debugpy_available:
  840. supported_features.append("debugger")
  841. return {
  842. "protocol_version": kernel_protocol_version,
  843. "implementation": self.implementation,
  844. "implementation_version": self.implementation_version,
  845. "language_info": self.language_info,
  846. "banner": self.banner,
  847. "help_links": self.help_links,
  848. "supported_features": supported_features,
  849. }
  850. async def kernel_info_request(self, stream, ident, parent):
  851. """Handle a kernel info request."""
  852. if not self.session:
  853. return
  854. content = {"status": "ok"}
  855. content.update(self.kernel_info)
  856. msg = self.session.send(stream, "kernel_info_reply", content, parent, ident)
  857. self.log.debug("%s", msg)
  858. async def comm_info_request(self, stream, ident, parent):
  859. """Handle a comm info request."""
  860. if not self.session:
  861. return
  862. content = parent["content"]
  863. target_name = content.get("target_name", None)
  864. # Should this be moved to ipkernel?
  865. if hasattr(self, "comm_manager"):
  866. comms = {
  867. k: dict(target_name=v.target_name)
  868. for (k, v) in self.comm_manager.comms.items()
  869. if v.target_name == target_name or target_name is None
  870. }
  871. else:
  872. comms = {}
  873. reply_content = dict(comms=comms, status="ok")
  874. msg = self.session.send(stream, "comm_info_reply", reply_content, parent, ident)
  875. self.log.debug("%s", msg)
  876. def _send_interrupt_children(self):
  877. if os.name == "nt":
  878. self.log.error("Interrupt message not supported on Windows")
  879. else:
  880. pid = os.getpid()
  881. pgid = os.getpgid(pid)
  882. # Prefer process-group over process
  883. # but only if the kernel is the leader of the process group
  884. if pgid and pgid == pid and hasattr(os, "killpg"):
  885. try:
  886. os.killpg(pgid, SIGINT)
  887. except OSError:
  888. os.kill(pid, SIGINT)
  889. raise
  890. else:
  891. os.kill(pid, SIGINT)
  892. async def interrupt_request(self, stream, ident, parent):
  893. """Handle an interrupt request."""
  894. if not self.session:
  895. return
  896. content: dict[str, t.Any] = {"status": "ok"}
  897. try:
  898. self._send_interrupt_children()
  899. except OSError as err:
  900. import traceback
  901. content = {
  902. "status": "error",
  903. "traceback": traceback.format_stack(),
  904. "ename": str(type(err).__name__),
  905. "evalue": str(err),
  906. }
  907. self.session.send(stream, "interrupt_reply", content, parent, ident=ident)
  908. return
  909. async def shutdown_request(self, stream, ident, parent):
  910. """Handle a shutdown request."""
  911. if not self.session:
  912. return
  913. content = self.do_shutdown(parent["content"]["restart"])
  914. if inspect.isawaitable(content):
  915. content = await content
  916. else:
  917. warnings.warn(
  918. _AWAITABLE_MESSAGE.format(func_name="do_shutdown", target=self.do_shutdown),
  919. PendingDeprecationWarning,
  920. stacklevel=1,
  921. )
  922. self.session.send(stream, "shutdown_reply", content, parent, ident=ident)
  923. # same content, but different msg_id for broadcasting on IOPub
  924. self._shutdown_message = self.session.msg("shutdown_reply", content, parent)
  925. await self._at_shutdown()
  926. self.log.debug("Stopping control ioloop")
  927. if self.control_stream:
  928. control_io_loop = self.control_stream.io_loop
  929. control_io_loop.add_callback(control_io_loop.stop)
  930. self.log.debug("Stopping shell ioloop")
  931. self.io_loop.add_callback(self.io_loop.stop)
  932. if self.shell_stream and self.shell_stream.io_loop != self.io_loop:
  933. shell_io_loop = self.shell_stream.io_loop
  934. shell_io_loop.add_callback(shell_io_loop.stop)
  935. def do_shutdown(self, restart):
  936. """Override in subclasses to do things when the frontend shuts down the
  937. kernel.
  938. """
  939. return {"status": "ok", "restart": restart}
  940. async def is_complete_request(self, stream, ident, parent):
  941. """Handle an is_complete request."""
  942. if not self.session:
  943. return
  944. content = parent["content"]
  945. code = content["code"]
  946. reply_content = self.do_is_complete(code)
  947. if inspect.isawaitable(reply_content):
  948. reply_content = await reply_content
  949. else:
  950. warnings.warn(
  951. _AWAITABLE_MESSAGE.format(func_name="do_is_complete", target=self.do_is_complete),
  952. PendingDeprecationWarning,
  953. stacklevel=1,
  954. )
  955. reply_content = json_clean(reply_content)
  956. reply_msg = self.session.send(stream, "is_complete_reply", reply_content, parent, ident)
  957. self.log.debug("%s", reply_msg)
  958. def do_is_complete(self, code):
  959. """Override in subclasses to find completions."""
  960. return {"status": "unknown"}
  961. async def debug_request(self, stream, ident, parent):
  962. """Handle a debug request."""
  963. if not self.session:
  964. return
  965. content = parent["content"]
  966. reply_content = self.do_debug_request(content)
  967. if inspect.isawaitable(reply_content):
  968. reply_content = await reply_content
  969. else:
  970. warnings.warn(
  971. _AWAITABLE_MESSAGE.format(
  972. func_name="do_debug_request", target=self.do_debug_request
  973. ),
  974. PendingDeprecationWarning,
  975. stacklevel=1,
  976. )
  977. reply_content = json_clean(reply_content)
  978. reply_msg = self.session.send(stream, "debug_reply", reply_content, parent, ident)
  979. self.log.debug("%s", reply_msg)
  980. def get_process_metric_value(self, process, name, attribute=None):
  981. """Get the process metric value."""
  982. try:
  983. metric_value = getattr(process, name)()
  984. if attribute is not None: # ... a named tuple
  985. return getattr(metric_value, attribute)
  986. # ... or a number
  987. return metric_value
  988. # Avoid littering logs with stack traces
  989. # complaining about dead processes
  990. except BaseException:
  991. return 0
  992. async def usage_request(self, stream, ident, parent):
  993. """Handle a usage request."""
  994. if not self.session:
  995. return
  996. reply_content = {"hostname": socket.gethostname(), "pid": os.getpid()}
  997. current_process = psutil.Process()
  998. all_processes = [current_process, *current_process.children(recursive=True)]
  999. # Ensure 1) self.processes is updated to only current subprocesses
  1000. # and 2) we reuse processes when possible (needed for accurate CPU)
  1001. self.processes = {
  1002. process.pid: self.processes.get(process.pid, process) # type:ignore[misc,call-overload]
  1003. for process in all_processes
  1004. }
  1005. reply_content["kernel_cpu"] = sum(
  1006. [
  1007. self.get_process_metric_value(process, "cpu_percent", None)
  1008. for process in self.processes.values()
  1009. ]
  1010. )
  1011. mem_info_type = "pss" if hasattr(current_process.memory_full_info(), "pss") else "rss"
  1012. reply_content["kernel_memory"] = sum(
  1013. [
  1014. self.get_process_metric_value(process, "memory_full_info", mem_info_type)
  1015. for process in self.processes.values()
  1016. ]
  1017. )
  1018. cpu_percent = psutil.cpu_percent()
  1019. # https://psutil.readthedocs.io/en/latest/index.html?highlight=cpu#psutil.cpu_percent
  1020. # The first time cpu_percent is called it will return a meaningless 0.0 value which you are supposed to ignore.
  1021. if cpu_percent is not None and cpu_percent != 0.0: # type:ignore[redundant-expr]
  1022. reply_content["host_cpu_percent"] = cpu_percent
  1023. reply_content["cpu_count"] = psutil.cpu_count(logical=True)
  1024. reply_content["host_virtual_memory"] = dict(psutil.virtual_memory()._asdict())
  1025. reply_msg = self.session.send(stream, "usage_reply", reply_content, parent, ident)
  1026. self.log.debug("%s", reply_msg)
  1027. async def do_debug_request(self, msg):
  1028. raise NotImplementedError
  1029. async def create_subshell_request(self, socket, ident, parent) -> None:
  1030. """Handle a create subshell request.
  1031. .. versionadded:: 7
  1032. """
  1033. if not self.session:
  1034. return
  1035. if not self._supports_kernel_subshells:
  1036. self.log.error("Subshells are not supported by this kernel")
  1037. return
  1038. assert threading.current_thread().name == CONTROL_THREAD_NAME
  1039. # This should only be called in the control thread if it exists.
  1040. # Request is passed to shell channel thread to process.
  1041. control_socket = self.shell_channel_thread.manager.control_to_shell_channel.from_socket
  1042. control_socket.send_json({"type": "create"})
  1043. reply = control_socket.recv_json()
  1044. self.session.send(socket, "create_subshell_reply", reply, parent, ident)
  1045. async def delete_subshell_request(self, socket, ident, parent) -> None:
  1046. """Handle a delete subshell request.
  1047. .. versionadded:: 7
  1048. """
  1049. if not self.session:
  1050. return
  1051. if not self._supports_kernel_subshells:
  1052. self.log.error("KERNEL SUBSHELLS NOT SUPPORTED")
  1053. return
  1054. assert threading.current_thread().name == CONTROL_THREAD_NAME
  1055. try:
  1056. content = parent["content"]
  1057. subshell_id = content["subshell_id"]
  1058. except Exception:
  1059. self.log.error("Got bad msg from parent: %s", parent)
  1060. return
  1061. # This should only be called in the control thread if it exists.
  1062. # Request is passed to shell channel thread to process.
  1063. control_socket = self.shell_channel_thread.manager.control_to_shell_channel.from_socket
  1064. control_socket.send_json({"type": "delete", "subshell_id": subshell_id})
  1065. reply = control_socket.recv_json()
  1066. self.session.send(socket, "delete_subshell_reply", reply, parent, ident)
  1067. async def list_subshell_request(self, socket, ident, parent) -> None:
  1068. """Handle a list subshell request.
  1069. .. versionadded:: 7
  1070. """
  1071. if not self.session:
  1072. return
  1073. if not self._supports_kernel_subshells:
  1074. self.log.error("Subshells are not supported by this kernel")
  1075. return
  1076. assert threading.current_thread().name == CONTROL_THREAD_NAME
  1077. # This should only be called in the control thread if it exists.
  1078. # Request is passed to shell channel thread to process.
  1079. control_socket = self.shell_channel_thread.manager.control_to_shell_channel.from_socket
  1080. control_socket.send_json({"type": "list"})
  1081. reply = control_socket.recv_json()
  1082. self.session.send(socket, "list_subshell_reply", reply, parent, ident)
  1083. # ---------------------------------------------------------------------------
  1084. # Protected interface
  1085. # ---------------------------------------------------------------------------
  1086. def _topic(self, topic):
  1087. """prefixed topic for IOPub messages"""
  1088. base = "kernel.%s" % self.ident
  1089. return (f"{base}.{topic}").encode()
  1090. _aborting = Bool(False)
  1091. def _post_dummy_stop_aborting_message(self, subshell_id: str | None) -> None:
  1092. """Post a dummy message to the correct subshell that when handled will unset
  1093. the _aborting flag.
  1094. """
  1095. subshell_manager = self.shell_channel_thread.manager
  1096. socket = subshell_manager.get_shell_channel_to_subshell_socket(subshell_id)
  1097. assert socket is not None
  1098. msg = b"stop aborting" # Magic string for dummy message.
  1099. socket.send(msg, copy=False)
  1100. def _abort_queues(self, subshell_id: str | None = None):
  1101. # while this flag is true,
  1102. # execute requests will be aborted
  1103. if subshell_id is None:
  1104. self._aborting = True
  1105. else:
  1106. self.shell_channel_thread.manager.set_subshell_aborting(subshell_id, True)
  1107. self.log.info("Aborting queue")
  1108. if self.shell_channel_thread:
  1109. # Only really need to do this if there are messages already queued
  1110. self.shell_channel_thread.io_loop.add_callback(
  1111. self._post_dummy_stop_aborting_message, subshell_id
  1112. )
  1113. return
  1114. # flush streams, so all currently waiting messages
  1115. # are added to the queue
  1116. if self.shell_stream and not self._supports_kernel_subshells:
  1117. self.shell_stream.flush()
  1118. # Callback to signal that we are done aborting
  1119. # dispatch functions _must_ be async
  1120. async def stop_aborting():
  1121. self.log.info("Finishing abort")
  1122. self._aborting = False
  1123. if self.stop_on_error_timeout:
  1124. # if we have a delay, give messages this long to arrive on the queue
  1125. # before we stop aborting requests
  1126. self.io_loop.call_later(self.stop_on_error_timeout, stop_aborting)
  1127. # If we have an eventloop, it may interfere with the call_later above.
  1128. # If the loop has a _schedule_exit method, we call that so the loop exits
  1129. # after stop_on_error_timeout, returning to the main io_loop and letting
  1130. # the call_later fire.
  1131. if self.eventloop is not None and hasattr(self.eventloop, "_schedule_exit"):
  1132. self.eventloop._schedule_exit(self.stop_on_error_timeout + 0.01)
  1133. else:
  1134. self.io_loop.add_callback(stop_aborting)
  1135. def _send_abort_reply(self, stream, msg, idents):
  1136. """Send a reply to an aborted request"""
  1137. if not self.session:
  1138. return
  1139. self.log.info("Aborting %s: %s", msg["header"]["msg_id"], msg["header"]["msg_type"])
  1140. reply_type = msg["header"]["msg_type"].rsplit("_", 1)[0] + "_reply"
  1141. status = {"status": "aborted"}
  1142. md = self.init_metadata(msg)
  1143. md = self.finish_metadata(msg, md, status)
  1144. md.update(status)
  1145. self.session.send(
  1146. stream,
  1147. reply_type,
  1148. metadata=md,
  1149. content=status,
  1150. parent=msg,
  1151. ident=idents,
  1152. )
  1153. def _no_raw_input(self):
  1154. """Raise StdinNotImplementedError if active frontend doesn't support
  1155. stdin."""
  1156. msg = "raw_input was called, but this frontend does not support stdin."
  1157. raise StdinNotImplementedError(msg)
  1158. def getpass(self, prompt="", stream=None):
  1159. """Forward getpass to frontends
  1160. Raises
  1161. ------
  1162. StdinNotImplementedError if active frontend doesn't support stdin.
  1163. """
  1164. if not self._allow_stdin:
  1165. msg = "getpass was called, but this frontend does not support input requests."
  1166. raise StdinNotImplementedError(msg)
  1167. if stream is not None:
  1168. import warnings
  1169. warnings.warn(
  1170. "The `stream` parameter of `getpass.getpass` will have no effect when using ipykernel",
  1171. UserWarning,
  1172. stacklevel=2,
  1173. )
  1174. return self._input_request(
  1175. prompt,
  1176. self._get_shell_context_var(self._shell_parent_ident),
  1177. self.get_parent("shell"),
  1178. password=True,
  1179. )
  1180. def raw_input(self, prompt=""):
  1181. """Forward raw_input to frontends
  1182. Raises
  1183. ------
  1184. StdinNotImplementedError if active frontend doesn't support stdin.
  1185. """
  1186. if not self._allow_stdin:
  1187. msg = "raw_input was called, but this frontend does not support input requests."
  1188. raise StdinNotImplementedError(msg)
  1189. return self._input_request(
  1190. str(prompt),
  1191. self._get_shell_context_var(self._shell_parent_ident),
  1192. self.get_parent("shell"),
  1193. password=False,
  1194. )
  1195. def _input_request(self, prompt, ident, parent, password=False):
  1196. # Flush output before making the request.
  1197. if sys.stdout is not None:
  1198. sys.stdout.flush()
  1199. if sys.stderr is not None:
  1200. sys.stderr.flush()
  1201. # flush the stdin socket, to purge stale replies
  1202. while True:
  1203. try:
  1204. self.stdin_socket.recv_multipart(zmq.NOBLOCK)
  1205. except zmq.ZMQError as e:
  1206. if e.errno == zmq.EAGAIN:
  1207. break
  1208. raise
  1209. # Send the input request.
  1210. assert self.session is not None
  1211. content = json_clean(dict(prompt=prompt, password=password))
  1212. self.session.send(self.stdin_socket, "input_request", content, parent, ident=ident)
  1213. # Await a response.
  1214. while True:
  1215. try:
  1216. # Use polling with select() so KeyboardInterrupts can get
  1217. # through; doing a blocking recv() means stdin reads are
  1218. # uninterruptible on Windows. We need a timeout because
  1219. # zmq.select() is also uninterruptible, but at least this
  1220. # way reads get noticed immediately and KeyboardInterrupts
  1221. # get noticed fairly quickly by human response time standards.
  1222. rlist, _, xlist = zmq.select([self.stdin_socket], [], [self.stdin_socket], 0.01)
  1223. if rlist or xlist:
  1224. ident, reply = self.session.recv(self.stdin_socket)
  1225. if (ident, reply) != (None, None):
  1226. break
  1227. except KeyboardInterrupt:
  1228. # re-raise KeyboardInterrupt, to truncate traceback
  1229. msg = "Interrupted by user"
  1230. raise KeyboardInterrupt(msg) from None
  1231. except Exception:
  1232. self.log.warning("Invalid Message:", exc_info=True)
  1233. try:
  1234. value = reply["content"]["value"] # type:ignore[index]
  1235. except Exception:
  1236. self.log.error("Bad input_reply: %s", parent)
  1237. value = ""
  1238. if value == "\x04":
  1239. # EOF
  1240. raise EOFError
  1241. return value
  1242. def _signal_children(self, signum):
  1243. """
  1244. Send a signal to all our children
  1245. Like `killpg`, but does not include the current process
  1246. (or possible parents).
  1247. """
  1248. sig_rep = f"{Signals(signum)!r}"
  1249. for p in self._process_children():
  1250. self.log.debug("Sending %s to subprocess %s", sig_rep, p)
  1251. try:
  1252. if signum == SIGTERM:
  1253. p.terminate()
  1254. elif signum == SIGKILL:
  1255. p.kill()
  1256. else:
  1257. p.send_signal(signum)
  1258. except psutil.NoSuchProcess:
  1259. pass
  1260. def _process_children(self):
  1261. """Retrieve child processes in the kernel's process group
  1262. Avoids:
  1263. - including parents and self with killpg
  1264. - including all children that may have forked-off a new group
  1265. """
  1266. kernel_process = psutil.Process()
  1267. all_children = kernel_process.children(recursive=True)
  1268. if os.name == "nt":
  1269. return all_children
  1270. kernel_pgid = os.getpgrp()
  1271. process_group_children = []
  1272. for child in all_children:
  1273. try:
  1274. child_pgid = os.getpgid(child.pid)
  1275. except OSError:
  1276. pass
  1277. else:
  1278. if child_pgid == kernel_pgid:
  1279. process_group_children.append(child)
  1280. return process_group_children
  1281. async def _progressively_terminate_all_children(self):
  1282. sleeps = (0.01, 0.03, 0.1, 0.3, 1, 3, 10)
  1283. if not self._process_children():
  1284. self.log.debug("Kernel has no children.")
  1285. return
  1286. for signum in (SIGTERM, SIGKILL):
  1287. for delay in sleeps:
  1288. children = self._process_children()
  1289. if not children:
  1290. self.log.debug("No more children, continuing shutdown routine.")
  1291. return
  1292. # signals only children, not current process
  1293. self._signal_children(signum)
  1294. self.log.debug(
  1295. "Will sleep %s sec before checking for children and retrying. %s",
  1296. delay,
  1297. children,
  1298. )
  1299. await asyncio.sleep(delay)
  1300. async def _at_shutdown(self):
  1301. """Actions taken at shutdown by the kernel, called by python's atexit."""
  1302. try:
  1303. await self._progressively_terminate_all_children()
  1304. except Exception as e:
  1305. self.log.exception("Exception during subprocesses termination %s", e)
  1306. finally:
  1307. if self._shutdown_message is not None and self.session:
  1308. self.session.send(
  1309. self.iopub_socket,
  1310. self._shutdown_message,
  1311. ident=self._topic("shutdown"),
  1312. )
  1313. self.log.debug("%s", self._shutdown_message)
  1314. if self.control_stream:
  1315. self.control_stream.flush(zmq.POLLOUT)
  1316. @property
  1317. def _supports_kernel_subshells(self):
  1318. return self.shell_channel_thread is not None