exec.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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], backend_present=True):
  57. """Run the process and launch the URL.
  58. Args:
  59. run_command: The command to run.
  60. backend_present: Whether the backend is present.
  61. """
  62. from reflex.utils import processes
  63. json_file_path = os.path.join(constants.Dirs.WEB, "package.json")
  64. last_hash = detect_package_change(json_file_path)
  65. process = None
  66. first_run = True
  67. while True:
  68. if process is None:
  69. kwargs = {}
  70. if constants.IS_WINDOWS and backend_present:
  71. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  72. process = processes.new_process(
  73. run_command,
  74. cwd=constants.Dirs.WEB,
  75. shell=constants.IS_WINDOWS,
  76. **kwargs,
  77. )
  78. global frontend_process
  79. frontend_process = process
  80. if process.stdout:
  81. for line in processes.stream_logs("Starting frontend", process):
  82. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  83. if match:
  84. if first_run:
  85. url = match.group(1)
  86. if get_config().frontend_path != "":
  87. url = urljoin(url, get_config().frontend_path)
  88. console.print(
  89. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  90. )
  91. if backend_present:
  92. console.print(
  93. f"Backend running at: [bold green]http://0.0.0.0:{get_config().backend_port}[/bold green]"
  94. )
  95. first_run = False
  96. else:
  97. console.print("New packages detected: Updating app...")
  98. else:
  99. if any(
  100. [x in line for x in ("bin executable does not exist on disk",)]
  101. ):
  102. console.error(
  103. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  104. "`REFLEX_USE_NPM=1 reflex init`\n"
  105. "`REFLEX_USE_NPM=1 reflex run`"
  106. )
  107. new_hash = detect_package_change(json_file_path)
  108. if new_hash != last_hash:
  109. last_hash = new_hash
  110. kill(process.pid)
  111. process = None
  112. break # for line in process.stdout
  113. if process is not None:
  114. break # while True
  115. def run_frontend(root: Path, port: str, backend_present=True):
  116. """Run the frontend.
  117. Args:
  118. root: The root path of the project.
  119. port: The port to run the frontend on.
  120. backend_present: Whether the backend is present.
  121. """
  122. from reflex.utils import prerequisites
  123. # Start watching asset folder.
  124. start_watching_assets_folder(root)
  125. # validate dependencies before run
  126. prerequisites.validate_frontend_dependencies(init=False)
  127. # Run the frontend in development mode.
  128. console.rule("[bold green]App Running")
  129. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  130. run_process_and_launch_url(
  131. [prerequisites.get_package_manager(), "run", "dev"], # type: ignore
  132. backend_present,
  133. )
  134. def run_frontend_prod(root: Path, port: str, backend_present=True):
  135. """Run the frontend.
  136. Args:
  137. root: The root path of the project (to keep same API as run_frontend).
  138. port: The port to run the frontend on.
  139. backend_present: Whether the backend is present.
  140. """
  141. from reflex.utils import prerequisites
  142. # Set the port.
  143. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  144. # validate dependencies before run
  145. prerequisites.validate_frontend_dependencies(init=False)
  146. # Run the frontend in production mode.
  147. console.rule("[bold green]App Running")
  148. run_process_and_launch_url(
  149. [prerequisites.get_package_manager(), "run", "prod"], # type: ignore
  150. backend_present,
  151. )
  152. def run_backend(
  153. host: str,
  154. port: int,
  155. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  156. ):
  157. """Run the backend.
  158. Args:
  159. host: The app host
  160. port: The app port
  161. loglevel: The log level.
  162. """
  163. import uvicorn
  164. config = get_config()
  165. app_module = f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  166. # Create a .nocompile file to skip compile for backend.
  167. if os.path.exists(constants.Dirs.WEB):
  168. with open(constants.NOCOMPILE_FILE, "w"):
  169. pass
  170. # Run the backend in development mode.
  171. uvicorn.run(
  172. app=f"{app_module}.{constants.CompileVars.API}",
  173. host=host,
  174. port=port,
  175. log_level=loglevel.value,
  176. reload=True,
  177. reload_dirs=[config.app_name],
  178. reload_excludes=[constants.Dirs.WEB],
  179. )
  180. def run_backend_prod(
  181. host: str,
  182. port: int,
  183. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  184. ):
  185. """Run the backend.
  186. Args:
  187. host: The app host
  188. port: The app port
  189. loglevel: The log level.
  190. """
  191. from reflex.utils import processes
  192. config = get_config()
  193. num_workers = (
  194. processes.get_num_workers()
  195. if not config.gunicorn_workers
  196. else config.gunicorn_workers
  197. )
  198. RUN_BACKEND_PROD = f"gunicorn --worker-class {config.gunicorn_worker_class} --preload --timeout {config.timeout} --log-level critical".split()
  199. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --timeout-keep-alive {config.timeout}".split()
  200. app_module = f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  201. command = (
  202. [
  203. *RUN_BACKEND_PROD_WINDOWS,
  204. "--host",
  205. host,
  206. "--port",
  207. str(port),
  208. app_module,
  209. ]
  210. if constants.IS_WINDOWS
  211. else [
  212. *RUN_BACKEND_PROD,
  213. "--bind",
  214. f"{host}:{port}",
  215. "--threads",
  216. str(num_workers),
  217. f"{app_module}()",
  218. ]
  219. )
  220. command += [
  221. "--log-level",
  222. loglevel.value,
  223. "--workers",
  224. str(num_workers),
  225. ]
  226. processes.new_process(
  227. command,
  228. run=True,
  229. show_logs=True,
  230. env={constants.SKIP_COMPILE_ENV_VAR: "yes"}, # skip compile for prod backend
  231. )
  232. def output_system_info():
  233. """Show system information if the loglevel is in DEBUG."""
  234. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  235. return
  236. from reflex.utils import prerequisites
  237. config = get_config()
  238. try:
  239. config_file = sys.modules[config.__module__].__file__
  240. except Exception:
  241. config_file = None
  242. console.rule(f"System Info")
  243. console.debug(f"Config file: {config_file!r}")
  244. console.debug(f"Config: {config}")
  245. dependencies = [
  246. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  247. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  248. ]
  249. system = platform.system()
  250. if (
  251. system != "Windows"
  252. or system == "Windows"
  253. and prerequisites.is_windows_bun_supported()
  254. ):
  255. dependencies.extend(
  256. [
  257. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  258. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  259. ],
  260. )
  261. else:
  262. dependencies.append(
  263. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  264. )
  265. if system == "Linux":
  266. import distro # type: ignore
  267. os_version = distro.name(pretty=True)
  268. else:
  269. os_version = platform.version()
  270. dependencies.append(f"[OS {platform.system()} {os_version}]")
  271. for dep in dependencies:
  272. console.debug(f"{dep}")
  273. console.debug(
  274. f"Using package installer at: {prerequisites.get_install_package_manager()}" # type: ignore
  275. )
  276. console.debug(f"Using package executer at: {prerequisites.get_package_manager()}") # type: ignore
  277. if system != "Windows":
  278. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  279. def is_testing_env() -> bool:
  280. """Whether the app is running in a testing environment.
  281. Returns:
  282. True if the app is running in under pytest.
  283. """
  284. return constants.PYTEST_CURRENT_TEST in os.environ
  285. def is_prod_mode() -> bool:
  286. """Check if the app is running in production mode.
  287. Returns:
  288. True if the app is running in production mode or False if running in dev mode.
  289. """
  290. current_mode = os.environ.get(
  291. constants.ENV_MODE_ENV_VAR,
  292. constants.Env.DEV.value,
  293. )
  294. return current_mode == constants.Env.PROD.value
  295. def should_skip_compile() -> bool:
  296. """Whether the app should skip compile.
  297. Returns:
  298. True if the app should skip compile.
  299. """
  300. return os.environ.get(constants.SKIP_COMPILE_ENV_VAR) == "yes"