process_test.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import asyncio
  2. import logging
  3. import os
  4. import signal
  5. import subprocess
  6. import sys
  7. import unittest
  8. from tornado.httpclient import HTTPClient, HTTPError
  9. from tornado.httpserver import HTTPServer
  10. from tornado.ioloop import IOLoop
  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(ProcessTest, self).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.assertTrue(id is not None)
  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.assertTrue(task_id() is None)
  67. sock.close()
  68. return
  69. try:
  70. if asyncio is not None:
  71. # Reset the global asyncio event loop, which was put into
  72. # a broken state by the fork.
  73. asyncio.set_event_loop(asyncio.new_event_loop())
  74. if id in (0, 1):
  75. self.assertEqual(id, task_id())
  76. server = HTTPServer(self.get_app())
  77. server.add_sockets([sock])
  78. IOLoop.current().start()
  79. elif id == 2:
  80. self.assertEqual(id, task_id())
  81. sock.close()
  82. # Always use SimpleAsyncHTTPClient here; the curl
  83. # version appears to get confused sometimes if the
  84. # connection gets closed before it's had a chance to
  85. # switch from writing mode to reading mode.
  86. client = HTTPClient(SimpleAsyncHTTPClient)
  87. def fetch(url, fail_ok=False):
  88. try:
  89. return client.fetch(get_url(url))
  90. except HTTPError as e:
  91. if not (fail_ok and e.code == 599):
  92. raise
  93. # Make two processes exit abnormally
  94. fetch("/?exit=2", fail_ok=True)
  95. fetch("/?exit=3", fail_ok=True)
  96. # They've been restarted, so a new fetch will work
  97. int(fetch("/").body)
  98. # Now the same with signals
  99. # Disabled because on the mac a process dying with a signal
  100. # can trigger an "Application exited abnormally; send error
  101. # report to Apple?" prompt.
  102. # fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True)
  103. # fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True)
  104. # int(fetch("/").body)
  105. # Now kill them normally so they won't be restarted
  106. fetch("/?exit=0", fail_ok=True)
  107. # One process left; watch it's pid change
  108. pid = int(fetch("/").body)
  109. fetch("/?exit=4", fail_ok=True)
  110. pid2 = int(fetch("/").body)
  111. self.assertNotEqual(pid, pid2)
  112. # Kill the last one so we shut down cleanly
  113. fetch("/?exit=0", fail_ok=True)
  114. os._exit(0)
  115. except Exception:
  116. logging.error("exception in child process %d", id, exc_info=True)
  117. raise
  118. @skipIfNonUnix
  119. class SubprocessTest(AsyncTestCase):
  120. def term_and_wait(self, subproc):
  121. subproc.proc.terminate()
  122. subproc.proc.wait()
  123. @gen_test
  124. def test_subprocess(self):
  125. if IOLoop.configured_class().__name__.endswith("LayeredTwistedIOLoop"):
  126. # This test fails non-deterministically with LayeredTwistedIOLoop.
  127. # (the read_until('\n') returns '\n' instead of 'hello\n')
  128. # This probably indicates a problem with either TornadoReactor
  129. # or TwistedIOLoop, but I haven't been able to track it down
  130. # and for now this is just causing spurious travis-ci failures.
  131. raise unittest.SkipTest(
  132. "Subprocess tests not compatible with " "LayeredTwistedIOLoop"
  133. )
  134. subproc = Subprocess(
  135. [sys.executable, "-u", "-i"],
  136. stdin=Subprocess.STREAM,
  137. stdout=Subprocess.STREAM,
  138. stderr=subprocess.STDOUT,
  139. )
  140. self.addCleanup(lambda: self.term_and_wait(subproc))
  141. self.addCleanup(subproc.stdout.close)
  142. self.addCleanup(subproc.stdin.close)
  143. yield subproc.stdout.read_until(b">>> ")
  144. subproc.stdin.write(b"print('hello')\n")
  145. data = yield subproc.stdout.read_until(b"\n")
  146. self.assertEqual(data, b"hello\n")
  147. yield subproc.stdout.read_until(b">>> ")
  148. subproc.stdin.write(b"raise SystemExit\n")
  149. data = yield subproc.stdout.read_until_close()
  150. self.assertEqual(data, b"")
  151. @gen_test
  152. def test_close_stdin(self):
  153. # Close the parent's stdin handle and see that the child recognizes it.
  154. subproc = Subprocess(
  155. [sys.executable, "-u", "-i"],
  156. stdin=Subprocess.STREAM,
  157. stdout=Subprocess.STREAM,
  158. stderr=subprocess.STDOUT,
  159. )
  160. self.addCleanup(lambda: self.term_and_wait(subproc))
  161. yield subproc.stdout.read_until(b">>> ")
  162. subproc.stdin.close()
  163. data = yield subproc.stdout.read_until_close()
  164. self.assertEqual(data, b"\n")
  165. @gen_test
  166. def test_stderr(self):
  167. # This test is mysteriously flaky on twisted: it succeeds, but logs
  168. # an error of EBADF on closing a file descriptor.
  169. subproc = Subprocess(
  170. [sys.executable, "-u", "-c", r"import sys; sys.stderr.write('hello\n')"],
  171. stderr=Subprocess.STREAM,
  172. )
  173. self.addCleanup(lambda: self.term_and_wait(subproc))
  174. data = yield subproc.stderr.read_until(b"\n")
  175. self.assertEqual(data, b"hello\n")
  176. # More mysterious EBADF: This fails if done with self.addCleanup instead of here.
  177. subproc.stderr.close()
  178. def test_sigchild(self):
  179. Subprocess.initialize()
  180. self.addCleanup(Subprocess.uninitialize)
  181. subproc = Subprocess([sys.executable, "-c", "pass"])
  182. subproc.set_exit_callback(self.stop)
  183. ret = self.wait()
  184. self.assertEqual(ret, 0)
  185. self.assertEqual(subproc.returncode, ret)
  186. @gen_test
  187. def test_sigchild_future(self):
  188. Subprocess.initialize()
  189. self.addCleanup(Subprocess.uninitialize)
  190. subproc = Subprocess([sys.executable, "-c", "pass"])
  191. ret = yield subproc.wait_for_exit()
  192. self.assertEqual(ret, 0)
  193. self.assertEqual(subproc.returncode, ret)
  194. def test_sigchild_signal(self):
  195. Subprocess.initialize()
  196. self.addCleanup(Subprocess.uninitialize)
  197. subproc = Subprocess(
  198. [sys.executable, "-c", "import time; time.sleep(30)"],
  199. stdout=Subprocess.STREAM,
  200. )
  201. self.addCleanup(subproc.stdout.close)
  202. subproc.set_exit_callback(self.stop)
  203. os.kill(subproc.pid, signal.SIGTERM)
  204. try:
  205. ret = self.wait(timeout=1.0)
  206. except AssertionError:
  207. # We failed to get the termination signal. This test is
  208. # occasionally flaky on pypy, so try to get a little more
  209. # information: did the process close its stdout
  210. # (indicating that the problem is in the parent process's
  211. # signal handling) or did the child process somehow fail
  212. # to terminate?
  213. fut = subproc.stdout.read_until_close()
  214. fut.add_done_callback(lambda f: self.stop()) # type: ignore
  215. try:
  216. self.wait(timeout=1.0)
  217. except AssertionError:
  218. raise AssertionError("subprocess failed to terminate")
  219. else:
  220. raise AssertionError(
  221. "subprocess closed stdout but failed to " "get termination signal"
  222. )
  223. self.assertEqual(subproc.returncode, ret)
  224. self.assertEqual(ret, -signal.SIGTERM)
  225. @gen_test
  226. def test_wait_for_exit_raise(self):
  227. Subprocess.initialize()
  228. self.addCleanup(Subprocess.uninitialize)
  229. subproc = Subprocess([sys.executable, "-c", "import sys; sys.exit(1)"])
  230. with self.assertRaises(subprocess.CalledProcessError) as cm:
  231. yield subproc.wait_for_exit()
  232. self.assertEqual(cm.exception.returncode, 1)
  233. @gen_test
  234. def test_wait_for_exit_raise_disabled(self):
  235. Subprocess.initialize()
  236. self.addCleanup(Subprocess.uninitialize)
  237. subproc = Subprocess([sys.executable, "-c", "import sys; sys.exit(1)"])
  238. ret = yield subproc.wait_for_exit(raise_error=False)
  239. self.assertEqual(ret, 1)