exec.py 10 KB

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