cros_subprocess.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. # Copyright (c) 2012 The Chromium OS Authors.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. #
  5. # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
  6. # Licensed to PSF under a Contributor Agreement.
  7. # See http://www.python.org/2.4/license for licensing details.
  8. """Subprocess execution
  9. This module holds a subclass of subprocess.Popen with our own required
  10. features, mainly that we get access to the subprocess output while it
  11. is running rather than just at the end. This makes it easier to show
  12. progress information and filter output in real time.
  13. """
  14. import errno
  15. import os
  16. import pty
  17. import select
  18. import subprocess
  19. import sys
  20. import unittest
  21. # Import these here so the caller does not need to import subprocess also.
  22. PIPE = subprocess.PIPE
  23. STDOUT = subprocess.STDOUT
  24. PIPE_PTY = -3 # Pipe output through a pty
  25. stay_alive = True
  26. class Popen(subprocess.Popen):
  27. """Like subprocess.Popen with ptys and incremental output
  28. This class deals with running a child process and filtering its output on
  29. both stdout and stderr while it is running. We do this so we can monitor
  30. progress, and possibly relay the output to the user if requested.
  31. The class is similar to subprocess.Popen, the equivalent is something like:
  32. Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  33. But this class has many fewer features, and two enhancement:
  34. 1. Rather than getting the output data only at the end, this class sends it
  35. to a provided operation as it arrives.
  36. 2. We use pseudo terminals so that the child will hopefully flush its output
  37. to us as soon as it is produced, rather than waiting for the end of a
  38. line.
  39. Use communicate_filter() to handle output from the subprocess.
  40. """
  41. def __init__(self, args, stdin=None, stdout=PIPE_PTY, stderr=PIPE_PTY,
  42. shell=False, cwd=None, env=None, **kwargs):
  43. """Cut-down constructor
  44. Args:
  45. args: Program and arguments for subprocess to execute.
  46. stdin: See subprocess.Popen()
  47. stdout: See subprocess.Popen(), except that we support the sentinel
  48. value of cros_subprocess.PIPE_PTY.
  49. stderr: See subprocess.Popen(), except that we support the sentinel
  50. value of cros_subprocess.PIPE_PTY.
  51. shell: See subprocess.Popen()
  52. cwd: Working directory to change to for subprocess, or None if none.
  53. env: Environment to use for this subprocess, or None to inherit parent.
  54. kwargs: No other arguments are supported at the moment. Passing other
  55. arguments will cause a ValueError to be raised.
  56. """
  57. stdout_pty = None
  58. stderr_pty = None
  59. if stdout == PIPE_PTY:
  60. stdout_pty = pty.openpty()
  61. stdout = os.fdopen(stdout_pty[1])
  62. if stderr == PIPE_PTY:
  63. stderr_pty = pty.openpty()
  64. stderr = os.fdopen(stderr_pty[1])
  65. super(Popen, self).__init__(args, stdin=stdin,
  66. stdout=stdout, stderr=stderr, shell=shell, cwd=cwd, env=env,
  67. **kwargs)
  68. # If we're on a PTY, we passed the slave half of the PTY to the subprocess.
  69. # We want to use the master half on our end from now on. Setting this here
  70. # does make some assumptions about the implementation of subprocess, but
  71. # those assumptions are pretty minor.
  72. # Note that if stderr is STDOUT, then self.stderr will be set to None by
  73. # this constructor.
  74. if stdout_pty is not None:
  75. self.stdout = os.fdopen(stdout_pty[0])
  76. if stderr_pty is not None:
  77. self.stderr = os.fdopen(stderr_pty[0])
  78. # Insist that unit tests exist for other arguments we don't support.
  79. if kwargs:
  80. raise ValueError("Unit tests do not test extra args - please add tests")
  81. def convert_data(self, data):
  82. """Convert stdout/stderr data to the correct format for output
  83. Args:
  84. data: Data to convert, or None for ''
  85. Returns:
  86. Converted data, as bytes
  87. """
  88. if data is None:
  89. return b''
  90. return data
  91. def communicate_filter(self, output, input_buf=''):
  92. """Interact with process: Read data from stdout and stderr.
  93. This method runs until end-of-file is reached, then waits for the
  94. subprocess to terminate.
  95. The output function is sent all output from the subprocess and must be
  96. defined like this:
  97. def output([self,] stream, data)
  98. Args:
  99. stream: the stream the output was received on, which will be
  100. sys.stdout or sys.stderr.
  101. data: a string containing the data
  102. Returns:
  103. True to terminate the process
  104. Note: The data read is buffered in memory, so do not use this
  105. method if the data size is large or unlimited.
  106. Args:
  107. output: Function to call with each fragment of output.
  108. Returns:
  109. A tuple (stdout, stderr, combined) which is the data received on
  110. stdout, stderr and the combined data (interleaved stdout and stderr).
  111. Note that the interleaved output will only be sensible if you have
  112. set both stdout and stderr to PIPE or PIPE_PTY. Even then it depends on
  113. the timing of the output in the subprocess. If a subprocess flips
  114. between stdout and stderr quickly in succession, by the time we come to
  115. read the output from each we may see several lines in each, and will read
  116. all the stdout lines, then all the stderr lines. So the interleaving
  117. may not be correct. In this case you might want to pass
  118. stderr=cros_subprocess.STDOUT to the constructor.
  119. This feature is still useful for subprocesses where stderr is
  120. rarely used and indicates an error.
  121. Note also that if you set stderr to STDOUT, then stderr will be empty
  122. and the combined output will just be the same as stdout.
  123. """
  124. read_set = []
  125. write_set = []
  126. stdout = None # Return
  127. stderr = None # Return
  128. if self.stdin:
  129. # Flush stdio buffer. This might block, if the user has
  130. # been writing to .stdin in an uncontrolled fashion.
  131. self.stdin.flush()
  132. if input_buf:
  133. write_set.append(self.stdin)
  134. else:
  135. self.stdin.close()
  136. if self.stdout:
  137. read_set.append(self.stdout)
  138. stdout = bytearray()
  139. if self.stderr and self.stderr != self.stdout:
  140. read_set.append(self.stderr)
  141. stderr = bytearray()
  142. combined = bytearray()
  143. stop_now = False
  144. input_offset = 0
  145. while read_set or write_set:
  146. try:
  147. rlist, wlist, _ = select.select(read_set, write_set, [], 0.2)
  148. except select.error as e:
  149. if e.args[0] == errno.EINTR:
  150. continue
  151. raise
  152. if not stay_alive:
  153. self.terminate()
  154. if self.stdin in wlist:
  155. # When select has indicated that the file is writable,
  156. # we can write up to PIPE_BUF bytes without risk
  157. # blocking. POSIX defines PIPE_BUF >= 512
  158. chunk = input_buf[input_offset : input_offset + 512]
  159. bytes_written = os.write(self.stdin.fileno(), chunk)
  160. input_offset += bytes_written
  161. if input_offset >= len(input_buf):
  162. self.stdin.close()
  163. write_set.remove(self.stdin)
  164. if self.stdout in rlist:
  165. data = b''
  166. # We will get an error on read if the pty is closed
  167. try:
  168. data = os.read(self.stdout.fileno(), 1024)
  169. except OSError:
  170. pass
  171. if not len(data):
  172. self.stdout.close()
  173. read_set.remove(self.stdout)
  174. else:
  175. stdout += data
  176. combined += data
  177. if output:
  178. stop_now = output(sys.stdout, data)
  179. if self.stderr in rlist:
  180. data = b''
  181. # We will get an error on read if the pty is closed
  182. try:
  183. data = os.read(self.stderr.fileno(), 1024)
  184. except OSError:
  185. pass
  186. if not len(data):
  187. self.stderr.close()
  188. read_set.remove(self.stderr)
  189. else:
  190. stderr += data
  191. combined += data
  192. if output:
  193. stop_now = output(sys.stderr, data)
  194. if stop_now:
  195. self.terminate()
  196. # All data exchanged. Translate lists into strings.
  197. stdout = self.convert_data(stdout)
  198. stderr = self.convert_data(stderr)
  199. combined = self.convert_data(combined)
  200. self.wait()
  201. return (stdout, stderr, combined)
  202. # Just being a unittest.TestCase gives us 14 public methods. Unless we
  203. # disable this, we can only have 6 tests in a TestCase. That's not enough.
  204. #
  205. # pylint: disable=R0904
  206. class TestSubprocess(unittest.TestCase):
  207. """Our simple unit test for this module"""
  208. class MyOperation:
  209. """Provides a operation that we can pass to Popen"""
  210. def __init__(self, input_to_send=None):
  211. """Constructor to set up the operation and possible input.
  212. Args:
  213. input_to_send: a text string to send when we first get input. We will
  214. add \r\n to the string.
  215. """
  216. self.stdout_data = ''
  217. self.stderr_data = ''
  218. self.combined_data = ''
  219. self.stdin_pipe = None
  220. self._input_to_send = input_to_send
  221. if input_to_send:
  222. pipe = os.pipe()
  223. self.stdin_read_pipe = pipe[0]
  224. self._stdin_write_pipe = os.fdopen(pipe[1], 'w')
  225. def output(self, stream, data):
  226. """Output handler for Popen. Stores the data for later comparison"""
  227. if stream == sys.stdout:
  228. self.stdout_data += data
  229. if stream == sys.stderr:
  230. self.stderr_data += data
  231. self.combined_data += data
  232. # Output the input string if we have one.
  233. if self._input_to_send:
  234. self._stdin_write_pipe.write(self._input_to_send + '\r\n')
  235. self._stdin_write_pipe.flush()
  236. def _basic_check(self, plist, oper):
  237. """Basic checks that the output looks sane."""
  238. self.assertEqual(plist[0], oper.stdout_data)
  239. self.assertEqual(plist[1], oper.stderr_data)
  240. self.assertEqual(plist[2], oper.combined_data)
  241. # The total length of stdout and stderr should equal the combined length
  242. self.assertEqual(len(plist[0]) + len(plist[1]), len(plist[2]))
  243. def test_simple(self):
  244. """Simple redirection: Get process list"""
  245. oper = TestSubprocess.MyOperation()
  246. plist = Popen(['ps']).communicate_filter(oper.output)
  247. self._basic_check(plist, oper)
  248. def test_stderr(self):
  249. """Check stdout and stderr"""
  250. oper = TestSubprocess.MyOperation()
  251. cmd = 'echo fred >/dev/stderr && false || echo bad'
  252. plist = Popen([cmd], shell=True).communicate_filter(oper.output)
  253. self._basic_check(plist, oper)
  254. self.assertEqual(plist [0], 'bad\r\n')
  255. self.assertEqual(plist [1], 'fred\r\n')
  256. def test_shell(self):
  257. """Check with and without shell works"""
  258. oper = TestSubprocess.MyOperation()
  259. cmd = 'echo test >/dev/stderr'
  260. self.assertRaises(OSError, Popen, [cmd], shell=False)
  261. plist = Popen([cmd], shell=True).communicate_filter(oper.output)
  262. self._basic_check(plist, oper)
  263. self.assertEqual(len(plist [0]), 0)
  264. self.assertEqual(plist [1], 'test\r\n')
  265. def test_list_args(self):
  266. """Check with and without shell works using list arguments"""
  267. oper = TestSubprocess.MyOperation()
  268. cmd = ['echo', 'test', '>/dev/stderr']
  269. plist = Popen(cmd, shell=False).communicate_filter(oper.output)
  270. self._basic_check(plist, oper)
  271. self.assertEqual(plist [0], ' '.join(cmd[1:]) + '\r\n')
  272. self.assertEqual(len(plist [1]), 0)
  273. oper = TestSubprocess.MyOperation()
  274. # this should be interpreted as 'echo' with the other args dropped
  275. cmd = ['echo', 'test', '>/dev/stderr']
  276. plist = Popen(cmd, shell=True).communicate_filter(oper.output)
  277. self._basic_check(plist, oper)
  278. self.assertEqual(plist [0], '\r\n')
  279. def test_cwd(self):
  280. """Check we can change directory"""
  281. for shell in (False, True):
  282. oper = TestSubprocess.MyOperation()
  283. plist = Popen('pwd', shell=shell, cwd='/tmp').communicate_filter(
  284. oper.output)
  285. self._basic_check(plist, oper)
  286. self.assertEqual(plist [0], '/tmp\r\n')
  287. def test_env(self):
  288. """Check we can change environment"""
  289. for add in (False, True):
  290. oper = TestSubprocess.MyOperation()
  291. env = os.environ
  292. if add:
  293. env ['FRED'] = 'fred'
  294. cmd = 'echo $FRED'
  295. plist = Popen(cmd, shell=True, env=env).communicate_filter(oper.output)
  296. self._basic_check(plist, oper)
  297. self.assertEqual(plist [0], add and 'fred\r\n' or '\r\n')
  298. def test_extra_args(self):
  299. """Check we can't add extra arguments"""
  300. self.assertRaises(ValueError, Popen, 'true', close_fds=False)
  301. def test_basic_input(self):
  302. """Check that incremental input works
  303. We set up a subprocess which will prompt for name. When we see this prompt
  304. we send the name as input to the process. It should then print the name
  305. properly to stdout.
  306. """
  307. oper = TestSubprocess.MyOperation('Flash')
  308. prompt = 'What is your name?: '
  309. cmd = 'echo -n "%s"; read name; echo Hello $name' % prompt
  310. plist = Popen([cmd], stdin=oper.stdin_read_pipe,
  311. shell=True).communicate_filter(oper.output)
  312. self._basic_check(plist, oper)
  313. self.assertEqual(len(plist [1]), 0)
  314. self.assertEqual(plist [0], prompt + 'Hello Flash\r\r\n')
  315. def test_isatty(self):
  316. """Check that ptys appear as terminals to the subprocess"""
  317. oper = TestSubprocess.MyOperation()
  318. cmd = ('if [ -t %d ]; then echo "terminal %d" >&%d; '
  319. 'else echo "not %d" >&%d; fi;')
  320. both_cmds = ''
  321. for fd in (1, 2):
  322. both_cmds += cmd % (fd, fd, fd, fd, fd)
  323. plist = Popen(both_cmds, shell=True).communicate_filter(oper.output)
  324. self._basic_check(plist, oper)
  325. self.assertEqual(plist [0], 'terminal 1\r\n')
  326. self.assertEqual(plist [1], 'terminal 2\r\n')
  327. # Now try with PIPE and make sure it is not a terminal
  328. oper = TestSubprocess.MyOperation()
  329. plist = Popen(both_cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  330. shell=True).communicate_filter(oper.output)
  331. self._basic_check(plist, oper)
  332. self.assertEqual(plist [0], 'not 1\n')
  333. self.assertEqual(plist [1], 'not 2\n')
  334. if __name__ == '__main__':
  335. unittest.main()