[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 1 | # coding=utf8 |
[email protected] | 4f6852c | 2012-04-20 20:39:20 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """Collection of subprocess wrapper functions. |
| 6 | |
| 7 | In theory you shouldn't need anything else in subprocess, or this module failed. |
| 8 | """ |
| 9 | |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 10 | import cStringIO |
[email protected] | 1d9f629 | 2011-04-07 14:15:36 | [diff] [blame] | 11 | import errno |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 12 | import logging |
| 13 | import os |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 14 | import Queue |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 15 | import subprocess |
| 16 | import sys |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 17 | import time |
| 18 | import threading |
| 19 | |
[email protected] | a8e8163 | 2011-12-01 00:35:24 | [diff] [blame] | 20 | |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 21 | # Constants forwarded from subprocess. |
| 22 | PIPE = subprocess.PIPE |
| 23 | STDOUT = subprocess.STDOUT |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 24 | # Sends stdout or stderr to os.devnull. |
[email protected] | 0d5ef24 | 2011-04-18 13:52:58 | [diff] [blame] | 25 | VOID = object() |
[email protected] | 1d9f629 | 2011-04-07 14:15:36 | [diff] [blame] | 26 | # Error code when a process was killed because it timed out. |
| 27 | TIMED_OUT = -2001 |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 28 | |
| 29 | # Globals. |
| 30 | # Set to True if you somehow need to disable this hack. |
| 31 | SUBPROCESS_CLEANUP_HACKED = False |
| 32 | |
| 33 | |
| 34 | class CalledProcessError(subprocess.CalledProcessError): |
| 35 | """Augment the standard exception with more data.""" |
| 36 | def __init__(self, returncode, cmd, cwd, stdout, stderr): |
| 37 | super(CalledProcessError, self).__init__(returncode, cmd) |
| 38 | self.stdout = stdout |
| 39 | self.stderr = stderr |
| 40 | self.cwd = cwd |
| 41 | |
| 42 | def __str__(self): |
| 43 | out = 'Command %s returned non-zero exit status %s' % ( |
| 44 | ' '.join(self.cmd), self.returncode) |
| 45 | if self.cwd: |
| 46 | out += ' in ' + self.cwd |
| 47 | return '\n'.join(filter(None, (out, self.stdout, self.stderr))) |
| 48 | |
| 49 | |
[email protected] | 1d9f629 | 2011-04-07 14:15:36 | [diff] [blame] | 50 | class CygwinRebaseError(CalledProcessError): |
| 51 | """Occurs when cygwin's fork() emulation fails due to rebased dll.""" |
| 52 | |
| 53 | |
[email protected] | fb3d324 | 2011-04-01 14:03:08 | [diff] [blame] | 54 | ## Utility functions |
| 55 | |
| 56 | |
| 57 | def kill_pid(pid): |
| 58 | """Kills a process by its process id.""" |
| 59 | try: |
| 60 | # Unable to import 'module' |
[email protected] | c98c0c5 | 2011-04-06 13:39:43 | [diff] [blame] | 61 | # pylint: disable=E1101,F0401 |
[email protected] | fb3d324 | 2011-04-01 14:03:08 | [diff] [blame] | 62 | import signal |
| 63 | return os.kill(pid, signal.SIGKILL) |
| 64 | except ImportError: |
| 65 | pass |
| 66 | |
| 67 | |
| 68 | def kill_win(process): |
| 69 | """Kills a process with its windows handle. |
| 70 | |
| 71 | Has no effect on other platforms. |
| 72 | """ |
| 73 | try: |
| 74 | # Unable to import 'module' |
| 75 | # pylint: disable=F0401 |
| 76 | import win32process |
| 77 | # Access to a protected member _handle of a client class |
| 78 | # pylint: disable=W0212 |
| 79 | return win32process.TerminateProcess(process._handle, -1) |
| 80 | except ImportError: |
| 81 | pass |
| 82 | |
| 83 | |
| 84 | def add_kill(): |
| 85 | """Adds kill() method to subprocess.Popen for python <2.6""" |
| 86 | if hasattr(subprocess.Popen, 'kill'): |
| 87 | return |
| 88 | |
| 89 | if sys.platform == 'win32': |
| 90 | subprocess.Popen.kill = kill_win |
| 91 | else: |
| 92 | subprocess.Popen.kill = lambda process: kill_pid(process.pid) |
| 93 | |
| 94 | |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 95 | def hack_subprocess(): |
| 96 | """subprocess functions may throw exceptions when used in multiple threads. |
| 97 | |
| 98 | See http://bugs.python.org/issue1731717 for more information. |
| 99 | """ |
| 100 | global SUBPROCESS_CLEANUP_HACKED |
| 101 | if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1: |
| 102 | # Only hack if there is ever multiple threads. |
| 103 | # There is no point to leak with only one thread. |
| 104 | subprocess._cleanup = lambda: None |
| 105 | SUBPROCESS_CLEANUP_HACKED = True |
| 106 | |
| 107 | |
| 108 | def get_english_env(env): |
| 109 | """Forces LANG and/or LANGUAGE to be English. |
| 110 | |
| 111 | Forces encoding to utf-8 for subprocesses. |
| 112 | |
| 113 | Returns None if it is unnecessary. |
| 114 | """ |
[email protected] | c98c0c5 | 2011-04-06 13:39:43 | [diff] [blame] | 115 | if sys.platform == 'win32': |
| 116 | return None |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 117 | env = env or os.environ |
| 118 | |
| 119 | # Test if it is necessary at all. |
| 120 | is_english = lambda name: env.get(name, 'en').startswith('en') |
| 121 | |
| 122 | if is_english('LANG') and is_english('LANGUAGE'): |
| 123 | return None |
| 124 | |
| 125 | # Requires modifications. |
| 126 | env = env.copy() |
| 127 | def fix_lang(name): |
| 128 | if not is_english(name): |
| 129 | env[name] = 'en_US.UTF-8' |
| 130 | fix_lang('LANG') |
| 131 | fix_lang('LANGUAGE') |
| 132 | return env |
| 133 | |
| 134 | |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 135 | class NagTimer(object): |
| 136 | """ |
| 137 | Triggers a callback when a time interval passes without an event being fired. |
| 138 | |
| 139 | For example, the event could be receiving terminal output from a subprocess; |
| 140 | and the callback could print a warning to stderr that the subprocess appeared |
| 141 | to be hung. |
| 142 | """ |
| 143 | def __init__(self, interval, cb): |
| 144 | self.interval = interval |
| 145 | self.cb = cb |
| 146 | self.timer = threading.Timer(self.interval, self.fn) |
| 147 | self.last_output = self.previous_last_output = 0 |
| 148 | |
| 149 | def start(self): |
| 150 | self.last_output = self.previous_last_output = time.time() |
| 151 | self.timer.start() |
| 152 | |
| 153 | def event(self): |
| 154 | self.last_output = time.time() |
| 155 | |
| 156 | def fn(self): |
| 157 | now = time.time() |
| 158 | if self.last_output == self.previous_last_output: |
| 159 | self.cb(now - self.previous_last_output) |
| 160 | # Use 0.1 fudge factor, just in case |
| 161 | # (self.last_output - now) is very close to zero. |
| 162 | sleep_time = (self.last_output - now - 0.1) % self.interval |
| 163 | self.previous_last_output = self.last_output |
| 164 | self.timer = threading.Timer(sleep_time + 0.1, self.fn) |
| 165 | self.timer.start() |
| 166 | |
| 167 | def cancel(self): |
| 168 | self.timer.cancel() |
| 169 | |
| 170 | |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 171 | class Popen(subprocess.Popen): |
[email protected] | 57bf78d | 2011-09-08 18:57:33 | [diff] [blame] | 172 | """Wraps subprocess.Popen() with various workarounds. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 173 | |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 174 | - Forces English output since it's easier to parse the stdout if it is always |
| 175 | in English. |
| 176 | - Sets shell=True on windows by default. You can override this by forcing |
| 177 | shell parameter to a value. |
| 178 | - Adds support for VOID to not buffer when not needed. |
[email protected] | dd9837f | 2011-11-30 01:55:22 | [diff] [blame] | 179 | - Adds self.start property. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 180 | |
[email protected] | 57bf78d | 2011-09-08 18:57:33 | [diff] [blame] | 181 | Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate |
| 182 | exceptions generated by cygwin when it fails trying to emulate fork(). |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 183 | """ |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 184 | def __init__(self, args, **kwargs): |
| 185 | # Make sure we hack subprocess if necessary. |
| 186 | hack_subprocess() |
| 187 | add_kill() |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 188 | |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 189 | env = get_english_env(kwargs.get('env')) |
| 190 | if env: |
| 191 | kwargs['env'] = env |
| 192 | if kwargs.get('shell') is None: |
| 193 | # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for |
| 194 | # the executable, but shell=True makes subprocess on Linux fail when it's |
| 195 | # called with a list because it only tries to execute the first item in |
| 196 | # the list. |
| 197 | kwargs['shell'] = bool(sys.platform=='win32') |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 198 | |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 199 | if isinstance(args, basestring): |
| 200 | tmp_str = args |
| 201 | elif isinstance(args, (list, tuple)): |
| 202 | tmp_str = ' '.join(args) |
| 203 | else: |
| 204 | raise CalledProcessError(None, args, kwargs.get('cwd'), None, None) |
| 205 | if kwargs.get('cwd', None): |
| 206 | tmp_str += '; cwd=%s' % kwargs['cwd'] |
| 207 | logging.debug(tmp_str) |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 208 | |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 209 | self.stdout_cb = None |
| 210 | self.stderr_cb = None |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 211 | self.stdin_is_void = False |
| 212 | self.stdout_is_void = False |
| 213 | self.stderr_is_void = False |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 214 | self.cmd_str = tmp_str |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 215 | |
| 216 | if kwargs.get('stdin') is VOID: |
| 217 | kwargs['stdin'] = open(os.devnull, 'r') |
| 218 | self.stdin_is_void = True |
| 219 | |
| 220 | for stream in ('stdout', 'stderr'): |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 221 | if kwargs.get(stream) in (VOID, os.devnull): |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 222 | kwargs[stream] = open(os.devnull, 'w') |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 223 | setattr(self, stream + '_is_void', True) |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 224 | if callable(kwargs.get(stream)): |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 225 | setattr(self, stream + '_cb', kwargs[stream]) |
| 226 | kwargs[stream] = PIPE |
[email protected] | 1d9f629 | 2011-04-07 14:15:36 | [diff] [blame] | 227 | |
[email protected] | dd9837f | 2011-11-30 01:55:22 | [diff] [blame] | 228 | self.start = time.time() |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 229 | self.timeout = None |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 230 | self.nag_timer = None |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 231 | self.nag_max = None |
[email protected] | a8e8163 | 2011-12-01 00:35:24 | [diff] [blame] | 232 | self.shell = kwargs.get('shell', None) |
[email protected] | 14e37ad | 2011-11-30 20:26:16 | [diff] [blame] | 233 | # Silence pylint on MacOSX |
| 234 | self.returncode = None |
[email protected] | a8e8163 | 2011-12-01 00:35:24 | [diff] [blame] | 235 | |
[email protected] | ef77f9e | 2011-11-24 15:24:02 | [diff] [blame] | 236 | try: |
| 237 | super(Popen, self).__init__(args, **kwargs) |
| 238 | except OSError, e: |
| 239 | if e.errno == errno.EAGAIN and sys.platform == 'cygwin': |
| 240 | # Convert fork() emulation failure into a CygwinRebaseError(). |
| 241 | raise CygwinRebaseError( |
| 242 | e.errno, |
| 243 | args, |
| 244 | kwargs.get('cwd'), |
| 245 | None, |
| 246 | 'Visit ' |
| 247 | 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure ' |
| 248 | 'to learn how to fix this error; you need to rebase your cygwin ' |
| 249 | 'dlls') |
| 250 | # Popen() can throw OSError when cwd or args[0] doesn't exist. Let it go |
| 251 | # through |
| 252 | raise |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 253 | |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 254 | def _tee_threads(self, input): # pylint: disable=W0622 |
| 255 | """Does I/O for a process's pipes using threads. |
| 256 | |
| 257 | It's the simplest and slowest implementation. Expect very slow behavior. |
| 258 | |
| 259 | If there is a callback and it doesn't keep up with the calls, the timeout |
| 260 | effectiveness will be delayed accordingly. |
| 261 | """ |
| 262 | # Queue of either of <threadname> when done or (<threadname>, data). In |
| 263 | # theory we would like to limit to ~64kb items to not cause large memory |
| 264 | # usage when the callback blocks. It is not done because it slows down |
| 265 | # processing on OSX10.6 by a factor of 2x, making it even slower than |
| 266 | # Windows! Revisit this decision if it becomes a problem, e.g. crash |
| 267 | # because of memory exhaustion. |
| 268 | queue = Queue.Queue() |
| 269 | done = threading.Event() |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 270 | nag = None |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 271 | |
| 272 | def write_stdin(): |
| 273 | try: |
| 274 | stdin_io = cStringIO.StringIO(input) |
| 275 | while True: |
| 276 | data = stdin_io.read(1024) |
| 277 | if data: |
| 278 | self.stdin.write(data) |
| 279 | else: |
| 280 | self.stdin.close() |
| 281 | break |
| 282 | finally: |
| 283 | queue.put('stdin') |
| 284 | |
| 285 | def _queue_pipe_read(pipe, name): |
| 286 | """Queues characters read from a pipe into a queue.""" |
| 287 | try: |
| 288 | while True: |
| 289 | data = pipe.read(1) |
| 290 | if not data: |
| 291 | break |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 292 | if nag: |
| 293 | nag.event() |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 294 | queue.put((name, data)) |
| 295 | finally: |
| 296 | queue.put(name) |
| 297 | |
| 298 | def timeout_fn(): |
| 299 | try: |
| 300 | done.wait(self.timeout) |
| 301 | finally: |
| 302 | queue.put('timeout') |
| 303 | |
| 304 | def wait_fn(): |
| 305 | try: |
| 306 | self.wait() |
| 307 | finally: |
| 308 | queue.put('wait') |
| 309 | |
| 310 | # Starts up to 5 threads: |
| 311 | # Wait for the process to quit |
| 312 | # Read stdout |
| 313 | # Read stderr |
| 314 | # Write stdin |
| 315 | # Timeout |
| 316 | threads = { |
| 317 | 'wait': threading.Thread(target=wait_fn), |
| 318 | } |
| 319 | if self.timeout is not None: |
| 320 | threads['timeout'] = threading.Thread(target=timeout_fn) |
| 321 | if self.stdout_cb: |
| 322 | threads['stdout'] = threading.Thread( |
| 323 | target=_queue_pipe_read, args=(self.stdout, 'stdout')) |
| 324 | if self.stderr_cb: |
| 325 | threads['stderr'] = threading.Thread( |
| 326 | target=_queue_pipe_read, args=(self.stderr, 'stderr')) |
| 327 | if input: |
| 328 | threads['stdin'] = threading.Thread(target=write_stdin) |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 329 | elif self.stdin: |
| 330 | # Pipe but no input, make sure it's closed. |
| 331 | self.stdin.close() |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 332 | for t in threads.itervalues(): |
| 333 | t.start() |
| 334 | |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 335 | if self.nag_timer: |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 336 | def _nag_cb(elapsed): |
| 337 | logging.warn(' No output for %.0f seconds from command:' % elapsed) |
| 338 | logging.warn(' %s' % self.cmd_str) |
| 339 | if (self.nag_max and |
| 340 | int('%.0f' % (elapsed / self.nag_timer)) >= self.nag_max): |
| 341 | queue.put('timeout') |
| 342 | done.set() # Must do this so that timeout thread stops waiting. |
| 343 | nag = NagTimer(self.nag_timer, _nag_cb) |
| 344 | nag.start() |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 345 | |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 346 | timed_out = False |
| 347 | try: |
| 348 | # This thread needs to be optimized for speed. |
| 349 | while threads: |
| 350 | item = queue.get() |
[email protected] | cd8d8e1 | 2012-10-03 17:16:25 | [diff] [blame] | 351 | if item[0] == 'stdout': |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 352 | self.stdout_cb(item[1]) |
[email protected] | cd8d8e1 | 2012-10-03 17:16:25 | [diff] [blame] | 353 | elif item[0] == 'stderr': |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 354 | self.stderr_cb(item[1]) |
| 355 | else: |
| 356 | # A thread terminated. |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 357 | if item in threads: |
| 358 | threads[item].join() |
| 359 | del threads[item] |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 360 | if item == 'wait': |
| 361 | # Terminate the timeout thread if necessary. |
| 362 | done.set() |
| 363 | elif item == 'timeout' and not timed_out and self.poll() is None: |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 364 | logging.debug('Timed out after %.0fs: killing' % ( |
| 365 | time.time() - self.start)) |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 366 | self.kill() |
| 367 | timed_out = True |
| 368 | finally: |
| 369 | # Stop the threads. |
| 370 | done.set() |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 371 | if nag: |
| 372 | nag.cancel() |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 373 | if 'wait' in threads: |
| 374 | # Accelerate things, otherwise it would hang until the child process is |
| 375 | # done. |
| 376 | logging.debug('Killing child because of an exception') |
| 377 | self.kill() |
| 378 | # Join threads. |
| 379 | for thread in threads.itervalues(): |
| 380 | thread.join() |
| 381 | if timed_out: |
| 382 | self.returncode = TIMED_OUT |
| 383 | |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 384 | # pylint: disable=W0221,W0622 |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 385 | def communicate(self, input=None, timeout=None, nag_timer=None, |
| 386 | nag_max=None): |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 387 | """Adds timeout and callbacks support. |
| 388 | |
| 389 | Returns (stdout, stderr) like subprocess.Popen().communicate(). |
| 390 | |
| 391 | - The process will be killed after |timeout| seconds and returncode set to |
| 392 | TIMED_OUT. |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 393 | - If the subprocess runs for |nag_timer| seconds without producing terminal |
| 394 | output, print a warning to stderr. |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 395 | """ |
| 396 | self.timeout = timeout |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 397 | self.nag_timer = nag_timer |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 398 | self.nag_max = nag_max |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 399 | if (not self.timeout and not self.nag_timer and |
| 400 | not self.stdout_cb and not self.stderr_cb): |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 401 | return super(Popen, self).communicate(input) |
| 402 | |
| 403 | if self.timeout and self.shell: |
| 404 | raise TypeError( |
| 405 | 'Using timeout and shell simultaneously will cause a process leak ' |
| 406 | 'since the shell will be killed instead of the child process.') |
| 407 | |
| 408 | stdout = None |
| 409 | stderr = None |
| 410 | # Convert to a lambda to workaround python's deadlock. |
| 411 | # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 412 | # When the pipe fills up, it would deadlock this process. |
| 413 | if self.stdout and not self.stdout_cb and not self.stdout_is_void: |
| 414 | stdout = [] |
| 415 | self.stdout_cb = stdout.append |
| 416 | if self.stderr and not self.stderr_cb and not self.stderr_is_void: |
| 417 | stderr = [] |
| 418 | self.stderr_cb = stderr.append |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 419 | self._tee_threads(input) |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 420 | if stdout is not None: |
| 421 | stdout = ''.join(stdout) |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 422 | if stderr is not None: |
| 423 | stderr = ''.join(stderr) |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 424 | return (stdout, stderr) |
| 425 | |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 426 | |
[email protected] | 12b07e7 | 2013-05-03 22:06:34 | [diff] [blame] | 427 | def communicate(args, timeout=None, nag_timer=None, nag_max=None, **kwargs): |
[email protected] | dd9837f | 2011-11-30 01:55:22 | [diff] [blame] | 428 | """Wraps subprocess.Popen().communicate() and add timeout support. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 429 | |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 430 | Returns ((stdout, stderr), returncode). |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 431 | |
[email protected] | 1d9f629 | 2011-04-07 14:15:36 | [diff] [blame] | 432 | - The process will be killed after |timeout| seconds and returncode set to |
| 433 | TIMED_OUT. |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 434 | - If the subprocess runs for |nag_timer| seconds without producing terminal |
| 435 | output, print a warning to stderr. |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 436 | - Automatically passes stdin content as input so do not specify stdin=PIPE. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 437 | """ |
| 438 | stdin = kwargs.pop('stdin', None) |
| 439 | if stdin is not None: |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 440 | if isinstance(stdin, basestring): |
[email protected] | 0d5ef24 | 2011-04-18 13:52:58 | [diff] [blame] | 441 | # When stdin is passed as an argument, use it as the actual input data and |
| 442 | # set the Popen() parameter accordingly. |
| 443 | kwargs['stdin'] = PIPE |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 444 | else: |
| 445 | kwargs['stdin'] = stdin |
| 446 | stdin = None |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 447 | |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 448 | proc = Popen(args, **kwargs) |
[email protected] | 740a6c0 | 2011-12-05 23:46:44 | [diff] [blame] | 449 | if stdin: |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 450 | return proc.communicate(stdin, timeout, nag_timer), proc.returncode |
[email protected] | 94c712f | 2011-12-01 15:04:57 | [diff] [blame] | 451 | else: |
[email protected] | e0558e6 | 2013-05-02 02:48:51 | [diff] [blame] | 452 | return proc.communicate(None, timeout, nag_timer), proc.returncode |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 453 | |
| 454 | |
[email protected] | 1f063db | 2011-04-18 19:04:52 | [diff] [blame] | 455 | def call(args, **kwargs): |
| 456 | """Emulates subprocess.call(). |
| 457 | |
| 458 | Automatically convert stdout=PIPE or stderr=PIPE to VOID. |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 459 | In no case they can be returned since no code path raises |
| 460 | subprocess2.CalledProcessError. |
[email protected] | 1f063db | 2011-04-18 19:04:52 | [diff] [blame] | 461 | """ |
| 462 | if kwargs.get('stdout') == PIPE: |
| 463 | kwargs['stdout'] = VOID |
| 464 | if kwargs.get('stderr') == PIPE: |
| 465 | kwargs['stderr'] = VOID |
| 466 | return communicate(args, **kwargs)[1] |
| 467 | |
| 468 | |
[email protected] | 0bcd1d3 | 2011-04-26 15:55:49 | [diff] [blame] | 469 | def check_call_out(args, **kwargs): |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 470 | """Improved version of subprocess.check_call(). |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 471 | |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 472 | Returns (stdout, stderr), unlike subprocess.check_call(). |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 473 | """ |
[email protected] | 1f063db | 2011-04-18 19:04:52 | [diff] [blame] | 474 | out, returncode = communicate(args, **kwargs) |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 475 | if returncode: |
| 476 | raise CalledProcessError( |
| 477 | returncode, args, kwargs.get('cwd'), out[0], out[1]) |
| 478 | return out |
| 479 | |
| 480 | |
[email protected] | 0bcd1d3 | 2011-04-26 15:55:49 | [diff] [blame] | 481 | def check_call(args, **kwargs): |
| 482 | """Emulate subprocess.check_call().""" |
| 483 | check_call_out(args, **kwargs) |
| 484 | return 0 |
| 485 | |
| 486 | |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 487 | def capture(args, **kwargs): |
| 488 | """Captures stdout of a process call and returns it. |
| 489 | |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 490 | Returns stdout. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 491 | |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 492 | - Discards returncode. |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 493 | - Blocks stdin by default if not specified since no output will be visible. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 494 | """ |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 495 | kwargs.setdefault('stdin', VOID) |
| 496 | |
| 497 | # Like check_output, deny the caller from using stdout arg. |
| 498 | return communicate(args, stdout=PIPE, **kwargs)[0][0] |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 499 | |
| 500 | |
| 501 | def check_output(args, **kwargs): |
[email protected] | 0bcd1d3 | 2011-04-26 15:55:49 | [diff] [blame] | 502 | """Emulates subprocess.check_output(). |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 503 | |
[email protected] | 0bcd1d3 | 2011-04-26 15:55:49 | [diff] [blame] | 504 | Captures stdout of a process call and returns stdout only. |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 505 | |
[email protected] | 421982f | 2011-04-01 17:38:06 | [diff] [blame] | 506 | - Throws if return code is not 0. |
| 507 | - Works even prior to python 2.7. |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 508 | - Blocks stdin by default if not specified since no output will be visible. |
| 509 | - As per doc, "The stdout argument is not allowed as it is used internally." |
[email protected] | 4860f05 | 2011-03-25 20:34:38 | [diff] [blame] | 510 | """ |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 511 | kwargs.setdefault('stdin', VOID) |
[email protected] | db59bfc | 2011-11-30 14:03:14 | [diff] [blame] | 512 | if 'stdout' in kwargs: |
| 513 | raise ValueError('stdout argument not allowed, it will be overridden.') |
[email protected] | 87e6d33 | 2011-09-09 19:01:28 | [diff] [blame] | 514 | return check_call_out(args, stdout=PIPE, **kwargs)[0] |