You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

344 lines
12 KiB

4 years ago
  1. """Terminal management for exposing terminals to a web interface using Tornado.
  2. """
  3. # Copyright (c) Jupyter Development Team
  4. # Copyright (c) 2014, Ramalingam Saravanan <sarava@sarava.net>
  5. # Distributed under the terms of the Simplified BSD License.
  6. from __future__ import absolute_import, print_function
  7. import sys
  8. if sys.version_info[0] < 3:
  9. byte_code = ord
  10. else:
  11. byte_code = lambda x: x
  12. unicode = str
  13. from collections import deque
  14. import itertools
  15. import logging
  16. import os
  17. import signal
  18. try:
  19. from ptyprocess import PtyProcessUnicode
  20. except ImportError:
  21. from winpty import PtyProcess as PtyProcessUnicode
  22. from tornado import gen
  23. from tornado.ioloop import IOLoop
  24. ENV_PREFIX = "PYXTERM_" # Environment variable prefix
  25. DEFAULT_TERM_TYPE = "xterm"
  26. class PtyWithClients(object):
  27. def __init__(self, ptyproc):
  28. self.ptyproc = ptyproc
  29. self.clients = []
  30. # Store the last few things read, so when a new client connects,
  31. # it can show e.g. the most recent prompt, rather than absolutely
  32. # nothing.
  33. self.read_buffer = deque([], maxlen=10)
  34. def resize_to_smallest(self):
  35. """Set the terminal size to that of the smallest client dimensions.
  36. A terminal not using the full space available is much nicer than a
  37. terminal trying to use more than the available space, so we keep it
  38. sized to the smallest client.
  39. """
  40. minrows = mincols = 10001
  41. for client in self.clients:
  42. rows, cols = client.size
  43. if rows is not None and rows < minrows:
  44. minrows = rows
  45. if cols is not None and cols < mincols:
  46. mincols = cols
  47. if minrows == 10001 or mincols == 10001:
  48. return
  49. rows, cols = self.ptyproc.getwinsize()
  50. if (rows, cols) != (minrows, mincols):
  51. self.ptyproc.setwinsize(minrows, mincols)
  52. def kill(self, sig=signal.SIGTERM):
  53. """Send a signal to the process in the pty"""
  54. self.ptyproc.kill(sig)
  55. def killpg(self, sig=signal.SIGTERM):
  56. """Send a signal to the process group of the process in the pty"""
  57. if os.name == 'nt':
  58. return self.ptyproc.kill(sig)
  59. pgid = os.getpgid(self.ptyproc.pid)
  60. os.killpg(pgid, sig)
  61. @gen.coroutine
  62. def terminate(self, force=False):
  63. '''This forces a child process to terminate. It starts nicely with
  64. SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
  65. returns True if the child was terminated. This returns False if the
  66. child could not be terminated. '''
  67. if os.name == 'nt':
  68. signals = [signal.SIGINT, signal.SIGTERM]
  69. else:
  70. signals = [signal.SIGHUP, signal.SIGCONT, signal.SIGINT,
  71. signal.SIGTERM]
  72. loop = IOLoop.current()
  73. sleep = lambda : gen.Task(loop.add_timeout, loop.time() + self.ptyproc.delayafterterminate)
  74. if not self.ptyproc.isalive():
  75. raise gen.Return(True)
  76. try:
  77. for sig in signals:
  78. self.kill(sig)
  79. yield sleep()
  80. if not self.ptyproc.isalive():
  81. raise gen.Return(True)
  82. if force:
  83. self.kill(signal.SIGKILL)
  84. yield sleep()
  85. if not self.ptyproc.isalive():
  86. raise gen.Return(True)
  87. else:
  88. raise gen.Return(False)
  89. raise gen.Return(False)
  90. except OSError:
  91. # I think there are kernel timing issues that sometimes cause
  92. # this to happen. I think isalive() reports True, but the
  93. # process is dead to the kernel.
  94. # Make one last attempt to see if the kernel is up to date.
  95. yield sleep()
  96. if not self.ptyproc.isalive():
  97. raise gen.Return(True)
  98. else:
  99. raise gen.Return(False)
  100. def _update_removing(target, changes):
  101. """Like dict.update(), but remove keys where the value is None.
  102. """
  103. for k, v in changes.items():
  104. if v is None:
  105. target.pop(k, None)
  106. else:
  107. target[k] = v
  108. class TermManagerBase(object):
  109. """Base class for a terminal manager."""
  110. def __init__(self, shell_command, server_url="", term_settings={},
  111. extra_env=None, ioloop=None):
  112. self.shell_command = shell_command
  113. self.server_url = server_url
  114. self.term_settings = term_settings
  115. self.extra_env = extra_env
  116. self.log = logging.getLogger(__name__)
  117. self.ptys_by_fd = {}
  118. if ioloop is not None:
  119. self.ioloop = ioloop
  120. else:
  121. import tornado.ioloop
  122. self.ioloop = tornado.ioloop.IOLoop.instance()
  123. def make_term_env(self, height=25, width=80, winheight=0, winwidth=0, **kwargs):
  124. """Build the environment variables for the process in the terminal."""
  125. env = os.environ.copy()
  126. env["TERM"] = self.term_settings.get("type",DEFAULT_TERM_TYPE)
  127. dimensions = "%dx%d" % (width, height)
  128. if winwidth and winheight:
  129. dimensions += ";%dx%d" % (winwidth, winheight)
  130. env[ENV_PREFIX+"DIMENSIONS"] = dimensions
  131. env["COLUMNS"] = str(width)
  132. env["LINES"] = str(height)
  133. if self.server_url:
  134. env[ENV_PREFIX+"URL"] = self.server_url
  135. if self.extra_env:
  136. _update_removing(env, self.extra_env)
  137. return env
  138. def new_terminal(self, **kwargs):
  139. """Make a new terminal, return a :class:`PtyWithClients` instance."""
  140. options = self.term_settings.copy()
  141. options['shell_command'] = self.shell_command
  142. options.update(kwargs)
  143. argv = options['shell_command']
  144. env = self.make_term_env(**options)
  145. pty = PtyProcessUnicode.spawn(argv, env=env, cwd=options.get('cwd', None))
  146. return PtyWithClients(pty)
  147. def start_reading(self, ptywclients):
  148. """Connect a terminal to the tornado event loop to read data from it."""
  149. fd = ptywclients.ptyproc.fd
  150. self.ptys_by_fd[fd] = ptywclients
  151. self.ioloop.add_handler(fd, self.pty_read, self.ioloop.READ)
  152. def on_eof(self, ptywclients):
  153. """Called when the pty has closed.
  154. """
  155. # Stop trying to read from that terminal
  156. fd = ptywclients.ptyproc.fd
  157. self.log.info("EOF on FD %d; stopping reading", fd)
  158. del self.ptys_by_fd[fd]
  159. self.ioloop.remove_handler(fd)
  160. # This closes the fd, and should result in the process being reaped.
  161. ptywclients.ptyproc.close()
  162. def pty_read(self, fd, events=None):
  163. """Called by the event loop when there is pty data ready to read."""
  164. ptywclients = self.ptys_by_fd[fd]
  165. try:
  166. s = ptywclients.ptyproc.read(65536)
  167. ptywclients.read_buffer.append(s)
  168. for client in ptywclients.clients:
  169. client.on_pty_read(s)
  170. except EOFError:
  171. self.on_eof(ptywclients)
  172. for client in ptywclients.clients:
  173. client.on_pty_died()
  174. def get_terminal(self, url_component=None):
  175. """Override in a subclass to give a terminal to a new websocket connection
  176. The :class:`TermSocket` handler works with zero or one URL components
  177. (capturing groups in the URL spec regex). If it receives one, it is
  178. passed as the ``url_component`` parameter; otherwise, this is None.
  179. """
  180. raise NotImplementedError
  181. def client_disconnected(self, websocket):
  182. """Override this to e.g. kill terminals on client disconnection.
  183. """
  184. pass
  185. @gen.coroutine
  186. def shutdown(self):
  187. yield self.kill_all()
  188. @gen.coroutine
  189. def kill_all(self):
  190. futures = []
  191. for term in self.ptys_by_fd.values():
  192. futures.append(term.terminate(force=True))
  193. # wait for futures to finish
  194. for f in futures:
  195. yield f
  196. class SingleTermManager(TermManagerBase):
  197. """All connections to the websocket share a common terminal."""
  198. def __init__(self, **kwargs):
  199. super(SingleTermManager, self).__init__(**kwargs)
  200. self.terminal = None
  201. def get_terminal(self, url_component=None):
  202. if self.terminal is None:
  203. self.terminal = self.new_terminal()
  204. self.start_reading(self.terminal)
  205. return self.terminal
  206. @gen.coroutine
  207. def kill_all(self):
  208. yield super(SingleTermManager, self).kill_all()
  209. self.terminal = None
  210. class MaxTerminalsReached(Exception):
  211. def __init__(self, max_terminals):
  212. self.max_terminals = max_terminals
  213. def __str__(self):
  214. return "Cannot create more than %d terminals" % self.max_terminals
  215. class UniqueTermManager(TermManagerBase):
  216. """Give each websocket a unique terminal to use."""
  217. def __init__(self, max_terminals=None, **kwargs):
  218. super(UniqueTermManager, self).__init__(**kwargs)
  219. self.max_terminals = max_terminals
  220. def get_terminal(self, url_component=None):
  221. if self.max_terminals and len(self.ptys_by_fd) >= self.max_terminals:
  222. raise MaxTerminalsReached(self.max_terminals)
  223. term = self.new_terminal()
  224. self.start_reading(term)
  225. return term
  226. def client_disconnected(self, websocket):
  227. """Send terminal SIGHUP when client disconnects."""
  228. self.log.info("Websocket closed, sending SIGHUP to terminal.")
  229. if websocket.terminal:
  230. if os.name == 'nt':
  231. websocket.terminal.kill()
  232. # Immediately call the pty reader to process
  233. # the eof and free up space
  234. self.pty_read(websocket.terminal.ptyproc.fd)
  235. return
  236. websocket.terminal.killpg(signal.SIGHUP)
  237. class NamedTermManager(TermManagerBase):
  238. """Share terminals between websockets connected to the same endpoint.
  239. """
  240. def __init__(self, max_terminals=None, **kwargs):
  241. super(NamedTermManager, self).__init__(**kwargs)
  242. self.max_terminals = max_terminals
  243. self.terminals = {}
  244. def get_terminal(self, term_name):
  245. assert term_name is not None
  246. if term_name in self.terminals:
  247. return self.terminals[term_name]
  248. if self.max_terminals and len(self.terminals) >= self.max_terminals:
  249. raise MaxTerminalsReached(self.max_terminals)
  250. # Create new terminal
  251. self.log.info("New terminal with specified name: %s", term_name)
  252. term = self.new_terminal()
  253. term.term_name = term_name
  254. self.terminals[term_name] = term
  255. self.start_reading(term)
  256. return term
  257. name_template = "%d"
  258. def _next_available_name(self):
  259. for n in itertools.count(start=1):
  260. name = self.name_template % n
  261. if name not in self.terminals:
  262. return name
  263. def new_named_terminal(self):
  264. name = self._next_available_name()
  265. term = self.new_terminal()
  266. self.log.info("New terminal with automatic name: %s", name)
  267. term.term_name = name
  268. self.terminals[name] = term
  269. self.start_reading(term)
  270. return name, term
  271. def kill(self, name, sig=signal.SIGTERM):
  272. term = self.terminals[name]
  273. term.kill(sig) # This should lead to an EOF
  274. @gen.coroutine
  275. def terminate(self, name, force=False):
  276. term = self.terminals[name]
  277. yield term.terminate(force=force)
  278. def on_eof(self, ptywclients):
  279. super(NamedTermManager, self).on_eof(ptywclients)
  280. name = ptywclients.term_name
  281. self.log.info("Terminal %s closed", name)
  282. self.terminals.pop(name, None)
  283. @gen.coroutine
  284. def kill_all(self):
  285. yield super(NamedTermManager, self).kill_all()
  286. self.terminals = {}