Raul Tambre | a04028c | 2019-05-13 17:23:36 +0000 | [diff] [blame] | 1 | # coding=utf-8 |
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 |
| 15 | import subprocess |
| 16 | import sys |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 17 | import threading |
| 18 | |
John Budorick | 9875e18 | 2018-12-05 22:57:31 +0000 | [diff] [blame] | 19 | # Cache the string-escape codec to ensure subprocess can find it later. |
| 20 | # See crbug.com/912292#c2 for context. |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 21 | if sys.version_info.major == 2: |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 22 | import Queue |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 23 | codecs.lookup('string-escape') |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 24 | else: |
| 25 | import queue as Queue |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 26 | # pylint: disable=redefined-builtin |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 27 | basestring = (str, bytes) |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 28 | |
| 29 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 30 | # Constants forwarded from subprocess. |
| 31 | PIPE = subprocess.PIPE |
| 32 | STDOUT = subprocess.STDOUT |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 33 | # Sends stdout or stderr to os.devnull. |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 34 | VOID = open(os.devnull, 'w') |
| 35 | VOID_INPUT = open(os.devnull, 'r') |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 36 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 37 | |
| 38 | class CalledProcessError(subprocess.CalledProcessError): |
| 39 | """Augment the standard exception with more data.""" |
| 40 | def __init__(self, returncode, cmd, cwd, stdout, stderr): |
tandrii@chromium.org | c15fe57 | 2014-09-19 11:51:43 +0000 | [diff] [blame] | 41 | super(CalledProcessError, self).__init__(returncode, cmd, output=stdout) |
| 42 | self.stdout = self.output # for backward compatibility. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 43 | self.stderr = stderr |
| 44 | self.cwd = cwd |
| 45 | |
| 46 | def __str__(self): |
sbc@chromium.org | 217330f | 2015-06-01 22:10:14 +0000 | [diff] [blame] | 47 | out = 'Command %r returned non-zero exit status %s' % ( |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 48 | ' '.join(self.cmd), self.returncode) |
| 49 | if self.cwd: |
| 50 | out += ' in ' + self.cwd |
| 51 | return '\n'.join(filter(None, (out, self.stdout, self.stderr))) |
| 52 | |
| 53 | |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 54 | class CygwinRebaseError(CalledProcessError): |
| 55 | """Occurs when cygwin's fork() emulation fails due to rebased dll.""" |
| 56 | |
| 57 | |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 58 | ## Utility functions |
| 59 | |
| 60 | |
| 61 | def kill_pid(pid): |
| 62 | """Kills a process by its process id.""" |
| 63 | try: |
| 64 | # Unable to import 'module' |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 65 | # pylint: disable=no-member,F0401 |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 66 | import signal |
Raul Tambre | e99d4b4 | 2019-05-24 18:34:41 +0000 | [diff] [blame] | 67 | return os.kill(pid, signal.SIGTERM) |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 68 | except ImportError: |
| 69 | pass |
| 70 | |
| 71 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 72 | def get_english_env(env): |
| 73 | """Forces LANG and/or LANGUAGE to be English. |
| 74 | |
| 75 | Forces encoding to utf-8 for subprocesses. |
| 76 | |
| 77 | Returns None if it is unnecessary. |
| 78 | """ |
maruel@chromium.org | c98c0c5 | 2011-04-06 13:39:43 +0000 | [diff] [blame] | 79 | if sys.platform == 'win32': |
| 80 | return None |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 81 | env = env or os.environ |
| 82 | |
| 83 | # Test if it is necessary at all. |
| 84 | is_english = lambda name: env.get(name, 'en').startswith('en') |
| 85 | |
| 86 | if is_english('LANG') and is_english('LANGUAGE'): |
| 87 | return None |
| 88 | |
| 89 | # Requires modifications. |
| 90 | env = env.copy() |
| 91 | def fix_lang(name): |
| 92 | if not is_english(name): |
| 93 | env[name] = 'en_US.UTF-8' |
| 94 | fix_lang('LANG') |
| 95 | fix_lang('LANGUAGE') |
| 96 | return env |
| 97 | |
| 98 | |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 99 | class Popen(subprocess.Popen): |
maruel@chromium.org | 57bf78d | 2011-09-08 18:57:33 +0000 | [diff] [blame] | 100 | """Wraps subprocess.Popen() with various workarounds. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 101 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 102 | - Forces English output since it's easier to parse the stdout if it is always |
| 103 | in English. |
| 104 | - Sets shell=True on windows by default. You can override this by forcing |
| 105 | shell parameter to a value. |
| 106 | - Adds support for VOID to not buffer when not needed. |
maruel@chromium.org | dd9837f | 2011-11-30 01:55:22 +0000 | [diff] [blame] | 107 | - Adds self.start property. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 108 | |
maruel@chromium.org | 57bf78d | 2011-09-08 18:57:33 +0000 | [diff] [blame] | 109 | Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate |
| 110 | exceptions generated by cygwin when it fails trying to emulate fork(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 111 | """ |
torne@chromium.org | 434e790 | 2015-09-15 09:57:01 +0000 | [diff] [blame] | 112 | # subprocess.Popen.__init__() is not threadsafe; there is a race between |
| 113 | # creating the exec-error pipe for the child and setting it to CLOEXEC during |
| 114 | # which another thread can fork and cause the pipe to be inherited by its |
| 115 | # descendents, which will cause the current Popen to hang until all those |
| 116 | # descendents exit. Protect this with a lock so that only one fork/exec can |
| 117 | # happen at a time. |
| 118 | popen_lock = threading.Lock() |
| 119 | |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 120 | def __init__(self, args, **kwargs): |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 121 | env = get_english_env(kwargs.get('env')) |
| 122 | if env: |
| 123 | kwargs['env'] = env |
Raul Tambre | e9730d7 | 2020-01-15 19:28:48 +0000 | [diff] [blame] | 124 | if kwargs.get('env') is not None and sys.version_info.major != 2: |
| 125 | # Subprocess expects environment variables to be strings in Python 3. |
| 126 | def ensure_str(value): |
| 127 | if isinstance(value, bytes): |
| 128 | return value.decode() |
| 129 | return value |
| 130 | |
| 131 | kwargs['env'] = { |
| 132 | ensure_str(k): ensure_str(v) |
| 133 | for k, v in kwargs['env'].items() |
| 134 | } |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 135 | if kwargs.get('shell') is None: |
| 136 | # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for |
| 137 | # the executable, but shell=True makes subprocess on Linux fail when it's |
| 138 | # called with a list because it only tries to execute the first item in |
| 139 | # the list. |
| 140 | kwargs['shell'] = bool(sys.platform=='win32') |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 141 | |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 142 | if isinstance(args, basestring): |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 143 | tmp_str = args |
| 144 | elif isinstance(args, (list, tuple)): |
| 145 | tmp_str = ' '.join(args) |
| 146 | else: |
| 147 | raise CalledProcessError(None, args, kwargs.get('cwd'), None, None) |
| 148 | if kwargs.get('cwd', None): |
| 149 | tmp_str += '; cwd=%s' % kwargs['cwd'] |
| 150 | logging.debug(tmp_str) |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 151 | |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 152 | try: |
torne@chromium.org | 434e790 | 2015-09-15 09:57:01 +0000 | [diff] [blame] | 153 | with self.popen_lock: |
| 154 | super(Popen, self).__init__(args, **kwargs) |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 155 | except OSError as e: |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 156 | if e.errno == errno.EAGAIN and sys.platform == 'cygwin': |
| 157 | # Convert fork() emulation failure into a CygwinRebaseError(). |
| 158 | raise CygwinRebaseError( |
| 159 | e.errno, |
| 160 | args, |
| 161 | kwargs.get('cwd'), |
| 162 | None, |
| 163 | 'Visit ' |
| 164 | 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure ' |
| 165 | 'to learn how to fix this error; you need to rebase your cygwin ' |
| 166 | 'dlls') |
luqui@chromium.org | 7f627a9 | 2014-03-28 00:57:44 +0000 | [diff] [blame] | 167 | # 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] | 168 | raise OSError('Execution failed with error: %s.\n' |
| 169 | 'Check that %s or %s exist and have execution permission.' |
| 170 | % (str(e), kwargs.get('cwd'), args[0])) |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 171 | |
maruel@chromium.org | 94c712f | 2011-12-01 15:04:57 +0000 | [diff] [blame] | 172 | |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 173 | def communicate(args, **kwargs): |
| 174 | """Wraps subprocess.Popen().communicate(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 175 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 176 | Returns ((stdout, stderr), returncode). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 177 | |
szager@chromium.org | e0558e6 | 2013-05-02 02:48:51 +0000 | [diff] [blame] | 178 | - If the subprocess runs for |nag_timer| seconds without producing terminal |
| 179 | output, print a warning to stderr. |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 180 | - 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] | 181 | """ |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 182 | stdin = None |
| 183 | # When stdin is passed as an argument, use it as the actual input data and |
| 184 | # set the Popen() parameter accordingly. |
| 185 | if 'stdin' in kwargs and isinstance(kwargs['stdin'], basestring): |
| 186 | stdin = kwargs['stdin'] |
| 187 | kwargs['stdin'] = PIPE |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 188 | |
maruel@chromium.org | 94c712f | 2011-12-01 15:04:57 +0000 | [diff] [blame] | 189 | proc = Popen(args, **kwargs) |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 190 | return proc.communicate(stdin), proc.returncode |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 191 | |
| 192 | |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 193 | def call(args, **kwargs): |
| 194 | """Emulates subprocess.call(). |
| 195 | |
| 196 | Automatically convert stdout=PIPE or stderr=PIPE to VOID. |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 197 | In no case they can be returned since no code path raises |
| 198 | subprocess2.CalledProcessError. |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 199 | """ |
| 200 | if kwargs.get('stdout') == PIPE: |
| 201 | kwargs['stdout'] = VOID |
| 202 | if kwargs.get('stderr') == PIPE: |
| 203 | kwargs['stderr'] = VOID |
| 204 | return communicate(args, **kwargs)[1] |
| 205 | |
| 206 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 207 | def check_call_out(args, **kwargs): |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 208 | """Improved version of subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 209 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 210 | Returns (stdout, stderr), unlike subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 211 | """ |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 212 | out, returncode = communicate(args, **kwargs) |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 213 | if returncode: |
| 214 | raise CalledProcessError( |
| 215 | returncode, args, kwargs.get('cwd'), out[0], out[1]) |
| 216 | return out |
| 217 | |
| 218 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 219 | def check_call(args, **kwargs): |
| 220 | """Emulate subprocess.check_call().""" |
| 221 | check_call_out(args, **kwargs) |
| 222 | return 0 |
| 223 | |
| 224 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 225 | def capture(args, **kwargs): |
| 226 | """Captures stdout of a process call and returns it. |
| 227 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 228 | Returns stdout. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 229 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 230 | - Discards returncode. |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 231 | - 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] | 232 | """ |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 233 | kwargs.setdefault('stdin', VOID_INPUT) |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 234 | |
| 235 | # Like check_output, deny the caller from using stdout arg. |
| 236 | return communicate(args, stdout=PIPE, **kwargs)[0][0] |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 237 | |
| 238 | |
| 239 | def check_output(args, **kwargs): |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 240 | """Emulates subprocess.check_output(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 241 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 242 | Captures stdout of a process call and returns stdout only. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 243 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 244 | - Throws if return code is not 0. |
| 245 | - Works even prior to python 2.7. |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 246 | - Blocks stdin by default if not specified since no output will be visible. |
| 247 | - 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] | 248 | """ |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 249 | kwargs.setdefault('stdin', VOID_INPUT) |
maruel@chromium.org | db59bfc | 2011-11-30 14:03:14 +0000 | [diff] [blame] | 250 | if 'stdout' in kwargs: |
pgervais@chromium.org | 022d06e | 2014-04-29 17:08:12 +0000 | [diff] [blame] | 251 | raise ValueError('stdout argument not allowed, it would be overridden.') |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 252 | return check_call_out(args, stdout=PIPE, **kwargs)[0] |