processes.py 16 KB

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