autoreload.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. import itertools
  2. import logging
  3. import os
  4. import signal
  5. import subprocess
  6. import sys
  7. import threading
  8. import time
  9. import traceback
  10. import weakref
  11. from collections import defaultdict
  12. from functools import lru_cache, wraps
  13. from pathlib import Path
  14. from types import ModuleType
  15. from zipimport import zipimporter
  16. import django
  17. from django.apps import apps
  18. from django.core.signals import request_finished
  19. from django.dispatch import Signal
  20. from django.utils.functional import cached_property
  21. from django.utils.version import get_version_tuple
  22. autoreload_started = Signal()
  23. file_changed = Signal()
  24. DJANGO_AUTORELOAD_ENV = "RUN_MAIN"
  25. logger = logging.getLogger("django.utils.autoreload")
  26. # If an error is raised while importing a file, it's not placed in sys.modules.
  27. # This means that any future modifications aren't caught. Keep a list of these
  28. # file paths to allow watching them in the future.
  29. _error_files = []
  30. _exception = None
  31. try:
  32. import termios
  33. except ImportError:
  34. termios = None
  35. try:
  36. import pywatchman
  37. except ImportError:
  38. pywatchman = None
  39. def is_django_module(module):
  40. """Return True if the given module is nested under Django."""
  41. return module.__name__.startswith("django.")
  42. def is_django_path(path):
  43. """Return True if the given file path is nested under Django."""
  44. return Path(django.__file__).parent in Path(path).parents
  45. def check_errors(fn):
  46. @wraps(fn)
  47. def wrapper(*args, **kwargs):
  48. global _exception
  49. try:
  50. fn(*args, **kwargs)
  51. except Exception:
  52. _exception = sys.exc_info()
  53. et, ev, tb = _exception
  54. if getattr(ev, "filename", None) is None:
  55. # get the filename from the last item in the stack
  56. filename = traceback.extract_tb(tb)[-1][0]
  57. else:
  58. filename = ev.filename
  59. if filename not in _error_files:
  60. _error_files.append(filename)
  61. raise
  62. return wrapper
  63. def raise_last_exception():
  64. if _exception is not None:
  65. raise _exception[1]
  66. def ensure_echo_on():
  67. """
  68. Ensure that echo mode is enabled. Some tools such as PDB disable
  69. it which causes usability issues after reload.
  70. """
  71. if not termios or not sys.stdin.isatty():
  72. return
  73. attr_list = termios.tcgetattr(sys.stdin)
  74. if not attr_list[3] & termios.ECHO:
  75. attr_list[3] |= termios.ECHO
  76. if hasattr(signal, "SIGTTOU"):
  77. old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
  78. else:
  79. old_handler = None
  80. termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list)
  81. if old_handler is not None:
  82. signal.signal(signal.SIGTTOU, old_handler)
  83. def iter_all_python_module_files():
  84. # This is a hot path during reloading. Create a stable sorted list of
  85. # modules based on the module name and pass it to iter_modules_and_files().
  86. # This ensures cached results are returned in the usual case that modules
  87. # aren't loaded on the fly.
  88. keys = sorted(sys.modules)
  89. modules = tuple(
  90. m
  91. for m in map(sys.modules.__getitem__, keys)
  92. if not isinstance(m, weakref.ProxyTypes)
  93. )
  94. return iter_modules_and_files(modules, frozenset(_error_files))
  95. @lru_cache(maxsize=1)
  96. def iter_modules_and_files(modules, extra_files):
  97. """Iterate through all modules needed to be watched."""
  98. sys_file_paths = []
  99. for module in modules:
  100. # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects
  101. # are added to sys.modules, however they are types not modules and so
  102. # cause issues here.
  103. if not isinstance(module, ModuleType):
  104. continue
  105. if module.__name__ in ("__main__", "__mp_main__"):
  106. # __main__ (usually manage.py) doesn't always have a __spec__ set.
  107. # Handle this by falling back to using __file__, resolved below.
  108. # See https://docs.python.org/reference/import.html#main-spec
  109. # __file__ may not exists, e.g. when running ipdb debugger.
  110. if hasattr(module, "__file__"):
  111. sys_file_paths.append(module.__file__)
  112. continue
  113. if getattr(module, "__spec__", None) is None:
  114. continue
  115. spec = module.__spec__
  116. # Modules could be loaded from places without a concrete location. If
  117. # this is the case, skip them.
  118. if spec.has_location:
  119. origin = (
  120. spec.loader.archive
  121. if isinstance(spec.loader, zipimporter)
  122. else spec.origin
  123. )
  124. sys_file_paths.append(origin)
  125. results = set()
  126. for filename in itertools.chain(sys_file_paths, extra_files):
  127. if not filename:
  128. continue
  129. path = Path(filename)
  130. try:
  131. if not path.exists():
  132. # The module could have been removed, don't fail loudly if this
  133. # is the case.
  134. continue
  135. except ValueError as e:
  136. # Network filesystems may return null bytes in file paths.
  137. logger.debug('"%s" raised when resolving path: "%s"', e, path)
  138. continue
  139. resolved_path = path.resolve().absolute()
  140. results.add(resolved_path)
  141. return frozenset(results)
  142. @lru_cache(maxsize=1)
  143. def common_roots(paths):
  144. """
  145. Return a tuple of common roots that are shared between the given paths.
  146. File system watchers operate on directories and aren't cheap to create.
  147. Try to find the minimum set of directories to watch that encompass all of
  148. the files that need to be watched.
  149. """
  150. # Inspired from Werkzeug:
  151. # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py
  152. # Create a sorted list of the path components, longest first.
  153. path_parts = sorted([x.parts for x in paths], key=len, reverse=True)
  154. tree = {}
  155. for chunks in path_parts:
  156. node = tree
  157. # Add each part of the path to the tree.
  158. for chunk in chunks:
  159. node = node.setdefault(chunk, {})
  160. # Clear the last leaf in the tree.
  161. node.clear()
  162. # Turn the tree into a list of Path instances.
  163. def _walk(node, path):
  164. for prefix, child in node.items():
  165. yield from _walk(child, path + (prefix,))
  166. if not node:
  167. yield Path(*path)
  168. return tuple(_walk(tree, ()))
  169. def sys_path_directories():
  170. """
  171. Yield absolute directories from sys.path, ignoring entries that don't
  172. exist.
  173. """
  174. for path in sys.path:
  175. path = Path(path)
  176. if not path.exists():
  177. continue
  178. resolved_path = path.resolve().absolute()
  179. # If the path is a file (like a zip file), watch the parent directory.
  180. if resolved_path.is_file():
  181. yield resolved_path.parent
  182. else:
  183. yield resolved_path
  184. def get_child_arguments():
  185. """
  186. Return the executable. This contains a workaround for Windows if the
  187. executable is reported to not have the .exe extension which can cause bugs
  188. on reloading.
  189. """
  190. import __main__
  191. py_script = Path(sys.argv[0])
  192. args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions]
  193. if sys.implementation.name == "cpython":
  194. args.extend(
  195. f"-X{key}" if value is True else f"-X{key}={value}"
  196. for key, value in sys._xoptions.items()
  197. )
  198. # __spec__ is set when the server was started with the `-m` option,
  199. # see https://docs.python.org/3/reference/import.html#main-spec
  200. # __spec__ may not exist, e.g. when running in a Conda env.
  201. if getattr(__main__, "__spec__", None) is not None:
  202. spec = __main__.__spec__
  203. if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent:
  204. name = spec.parent
  205. else:
  206. name = spec.name
  207. args += ["-m", name]
  208. args += sys.argv[1:]
  209. elif not py_script.exists():
  210. # sys.argv[0] may not exist for several reasons on Windows.
  211. # It may exist with a .exe extension or have a -script.py suffix.
  212. exe_entrypoint = py_script.with_suffix(".exe")
  213. if exe_entrypoint.exists():
  214. # Should be executed directly, ignoring sys.executable.
  215. return [exe_entrypoint, *sys.argv[1:]]
  216. script_entrypoint = py_script.with_name("%s-script.py" % py_script.name)
  217. if script_entrypoint.exists():
  218. # Should be executed as usual.
  219. return [*args, script_entrypoint, *sys.argv[1:]]
  220. raise RuntimeError("Script %s does not exist." % py_script)
  221. else:
  222. args += sys.argv
  223. return args
  224. def trigger_reload(filename):
  225. logger.info("%s changed, reloading.", filename)
  226. sys.exit(3)
  227. def restart_with_reloader():
  228. new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: "true"}
  229. args = get_child_arguments()
  230. while True:
  231. p = subprocess.run(args, env=new_environ, close_fds=False)
  232. if p.returncode != 3:
  233. return p.returncode
  234. class BaseReloader:
  235. def __init__(self):
  236. self.extra_files = set()
  237. self.directory_globs = defaultdict(set)
  238. self._stop_condition = threading.Event()
  239. def watch_dir(self, path, glob):
  240. path = Path(path)
  241. try:
  242. path = path.absolute()
  243. except FileNotFoundError:
  244. logger.debug(
  245. "Unable to watch directory %s as it cannot be resolved.",
  246. path,
  247. exc_info=True,
  248. )
  249. return
  250. logger.debug("Watching dir %s with glob %s.", path, glob)
  251. self.directory_globs[path].add(glob)
  252. def watched_files(self, include_globs=True):
  253. """
  254. Yield all files that need to be watched, including module files and
  255. files within globs.
  256. """
  257. yield from iter_all_python_module_files()
  258. yield from self.extra_files
  259. if include_globs:
  260. for directory, patterns in self.directory_globs.items():
  261. for pattern in patterns:
  262. yield from directory.glob(pattern)
  263. def wait_for_apps_ready(self, app_reg, django_main_thread):
  264. """
  265. Wait until Django reports that the apps have been loaded. If the given
  266. thread has terminated before the apps are ready, then a SyntaxError or
  267. other non-recoverable error has been raised. In that case, stop waiting
  268. for the apps_ready event and continue processing.
  269. Return True if the thread is alive and the ready event has been
  270. triggered, or False if the thread is terminated while waiting for the
  271. event.
  272. """
  273. while django_main_thread.is_alive():
  274. if app_reg.ready_event.wait(timeout=0.1):
  275. return True
  276. else:
  277. logger.debug("Main Django thread has terminated before apps are ready.")
  278. return False
  279. def run(self, django_main_thread):
  280. logger.debug("Waiting for apps ready_event.")
  281. self.wait_for_apps_ready(apps, django_main_thread)
  282. from django.urls import get_resolver
  283. # Prevent a race condition where URL modules aren't loaded when the
  284. # reloader starts by accessing the urlconf_module property.
  285. try:
  286. get_resolver().urlconf_module
  287. except Exception:
  288. # Loading the urlconf can result in errors during development.
  289. # If this occurs then swallow the error and continue.
  290. pass
  291. logger.debug("Apps ready_event triggered. Sending autoreload_started signal.")
  292. autoreload_started.send(sender=self)
  293. self.run_loop()
  294. def run_loop(self):
  295. ticker = self.tick()
  296. while not self.should_stop:
  297. try:
  298. next(ticker)
  299. except StopIteration:
  300. break
  301. self.stop()
  302. def tick(self):
  303. """
  304. This generator is called in a loop from run_loop. It's important that
  305. the method takes care of pausing or otherwise waiting for a period of
  306. time. This split between run_loop() and tick() is to improve the
  307. testability of the reloader implementations by decoupling the work they
  308. do from the loop.
  309. """
  310. raise NotImplementedError("subclasses must implement tick().")
  311. @classmethod
  312. def check_availability(cls):
  313. raise NotImplementedError("subclasses must implement check_availability().")
  314. def notify_file_changed(self, path):
  315. results = file_changed.send(sender=self, file_path=path)
  316. logger.debug("%s notified as changed. Signal results: %s.", path, results)
  317. if not any(res[1] for res in results):
  318. trigger_reload(path)
  319. # These are primarily used for testing.
  320. @property
  321. def should_stop(self):
  322. return self._stop_condition.is_set()
  323. def stop(self):
  324. self._stop_condition.set()
  325. class StatReloader(BaseReloader):
  326. SLEEP_TIME = 1 # Check for changes once per second.
  327. def tick(self):
  328. mtimes = {}
  329. while True:
  330. for filepath, mtime in self.snapshot_files():
  331. old_time = mtimes.get(filepath)
  332. mtimes[filepath] = mtime
  333. if old_time is None:
  334. logger.debug("File %s first seen with mtime %s", filepath, mtime)
  335. continue
  336. elif mtime > old_time:
  337. logger.debug(
  338. "File %s previous mtime: %s, current mtime: %s",
  339. filepath,
  340. old_time,
  341. mtime,
  342. )
  343. self.notify_file_changed(filepath)
  344. time.sleep(self.SLEEP_TIME)
  345. yield
  346. def snapshot_files(self):
  347. # watched_files may produce duplicate paths if globs overlap.
  348. seen_files = set()
  349. for file in self.watched_files():
  350. if file in seen_files:
  351. continue
  352. try:
  353. mtime = file.stat().st_mtime
  354. except OSError:
  355. # This is thrown when the file does not exist.
  356. continue
  357. seen_files.add(file)
  358. yield file, mtime
  359. @classmethod
  360. def check_availability(cls):
  361. return True
  362. class WatchmanUnavailable(RuntimeError):
  363. pass
  364. class WatchmanReloader(BaseReloader):
  365. def __init__(self):
  366. self.roots = defaultdict(set)
  367. self.processed_request = threading.Event()
  368. self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5))
  369. super().__init__()
  370. @cached_property
  371. def client(self):
  372. return pywatchman.client(timeout=self.client_timeout)
  373. def _watch_root(self, root):
  374. # In practice this shouldn't occur, however, it's possible that a
  375. # directory that doesn't exist yet is being watched. If it's outside of
  376. # sys.path then this will end up a new root. How to handle this isn't
  377. # clear: Not adding the root will likely break when subscribing to the
  378. # changes, however, as this is currently an internal API, no files
  379. # will be being watched outside of sys.path. Fixing this by checking
  380. # inside watch_glob() and watch_dir() is expensive, instead this could
  381. # could fall back to the StatReloader if this case is detected? For
  382. # now, watching its parent, if possible, is sufficient.
  383. if not root.exists():
  384. if not root.parent.exists():
  385. logger.warning(
  386. "Unable to watch root dir %s as neither it or its parent exist.",
  387. root,
  388. )
  389. return
  390. root = root.parent
  391. result = self.client.query("watch-project", str(root.absolute()))
  392. if "warning" in result:
  393. logger.warning("Watchman warning: %s", result["warning"])
  394. logger.debug("Watchman watch-project result: %s", result)
  395. return result["watch"], result.get("relative_path")
  396. @lru_cache
  397. def _get_clock(self, root):
  398. return self.client.query("clock", root)["clock"]
  399. def _subscribe(self, directory, name, expression):
  400. root, rel_path = self._watch_root(directory)
  401. # Only receive notifications of files changing, filtering out other types
  402. # like special files: https://facebook.github.io/watchman/docs/type
  403. only_files_expression = [
  404. "allof",
  405. ["anyof", ["type", "f"], ["type", "l"]],
  406. expression,
  407. ]
  408. query = {
  409. "expression": only_files_expression,
  410. "fields": ["name"],
  411. "since": self._get_clock(root),
  412. "dedup_results": True,
  413. }
  414. if rel_path:
  415. query["relative_root"] = rel_path
  416. logger.debug(
  417. "Issuing watchman subscription %s, for root %s. Query: %s",
  418. name,
  419. root,
  420. query,
  421. )
  422. self.client.query("subscribe", root, name, query)
  423. def _subscribe_dir(self, directory, filenames):
  424. if not directory.exists():
  425. if not directory.parent.exists():
  426. logger.warning(
  427. "Unable to watch directory %s as neither it or its parent exist.",
  428. directory,
  429. )
  430. return
  431. prefix = "files-parent-%s" % directory.name
  432. filenames = ["%s/%s" % (directory.name, filename) for filename in filenames]
  433. directory = directory.parent
  434. expression = ["name", filenames, "wholename"]
  435. else:
  436. prefix = "files"
  437. expression = ["name", filenames]
  438. self._subscribe(directory, "%s:%s" % (prefix, directory), expression)
  439. def _watch_glob(self, directory, patterns):
  440. """
  441. Watch a directory with a specific glob. If the directory doesn't yet
  442. exist, attempt to watch the parent directory and amend the patterns to
  443. include this. It's important this method isn't called more than one per
  444. directory when updating all subscriptions. Subsequent calls will
  445. overwrite the named subscription, so it must include all possible glob
  446. expressions.
  447. """
  448. prefix = "glob"
  449. if not directory.exists():
  450. if not directory.parent.exists():
  451. logger.warning(
  452. "Unable to watch directory %s as neither it or its parent exist.",
  453. directory,
  454. )
  455. return
  456. prefix = "glob-parent-%s" % directory.name
  457. patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns]
  458. directory = directory.parent
  459. expression = ["anyof"]
  460. for pattern in patterns:
  461. expression.append(["match", pattern, "wholename"])
  462. self._subscribe(directory, "%s:%s" % (prefix, directory), expression)
  463. def watched_roots(self, watched_files):
  464. extra_directories = self.directory_globs.keys()
  465. watched_file_dirs = [f.parent for f in watched_files]
  466. sys_paths = list(sys_path_directories())
  467. return frozenset((*extra_directories, *watched_file_dirs, *sys_paths))
  468. def _update_watches(self):
  469. watched_files = list(self.watched_files(include_globs=False))
  470. found_roots = common_roots(self.watched_roots(watched_files))
  471. logger.debug("Watching %s files", len(watched_files))
  472. logger.debug("Found common roots: %s", found_roots)
  473. # Setup initial roots for performance, shortest roots first.
  474. for root in sorted(found_roots):
  475. self._watch_root(root)
  476. for directory, patterns in self.directory_globs.items():
  477. self._watch_glob(directory, patterns)
  478. # Group sorted watched_files by their parent directory.
  479. sorted_files = sorted(watched_files, key=lambda p: p.parent)
  480. for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent):
  481. # These paths need to be relative to the parent directory.
  482. self._subscribe_dir(
  483. directory, [str(p.relative_to(directory)) for p in group]
  484. )
  485. def update_watches(self):
  486. try:
  487. self._update_watches()
  488. except Exception as ex:
  489. # If the service is still available, raise the original exception.
  490. if self.check_server_status(ex):
  491. raise
  492. def _check_subscription(self, sub):
  493. subscription = self.client.getSubscription(sub)
  494. if not subscription:
  495. return
  496. logger.debug("Watchman subscription %s has results.", sub)
  497. for result in subscription:
  498. # When using watch-project, it's not simple to get the relative
  499. # directory without storing some specific state. Store the full
  500. # path to the directory in the subscription name, prefixed by its
  501. # type (glob, files).
  502. root_directory = Path(result["subscription"].split(":", 1)[1])
  503. logger.debug("Found root directory %s", root_directory)
  504. for file in result.get("files", []):
  505. self.notify_file_changed(root_directory / file)
  506. def request_processed(self, **kwargs):
  507. logger.debug("Request processed. Setting update_watches event.")
  508. self.processed_request.set()
  509. def tick(self):
  510. request_finished.connect(self.request_processed)
  511. self.update_watches()
  512. while True:
  513. if self.processed_request.is_set():
  514. self.update_watches()
  515. self.processed_request.clear()
  516. try:
  517. self.client.receive()
  518. except pywatchman.SocketTimeout:
  519. pass
  520. except pywatchman.WatchmanError as ex:
  521. logger.debug("Watchman error: %s, checking server status.", ex)
  522. self.check_server_status(ex)
  523. else:
  524. for sub in list(self.client.subs.keys()):
  525. self._check_subscription(sub)
  526. yield
  527. # Protect against busy loops.
  528. time.sleep(0.1)
  529. def stop(self):
  530. self.client.close()
  531. super().stop()
  532. def check_server_status(self, inner_ex=None):
  533. """Return True if the server is available."""
  534. try:
  535. self.client.query("version")
  536. except Exception:
  537. raise WatchmanUnavailable(str(inner_ex)) from inner_ex
  538. return True
  539. @classmethod
  540. def check_availability(cls):
  541. if not pywatchman:
  542. raise WatchmanUnavailable("pywatchman not installed.")
  543. client = pywatchman.client(timeout=0.1)
  544. try:
  545. result = client.capabilityCheck()
  546. except Exception:
  547. # The service is down?
  548. raise WatchmanUnavailable("Cannot connect to the watchman service.")
  549. version = get_version_tuple(result["version"])
  550. # Watchman 4.9 includes multiple improvements to watching project
  551. # directories as well as case insensitive filesystems.
  552. logger.debug("Watchman version %s", version)
  553. if version < (4, 9):
  554. raise WatchmanUnavailable("Watchman 4.9 or later is required.")
  555. def get_reloader():
  556. """Return the most suitable reloader for this environment."""
  557. try:
  558. WatchmanReloader.check_availability()
  559. except WatchmanUnavailable:
  560. return StatReloader()
  561. return WatchmanReloader()
  562. def start_django(reloader, main_func, *args, **kwargs):
  563. ensure_echo_on()
  564. main_func = check_errors(main_func)
  565. django_main_thread = threading.Thread(
  566. target=main_func, args=args, kwargs=kwargs, name="django-main-thread"
  567. )
  568. django_main_thread.daemon = True
  569. django_main_thread.start()
  570. while not reloader.should_stop:
  571. reloader.run(django_main_thread)
  572. def run_with_reloader(main_func, *args, **kwargs):
  573. signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  574. try:
  575. if os.environ.get(DJANGO_AUTORELOAD_ENV) == "true":
  576. reloader = get_reloader()
  577. logger.info(
  578. "Watching for file changes with %s", reloader.__class__.__name__
  579. )
  580. start_django(reloader, main_func, *args, **kwargs)
  581. else:
  582. exit_code = restart_with_reloader()
  583. sys.exit(exit_code)
  584. except KeyboardInterrupt:
  585. pass