exec.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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.prerequisites import get_web_dir
  17. # For uvicorn windows bug fix (#2335)
  18. frontend_process = None
  19. def detect_package_change(json_file_path: str) -> str:
  20. """Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
  21. Args:
  22. json_file_path: The path to the JSON file to be hashed.
  23. Returns:
  24. str: The SHA-256 hash of the JSON file as a hexadecimal string.
  25. Example:
  26. >>> detect_package_change("package.json")
  27. 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
  28. """
  29. with open(json_file_path, "r") as file:
  30. json_data = json.load(file)
  31. # Calculate the hash
  32. json_string = json.dumps(json_data, sort_keys=True)
  33. hash_object = hashlib.sha256(json_string.encode())
  34. return hash_object.hexdigest()
  35. def kill(proc_pid: int):
  36. """Kills a process and all its child processes.
  37. Args:
  38. proc_pid (int): The process ID of the process to be killed.
  39. Example:
  40. >>> kill(1234)
  41. """
  42. process = psutil.Process(proc_pid)
  43. for proc in process.children(recursive=True):
  44. proc.kill()
  45. process.kill()
  46. def notify_backend():
  47. """Output a string notifying where the backend is running."""
  48. console.print(
  49. f"Backend running at: [bold green]http://0.0.0.0:{get_config().backend_port}[/bold green]"
  50. )
  51. # run_process_and_launch_url is assumed to be used
  52. # only to launch the frontend
  53. # If this is not the case, might have to change the logic
  54. def run_process_and_launch_url(run_command: list[str], backend_present=True):
  55. """Run the process and launch the URL.
  56. Args:
  57. run_command: The command to run.
  58. backend_present: Whether the backend is present.
  59. """
  60. from reflex.utils import processes
  61. json_file_path = get_web_dir() / constants.PackageJson.PATH
  62. last_hash = detect_package_change(str(json_file_path))
  63. process = None
  64. first_run = True
  65. while True:
  66. if process is None:
  67. kwargs = {}
  68. if constants.IS_WINDOWS and backend_present:
  69. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  70. process = processes.new_process(
  71. run_command,
  72. cwd=get_web_dir(),
  73. shell=constants.IS_WINDOWS,
  74. **kwargs,
  75. )
  76. global frontend_process
  77. frontend_process = process
  78. if process.stdout:
  79. for line in processes.stream_logs("Starting frontend", process):
  80. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  81. if match:
  82. if first_run:
  83. url = match.group(1)
  84. if get_config().frontend_path != "":
  85. url = urljoin(url, get_config().frontend_path)
  86. console.print(
  87. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  88. )
  89. if backend_present:
  90. notify_backend()
  91. first_run = False
  92. else:
  93. console.print("New packages detected: Updating app...")
  94. else:
  95. if any(
  96. [x in line for x in ("bin executable does not exist on disk",)]
  97. ):
  98. console.error(
  99. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  100. "`REFLEX_USE_NPM=1 reflex init`\n"
  101. "`REFLEX_USE_NPM=1 reflex run`"
  102. )
  103. new_hash = detect_package_change(str(json_file_path))
  104. if new_hash != last_hash:
  105. last_hash = new_hash
  106. kill(process.pid)
  107. process = None
  108. break # for line in process.stdout
  109. if process is not None:
  110. break # while True
  111. def run_frontend(root: Path, port: str, backend_present=True):
  112. """Run the frontend.
  113. Args:
  114. root: The root path of the project.
  115. port: The port to run the frontend on.
  116. backend_present: Whether the backend is present.
  117. """
  118. from reflex.utils import prerequisites
  119. # validate dependencies before run
  120. prerequisites.validate_frontend_dependencies(init=False)
  121. # Run the frontend in development mode.
  122. console.rule("[bold green]App Running")
  123. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  124. run_process_and_launch_url(
  125. [prerequisites.get_package_manager(), "run", "dev"], # type: ignore
  126. backend_present,
  127. )
  128. def run_frontend_prod(root: Path, port: str, backend_present=True):
  129. """Run the frontend.
  130. Args:
  131. root: The root path of the project (to keep same API as run_frontend).
  132. port: The port to run the frontend on.
  133. backend_present: Whether the backend is present.
  134. """
  135. from reflex.utils import prerequisites
  136. # Set the port.
  137. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  138. # validate dependencies before run
  139. prerequisites.validate_frontend_dependencies(init=False)
  140. # Run the frontend in production mode.
  141. console.rule("[bold green]App Running")
  142. run_process_and_launch_url(
  143. [prerequisites.get_package_manager(), "run", "prod"], # type: ignore
  144. backend_present,
  145. )
  146. def should_use_granian():
  147. """Whether to use Granian for backend.
  148. Returns:
  149. True if Granian should be used.
  150. """
  151. return os.getenv("REFLEX_USE_GRANIAN", "0") == "1"
  152. def get_app_module():
  153. """Get the app module for the backend.
  154. Returns:
  155. The app module for the backend.
  156. """
  157. return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  158. def get_granian_target():
  159. """Get the Granian target for the backend.
  160. Returns:
  161. The Granian target for the backend.
  162. """
  163. return get_app_module() + f".{constants.CompileVars.API}"
  164. def run_backend(
  165. host: str,
  166. port: int,
  167. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  168. frontend_present: bool = False,
  169. ):
  170. """Run the backend.
  171. Args:
  172. host: The app host
  173. port: The app port
  174. loglevel: The log level.
  175. frontend_present: Whether the frontend is present.
  176. """
  177. web_dir = get_web_dir()
  178. # Create a .nocompile file to skip compile for backend.
  179. if web_dir.exists():
  180. (web_dir / constants.NOCOMPILE_FILE).touch()
  181. if not frontend_present:
  182. notify_backend()
  183. # Run the backend in development mode.
  184. if should_use_granian():
  185. run_granian_backend(host, port, loglevel)
  186. else:
  187. run_uvicorn_backend(host, port, loglevel)
  188. def run_uvicorn_backend(host, port, loglevel):
  189. """Run the backend in development mode using Uvicorn.
  190. Args:
  191. host: The app host
  192. port: The app port
  193. loglevel: The log level.
  194. """
  195. import uvicorn
  196. uvicorn.run(
  197. app=f"{get_app_module()}.{constants.CompileVars.API}",
  198. host=host,
  199. port=port,
  200. log_level=loglevel.value,
  201. reload=True,
  202. reload_dirs=[get_config().app_name],
  203. )
  204. def run_granian_backend(host, port, loglevel):
  205. """Run the backend in development mode using Granian.
  206. Args:
  207. host: The app host
  208. port: The app port
  209. loglevel: The log level.
  210. """
  211. console.debug("Using Granian for backend")
  212. try:
  213. from granian import Granian # type: ignore
  214. from granian.constants import Interfaces # type: ignore
  215. from granian.log import LogLevels # type: ignore
  216. Granian(
  217. target=get_granian_target(),
  218. address=host,
  219. port=port,
  220. interface=Interfaces.ASGI,
  221. log_level=LogLevels(loglevel.value),
  222. reload=True,
  223. reload_paths=[Path(get_config().app_name)],
  224. reload_ignore_dirs=[".web"],
  225. ).serve()
  226. except ImportError:
  227. console.error(
  228. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian>=1.6.0"`)'
  229. )
  230. os._exit(1)
  231. def _get_backend_workers():
  232. from reflex.utils import processes
  233. config = get_config()
  234. return (
  235. processes.get_num_workers()
  236. if not config.gunicorn_workers
  237. else config.gunicorn_workers
  238. )
  239. def run_backend_prod(
  240. host: str,
  241. port: int,
  242. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  243. frontend_present: bool = False,
  244. ):
  245. """Run the backend.
  246. Args:
  247. host: The app host
  248. port: The app port
  249. loglevel: The log level.
  250. frontend_present: Whether the frontend is present.
  251. """
  252. if not frontend_present:
  253. notify_backend()
  254. if should_use_granian():
  255. run_granian_backend_prod(host, port, loglevel)
  256. else:
  257. run_uvicorn_backend_prod(host, port, loglevel)
  258. def run_uvicorn_backend_prod(host, port, loglevel):
  259. """Run the backend in production mode using Uvicorn.
  260. Args:
  261. host: The app host
  262. port: The app port
  263. loglevel: The log level.
  264. """
  265. from reflex.utils import processes
  266. config = get_config()
  267. app_module = get_app_module()
  268. RUN_BACKEND_PROD = f"gunicorn --worker-class {config.gunicorn_worker_class} --preload --timeout {config.timeout} --log-level critical".split()
  269. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --timeout-keep-alive {config.timeout}".split()
  270. command = (
  271. [
  272. *RUN_BACKEND_PROD_WINDOWS,
  273. "--host",
  274. host,
  275. "--port",
  276. str(port),
  277. app_module,
  278. ]
  279. if constants.IS_WINDOWS
  280. else [
  281. *RUN_BACKEND_PROD,
  282. "--bind",
  283. f"{host}:{port}",
  284. "--threads",
  285. str(_get_backend_workers()),
  286. f"{app_module}()",
  287. ]
  288. )
  289. command += [
  290. "--log-level",
  291. loglevel.value,
  292. "--workers",
  293. str(_get_backend_workers()),
  294. ]
  295. processes.new_process(
  296. command,
  297. run=True,
  298. show_logs=True,
  299. env={constants.SKIP_COMPILE_ENV_VAR: "yes"}, # skip compile for prod backend
  300. )
  301. def run_granian_backend_prod(host, port, loglevel):
  302. """Run the backend in production mode using Granian.
  303. Args:
  304. host: The app host
  305. port: The app port
  306. loglevel: The log level.
  307. """
  308. from reflex.utils import processes
  309. try:
  310. from granian.constants import Interfaces # type: ignore
  311. command = [
  312. "granian",
  313. "--workers",
  314. str(_get_backend_workers()),
  315. "--log-level",
  316. "critical",
  317. "--host",
  318. host,
  319. "--port",
  320. str(port),
  321. "--interface",
  322. str(Interfaces.ASGI),
  323. get_granian_target(),
  324. ]
  325. processes.new_process(
  326. command,
  327. run=True,
  328. show_logs=True,
  329. env={
  330. constants.SKIP_COMPILE_ENV_VAR: "yes"
  331. }, # skip compile for prod backend
  332. )
  333. except ImportError:
  334. console.error(
  335. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian>=1.6.0"`)'
  336. )
  337. def output_system_info():
  338. """Show system information if the loglevel is in DEBUG."""
  339. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  340. return
  341. from reflex.utils import prerequisites
  342. config = get_config()
  343. try:
  344. config_file = sys.modules[config.__module__].__file__
  345. except Exception:
  346. config_file = None
  347. console.rule(f"System Info")
  348. console.debug(f"Config file: {config_file!r}")
  349. console.debug(f"Config: {config}")
  350. dependencies = [
  351. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  352. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  353. ]
  354. system = platform.system()
  355. if (
  356. system != "Windows"
  357. or system == "Windows"
  358. and prerequisites.is_windows_bun_supported()
  359. ):
  360. dependencies.extend(
  361. [
  362. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  363. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  364. ],
  365. )
  366. else:
  367. dependencies.append(
  368. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  369. )
  370. if system == "Linux":
  371. import distro # type: ignore
  372. os_version = distro.name(pretty=True)
  373. else:
  374. os_version = platform.version()
  375. dependencies.append(f"[OS {platform.system()} {os_version}]")
  376. for dep in dependencies:
  377. console.debug(f"{dep}")
  378. console.debug(
  379. f"Using package installer at: {prerequisites.get_install_package_manager()}" # type: ignore
  380. )
  381. console.debug(f"Using package executer at: {prerequisites.get_package_manager()}") # type: ignore
  382. if system != "Windows":
  383. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  384. def is_testing_env() -> bool:
  385. """Whether the app is running in a testing environment.
  386. Returns:
  387. True if the app is running in under pytest.
  388. """
  389. return constants.PYTEST_CURRENT_TEST in os.environ
  390. def is_prod_mode() -> bool:
  391. """Check if the app is running in production mode.
  392. Returns:
  393. True if the app is running in production mode or False if running in dev mode.
  394. """
  395. current_mode = os.environ.get(
  396. constants.ENV_MODE_ENV_VAR,
  397. constants.Env.DEV.value,
  398. )
  399. return current_mode == constants.Env.PROD.value
  400. def should_skip_compile() -> bool:
  401. """Whether the app should skip compile.
  402. Returns:
  403. True if the app should skip compile.
  404. """
  405. return os.environ.get(constants.SKIP_COMPILE_ENV_VAR) == "yes"