You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autoreload.py 22KB

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