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