manager.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. """Base class to manage a running kernel"""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import absolute_import
  5. from contextlib import contextmanager
  6. import os
  7. import re
  8. import signal
  9. import sys
  10. import time
  11. import warnings
  12. import zmq
  13. from ipython_genutils.importstring import import_item
  14. from .localinterfaces import is_local_ip, local_ips
  15. from traitlets import (
  16. Any, Float, Instance, Unicode, List, Bool, Type, DottedObjectName
  17. )
  18. from jupyter_client import (
  19. launch_kernel,
  20. kernelspec,
  21. )
  22. from .connect import ConnectionFileMixin
  23. from .managerabc import (
  24. KernelManagerABC
  25. )
  26. class KernelManager(ConnectionFileMixin):
  27. """Manages a single kernel in a subprocess on this host.
  28. This version starts kernels with Popen.
  29. """
  30. # The PyZMQ Context to use for communication with the kernel.
  31. context = Instance(zmq.Context)
  32. def _context_default(self):
  33. return zmq.Context()
  34. # the class to create with our `client` method
  35. client_class = DottedObjectName('jupyter_client.blocking.BlockingKernelClient')
  36. client_factory = Type(klass='jupyter_client.KernelClient')
  37. def _client_factory_default(self):
  38. return import_item(self.client_class)
  39. def _client_class_changed(self, name, old, new):
  40. self.client_factory = import_item(str(new))
  41. # The kernel process with which the KernelManager is communicating.
  42. # generally a Popen instance
  43. kernel = Any()
  44. kernel_spec_manager = Instance(kernelspec.KernelSpecManager)
  45. def _kernel_spec_manager_default(self):
  46. return kernelspec.KernelSpecManager(data_dir=self.data_dir)
  47. def _kernel_spec_manager_changed(self):
  48. self._kernel_spec = None
  49. shutdown_wait_time = Float(
  50. 5.0, config=True,
  51. help="Time to wait for a kernel to terminate before killing it, "
  52. "in seconds.")
  53. kernel_name = Unicode(kernelspec.NATIVE_KERNEL_NAME)
  54. def _kernel_name_changed(self, name, old, new):
  55. self._kernel_spec = None
  56. if new == 'python':
  57. self.kernel_name = kernelspec.NATIVE_KERNEL_NAME
  58. _kernel_spec = None
  59. @property
  60. def kernel_spec(self):
  61. if self._kernel_spec is None and self.kernel_name is not '':
  62. self._kernel_spec = self.kernel_spec_manager.get_kernel_spec(self.kernel_name)
  63. return self._kernel_spec
  64. kernel_cmd = List(Unicode(), config=True,
  65. help="""DEPRECATED: Use kernel_name instead.
  66. The Popen Command to launch the kernel.
  67. Override this if you have a custom kernel.
  68. If kernel_cmd is specified in a configuration file,
  69. Jupyter does not pass any arguments to the kernel,
  70. because it cannot make any assumptions about the
  71. arguments that the kernel understands. In particular,
  72. this means that the kernel does not receive the
  73. option --debug if it given on the Jupyter command line.
  74. """
  75. )
  76. def _kernel_cmd_changed(self, name, old, new):
  77. warnings.warn("Setting kernel_cmd is deprecated, use kernel_spec to "
  78. "start different kernels.")
  79. @property
  80. def ipykernel(self):
  81. return self.kernel_name in {'python', 'python2', 'python3'}
  82. # Protected traits
  83. _launch_args = Any()
  84. _control_socket = Any()
  85. _restarter = Any()
  86. autorestart = Bool(True, config=True,
  87. help="""Should we autorestart the kernel if it dies."""
  88. )
  89. def __del__(self):
  90. self._close_control_socket()
  91. self.cleanup_connection_file()
  92. #--------------------------------------------------------------------------
  93. # Kernel restarter
  94. #--------------------------------------------------------------------------
  95. def start_restarter(self):
  96. pass
  97. def stop_restarter(self):
  98. pass
  99. def add_restart_callback(self, callback, event='restart'):
  100. """register a callback to be called when a kernel is restarted"""
  101. if self._restarter is None:
  102. return
  103. self._restarter.add_callback(callback, event)
  104. def remove_restart_callback(self, callback, event='restart'):
  105. """unregister a callback to be called when a kernel is restarted"""
  106. if self._restarter is None:
  107. return
  108. self._restarter.remove_callback(callback, event)
  109. #--------------------------------------------------------------------------
  110. # create a Client connected to our Kernel
  111. #--------------------------------------------------------------------------
  112. def client(self, **kwargs):
  113. """Create a client configured to connect to our kernel"""
  114. kw = {}
  115. kw.update(self.get_connection_info(session=True))
  116. kw.update(dict(
  117. connection_file=self.connection_file,
  118. parent=self,
  119. ))
  120. # add kwargs last, for manual overrides
  121. kw.update(kwargs)
  122. return self.client_factory(**kw)
  123. #--------------------------------------------------------------------------
  124. # Kernel management
  125. #--------------------------------------------------------------------------
  126. def format_kernel_cmd(self, extra_arguments=None):
  127. """replace templated args (e.g. {connection_file})"""
  128. extra_arguments = extra_arguments or []
  129. if self.kernel_cmd:
  130. cmd = self.kernel_cmd + extra_arguments
  131. else:
  132. cmd = self.kernel_spec.argv + extra_arguments
  133. if cmd and cmd[0] in {'python',
  134. 'python%i' % sys.version_info[0],
  135. 'python%i.%i' % sys.version_info[:2]}:
  136. # executable is 'python' or 'python3', use sys.executable.
  137. # These will typically be the same,
  138. # but if the current process is in an env
  139. # and has been launched by abspath without
  140. # activating the env, python on PATH may not be sys.executable,
  141. # but it should be.
  142. cmd[0] = sys.executable
  143. ns = dict(connection_file=self.connection_file,
  144. prefix=sys.prefix,
  145. )
  146. if self.kernel_spec:
  147. ns["resource_dir"] = self.kernel_spec.resource_dir
  148. ns.update(self._launch_args)
  149. pat = re.compile(r'\{([A-Za-z0-9_]+)\}')
  150. def from_ns(match):
  151. """Get the key out of ns if it's there, otherwise no change."""
  152. return ns.get(match.group(1), match.group())
  153. return [ pat.sub(from_ns, arg) for arg in cmd ]
  154. def _launch_kernel(self, kernel_cmd, **kw):
  155. """actually launch the kernel
  156. override in a subclass to launch kernel subprocesses differently
  157. """
  158. return launch_kernel(kernel_cmd, **kw)
  159. # Control socket used for polite kernel shutdown
  160. def _connect_control_socket(self):
  161. if self._control_socket is None:
  162. self._control_socket = self._create_connected_socket('control')
  163. self._control_socket.linger = 100
  164. def _close_control_socket(self):
  165. if self._control_socket is None:
  166. return
  167. self._control_socket.close()
  168. self._control_socket = None
  169. def start_kernel(self, **kw):
  170. """Starts a kernel on this host in a separate process.
  171. If random ports (port=0) are being used, this method must be called
  172. before the channels are created.
  173. Parameters
  174. ----------
  175. `**kw` : optional
  176. keyword arguments that are passed down to build the kernel_cmd
  177. and launching the kernel (e.g. Popen kwargs).
  178. """
  179. if self.transport == 'tcp' and not is_local_ip(self.ip):
  180. raise RuntimeError("Can only launch a kernel on a local interface. "
  181. "This one is not: %s."
  182. "Make sure that the '*_address' attributes are "
  183. "configured properly. "
  184. "Currently valid addresses are: %s" % (self.ip, local_ips())
  185. )
  186. # write connection file / get default ports
  187. self.write_connection_file()
  188. # save kwargs for use in restart
  189. self._launch_args = kw.copy()
  190. # build the Popen cmd
  191. extra_arguments = kw.pop('extra_arguments', [])
  192. kernel_cmd = self.format_kernel_cmd(extra_arguments=extra_arguments)
  193. env = kw.pop('env', os.environ).copy()
  194. # Don't allow PYTHONEXECUTABLE to be passed to kernel process.
  195. # If set, it can bork all the things.
  196. env.pop('PYTHONEXECUTABLE', None)
  197. if not self.kernel_cmd:
  198. # If kernel_cmd has been set manually, don't refer to a kernel spec
  199. # Environment variables from kernel spec are added to os.environ
  200. env.update(self.kernel_spec.env or {})
  201. # launch the kernel subprocess
  202. self.log.debug("Starting kernel: %s", kernel_cmd)
  203. self.kernel = self._launch_kernel(kernel_cmd, env=env,
  204. **kw)
  205. self.start_restarter()
  206. self._connect_control_socket()
  207. def request_shutdown(self, restart=False):
  208. """Send a shutdown request via control channel
  209. """
  210. content = dict(restart=restart)
  211. msg = self.session.msg("shutdown_request", content=content)
  212. # ensure control socket is connected
  213. self._connect_control_socket()
  214. self.session.send(self._control_socket, msg)
  215. def finish_shutdown(self, waittime=None, pollinterval=0.1):
  216. """Wait for kernel shutdown, then kill process if it doesn't shutdown.
  217. This does not send shutdown requests - use :meth:`request_shutdown`
  218. first.
  219. """
  220. if waittime is None:
  221. waittime = max(self.shutdown_wait_time, 0)
  222. for i in range(int(waittime/pollinterval)):
  223. if self.is_alive():
  224. time.sleep(pollinterval)
  225. else:
  226. break
  227. else:
  228. # OK, we've waited long enough.
  229. if self.has_kernel:
  230. self.log.debug("Kernel is taking too long to finish, killing")
  231. self._kill_kernel()
  232. def cleanup(self, connection_file=True):
  233. """Clean up resources when the kernel is shut down"""
  234. if connection_file:
  235. self.cleanup_connection_file()
  236. self.cleanup_ipc_files()
  237. self._close_control_socket()
  238. def shutdown_kernel(self, now=False, restart=False):
  239. """Attempts to stop the kernel process cleanly.
  240. This attempts to shutdown the kernels cleanly by:
  241. 1. Sending it a shutdown message over the shell channel.
  242. 2. If that fails, the kernel is shutdown forcibly by sending it
  243. a signal.
  244. Parameters
  245. ----------
  246. now : bool
  247. Should the kernel be forcible killed *now*. This skips the
  248. first, nice shutdown attempt.
  249. restart: bool
  250. Will this kernel be restarted after it is shutdown. When this
  251. is True, connection files will not be cleaned up.
  252. """
  253. # Stop monitoring for restarting while we shutdown.
  254. self.stop_restarter()
  255. if now:
  256. self._kill_kernel()
  257. else:
  258. self.request_shutdown(restart=restart)
  259. # Don't send any additional kernel kill messages immediately, to give
  260. # the kernel a chance to properly execute shutdown actions. Wait for at
  261. # most 1s, checking every 0.1s.
  262. self.finish_shutdown()
  263. self.cleanup(connection_file=not restart)
  264. def restart_kernel(self, now=False, newports=False, **kw):
  265. """Restarts a kernel with the arguments that were used to launch it.
  266. Parameters
  267. ----------
  268. now : bool, optional
  269. If True, the kernel is forcefully restarted *immediately*, without
  270. having a chance to do any cleanup action. Otherwise the kernel is
  271. given 1s to clean up before a forceful restart is issued.
  272. In all cases the kernel is restarted, the only difference is whether
  273. it is given a chance to perform a clean shutdown or not.
  274. newports : bool, optional
  275. If the old kernel was launched with random ports, this flag decides
  276. whether the same ports and connection file will be used again.
  277. If False, the same ports and connection file are used. This is
  278. the default. If True, new random port numbers are chosen and a
  279. new connection file is written. It is still possible that the newly
  280. chosen random port numbers happen to be the same as the old ones.
  281. `**kw` : optional
  282. Any options specified here will overwrite those used to launch the
  283. kernel.
  284. """
  285. if self._launch_args is None:
  286. raise RuntimeError("Cannot restart the kernel. "
  287. "No previous call to 'start_kernel'.")
  288. else:
  289. # Stop currently running kernel.
  290. self.shutdown_kernel(now=now, restart=True)
  291. if newports:
  292. self.cleanup_random_ports()
  293. # Start new kernel.
  294. self._launch_args.update(kw)
  295. self.start_kernel(**self._launch_args)
  296. @property
  297. def has_kernel(self):
  298. """Has a kernel been started that we are managing."""
  299. return self.kernel is not None
  300. def _kill_kernel(self):
  301. """Kill the running kernel.
  302. This is a private method, callers should use shutdown_kernel(now=True).
  303. """
  304. if self.has_kernel:
  305. # Signal the kernel to terminate (sends SIGKILL on Unix and calls
  306. # TerminateProcess() on Win32).
  307. try:
  308. if hasattr(signal, 'SIGKILL'):
  309. self.signal_kernel(signal.SIGKILL)
  310. else:
  311. self.kernel.kill()
  312. except OSError as e:
  313. # In Windows, we will get an Access Denied error if the process
  314. # has already terminated. Ignore it.
  315. if sys.platform == 'win32':
  316. if e.winerror != 5:
  317. raise
  318. # On Unix, we may get an ESRCH error if the process has already
  319. # terminated. Ignore it.
  320. else:
  321. from errno import ESRCH
  322. if e.errno != ESRCH:
  323. raise
  324. # Block until the kernel terminates.
  325. self.kernel.wait()
  326. self.kernel = None
  327. else:
  328. raise RuntimeError("Cannot kill kernel. No kernel is running!")
  329. def interrupt_kernel(self):
  330. """Interrupts the kernel by sending it a signal.
  331. Unlike ``signal_kernel``, this operation is well supported on all
  332. platforms.
  333. """
  334. if self.has_kernel:
  335. interrupt_mode = self.kernel_spec.interrupt_mode
  336. if interrupt_mode == 'signal':
  337. if sys.platform == 'win32':
  338. from .win_interrupt import send_interrupt
  339. send_interrupt(self.kernel.win32_interrupt_event)
  340. else:
  341. self.signal_kernel(signal.SIGINT)
  342. elif interrupt_mode == 'message':
  343. msg = self.session.msg("interrupt_request", content={})
  344. self._connect_control_socket()
  345. self.session.send(self._control_socket, msg)
  346. else:
  347. raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
  348. def signal_kernel(self, signum):
  349. """Sends a signal to the process group of the kernel (this
  350. usually includes the kernel and any subprocesses spawned by
  351. the kernel).
  352. Note that since only SIGTERM is supported on Windows, this function is
  353. only useful on Unix systems.
  354. """
  355. if self.has_kernel:
  356. if hasattr(os, "getpgid") and hasattr(os, "killpg"):
  357. try:
  358. pgid = os.getpgid(self.kernel.pid)
  359. os.killpg(pgid, signum)
  360. return
  361. except OSError:
  362. pass
  363. self.kernel.send_signal(signum)
  364. else:
  365. raise RuntimeError("Cannot signal kernel. No kernel is running!")
  366. def is_alive(self):
  367. """Is the kernel process still running?"""
  368. if self.has_kernel:
  369. if self.kernel.poll() is None:
  370. return True
  371. else:
  372. return False
  373. else:
  374. # we don't have a kernel
  375. return False
  376. KernelManagerABC.register(KernelManager)
  377. def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs):
  378. """Start a new kernel, and return its Manager and Client"""
  379. km = KernelManager(kernel_name=kernel_name)
  380. km.start_kernel(**kwargs)
  381. kc = km.client()
  382. kc.start_channels()
  383. try:
  384. kc.wait_for_ready(timeout=startup_timeout)
  385. except RuntimeError:
  386. kc.stop_channels()
  387. km.shutdown_kernel()
  388. raise
  389. return km, kc
  390. @contextmanager
  391. def run_kernel(**kwargs):
  392. """Context manager to create a kernel in a subprocess.
  393. The kernel is shut down when the context exits.
  394. Returns
  395. -------
  396. kernel_client: connected KernelClient instance
  397. """
  398. km, kc = start_new_kernel(**kwargs)
  399. try:
  400. yield kc
  401. finally:
  402. kc.stop_channels()
  403. km.shutdown_kernel(now=True)