maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 1 | # coding=utf8 |
| 2 | # Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 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 | |
maruel@chromium.org | 45d8db0 | 2011-03-31 20:43:56 +0000 | [diff] [blame] | 10 | from __future__ import with_statement |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 11 | import errno |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 12 | import logging |
| 13 | import os |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | import threading |
| 19 | |
| 20 | # Constants forwarded from subprocess. |
| 21 | PIPE = subprocess.PIPE |
| 22 | STDOUT = subprocess.STDOUT |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 23 | # Sends stdout or stderr to os.devnull. |
maruel@chromium.org | 0d5ef24 | 2011-04-18 13:52:58 +0000 | [diff] [blame] | 24 | VOID = object() |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 25 | # Error code when a process was killed because it timed out. |
| 26 | TIMED_OUT = -2001 |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 27 | |
| 28 | # Globals. |
| 29 | # Set to True if you somehow need to disable this hack. |
| 30 | SUBPROCESS_CLEANUP_HACKED = False |
| 31 | |
| 32 | |
| 33 | class CalledProcessError(subprocess.CalledProcessError): |
| 34 | """Augment the standard exception with more data.""" |
| 35 | def __init__(self, returncode, cmd, cwd, stdout, stderr): |
| 36 | super(CalledProcessError, self).__init__(returncode, cmd) |
| 37 | self.stdout = stdout |
| 38 | self.stderr = stderr |
| 39 | self.cwd = cwd |
| 40 | |
| 41 | def __str__(self): |
| 42 | out = 'Command %s returned non-zero exit status %s' % ( |
| 43 | ' '.join(self.cmd), self.returncode) |
| 44 | if self.cwd: |
| 45 | out += ' in ' + self.cwd |
| 46 | return '\n'.join(filter(None, (out, self.stdout, self.stderr))) |
| 47 | |
| 48 | |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 49 | class CygwinRebaseError(CalledProcessError): |
| 50 | """Occurs when cygwin's fork() emulation fails due to rebased dll.""" |
| 51 | |
| 52 | |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 53 | ## Utility functions |
| 54 | |
| 55 | |
| 56 | def kill_pid(pid): |
| 57 | """Kills a process by its process id.""" |
| 58 | try: |
| 59 | # Unable to import 'module' |
maruel@chromium.org | c98c0c5 | 2011-04-06 13:39:43 +0000 | [diff] [blame] | 60 | # pylint: disable=E1101,F0401 |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 61 | import signal |
| 62 | return os.kill(pid, signal.SIGKILL) |
| 63 | except ImportError: |
| 64 | pass |
| 65 | |
| 66 | |
| 67 | def kill_win(process): |
| 68 | """Kills a process with its windows handle. |
| 69 | |
| 70 | Has no effect on other platforms. |
| 71 | """ |
| 72 | try: |
| 73 | # Unable to import 'module' |
| 74 | # pylint: disable=F0401 |
| 75 | import win32process |
| 76 | # Access to a protected member _handle of a client class |
| 77 | # pylint: disable=W0212 |
| 78 | return win32process.TerminateProcess(process._handle, -1) |
| 79 | except ImportError: |
| 80 | pass |
| 81 | |
| 82 | |
| 83 | def add_kill(): |
| 84 | """Adds kill() method to subprocess.Popen for python <2.6""" |
| 85 | if hasattr(subprocess.Popen, 'kill'): |
| 86 | return |
| 87 | |
| 88 | if sys.platform == 'win32': |
| 89 | subprocess.Popen.kill = kill_win |
| 90 | else: |
| 91 | subprocess.Popen.kill = lambda process: kill_pid(process.pid) |
| 92 | |
| 93 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 94 | def hack_subprocess(): |
| 95 | """subprocess functions may throw exceptions when used in multiple threads. |
| 96 | |
| 97 | See http://bugs.python.org/issue1731717 for more information. |
| 98 | """ |
| 99 | global SUBPROCESS_CLEANUP_HACKED |
| 100 | if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1: |
| 101 | # Only hack if there is ever multiple threads. |
| 102 | # There is no point to leak with only one thread. |
| 103 | subprocess._cleanup = lambda: None |
| 104 | SUBPROCESS_CLEANUP_HACKED = True |
| 105 | |
| 106 | |
| 107 | def get_english_env(env): |
| 108 | """Forces LANG and/or LANGUAGE to be English. |
| 109 | |
| 110 | Forces encoding to utf-8 for subprocesses. |
| 111 | |
| 112 | Returns None if it is unnecessary. |
| 113 | """ |
maruel@chromium.org | c98c0c5 | 2011-04-06 13:39:43 +0000 | [diff] [blame] | 114 | if sys.platform == 'win32': |
| 115 | return None |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 116 | env = env or os.environ |
| 117 | |
| 118 | # Test if it is necessary at all. |
| 119 | is_english = lambda name: env.get(name, 'en').startswith('en') |
| 120 | |
| 121 | if is_english('LANG') and is_english('LANGUAGE'): |
| 122 | return None |
| 123 | |
| 124 | # Requires modifications. |
| 125 | env = env.copy() |
| 126 | def fix_lang(name): |
| 127 | if not is_english(name): |
| 128 | env[name] = 'en_US.UTF-8' |
| 129 | fix_lang('LANG') |
| 130 | fix_lang('LANGUAGE') |
| 131 | return env |
| 132 | |
| 133 | |
| 134 | def Popen(args, **kwargs): |
maruel@chromium.org | 57bf78d | 2011-09-08 18:57:33 +0000 | [diff] [blame] | 135 | """Wraps subprocess.Popen() with various workarounds. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 136 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 137 | Returns a subprocess.Popen object. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 138 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 139 | - Forces English output since it's easier to parse the stdout if it is always |
| 140 | in English. |
| 141 | - Sets shell=True on windows by default. You can override this by forcing |
| 142 | shell parameter to a value. |
| 143 | - Adds support for VOID to not buffer when not needed. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 144 | |
maruel@chromium.org | 57bf78d | 2011-09-08 18:57:33 +0000 | [diff] [blame] | 145 | Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate |
| 146 | exceptions generated by cygwin when it fails trying to emulate fork(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 147 | """ |
| 148 | # Make sure we hack subprocess if necessary. |
| 149 | hack_subprocess() |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 150 | add_kill() |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 151 | |
| 152 | env = get_english_env(kwargs.get('env')) |
| 153 | if env: |
| 154 | kwargs['env'] = env |
maruel@chromium.org | f08b09c | 2011-04-06 13:14:27 +0000 | [diff] [blame] | 155 | if kwargs.get('shell') is None: |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 156 | # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the |
| 157 | # executable, but shell=True makes subprocess on Linux fail when it's called |
| 158 | # with a list because it only tries to execute the first item in the list. |
maruel@chromium.org | f08b09c | 2011-04-06 13:14:27 +0000 | [diff] [blame] | 159 | kwargs['shell'] = bool(sys.platform=='win32') |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 160 | |
| 161 | tmp_str = ' '.join(args) |
| 162 | if kwargs.get('cwd', None): |
| 163 | tmp_str += '; cwd=%s' % kwargs['cwd'] |
| 164 | logging.debug(tmp_str) |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 165 | |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 166 | def fix(stream): |
| 167 | if kwargs.get(stream) in (VOID, os.devnull): |
| 168 | # Replaces VOID with handle to /dev/null. |
| 169 | # Create a temporary file to workaround python's deadlock. |
| 170 | # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait |
| 171 | # When the pipe fills up, it will deadlock this process. Using a real file |
| 172 | # works around that issue. |
| 173 | kwargs[stream] = open(os.devnull, 'w') |
| 174 | |
| 175 | fix('stdout') |
| 176 | fix('stderr') |
| 177 | |
| 178 | try: |
| 179 | return subprocess.Popen(args, **kwargs) |
| 180 | except OSError, e: |
| 181 | if e.errno == errno.EAGAIN and sys.platform == 'cygwin': |
| 182 | # Convert fork() emulation failure into a CygwinRebaseError(). |
| 183 | raise CygwinRebaseError( |
| 184 | e.errno, |
| 185 | args, |
| 186 | kwargs.get('cwd'), |
| 187 | None, |
| 188 | 'Visit ' |
| 189 | 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure to ' |
| 190 | 'learn how to fix this error; you need to rebase your cygwin dlls') |
| 191 | # Popen() can throw OSError when cwd or args[0] doesn't exist. Let it go |
| 192 | # through |
| 193 | raise |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 194 | |
| 195 | |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 196 | def communicate(args, timeout=None, **kwargs): |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 197 | """Wraps subprocess.Popen().communicate(). |
| 198 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 199 | Returns ((stdout, stderr), returncode). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 200 | |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 201 | - The process will be killed after |timeout| seconds and returncode set to |
| 202 | TIMED_OUT. |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 203 | - 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] | 204 | """ |
| 205 | stdin = kwargs.pop('stdin', None) |
| 206 | if stdin is not None: |
maruel@chromium.org | 0d5ef24 | 2011-04-18 13:52:58 +0000 | [diff] [blame] | 207 | if stdin is VOID: |
| 208 | kwargs['stdin'] = open(os.devnull, 'r') |
| 209 | stdin = None |
| 210 | else: |
maruel@chromium.org | 39f645f | 2011-04-21 00:07:53 +0000 | [diff] [blame] | 211 | assert isinstance(stdin, basestring) |
maruel@chromium.org | 0d5ef24 | 2011-04-18 13:52:58 +0000 | [diff] [blame] | 212 | # When stdin is passed as an argument, use it as the actual input data and |
| 213 | # set the Popen() parameter accordingly. |
| 214 | kwargs['stdin'] = PIPE |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 215 | |
| 216 | if not timeout: |
| 217 | # Normal workflow. |
| 218 | proc = Popen(args, **kwargs) |
| 219 | if stdin is not None: |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 220 | return proc.communicate(stdin), proc.returncode |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 221 | else: |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 222 | return proc.communicate(), proc.returncode |
| 223 | |
| 224 | # Create a temporary file to workaround python's deadlock. |
| 225 | # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait |
| 226 | # When the pipe fills up, it will deadlock this process. Using a real file |
| 227 | # works around that issue. |
| 228 | with tempfile.TemporaryFile() as buff: |
| 229 | start = time.time() |
| 230 | kwargs['stdout'] = buff |
| 231 | proc = Popen(args, **kwargs) |
| 232 | if stdin is not None: |
| 233 | proc.stdin.write(stdin) |
| 234 | while proc.returncode is None: |
| 235 | proc.poll() |
| 236 | if timeout and (time.time() - start) > timeout: |
| 237 | proc.kill() |
| 238 | proc.wait() |
| 239 | # It's -9 on linux and 1 on Windows. Standardize to TIMED_OUT. |
| 240 | proc.returncode = TIMED_OUT |
| 241 | time.sleep(0.001) |
| 242 | # Now that the process died, reset the cursor and read the file. |
| 243 | buff.seek(0) |
| 244 | out = [buff.read(), None] |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 245 | return out, proc.returncode |
| 246 | |
| 247 | |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 248 | def call(args, **kwargs): |
| 249 | """Emulates subprocess.call(). |
| 250 | |
| 251 | Automatically convert stdout=PIPE or stderr=PIPE to VOID. |
| 252 | """ |
| 253 | if kwargs.get('stdout') == PIPE: |
| 254 | kwargs['stdout'] = VOID |
| 255 | if kwargs.get('stderr') == PIPE: |
| 256 | kwargs['stderr'] = VOID |
| 257 | return communicate(args, **kwargs)[1] |
| 258 | |
| 259 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 260 | def check_call_out(args, **kwargs): |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 261 | """Improved version of subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 262 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 263 | Returns (stdout, stderr), unlike subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 264 | """ |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 265 | out, returncode = communicate(args, **kwargs) |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 266 | if returncode: |
| 267 | raise CalledProcessError( |
| 268 | returncode, args, kwargs.get('cwd'), out[0], out[1]) |
| 269 | return out |
| 270 | |
| 271 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 272 | def check_call(args, **kwargs): |
| 273 | """Emulate subprocess.check_call().""" |
| 274 | check_call_out(args, **kwargs) |
| 275 | return 0 |
| 276 | |
| 277 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 278 | def capture(args, **kwargs): |
| 279 | """Captures stdout of a process call and returns it. |
| 280 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 281 | Returns stdout. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 282 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 283 | - Discards returncode. |
| 284 | - Discards stderr. By default sets stderr=STDOUT. |
maruel@chromium.org | 4a98227 | 2011-04-12 20:49:37 +0000 | [diff] [blame] | 285 | - Blocks stdin by default since no output will be visible. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 286 | """ |
maruel@chromium.org | 4a98227 | 2011-04-12 20:49:37 +0000 | [diff] [blame] | 287 | if kwargs.get('stdin') is None: |
| 288 | kwargs['stdin'] = VOID |
maruel@chromium.org | eba4022 | 2011-04-05 14:52:48 +0000 | [diff] [blame] | 289 | if kwargs.get('stdout') is None: |
| 290 | kwargs['stdout'] = PIPE |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 291 | if kwargs.get('stderr') is None: |
| 292 | kwargs['stderr'] = STDOUT |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 293 | return communicate(args, **kwargs)[0][0] |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 294 | |
| 295 | |
| 296 | def check_output(args, **kwargs): |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 297 | """Emulates subprocess.check_output(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 298 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 299 | Captures stdout of a process call and returns stdout only. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 300 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 301 | - Discards stderr. By default sets stderr=STDOUT. |
| 302 | - Throws if return code is not 0. |
| 303 | - Works even prior to python 2.7. |
maruel@chromium.org | 4a98227 | 2011-04-12 20:49:37 +0000 | [diff] [blame] | 304 | - Blocks stdin by default since no output will be visible. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 305 | """ |
maruel@chromium.org | 4a98227 | 2011-04-12 20:49:37 +0000 | [diff] [blame] | 306 | if kwargs.get('stdin') is None: |
| 307 | kwargs['stdin'] = VOID |
maruel@chromium.org | eba4022 | 2011-04-05 14:52:48 +0000 | [diff] [blame] | 308 | if kwargs.get('stdout') is None: |
| 309 | kwargs['stdout'] = PIPE |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 310 | if kwargs.get('stderr') is None: |
| 311 | kwargs['stderr'] = STDOUT |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 312 | return check_call_out(args, **kwargs)[0] |