autoreload.py 24 KB

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