processes.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 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.config import environment
  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. with contextlib.suppress(
  47. psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess
  48. ):
  49. if importlib.metadata.version("psutil") >= "6.0.0":
  50. conns = proc.net_connections(kind="inet") # type: ignore
  51. else:
  52. conns = proc.connections(kind="inet")
  53. for conn in conns:
  54. if conn.laddr.port == int(port):
  55. return proc
  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 hasn't 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. # Check for invalid command first.
  122. if None in args:
  123. console.error(f"Invalid command: {args}")
  124. raise typer.Exit(1)
  125. path_env: str = os.environ.get("PATH", "")
  126. # Add node_bin_path to the PATH environment variable.
  127. if not environment.REFLEX_BACKEND_ONLY.get():
  128. node_bin_path = str(path_ops.get_node_bin_path())
  129. if not node_bin_path and not prerequisites.CURRENTLY_INSTALLING_NODE:
  130. console.warn(
  131. "The path to the Node binary could not be found. Please ensure that Node is properly "
  132. "installed and added to your system's PATH environment variable or try running "
  133. "`reflex init` again."
  134. )
  135. path_env = os.pathsep.join([node_bin_path, path_env])
  136. env: dict[str, str] = {
  137. **os.environ,
  138. "PATH": path_env,
  139. **kwargs.pop("env", {}),
  140. }
  141. kwargs = {
  142. "env": env,
  143. "stderr": None if show_logs else subprocess.STDOUT,
  144. "stdout": None if show_logs else subprocess.PIPE,
  145. "universal_newlines": True,
  146. "encoding": "UTF-8",
  147. "errors": "replace", # Avoid UnicodeDecodeError in unknown command output
  148. **kwargs,
  149. }
  150. console.debug(f"Running command: {args}")
  151. fn = subprocess.run if run else subprocess.Popen
  152. return fn(args, **kwargs)
  153. @contextlib.contextmanager
  154. def run_concurrently_context(
  155. *fns: Union[Callable, Tuple],
  156. ) -> Generator[list[futures.Future], None, None]:
  157. """Run functions concurrently in a thread pool.
  158. Args:
  159. *fns: The functions to run.
  160. Yields:
  161. The futures for the functions.
  162. """
  163. # If no functions are provided, yield an empty list and return.
  164. if not fns:
  165. yield []
  166. return
  167. # Convert the functions to tuples.
  168. fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # type: ignore
  169. # Run the functions concurrently.
  170. executor = None
  171. try:
  172. executor = futures.ThreadPoolExecutor(max_workers=len(fns))
  173. # Submit the tasks.
  174. tasks = [executor.submit(*fn) for fn in fns] # type: ignore
  175. # Yield control back to the main thread while tasks are running.
  176. yield tasks
  177. # Get the results in the order completed to check any exceptions.
  178. for task in futures.as_completed(tasks):
  179. # if task throws something, we let it bubble up immediately
  180. task.result()
  181. finally:
  182. # Shutdown the executor
  183. if executor:
  184. executor.shutdown(wait=False)
  185. def run_concurrently(*fns: Union[Callable, Tuple]) -> None:
  186. """Run functions concurrently in a thread pool.
  187. Args:
  188. *fns: The functions to run.
  189. """
  190. with run_concurrently_context(*fns):
  191. pass
  192. def stream_logs(
  193. message: str,
  194. process: subprocess.Popen,
  195. progress=None,
  196. suppress_errors: bool = False,
  197. analytics_enabled: bool = False,
  198. ):
  199. """Stream the logs for a process.
  200. Args:
  201. message: The message to display.
  202. process: The process.
  203. progress: The ongoing progress bar if one is being used.
  204. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  205. analytics_enabled: Whether analytics are enabled for this command.
  206. Yields:
  207. The lines of the process output.
  208. Raises:
  209. Exit: If the process failed.
  210. """
  211. from reflex.utils import telemetry
  212. # Store the tail of the logs.
  213. logs = collections.deque(maxlen=512)
  214. with process:
  215. console.debug(message, progress=progress)
  216. if process.stdout is None:
  217. return
  218. for line in process.stdout:
  219. console.debug(line, end="", progress=progress)
  220. logs.append(line)
  221. yield line
  222. # Check if the process failed (not printing the logs for SIGINT).
  223. # Windows uvicorn bug
  224. # https://github.com/reflex-dev/reflex/issues/2335
  225. accepted_return_codes = [0, -2, 15] if constants.IS_WINDOWS else [0, -2]
  226. if process.returncode not in accepted_return_codes and not suppress_errors:
  227. console.error(f"{message} failed with exit code {process.returncode}")
  228. for line in logs:
  229. console.error(line, end="")
  230. if analytics_enabled:
  231. telemetry.send("error", context=message)
  232. console.error("Run with [bold]--loglevel debug [/bold] for the full log.")
  233. raise typer.Exit(1)
  234. def show_logs(message: str, process: subprocess.Popen):
  235. """Show the logs for a process.
  236. Args:
  237. message: The message to display.
  238. process: The process.
  239. """
  240. for _ in stream_logs(message, process):
  241. pass
  242. def show_status(
  243. message: str,
  244. process: subprocess.Popen,
  245. suppress_errors: bool = False,
  246. analytics_enabled: bool = False,
  247. ):
  248. """Show the status of a process.
  249. Args:
  250. message: The initial message to display.
  251. process: The process.
  252. suppress_errors: If True, do not exit if errors are encountered (for fallback).
  253. analytics_enabled: Whether analytics are enabled for this command.
  254. """
  255. with console.status(message) as status:
  256. for line in stream_logs(
  257. message,
  258. process,
  259. suppress_errors=suppress_errors,
  260. analytics_enabled=analytics_enabled,
  261. ):
  262. status.update(f"{message} {line}")
  263. def show_progress(message: str, process: subprocess.Popen, checkpoints: List[str]):
  264. """Show a progress bar for a process.
  265. Args:
  266. message: The message to display.
  267. process: The process.
  268. checkpoints: The checkpoints to advance the progress bar.
  269. """
  270. # Iterate over the process output.
  271. with console.progress() as progress:
  272. task = progress.add_task(f"{message}: ", total=len(checkpoints))
  273. for line in stream_logs(message, process, progress=progress):
  274. # Check for special strings and update the progress bar.
  275. for special_string in checkpoints:
  276. if special_string in line:
  277. progress.update(task, advance=1)
  278. if special_string == checkpoints[-1]:
  279. progress.update(task, completed=len(checkpoints))
  280. break
  281. def atexit_handler():
  282. """Display a custom message with the current time when exiting an app."""
  283. console.log("Reflex app stopped.")
  284. def get_command_with_loglevel(command: list[str]) -> list[str]:
  285. """Add the right loglevel flag to the designated command.
  286. npm uses --loglevel <level>, Bun doesn't use the --loglevel flag and
  287. runs in debug mode by default.
  288. Args:
  289. command:The command to add loglevel flag.
  290. Returns:
  291. The updated command list
  292. """
  293. npm_path = path_ops.get_npm_path()
  294. npm_path = str(npm_path) if npm_path else None
  295. if command[0] == npm_path:
  296. return [*command, "--loglevel", "silly"]
  297. return command
  298. def run_process_with_fallback(
  299. args,
  300. *,
  301. show_status_message,
  302. fallback=None,
  303. analytics_enabled: bool = False,
  304. **kwargs,
  305. ):
  306. """Run subprocess and retry using fallback command if initial command fails.
  307. Args:
  308. args: A string, or a sequence of program arguments.
  309. show_status_message: The status message to be displayed in the console.
  310. fallback: The fallback command to run.
  311. analytics_enabled: Whether analytics are enabled for this command.
  312. kwargs: Kwargs to pass to new_process function.
  313. """
  314. process = new_process(get_command_with_loglevel(args), **kwargs)
  315. if fallback is None:
  316. # No fallback given, or this _is_ the fallback command.
  317. show_status(
  318. show_status_message,
  319. process,
  320. analytics_enabled=analytics_enabled,
  321. )
  322. else:
  323. # Suppress errors for initial command, because we will try to fallback
  324. show_status(show_status_message, process, suppress_errors=True)
  325. if process.returncode != 0:
  326. # retry with fallback command.
  327. fallback_args = [fallback, *args[1:]]
  328. console.warn(
  329. f"There was an error running command: {args}. Falling back to: {fallback_args}."
  330. )
  331. run_process_with_fallback(
  332. fallback_args,
  333. show_status_message=show_status_message,
  334. fallback=None,
  335. analytics_enabled=analytics_enabled,
  336. **kwargs,
  337. )
  338. def execute_command_and_return_output(command) -> str | None:
  339. """Execute a command and return the output.
  340. Args:
  341. command: The command to run.
  342. Returns:
  343. The output of the command.
  344. """
  345. try:
  346. return subprocess.check_output(command, shell=True).decode().strip()
  347. except subprocess.SubprocessError as err:
  348. console.error(
  349. f"The command `{command}` failed with error: {err}. This will return None."
  350. )
  351. return None