process_test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import asyncio
  2. import logging
  3. import os
  4. import signal
  5. import subprocess
  6. import sys
  7. import time
  8. import unittest
  9. from tornado.httpclient import HTTPClient, HTTPError
  10. from tornado.httpserver import HTTPServer
  11. from tornado.log import gen_log
  12. from tornado.process import fork_processes, task_id, Subprocess
  13. from tornado.simple_httpclient import SimpleAsyncHTTPClient
  14. from tornado.testing import bind_unused_port, ExpectLog, AsyncTestCase, gen_test
  15. from tornado.test.util import skipIfNonUnix
  16. from tornado.web import RequestHandler, Application
  17. # Not using AsyncHTTPTestCase because we need control over the IOLoop.
  18. @skipIfNonUnix
  19. class ProcessTest(unittest.TestCase):
  20. def get_app(self):
  21. class ProcessHandler(RequestHandler):
  22. def get(self):
  23. if self.get_argument("exit", None):
  24. # must use os._exit instead of sys.exit so unittest's
  25. # exception handler doesn't catch it
  26. os._exit(int(self.get_argument("exit")))
  27. if self.get_argument("signal", None):
  28. os.kill(os.getpid(), int(self.get_argument("signal")))
  29. self.write(str(os.getpid()))
  30. return Application([("/", ProcessHandler)])
  31. def tearDown(self):
  32. if task_id() is not None:
  33. # We're in a child process, and probably got to this point
  34. # via an uncaught exception. If we return now, both
  35. # processes will continue with the rest of the test suite.
  36. # Exit now so the parent process will restart the child
  37. # (since we don't have a clean way to signal failure to
  38. # the parent that won't restart)
  39. logging.error("aborting child process from tearDown")
  40. logging.shutdown()
  41. os._exit(1)
  42. # In the surviving process, clear the alarm we set earlier
  43. signal.alarm(0)
  44. super().tearDown()
  45. def test_multi_process(self):
  46. # This test doesn't work on twisted because we use the global
  47. # reactor and don't restore it to a sane state after the fork
  48. # (asyncio has the same issue, but we have a special case in
  49. # place for it).
  50. with ExpectLog(
  51. gen_log, "(Starting .* processes|child .* exited|uncaught exception)"
  52. ):
  53. sock, port = bind_unused_port()
  54. def get_url(path):
  55. return "http://127.0.0.1:%d%s" % (port, path)
  56. # ensure that none of these processes live too long
  57. signal.alarm(5) # master process
  58. try:
  59. id = fork_processes(3, max_restarts=3)
  60. self.assertIsNotNone(id)
  61. signal.alarm(5) # child processes
  62. except SystemExit as e:
  63. # if we exit cleanly from fork_processes, all the child processes
  64. # finished with status 0
  65. self.assertEqual(e.code, 0)
  66. self.assertIsNone(task_id())
  67. sock.close()
  68. return
  69. try:
  70. if id in (0, 1):
  71. self.assertEqual(id, task_id())
  72. async def f():
  73. server = HTTPServer(self.get_app())
  74. server.add_sockets([sock])
  75. await asyncio.Event().wait()
  76. asyncio.run(f())
  77. elif id == 2:
  78. self.assertEqual(id, task_id())
  79. sock.close()
  80. # Always use SimpleAsyncHTTPClient here; the curl
  81. # version appears to get confused sometimes if the
  82. # connection gets closed before it's had a chance to
  83. # switch from writing mode to reading mode.
  84. client = HTTPClient(SimpleAsyncHTTPClient)
  85. def fetch(url, fail_ok=False):
  86. try:
  87. return client.fetch(get_url(url))
  88. except HTTPError as e:
  89. if not (fail_ok and e.code == 599):
  90. raise
  91. # Make two processes exit abnormally
  92. fetch("/?exit=2", fail_ok=True)
  93. fetch("/?exit=3", fail_ok=True)
  94. # They've been restarted, so a new fetch will work
  95. int(fetch("/").body)
  96. # Now the same with signals
  97. # Disabled because on the mac a process dying with a signal
  98. # can trigger an "Application exited abnormally; send error
  99. # report to Apple?" prompt.
  100. # fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True)
  101. # fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True)
  102. # int(fetch("/").body)
  103. # Now kill them normally so they won't be restarted
  104. fetch("/?exit=0", fail_ok=True)
  105. # One process left; watch it's pid change
  106. pid = int(fetch("/").body)
  107. fetch("/?exit=4", fail_ok=True)
  108. pid2 = int(fetch("/").body)
  109. self.assertNotEqual(pid, pid2)
  110. # Kill the last one so we shut down cleanly
  111. fetch("/?exit=0", fail_ok=True)
  112. os._exit(0)
  113. except Exception:
  114. logging.error("exception in child process %d", id, exc_info=True)
  115. raise
  116. @skipIfNonUnix
  117. class SubprocessTest(AsyncTestCase):
  118. def term_and_wait(self, subproc):
  119. subproc.proc.terminate()
  120. subproc.proc.wait()
  121. @gen_test
  122. def test_subprocess(self):
  123. subproc = Subprocess(
  124. [sys.executable, "-u", "-i", "-I"],
  125. stdin=Subprocess.STREAM,
  126. stdout=Subprocess.STREAM,
  127. stderr=subprocess.STDOUT,
  128. )
  129. self.addCleanup(lambda: self.term_and_wait(subproc))
  130. self.addCleanup(subproc.stdout.close)
  131. self.addCleanup(subproc.stdin.close)
  132. yield subproc.stdout.read_until(b">>> ")
  133. subproc.stdin.write(b"print('hello')\n")
  134. data = yield subproc.stdout.read_until(b"\n")
  135. self.assertEqual(data, b"hello\n")
  136. yield subproc.stdout.read_until(b">>> ")
  137. subproc.stdin.write(b"raise SystemExit\n")
  138. data = yield subproc.stdout.read_until_close()
  139. self.assertEqual(data, b"")
  140. @gen_test
  141. def test_close_stdin(self):
  142. # Close the parent's stdin handle and see that the child recognizes it.
  143. subproc = Subprocess(
  144. [sys.executable, "-u", "-i", "-I"],
  145. stdin=Subprocess.STREAM,
  146. stdout=Subprocess.STREAM,
  147. stderr=subprocess.STDOUT,
  148. )
  149. self.addCleanup(lambda: self.term_and_wait(subproc))
  150. yield subproc.stdout.read_until(b">>> ")
  151. subproc.stdin.close()
  152. data = yield subproc.stdout.read_until_close()
  153. self.assertEqual(data, b"\n")
  154. @gen_test
  155. def test_stderr(self):
  156. # This test is mysteriously flaky on twisted: it succeeds, but logs
  157. # an error of EBADF on closing a file descriptor.
  158. subproc = Subprocess(
  159. [sys.executable, "-u", "-c", r"import sys; sys.stderr.write('hello\n')"],
  160. stderr=Subprocess.STREAM,
  161. )
  162. self.addCleanup(lambda: self.term_and_wait(subproc))
  163. data = yield subproc.stderr.read_until(b"\n")
  164. self.assertEqual(data, b"hello\n")
  165. # More mysterious EBADF: This fails if done with self.addCleanup instead of here.
  166. subproc.stderr.close()
  167. def test_sigchild(self):
  168. Subprocess.initialize()
  169. self.addCleanup(Subprocess.uninitialize)
  170. subproc = Subprocess([sys.executable, "-c", "pass"])
  171. subproc.set_exit_callback(self.stop)
  172. ret = self.wait()
  173. self.assertEqual(ret, 0)
  174. self.assertEqual(subproc.returncode, ret)
  175. @gen_test
  176. def test_sigchild_future(self):
  177. Subprocess.initialize()
  178. self.addCleanup(Subprocess.uninitialize)
  179. subproc = Subprocess([sys.executable, "-c", "pass"])
  180. ret = yield subproc.wait_for_exit()
  181. self.assertEqual(ret, 0)
  182. self.assertEqual(subproc.returncode, ret)
  183. def test_sigchild_signal(self):
  184. Subprocess.initialize()
  185. self.addCleanup(Subprocess.uninitialize)
  186. subproc = Subprocess(
  187. [sys.executable, "-c", "import time; time.sleep(30)"],
  188. stdout=Subprocess.STREAM,
  189. )
  190. self.addCleanup(subproc.stdout.close)
  191. subproc.set_exit_callback(self.stop)
  192. # For unclear reasons, killing a process too soon after
  193. # creating it can result in an exit status corresponding to
  194. # SIGKILL instead of the actual signal involved. This has been
  195. # observed on macOS 10.15 with Python 3.8 installed via brew,
  196. # but not with the system-installed Python 3.7.
  197. time.sleep(0.1)
  198. os.kill(subproc.pid, signal.SIGTERM)
  199. try:
  200. ret = self.wait()
  201. except AssertionError:
  202. # We failed to get the termination signal. This test is
  203. # occasionally flaky on pypy, so try to get a little more
  204. # information: did the process close its stdout
  205. # (indicating that the problem is in the parent process's
  206. # signal handling) or did the child process somehow fail
  207. # to terminate?
  208. fut = subproc.stdout.read_until_close()
  209. fut.add_done_callback(lambda f: self.stop()) # type: ignore
  210. try:
  211. self.wait()
  212. except AssertionError:
  213. raise AssertionError("subprocess failed to terminate")
  214. else:
  215. raise AssertionError(
  216. "subprocess closed stdout but failed to " "get termination signal"
  217. )
  218. self.assertEqual(subproc.returncode, ret)
  219. self.assertEqual(ret, -signal.SIGTERM)
  220. @gen_test
  221. def test_wait_for_exit_raise(self):
  222. Subprocess.initialize()
  223. self.addCleanup(Subprocess.uninitialize)
  224. subproc = Subprocess([sys.executable, "-c", "import sys; sys.exit(1)"])
  225. with self.assertRaises(subprocess.CalledProcessError) as cm:
  226. yield subproc.wait_for_exit()
  227. self.assertEqual(cm.exception.returncode, 1)
  228. @gen_test
  229. def test_wait_for_exit_raise_disabled(self):
  230. Subprocess.initialize()
  231. self.addCleanup(Subprocess.uninitialize)
  232. subproc = Subprocess([sys.executable, "-c", "import sys; sys.exit(1)"])
  233. ret = yield subproc.wait_for_exit(raise_error=False)
  234. self.assertEqual(ret, 1)