processes.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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, Sequence, 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 = path_ops.get_node_bin_path()
  136. if node_bin_path:
  137. path_env = os.pathsep.join([str(node_bin_path), path_env])
  138. env: dict[str, str] = {
  139. **os.environ,
  140. "PATH": path_env,
  141. **kwargs.pop("env", {}),
  142. }
  143. kwargs = {
  144. "env": env,
  145. "stderr": None if show_logs else subprocess.STDOUT,
  146. "stdout": None if show_logs else subprocess.PIPE,
  147. "universal_newlines": True,
  148. "encoding": "UTF-8",
  149. "errors": "replace", # Avoid UnicodeDecodeError in unknown command output
  150. **kwargs,
  151. }
  152. console.debug(f"Running command: {args}")
  153. fn = subprocess.run if run else subprocess.Popen
  154. return fn(args, **kwargs) # pyright: ignore [reportCallIssue, reportArgumentType]
  155. @contextlib.contextmanager
  156. def run_concurrently_context(
  157. *fns: Callable | Tuple,
  158. ) -> Generator[list[futures.Future], None, None]:
  159. """Run functions concurrently in a thread pool.
  160. Args:
  161. *fns: The functions to run.
  162. Yields:
  163. The futures for the functions.
  164. """
  165. # If no functions are provided, yield an empty list and return.
  166. if not fns:
  167. yield []
  168. return
  169. # Convert the functions to tuples.
  170. fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # pyright: ignore [reportAssignmentType]
  171. # Run the functions concurrently.
  172. executor = None
  173. try:
  174. executor = futures.ThreadPoolExecutor(max_workers=len(fns))
  175. # Submit the tasks.
  176. tasks = [executor.submit(*fn) for fn in fns] # pyright: ignore [reportArgumentType]
  177. # Yield control back to the main thread while tasks are running.
  178. yield tasks
  179. # Get the results in the order completed to check any exceptions.
  180. for task in futures.as_completed(tasks):
  181. # if task throws something, we let it bubble up immediately
  182. task.result()
  183. finally:
  184. # Shutdown the executor
  185. if executor:
  186. executor.shutdown(wait=False)
  187. def run_concurrently(*fns: Callable | Tuple) -> None:
  188. """Run functions concurrently in a thread pool.
  189. Args:
  190. *fns: The functions to run.
  191. """
  192. with run_concurrently_context(*fns):
  193. pass
  194. def stream_logs(
  195. message: str,
  196. process: subprocess.Popen,
  197. progress: Progress | None = None,
  198. suppress_errors: bool = False,
  199. analytics_enabled: bool = False,
  200. ):
  201. """Stream the logs for a process.
  202. Args:
  203. message: The message to display.
  204. process: The process.
  205. progress: The ongoing progress bar if one is being used.
  206. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  207. analytics_enabled: Whether analytics are enabled for this command.
  208. Yields:
  209. The lines of the process output.
  210. Raises:
  211. Exit: If the process failed.
  212. """
  213. from reflex.utils import telemetry
  214. # Store the tail of the logs.
  215. logs = collections.deque(maxlen=512)
  216. with process:
  217. console.debug(message, progress=progress)
  218. if process.stdout is None:
  219. return
  220. for line in process.stdout:
  221. console.debug(line, end="", progress=progress)
  222. logs.append(line)
  223. yield line
  224. # Check if the process failed (not printing the logs for SIGINT).
  225. # Windows uvicorn bug
  226. # https://github.com/reflex-dev/reflex/issues/2335
  227. accepted_return_codes = [0, -2, 15] if constants.IS_WINDOWS else [0, -2]
  228. if process.returncode not in accepted_return_codes and not suppress_errors:
  229. console.error(f"{message} failed with exit code {process.returncode}")
  230. for line in logs:
  231. console.error(line, end="")
  232. if analytics_enabled:
  233. telemetry.send("error", context=message)
  234. console.error("Run with [bold]--loglevel debug [/bold] for the full log.")
  235. raise typer.Exit(1)
  236. def show_logs(message: str, process: subprocess.Popen):
  237. """Show the logs for a process.
  238. Args:
  239. message: The message to display.
  240. process: The process.
  241. """
  242. for _ in stream_logs(message, process):
  243. pass
  244. def show_status(
  245. message: str,
  246. process: subprocess.Popen,
  247. suppress_errors: bool = False,
  248. analytics_enabled: bool = False,
  249. ):
  250. """Show the status of a process.
  251. Args:
  252. message: The initial message to display.
  253. process: The process.
  254. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  255. analytics_enabled: Whether analytics are enabled for this command.
  256. """
  257. with console.status(message) as status:
  258. for line in stream_logs(
  259. message,
  260. process,
  261. suppress_errors=suppress_errors,
  262. analytics_enabled=analytics_enabled,
  263. ):
  264. status.update(f"{message} {line}")
  265. def show_progress(message: str, process: subprocess.Popen, checkpoints: list[str]):
  266. """Show a progress bar for a process.
  267. Args:
  268. message: The message to display.
  269. process: The process.
  270. checkpoints: The checkpoints to advance the progress bar.
  271. """
  272. # Iterate over the process output.
  273. with console.progress() as progress:
  274. task = progress.add_task(f"{message}: ", total=len(checkpoints))
  275. for line in stream_logs(message, process, progress=progress):
  276. # Check for special strings and update the progress bar.
  277. for special_string in checkpoints:
  278. if special_string in line:
  279. progress.update(task, advance=1)
  280. if special_string == checkpoints[-1]:
  281. progress.update(task, completed=len(checkpoints))
  282. break
  283. def atexit_handler():
  284. """Display a custom message with the current time when exiting an app."""
  285. console.log("Reflex app stopped.")
  286. def get_command_with_loglevel(command: list[str]) -> list[str]:
  287. """Add the right loglevel flag to the designated command.
  288. npm uses --loglevel <level>, Bun doesn't use the --loglevel flag and
  289. runs in debug mode by default.
  290. Args:
  291. command:The command to add loglevel flag.
  292. Returns:
  293. The updated command list
  294. """
  295. npm_path = path_ops.get_npm_path()
  296. npm_path = str(npm_path) if npm_path else None
  297. if command[0] == npm_path:
  298. return [*command, "--loglevel", "silly"]
  299. return command
  300. def run_process_with_fallbacks(
  301. args: list[str],
  302. *,
  303. show_status_message: str,
  304. fallbacks: str | Sequence[str] | Sequence[Sequence[str]] | None = None,
  305. analytics_enabled: bool = False,
  306. **kwargs,
  307. ):
  308. """Run subprocess and retry using fallback command if initial command fails.
  309. Args:
  310. args: A string, or a sequence of program arguments.
  311. show_status_message: The status message to be displayed in the console.
  312. fallbacks: The fallback command to run if the initial command fails.
  313. analytics_enabled: Whether analytics are enabled for this command.
  314. kwargs: Kwargs to pass to new_process function.
  315. """
  316. process = new_process(get_command_with_loglevel(args), **kwargs)
  317. if not fallbacks:
  318. # No fallback given, or this _is_ the fallback command.
  319. show_status(
  320. show_status_message,
  321. process,
  322. analytics_enabled=analytics_enabled,
  323. )
  324. else:
  325. # Suppress errors for initial command, because we will try to fallback
  326. show_status(show_status_message, process, suppress_errors=True)
  327. current_fallback = fallbacks[0] if not isinstance(fallbacks, str) else fallbacks
  328. next_fallbacks = fallbacks[1:] if not isinstance(fallbacks, str) else None
  329. if process.returncode != 0:
  330. # retry with fallback command.
  331. fallback_with_args = (
  332. [current_fallback, *args[1:]]
  333. if isinstance(fallbacks, str)
  334. else [*current_fallback, *args[1:]]
  335. )
  336. console.warn(
  337. f"There was an error running command: {args}. Falling back to: {fallback_with_args}."
  338. )
  339. run_process_with_fallbacks(
  340. fallback_with_args,
  341. show_status_message=show_status_message,
  342. fallbacks=next_fallbacks,
  343. analytics_enabled=analytics_enabled,
  344. **kwargs,
  345. )
  346. def execute_command_and_return_output(command: str) -> str | None:
  347. """Execute a command and return the output.
  348. Args:
  349. command: The command to run.
  350. Returns:
  351. The output of the command.
  352. """
  353. try:
  354. return subprocess.check_output(command, shell=True).decode().strip()
  355. except subprocess.SubprocessError as err:
  356. console.error(
  357. f"The command `{command}` failed with error: {err}. This will return None."
  358. )
  359. return None