processes.py 13 KB

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