exec.py 11 KB

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