1
0

processes.py 13 KB

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