exec.py 11 KB

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