exec.py 11 KB

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