management.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 annotations
  7. import asyncio
  8. import codecs
  9. import itertools
  10. import logging
  11. import os
  12. import select
  13. import signal
  14. import warnings
  15. from collections import deque
  16. from concurrent import futures
  17. from typing import TYPE_CHECKING, Any, Coroutine
  18. if TYPE_CHECKING:
  19. from terminado.websocket import TermSocket
  20. try:
  21. from ptyprocess import PtyProcessUnicode # type:ignore[import-untyped]
  22. def preexec_fn() -> None:
  23. """A prexec function to set up a signal handler."""
  24. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  25. except ImportError:
  26. try:
  27. from winpty import PtyProcess as PtyProcessUnicode # type:ignore[import-not-found]
  28. except ImportError:
  29. PtyProcessUnicode = object
  30. preexec_fn = None # type:ignore[assignment]
  31. from tornado.ioloop import IOLoop
  32. ENV_PREFIX = "PYXTERM_" # Environment variable prefix
  33. # TERM is set according to xterm.js capabilities
  34. DEFAULT_TERM_TYPE = "xterm-256color"
  35. class PtyWithClients:
  36. """A pty object with associated clients."""
  37. term_name: str | None
  38. def __init__(self, argv: Any, env: dict[str, str] | None = None, cwd: str | None = None):
  39. """Initialize the pty."""
  40. self.clients: list[Any] = []
  41. # Use read_buffer to store historical messages for reconnection
  42. self.read_buffer: deque[str] = deque([], maxlen=1000)
  43. kwargs = {"argv": argv, "env": env or [], "cwd": cwd}
  44. if preexec_fn is not None:
  45. kwargs["preexec_fn"] = preexec_fn
  46. self.ptyproc = PtyProcessUnicode.spawn(**kwargs)
  47. # The output might not be strictly UTF-8 encoded, so
  48. # we replace the inner decoder of PtyProcessUnicode
  49. # to allow non-strict decode.
  50. self.ptyproc.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
  51. def resize_to_smallest(self) -> None:
  52. """Set the terminal size to that of the smallest client dimensions.
  53. A terminal not using the full space available is much nicer than a
  54. terminal trying to use more than the available space, so we keep it
  55. sized to the smallest client.
  56. """
  57. minrows = mincols = 10001
  58. for client in self.clients:
  59. rows, cols = client.size
  60. if rows is not None and rows < minrows:
  61. minrows = rows
  62. if cols is not None and cols < mincols:
  63. mincols = cols
  64. if minrows == 10001 or mincols == 10001:
  65. return
  66. rows, cols = self.ptyproc.getwinsize()
  67. if (rows, cols) != (minrows, mincols):
  68. self.ptyproc.setwinsize(minrows, mincols)
  69. def kill(self, sig: int = signal.SIGTERM) -> None:
  70. """Send a signal to the process in the pty"""
  71. self.ptyproc.kill(sig)
  72. def killpg(self, sig: int = signal.SIGTERM) -> Any:
  73. """Send a signal to the process group of the process in the pty"""
  74. if os.name == "nt":
  75. return self.ptyproc.kill(sig)
  76. pgid = os.getpgid(self.ptyproc.pid)
  77. os.killpg(pgid, sig)
  78. return None
  79. async def terminate(self, force: bool = False) -> bool:
  80. """This forces a child process to terminate. It starts nicely with
  81. SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
  82. returns True if the child was terminated. This returns False if the
  83. child could not be terminated."""
  84. if os.name == "nt":
  85. signals = [signal.SIGINT, signal.SIGTERM]
  86. else:
  87. signals = [signal.SIGHUP, signal.SIGCONT, signal.SIGINT, signal.SIGTERM]
  88. _ = IOLoop.current()
  89. def sleep() -> Coroutine[Any, Any, None]:
  90. """Sleep to allow the terminal to exit gracefully."""
  91. return asyncio.sleep(self.ptyproc.delayafterterminate)
  92. if not self.ptyproc.isalive():
  93. return True
  94. try:
  95. for sig in signals:
  96. self.kill(sig)
  97. await sleep()
  98. if not self.ptyproc.isalive():
  99. return True
  100. if force:
  101. self.kill(signal.SIGKILL)
  102. await sleep()
  103. return bool(not self.ptyproc.isalive())
  104. return False
  105. except OSError:
  106. # I think there are kernel timing issues that sometimes cause
  107. # this to happen. I think isalive() reports True, but the
  108. # process is dead to the kernel.
  109. # Make one last attempt to see if the kernel is up to date.
  110. await sleep()
  111. return bool(not self.ptyproc.isalive())
  112. def _update_removing(target: Any, changes: Any) -> None:
  113. """Like dict.update(), but remove keys where the value is None."""
  114. for k, v in changes.items():
  115. if v is None:
  116. target.pop(k, None)
  117. else:
  118. target[k] = v
  119. def _poll(fd: int, timeout: float = 0.1) -> list[tuple[int, int]]:
  120. """Poll using poll() on posix systems and select() elsewhere (e.g., Windows)"""
  121. if os.name == "posix":
  122. poller = select.poll()
  123. poller.register(
  124. fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR
  125. ) # read-only
  126. return poller.poll(timeout * 1000) # milliseconds
  127. # poll() not supported on Windows
  128. r, _, _ = select.select([fd], [], [], timeout)
  129. return r
  130. class TermManagerBase:
  131. """Base class for a terminal manager."""
  132. def __init__(
  133. self,
  134. shell_command: str,
  135. server_url: str = "",
  136. term_settings: Any = None,
  137. extra_env: Any = None,
  138. ioloop: Any = None,
  139. blocking_io_executor: Any = None,
  140. ):
  141. """Initialize the manager."""
  142. self.shell_command = shell_command
  143. self.server_url = server_url
  144. self.term_settings = term_settings or {}
  145. self.extra_env = extra_env
  146. self.log = logging.getLogger(__name__)
  147. self.ptys_by_fd: dict[int, PtyWithClients] = {}
  148. if blocking_io_executor is None:
  149. self._blocking_io_executor_is_external = False
  150. self.blocking_io_executor = futures.ThreadPoolExecutor(max_workers=1)
  151. else:
  152. self._blocking_io_executor_is_external = True
  153. self.blocking_io_executor = blocking_io_executor
  154. if ioloop is not None:
  155. warnings.warn(
  156. f"Setting {self.__class__.__name__}.ioloop is deprecated and ignored",
  157. DeprecationWarning,
  158. stacklevel=2,
  159. )
  160. def make_term_env(
  161. self,
  162. height: int = 25,
  163. width: int = 80,
  164. winheight: int = 0,
  165. winwidth: int = 0,
  166. **kwargs: Any,
  167. ) -> dict[str, str]:
  168. """Build the environment variables for the process in the terminal."""
  169. env = os.environ.copy()
  170. # ignore any previously set TERM
  171. # TERM is set according to xterm.js capabilities
  172. env["TERM"] = self.term_settings.get("type", DEFAULT_TERM_TYPE)
  173. dimensions = "%dx%d" % (width, height)
  174. if winwidth and winheight:
  175. dimensions += ";%dx%d" % (winwidth, winheight)
  176. env[ENV_PREFIX + "DIMENSIONS"] = dimensions
  177. env["COLUMNS"] = str(width)
  178. env["LINES"] = str(height)
  179. if self.server_url:
  180. env[ENV_PREFIX + "URL"] = self.server_url
  181. if self.extra_env:
  182. _update_removing(env, self.extra_env)
  183. term_env = kwargs.get("extra_env", {})
  184. if term_env and isinstance(term_env, dict):
  185. _update_removing(env, term_env)
  186. return env
  187. def new_terminal(self, **kwargs: Any) -> PtyWithClients:
  188. """Make a new terminal, return a :class:`PtyWithClients` instance."""
  189. options = self.term_settings.copy()
  190. options["shell_command"] = self.shell_command
  191. options.update(kwargs)
  192. argv = options["shell_command"]
  193. env = self.make_term_env(**options)
  194. cwd = options.get("cwd", None)
  195. return PtyWithClients(argv, env, cwd)
  196. def start_reading(self, ptywclients: PtyWithClients) -> None:
  197. """Connect a terminal to the tornado event loop to read data from it."""
  198. fd = ptywclients.ptyproc.fd
  199. self.ptys_by_fd[fd] = ptywclients
  200. loop = IOLoop.current()
  201. loop.add_handler(fd, self.pty_read, loop.READ)
  202. def on_eof(self, ptywclients: PtyWithClients) -> None:
  203. """Called when the pty has closed."""
  204. # Stop trying to read from that terminal
  205. fd = ptywclients.ptyproc.fd
  206. self.log.info("EOF on FD %d; stopping reading", fd)
  207. del self.ptys_by_fd[fd]
  208. IOLoop.current().remove_handler(fd)
  209. # This closes the fd, and should result in the process being reaped.
  210. ptywclients.ptyproc.close()
  211. def pty_read(self, fd: int, events: Any = None) -> None:
  212. """Called by the event loop when there is pty data ready to read."""
  213. # prevent blocking on fd
  214. if not _poll(fd, timeout=0.1): # 100ms
  215. self.log.debug("Spurious pty_read() on fd %s", fd)
  216. return
  217. ptywclients = self.ptys_by_fd[fd]
  218. try:
  219. self.pre_pty_read_hook(ptywclients)
  220. s = ptywclients.ptyproc.read(65536)
  221. ptywclients.read_buffer.append(s)
  222. for client in ptywclients.clients:
  223. client.on_pty_read(s)
  224. except EOFError:
  225. self.on_eof(ptywclients)
  226. for client in ptywclients.clients:
  227. client.on_pty_died()
  228. def pre_pty_read_hook(self, ptywclients: PtyWithClients) -> None:
  229. """Hook before pty read, subclass can patch something into ptywclients when pty_read"""
  230. def get_terminal(self, url_component: Any = None) -> PtyWithClients:
  231. """Override in a subclass to give a terminal to a new websocket connection
  232. The :class:`TermSocket` handler works with zero or one URL components
  233. (capturing groups in the URL spec regex). If it receives one, it is
  234. passed as the ``url_component`` parameter; otherwise, this is None.
  235. """
  236. raise NotImplementedError
  237. def client_disconnected(self, websocket: Any) -> None:
  238. """Override this to e.g. kill terminals on client disconnection."""
  239. async def shutdown(self) -> None:
  240. """Shutdown the manager."""
  241. await self.kill_all()
  242. if not self._blocking_io_executor_is_external:
  243. self.blocking_io_executor.shutdown(wait=False, cancel_futures=True) # type:ignore[call-arg]
  244. async def kill_all(self) -> None:
  245. """Kill all terminals."""
  246. futures = []
  247. for term in self.ptys_by_fd.values():
  248. futures.append(term.terminate(force=True))
  249. # wait for futures to finish
  250. if futures:
  251. await asyncio.gather(*futures)
  252. class SingleTermManager(TermManagerBase):
  253. """All connections to the websocket share a common terminal."""
  254. def __init__(self, **kwargs: Any) -> None:
  255. """Initialize the manager."""
  256. super().__init__(**kwargs)
  257. self.terminal: PtyWithClients | None = None
  258. def get_terminal(self, url_component: Any = None) -> PtyWithClients:
  259. """ "Get the singleton terminal."""
  260. if self.terminal is None:
  261. self.terminal = self.new_terminal()
  262. self.start_reading(self.terminal)
  263. return self.terminal
  264. async def kill_all(self) -> None:
  265. """Kill the singletone terminal."""
  266. await super().kill_all()
  267. self.terminal = None
  268. class MaxTerminalsReached(Exception):
  269. """An error raised when we exceed the max number of terminals."""
  270. def __init__(self, max_terminals: int) -> None:
  271. """Initialize the error."""
  272. self.max_terminals = max_terminals
  273. def __str__(self) -> str:
  274. """The string representation of the error."""
  275. return "Cannot create more than %d terminals" % self.max_terminals
  276. class UniqueTermManager(TermManagerBase):
  277. """Give each websocket a unique terminal to use."""
  278. def __init__(self, max_terminals: int | None = None, **kwargs: Any) -> None:
  279. """Initialize the manager."""
  280. super().__init__(**kwargs)
  281. self.max_terminals = max_terminals
  282. def get_terminal(self, url_component: Any = None) -> PtyWithClients:
  283. """Get a terminal from the manager."""
  284. if self.max_terminals and len(self.ptys_by_fd) >= self.max_terminals:
  285. raise MaxTerminalsReached(self.max_terminals)
  286. term = self.new_terminal()
  287. self.start_reading(term)
  288. return term
  289. def client_disconnected(self, websocket: TermSocket) -> None:
  290. """Send terminal SIGHUP when client disconnects."""
  291. self.log.info("Websocket closed, sending SIGHUP to terminal.")
  292. if websocket.terminal:
  293. if os.name == "nt":
  294. websocket.terminal.kill()
  295. # Immediately call the pty reader to process
  296. # the eof and free up space
  297. self.pty_read(websocket.terminal.ptyproc.fd)
  298. return
  299. websocket.terminal.killpg(signal.SIGHUP)
  300. class NamedTermManager(TermManagerBase):
  301. """Share terminals between websockets connected to the same endpoint."""
  302. def __init__(self, max_terminals: Any = None, **kwargs: Any) -> None:
  303. """Initialize the manager."""
  304. super().__init__(**kwargs)
  305. self.max_terminals = max_terminals
  306. self.terminals: dict[str, PtyWithClients] = {}
  307. def get_terminal(self, term_name: str) -> PtyWithClients: # type:ignore[override]
  308. """Get or create a terminal by name."""
  309. assert term_name is not None
  310. if term_name in self.terminals:
  311. return self.terminals[term_name]
  312. if self.max_terminals and len(self.terminals) >= self.max_terminals:
  313. raise MaxTerminalsReached(self.max_terminals)
  314. # Create new terminal
  315. self.log.info("New terminal with specified name: %s", term_name)
  316. term = self.new_terminal()
  317. term.term_name = term_name
  318. self.terminals[term_name] = term
  319. self.start_reading(term)
  320. return term
  321. name_template = "%d"
  322. def _next_available_name(self) -> str | None:
  323. for n in itertools.count(start=1):
  324. name = self.name_template % n
  325. if name not in self.terminals:
  326. return name
  327. return None
  328. def new_named_terminal(self, **kwargs: Any) -> tuple[str, PtyWithClients]:
  329. """Create a new named terminal with an automatic name."""
  330. name = kwargs["name"] if "name" in kwargs else self._next_available_name()
  331. term = self.new_terminal(**kwargs)
  332. self.log.info("New terminal with automatic name: %s", name)
  333. term.term_name = name
  334. self.terminals[name] = term
  335. self.start_reading(term)
  336. return name, term
  337. def kill(self, name: str, sig: int = signal.SIGTERM) -> None:
  338. """Kill a terminal by name."""
  339. term = self.terminals[name]
  340. term.kill(sig) # This should lead to an EOF
  341. async def terminate(self, name: str, force: bool = False) -> None:
  342. """Terminate a terminal by name."""
  343. term = self.terminals[name]
  344. await term.terminate(force=force)
  345. def on_eof(self, ptywclients: PtyWithClients) -> None:
  346. """Handle end of file for a pty with clients."""
  347. super().on_eof(ptywclients)
  348. name = ptywclients.term_name
  349. self.log.info("Terminal %s closed", name)
  350. assert name is not None
  351. self.terminals.pop(name, None)
  352. async def kill_all(self) -> None:
  353. """Kill all terminals."""
  354. await super().kill_all()
  355. self.terminals = {}