client.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. """Base class to manage the interaction with 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 jupyter_client.channels import major_protocol_version
  6. from ipython_genutils.py3compat import string_types, iteritems
  7. import zmq
  8. from traitlets import (
  9. Any, Instance, Type,
  10. )
  11. from .channelsabc import (ChannelABC, HBChannelABC)
  12. from .clientabc import KernelClientABC
  13. from .connect import ConnectionFileMixin
  14. # some utilities to validate message structure, these might get moved elsewhere
  15. # if they prove to have more generic utility
  16. def validate_string_dict(dct):
  17. """Validate that the input is a dict with string keys and values.
  18. Raises ValueError if not."""
  19. for k,v in iteritems(dct):
  20. if not isinstance(k, string_types):
  21. raise ValueError('key %r in dict must be a string' % k)
  22. if not isinstance(v, string_types):
  23. raise ValueError('value %r in dict must be a string' % v)
  24. class KernelClient(ConnectionFileMixin):
  25. """Communicates with a single kernel on any host via zmq channels.
  26. There are four channels associated with each kernel:
  27. * shell: for request/reply calls to the kernel.
  28. * iopub: for the kernel to publish results to frontends.
  29. * hb: for monitoring the kernel's heartbeat.
  30. * stdin: for frontends to reply to raw_input calls in the kernel.
  31. The messages that can be sent on these channels are exposed as methods of the
  32. client (KernelClient.execute, complete, history, etc.). These methods only
  33. send the message, they don't wait for a reply. To get results, use e.g.
  34. :meth:`get_shell_msg` to fetch messages from the shell channel.
  35. """
  36. # The PyZMQ Context to use for communication with the kernel.
  37. context = Instance(zmq.Context)
  38. def _context_default(self):
  39. return zmq.Context()
  40. # The classes to use for the various channels
  41. shell_channel_class = Type(ChannelABC)
  42. iopub_channel_class = Type(ChannelABC)
  43. stdin_channel_class = Type(ChannelABC)
  44. hb_channel_class = Type(HBChannelABC)
  45. # Protected traits
  46. _shell_channel = Any()
  47. _iopub_channel = Any()
  48. _stdin_channel = Any()
  49. _hb_channel = Any()
  50. # flag for whether execute requests should be allowed to call raw_input:
  51. allow_stdin = True
  52. #--------------------------------------------------------------------------
  53. # Channel proxy methods
  54. #--------------------------------------------------------------------------
  55. def get_shell_msg(self, *args, **kwargs):
  56. """Get a message from the shell channel"""
  57. return self.shell_channel.get_msg(*args, **kwargs)
  58. def get_iopub_msg(self, *args, **kwargs):
  59. """Get a message from the iopub channel"""
  60. return self.iopub_channel.get_msg(*args, **kwargs)
  61. def get_stdin_msg(self, *args, **kwargs):
  62. """Get a message from the stdin channel"""
  63. return self.stdin_channel.get_msg(*args, **kwargs)
  64. #--------------------------------------------------------------------------
  65. # Channel management methods
  66. #--------------------------------------------------------------------------
  67. def start_channels(self, shell=True, iopub=True, stdin=True, hb=True):
  68. """Starts the channels for this kernel.
  69. This will create the channels if they do not exist and then start
  70. them (their activity runs in a thread). If port numbers of 0 are
  71. being used (random ports) then you must first call
  72. :meth:`start_kernel`. If the channels have been stopped and you
  73. call this, :class:`RuntimeError` will be raised.
  74. """
  75. if shell:
  76. self.shell_channel.start()
  77. self.kernel_info()
  78. if iopub:
  79. self.iopub_channel.start()
  80. if stdin:
  81. self.stdin_channel.start()
  82. self.allow_stdin = True
  83. else:
  84. self.allow_stdin = False
  85. if hb:
  86. self.hb_channel.start()
  87. def stop_channels(self):
  88. """Stops all the running channels for this kernel.
  89. This stops their event loops and joins their threads.
  90. """
  91. if self.shell_channel.is_alive():
  92. self.shell_channel.stop()
  93. if self.iopub_channel.is_alive():
  94. self.iopub_channel.stop()
  95. if self.stdin_channel.is_alive():
  96. self.stdin_channel.stop()
  97. if self.hb_channel.is_alive():
  98. self.hb_channel.stop()
  99. @property
  100. def channels_running(self):
  101. """Are any of the channels created and running?"""
  102. return (self.shell_channel.is_alive() or self.iopub_channel.is_alive() or
  103. self.stdin_channel.is_alive() or self.hb_channel.is_alive())
  104. ioloop = None # Overridden in subclasses that use pyzmq event loop
  105. @property
  106. def shell_channel(self):
  107. """Get the shell channel object for this kernel."""
  108. if self._shell_channel is None:
  109. url = self._make_url('shell')
  110. self.log.debug("connecting shell channel to %s", url)
  111. socket = self.connect_shell(identity=self.session.bsession)
  112. self._shell_channel = self.shell_channel_class(
  113. socket, self.session, self.ioloop
  114. )
  115. return self._shell_channel
  116. @property
  117. def iopub_channel(self):
  118. """Get the iopub channel object for this kernel."""
  119. if self._iopub_channel is None:
  120. url = self._make_url('iopub')
  121. self.log.debug("connecting iopub channel to %s", url)
  122. socket = self.connect_iopub()
  123. self._iopub_channel = self.iopub_channel_class(
  124. socket, self.session, self.ioloop
  125. )
  126. return self._iopub_channel
  127. @property
  128. def stdin_channel(self):
  129. """Get the stdin channel object for this kernel."""
  130. if self._stdin_channel is None:
  131. url = self._make_url('stdin')
  132. self.log.debug("connecting stdin channel to %s", url)
  133. socket = self.connect_stdin(identity=self.session.bsession)
  134. self._stdin_channel = self.stdin_channel_class(
  135. socket, self.session, self.ioloop
  136. )
  137. return self._stdin_channel
  138. @property
  139. def hb_channel(self):
  140. """Get the hb channel object for this kernel."""
  141. if self._hb_channel is None:
  142. url = self._make_url('hb')
  143. self.log.debug("connecting heartbeat channel to %s", url)
  144. self._hb_channel = self.hb_channel_class(
  145. self.context, self.session, url
  146. )
  147. return self._hb_channel
  148. def is_alive(self):
  149. """Is the kernel process still running?"""
  150. from .manager import KernelManager
  151. if isinstance(self.parent, KernelManager):
  152. # This KernelClient was created by a KernelManager,
  153. # we can ask the parent KernelManager:
  154. return self.parent.is_alive()
  155. if self._hb_channel is not None:
  156. # We don't have access to the KernelManager,
  157. # so we use the heartbeat.
  158. return self._hb_channel.is_beating()
  159. else:
  160. # no heartbeat and not local, we can't tell if it's running,
  161. # so naively return True
  162. return True
  163. # Methods to send specific messages on channels
  164. def execute(self, code, silent=False, store_history=True,
  165. user_expressions=None, allow_stdin=None, stop_on_error=True):
  166. """Execute code in the kernel.
  167. Parameters
  168. ----------
  169. code : str
  170. A string of code in the kernel's language.
  171. silent : bool, optional (default False)
  172. If set, the kernel will execute the code as quietly possible, and
  173. will force store_history to be False.
  174. store_history : bool, optional (default True)
  175. If set, the kernel will store command history. This is forced
  176. to be False if silent is True.
  177. user_expressions : dict, optional
  178. A dict mapping names to expressions to be evaluated in the user's
  179. dict. The expression values are returned as strings formatted using
  180. :func:`repr`.
  181. allow_stdin : bool, optional (default self.allow_stdin)
  182. Flag for whether the kernel can send stdin requests to frontends.
  183. Some frontends (e.g. the Notebook) do not support stdin requests.
  184. If raw_input is called from code executed from such a frontend, a
  185. StdinNotImplementedError will be raised.
  186. stop_on_error: bool, optional (default True)
  187. Flag whether to abort the execution queue, if an exception is encountered.
  188. Returns
  189. -------
  190. The msg_id of the message sent.
  191. """
  192. if user_expressions is None:
  193. user_expressions = {}
  194. if allow_stdin is None:
  195. allow_stdin = self.allow_stdin
  196. # Don't waste network traffic if inputs are invalid
  197. if not isinstance(code, string_types):
  198. raise ValueError('code %r must be a string' % code)
  199. validate_string_dict(user_expressions)
  200. # Create class for content/msg creation. Related to, but possibly
  201. # not in Session.
  202. content = dict(code=code, silent=silent, store_history=store_history,
  203. user_expressions=user_expressions,
  204. allow_stdin=allow_stdin, stop_on_error=stop_on_error
  205. )
  206. msg = self.session.msg('execute_request', content)
  207. self.shell_channel.send(msg)
  208. return msg['header']['msg_id']
  209. def complete(self, code, cursor_pos=None):
  210. """Tab complete text in the kernel's namespace.
  211. Parameters
  212. ----------
  213. code : str
  214. The context in which completion is requested.
  215. Can be anything between a variable name and an entire cell.
  216. cursor_pos : int, optional
  217. The position of the cursor in the block of code where the completion was requested.
  218. Default: ``len(code)``
  219. Returns
  220. -------
  221. The msg_id of the message sent.
  222. """
  223. if cursor_pos is None:
  224. cursor_pos = len(code)
  225. content = dict(code=code, cursor_pos=cursor_pos)
  226. msg = self.session.msg('complete_request', content)
  227. self.shell_channel.send(msg)
  228. return msg['header']['msg_id']
  229. def inspect(self, code, cursor_pos=None, detail_level=0):
  230. """Get metadata information about an object in the kernel's namespace.
  231. It is up to the kernel to determine the appropriate object to inspect.
  232. Parameters
  233. ----------
  234. code : str
  235. The context in which info is requested.
  236. Can be anything between a variable name and an entire cell.
  237. cursor_pos : int, optional
  238. The position of the cursor in the block of code where the info was requested.
  239. Default: ``len(code)``
  240. detail_level : int, optional
  241. The level of detail for the introspection (0-2)
  242. Returns
  243. -------
  244. The msg_id of the message sent.
  245. """
  246. if cursor_pos is None:
  247. cursor_pos = len(code)
  248. content = dict(code=code, cursor_pos=cursor_pos,
  249. detail_level=detail_level,
  250. )
  251. msg = self.session.msg('inspect_request', content)
  252. self.shell_channel.send(msg)
  253. return msg['header']['msg_id']
  254. def history(self, raw=True, output=False, hist_access_type='range', **kwargs):
  255. """Get entries from the kernel's history list.
  256. Parameters
  257. ----------
  258. raw : bool
  259. If True, return the raw input.
  260. output : bool
  261. If True, then return the output as well.
  262. hist_access_type : str
  263. 'range' (fill in session, start and stop params), 'tail' (fill in n)
  264. or 'search' (fill in pattern param).
  265. session : int
  266. For a range request, the session from which to get lines. Session
  267. numbers are positive integers; negative ones count back from the
  268. current session.
  269. start : int
  270. The first line number of a history range.
  271. stop : int
  272. The final (excluded) line number of a history range.
  273. n : int
  274. The number of lines of history to get for a tail request.
  275. pattern : str
  276. The glob-syntax pattern for a search request.
  277. Returns
  278. -------
  279. The ID of the message sent.
  280. """
  281. if hist_access_type == 'range':
  282. kwargs.setdefault('session', 0)
  283. kwargs.setdefault('start', 0)
  284. content = dict(raw=raw, output=output, hist_access_type=hist_access_type,
  285. **kwargs)
  286. msg = self.session.msg('history_request', content)
  287. self.shell_channel.send(msg)
  288. return msg['header']['msg_id']
  289. def kernel_info(self):
  290. """Request kernel info
  291. Returns
  292. -------
  293. The msg_id of the message sent
  294. """
  295. msg = self.session.msg('kernel_info_request')
  296. self.shell_channel.send(msg)
  297. return msg['header']['msg_id']
  298. def comm_info(self, target_name=None):
  299. """Request comm info
  300. Returns
  301. -------
  302. The msg_id of the message sent
  303. """
  304. if target_name is None:
  305. content = {}
  306. else:
  307. content = dict(target_name=target_name)
  308. msg = self.session.msg('comm_info_request', content)
  309. self.shell_channel.send(msg)
  310. return msg['header']['msg_id']
  311. def _handle_kernel_info_reply(self, msg):
  312. """handle kernel info reply
  313. sets protocol adaptation version. This might
  314. be run from a separate thread.
  315. """
  316. adapt_version = int(msg['content']['protocol_version'].split('.')[0])
  317. if adapt_version != major_protocol_version:
  318. self.session.adapt_version = adapt_version
  319. def shutdown(self, restart=False):
  320. """Request an immediate kernel shutdown.
  321. Upon receipt of the (empty) reply, client code can safely assume that
  322. the kernel has shut down and it's safe to forcefully terminate it if
  323. it's still alive.
  324. The kernel will send the reply via a function registered with Python's
  325. atexit module, ensuring it's truly done as the kernel is done with all
  326. normal operation.
  327. Returns
  328. -------
  329. The msg_id of the message sent
  330. """
  331. # Send quit message to kernel. Once we implement kernel-side setattr,
  332. # this should probably be done that way, but for now this will do.
  333. msg = self.session.msg('shutdown_request', {'restart':restart})
  334. self.shell_channel.send(msg)
  335. return msg['header']['msg_id']
  336. def is_complete(self, code):
  337. """Ask the kernel whether some code is complete and ready to execute."""
  338. msg = self.session.msg('is_complete_request', {'code': code})
  339. self.shell_channel.send(msg)
  340. return msg['header']['msg_id']
  341. def input(self, string):
  342. """Send a string of raw input to the kernel.
  343. This should only be called in response to the kernel sending an
  344. ``input_request`` message on the stdin channel.
  345. """
  346. content = dict(value=string)
  347. msg = self.session.msg('input_reply', content)
  348. self.stdin_channel.send(msg)
  349. KernelClientABC.register(KernelClient)