1
0

exec.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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_package_list, 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. console.print(
  65. f"DETECT_PACKAGE_CHANGE init {last_hash}, {json.dumps(json.loads(json_file_path.read_text()))}"
  66. )
  67. last_packages = get_package_list()
  68. console.print(
  69. f"DETECT_PACKAGE_CHANGE init {last_packages}",
  70. )
  71. process = None
  72. first_run = True
  73. while True:
  74. if process is None:
  75. kwargs = {}
  76. if constants.IS_WINDOWS and backend_present:
  77. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  78. process = processes.new_process(
  79. run_command,
  80. cwd=get_web_dir(),
  81. shell=constants.IS_WINDOWS,
  82. **kwargs,
  83. )
  84. global frontend_process
  85. frontend_process = process
  86. if process.stdout:
  87. for line in processes.stream_logs("Starting frontend", process):
  88. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  89. if match:
  90. if first_run:
  91. url = match.group(1)
  92. if get_config().frontend_path != "":
  93. url = urljoin(url, get_config().frontend_path)
  94. console.print(
  95. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  96. )
  97. if backend_present:
  98. notify_backend()
  99. first_run = False
  100. else:
  101. console.print(f"New packages detected: Updating app... {line}")
  102. else:
  103. if any(
  104. x in line for x in ("bin executable does not exist on disk",)
  105. ):
  106. console.error(
  107. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  108. "`REFLEX_USE_NPM=1 reflex init`\n"
  109. "`REFLEX_USE_NPM=1 reflex run`"
  110. )
  111. new_hash = detect_package_change(json_file_path)
  112. if new_hash != last_hash:
  113. new_content = json.dumps(json.loads(json_file_path.read_text()))
  114. console.print(
  115. f"DETECT_PACKAGE_CHANGE hit {last_hash} != {new_hash} (new), {new_content}"
  116. )
  117. last_hash = new_hash
  118. new_packages = get_package_list()
  119. if new_packages != last_packages:
  120. console.print("Reloading app due to new content...")
  121. console.print(
  122. f"DETECT_PACKAGE_CHANGE init {new_packages}",
  123. )
  124. last_packages = new_packages
  125. kill(process.pid)
  126. process = None
  127. break # for line in process.stdout
  128. if process is not None:
  129. break # while True
  130. def run_frontend(root: Path, port: str, backend_present=True):
  131. """Run the frontend.
  132. Args:
  133. root: The root path of the project.
  134. port: The port to run the frontend on.
  135. backend_present: Whether the backend is present.
  136. """
  137. from reflex.utils import prerequisites
  138. # validate dependencies before run
  139. prerequisites.validate_frontend_dependencies(init=False)
  140. # Run the frontend in development mode.
  141. console.rule("[bold green]App Running")
  142. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  143. run_process_and_launch_url(
  144. [prerequisites.get_package_manager(), "run", "dev"], # type: ignore
  145. backend_present,
  146. )
  147. def run_frontend_prod(root: Path, port: str, backend_present=True):
  148. """Run the frontend.
  149. Args:
  150. root: The root path of the project (to keep same API as run_frontend).
  151. port: The port to run the frontend on.
  152. backend_present: Whether the backend is present.
  153. """
  154. from reflex.utils import prerequisites
  155. # Set the port.
  156. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  157. # validate dependencies before run
  158. prerequisites.validate_frontend_dependencies(init=False)
  159. # Run the frontend in production mode.
  160. console.rule("[bold green]App Running")
  161. run_process_and_launch_url(
  162. [prerequisites.get_package_manager(), "run", "prod"], # type: ignore
  163. backend_present,
  164. )
  165. def should_use_granian():
  166. """Whether to use Granian for backend.
  167. Returns:
  168. True if Granian should be used.
  169. """
  170. return environment.REFLEX_USE_GRANIAN.get()
  171. def get_app_module():
  172. """Get the app module for the backend.
  173. Returns:
  174. The app module for the backend.
  175. """
  176. return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  177. def get_granian_target():
  178. """Get the Granian target for the backend.
  179. Returns:
  180. The Granian target for the backend.
  181. """
  182. import reflex
  183. app_module_path = Path(reflex.__file__).parent / "app_module_for_backend.py"
  184. return (
  185. f"{app_module_path!s}:{constants.CompileVars.APP}.{constants.CompileVars.API}"
  186. )
  187. def run_backend(
  188. host: str,
  189. port: int,
  190. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  191. frontend_present: bool = False,
  192. ):
  193. """Run the backend.
  194. Args:
  195. host: The app host
  196. port: The app port
  197. loglevel: The log level.
  198. frontend_present: Whether the frontend is present.
  199. """
  200. web_dir = get_web_dir()
  201. # Create a .nocompile file to skip compile for backend.
  202. if web_dir.exists():
  203. (web_dir / constants.NOCOMPILE_FILE).touch()
  204. if not frontend_present:
  205. notify_backend()
  206. # Run the backend in development mode.
  207. if should_use_granian():
  208. run_granian_backend(host, port, loglevel)
  209. else:
  210. run_uvicorn_backend(host, port, loglevel)
  211. def run_uvicorn_backend(host, port, loglevel: LogLevel):
  212. """Run the backend in development mode using Uvicorn.
  213. Args:
  214. host: The app host
  215. port: The app port
  216. loglevel: The log level.
  217. """
  218. import uvicorn
  219. uvicorn.run(
  220. app=f"{get_app_module()}.{constants.CompileVars.API}",
  221. host=host,
  222. port=port,
  223. log_level=loglevel.value,
  224. reload=True,
  225. reload_dirs=[get_config().app_name],
  226. )
  227. def run_granian_backend(host, port, loglevel: LogLevel):
  228. """Run the backend in development mode using Granian.
  229. Args:
  230. host: The app host
  231. port: The app port
  232. loglevel: The log level.
  233. """
  234. console.debug("Using Granian for backend")
  235. try:
  236. from granian import Granian # type: ignore
  237. from granian.constants import Interfaces # type: ignore
  238. from granian.log import LogLevels # type: ignore
  239. Granian(
  240. target=get_granian_target(),
  241. address=host,
  242. port=port,
  243. interface=Interfaces.ASGI,
  244. log_level=LogLevels(loglevel.value),
  245. reload=True,
  246. reload_paths=[Path(get_config().app_name)],
  247. reload_ignore_dirs=[".web"],
  248. ).serve()
  249. except ImportError:
  250. console.error(
  251. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  252. )
  253. os._exit(1)
  254. def _get_backend_workers():
  255. from reflex.utils import processes
  256. config = get_config()
  257. return (
  258. processes.get_num_workers()
  259. if not config.gunicorn_workers
  260. else config.gunicorn_workers
  261. )
  262. def run_backend_prod(
  263. host: str,
  264. port: int,
  265. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  266. frontend_present: bool = False,
  267. ):
  268. """Run the backend.
  269. Args:
  270. host: The app host
  271. port: The app port
  272. loglevel: The log level.
  273. frontend_present: Whether the frontend is present.
  274. """
  275. if not frontend_present:
  276. notify_backend()
  277. if should_use_granian():
  278. run_granian_backend_prod(host, port, loglevel)
  279. else:
  280. run_uvicorn_backend_prod(host, port, loglevel)
  281. def run_uvicorn_backend_prod(host, port, loglevel):
  282. """Run the backend in production mode using Uvicorn.
  283. Args:
  284. host: The app host
  285. port: The app port
  286. loglevel: The log level.
  287. """
  288. from reflex.utils import processes
  289. config = get_config()
  290. app_module = get_app_module()
  291. 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()
  292. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split()
  293. command = (
  294. [
  295. *RUN_BACKEND_PROD_WINDOWS,
  296. "--host",
  297. host,
  298. "--port",
  299. str(port),
  300. app_module,
  301. ]
  302. if constants.IS_WINDOWS
  303. else [
  304. *RUN_BACKEND_PROD,
  305. "--bind",
  306. f"{host}:{port}",
  307. "--threads",
  308. str(_get_backend_workers()),
  309. f"{app_module}()",
  310. ]
  311. )
  312. command += [
  313. "--log-level",
  314. loglevel.value,
  315. "--workers",
  316. str(_get_backend_workers()),
  317. ]
  318. processes.new_process(
  319. command,
  320. run=True,
  321. show_logs=True,
  322. env={
  323. environment.REFLEX_SKIP_COMPILE.name: "true"
  324. }, # skip compile for prod backend
  325. )
  326. def run_granian_backend_prod(host, port, loglevel):
  327. """Run the backend in production mode using Granian.
  328. Args:
  329. host: The app host
  330. port: The app port
  331. loglevel: The log level.
  332. """
  333. from reflex.utils import processes
  334. try:
  335. from granian.constants import Interfaces # type: ignore
  336. command = [
  337. "granian",
  338. "--workers",
  339. str(_get_backend_workers()),
  340. "--log-level",
  341. "critical",
  342. "--host",
  343. host,
  344. "--port",
  345. str(port),
  346. "--interface",
  347. str(Interfaces.ASGI),
  348. get_granian_target(),
  349. ]
  350. processes.new_process(
  351. command,
  352. run=True,
  353. show_logs=True,
  354. env={
  355. environment.REFLEX_SKIP_COMPILE.name: "true"
  356. }, # skip compile for prod backend
  357. )
  358. except ImportError:
  359. console.error(
  360. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  361. )
  362. def output_system_info():
  363. """Show system information if the loglevel is in DEBUG."""
  364. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  365. return
  366. from reflex.utils import prerequisites
  367. config = get_config()
  368. try:
  369. config_file = sys.modules[config.__module__].__file__
  370. except Exception:
  371. config_file = None
  372. console.rule("System Info")
  373. console.debug(f"Config file: {config_file!r}")
  374. console.debug(f"Config: {config}")
  375. dependencies = [
  376. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  377. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  378. ]
  379. system = platform.system()
  380. if system != "Windows" or (
  381. system == "Windows" and prerequisites.is_windows_bun_supported()
  382. ):
  383. dependencies.extend(
  384. [
  385. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  386. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  387. ],
  388. )
  389. else:
  390. dependencies.append(
  391. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  392. )
  393. if system == "Linux":
  394. import distro # type: ignore
  395. os_version = distro.name(pretty=True)
  396. else:
  397. os_version = platform.version()
  398. dependencies.append(f"[OS {platform.system()} {os_version}]")
  399. for dep in dependencies:
  400. console.debug(f"{dep}")
  401. console.debug(
  402. f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}" # type: ignore
  403. )
  404. console.debug(
  405. f"Using package executer at: {prerequisites.get_package_manager(on_failure_return_none=True)}"
  406. ) # type: ignore
  407. if system != "Windows":
  408. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  409. def is_testing_env() -> bool:
  410. """Whether the app is running in a testing environment.
  411. Returns:
  412. True if the app is running in under pytest.
  413. """
  414. return constants.PYTEST_CURRENT_TEST in os.environ
  415. def is_prod_mode() -> bool:
  416. """Check if the app is running in production mode.
  417. Returns:
  418. True if the app is running in production mode or False if running in dev mode.
  419. """
  420. current_mode = environment.REFLEX_ENV_MODE.get()
  421. return current_mode == constants.Env.PROD
  422. def is_frontend_only() -> bool:
  423. """Check if the app is running in frontend-only mode.
  424. Returns:
  425. True if the app is running in frontend-only mode.
  426. """
  427. console.deprecate(
  428. "is_frontend_only() is deprecated and will be removed in a future release.",
  429. reason="Use `environment.REFLEX_FRONTEND_ONLY.get()` instead.",
  430. deprecation_version="0.6.5",
  431. removal_version="0.7.0",
  432. )
  433. return environment.REFLEX_FRONTEND_ONLY.get()
  434. def is_backend_only() -> bool:
  435. """Check if the app is running in backend-only mode.
  436. Returns:
  437. True if the app is running in backend-only mode.
  438. """
  439. console.deprecate(
  440. "is_backend_only() is deprecated and will be removed in a future release.",
  441. reason="Use `environment.REFLEX_BACKEND_ONLY.get()` instead.",
  442. deprecation_version="0.6.5",
  443. removal_version="0.7.0",
  444. )
  445. return environment.REFLEX_BACKEND_ONLY.get()
  446. def should_skip_compile() -> bool:
  447. """Whether the app should skip compile.
  448. Returns:
  449. True if the app should skip compile.
  450. """
  451. console.deprecate(
  452. "should_skip_compile() is deprecated and will be removed in a future release.",
  453. reason="Use `environment.REFLEX_SKIP_COMPILE.get()` instead.",
  454. deprecation_version="0.6.5",
  455. removal_version="0.7.0",
  456. )
  457. return environment.REFLEX_SKIP_COMPILE.get()