processes.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. """Process operations."""
  2. from __future__ import annotations
  3. import collections
  4. import contextlib
  5. import os
  6. import signal
  7. import subprocess
  8. from concurrent import futures
  9. from typing import Callable, Generator, List, Optional, Tuple, Union
  10. import psutil
  11. import typer
  12. from redis.exceptions import RedisError
  13. from reflex import constants
  14. from reflex.utils import console, path_ops, prerequisites
  15. def kill(pid):
  16. """Kill a process.
  17. Args:
  18. pid: The process ID.
  19. """
  20. os.kill(pid, signal.SIGTERM)
  21. def get_num_workers() -> int:
  22. """Get the number of backend worker processes.
  23. Raises:
  24. Exit: If unable to connect to Redis.
  25. Returns:
  26. The number of backend worker processes.
  27. """
  28. if (redis_client := prerequisites.get_redis_sync()) is None:
  29. return 1
  30. try:
  31. redis_client.ping()
  32. except RedisError as re:
  33. console.error(f"Unable to connect to Redis: {re}")
  34. raise typer.Exit(1) from re
  35. return (os.cpu_count() or 1) * 2 + 1
  36. def get_process_on_port(port) -> Optional[psutil.Process]:
  37. """Get the process on the given port.
  38. Args:
  39. port: The port.
  40. Returns:
  41. The process on the given port.
  42. """
  43. for proc in psutil.process_iter(["pid", "name", "cmdline"]):
  44. try:
  45. for conns in proc.connections(kind="inet"):
  46. if conns.laddr.port == int(port):
  47. return proc
  48. except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  49. pass
  50. return None
  51. def is_process_on_port(port) -> bool:
  52. """Check if a process is running on the given port.
  53. Args:
  54. port: The port.
  55. Returns:
  56. Whether a process is running on the given port.
  57. """
  58. return get_process_on_port(port) is not None
  59. def kill_process_on_port(port):
  60. """Kill the process on the given port.
  61. Args:
  62. port: The port.
  63. """
  64. if get_process_on_port(port) is not None:
  65. with contextlib.suppress(psutil.AccessDenied):
  66. get_process_on_port(port).kill() # type: ignore
  67. def change_port(port: str, _type: str) -> str:
  68. """Change the port.
  69. Args:
  70. port: The port.
  71. _type: The type of the port.
  72. Returns:
  73. The new port.
  74. """
  75. new_port = str(int(port) + 1)
  76. if is_process_on_port(new_port):
  77. return change_port(new_port, _type)
  78. console.info(
  79. f"The {_type} will run on port [bold underline]{new_port}[/bold underline]."
  80. )
  81. return new_port
  82. def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
  83. """Wrapper over subprocess.Popen to unify the launch of child processes.
  84. Args:
  85. args: A string, or a sequence of program arguments.
  86. run: Whether to run the process to completion.
  87. show_logs: Whether to show the logs of the process.
  88. **kwargs: Kwargs to override default wrap values to pass to subprocess.Popen as arguments.
  89. Returns:
  90. Execute a child program in a new process.
  91. Raises:
  92. Exit: When attempting to run a command with a None value.
  93. """
  94. node_bin_path = path_ops.get_node_bin_path()
  95. if not node_bin_path and not prerequisites.CURRENTLY_INSTALLING_NODE:
  96. console.warn(
  97. "The path to the Node binary could not be found. Please ensure that Node is properly "
  98. "installed and added to your system's PATH environment variable or try running "
  99. "`reflex init` again."
  100. )
  101. if None in args:
  102. console.error(f"Invalid command: {args}")
  103. raise typer.Exit(1)
  104. # Add the node bin path to the PATH environment variable.
  105. env = {
  106. **os.environ,
  107. "PATH": os.pathsep.join([node_bin_path if node_bin_path else "", os.environ["PATH"]]), # type: ignore
  108. **kwargs.pop("env", {}),
  109. }
  110. kwargs = {
  111. "env": env,
  112. "stderr": None if show_logs else subprocess.STDOUT,
  113. "stdout": None if show_logs else subprocess.PIPE,
  114. "universal_newlines": True,
  115. "encoding": "UTF-8",
  116. "errors": "replace", # Avoid UnicodeDecodeError in unknown command output
  117. **kwargs,
  118. }
  119. console.debug(f"Running command: {args}")
  120. fn = subprocess.run if run else subprocess.Popen
  121. return fn(args, **kwargs)
  122. @contextlib.contextmanager
  123. def run_concurrently_context(
  124. *fns: Union[Callable, Tuple]
  125. ) -> Generator[list[futures.Future], None, None]:
  126. """Run functions concurrently in a thread pool.
  127. Args:
  128. *fns: The functions to run.
  129. Yields:
  130. The futures for the functions.
  131. """
  132. # If no functions are provided, yield an empty list and return.
  133. if not fns:
  134. yield []
  135. return
  136. # Convert the functions to tuples.
  137. fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # type: ignore
  138. # Run the functions concurrently.
  139. executor = None
  140. try:
  141. executor = futures.ThreadPoolExecutor(max_workers=len(fns))
  142. # Submit the tasks.
  143. tasks = [executor.submit(*fn) for fn in fns] # type: ignore
  144. # Yield control back to the main thread while tasks are running.
  145. yield tasks
  146. # Get the results in the order completed to check any exceptions.
  147. for task in futures.as_completed(tasks):
  148. # if task throws something, we let it bubble up immediately
  149. task.result()
  150. finally:
  151. # Shutdown the executor
  152. if executor:
  153. executor.shutdown(wait=False)
  154. def run_concurrently(*fns: Union[Callable, Tuple]) -> None:
  155. """Run functions concurrently in a thread pool.
  156. Args:
  157. *fns: The functions to run.
  158. """
  159. with run_concurrently_context(*fns):
  160. pass
  161. def stream_logs(
  162. message: str,
  163. process: subprocess.Popen,
  164. progress=None,
  165. suppress_errors: bool = False,
  166. ):
  167. """Stream the logs for a process.
  168. Args:
  169. message: The message to display.
  170. process: The process.
  171. progress: The ongoing progress bar if one is being used.
  172. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  173. Yields:
  174. The lines of the process output.
  175. Raises:
  176. Exit: If the process failed.
  177. """
  178. # Store the tail of the logs.
  179. logs = collections.deque(maxlen=512)
  180. with process:
  181. console.debug(message, progress=progress)
  182. if process.stdout is None:
  183. return
  184. for line in process.stdout:
  185. console.debug(line, end="", progress=progress)
  186. logs.append(line)
  187. yield line
  188. # Check if the process failed (not printing the logs for SIGINT).
  189. # Windows uvicorn bug
  190. # https://github.com/reflex-dev/reflex/issues/2335
  191. accepted_return_codes = [0, -2, 15] if constants.IS_WINDOWS else [0, -2]
  192. if process.returncode not in accepted_return_codes and not suppress_errors:
  193. console.error(f"{message} failed with exit code {process.returncode}")
  194. for line in logs:
  195. console.error(line, end="")
  196. console.error("Run with [bold]--loglevel debug [/bold] for the full log.")
  197. raise typer.Exit(1)
  198. def show_logs(message: str, process: subprocess.Popen):
  199. """Show the logs for a process.
  200. Args:
  201. message: The message to display.
  202. process: The process.
  203. """
  204. for _ in stream_logs(message, process):
  205. pass
  206. def show_status(message: str, process: subprocess.Popen, suppress_errors: bool = False):
  207. """Show the status of a process.
  208. Args:
  209. message: The initial message to display.
  210. process: The process.
  211. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  212. """
  213. with console.status(message) as status:
  214. for line in stream_logs(message, process, suppress_errors=suppress_errors):
  215. status.update(f"{message} {line}")
  216. def show_progress(message: str, process: subprocess.Popen, checkpoints: List[str]):
  217. """Show a progress bar for a process.
  218. Args:
  219. message: The message to display.
  220. process: The process.
  221. checkpoints: The checkpoints to advance the progress bar.
  222. """
  223. # Iterate over the process output.
  224. with console.progress() as progress:
  225. task = progress.add_task(f"{message}: ", total=len(checkpoints))
  226. for line in stream_logs(message, process, progress=progress):
  227. # Check for special strings and update the progress bar.
  228. for special_string in checkpoints:
  229. if special_string in line:
  230. progress.update(task, advance=1)
  231. if special_string == checkpoints[-1]:
  232. progress.update(task, completed=len(checkpoints))
  233. break
  234. def atexit_handler():
  235. """Display a custom message with the current time when exiting an app."""
  236. console.log("Reflex app stopped.")
  237. def run_process_with_fallback(args, *, show_status_message, fallback=None, **kwargs):
  238. """Run subprocess and retry using fallback command if initial command fails.
  239. Args:
  240. args: A string, or a sequence of program arguments.
  241. show_status_message: The status message to be displayed in the console.
  242. fallback: The fallback command to run.
  243. kwargs: Kwargs to pass to new_process function.
  244. """
  245. process = new_process(args, **kwargs)
  246. if fallback is None:
  247. # No fallback given, or this _is_ the fallback command.
  248. show_status(show_status_message, process)
  249. else:
  250. # Suppress errors for initial command, because we will try to fallback
  251. show_status(show_status_message, process, suppress_errors=True)
  252. if process.returncode != 0:
  253. # retry with fallback command.
  254. fallback_args = [fallback, *args[1:]]
  255. console.warn(
  256. f"There was an error running command: {args}. Falling back to: {fallback_args}."
  257. )
  258. run_process_with_fallback(
  259. fallback_args,
  260. show_status_message=show_status_message,
  261. fallback=None,
  262. **kwargs,
  263. )