processes.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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, List, Optional, Tuple, Union
  10. from urllib.parse import urlparse
  11. import psutil
  12. import typer
  13. from reflex import constants
  14. from reflex.config import get_config
  15. from reflex.utils import console, 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. Returns:
  25. The number of backend worker processes.
  26. """
  27. return 1 if prerequisites.get_redis() is None else (os.cpu_count() or 1) * 2 + 1
  28. def get_api_port() -> int:
  29. """Get the API port.
  30. Returns:
  31. The API port.
  32. """
  33. port = urlparse(get_config().api_url).port
  34. if port is None:
  35. port = urlparse(constants.API_URL).port
  36. assert port is not None
  37. return port
  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. for conns in proc.connections(kind="inet"):
  48. if conns.laddr.port == int(port):
  49. return proc
  50. except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  51. pass
  52. return None
  53. def is_process_on_port(port) -> bool:
  54. """Check if a process is running on the given port.
  55. Args:
  56. port: The port.
  57. Returns:
  58. Whether a process is running on the given port.
  59. """
  60. return get_process_on_port(port) is not None
  61. def kill_process_on_port(port):
  62. """Kill the process on the given port.
  63. Args:
  64. port: The port.
  65. """
  66. if get_process_on_port(port) is not None:
  67. with contextlib.suppress(psutil.AccessDenied):
  68. get_process_on_port(port).kill() # type: ignore
  69. def change_or_terminate_port(port, _type) -> str:
  70. """Terminate or change the port.
  71. Args:
  72. port: The port.
  73. _type: The type of the port.
  74. Returns:
  75. The new port or the current one.
  76. Raises:
  77. Exit: If the user wants to exit.
  78. """
  79. console.info(
  80. f"Something is already running on port [bold underline]{port}[/bold underline]. This is the port the {_type} runs on."
  81. )
  82. frontend_action = console.ask("Kill or change it?", choices=["k", "c", "n"])
  83. if frontend_action == "k":
  84. kill_process_on_port(port)
  85. return port
  86. elif frontend_action == "c":
  87. new_port = console.ask("Specify the new port")
  88. # Check if also the new port is used
  89. if is_process_on_port(new_port):
  90. return change_or_terminate_port(new_port, _type)
  91. else:
  92. console.info(
  93. f"The {_type} will run on port [bold underline]{new_port}[/bold underline]."
  94. )
  95. return new_port
  96. else:
  97. console.log("Exiting...")
  98. raise typer.Exit()
  99. def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
  100. """Wrapper over subprocess.Popen to unify the launch of child processes.
  101. Args:
  102. args: A string, or a sequence of program arguments.
  103. run: Whether to run the process to completion.
  104. show_logs: Whether to show the logs of the process.
  105. **kwargs: Kwargs to override default wrap values to pass to subprocess.Popen as arguments.
  106. Returns:
  107. Execute a child program in a new process.
  108. """
  109. # Add the node bin path to the PATH environment variable.
  110. env = {
  111. **os.environ,
  112. "PATH": os.pathsep.join([constants.NODE_BIN_PATH, os.environ["PATH"]]),
  113. }
  114. kwargs = {
  115. "env": env,
  116. "stderr": None if show_logs else subprocess.STDOUT,
  117. "stdout": None if show_logs else subprocess.PIPE,
  118. "universal_newlines": True,
  119. "encoding": "UTF-8",
  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. def run_concurrently(*fns: Union[Callable, Tuple]):
  126. """Run functions concurrently in a thread pool.
  127. Args:
  128. *fns: The functions to run.
  129. """
  130. # Convert the functions to tuples.
  131. fns = [fn if isinstance(fn, tuple) else (fn,) for fn in fns] # type: ignore
  132. # Run the functions concurrently.
  133. with futures.ThreadPoolExecutor(max_workers=len(fns)) as executor:
  134. # Submit the tasks.
  135. tasks = [executor.submit(*fn) for fn in fns] # type: ignore
  136. # Get the results in the order completed to check any exceptions.
  137. for task in futures.as_completed(tasks):
  138. task.result()
  139. def stream_logs(
  140. message: str,
  141. process: subprocess.Popen,
  142. ):
  143. """Stream the logs for a process.
  144. Args:
  145. message: The message to display.
  146. process: The process.
  147. Yields:
  148. The lines of the process output.
  149. Raises:
  150. Exit: If the process failed.
  151. """
  152. # Store the tail of the logs.
  153. logs = collections.deque(maxlen=512)
  154. with process:
  155. console.debug(message)
  156. if process.stdout is None:
  157. return
  158. for line in process.stdout:
  159. console.debug(line, end="")
  160. logs.append(line)
  161. yield line
  162. if process.returncode != 0:
  163. console.error(f"{message} failed with exit code {process.returncode}")
  164. for line in logs:
  165. console.error(line, end="")
  166. console.error("Run with [bold]--loglevel debug [/bold] for the full log.")
  167. raise typer.Exit(1)
  168. def show_logs(
  169. message: str,
  170. process: subprocess.Popen,
  171. ):
  172. """Show the logs for a process.
  173. Args:
  174. message: The message to display.
  175. process: The process.
  176. """
  177. for _ in stream_logs(message, process):
  178. pass
  179. def show_status(message: str, process: subprocess.Popen):
  180. """Show the status of a process.
  181. Args:
  182. message: The initial message to display.
  183. process: The process.
  184. """
  185. with console.status(message) as status:
  186. for line in stream_logs(message, process):
  187. status.update(f"{message} {line}")
  188. def show_progress(message: str, process: subprocess.Popen, checkpoints: List[str]):
  189. """Show a progress bar for a process.
  190. Args:
  191. message: The message to display.
  192. process: The process.
  193. checkpoints: The checkpoints to advance the progress bar.
  194. """
  195. # Iterate over the process output.
  196. with console.progress() as progress:
  197. task = progress.add_task(f"{message}: ", total=len(checkpoints))
  198. for line in stream_logs(message, process):
  199. # Check for special strings and update the progress bar.
  200. for special_string in checkpoints:
  201. if special_string in line:
  202. progress.update(task, advance=1)
  203. if special_string == checkpoints[-1]:
  204. progress.update(task, completed=len(checkpoints))
  205. break
  206. def catch_keyboard_interrupt(signal, frame):
  207. """Display a custom message with the current time when exiting an app.
  208. Args:
  209. signal: The keyboard interrupt signal.
  210. frame: The current stack frame.
  211. """
  212. console.log("Reflex app stopped.")