kernelmanager.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. """A MultiKernelManager for use in the notebook webserver
  2. - raises HTTPErrors
  3. - creates REST API models
  4. """
  5. # Copyright (c) Jupyter Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from collections import defaultdict
  8. from datetime import datetime, timedelta
  9. from functools import partial
  10. import os
  11. from tornado import gen, web
  12. from tornado.concurrent import Future
  13. from tornado.ioloop import IOLoop, PeriodicCallback
  14. from jupyter_client.session import Session
  15. from jupyter_client.multikernelmanager import MultiKernelManager
  16. from traitlets import (Any, Bool, Dict, List, Unicode, TraitError, Integer,
  17. Float, Instance, default, validate
  18. )
  19. from notebook.utils import to_os_path, exists
  20. from notebook._tz import utcnow, isoformat
  21. from ipython_genutils.py3compat import getcwd
  22. class MappingKernelManager(MultiKernelManager):
  23. """A KernelManager that handles notebook mapping and HTTP error handling"""
  24. @default('kernel_manager_class')
  25. def _default_kernel_manager_class(self):
  26. return "jupyter_client.ioloop.IOLoopKernelManager"
  27. kernel_argv = List(Unicode())
  28. root_dir = Unicode(config=True)
  29. _kernel_connections = Dict()
  30. _culler_callback = None
  31. _initialized_culler = False
  32. @default('root_dir')
  33. def _default_root_dir(self):
  34. try:
  35. return self.parent.notebook_dir
  36. except AttributeError:
  37. return getcwd()
  38. @validate('root_dir')
  39. def _update_root_dir(self, proposal):
  40. """Do a bit of validation of the root dir."""
  41. value = proposal['value']
  42. if not os.path.isabs(value):
  43. # If we receive a non-absolute path, make it absolute.
  44. value = os.path.abspath(value)
  45. if not exists(value) or not os.path.isdir(value):
  46. raise TraitError("kernel root dir %r is not a directory" % value)
  47. return value
  48. cull_idle_timeout = Integer(0, config=True,
  49. help="""Timeout (in seconds) after which a kernel is considered idle and ready to be culled.
  50. Values of 0 or lower disable culling. Very short timeouts may result in kernels being culled
  51. for users with poor network connections."""
  52. )
  53. cull_interval_default = 300 # 5 minutes
  54. cull_interval = Integer(cull_interval_default, config=True,
  55. help="""The interval (in seconds) on which to check for idle kernels exceeding the cull timeout value."""
  56. )
  57. cull_connected = Bool(False, config=True,
  58. help="""Whether to consider culling kernels which have one or more connections.
  59. Only effective if cull_idle_timeout > 0."""
  60. )
  61. cull_busy = Bool(False, config=True,
  62. help="""Whether to consider culling kernels which are busy.
  63. Only effective if cull_idle_timeout > 0."""
  64. )
  65. buffer_offline_messages = Bool(True, config=True,
  66. help="""Whether messages from kernels whose frontends have disconnected should be buffered in-memory.
  67. When True (default), messages are buffered and replayed on reconnect,
  68. avoiding lost messages due to interrupted connectivity.
  69. Disable if long-running kernels will produce too much output while
  70. no frontends are connected.
  71. """
  72. )
  73. kernel_info_timeout = Float(60, config=True,
  74. help="""Timeout for giving up on a kernel (in seconds).
  75. On starting and restarting kernels, we check whether the
  76. kernel is running and responsive by sending kernel_info_requests.
  77. This sets the timeout in seconds for how long the kernel can take
  78. before being presumed dead.
  79. This affects the MappingKernelManager (which handles kernel restarts)
  80. and the ZMQChannelsHandler (which handles the startup).
  81. """
  82. )
  83. _kernel_buffers = Any()
  84. @default('_kernel_buffers')
  85. def _default_kernel_buffers(self):
  86. return defaultdict(lambda: {'buffer': [], 'session_key': '', 'channels': {}})
  87. last_kernel_activity = Instance(datetime,
  88. help="The last activity on any kernel, including shutting down a kernel")
  89. def __init__(self, **kwargs):
  90. super(MappingKernelManager, self).__init__(**kwargs)
  91. self.last_kernel_activity = utcnow()
  92. #-------------------------------------------------------------------------
  93. # Methods for managing kernels and sessions
  94. #-------------------------------------------------------------------------
  95. def _handle_kernel_died(self, kernel_id):
  96. """notice that a kernel died"""
  97. self.log.warning("Kernel %s died, removing from map.", kernel_id)
  98. self.remove_kernel(kernel_id)
  99. def cwd_for_path(self, path):
  100. """Turn API path into absolute OS path."""
  101. os_path = to_os_path(path, self.root_dir)
  102. # in the case of notebooks and kernels not being on the same filesystem,
  103. # walk up to root_dir if the paths don't exist
  104. while not os.path.isdir(os_path) and os_path != self.root_dir:
  105. os_path = os.path.dirname(os_path)
  106. return os_path
  107. @gen.coroutine
  108. def start_kernel(self, kernel_id=None, path=None, **kwargs):
  109. """Start a kernel for a session and return its kernel_id.
  110. Parameters
  111. ----------
  112. kernel_id : uuid
  113. The uuid to associate the new kernel with. If this
  114. is not None, this kernel will be persistent whenever it is
  115. requested.
  116. path : API path
  117. The API path (unicode, '/' delimited) for the cwd.
  118. Will be transformed to an OS path relative to root_dir.
  119. kernel_name : str
  120. The name identifying which kernel spec to launch. This is ignored if
  121. an existing kernel is returned, but it may be checked in the future.
  122. """
  123. if kernel_id is None:
  124. if path is not None:
  125. kwargs['cwd'] = self.cwd_for_path(path)
  126. kernel_id = yield gen.maybe_future(
  127. super(MappingKernelManager, self).start_kernel(**kwargs)
  128. )
  129. self._kernel_connections[kernel_id] = 0
  130. self.start_watching_activity(kernel_id)
  131. self.log.info("Kernel started: %s" % kernel_id)
  132. self.log.debug("Kernel args: %r" % kwargs)
  133. # register callback for failed auto-restart
  134. self.add_restart_callback(kernel_id,
  135. lambda : self._handle_kernel_died(kernel_id),
  136. 'dead',
  137. )
  138. else:
  139. self._check_kernel_id(kernel_id)
  140. self.log.info("Using existing kernel: %s" % kernel_id)
  141. # Initialize culling if not already
  142. if not self._initialized_culler:
  143. self.initialize_culler()
  144. # py2-compat
  145. raise gen.Return(kernel_id)
  146. def start_buffering(self, kernel_id, session_key, channels):
  147. """Start buffering messages for a kernel
  148. Parameters
  149. ----------
  150. kernel_id : str
  151. The id of the kernel to stop buffering.
  152. session_key: str
  153. The session_key, if any, that should get the buffer.
  154. If the session_key matches the current buffered session_key,
  155. the buffer will be returned.
  156. channels: dict({'channel': ZMQStream})
  157. The zmq channels whose messages should be buffered.
  158. """
  159. if not self.buffer_offline_messages:
  160. for channel, stream in channels.items():
  161. stream.close()
  162. return
  163. self.log.info("Starting buffering for %s", session_key)
  164. self._check_kernel_id(kernel_id)
  165. # clear previous buffering state
  166. self.stop_buffering(kernel_id)
  167. buffer_info = self._kernel_buffers[kernel_id]
  168. # record the session key because only one session can buffer
  169. buffer_info['session_key'] = session_key
  170. # TODO: the buffer should likely be a memory bounded queue, we're starting with a list to keep it simple
  171. buffer_info['buffer'] = []
  172. buffer_info['channels'] = channels
  173. # forward any future messages to the internal buffer
  174. def buffer_msg(channel, msg_parts):
  175. self.log.debug("Buffering msg on %s:%s", kernel_id, channel)
  176. buffer_info['buffer'].append((channel, msg_parts))
  177. for channel, stream in channels.items():
  178. stream.on_recv(partial(buffer_msg, channel))
  179. def get_buffer(self, kernel_id, session_key):
  180. """Get the buffer for a given kernel
  181. Parameters
  182. ----------
  183. kernel_id : str
  184. The id of the kernel to stop buffering.
  185. session_key: str, optional
  186. The session_key, if any, that should get the buffer.
  187. If the session_key matches the current buffered session_key,
  188. the buffer will be returned.
  189. """
  190. self.log.debug("Getting buffer for %s", kernel_id)
  191. if kernel_id not in self._kernel_buffers:
  192. return
  193. buffer_info = self._kernel_buffers[kernel_id]
  194. if buffer_info['session_key'] == session_key:
  195. # remove buffer
  196. self._kernel_buffers.pop(kernel_id)
  197. # only return buffer_info if it's a match
  198. return buffer_info
  199. else:
  200. self.stop_buffering(kernel_id)
  201. def stop_buffering(self, kernel_id):
  202. """Stop buffering kernel messages
  203. Parameters
  204. ----------
  205. kernel_id : str
  206. The id of the kernel to stop buffering.
  207. """
  208. self.log.debug("Clearing buffer for %s", kernel_id)
  209. self._check_kernel_id(kernel_id)
  210. if kernel_id not in self._kernel_buffers:
  211. return
  212. buffer_info = self._kernel_buffers.pop(kernel_id)
  213. # close buffering streams
  214. for stream in buffer_info['channels'].values():
  215. if not stream.closed():
  216. stream.on_recv(None)
  217. stream.close()
  218. msg_buffer = buffer_info['buffer']
  219. if msg_buffer:
  220. self.log.info("Discarding %s buffered messages for %s",
  221. len(msg_buffer), buffer_info['session_key'])
  222. def shutdown_kernel(self, kernel_id, now=False):
  223. """Shutdown a kernel by kernel_id"""
  224. self._check_kernel_id(kernel_id)
  225. kernel = self._kernels[kernel_id]
  226. if kernel._activity_stream:
  227. kernel._activity_stream.close()
  228. kernel._activity_stream = None
  229. self.stop_buffering(kernel_id)
  230. self._kernel_connections.pop(kernel_id, None)
  231. self.last_kernel_activity = utcnow()
  232. return super(MappingKernelManager, self).shutdown_kernel(kernel_id, now=now)
  233. @gen.coroutine
  234. def restart_kernel(self, kernel_id):
  235. """Restart a kernel by kernel_id"""
  236. self._check_kernel_id(kernel_id)
  237. yield gen.maybe_future(super(MappingKernelManager, self).restart_kernel(kernel_id))
  238. kernel = self.get_kernel(kernel_id)
  239. # return a Future that will resolve when the kernel has successfully restarted
  240. channel = kernel.connect_shell()
  241. future = Future()
  242. def finish():
  243. """Common cleanup when restart finishes/fails for any reason."""
  244. if not channel.closed():
  245. channel.close()
  246. loop.remove_timeout(timeout)
  247. kernel.remove_restart_callback(on_restart_failed, 'dead')
  248. def on_reply(msg):
  249. self.log.debug("Kernel info reply received: %s", kernel_id)
  250. finish()
  251. if not future.done():
  252. future.set_result(msg)
  253. def on_timeout():
  254. self.log.warning("Timeout waiting for kernel_info_reply: %s", kernel_id)
  255. finish()
  256. if not future.done():
  257. future.set_exception(gen.TimeoutError("Timeout waiting for restart"))
  258. def on_restart_failed():
  259. self.log.warning("Restarting kernel failed: %s", kernel_id)
  260. finish()
  261. if not future.done():
  262. future.set_exception(RuntimeError("Restart failed"))
  263. kernel.add_restart_callback(on_restart_failed, 'dead')
  264. kernel.session.send(channel, "kernel_info_request")
  265. channel.on_recv(on_reply)
  266. loop = IOLoop.current()
  267. timeout = loop.add_timeout(loop.time() + self.kernel_info_timeout, on_timeout)
  268. # wait for restart to complete
  269. yield future
  270. def notify_connect(self, kernel_id):
  271. """Notice a new connection to a kernel"""
  272. if kernel_id in self._kernel_connections:
  273. self._kernel_connections[kernel_id] += 1
  274. def notify_disconnect(self, kernel_id):
  275. """Notice a disconnection from a kernel"""
  276. if kernel_id in self._kernel_connections:
  277. self._kernel_connections[kernel_id] -= 1
  278. def kernel_model(self, kernel_id):
  279. """Return a JSON-safe dict representing a kernel
  280. For use in representing kernels in the JSON APIs.
  281. """
  282. self._check_kernel_id(kernel_id)
  283. kernel = self._kernels[kernel_id]
  284. model = {
  285. "id":kernel_id,
  286. "name": kernel.kernel_name,
  287. "last_activity": isoformat(kernel.last_activity),
  288. "execution_state": kernel.execution_state,
  289. "connections": self._kernel_connections[kernel_id],
  290. }
  291. return model
  292. def list_kernels(self):
  293. """Returns a list of kernel_id's of kernels running."""
  294. kernels = []
  295. kernel_ids = super(MappingKernelManager, self).list_kernel_ids()
  296. for kernel_id in kernel_ids:
  297. model = self.kernel_model(kernel_id)
  298. kernels.append(model)
  299. return kernels
  300. # override _check_kernel_id to raise 404 instead of KeyError
  301. def _check_kernel_id(self, kernel_id):
  302. """Check a that a kernel_id exists and raise 404 if not."""
  303. if kernel_id not in self:
  304. raise web.HTTPError(404, u'Kernel does not exist: %s' % kernel_id)
  305. # monitoring activity:
  306. def start_watching_activity(self, kernel_id):
  307. """Start watching IOPub messages on a kernel for activity.
  308. - update last_activity on every message
  309. - record execution_state from status messages
  310. """
  311. kernel = self._kernels[kernel_id]
  312. # add busy/activity markers:
  313. kernel.execution_state = 'starting'
  314. kernel.last_activity = utcnow()
  315. kernel._activity_stream = kernel.connect_iopub()
  316. session = Session(
  317. config=kernel.session.config,
  318. key=kernel.session.key,
  319. )
  320. def record_activity(msg_list):
  321. """Record an IOPub message arriving from a kernel"""
  322. self.last_kernel_activity = kernel.last_activity = utcnow()
  323. idents, fed_msg_list = session.feed_identities(msg_list)
  324. msg = session.deserialize(fed_msg_list)
  325. msg_type = msg['header']['msg_type']
  326. self.log.debug("activity on %s: %s", kernel_id, msg_type)
  327. if msg_type == 'status':
  328. kernel.execution_state = msg['content']['execution_state']
  329. kernel._activity_stream.on_recv(record_activity)
  330. def initialize_culler(self):
  331. """Start idle culler if 'cull_idle_timeout' is greater than zero.
  332. Regardless of that value, set flag that we've been here.
  333. """
  334. if not self._initialized_culler and self.cull_idle_timeout > 0:
  335. if self._culler_callback is None:
  336. loop = IOLoop.current()
  337. if self.cull_interval <= 0: #handle case where user set invalid value
  338. self.log.warning("Invalid value for 'cull_interval' detected (%s) - using default value (%s).",
  339. self.cull_interval, self.cull_interval_default)
  340. self.cull_interval = self.cull_interval_default
  341. self._culler_callback = PeriodicCallback(
  342. self.cull_kernels, 1000*self.cull_interval)
  343. self.log.info("Culling kernels with idle durations > %s seconds at %s second intervals ...",
  344. self.cull_idle_timeout, self.cull_interval)
  345. if self.cull_busy:
  346. self.log.info("Culling kernels even if busy")
  347. if self.cull_connected:
  348. self.log.info("Culling kernels even with connected clients")
  349. self._culler_callback.start()
  350. self._initialized_culler = True
  351. def cull_kernels(self):
  352. self.log.debug("Polling every %s seconds for kernels idle > %s seconds...",
  353. self.cull_interval, self.cull_idle_timeout)
  354. """Create a separate list of kernels to avoid conflicting updates while iterating"""
  355. for kernel_id in list(self._kernels):
  356. try:
  357. self.cull_kernel_if_idle(kernel_id)
  358. except Exception as e:
  359. self.log.exception("The following exception was encountered while checking the idle duration of kernel %s: %s",
  360. kernel_id, e)
  361. def cull_kernel_if_idle(self, kernel_id):
  362. kernel = self._kernels[kernel_id]
  363. self.log.debug("kernel_id=%s, kernel_name=%s, last_activity=%s", kernel_id, kernel.kernel_name, kernel.last_activity)
  364. if kernel.last_activity is not None:
  365. dt_now = utcnow()
  366. dt_idle = dt_now - kernel.last_activity
  367. # Compute idle properties
  368. is_idle_time = dt_idle > timedelta(seconds=self.cull_idle_timeout)
  369. is_idle_execute = self.cull_busy or (kernel.execution_state != 'busy')
  370. connections = self._kernel_connections.get(kernel_id, 0)
  371. is_idle_connected = self.cull_connected or not connections
  372. # Cull the kernel if all three criteria are met
  373. if (is_idle_time and is_idle_execute and is_idle_connected):
  374. idle_duration = int(dt_idle.total_seconds())
  375. self.log.warning("Culling '%s' kernel '%s' (%s) with %d connections due to %s seconds of inactivity.",
  376. kernel.execution_state, kernel.kernel_name, kernel_id, connections, idle_duration)
  377. self.shutdown_kernel(kernel_id)