process.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """JupyterLab Server process handler"""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import atexit
  6. import logging
  7. import os
  8. import re
  9. import signal
  10. import subprocess
  11. import sys
  12. import threading
  13. import time
  14. import weakref
  15. from logging import Logger
  16. from shutil import which as _which
  17. from typing import Any
  18. from tornado import gen
  19. try:
  20. import pty
  21. except ImportError:
  22. pty = None # type:ignore[assignment]
  23. if sys.platform == "win32":
  24. list2cmdline = subprocess.list2cmdline
  25. else:
  26. def list2cmdline(cmd_list: list[str]) -> str:
  27. """Shim for list2cmdline on posix."""
  28. import shlex
  29. return " ".join(map(shlex.quote, cmd_list))
  30. def which(command: str, env: dict[str, str] | None = None) -> str:
  31. """Get the full path to a command.
  32. Parameters
  33. ----------
  34. command: str
  35. The command name or path.
  36. env: dict, optional
  37. The environment variables, defaults to `os.environ`.
  38. """
  39. env = env or os.environ # type:ignore[assignment]
  40. path = env.get("PATH") or os.defpath # type:ignore[union-attr]
  41. command_with_path = _which(command, path=path)
  42. # Allow nodejs as an alias to node.
  43. if command == "node" and not command_with_path:
  44. command = "nodejs"
  45. command_with_path = _which("nodejs", path=path)
  46. if not command_with_path:
  47. if command in ["nodejs", "node", "npm"]:
  48. msg = "Please install Node.js and npm before continuing installation. You may be able to install Node.js from your package manager, from conda, or directly from the Node.js website (https://nodejs.org)."
  49. raise ValueError(msg)
  50. raise ValueError("The command was not found or was not " + "executable: %s." % command)
  51. return os.path.abspath(command_with_path)
  52. class Process:
  53. """A wrapper for a child process."""
  54. _procs: weakref.WeakSet = weakref.WeakSet()
  55. _pool = None
  56. def __init__(
  57. self,
  58. cmd: list[str],
  59. logger: Logger | None = None,
  60. cwd: str | None = None,
  61. kill_event: threading.Event | None = None,
  62. env: dict[str, str] | None = None,
  63. quiet: bool = False,
  64. ) -> None:
  65. """Start a subprocess that can be run asynchronously.
  66. Parameters
  67. ----------
  68. cmd: list
  69. The command to run.
  70. logger: :class:`~logger.Logger`, optional
  71. The logger instance.
  72. cwd: string, optional
  73. The cwd of the process.
  74. env: dict, optional
  75. The environment for the process.
  76. kill_event: :class:`~threading.Event`, optional
  77. An event used to kill the process operation.
  78. quiet: bool, optional
  79. Whether to suppress output.
  80. """
  81. if not isinstance(cmd, (list, tuple)):
  82. msg = "Command must be given as a list" # type:ignore[unreachable]
  83. raise ValueError(msg)
  84. if kill_event and kill_event.is_set():
  85. msg = "Process aborted"
  86. raise ValueError(msg)
  87. self.logger = logger or self.get_log()
  88. self._last_line = ""
  89. if not quiet:
  90. self.logger.info("> %s", list2cmdline(cmd))
  91. self.cmd = cmd
  92. kwargs = {}
  93. if quiet:
  94. kwargs["stdout"] = subprocess.DEVNULL
  95. self.proc = self._create_process(cwd=cwd, env=env, **kwargs)
  96. self._kill_event = kill_event or threading.Event()
  97. Process._procs.add(self)
  98. def terminate(self) -> int:
  99. """Terminate the process and return the exit code."""
  100. proc = self.proc
  101. # Kill the process.
  102. if proc.poll() is None:
  103. os.kill(proc.pid, signal.SIGTERM)
  104. # Wait for the process to close.
  105. try:
  106. proc.wait(timeout=2.0)
  107. except subprocess.TimeoutExpired:
  108. if os.name == "nt": # noqa: SIM108
  109. sig = signal.SIGBREAK # type:ignore[attr-defined]
  110. else:
  111. sig = signal.SIGKILL
  112. if proc.poll() is None:
  113. os.kill(proc.pid, sig)
  114. finally:
  115. if self in Process._procs:
  116. Process._procs.remove(self)
  117. return proc.wait()
  118. def wait(self) -> int:
  119. """Wait for the process to finish.
  120. Returns
  121. -------
  122. The process exit code.
  123. """
  124. proc = self.proc
  125. kill_event = self._kill_event
  126. while proc.poll() is None:
  127. if kill_event.is_set():
  128. self.terminate()
  129. msg = "Process was aborted"
  130. raise ValueError(msg)
  131. time.sleep(1.0)
  132. return self.terminate()
  133. @gen.coroutine
  134. def wait_async(self) -> Any:
  135. """Asynchronously wait for the process to finish."""
  136. proc = self.proc
  137. kill_event = self._kill_event
  138. while proc.poll() is None:
  139. if kill_event.is_set():
  140. self.terminate()
  141. msg = "Process was aborted"
  142. raise ValueError(msg)
  143. yield gen.sleep(1.0)
  144. raise gen.Return(self.terminate())
  145. def _create_process(self, **kwargs: Any) -> subprocess.Popen[str]:
  146. """Create the process."""
  147. cmd = list(self.cmd)
  148. kwargs.setdefault("stderr", subprocess.STDOUT)
  149. cmd[0] = which(cmd[0], kwargs.get("env"))
  150. if os.name == "nt":
  151. kwargs["shell"] = True
  152. return subprocess.Popen(cmd, **kwargs) # noqa: S603
  153. @classmethod
  154. def _cleanup(cls: type[Process]) -> None:
  155. """Clean up the started subprocesses at exit."""
  156. for proc in list(cls._procs):
  157. proc.terminate()
  158. def get_log(self) -> Logger:
  159. """Get our logger."""
  160. if hasattr(self, "logger") and self.logger is not None:
  161. return self.logger
  162. # fallback logger
  163. self.logger = logging.getLogger("jupyterlab")
  164. self.logger.setLevel(logging.INFO)
  165. return self.logger
  166. class WatchHelper(Process):
  167. """A process helper for a watch process."""
  168. def __init__(
  169. self,
  170. cmd: list[str],
  171. startup_regex: str,
  172. logger: Logger | None = None,
  173. cwd: str | None = None,
  174. kill_event: threading.Event | None = None,
  175. env: dict[str, str] | None = None,
  176. ) -> None:
  177. """Initialize the process helper.
  178. Parameters
  179. ----------
  180. cmd: list
  181. The command to run.
  182. startup_regex: string
  183. The regex to wait for at startup.
  184. logger: :class:`~logger.Logger`, optional
  185. The logger instance.
  186. cwd: string, optional
  187. The cwd of the process.
  188. env: dict, optional
  189. The environment for the process.
  190. kill_event: callable, optional
  191. A function to call to check if we should abort.
  192. """
  193. super().__init__(cmd, logger=logger, cwd=cwd, kill_event=kill_event, env=env)
  194. if pty is None:
  195. self._stdout = self.proc.stdout # type:ignore[unreachable]
  196. while 1:
  197. line = self._stdout.readline().decode("utf-8") # type:ignore[has-type]
  198. if not line:
  199. msg = "Process ended improperly"
  200. raise RuntimeError(msg)
  201. print(line.rstrip())
  202. if re.match(startup_regex, line):
  203. break
  204. self._read_thread = threading.Thread(target=self._read_incoming, daemon=True)
  205. self._read_thread.start()
  206. def terminate(self) -> int:
  207. """Terminate the process."""
  208. proc = self.proc
  209. if proc.poll() is None:
  210. if os.name != "nt":
  211. # Kill the process group if we started a new session.
  212. os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
  213. else:
  214. os.kill(proc.pid, signal.SIGTERM)
  215. # Wait for the process to close.
  216. try:
  217. proc.wait()
  218. finally:
  219. if self in Process._procs:
  220. Process._procs.remove(self)
  221. return proc.returncode
  222. def _read_incoming(self) -> None:
  223. """Run in a thread to read stdout and print"""
  224. fileno = self._stdout.fileno() # type:ignore[has-type]
  225. while 1:
  226. try:
  227. buf = os.read(fileno, 1024)
  228. except OSError as e:
  229. self.logger.debug("Read incoming error %s", e)
  230. return
  231. if not buf:
  232. return
  233. print(buf.decode("utf-8"), end="")
  234. def _create_process(self, **kwargs: Any) -> subprocess.Popen[str]:
  235. """Create the watcher helper process."""
  236. kwargs["bufsize"] = 0
  237. if pty is not None:
  238. master, slave = pty.openpty()
  239. kwargs["stderr"] = kwargs["stdout"] = slave
  240. kwargs["start_new_session"] = True
  241. self._stdout = os.fdopen(master, "rb") # type:ignore[has-type]
  242. else:
  243. kwargs["stdout"] = subprocess.PIPE # type:ignore[unreachable]
  244. if os.name == "nt":
  245. startupinfo = subprocess.STARTUPINFO()
  246. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  247. kwargs["startupinfo"] = startupinfo
  248. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  249. kwargs["shell"] = True
  250. return super()._create_process(**kwargs)
  251. # Register the cleanup handler.
  252. atexit.register(Process._cleanup)