managers.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. """Kernel gateway managers."""
  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 datetime
  7. import json
  8. import os
  9. from queue import Empty, Queue
  10. from threading import Thread
  11. from time import monotonic
  12. from typing import TYPE_CHECKING, Any, Optional, cast
  13. import websocket
  14. from jupyter_client.asynchronous.client import AsyncKernelClient
  15. from jupyter_client.clientabc import KernelClientABC
  16. from jupyter_client.kernelspec import KernelSpecManager
  17. from jupyter_client.managerabc import KernelManagerABC
  18. from jupyter_core.utils import ensure_async
  19. from tornado import web
  20. from tornado.escape import json_decode, json_encode, url_escape, utf8
  21. from traitlets import DottedObjectName, Instance, Type, default
  22. from .._tz import UTC, utcnow
  23. from ..services.kernels.kernelmanager import (
  24. AsyncMappingKernelManager,
  25. ServerKernelManager,
  26. emit_kernel_action_event,
  27. )
  28. from ..services.sessions.sessionmanager import SessionManager
  29. from ..utils import url_path_join
  30. from .gateway_client import GatewayClient, gateway_request
  31. if TYPE_CHECKING:
  32. from logging import Logger
  33. class GatewayMappingKernelManager(AsyncMappingKernelManager):
  34. """Kernel manager that supports remote kernels hosted by Jupyter Kernel or Enterprise Gateway."""
  35. # We'll maintain our own set of kernel ids
  36. _kernels: dict[str, GatewayKernelManager] = {} # type:ignore[assignment]
  37. @default("kernel_manager_class")
  38. def _default_kernel_manager_class(self):
  39. return "jupyter_server.gateway.managers.GatewayKernelManager"
  40. @default("shared_context")
  41. def _default_shared_context(self):
  42. return False # no need to share zmq contexts
  43. def __init__(self, **kwargs):
  44. """Initialize a gateway mapping kernel manager."""
  45. super().__init__(**kwargs)
  46. self.kernels_url = url_path_join(
  47. GatewayClient.instance().url or "", GatewayClient.instance().kernels_endpoint or ""
  48. )
  49. def remove_kernel(self, kernel_id):
  50. """Complete override since we want to be more tolerant of missing keys"""
  51. try:
  52. return self._kernels.pop(kernel_id)
  53. except KeyError:
  54. pass
  55. async def start_kernel(self, *, kernel_id=None, path=None, **kwargs):
  56. """Start a kernel for a session and return its kernel_id.
  57. Parameters
  58. ----------
  59. kernel_id : uuid
  60. The uuid to associate the new kernel with. If this
  61. is not None, this kernel will be persistent whenever it is
  62. requested.
  63. path : API path
  64. The API path (unicode, '/' delimited) for the cwd.
  65. Will be transformed to an OS path relative to root_dir.
  66. """
  67. self.log.info(f"Request start kernel: kernel_id={kernel_id}, path='{path}'")
  68. if kernel_id is None and path is not None:
  69. kwargs["cwd"] = self.cwd_for_path(path)
  70. km = self.kernel_manager_factory(parent=self, log=self.log)
  71. await km.start_kernel(kernel_id=kernel_id, **kwargs)
  72. kernel_id = km.kernel_id
  73. self._kernels[kernel_id] = km
  74. # Initialize culling if not already
  75. if not self._initialized_culler:
  76. self.initialize_culler()
  77. return kernel_id
  78. async def kernel_model(self, kernel_id):
  79. """Return a dictionary of kernel information described in the
  80. JSON standard model.
  81. Parameters
  82. ----------
  83. kernel_id : uuid
  84. The uuid of the kernel.
  85. """
  86. model = None
  87. km = self.get_kernel(str(kernel_id))
  88. if km: # type:ignore[truthy-bool]
  89. model = km.kernel # type:ignore[attr-defined]
  90. return model
  91. async def list_kernels(self, **kwargs):
  92. """Get a list of running kernels from the Gateway server.
  93. We'll use this opportunity to refresh the models in each of
  94. the kernels we're managing.
  95. """
  96. self.log.debug(f"Request list kernels: {self.kernels_url}")
  97. response = await gateway_request(self.kernels_url, method="GET")
  98. kernels = json_decode(response.body)
  99. # Refresh our models to those we know about, and filter
  100. # the return value with only our kernels.
  101. kernel_models = {}
  102. for model in kernels:
  103. kid = model["id"]
  104. if kid in self._kernels:
  105. await self._kernels[kid].refresh_model(model)
  106. kernel_models[kid] = model
  107. # Remove any of our kernels that may have been culled on the gateway server
  108. our_kernels = self._kernels.copy()
  109. culled_ids = []
  110. for kid in our_kernels:
  111. if kid not in kernel_models:
  112. # The upstream kernel was not reported in the list of kernels.
  113. self.log.warning(
  114. f"Kernel {kid} not present in the list of kernels - possibly culled on Gateway server."
  115. )
  116. try:
  117. # Try to directly refresh the model for this specific kernel in case
  118. # the upstream list of kernels was erroneously incomplete.
  119. #
  120. # That might happen if the case of a proxy that manages multiple
  121. # backends where there could be transient connectivity issues with
  122. # a single backend.
  123. #
  124. # Alternatively, it could happen if there is simply a bug in the
  125. # upstream gateway server.
  126. #
  127. # Either way, including this check improves our reliability in the
  128. # face of such scenarios.
  129. model = await self._kernels[kid].refresh_model()
  130. except web.HTTPError:
  131. model = None
  132. if model:
  133. kernel_models[kid] = model
  134. else:
  135. self.log.warning(
  136. f"Kernel {kid} no longer active - probably culled on Gateway server."
  137. )
  138. self._kernels.pop(kid, None)
  139. culled_ids.append(kid) # TODO: Figure out what do with these.
  140. return list(kernel_models.values())
  141. async def shutdown_kernel(self, kernel_id, now=False, restart=False):
  142. """Shutdown a kernel by its kernel uuid.
  143. Parameters
  144. ==========
  145. kernel_id : uuid
  146. The id of the kernel to shutdown.
  147. now : bool
  148. Shutdown the kernel immediately (True) or gracefully (False)
  149. restart : bool
  150. The purpose of this shutdown is to restart the kernel (True)
  151. """
  152. km = self.get_kernel(kernel_id)
  153. await ensure_async(km.shutdown_kernel(now=now, restart=restart))
  154. self.remove_kernel(kernel_id)
  155. async def restart_kernel(self, kernel_id, now=False, **kwargs):
  156. """Restart a kernel by its kernel uuid.
  157. Parameters
  158. ==========
  159. kernel_id : uuid
  160. The id of the kernel to restart.
  161. """
  162. km = self.get_kernel(kernel_id)
  163. await ensure_async(km.restart_kernel(now=now, **kwargs))
  164. async def interrupt_kernel(self, kernel_id, **kwargs):
  165. """Interrupt a kernel by its kernel uuid.
  166. Parameters
  167. ==========
  168. kernel_id : uuid
  169. The id of the kernel to interrupt.
  170. """
  171. km = self.get_kernel(kernel_id)
  172. await ensure_async(km.interrupt_kernel())
  173. async def shutdown_all(self, now=False):
  174. """Shutdown all kernels."""
  175. kids = list(self._kernels)
  176. for kernel_id in kids:
  177. km = self.get_kernel(kernel_id)
  178. await ensure_async(km.shutdown_kernel(now=now))
  179. self.remove_kernel(kernel_id)
  180. async def cull_kernels(self):
  181. """Override cull_kernels, so we can be sure their state is current."""
  182. await self.list_kernels()
  183. await super().cull_kernels()
  184. class GatewayKernelSpecManager(KernelSpecManager):
  185. """A gateway kernel spec manager."""
  186. def __init__(self, **kwargs):
  187. """Initialize a gateway kernel spec manager."""
  188. super().__init__(**kwargs)
  189. base_endpoint = url_path_join(
  190. GatewayClient.instance().url or "", GatewayClient.instance().kernelspecs_endpoint
  191. )
  192. self.base_endpoint = GatewayKernelSpecManager._get_endpoint_for_user_filter(base_endpoint)
  193. self.base_resource_endpoint = url_path_join(
  194. GatewayClient.instance().url or "",
  195. GatewayClient.instance().kernelspecs_resource_endpoint,
  196. )
  197. @staticmethod
  198. def _get_endpoint_for_user_filter(default_endpoint):
  199. """Get the endpoint for a user filter."""
  200. kernel_user = os.environ.get("KERNEL_USERNAME")
  201. if kernel_user:
  202. return f"{default_endpoint}?user={kernel_user}"
  203. return default_endpoint
  204. def _replace_path_kernelspec_resources(self, kernel_specs):
  205. """Helper method that replaces any gateway base_url with the server's base_url
  206. This enables clients to properly route through jupyter_server to a gateway
  207. for kernel resources such as logo files
  208. """
  209. if not self.parent:
  210. return {}
  211. kernelspecs = kernel_specs["kernelspecs"]
  212. for kernel_name in kernelspecs:
  213. resources = kernelspecs[kernel_name]["resources"]
  214. for resource_name in resources:
  215. original_path = resources[resource_name]
  216. split_eg_base_url = str.rsplit(original_path, sep="/kernelspecs/", maxsplit=1)
  217. if len(split_eg_base_url) > 1:
  218. new_path = url_path_join(
  219. self.parent.base_url, "kernelspecs", split_eg_base_url[1]
  220. )
  221. kernel_specs["kernelspecs"][kernel_name]["resources"][resource_name] = new_path
  222. if original_path != new_path:
  223. self.log.debug(
  224. f"Replaced original kernel resource path {original_path} with new "
  225. f"path {kernel_specs['kernelspecs'][kernel_name]['resources'][resource_name]}"
  226. )
  227. return kernel_specs
  228. def _get_kernelspecs_endpoint_url(self, kernel_name=None):
  229. """Builds a url for the kernels endpoint
  230. Parameters
  231. ----------
  232. kernel_name : kernel name (optional)
  233. """
  234. if kernel_name:
  235. return url_path_join(self.base_endpoint, url_escape(kernel_name))
  236. return self.base_endpoint
  237. async def get_all_specs(self):
  238. """Get all of the kernel specs for the gateway."""
  239. fetched_kspecs = await self.list_kernel_specs()
  240. # get the default kernel name and compare to that of this server.
  241. # If different log a warning and reset the default. However, the
  242. # caller of this method will still return this server's value until
  243. # the next fetch of kernelspecs - at which time they'll match.
  244. if not self.parent:
  245. return {}
  246. km = self.parent.kernel_manager
  247. remote_default_kernel_name = fetched_kspecs.get("default")
  248. if remote_default_kernel_name != km.default_kernel_name:
  249. self.log.info(
  250. f"Default kernel name on Gateway server ({remote_default_kernel_name}) differs from "
  251. f"Notebook server ({km.default_kernel_name}). Updating to Gateway server's value."
  252. )
  253. km.default_kernel_name = remote_default_kernel_name
  254. remote_kspecs = fetched_kspecs.get("kernelspecs")
  255. return remote_kspecs
  256. async def list_kernel_specs(self):
  257. """Get a list of kernel specs."""
  258. kernel_spec_url = self._get_kernelspecs_endpoint_url()
  259. self.log.debug(f"Request list kernel specs at: {kernel_spec_url}")
  260. response = await gateway_request(kernel_spec_url, method="GET")
  261. kernel_specs = json_decode(response.body)
  262. kernel_specs = self._replace_path_kernelspec_resources(kernel_specs)
  263. return kernel_specs
  264. async def get_kernel_spec(self, kernel_name, **kwargs):
  265. """Get kernel spec for kernel_name.
  266. Parameters
  267. ----------
  268. kernel_name : str
  269. The name of the kernel.
  270. """
  271. kernel_spec_url = self._get_kernelspecs_endpoint_url(kernel_name=str(kernel_name))
  272. self.log.debug(f"Request kernel spec at: {kernel_spec_url}")
  273. try:
  274. response = await gateway_request(kernel_spec_url, method="GET")
  275. except web.HTTPError as error:
  276. if error.status_code == 404:
  277. # Convert not found to KeyError since that's what the Notebook handler expects
  278. # message is not used, but might as well make it useful for troubleshooting
  279. msg = f"kernelspec {kernel_name} not found on Gateway server at: {GatewayClient.instance().url}"
  280. raise KeyError(msg) from None
  281. else:
  282. raise
  283. else:
  284. kernel_spec = json_decode(response.body)
  285. return kernel_spec
  286. async def get_kernel_spec_resource(self, kernel_name, path):
  287. """Get kernel spec for kernel_name.
  288. Parameters
  289. ----------
  290. kernel_name : str
  291. The name of the kernel.
  292. path : str
  293. The name of the desired resource
  294. """
  295. kernel_spec_resource_url = url_path_join(
  296. self.base_resource_endpoint, str(kernel_name), str(path)
  297. )
  298. self.log.debug(f"Request kernel spec resource '{path}' at: {kernel_spec_resource_url}")
  299. try:
  300. response = await gateway_request(kernel_spec_resource_url, method="GET")
  301. except web.HTTPError as error:
  302. if error.status_code == 404:
  303. kernel_spec_resource = None
  304. else:
  305. raise
  306. else:
  307. kernel_spec_resource = response.body
  308. return kernel_spec_resource
  309. class GatewaySessionManager(SessionManager):
  310. """A gateway session manager."""
  311. kernel_manager = Instance("jupyter_server.gateway.managers.GatewayMappingKernelManager")
  312. async def kernel_culled(self, kernel_id: str) -> bool: # typing: ignore
  313. """Checks if the kernel is still considered alive and returns true if it's not found."""
  314. km: Optional[GatewayKernelManager] = None
  315. try:
  316. # Since we keep the models up-to-date via client polling, use that state to determine
  317. # if this kernel no longer exists on the gateway server rather than perform a redundant
  318. # fetch operation - especially since this is called at approximately the same interval.
  319. # This has the effect of reducing GET /api/kernels requests against the gateway server
  320. # by 50%!
  321. # Note that should the redundant polling be consolidated, or replaced with an event-based
  322. # notification model, this will need to be revisited.
  323. km = self.kernel_manager.get_kernel(kernel_id)
  324. except Exception:
  325. # Let exceptions here reflect culled kernel
  326. pass
  327. return km is None
  328. class GatewayKernelManager(ServerKernelManager):
  329. """Manages a single kernel remotely via a Gateway Server."""
  330. kernel_id: Optional[str] = None # type:ignore[assignment]
  331. kernel = None
  332. @default("cache_ports")
  333. def _default_cache_ports(self):
  334. return False # no need to cache ports here
  335. def __init__(self, **kwargs):
  336. """Initialize the gateway kernel manager."""
  337. super().__init__(**kwargs)
  338. self.kernels_url = url_path_join(
  339. GatewayClient.instance().url or "", GatewayClient.instance().kernels_endpoint
  340. )
  341. self.kernel_url: str
  342. self.kernel = self.kernel_id = None
  343. # simulate busy/activity markers:
  344. self.execution_state = "starting"
  345. self.last_activity = utcnow()
  346. @property
  347. def has_kernel(self):
  348. """Has a kernel been started that we are managing."""
  349. return self.kernel is not None
  350. client_class = DottedObjectName("jupyter_server.gateway.managers.GatewayKernelClient")
  351. client_factory = Type(klass="jupyter_server.gateway.managers.GatewayKernelClient")
  352. # --------------------------------------------------------------------------
  353. # create a Client connected to our Kernel
  354. # --------------------------------------------------------------------------
  355. def client(self, **kwargs):
  356. """Create a client configured to connect to our kernel"""
  357. kw: dict[str, Any] = {}
  358. kw.update(self.get_connection_info(session=True))
  359. kw.update(
  360. {
  361. "connection_file": self.connection_file,
  362. "parent": self,
  363. }
  364. )
  365. kw["kernel_id"] = self.kernel_id
  366. # add kwargs last, for manual overrides
  367. kw.update(kwargs)
  368. return self.client_factory(**kw)
  369. async def refresh_model(self, model=None):
  370. """Refresh the kernel model.
  371. Parameters
  372. ----------
  373. model : dict
  374. The model from which to refresh the kernel. If None, the kernel
  375. model is fetched from the Gateway server.
  376. """
  377. if model is None:
  378. self.log.debug("Request kernel at: %s" % self.kernel_url)
  379. try:
  380. response = await gateway_request(self.kernel_url, method="GET")
  381. except web.HTTPError as error:
  382. if error.status_code == 404:
  383. self.log.warning("Kernel not found at: %s" % self.kernel_url)
  384. model = None
  385. else:
  386. raise
  387. else:
  388. model = json_decode(response.body)
  389. self.log.debug("Kernel retrieved: %s" % model)
  390. if model: # Update activity markers
  391. self.last_activity = datetime.datetime.strptime(
  392. model["last_activity"], "%Y-%m-%dT%H:%M:%S.%fZ"
  393. ).replace(tzinfo=UTC)
  394. self.execution_state = model["execution_state"]
  395. if isinstance(self.parent, AsyncMappingKernelManager):
  396. # Update connections only if there's a mapping kernel manager parent for
  397. # this kernel manager. The current kernel manager instance may not have
  398. # a parent instance if, say, a server extension is using another application
  399. # (e.g., papermill) that uses a KernelManager instance directly.
  400. self.parent._kernel_connections[self.kernel_id] = int(model["connections"]) # type:ignore[index]
  401. self.kernel = model
  402. return model
  403. # --------------------------------------------------------------------------
  404. # Kernel management
  405. # --------------------------------------------------------------------------
  406. @emit_kernel_action_event(
  407. success_msg="Kernel {kernel_id} was started.",
  408. )
  409. async def start_kernel(self, **kwargs):
  410. """Starts a kernel via HTTP in an asynchronous manner.
  411. Parameters
  412. ----------
  413. `**kwargs` : optional
  414. keyword arguments that are passed down to build the kernel_cmd
  415. and launching the kernel (e.g. Popen kwargs).
  416. """
  417. kernel_id = kwargs.get("kernel_id")
  418. if kernel_id is None:
  419. kernel_name = kwargs.get("kernel_name", "python3")
  420. self.log.debug("Request new kernel at: %s" % self.kernels_url)
  421. # Let KERNEL_USERNAME take precedent over http_user config option.
  422. if os.environ.get("KERNEL_USERNAME") is None and GatewayClient.instance().http_user:
  423. os.environ["KERNEL_USERNAME"] = GatewayClient.instance().http_user or ""
  424. payload_envs = os.environ.copy()
  425. payload_envs.update(kwargs.get("env", {})) # Add any env entries in this request
  426. # Build the actual env payload, filtering allowed_envs and those starting with 'KERNEL_'
  427. kernel_env = {
  428. k: v
  429. for (k, v) in payload_envs.items()
  430. if k.startswith("KERNEL_") or k in GatewayClient.instance().allowed_envs.split(",")
  431. }
  432. # Convey the full path to where this notebook file is located.
  433. if kwargs.get("cwd") is not None and kernel_env.get("KERNEL_WORKING_DIR") is None:
  434. kernel_env["KERNEL_WORKING_DIR"] = kwargs["cwd"]
  435. json_body = json_encode({"name": kernel_name, "env": kernel_env})
  436. response = await gateway_request(
  437. self.kernels_url,
  438. method="POST",
  439. headers={"Content-Type": "application/json"},
  440. body=json_body,
  441. )
  442. self.kernel = json_decode(response.body)
  443. self.kernel_id = self.kernel["id"]
  444. self.kernel_url = url_path_join(self.kernels_url, url_escape(str(self.kernel_id)))
  445. self.log.info(f"GatewayKernelManager started kernel: {self.kernel_id}, args: {kwargs}")
  446. else:
  447. self.kernel_id = kernel_id
  448. self.kernel_url = url_path_join(self.kernels_url, url_escape(str(self.kernel_id)))
  449. self.kernel = await self.refresh_model()
  450. self.log.info(f"GatewayKernelManager using existing kernel: {self.kernel_id}")
  451. @emit_kernel_action_event(
  452. success_msg="Kernel {kernel_id} was shutdown.",
  453. )
  454. async def shutdown_kernel(self, now=False, restart=False):
  455. """Attempts to stop the kernel process cleanly via HTTP."""
  456. if self.has_kernel:
  457. self.log.debug("Request shutdown kernel at: %s", self.kernel_url)
  458. try:
  459. response = await gateway_request(self.kernel_url, method="DELETE")
  460. self.log.debug("Shutdown kernel response: %d %s", response.code, response.reason)
  461. except web.HTTPError as error:
  462. if error.status_code == 404:
  463. self.log.debug("Shutdown kernel response: kernel not found (ignored)")
  464. else:
  465. raise
  466. @emit_kernel_action_event(
  467. success_msg="Kernel {kernel_id} was restarted.",
  468. )
  469. async def restart_kernel(self, **kw):
  470. """Restarts a kernel via HTTP."""
  471. if self.has_kernel:
  472. assert self.kernel_url is not None
  473. kernel_url = self.kernel_url + "/restart"
  474. self.log.debug("Request restart kernel at: %s", kernel_url)
  475. response = await gateway_request(
  476. kernel_url,
  477. method="POST",
  478. headers={"Content-Type": "application/json"},
  479. body=json_encode({}),
  480. )
  481. self.log.debug("Restart kernel response: %d %s", response.code, response.reason)
  482. @emit_kernel_action_event(
  483. success_msg="Kernel {kernel_id} was interrupted.",
  484. )
  485. async def interrupt_kernel(self):
  486. """Interrupts the kernel via an HTTP request."""
  487. if self.has_kernel:
  488. assert self.kernel_url is not None
  489. kernel_url = self.kernel_url + "/interrupt"
  490. self.log.debug("Request interrupt kernel at: %s", kernel_url)
  491. response = await gateway_request(
  492. kernel_url,
  493. method="POST",
  494. headers={"Content-Type": "application/json"},
  495. body=json_encode({}),
  496. )
  497. self.log.debug("Interrupt kernel response: %d %s", response.code, response.reason)
  498. async def is_alive(self):
  499. """Is the kernel process still running?"""
  500. if self.has_kernel:
  501. # Go ahead and issue a request to get the kernel
  502. self.kernel = await self.refresh_model()
  503. self.log.debug(f"The kernel: {self.kernel} is alive.")
  504. return True
  505. else: # we don't have a kernel
  506. self.log.debug(f"The kernel: {self.kernel} no longer exists.")
  507. return False
  508. def cleanup_resources(self, restart=False):
  509. """Clean up resources when the kernel is shut down"""
  510. KernelManagerABC.register(GatewayKernelManager)
  511. class ChannelQueue(Queue): # type:ignore[type-arg]
  512. """A queue for a named channel."""
  513. channel_name: Optional[str] = None
  514. response_router_finished: bool
  515. def __init__(self, channel_name: str, channel_socket: websocket.WebSocket, log: Logger):
  516. """Initialize a channel queue."""
  517. super().__init__()
  518. self.channel_name = channel_name
  519. self.channel_socket = channel_socket
  520. self.log = log
  521. self.response_router_finished = False
  522. async def _async_get(self, timeout=None):
  523. """Asynchronously get from the queue."""
  524. if timeout is None:
  525. timeout = float("inf")
  526. elif timeout < 0:
  527. msg = "'timeout' must be a non-negative number"
  528. raise ValueError(msg)
  529. end_time = monotonic() + timeout
  530. while True:
  531. try:
  532. return self.get(block=False)
  533. except Empty:
  534. if self.response_router_finished:
  535. msg = "Response router had finished"
  536. raise RuntimeError(msg) from None
  537. if monotonic() > end_time:
  538. raise
  539. await asyncio.sleep(0)
  540. async def get_msg(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
  541. """Get a message from the queue."""
  542. timeout = kwargs.get("timeout", 1)
  543. msg = await self._async_get(timeout=timeout)
  544. self.log.debug(
  545. "Received message on channel: %s, msg_id: %s, msg_type: %s",
  546. self.channel_name,
  547. msg["msg_id"],
  548. msg["msg_type"] if msg else "null",
  549. )
  550. self.task_done()
  551. return cast("dict[str, Any]", msg)
  552. def send(self, msg: dict[str, Any]) -> None:
  553. """Send a message to the queue."""
  554. message = json.dumps(msg, default=ChannelQueue.serialize_datetime).replace("</", "<\\/")
  555. self.log.debug(
  556. "Sending message on channel: %s, msg_id: %s, msg_type: %s",
  557. self.channel_name,
  558. msg["msg_id"],
  559. msg["msg_type"] if msg else "null",
  560. )
  561. self.channel_socket.send(message)
  562. @staticmethod
  563. def serialize_datetime(dt):
  564. """Serialize a datetime object."""
  565. if isinstance(dt, datetime.datetime):
  566. return dt.timestamp()
  567. return None
  568. def start(self) -> None:
  569. """Start the queue."""
  570. def stop(self) -> None:
  571. """Stop the queue."""
  572. if not self.empty():
  573. # If unprocessed messages are detected, drain the queue collecting non-status
  574. # messages. If any remain that are not 'shutdown_reply' and this is not iopub
  575. # go ahead and issue a warning.
  576. msgs = []
  577. while self.qsize():
  578. msg = self.get_nowait()
  579. if msg["msg_type"] != "status":
  580. msgs.append(msg["msg_type"])
  581. if self.channel_name == "iopub" and "shutdown_reply" in msgs:
  582. return
  583. if len(msgs):
  584. self.log.warning(
  585. f"Stopping channel '{self.channel_name}' with {len(msgs)} unprocessed non-status messages: {msgs}."
  586. )
  587. def is_alive(self) -> bool:
  588. """Whether the queue is alive."""
  589. return self.channel_socket is not None
  590. class HBChannelQueue(ChannelQueue):
  591. """A queue for the heartbeat channel."""
  592. def is_beating(self) -> bool:
  593. """Whether the channel is beating."""
  594. # Just use the is_alive status for now
  595. return self.is_alive()
  596. class GatewayKernelClient(AsyncKernelClient):
  597. """Communicates with a single kernel indirectly via a websocket to a gateway server.
  598. There are five channels associated with each kernel:
  599. * shell: for request/reply calls to the kernel.
  600. * iopub: for the kernel to publish results to frontends.
  601. * hb: for monitoring the kernel's heartbeat.
  602. * stdin: for frontends to reply to raw_input calls in the kernel.
  603. * control: for kernel management calls to the kernel.
  604. The messages that can be sent on these channels are exposed as methods of the
  605. client (KernelClient.execute, complete, history, etc.). These methods only
  606. send the message, they don't wait for a reply. To get results, use e.g.
  607. :meth:`get_shell_msg` to fetch messages from the shell channel.
  608. """
  609. # flag for whether execute requests should be allowed to call raw_input:
  610. allow_stdin = False
  611. _channels_stopped: bool
  612. _channel_queues: Optional[dict[str, ChannelQueue]]
  613. _control_channel: Optional[ChannelQueue] # type:ignore[assignment]
  614. _hb_channel: Optional[ChannelQueue] # type:ignore[assignment]
  615. _stdin_channel: Optional[ChannelQueue] # type:ignore[assignment]
  616. _iopub_channel: Optional[ChannelQueue] # type:ignore[assignment]
  617. _shell_channel: Optional[ChannelQueue] # type:ignore[assignment]
  618. def __init__(self, kernel_id, **kwargs):
  619. """Initialize a gateway kernel client."""
  620. super().__init__(**kwargs)
  621. self.kernel_id = kernel_id
  622. self.channel_socket: Optional[websocket.WebSocket] = None
  623. self.response_router: Optional[Thread] = None
  624. self._channels_stopped = False
  625. self._channel_queues = {}
  626. # --------------------------------------------------------------------------
  627. # Channel management methods
  628. # --------------------------------------------------------------------------
  629. async def start_channels(self, shell=True, iopub=True, stdin=True, hb=True, control=True):
  630. """Starts the channels for this kernel.
  631. For this class, we establish a websocket connection to the destination
  632. and set up the channel-based queues on which applicable messages will
  633. be posted.
  634. """
  635. ws_url = url_path_join(
  636. GatewayClient.instance().ws_url or "",
  637. GatewayClient.instance().kernels_endpoint,
  638. url_escape(self.kernel_id),
  639. "channels",
  640. )
  641. # Gather cert info in case where ssl is desired...
  642. ssl_options = {
  643. "ca_certs": GatewayClient.instance().ca_certs,
  644. "certfile": GatewayClient.instance().client_cert,
  645. "keyfile": GatewayClient.instance().client_key,
  646. }
  647. self.channel_socket = websocket.create_connection(
  648. ws_url,
  649. timeout=GatewayClient.instance().KERNEL_LAUNCH_TIMEOUT,
  650. enable_multithread=True,
  651. sslopt=ssl_options,
  652. )
  653. await ensure_async(
  654. super().start_channels(shell=shell, iopub=iopub, stdin=stdin, hb=hb, control=control)
  655. )
  656. self.response_router = Thread(target=self._route_responses)
  657. self.response_router.start()
  658. def stop_channels(self):
  659. """Stops all the running channels for this kernel.
  660. For this class, we close the websocket connection and destroy the
  661. channel-based queues.
  662. """
  663. super().stop_channels()
  664. self._channels_stopped = True
  665. self.log.debug("Closing websocket connection")
  666. assert self.channel_socket is not None
  667. self.channel_socket.close()
  668. assert self.response_router is not None
  669. self.response_router.join()
  670. if self._channel_queues:
  671. self._channel_queues.clear()
  672. self._channel_queues = None
  673. # Channels are implemented via a ChannelQueue that is used to send and receive messages
  674. @property
  675. def shell_channel(self):
  676. """Get the shell channel object for this kernel."""
  677. if self._shell_channel is None:
  678. self.log.debug("creating shell channel queue")
  679. assert self.channel_socket is not None
  680. self._shell_channel = ChannelQueue("shell", self.channel_socket, self.log)
  681. assert self._channel_queues is not None
  682. self._channel_queues["shell"] = self._shell_channel
  683. return self._shell_channel
  684. @property
  685. def iopub_channel(self):
  686. """Get the iopub channel object for this kernel."""
  687. if self._iopub_channel is None:
  688. self.log.debug("creating iopub channel queue")
  689. assert self.channel_socket is not None
  690. self._iopub_channel = ChannelQueue("iopub", self.channel_socket, self.log)
  691. assert self._channel_queues is not None
  692. self._channel_queues["iopub"] = self._iopub_channel
  693. return self._iopub_channel
  694. @property
  695. def stdin_channel(self):
  696. """Get the stdin channel object for this kernel."""
  697. if self._stdin_channel is None:
  698. self.log.debug("creating stdin channel queue")
  699. assert self.channel_socket is not None
  700. self._stdin_channel = ChannelQueue("stdin", self.channel_socket, self.log)
  701. assert self._channel_queues is not None
  702. self._channel_queues["stdin"] = self._stdin_channel
  703. return self._stdin_channel
  704. @property
  705. def hb_channel(self):
  706. """Get the hb channel object for this kernel."""
  707. if self._hb_channel is None:
  708. self.log.debug("creating hb channel queue")
  709. assert self.channel_socket is not None
  710. self._hb_channel = HBChannelQueue("hb", self.channel_socket, self.log)
  711. assert self._channel_queues is not None
  712. self._channel_queues["hb"] = self._hb_channel
  713. return self._hb_channel
  714. @property
  715. def control_channel(self):
  716. """Get the control channel object for this kernel."""
  717. if self._control_channel is None:
  718. self.log.debug("creating control channel queue")
  719. assert self.channel_socket is not None
  720. self._control_channel = ChannelQueue("control", self.channel_socket, self.log)
  721. assert self._channel_queues is not None
  722. self._channel_queues["control"] = self._control_channel
  723. return self._control_channel
  724. def _route_responses(self):
  725. """
  726. Reads responses from the websocket and routes each to the appropriate channel queue based
  727. on the message's channel. It does this for the duration of the class's lifetime until the
  728. channels are stopped, at which time the socket is closed (unblocking the router) and
  729. the thread terminates. If shutdown happens to occur while processing a response (unlikely),
  730. termination takes place via the loop control boolean.
  731. """
  732. try:
  733. while not self._channels_stopped:
  734. assert self.channel_socket is not None
  735. raw_message = self.channel_socket.recv()
  736. if not raw_message:
  737. break
  738. response_message = json_decode(utf8(raw_message))
  739. channel = response_message["channel"]
  740. assert self._channel_queues is not None
  741. self._channel_queues[channel].put_nowait(response_message)
  742. except websocket.WebSocketConnectionClosedException:
  743. pass # websocket closure most likely due to shut down
  744. except BaseException as be:
  745. if not self._channels_stopped:
  746. self.log.warning(f"Unexpected exception encountered ({be})")
  747. # Notify channel queues that this thread had finished and no more messages are being received
  748. assert self._channel_queues is not None
  749. for channel_queue in self._channel_queues.values():
  750. channel_queue.response_router_finished = True
  751. self.log.debug("Response router thread exiting...")
  752. KernelClientABC.register(GatewayKernelClient)