process.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2011 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """Utilities for working with multiple processes, including both forking
  17. the server into multiple processes and managing subprocesses.
  18. """
  19. from __future__ import absolute_import, division, print_function, with_statement
  20. import errno
  21. import os
  22. import signal
  23. import subprocess
  24. import sys
  25. import time
  26. from binascii import hexlify
  27. from tornado.concurrent import Future
  28. from tornado import ioloop
  29. from tornado.iostream import PipeIOStream
  30. from tornado.log import gen_log
  31. from tornado.platform.auto import set_close_exec
  32. from tornado import stack_context
  33. from tornado.util import errno_from_exception
  34. try:
  35. import multiprocessing
  36. except ImportError:
  37. # Multiprocessing is not available on Google App Engine.
  38. multiprocessing = None
  39. try:
  40. long # py2
  41. except NameError:
  42. long = int # py3
  43. # Re-export this exception for convenience.
  44. try:
  45. CalledProcessError = subprocess.CalledProcessError
  46. except AttributeError:
  47. # The subprocess module exists in Google App Engine, but is empty.
  48. # This module isn't very useful in that case, but it should
  49. # at least be importable.
  50. if 'APPENGINE_RUNTIME' not in os.environ:
  51. raise
  52. def cpu_count():
  53. """Returns the number of processors on this machine."""
  54. if multiprocessing is None:
  55. return 1
  56. try:
  57. return multiprocessing.cpu_count()
  58. except NotImplementedError:
  59. pass
  60. try:
  61. return os.sysconf("SC_NPROCESSORS_CONF")
  62. except ValueError:
  63. pass
  64. gen_log.error("Could not detect number of processors; assuming 1")
  65. return 1
  66. def _reseed_random():
  67. if 'random' not in sys.modules:
  68. return
  69. import random
  70. # If os.urandom is available, this method does the same thing as
  71. # random.seed (at least as of python 2.6). If os.urandom is not
  72. # available, we mix in the pid in addition to a timestamp.
  73. try:
  74. seed = long(hexlify(os.urandom(16)), 16)
  75. except NotImplementedError:
  76. seed = int(time.time() * 1000) ^ os.getpid()
  77. random.seed(seed)
  78. def _pipe_cloexec():
  79. r, w = os.pipe()
  80. set_close_exec(r)
  81. set_close_exec(w)
  82. return r, w
  83. _task_id = None
  84. def fork_processes(num_processes, max_restarts=100):
  85. """Starts multiple worker processes.
  86. If ``num_processes`` is None or <= 0, we detect the number of cores
  87. available on this machine and fork that number of child
  88. processes. If ``num_processes`` is given and > 0, we fork that
  89. specific number of sub-processes.
  90. Since we use processes and not threads, there is no shared memory
  91. between any server code.
  92. Note that multiple processes are not compatible with the autoreload
  93. module (or the ``autoreload=True`` option to `tornado.web.Application`
  94. which defaults to True when ``debug=True``).
  95. When using multiple processes, no IOLoops can be created or
  96. referenced until after the call to ``fork_processes``.
  97. In each child process, ``fork_processes`` returns its *task id*, a
  98. number between 0 and ``num_processes``. Processes that exit
  99. abnormally (due to a signal or non-zero exit status) are restarted
  100. with the same id (up to ``max_restarts`` times). In the parent
  101. process, ``fork_processes`` returns None if all child processes
  102. have exited normally, but will otherwise only exit by throwing an
  103. exception.
  104. """
  105. global _task_id
  106. assert _task_id is None
  107. if num_processes is None or num_processes <= 0:
  108. num_processes = cpu_count()
  109. if ioloop.IOLoop.initialized():
  110. raise RuntimeError("Cannot run in multiple processes: IOLoop instance "
  111. "has already been initialized. You cannot call "
  112. "IOLoop.instance() before calling start_processes()")
  113. gen_log.info("Starting %d processes", num_processes)
  114. children = {}
  115. def start_child(i):
  116. pid = os.fork()
  117. if pid == 0:
  118. # child process
  119. _reseed_random()
  120. global _task_id
  121. _task_id = i
  122. return i
  123. else:
  124. children[pid] = i
  125. return None
  126. for i in range(num_processes):
  127. id = start_child(i)
  128. if id is not None:
  129. return id
  130. num_restarts = 0
  131. while children:
  132. try:
  133. pid, status = os.wait()
  134. except OSError as e:
  135. if errno_from_exception(e) == errno.EINTR:
  136. continue
  137. raise
  138. if pid not in children:
  139. continue
  140. id = children.pop(pid)
  141. if os.WIFSIGNALED(status):
  142. gen_log.warning("child %d (pid %d) killed by signal %d, restarting",
  143. id, pid, os.WTERMSIG(status))
  144. elif os.WEXITSTATUS(status) != 0:
  145. gen_log.warning("child %d (pid %d) exited with status %d, restarting",
  146. id, pid, os.WEXITSTATUS(status))
  147. else:
  148. gen_log.info("child %d (pid %d) exited normally", id, pid)
  149. continue
  150. num_restarts += 1
  151. if num_restarts > max_restarts:
  152. raise RuntimeError("Too many child restarts, giving up")
  153. new_id = start_child(id)
  154. if new_id is not None:
  155. return new_id
  156. # All child processes exited cleanly, so exit the master process
  157. # instead of just returning to right after the call to
  158. # fork_processes (which will probably just start up another IOLoop
  159. # unless the caller checks the return value).
  160. sys.exit(0)
  161. def task_id():
  162. """Returns the current task id, if any.
  163. Returns None if this process was not created by `fork_processes`.
  164. """
  165. global _task_id
  166. return _task_id
  167. class Subprocess(object):
  168. """Wraps ``subprocess.Popen`` with IOStream support.
  169. The constructor is the same as ``subprocess.Popen`` with the following
  170. additions:
  171. * ``stdin``, ``stdout``, and ``stderr`` may have the value
  172. ``tornado.process.Subprocess.STREAM``, which will make the corresponding
  173. attribute of the resulting Subprocess a `.PipeIOStream`.
  174. * A new keyword argument ``io_loop`` may be used to pass in an IOLoop.
  175. .. versionchanged:: 4.1
  176. The ``io_loop`` argument is deprecated.
  177. """
  178. STREAM = object()
  179. _initialized = False
  180. _waiting = {}
  181. def __init__(self, *args, **kwargs):
  182. self.io_loop = kwargs.pop('io_loop', None) or ioloop.IOLoop.current()
  183. # All FDs we create should be closed on error; those in to_close
  184. # should be closed in the parent process on success.
  185. pipe_fds = []
  186. to_close = []
  187. if kwargs.get('stdin') is Subprocess.STREAM:
  188. in_r, in_w = _pipe_cloexec()
  189. kwargs['stdin'] = in_r
  190. pipe_fds.extend((in_r, in_w))
  191. to_close.append(in_r)
  192. self.stdin = PipeIOStream(in_w, io_loop=self.io_loop)
  193. if kwargs.get('stdout') is Subprocess.STREAM:
  194. out_r, out_w = _pipe_cloexec()
  195. kwargs['stdout'] = out_w
  196. pipe_fds.extend((out_r, out_w))
  197. to_close.append(out_w)
  198. self.stdout = PipeIOStream(out_r, io_loop=self.io_loop)
  199. if kwargs.get('stderr') is Subprocess.STREAM:
  200. err_r, err_w = _pipe_cloexec()
  201. kwargs['stderr'] = err_w
  202. pipe_fds.extend((err_r, err_w))
  203. to_close.append(err_w)
  204. self.stderr = PipeIOStream(err_r, io_loop=self.io_loop)
  205. try:
  206. self.proc = subprocess.Popen(*args, **kwargs)
  207. except:
  208. for fd in pipe_fds:
  209. os.close(fd)
  210. raise
  211. for fd in to_close:
  212. os.close(fd)
  213. for attr in ['stdin', 'stdout', 'stderr', 'pid']:
  214. if not hasattr(self, attr): # don't clobber streams set above
  215. setattr(self, attr, getattr(self.proc, attr))
  216. self._exit_callback = None
  217. self.returncode = None
  218. def set_exit_callback(self, callback):
  219. """Runs ``callback`` when this process exits.
  220. The callback takes one argument, the return code of the process.
  221. This method uses a ``SIGCHLD`` handler, which is a global setting
  222. and may conflict if you have other libraries trying to handle the
  223. same signal. If you are using more than one ``IOLoop`` it may
  224. be necessary to call `Subprocess.initialize` first to designate
  225. one ``IOLoop`` to run the signal handlers.
  226. In many cases a close callback on the stdout or stderr streams
  227. can be used as an alternative to an exit callback if the
  228. signal handler is causing a problem.
  229. """
  230. self._exit_callback = stack_context.wrap(callback)
  231. Subprocess.initialize(self.io_loop)
  232. Subprocess._waiting[self.pid] = self
  233. Subprocess._try_cleanup_process(self.pid)
  234. def wait_for_exit(self, raise_error=True):
  235. """Returns a `.Future` which resolves when the process exits.
  236. Usage::
  237. ret = yield proc.wait_for_exit()
  238. This is a coroutine-friendly alternative to `set_exit_callback`
  239. (and a replacement for the blocking `subprocess.Popen.wait`).
  240. By default, raises `subprocess.CalledProcessError` if the process
  241. has a non-zero exit status. Use ``wait_for_exit(raise_error=False)``
  242. to suppress this behavior and return the exit status without raising.
  243. .. versionadded:: 4.2
  244. """
  245. future = Future()
  246. def callback(ret):
  247. if ret != 0 and raise_error:
  248. # Unfortunately we don't have the original args any more.
  249. future.set_exception(CalledProcessError(ret, None))
  250. else:
  251. future.set_result(ret)
  252. self.set_exit_callback(callback)
  253. return future
  254. @classmethod
  255. def initialize(cls, io_loop=None):
  256. """Initializes the ``SIGCHLD`` handler.
  257. The signal handler is run on an `.IOLoop` to avoid locking issues.
  258. Note that the `.IOLoop` used for signal handling need not be the
  259. same one used by individual Subprocess objects (as long as the
  260. ``IOLoops`` are each running in separate threads).
  261. .. versionchanged:: 4.1
  262. The ``io_loop`` argument is deprecated.
  263. """
  264. if cls._initialized:
  265. return
  266. if io_loop is None:
  267. io_loop = ioloop.IOLoop.current()
  268. cls._old_sigchld = signal.signal(
  269. signal.SIGCHLD,
  270. lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))
  271. cls._initialized = True
  272. @classmethod
  273. def uninitialize(cls):
  274. """Removes the ``SIGCHLD`` handler."""
  275. if not cls._initialized:
  276. return
  277. signal.signal(signal.SIGCHLD, cls._old_sigchld)
  278. cls._initialized = False
  279. @classmethod
  280. def _cleanup(cls):
  281. for pid in list(cls._waiting.keys()): # make a copy
  282. cls._try_cleanup_process(pid)
  283. @classmethod
  284. def _try_cleanup_process(cls, pid):
  285. try:
  286. ret_pid, status = os.waitpid(pid, os.WNOHANG)
  287. except OSError as e:
  288. if errno_from_exception(e) == errno.ECHILD:
  289. return
  290. if ret_pid == 0:
  291. return
  292. assert ret_pid == pid
  293. subproc = cls._waiting.pop(pid)
  294. subproc.io_loop.add_callback_from_signal(
  295. subproc._set_returncode, status)
  296. def _set_returncode(self, status):
  297. if os.WIFSIGNALED(status):
  298. self.returncode = -os.WTERMSIG(status)
  299. else:
  300. assert os.WIFEXITED(status)
  301. self.returncode = os.WEXITSTATUS(status)
  302. if self._exit_callback:
  303. callback = self._exit_callback
  304. self._exit_callback = None
  305. callback(self.returncode)