exec.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. """Everything regarding execution of the built app."""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. import os
  6. import platform
  7. import re
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. from urllib.parse import urljoin
  12. import psutil
  13. from reflex import constants
  14. from reflex.config import get_config
  15. from reflex.utils import console, path_ops
  16. from reflex.utils.watch import AssetFolderWatch
  17. # For uvicorn windows bug fix (#2335)
  18. frontend_process = None
  19. def start_watching_assets_folder(root):
  20. """Start watching assets folder.
  21. Args:
  22. root: root path of the project.
  23. """
  24. asset_watch = AssetFolderWatch(root)
  25. asset_watch.start()
  26. def detect_package_change(json_file_path: str) -> str:
  27. """Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
  28. Args:
  29. json_file_path: The path to the JSON file to be hashed.
  30. Returns:
  31. str: The SHA-256 hash of the JSON file as a hexadecimal string.
  32. Example:
  33. >>> detect_package_change("package.json")
  34. 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
  35. """
  36. with open(json_file_path, "r") as file:
  37. json_data = json.load(file)
  38. # Calculate the hash
  39. json_string = json.dumps(json_data, sort_keys=True)
  40. hash_object = hashlib.sha256(json_string.encode())
  41. return hash_object.hexdigest()
  42. def kill(proc_pid: int):
  43. """Kills a process and all its child processes.
  44. Args:
  45. proc_pid (int): The process ID of the process to be killed.
  46. Example:
  47. >>> kill(1234)
  48. """
  49. process = psutil.Process(proc_pid)
  50. for proc in process.children(recursive=True):
  51. proc.kill()
  52. process.kill()
  53. # run_process_and_launch_url is assumed to be used
  54. # only to launch the frontend
  55. # If this is not the case, might have to change the logic
  56. def run_process_and_launch_url(run_command: list[str]):
  57. """Run the process and launch the URL.
  58. Args:
  59. run_command: The command to run.
  60. """
  61. from reflex.utils import processes
  62. json_file_path = os.path.join(constants.Dirs.WEB, "package.json")
  63. last_hash = detect_package_change(json_file_path)
  64. process = None
  65. first_run = True
  66. while True:
  67. if process is None:
  68. kwargs = {}
  69. if constants.IS_WINDOWS:
  70. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  71. process = processes.new_process(
  72. run_command,
  73. cwd=constants.Dirs.WEB,
  74. shell=constants.IS_WINDOWS,
  75. **kwargs,
  76. )
  77. global frontend_process
  78. frontend_process = process
  79. if process.stdout:
  80. for line in processes.stream_logs("Starting frontend", process):
  81. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  82. if match:
  83. if first_run:
  84. url = match.group(1)
  85. if get_config().frontend_path != "":
  86. url = urljoin(url, get_config().frontend_path)
  87. console.print(f"App running at: [bold green]{url}")
  88. first_run = False
  89. else:
  90. console.print("New packages detected: Updating app...")
  91. else:
  92. new_hash = detect_package_change(json_file_path)
  93. if new_hash != last_hash:
  94. last_hash = new_hash
  95. kill(process.pid)
  96. process = None
  97. break # for line in process.stdout
  98. if process is not None:
  99. break # while True
  100. def run_frontend(root: Path, port: str):
  101. """Run the frontend.
  102. Args:
  103. root: The root path of the project.
  104. port: The port to run the frontend on.
  105. """
  106. from reflex.utils import prerequisites
  107. # Start watching asset folder.
  108. start_watching_assets_folder(root)
  109. # validate dependencies before run
  110. prerequisites.validate_frontend_dependencies(init=False)
  111. # Run the frontend in development mode.
  112. console.rule("[bold green]App Running")
  113. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  114. run_process_and_launch_url([prerequisites.get_package_manager(), "run", "dev"]) # type: ignore
  115. def run_frontend_prod(root: Path, port: str):
  116. """Run the frontend.
  117. Args:
  118. root: The root path of the project (to keep same API as run_frontend).
  119. port: The port to run the frontend on.
  120. """
  121. from reflex.utils import prerequisites
  122. # Set the port.
  123. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  124. # validate dependencies before run
  125. prerequisites.validate_frontend_dependencies(init=False)
  126. # Run the frontend in production mode.
  127. console.rule("[bold green]App Running")
  128. run_process_and_launch_url([prerequisites.get_package_manager(), "run", "prod"]) # type: ignore
  129. def run_backend(
  130. host: str,
  131. port: int,
  132. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  133. ):
  134. """Run the backend.
  135. Args:
  136. host: The app host
  137. port: The app port
  138. loglevel: The log level.
  139. """
  140. import uvicorn
  141. config = get_config()
  142. app_module = f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  143. # Create a .nocompile file to skip compile for backend.
  144. if os.path.exists(constants.Dirs.WEB):
  145. with open(constants.NOCOMPILE_FILE, "w"):
  146. pass
  147. # Run the backend in development mode.
  148. uvicorn.run(
  149. app=f"{app_module}.{constants.CompileVars.API}",
  150. host=host,
  151. port=port,
  152. log_level=loglevel.value,
  153. reload=True,
  154. reload_dirs=[config.app_name],
  155. )
  156. def run_backend_prod(
  157. host: str,
  158. port: int,
  159. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  160. ):
  161. """Run the backend.
  162. Args:
  163. host: The app host
  164. port: The app port
  165. loglevel: The log level.
  166. """
  167. from reflex.utils import processes
  168. num_workers = processes.get_num_workers()
  169. config = get_config()
  170. RUN_BACKEND_PROD = f"gunicorn --worker-class {config.gunicorn_worker_class} --preload --timeout {config.timeout} --log-level critical".split()
  171. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --timeout-keep-alive {config.timeout}".split()
  172. app_module = f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  173. command = (
  174. [
  175. *RUN_BACKEND_PROD_WINDOWS,
  176. "--host",
  177. host,
  178. "--port",
  179. str(port),
  180. app_module,
  181. ]
  182. if constants.IS_WINDOWS
  183. else [
  184. *RUN_BACKEND_PROD,
  185. "--bind",
  186. f"{host}:{port}",
  187. "--threads",
  188. str(num_workers),
  189. f"{app_module}()",
  190. ]
  191. )
  192. command += [
  193. "--log-level",
  194. loglevel.value,
  195. "--workers",
  196. str(num_workers),
  197. ]
  198. processes.new_process(
  199. command,
  200. run=True,
  201. show_logs=True,
  202. env={constants.SKIP_COMPILE_ENV_VAR: "yes"}, # skip compile for prod backend
  203. )
  204. def output_system_info():
  205. """Show system information if the loglevel is in DEBUG."""
  206. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  207. return
  208. from reflex.utils import prerequisites
  209. config = get_config()
  210. try:
  211. config_file = sys.modules[config.__module__].__file__
  212. except Exception:
  213. config_file = None
  214. console.rule(f"System Info")
  215. console.debug(f"Config file: {config_file!r}")
  216. console.debug(f"Config: {config}")
  217. dependencies = [
  218. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  219. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  220. ]
  221. system = platform.system()
  222. if system != "Windows":
  223. dependencies.extend(
  224. [
  225. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  226. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  227. ],
  228. )
  229. else:
  230. dependencies.append(
  231. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  232. )
  233. if system == "Linux":
  234. import distro # type: ignore
  235. os_version = distro.name(pretty=True)
  236. else:
  237. os_version = platform.version()
  238. dependencies.append(f"[OS {platform.system()} {os_version}]")
  239. for dep in dependencies:
  240. console.debug(f"{dep}")
  241. console.debug(
  242. f"Using package installer at: {prerequisites.get_install_package_manager()}" # type: ignore
  243. )
  244. console.debug(f"Using package executer at: {prerequisites.get_package_manager()}") # type: ignore
  245. if system != "Windows":
  246. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  247. def is_testing_env() -> bool:
  248. """Whether the app is running in a testing environment.
  249. Returns:
  250. True if the app is running in under pytest.
  251. """
  252. return constants.PYTEST_CURRENT_TEST in os.environ
  253. def is_prod_mode() -> bool:
  254. """Check if the app is running in production mode.
  255. Returns:
  256. True if the app is running in production mode or False if running in dev mode.
  257. """
  258. current_mode = os.environ.get(
  259. constants.ENV_MODE_ENV_VAR,
  260. constants.Env.DEV.value,
  261. )
  262. return current_mode == constants.Env.PROD.value
  263. def should_skip_compile() -> bool:
  264. """Whether the app should skip compile.
  265. Returns:
  266. True if the app should skip compile.
  267. """
  268. return os.environ.get(constants.SKIP_COMPILE_ENV_VAR) == "yes"