connect.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. """Utilities for connecting to jupyter kernels
  2. The :class:`ConnectionFileMixin` class in this module encapsulates the logic
  3. related to writing and reading connections files.
  4. """
  5. # Copyright (c) Jupyter Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from __future__ import absolute_import
  8. import errno
  9. import glob
  10. import json
  11. import os
  12. import socket
  13. import stat
  14. import tempfile
  15. import warnings
  16. from getpass import getpass
  17. from contextlib import contextmanager
  18. import zmq
  19. from traitlets.config import LoggingConfigurable
  20. from .localinterfaces import localhost
  21. from ipython_genutils.path import filefind
  22. from ipython_genutils.py3compat import (
  23. bytes_to_str, cast_bytes, cast_bytes_py2, string_types,
  24. )
  25. from traitlets import (
  26. Bool, Integer, Unicode, CaselessStrEnum, Instance, Type,
  27. )
  28. from jupyter_core.paths import jupyter_data_dir, jupyter_runtime_dir, secure_write
  29. def write_connection_file(fname=None, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0,
  30. control_port=0, ip='', key=b'', transport='tcp',
  31. signature_scheme='hmac-sha256', kernel_name=''
  32. ):
  33. """Generates a JSON config file, including the selection of random ports.
  34. Parameters
  35. ----------
  36. fname : unicode
  37. The path to the file to write
  38. shell_port : int, optional
  39. The port to use for ROUTER (shell) channel.
  40. iopub_port : int, optional
  41. The port to use for the SUB channel.
  42. stdin_port : int, optional
  43. The port to use for the ROUTER (raw input) channel.
  44. control_port : int, optional
  45. The port to use for the ROUTER (control) channel.
  46. hb_port : int, optional
  47. The port to use for the heartbeat REP channel.
  48. ip : str, optional
  49. The ip address the kernel will bind to.
  50. key : str, optional
  51. The Session key used for message authentication.
  52. signature_scheme : str, optional
  53. The scheme used for message authentication.
  54. This has the form 'digest-hash', where 'digest'
  55. is the scheme used for digests, and 'hash' is the name of the hash function
  56. used by the digest scheme.
  57. Currently, 'hmac' is the only supported digest scheme,
  58. and 'sha256' is the default hash function.
  59. kernel_name : str, optional
  60. The name of the kernel currently connected to.
  61. """
  62. if not ip:
  63. ip = localhost()
  64. # default to temporary connector file
  65. if not fname:
  66. fd, fname = tempfile.mkstemp('.json')
  67. os.close(fd)
  68. # Find open ports as necessary.
  69. ports = []
  70. ports_needed = int(shell_port <= 0) + \
  71. int(iopub_port <= 0) + \
  72. int(stdin_port <= 0) + \
  73. int(control_port <= 0) + \
  74. int(hb_port <= 0)
  75. if transport == 'tcp':
  76. for i in range(ports_needed):
  77. sock = socket.socket()
  78. # struct.pack('ii', (0,0)) is 8 null bytes
  79. sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b'\0' * 8)
  80. sock.bind((ip, 0))
  81. ports.append(sock)
  82. for i, sock in enumerate(ports):
  83. port = sock.getsockname()[1]
  84. sock.close()
  85. ports[i] = port
  86. else:
  87. N = 1
  88. for i in range(ports_needed):
  89. while os.path.exists("%s-%s" % (ip, str(N))):
  90. N += 1
  91. ports.append(N)
  92. N += 1
  93. if shell_port <= 0:
  94. shell_port = ports.pop(0)
  95. if iopub_port <= 0:
  96. iopub_port = ports.pop(0)
  97. if stdin_port <= 0:
  98. stdin_port = ports.pop(0)
  99. if control_port <= 0:
  100. control_port = ports.pop(0)
  101. if hb_port <= 0:
  102. hb_port = ports.pop(0)
  103. cfg = dict( shell_port=shell_port,
  104. iopub_port=iopub_port,
  105. stdin_port=stdin_port,
  106. control_port=control_port,
  107. hb_port=hb_port,
  108. )
  109. cfg['ip'] = ip
  110. cfg['key'] = bytes_to_str(key)
  111. cfg['transport'] = transport
  112. cfg['signature_scheme'] = signature_scheme
  113. cfg['kernel_name'] = kernel_name
  114. # Only ever write this file as user read/writeable
  115. # This would otherwise introduce a vulnerability as a file has secrets
  116. # which would let others execute arbitrarily code as you
  117. with secure_write(fname) as f:
  118. f.write(json.dumps(cfg, indent=2))
  119. if hasattr(stat, 'S_ISVTX'):
  120. # set the sticky bit on the file and its parent directory
  121. # to avoid periodic cleanup
  122. paths = [fname]
  123. runtime_dir = os.path.dirname(fname)
  124. if runtime_dir:
  125. paths.append(runtime_dir)
  126. for path in paths:
  127. permissions = os.stat(path).st_mode
  128. new_permissions = permissions | stat.S_ISVTX
  129. if new_permissions != permissions:
  130. try:
  131. os.chmod(path, new_permissions)
  132. except OSError as e:
  133. if e.errno == errno.EPERM and path == runtime_dir:
  134. # suppress permission errors setting sticky bit on runtime_dir,
  135. # which we may not own.
  136. pass
  137. else:
  138. # failed to set sticky bit, probably not a big deal
  139. warnings.warn(
  140. "Failed to set sticky bit on %r: %s"
  141. "\nProbably not a big deal, but runtime files may be cleaned up periodically." % (path, e),
  142. RuntimeWarning,
  143. )
  144. return fname, cfg
  145. def find_connection_file(filename='kernel-*.json', path=None, profile=None):
  146. """find a connection file, and return its absolute path.
  147. The current working directory and optional search path
  148. will be searched for the file if it is not given by absolute path.
  149. If the argument does not match an existing file, it will be interpreted as a
  150. fileglob, and the matching file in the profile's security dir with
  151. the latest access time will be used.
  152. Parameters
  153. ----------
  154. filename : str
  155. The connection file or fileglob to search for.
  156. path : str or list of strs[optional]
  157. Paths in which to search for connection files.
  158. Returns
  159. -------
  160. str : The absolute path of the connection file.
  161. """
  162. if profile is not None:
  163. warnings.warn("Jupyter has no profiles. profile=%s has been ignored." % profile)
  164. if path is None:
  165. path = ['.', jupyter_runtime_dir()]
  166. if isinstance(path, string_types):
  167. path = [path]
  168. try:
  169. # first, try explicit name
  170. return filefind(filename, path)
  171. except IOError:
  172. pass
  173. # not found by full name
  174. if '*' in filename:
  175. # given as a glob already
  176. pat = filename
  177. else:
  178. # accept any substring match
  179. pat = '*%s*' % filename
  180. matches = []
  181. for p in path:
  182. matches.extend(glob.glob(os.path.join(p, pat)))
  183. matches = [ os.path.abspath(m) for m in matches ]
  184. if not matches:
  185. raise IOError("Could not find %r in %r" % (filename, path))
  186. elif len(matches) == 1:
  187. return matches[0]
  188. else:
  189. # get most recent match, by access time:
  190. return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
  191. def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
  192. """tunnel connections to a kernel via ssh
  193. This will open four SSH tunnels from localhost on this machine to the
  194. ports associated with the kernel. They can be either direct
  195. localhost-localhost tunnels, or if an intermediate server is necessary,
  196. the kernel must be listening on a public IP.
  197. Parameters
  198. ----------
  199. connection_info : dict or str (path)
  200. Either a connection dict, or the path to a JSON connection file
  201. sshserver : str
  202. The ssh sever to use to tunnel to the kernel. Can be a full
  203. `user@server:port` string. ssh config aliases are respected.
  204. sshkey : str [optional]
  205. Path to file containing ssh key to use for authentication.
  206. Only necessary if your ssh config does not already associate
  207. a keyfile with the host.
  208. Returns
  209. -------
  210. (shell, iopub, stdin, hb) : ints
  211. The four ports on localhost that have been forwarded to the kernel.
  212. """
  213. from zmq.ssh import tunnel
  214. if isinstance(connection_info, string_types):
  215. # it's a path, unpack it
  216. with open(connection_info) as f:
  217. connection_info = json.loads(f.read())
  218. cf = connection_info
  219. lports = tunnel.select_random_ports(4)
  220. rports = cf['shell_port'], cf['iopub_port'], cf['stdin_port'], cf['hb_port']
  221. remote_ip = cf['ip']
  222. if tunnel.try_passwordless_ssh(sshserver, sshkey):
  223. password=False
  224. else:
  225. password = getpass("SSH Password for %s: " % cast_bytes_py2(sshserver))
  226. for lp,rp in zip(lports, rports):
  227. tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password)
  228. return tuple(lports)
  229. #-----------------------------------------------------------------------------
  230. # Mixin for classes that work with connection files
  231. #-----------------------------------------------------------------------------
  232. channel_socket_types = {
  233. 'hb' : zmq.REQ,
  234. 'shell' : zmq.DEALER,
  235. 'iopub' : zmq.SUB,
  236. 'stdin' : zmq.DEALER,
  237. 'control': zmq.DEALER,
  238. }
  239. port_names = [ "%s_port" % channel for channel in ('shell', 'stdin', 'iopub', 'hb', 'control')]
  240. class ConnectionFileMixin(LoggingConfigurable):
  241. """Mixin for configurable classes that work with connection files"""
  242. data_dir = Unicode()
  243. def _data_dir_default(self):
  244. return jupyter_data_dir()
  245. # The addresses for the communication channels
  246. connection_file = Unicode('', config=True,
  247. help="""JSON file in which to store connection info [default: kernel-<pid>.json]
  248. This file will contain the IP, ports, and authentication key needed to connect
  249. clients to this kernel. By default, this file will be created in the security dir
  250. of the current profile, but can be specified by absolute path.
  251. """)
  252. _connection_file_written = Bool(False)
  253. transport = CaselessStrEnum(['tcp', 'ipc'], default_value='tcp', config=True)
  254. kernel_name = Unicode()
  255. ip = Unicode(config=True,
  256. help="""Set the kernel\'s IP address [default localhost].
  257. If the IP address is something other than localhost, then
  258. Consoles on other machines will be able to connect
  259. to the Kernel, so be careful!"""
  260. )
  261. def _ip_default(self):
  262. if self.transport == 'ipc':
  263. if self.connection_file:
  264. return os.path.splitext(self.connection_file)[0] + '-ipc'
  265. else:
  266. return 'kernel-ipc'
  267. else:
  268. return localhost()
  269. def _ip_changed(self, name, old, new):
  270. if new == '*':
  271. self.ip = '0.0.0.0'
  272. # protected traits
  273. hb_port = Integer(0, config=True,
  274. help="set the heartbeat port [default: random]")
  275. shell_port = Integer(0, config=True,
  276. help="set the shell (ROUTER) port [default: random]")
  277. iopub_port = Integer(0, config=True,
  278. help="set the iopub (PUB) port [default: random]")
  279. stdin_port = Integer(0, config=True,
  280. help="set the stdin (ROUTER) port [default: random]")
  281. control_port = Integer(0, config=True,
  282. help="set the control (ROUTER) port [default: random]")
  283. # names of the ports with random assignment
  284. _random_port_names = None
  285. @property
  286. def ports(self):
  287. return [ getattr(self, name) for name in port_names ]
  288. # The Session to use for communication with the kernel.
  289. session = Instance('jupyter_client.session.Session')
  290. def _session_default(self):
  291. from jupyter_client.session import Session
  292. return Session(parent=self)
  293. #--------------------------------------------------------------------------
  294. # Connection and ipc file management
  295. #--------------------------------------------------------------------------
  296. def get_connection_info(self, session=False):
  297. """Return the connection info as a dict
  298. Parameters
  299. ----------
  300. session : bool [default: False]
  301. If True, return our session object will be included in the connection info.
  302. If False (default), the configuration parameters of our session object will be included,
  303. rather than the session object itself.
  304. Returns
  305. -------
  306. connect_info : dict
  307. dictionary of connection information.
  308. """
  309. info = dict(
  310. transport=self.transport,
  311. ip=self.ip,
  312. shell_port=self.shell_port,
  313. iopub_port=self.iopub_port,
  314. stdin_port=self.stdin_port,
  315. hb_port=self.hb_port,
  316. control_port=self.control_port,
  317. )
  318. if session:
  319. # add *clone* of my session,
  320. # so that state such as digest_history is not shared.
  321. info['session'] = self.session.clone()
  322. else:
  323. # add session info
  324. info.update(dict(
  325. signature_scheme=self.session.signature_scheme,
  326. key=self.session.key,
  327. ))
  328. return info
  329. # factory for blocking clients
  330. blocking_class = Type(klass=object, default_value='jupyter_client.BlockingKernelClient')
  331. def blocking_client(self):
  332. """Make a blocking client connected to my kernel"""
  333. info = self.get_connection_info()
  334. info['parent'] = self
  335. bc = self.blocking_class(**info)
  336. bc.session.key = self.session.key
  337. return bc
  338. def cleanup_connection_file(self):
  339. """Cleanup connection file *if we wrote it*
  340. Will not raise if the connection file was already removed somehow.
  341. """
  342. if self._connection_file_written:
  343. # cleanup connection files on full shutdown of kernel we started
  344. self._connection_file_written = False
  345. try:
  346. os.remove(self.connection_file)
  347. except (IOError, OSError, AttributeError):
  348. pass
  349. def cleanup_ipc_files(self):
  350. """Cleanup ipc files if we wrote them."""
  351. if self.transport != 'ipc':
  352. return
  353. for port in self.ports:
  354. ipcfile = "%s-%i" % (self.ip, port)
  355. try:
  356. os.remove(ipcfile)
  357. except (IOError, OSError):
  358. pass
  359. def _record_random_port_names(self):
  360. """Records which of the ports are randomly assigned.
  361. Records on first invocation, if the transport is tcp.
  362. Does nothing on later invocations."""
  363. if self.transport != 'tcp':
  364. return
  365. if self._random_port_names is not None:
  366. return
  367. self._random_port_names = []
  368. for name in port_names:
  369. if getattr(self, name) <= 0:
  370. self._random_port_names.append(name)
  371. def cleanup_random_ports(self):
  372. """Forgets randomly assigned port numbers and cleans up the connection file.
  373. Does nothing if no port numbers have been randomly assigned.
  374. In particular, does nothing unless the transport is tcp.
  375. """
  376. if not self._random_port_names:
  377. return
  378. for name in self._random_port_names:
  379. setattr(self, name, 0)
  380. self.cleanup_connection_file()
  381. def write_connection_file(self):
  382. """Write connection info to JSON dict in self.connection_file."""
  383. if self._connection_file_written and os.path.exists(self.connection_file):
  384. return
  385. self.connection_file, cfg = write_connection_file(self.connection_file,
  386. transport=self.transport, ip=self.ip, key=self.session.key,
  387. stdin_port=self.stdin_port, iopub_port=self.iopub_port,
  388. shell_port=self.shell_port, hb_port=self.hb_port,
  389. control_port=self.control_port,
  390. signature_scheme=self.session.signature_scheme,
  391. kernel_name=self.kernel_name
  392. )
  393. # write_connection_file also sets default ports:
  394. self._record_random_port_names()
  395. for name in port_names:
  396. setattr(self, name, cfg[name])
  397. self._connection_file_written = True
  398. def load_connection_file(self, connection_file=None):
  399. """Load connection info from JSON dict in self.connection_file.
  400. Parameters
  401. ----------
  402. connection_file: unicode, optional
  403. Path to connection file to load.
  404. If unspecified, use self.connection_file
  405. """
  406. if connection_file is None:
  407. connection_file = self.connection_file
  408. self.log.debug(u"Loading connection file %s", connection_file)
  409. with open(connection_file) as f:
  410. info = json.load(f)
  411. self.load_connection_info(info)
  412. def load_connection_info(self, info):
  413. """Load connection info from a dict containing connection info.
  414. Typically this data comes from a connection file
  415. and is called by load_connection_file.
  416. Parameters
  417. ----------
  418. info: dict
  419. Dictionary containing connection_info.
  420. See the connection_file spec for details.
  421. """
  422. self.transport = info.get('transport', self.transport)
  423. self.ip = info.get('ip', self._ip_default())
  424. self._record_random_port_names()
  425. for name in port_names:
  426. if getattr(self, name) == 0 and name in info:
  427. # not overridden by config or cl_args
  428. setattr(self, name, info[name])
  429. if 'key' in info:
  430. self.session.key = cast_bytes(info['key'])
  431. if 'signature_scheme' in info:
  432. self.session.signature_scheme = info['signature_scheme']
  433. #--------------------------------------------------------------------------
  434. # Creating connected sockets
  435. #--------------------------------------------------------------------------
  436. def _make_url(self, channel):
  437. """Make a ZeroMQ URL for a given channel."""
  438. transport = self.transport
  439. ip = self.ip
  440. port = getattr(self, '%s_port' % channel)
  441. if transport == 'tcp':
  442. return "tcp://%s:%i" % (ip, port)
  443. else:
  444. return "%s://%s-%s" % (transport, ip, port)
  445. def _create_connected_socket(self, channel, identity=None):
  446. """Create a zmq Socket and connect it to the kernel."""
  447. url = self._make_url(channel)
  448. socket_type = channel_socket_types[channel]
  449. self.log.debug("Connecting to: %s" % url)
  450. sock = self.context.socket(socket_type)
  451. # set linger to 1s to prevent hangs at exit
  452. sock.linger = 1000
  453. if identity:
  454. sock.identity = identity
  455. sock.connect(url)
  456. return sock
  457. def connect_iopub(self, identity=None):
  458. """return zmq Socket connected to the IOPub channel"""
  459. sock = self._create_connected_socket('iopub', identity=identity)
  460. sock.setsockopt(zmq.SUBSCRIBE, b'')
  461. return sock
  462. def connect_shell(self, identity=None):
  463. """return zmq Socket connected to the Shell channel"""
  464. return self._create_connected_socket('shell', identity=identity)
  465. def connect_stdin(self, identity=None):
  466. """return zmq Socket connected to the StdIn channel"""
  467. return self._create_connected_socket('stdin', identity=identity)
  468. def connect_hb(self, identity=None):
  469. """return zmq Socket connected to the Heartbeat channel"""
  470. return self._create_connected_socket('hb', identity=identity)
  471. def connect_control(self, identity=None):
  472. """return zmq Socket connected to the Control channel"""
  473. return self._create_connected_socket('control', identity=identity)
  474. __all__ = [
  475. 'write_connection_file',
  476. 'find_connection_file',
  477. 'tunnel_to_kernel',
  478. ]