processes.py 16 KB

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