autoreload.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #
  2. # Copyright 2009 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """Automatically restart the server when a source file is modified.
  16. Most applications should not access this module directly. Instead,
  17. pass the keyword argument ``autoreload=True`` to the
  18. `tornado.web.Application` constructor (or ``debug=True``, which
  19. enables this setting and several others). This will enable autoreload
  20. mode as well as checking for changes to templates and static
  21. resources. Note that restarting is a destructive operation and any
  22. requests in progress will be aborted when the process restarts. (If
  23. you want to disable autoreload while using other debug-mode features,
  24. pass both ``debug=True`` and ``autoreload=False``).
  25. This module can also be used as a command-line wrapper around scripts
  26. such as unit test runners. See the `main` method for details.
  27. The command-line wrapper and Application debug modes can be used together.
  28. This combination is encouraged as the wrapper catches syntax errors and
  29. other import-time failures, while debug mode catches changes once
  30. the server has started.
  31. This module will not work correctly when `.HTTPServer`'s multi-process
  32. mode is used.
  33. Reloading loses any Python interpreter command-line arguments (e.g. ``-u``)
  34. because it re-executes Python using ``sys.executable`` and ``sys.argv``.
  35. Additionally, modifying these variables will cause reloading to behave
  36. incorrectly.
  37. """
  38. import os
  39. import sys
  40. # sys.path handling
  41. # -----------------
  42. #
  43. # If a module is run with "python -m", the current directory (i.e. "")
  44. # is automatically prepended to sys.path, but not if it is run as
  45. # "path/to/file.py". The processing for "-m" rewrites the former to
  46. # the latter, so subsequent executions won't have the same path as the
  47. # original.
  48. #
  49. # Conversely, when run as path/to/file.py, the directory containing
  50. # file.py gets added to the path, which can cause confusion as imports
  51. # may become relative in spite of the future import.
  52. #
  53. # We address the former problem by reconstructing the original command
  54. # line (Python >= 3.4) or by setting the $PYTHONPATH environment
  55. # variable (Python < 3.4) before re-execution so the new process will
  56. # see the correct path. We attempt to address the latter problem when
  57. # tornado.autoreload is run as __main__.
  58. if __name__ == "__main__":
  59. # This sys.path manipulation must come before our imports (as much
  60. # as possible - if we introduced a tornado.sys or tornado.os
  61. # module we'd be in trouble), or else our imports would become
  62. # relative again despite the future import.
  63. #
  64. # There is a separate __main__ block at the end of the file to call main().
  65. if sys.path[0] == os.path.dirname(__file__):
  66. del sys.path[0]
  67. import functools
  68. import logging
  69. import os
  70. import pkgutil # type: ignore
  71. import sys
  72. import traceback
  73. import types
  74. import subprocess
  75. import weakref
  76. from tornado import ioloop
  77. from tornado.log import gen_log
  78. from tornado import process
  79. from tornado.util import exec_in
  80. try:
  81. import signal
  82. except ImportError:
  83. signal = None # type: ignore
  84. import typing
  85. from typing import Callable, Dict
  86. if typing.TYPE_CHECKING:
  87. from typing import List, Optional, Union # noqa: F401
  88. # os.execv is broken on Windows and can't properly parse command line
  89. # arguments and executable name if they contain whitespaces. subprocess
  90. # fixes that behavior.
  91. _has_execv = sys.platform != "win32"
  92. _watched_files = set()
  93. _reload_hooks = []
  94. _reload_attempted = False
  95. _io_loops = weakref.WeakKeyDictionary() # type: ignore
  96. _autoreload_is_main = False
  97. _original_argv = None # type: Optional[List[str]]
  98. _original_spec = None
  99. def start(check_time: int = 500) -> None:
  100. """Begins watching source files for changes.
  101. .. versionchanged:: 5.0
  102. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  103. """
  104. io_loop = ioloop.IOLoop.current()
  105. if io_loop in _io_loops:
  106. return
  107. _io_loops[io_loop] = True
  108. if len(_io_loops) > 1:
  109. gen_log.warning("tornado.autoreload started more than once in the same process")
  110. modify_times = {} # type: Dict[str, float]
  111. callback = functools.partial(_reload_on_update, modify_times)
  112. scheduler = ioloop.PeriodicCallback(callback, check_time)
  113. scheduler.start()
  114. def wait() -> None:
  115. """Wait for a watched file to change, then restart the process.
  116. Intended to be used at the end of scripts like unit test runners,
  117. to run the tests again after any source file changes (but see also
  118. the command-line interface in `main`)
  119. """
  120. io_loop = ioloop.IOLoop()
  121. io_loop.add_callback(start)
  122. io_loop.start()
  123. def watch(filename: str) -> None:
  124. """Add a file to the watch list.
  125. All imported modules are watched by default.
  126. """
  127. _watched_files.add(filename)
  128. def add_reload_hook(fn: Callable[[], None]) -> None:
  129. """Add a function to be called before reloading the process.
  130. Note that for open file and socket handles it is generally
  131. preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or
  132. ``tornado.platform.auto.set_close_exec``) instead
  133. of using a reload hook to close them.
  134. """
  135. _reload_hooks.append(fn)
  136. def _reload_on_update(modify_times: Dict[str, float]) -> None:
  137. if _reload_attempted:
  138. # We already tried to reload and it didn't work, so don't try again.
  139. return
  140. if process.task_id() is not None:
  141. # We're in a child process created by fork_processes. If child
  142. # processes restarted themselves, they'd all restart and then
  143. # all call fork_processes again.
  144. return
  145. for module in list(sys.modules.values()):
  146. # Some modules play games with sys.modules (e.g. email/__init__.py
  147. # in the standard library), and occasionally this can cause strange
  148. # failures in getattr. Just ignore anything that's not an ordinary
  149. # module.
  150. if not isinstance(module, types.ModuleType):
  151. continue
  152. path = getattr(module, "__file__", None)
  153. if not path:
  154. continue
  155. if path.endswith(".pyc") or path.endswith(".pyo"):
  156. path = path[:-1]
  157. _check_file(modify_times, path)
  158. for path in _watched_files:
  159. _check_file(modify_times, path)
  160. def _check_file(modify_times: Dict[str, float], path: str) -> None:
  161. try:
  162. modified = os.stat(path).st_mtime
  163. except Exception:
  164. return
  165. if path not in modify_times:
  166. modify_times[path] = modified
  167. return
  168. if modify_times[path] != modified:
  169. gen_log.info("%s modified; restarting server", path)
  170. _reload()
  171. def _reload() -> None:
  172. global _reload_attempted
  173. _reload_attempted = True
  174. for fn in _reload_hooks:
  175. fn()
  176. if hasattr(signal, "setitimer"):
  177. # Clear the alarm signal set by
  178. # ioloop.set_blocking_log_threshold so it doesn't fire
  179. # after the exec.
  180. signal.setitimer(signal.ITIMER_REAL, 0, 0)
  181. # sys.path fixes: see comments at top of file. If __main__.__spec__
  182. # exists, we were invoked with -m and the effective path is about to
  183. # change on re-exec. Reconstruct the original command line to
  184. # ensure that the new process sees the same path we did. If
  185. # __spec__ is not available (Python < 3.4), check instead if
  186. # sys.path[0] is an empty string and add the current directory to
  187. # $PYTHONPATH.
  188. if _autoreload_is_main:
  189. assert _original_argv is not None
  190. spec = _original_spec
  191. argv = _original_argv
  192. else:
  193. spec = getattr(sys.modules["__main__"], "__spec__", None)
  194. argv = sys.argv
  195. if spec:
  196. argv = ["-m", spec.name] + argv[1:]
  197. else:
  198. path_prefix = "." + os.pathsep
  199. if sys.path[0] == "" and not os.environ.get("PYTHONPATH", "").startswith(
  200. path_prefix
  201. ):
  202. os.environ["PYTHONPATH"] = path_prefix + os.environ.get("PYTHONPATH", "")
  203. if not _has_execv:
  204. subprocess.Popen([sys.executable] + argv)
  205. os._exit(0)
  206. else:
  207. try:
  208. os.execv(sys.executable, [sys.executable] + argv)
  209. except OSError:
  210. # Mac OS X versions prior to 10.6 do not support execv in
  211. # a process that contains multiple threads. Instead of
  212. # re-executing in the current process, start a new one
  213. # and cause the current process to exit. This isn't
  214. # ideal since the new process is detached from the parent
  215. # terminal and thus cannot easily be killed with ctrl-C,
  216. # but it's better than not being able to autoreload at
  217. # all.
  218. # Unfortunately the errno returned in this case does not
  219. # appear to be consistent, so we can't easily check for
  220. # this error specifically.
  221. os.spawnv( # type: ignore
  222. os.P_NOWAIT, sys.executable, [sys.executable] + argv
  223. )
  224. # At this point the IOLoop has been closed and finally
  225. # blocks will experience errors if we allow the stack to
  226. # unwind, so just exit uncleanly.
  227. os._exit(0)
  228. _USAGE = """\
  229. Usage:
  230. python -m tornado.autoreload -m module.to.run [args...]
  231. python -m tornado.autoreload path/to/script.py [args...]
  232. """
  233. def main() -> None:
  234. """Command-line wrapper to re-run a script whenever its source changes.
  235. Scripts may be specified by filename or module name::
  236. python -m tornado.autoreload -m tornado.test.runtests
  237. python -m tornado.autoreload tornado/test/runtests.py
  238. Running a script with this wrapper is similar to calling
  239. `tornado.autoreload.wait` at the end of the script, but this wrapper
  240. can catch import-time problems like syntax errors that would otherwise
  241. prevent the script from reaching its call to `wait`.
  242. """
  243. # Remember that we were launched with autoreload as main.
  244. # The main module can be tricky; set the variables both in our globals
  245. # (which may be __main__) and the real importable version.
  246. import tornado.autoreload
  247. global _autoreload_is_main
  248. global _original_argv, _original_spec
  249. tornado.autoreload._autoreload_is_main = _autoreload_is_main = True
  250. original_argv = sys.argv
  251. tornado.autoreload._original_argv = _original_argv = original_argv
  252. original_spec = getattr(sys.modules["__main__"], "__spec__", None)
  253. tornado.autoreload._original_spec = _original_spec = original_spec
  254. sys.argv = sys.argv[:]
  255. if len(sys.argv) >= 3 and sys.argv[1] == "-m":
  256. mode = "module"
  257. module = sys.argv[2]
  258. del sys.argv[1:3]
  259. elif len(sys.argv) >= 2:
  260. mode = "script"
  261. script = sys.argv[1]
  262. sys.argv = sys.argv[1:]
  263. else:
  264. print(_USAGE, file=sys.stderr)
  265. sys.exit(1)
  266. try:
  267. if mode == "module":
  268. import runpy
  269. runpy.run_module(module, run_name="__main__", alter_sys=True)
  270. elif mode == "script":
  271. with open(script) as f:
  272. # Execute the script in our namespace instead of creating
  273. # a new one so that something that tries to import __main__
  274. # (e.g. the unittest module) will see names defined in the
  275. # script instead of just those defined in this module.
  276. global __file__
  277. __file__ = script
  278. # If __package__ is defined, imports may be incorrectly
  279. # interpreted as relative to this module.
  280. global __package__
  281. del __package__
  282. exec_in(f.read(), globals(), globals())
  283. except SystemExit as e:
  284. logging.basicConfig()
  285. gen_log.info("Script exited with status %s", e.code)
  286. except Exception as e:
  287. logging.basicConfig()
  288. gen_log.warning("Script exited with uncaught exception", exc_info=True)
  289. # If an exception occurred at import time, the file with the error
  290. # never made it into sys.modules and so we won't know to watch it.
  291. # Just to make sure we've covered everything, walk the stack trace
  292. # from the exception and watch every file.
  293. for (filename, lineno, name, line) in traceback.extract_tb(sys.exc_info()[2]):
  294. watch(filename)
  295. if isinstance(e, SyntaxError):
  296. # SyntaxErrors are special: their innermost stack frame is fake
  297. # so extract_tb won't see it and we have to get the filename
  298. # from the exception object.
  299. watch(e.filename)
  300. else:
  301. logging.basicConfig()
  302. gen_log.info("Script exited normally")
  303. # restore sys.argv so subsequent executions will include autoreload
  304. sys.argv = original_argv
  305. if mode == "module":
  306. # runpy did a fake import of the module as __main__, but now it's
  307. # no longer in sys.modules. Figure out where it is and watch it.
  308. loader = pkgutil.get_loader(module)
  309. if loader is not None:
  310. watch(loader.get_filename()) # type: ignore
  311. wait()
  312. if __name__ == "__main__":
  313. # See also the other __main__ block at the top of the file, which modifies
  314. # sys.path before our imports
  315. main()