exec.py 15 KB

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