multikernelmanager.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. """A kernel manager for multiple kernels"""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import asyncio
  6. import json
  7. import os
  8. import socket
  9. import typing as t
  10. import uuid
  11. from functools import wraps
  12. from pathlib import Path
  13. import zmq
  14. from traitlets import Any, Bool, Dict, DottedObjectName, Instance, Unicode, default, observe
  15. from traitlets.config.configurable import LoggingConfigurable
  16. from traitlets.utils.importstring import import_item
  17. from .connect import KernelConnectionInfo
  18. from .kernelspec import NATIVE_KERNEL_NAME, KernelSpecManager
  19. from .manager import KernelManager
  20. from .utils import ensure_async, run_sync, utcnow
  21. class DuplicateKernelError(Exception):
  22. pass
  23. def kernel_method(f: t.Callable) -> t.Callable:
  24. """decorator for proxying MKM.method(kernel_id) to individual KMs by ID"""
  25. @wraps(f)
  26. def wrapped(
  27. self: t.Any, kernel_id: str, *args: t.Any, **kwargs: t.Any
  28. ) -> t.Callable | t.Awaitable:
  29. # get the kernel
  30. km = self.get_kernel(kernel_id)
  31. method = getattr(km, f.__name__)
  32. # call the kernel's method
  33. r = method(*args, **kwargs)
  34. # last thing, call anything defined in the actual class method
  35. # such as logging messages
  36. f(self, kernel_id, *args, **kwargs)
  37. # return the method result
  38. return r
  39. return wrapped
  40. class MultiKernelManager(LoggingConfigurable):
  41. """A class for managing multiple kernels."""
  42. default_kernel_name = Unicode(
  43. NATIVE_KERNEL_NAME, help="The name of the default kernel to start"
  44. ).tag(config=True)
  45. kernel_spec_manager = Instance(KernelSpecManager, allow_none=True)
  46. kernel_manager_class = DottedObjectName(
  47. "jupyter_client.ioloop.IOLoopKernelManager",
  48. help="""The kernel manager class. This is configurable to allow
  49. subclassing of the KernelManager for customized behavior.
  50. """,
  51. ).tag(config=True)
  52. @observe("kernel_manager_class")
  53. def _kernel_manager_class_changed(self, change: t.Any) -> None:
  54. self.kernel_manager_factory = self._create_kernel_manager_factory()
  55. kernel_manager_factory = Any(help="this is kernel_manager_class after import")
  56. @default("kernel_manager_factory")
  57. def _kernel_manager_factory_default(self) -> t.Callable:
  58. return self._create_kernel_manager_factory()
  59. def _create_kernel_manager_factory(self) -> t.Callable:
  60. kernel_manager_ctor = import_item(self.kernel_manager_class)
  61. def create_kernel_manager(*args: t.Any, **kwargs: t.Any) -> KernelManager:
  62. if self.shared_context:
  63. if self.context.closed:
  64. # recreate context if closed
  65. self.context = self._context_default()
  66. kwargs.setdefault("context", self.context)
  67. km = kernel_manager_ctor(*args, **kwargs)
  68. return km
  69. return create_kernel_manager
  70. shared_context = Bool(
  71. True,
  72. help="Share a single zmq.Context to talk to all my kernels",
  73. ).tag(config=True)
  74. context = Instance("zmq.Context")
  75. _created_context = Bool(False)
  76. _pending_kernels = Dict()
  77. @property
  78. def _starting_kernels(self) -> dict:
  79. """A shim for backwards compatibility."""
  80. return self._pending_kernels
  81. @default("context")
  82. def _context_default(self) -> zmq.Context:
  83. self._created_context = True
  84. return zmq.Context()
  85. connection_dir = Unicode("")
  86. external_connection_dir = Unicode(None, allow_none=True)
  87. _kernels = Dict()
  88. def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
  89. super().__init__(*args, **kwargs)
  90. self.kernel_id_to_connection_file: dict[str, Path] = {}
  91. def __del__(self) -> None:
  92. """Handle garbage collection. Destroy context if applicable."""
  93. if self._created_context and self.context and not self.context.closed:
  94. if self.log:
  95. self.log.debug("Destroying zmq context for %s", self)
  96. self.context.destroy(linger=1000)
  97. try:
  98. super_del = super().__del__ # type:ignore[misc]
  99. except AttributeError:
  100. pass
  101. else:
  102. super_del()
  103. def list_kernel_ids(self) -> list[str]:
  104. """Return a list of the kernel ids of the active kernels."""
  105. if self.external_connection_dir is not None:
  106. external_connection_dir = Path(self.external_connection_dir)
  107. if external_connection_dir.is_dir():
  108. connection_files = [p for p in external_connection_dir.iterdir() if p.is_file()]
  109. # remove kernels (whose connection file has disappeared) from our list
  110. k = list(self.kernel_id_to_connection_file.keys())
  111. v = list(self.kernel_id_to_connection_file.values())
  112. for connection_file in list(self.kernel_id_to_connection_file.values()):
  113. if connection_file not in connection_files:
  114. kernel_id = k[v.index(connection_file)]
  115. del self.kernel_id_to_connection_file[kernel_id]
  116. del self._kernels[kernel_id]
  117. # add kernels (whose connection file appeared) to our list
  118. for connection_file in connection_files:
  119. if connection_file in self.kernel_id_to_connection_file.values():
  120. continue
  121. try:
  122. connection_info: KernelConnectionInfo = json.loads(
  123. connection_file.read_text()
  124. )
  125. except Exception: # noqa: S112
  126. continue
  127. self.log.debug("Loading connection file %s", connection_file)
  128. if not ("kernel_name" in connection_info and "key" in connection_info):
  129. continue
  130. # it looks like a connection file
  131. kernel_id = self.new_kernel_id()
  132. self.kernel_id_to_connection_file[kernel_id] = connection_file
  133. km = self.kernel_manager_factory(
  134. parent=self,
  135. log=self.log,
  136. owns_kernel=False,
  137. )
  138. km.load_connection_info(connection_info)
  139. km.last_activity = utcnow()
  140. km.execution_state = "idle"
  141. km.connections = 1
  142. km.kernel_id = kernel_id
  143. km.kernel_name = connection_info["kernel_name"]
  144. km.ready.set_result(None)
  145. self._kernels[kernel_id] = km
  146. # Create a copy so we can iterate over kernels in operations
  147. # that delete keys.
  148. return list(self._kernels.keys())
  149. def __len__(self) -> int:
  150. """Return the number of running kernels."""
  151. return len(self.list_kernel_ids())
  152. def __contains__(self, kernel_id: str) -> bool:
  153. return kernel_id in self._kernels
  154. def pre_start_kernel(
  155. self, kernel_name: str | None, kwargs: t.Any
  156. ) -> tuple[KernelManager, str, str]:
  157. # kwargs should be mutable, passing it as a dict argument.
  158. kernel_id = kwargs.pop("kernel_id", self.new_kernel_id(**kwargs))
  159. if kernel_id in self:
  160. raise DuplicateKernelError("Kernel already exists: %s" % kernel_id)
  161. if kernel_name is None:
  162. kernel_name = self.default_kernel_name
  163. # kernel_manager_factory is the constructor for the KernelManager
  164. # subclass we are using. It can be configured as any Configurable,
  165. # including things like its transport and ip.
  166. constructor_kwargs = {}
  167. if self.kernel_spec_manager:
  168. constructor_kwargs["kernel_spec_manager"] = self.kernel_spec_manager
  169. km = self.kernel_manager_factory(
  170. connection_file=os.path.join(self.connection_dir, "kernel-%s.json" % kernel_id),
  171. parent=self,
  172. log=self.log,
  173. kernel_name=kernel_name,
  174. **constructor_kwargs,
  175. )
  176. return km, kernel_name, kernel_id
  177. def update_env(self, *, kernel_id: str, env: t.Dict[str, str]) -> None:
  178. """
  179. Allow to update the environment of the given kernel.
  180. Forward the update env request to the corresponding kernel.
  181. .. version-added: 8.5
  182. """
  183. if kernel_id in self:
  184. self._kernels[kernel_id].update_env(env=env)
  185. async def _add_kernel_when_ready(
  186. self, kernel_id: str, km: KernelManager, kernel_awaitable: t.Awaitable
  187. ) -> None:
  188. try:
  189. await kernel_awaitable
  190. self._kernels[kernel_id] = km
  191. self._pending_kernels.pop(kernel_id, None)
  192. except Exception as e:
  193. self.log.exception(e)
  194. async def _remove_kernel_when_ready(
  195. self, kernel_id: str, kernel_awaitable: t.Awaitable
  196. ) -> None:
  197. try:
  198. await kernel_awaitable
  199. self.remove_kernel(kernel_id)
  200. self._pending_kernels.pop(kernel_id, None)
  201. except Exception as e:
  202. self.log.exception(e)
  203. def _using_pending_kernels(self) -> bool:
  204. """Returns a boolean; a clearer method for determining if
  205. this multikernelmanager is using pending kernels or not
  206. """
  207. return getattr(self, "use_pending_kernels", False)
  208. async def _async_start_kernel(self, *, kernel_name: str | None = None, **kwargs: t.Any) -> str:
  209. """Start a new kernel.
  210. The caller can pick a kernel_id by passing one in as a keyword arg,
  211. otherwise one will be generated using new_kernel_id().
  212. The kernel ID for the newly started kernel is returned.
  213. """
  214. km, kernel_name, kernel_id = self.pre_start_kernel(kernel_name, kwargs)
  215. if not isinstance(km, KernelManager):
  216. self.log.warning( # type:ignore[unreachable]
  217. f"Kernel manager class ({self.kernel_manager_class.__class__}) is not an instance of 'KernelManager'!"
  218. )
  219. kwargs["kernel_id"] = kernel_id # Make kernel_id available to manager and provisioner
  220. starter = ensure_async(km.start_kernel(**kwargs))
  221. task = asyncio.create_task(self._add_kernel_when_ready(kernel_id, km, starter))
  222. self._pending_kernels[kernel_id] = task
  223. # Handling a Pending Kernel
  224. if self._using_pending_kernels():
  225. # If using pending kernels, do not block
  226. # on the kernel start.
  227. self._kernels[kernel_id] = km
  228. else:
  229. await task
  230. # raise an exception if one occurred during kernel startup.
  231. if km.ready.exception():
  232. raise km.ready.exception() # type: ignore[misc]
  233. return kernel_id
  234. start_kernel = run_sync(_async_start_kernel)
  235. async def _async_shutdown_kernel(
  236. self,
  237. kernel_id: str,
  238. now: bool | None = False,
  239. restart: bool | None = False,
  240. ) -> None:
  241. """Shutdown a kernel by its kernel uuid.
  242. Parameters
  243. ==========
  244. kernel_id : uuid
  245. The id of the kernel to shutdown.
  246. now : bool
  247. Should the kernel be shutdown forcibly using a signal.
  248. restart : bool
  249. Will the kernel be restarted?
  250. """
  251. self.log.info("Kernel shutdown: %s", kernel_id)
  252. # If the kernel is still starting, wait for it to be ready.
  253. if kernel_id in self._pending_kernels:
  254. task = self._pending_kernels[kernel_id]
  255. try:
  256. await task
  257. km = self.get_kernel(kernel_id)
  258. await t.cast(asyncio.Future, km.ready)
  259. except asyncio.CancelledError:
  260. pass
  261. except Exception:
  262. self.remove_kernel(kernel_id)
  263. return
  264. km = self.get_kernel(kernel_id)
  265. # If a pending kernel raised an exception, remove it.
  266. if not km.ready.cancelled() and km.ready.exception():
  267. self.remove_kernel(kernel_id)
  268. return
  269. stopper = ensure_async(km.shutdown_kernel(now, restart))
  270. fut = asyncio.ensure_future(self._remove_kernel_when_ready(kernel_id, stopper))
  271. self._pending_kernels[kernel_id] = fut
  272. # Await the kernel if not using pending kernels.
  273. if not self._using_pending_kernels():
  274. await fut
  275. # raise an exception if one occurred during kernel shutdown.
  276. if km.ready.exception():
  277. raise km.ready.exception() # type: ignore[misc]
  278. shutdown_kernel = run_sync(_async_shutdown_kernel)
  279. @kernel_method
  280. def request_shutdown(self, kernel_id: str, restart: bool | None = False) -> None:
  281. """Ask a kernel to shut down by its kernel uuid"""
  282. @kernel_method
  283. def finish_shutdown(
  284. self,
  285. kernel_id: str,
  286. waittime: float | None = None,
  287. pollinterval: float | None = 0.1,
  288. ) -> None:
  289. """Wait for a kernel to finish shutting down, and kill it if it doesn't"""
  290. self.log.info("Kernel shutdown: %s", kernel_id)
  291. @kernel_method
  292. def cleanup_resources(self, kernel_id: str, restart: bool = False) -> None:
  293. """Clean up a kernel's resources"""
  294. def remove_kernel(self, kernel_id: str) -> KernelManager:
  295. """remove a kernel from our mapping.
  296. Mainly so that a kernel can be removed if it is already dead,
  297. without having to call shutdown_kernel.
  298. The kernel object is returned, or `None` if not found.
  299. """
  300. return self._kernels.pop(kernel_id, None)
  301. async def _async_shutdown_all(self, now: bool = False) -> None:
  302. """Shutdown all kernels."""
  303. kids = self.list_kernel_ids()
  304. kids += list(self._pending_kernels)
  305. kms = list(self._kernels.values())
  306. futs = [self._async_shutdown_kernel(kid, now=now) for kid in set(kids)]
  307. await asyncio.gather(*futs)
  308. # If using pending kernels, the kernels will not have been fully shut down.
  309. if self._using_pending_kernels():
  310. for km in kms:
  311. try:
  312. await km.ready
  313. except asyncio.CancelledError:
  314. self._pending_kernels[km.kernel_id].cancel()
  315. except Exception:
  316. # Will have been logged in _add_kernel_when_ready
  317. pass
  318. shutdown_all = run_sync(_async_shutdown_all)
  319. def interrupt_kernel(self, kernel_id: str) -> None:
  320. """Interrupt (SIGINT) the kernel by its uuid.
  321. Parameters
  322. ==========
  323. kernel_id : uuid
  324. The id of the kernel to interrupt.
  325. """
  326. kernel = self.get_kernel(kernel_id)
  327. if not kernel.ready.done():
  328. msg = "Kernel is in a pending state. Cannot interrupt."
  329. raise RuntimeError(msg)
  330. out = kernel.interrupt_kernel()
  331. self.log.info("Kernel interrupted: %s", kernel_id)
  332. return out
  333. @kernel_method
  334. def signal_kernel(self, kernel_id: str, signum: int) -> None:
  335. """Sends a signal to the kernel by its uuid.
  336. Note that since only SIGTERM is supported on Windows, this function
  337. is only useful on Unix systems.
  338. Parameters
  339. ==========
  340. kernel_id : uuid
  341. The id of the kernel to signal.
  342. signum : int
  343. Signal number to send kernel.
  344. """
  345. self.log.info("Signaled Kernel %s with %s", kernel_id, signum)
  346. async def _async_restart_kernel(self, kernel_id: str, now: bool = False) -> None:
  347. """Restart a kernel by its uuid, keeping the same ports.
  348. Parameters
  349. ==========
  350. kernel_id : uuid
  351. The id of the kernel to interrupt.
  352. now : bool, optional
  353. If True, the kernel is forcefully restarted *immediately*, without
  354. having a chance to do any cleanup action. Otherwise the kernel is
  355. given 1s to clean up before a forceful restart is issued.
  356. In all cases the kernel is restarted, the only difference is whether
  357. it is given a chance to perform a clean shutdown or not.
  358. """
  359. kernel = self.get_kernel(kernel_id)
  360. if self._using_pending_kernels() and not kernel.ready.done():
  361. msg = "Kernel is in a pending state. Cannot restart."
  362. raise RuntimeError(msg)
  363. await ensure_async(kernel.restart_kernel(now=now))
  364. self.log.info("Kernel restarted: %s", kernel_id)
  365. restart_kernel = run_sync(_async_restart_kernel)
  366. @kernel_method
  367. def is_alive(self, kernel_id: str) -> bool: # type:ignore[empty-body]
  368. """Is the kernel alive.
  369. This calls KernelManager.is_alive() which calls Popen.poll on the
  370. actual kernel subprocess.
  371. Parameters
  372. ==========
  373. kernel_id : uuid
  374. The id of the kernel.
  375. """
  376. def _check_kernel_id(self, kernel_id: str) -> None:
  377. """check that a kernel id is valid"""
  378. if kernel_id not in self:
  379. raise KeyError("Kernel with id not found: %s" % kernel_id)
  380. def get_kernel(self, kernel_id: str) -> KernelManager:
  381. """Get the single KernelManager object for a kernel by its uuid.
  382. Parameters
  383. ==========
  384. kernel_id : uuid
  385. The id of the kernel.
  386. """
  387. self._check_kernel_id(kernel_id)
  388. return self._kernels[kernel_id]
  389. @kernel_method
  390. def add_restart_callback(
  391. self, kernel_id: str, callback: t.Callable, event: str = "restart"
  392. ) -> None:
  393. """add a callback for the KernelRestarter"""
  394. @kernel_method
  395. def remove_restart_callback(
  396. self, kernel_id: str, callback: t.Callable, event: str = "restart"
  397. ) -> None:
  398. """remove a callback for the KernelRestarter"""
  399. @kernel_method
  400. def get_connection_info(self, kernel_id: str) -> dict[str, t.Any]: # type:ignore[empty-body]
  401. """Return a dictionary of connection data for a kernel.
  402. Parameters
  403. ==========
  404. kernel_id : uuid
  405. The id of the kernel.
  406. Returns
  407. =======
  408. connection_dict : dict
  409. A dict of the information needed to connect to a kernel.
  410. This includes the ip address and the integer port
  411. numbers of the different channels (stdin_port, iopub_port,
  412. shell_port, hb_port).
  413. """
  414. @kernel_method
  415. def connect_iopub( # type:ignore[empty-body]
  416. self, kernel_id: str, identity: bytes | None = None
  417. ) -> socket.socket:
  418. """Return a zmq Socket connected to the iopub channel.
  419. Parameters
  420. ==========
  421. kernel_id : uuid
  422. The id of the kernel
  423. identity : bytes (optional)
  424. The zmq identity of the socket
  425. Returns
  426. =======
  427. stream : zmq Socket or ZMQStream
  428. """
  429. @kernel_method
  430. def connect_shell( # type:ignore[empty-body]
  431. self, kernel_id: str, identity: bytes | None = None
  432. ) -> socket.socket:
  433. """Return a zmq Socket connected to the shell channel.
  434. Parameters
  435. ==========
  436. kernel_id : uuid
  437. The id of the kernel
  438. identity : bytes (optional)
  439. The zmq identity of the socket
  440. Returns
  441. =======
  442. stream : zmq Socket or ZMQStream
  443. """
  444. @kernel_method
  445. def connect_control( # type:ignore[empty-body]
  446. self, kernel_id: str, identity: bytes | None = None
  447. ) -> socket.socket:
  448. """Return a zmq Socket connected to the control channel.
  449. Parameters
  450. ==========
  451. kernel_id : uuid
  452. The id of the kernel
  453. identity : bytes (optional)
  454. The zmq identity of the socket
  455. Returns
  456. =======
  457. stream : zmq Socket or ZMQStream
  458. """
  459. @kernel_method
  460. def connect_stdin( # type:ignore[empty-body]
  461. self, kernel_id: str, identity: bytes | None = None
  462. ) -> socket.socket:
  463. """Return a zmq Socket connected to the stdin channel.
  464. Parameters
  465. ==========
  466. kernel_id : uuid
  467. The id of the kernel
  468. identity : bytes (optional)
  469. The zmq identity of the socket
  470. Returns
  471. =======
  472. stream : zmq Socket or ZMQStream
  473. """
  474. @kernel_method
  475. def connect_hb( # type:ignore[empty-body]
  476. self, kernel_id: str, identity: bytes | None = None
  477. ) -> socket.socket:
  478. """Return a zmq Socket connected to the hb channel.
  479. Parameters
  480. ==========
  481. kernel_id : uuid
  482. The id of the kernel
  483. identity : bytes (optional)
  484. The zmq identity of the socket
  485. Returns
  486. =======
  487. stream : zmq Socket or ZMQStream
  488. """
  489. def new_kernel_id(self, **kwargs: t.Any) -> str:
  490. """
  491. Returns the id to associate with the kernel for this request. Subclasses may override
  492. this method to substitute other sources of kernel ids.
  493. :param kwargs:
  494. :return: string-ized version 4 uuid
  495. """
  496. return str(uuid.uuid4())
  497. class AsyncMultiKernelManager(MultiKernelManager):
  498. kernel_manager_class = DottedObjectName(
  499. "jupyter_client.ioloop.AsyncIOLoopKernelManager",
  500. config=True,
  501. help="""The kernel manager class. This is configurable to allow
  502. subclassing of the AsyncKernelManager for customized behavior.
  503. """,
  504. )
  505. use_pending_kernels = Bool(
  506. False,
  507. help="""Whether to make kernels available before the process has started. The
  508. kernel has a `.ready` future which can be awaited before connecting""",
  509. ).tag(config=True)
  510. context = Instance("zmq.asyncio.Context")
  511. @default("context")
  512. def _context_default(self) -> zmq.asyncio.Context:
  513. self._created_context = True
  514. return zmq.asyncio.Context()
  515. start_kernel: t.Callable[..., t.Awaitable] = MultiKernelManager._async_start_kernel # type:ignore[assignment]
  516. restart_kernel: t.Callable[..., t.Awaitable] = MultiKernelManager._async_restart_kernel # type:ignore[assignment]
  517. shutdown_kernel: t.Callable[..., t.Awaitable] = MultiKernelManager._async_shutdown_kernel # type:ignore[assignment]
  518. shutdown_all: t.Callable[..., t.Awaitable] = MultiKernelManager._async_shutdown_all # type:ignore[assignment]