autoreload.py 22 KB

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