processes.py 12 KB

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