processes.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. """Process operations."""
  2. from __future__ import annotations
  3. import collections
  4. import contextlib
  5. import importlib.metadata
  6. import os
  7. import signal
  8. import subprocess
  9. from concurrent import futures
  10. from pathlib import Path
  11. from typing import Callable, Generator, Tuple
  12. import psutil
  13. import typer
  14. from redis.exceptions import RedisError
  15. from rich.progress import Progress
  16. from reflex import constants
  17. from reflex.config import environment
  18. from reflex.utils import console, path_ops, prerequisites
  19. def kill(pid: int):
  20. """Kill a process.
  21. Args:
  22. pid: The process ID.
  23. """
  24. os.kill(pid, signal.SIGTERM)
  25. def get_num_workers() -> int:
  26. """Get the number of backend worker processes.
  27. Raises:
  28. Exit: If unable to connect to Redis.
  29. Returns:
  30. The number of backend worker processes.
  31. """
  32. if (redis_client := prerequisites.get_redis_sync()) is None:
  33. return 1
  34. try:
  35. redis_client.ping()
  36. except RedisError as re:
  37. console.error(f"Unable to connect to Redis: {re}")
  38. raise typer.Exit(1) from re
  39. return (os.cpu_count() or 1) * 2 + 1
  40. def get_process_on_port(port: int) -> psutil.Process | None:
  41. """Get the process on the given port.
  42. Args:
  43. port: The port.
  44. Returns:
  45. The process on the given port.
  46. """
  47. for proc in psutil.process_iter(["pid", "name", "cmdline"]):
  48. with contextlib.suppress(
  49. psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess
  50. ):
  51. if importlib.metadata.version("psutil") >= "6.0.0":
  52. conns = proc.net_connections(kind="inet")
  53. else:
  54. conns = proc.connections(kind="inet")
  55. for conn in conns:
  56. if conn.laddr.port == int(port):
  57. return proc
  58. return None
  59. def is_process_on_port(port: int) -> bool:
  60. """Check if a process is running on the given port.
  61. Args:
  62. port: The port.
  63. Returns:
  64. Whether a process is running on the given port.
  65. """
  66. return get_process_on_port(port) is not None
  67. def kill_process_on_port(port: int):
  68. """Kill the process on the given port.
  69. Args:
  70. port: The port.
  71. """
  72. if get_process_on_port(port) is not None:
  73. with contextlib.suppress(psutil.AccessDenied):
  74. get_process_on_port(port).kill() # pyright: ignore [reportOptionalMemberAccess]
  75. def change_port(port: int, _type: str) -> int:
  76. """Change the port.
  77. Args:
  78. port: The port.
  79. _type: The type of the port.
  80. Returns:
  81. The new port.
  82. """
  83. new_port = port + 1
  84. if is_process_on_port(new_port):
  85. return change_port(new_port, _type)
  86. console.info(
  87. f"The {_type} will run on port [bold underline]{new_port}[/bold underline]."
  88. )
  89. return new_port
  90. def handle_port(service_name: str, port: int, auto_increment: bool) -> int:
  91. """Change port if the specified port is in use and is not explicitly specified as a CLI arg or config arg.
  92. Otherwise tell the user the port is in use and exit the app.
  93. Args:
  94. service_name: The frontend or backend.
  95. port: The provided port.
  96. auto_increment: Whether to automatically increment the port.
  97. Returns:
  98. The port to run the service on.
  99. Raises:
  100. Exit:when the port is in use.
  101. """
  102. if (process := get_process_on_port(port)) is None:
  103. return port
  104. if auto_increment:
  105. return change_port(port, service_name)
  106. else:
  107. console.error(
  108. f"{service_name.capitalize()} port: {port} is already in use by PID: {process.pid}."
  109. )
  110. raise typer.Exit()
  111. def new_process(
  112. args: str | list[str] | list[str | None] | list[str | Path | None],
  113. run: bool = False,
  114. show_logs: bool = False,
  115. **kwargs,
  116. ):
  117. """Wrapper over subprocess.Popen to unify the launch of child processes.
  118. Args:
  119. args: A string, or a sequence of program arguments.
  120. run: Whether to run the process to completion.
  121. show_logs: Whether to show the logs of the process.
  122. **kwargs: Kwargs to override default wrap values to pass to subprocess.Popen as arguments.
  123. Returns:
  124. Execute a child program in a new process.
  125. Raises:
  126. Exit: When attempting to run a command with a None value.
  127. """
  128. # Check for invalid command first.
  129. if isinstance(args, list) and None in args:
  130. console.error(f"Invalid command: {args}")
  131. raise typer.Exit(1)
  132. path_env: str = os.environ.get("PATH", "")
  133. # Add node_bin_path to the PATH environment variable.
  134. if not environment.REFLEX_BACKEND_ONLY.get():
  135. node_bin_path = str(path_ops.get_node_bin_path())
  136. if not node_bin_path and not prerequisites.CURRENTLY_INSTALLING_NODE:
  137. console.warn(
  138. "The path to the Node binary could not be found. Please ensure that Node is properly "
  139. "installed and added to your system's PATH environment variable or try running "
  140. "`reflex init` again."
  141. )
  142. path_env = os.pathsep.join([node_bin_path, path_env])
  143. env: dict[str, str] = {
  144. **os.environ,
  145. "PATH": path_env,
  146. **kwargs.pop("env", {}),
  147. }
  148. kwargs = {
  149. "env": env,
  150. "stderr": None if show_logs else subprocess.STDOUT,
  151. "stdout": None if show_logs else subprocess.PIPE,
  152. "universal_newlines": True,
  153. "encoding": "UTF-8",
  154. "errors": "replace", # Avoid UnicodeDecodeError in unknown command output
  155. **kwargs,
  156. }
  157. console.debug(f"Running command: {args}")
  158. fn = subprocess.run if run else subprocess.Popen
  159. return fn(args, **kwargs) # pyright: ignore [reportCallIssue, reportArgumentType]
  160. @contextlib.contextmanager
  161. def run_concurrently_context(
  162. *fns: Callable | Tuple,
  163. ) -> Generator[list[futures.Future], None, None]:
  164. """Run functions concurrently in a thread pool.
  165. Args:
  166. *fns: The functions to run.
  167. Yields:
  168. The futures for the functions.
  169. """
  170. # If no functions are provided, yield an empty list and return.
  171. if not fns:
  172. yield []
  173. return
  174. # Convert the functions to tuples.
  175. fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # pyright: ignore [reportAssignmentType]
  176. # Run the functions concurrently.
  177. executor = None
  178. try:
  179. executor = futures.ThreadPoolExecutor(max_workers=len(fns))
  180. # Submit the tasks.
  181. tasks = [executor.submit(*fn) for fn in fns] # pyright: ignore [reportArgumentType]
  182. # Yield control back to the main thread while tasks are running.
  183. yield tasks
  184. # Get the results in the order completed to check any exceptions.
  185. for task in futures.as_completed(tasks):
  186. # if task throws something, we let it bubble up immediately
  187. task.result()
  188. finally:
  189. # Shutdown the executor
  190. if executor:
  191. executor.shutdown(wait=False)
  192. def run_concurrently(*fns: Callable | Tuple) -> None:
  193. """Run functions concurrently in a thread pool.
  194. Args:
  195. *fns: The functions to run.
  196. """
  197. with run_concurrently_context(*fns):
  198. pass
  199. def stream_logs(
  200. message: str,
  201. process: subprocess.Popen,
  202. progress: Progress | None = None,
  203. suppress_errors: bool = False,
  204. analytics_enabled: bool = False,
  205. ):
  206. """Stream the logs for a process.
  207. Args:
  208. message: The message to display.
  209. process: The process.
  210. progress: The ongoing progress bar if one is being used.
  211. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  212. analytics_enabled: Whether analytics are enabled for this command.
  213. Yields:
  214. The lines of the process output.
  215. Raises:
  216. Exit: If the process failed.
  217. """
  218. from reflex.utils import telemetry
  219. # Store the tail of the logs.
  220. logs = collections.deque(maxlen=512)
  221. with process:
  222. console.debug(message, progress=progress)
  223. if process.stdout is None:
  224. return
  225. for line in process.stdout:
  226. console.debug(line, end="", progress=progress)
  227. logs.append(line)
  228. yield line
  229. # Check if the process failed (not printing the logs for SIGINT).
  230. # Windows uvicorn bug
  231. # https://github.com/reflex-dev/reflex/issues/2335
  232. accepted_return_codes = [0, -2, 15] if constants.IS_WINDOWS else [0, -2]
  233. if process.returncode not in accepted_return_codes and not suppress_errors:
  234. console.error(f"{message} failed with exit code {process.returncode}")
  235. for line in logs:
  236. console.error(line, end="")
  237. if analytics_enabled:
  238. telemetry.send("error", context=message)
  239. console.error("Run with [bold]--loglevel debug [/bold] for the full log.")
  240. raise typer.Exit(1)
  241. def show_logs(message: str, process: subprocess.Popen):
  242. """Show the logs for a process.
  243. Args:
  244. message: The message to display.
  245. process: The process.
  246. """
  247. for _ in stream_logs(message, process):
  248. pass
  249. def show_status(
  250. message: str,
  251. process: subprocess.Popen,
  252. suppress_errors: bool = False,
  253. analytics_enabled: bool = False,
  254. ):
  255. """Show the status of a process.
  256. Args:
  257. message: The initial message to display.
  258. process: The process.
  259. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  260. analytics_enabled: Whether analytics are enabled for this command.
  261. """
  262. with console.status(message) as status:
  263. for line in stream_logs(
  264. message,
  265. process,
  266. suppress_errors=suppress_errors,
  267. analytics_enabled=analytics_enabled,
  268. ):
  269. status.update(f"{message} {line}")
  270. def show_progress(message: str, process: subprocess.Popen, checkpoints: list[str]):
  271. """Show a progress bar for a process.
  272. Args:
  273. message: The message to display.
  274. process: The process.
  275. checkpoints: The checkpoints to advance the progress bar.
  276. """
  277. # Iterate over the process output.
  278. with console.progress() as progress:
  279. task = progress.add_task(f"{message}: ", total=len(checkpoints))
  280. for line in stream_logs(message, process, progress=progress):
  281. # Check for special strings and update the progress bar.
  282. for special_string in checkpoints:
  283. if special_string in line:
  284. progress.update(task, advance=1)
  285. if special_string == checkpoints[-1]:
  286. progress.update(task, completed=len(checkpoints))
  287. break
  288. def atexit_handler():
  289. """Display a custom message with the current time when exiting an app."""
  290. console.log("Reflex app stopped.")
  291. def get_command_with_loglevel(command: list[str]) -> list[str]:
  292. """Add the right loglevel flag to the designated command.
  293. npm uses --loglevel <level>, Bun doesn't use the --loglevel flag and
  294. runs in debug mode by default.
  295. Args:
  296. command:The command to add loglevel flag.
  297. Returns:
  298. The updated command list
  299. """
  300. npm_path = path_ops.get_npm_path()
  301. npm_path = str(npm_path) if npm_path else None
  302. if command[0] == npm_path:
  303. return [*command, "--loglevel", "silly"]
  304. return command
  305. def run_process_with_fallback(
  306. args: list[str],
  307. *,
  308. show_status_message: str,
  309. fallback: str | list | None = None,
  310. analytics_enabled: bool = False,
  311. **kwargs,
  312. ):
  313. """Run subprocess and retry using fallback command if initial command fails.
  314. Args:
  315. args: A string, or a sequence of program arguments.
  316. show_status_message: The status message to be displayed in the console.
  317. fallback: The fallback command to run.
  318. analytics_enabled: Whether analytics are enabled for this command.
  319. kwargs: Kwargs to pass to new_process function.
  320. """
  321. process = new_process(get_command_with_loglevel(args), **kwargs)
  322. if fallback is None:
  323. # No fallback given, or this _is_ the fallback command.
  324. show_status(
  325. show_status_message,
  326. process,
  327. analytics_enabled=analytics_enabled,
  328. )
  329. else:
  330. # Suppress errors for initial command, because we will try to fallback
  331. show_status(show_status_message, process, suppress_errors=True)
  332. if process.returncode != 0:
  333. # retry with fallback command.
  334. fallback_args = [fallback, *args[1:]]
  335. console.warn(
  336. f"There was an error running command: {args}. Falling back to: {fallback_args}."
  337. )
  338. run_process_with_fallback(
  339. fallback_args,
  340. show_status_message=show_status_message,
  341. fallback=None,
  342. analytics_enabled=analytics_enabled,
  343. **kwargs,
  344. )
  345. def execute_command_and_return_output(command: str) -> str | None:
  346. """Execute a command and return the output.
  347. Args:
  348. command: The command to run.
  349. Returns:
  350. The output of the command.
  351. """
  352. try:
  353. return subprocess.check_output(command, shell=True).decode().strip()
  354. except subprocess.SubprocessError as err:
  355. console.error(
  356. f"The command `{command}` failed with error: {err}. This will return None."
  357. )
  358. return None