blob: dea1a2d6c7d40ea398bc476827b84a11c668d16f [file] [log] [blame]
Raul Tambrea04028c2019-05-13 17:23:36 +00001# coding=utf-8
maruel@chromium.org4f6852c2012-04-20 20:39:20 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.org4860f052011-03-25 20:34:38 +00003# 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
7In theory you shouldn't need anything else in subprocess, or this module failed.
8"""
9
John Budorick9875e182018-12-05 22:57:31 +000010import codecs
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000011import errno
Raul Tambreb946b232019-03-26 14:48:46 +000012import io
maruel@chromium.org4860f052011-03-25 20:34:38 +000013import logging
14import os
15import subprocess
16import sys
maruel@chromium.org4860f052011-03-25 20:34:38 +000017import threading
18
John Budorick9875e182018-12-05 22:57:31 +000019# Cache the string-escape codec to ensure subprocess can find it later.
20# See crbug.com/912292#c2 for context.
Raul Tambreb946b232019-03-26 14:48:46 +000021if sys.version_info.major == 2:
Edward Lemur1556fbc2019-08-09 15:24:48 +000022 import Queue
Raul Tambreb946b232019-03-26 14:48:46 +000023 codecs.lookup('string-escape')
Edward Lemur1556fbc2019-08-09 15:24:48 +000024else:
25 import queue as Queue
Aaron Gableac9b0f32019-04-18 17:38:37 +000026 # pylint: disable=redefined-builtin
Edward Lemur1556fbc2019-08-09 15:24:48 +000027 basestring = (str, bytes)
Aaron Gableac9b0f32019-04-18 17:38:37 +000028
29
maruel@chromium.org4860f052011-03-25 20:34:38 +000030# Constants forwarded from subprocess.
31PIPE = subprocess.PIPE
32STDOUT = subprocess.STDOUT
maruel@chromium.org421982f2011-04-01 17:38:06 +000033# Sends stdout or stderr to os.devnull.
Edward Lemur1556fbc2019-08-09 15:24:48 +000034VOID = open(os.devnull, 'w')
35VOID_INPUT = open(os.devnull, 'r')
maruel@chromium.org4860f052011-03-25 20:34:38 +000036
maruel@chromium.org4860f052011-03-25 20:34:38 +000037
38class CalledProcessError(subprocess.CalledProcessError):
39 """Augment the standard exception with more data."""
40 def __init__(self, returncode, cmd, cwd, stdout, stderr):
tandrii@chromium.orgc15fe572014-09-19 11:51:43 +000041 super(CalledProcessError, self).__init__(returncode, cmd, output=stdout)
42 self.stdout = self.output # for backward compatibility.
maruel@chromium.org4860f052011-03-25 20:34:38 +000043 self.stderr = stderr
44 self.cwd = cwd
45
46 def __str__(self):
sbc@chromium.org217330f2015-06-01 22:10:14 +000047 out = 'Command %r returned non-zero exit status %s' % (
maruel@chromium.org4860f052011-03-25 20:34:38 +000048 ' '.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.org1d9f6292011-04-07 14:15:36 +000054class CygwinRebaseError(CalledProcessError):
55 """Occurs when cygwin's fork() emulation fails due to rebased dll."""
56
57
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000058## Utility functions
59
60
61def kill_pid(pid):
62 """Kills a process by its process id."""
63 try:
64 # Unable to import 'module'
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080065 # pylint: disable=no-member,F0401
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000066 import signal
Raul Tambree99d4b42019-05-24 18:34:41 +000067 return os.kill(pid, signal.SIGTERM)
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000068 except ImportError:
69 pass
70
71
maruel@chromium.org4860f052011-03-25 20:34:38 +000072def 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.orgc98c0c52011-04-06 13:39:43 +000079 if sys.platform == 'win32':
80 return None
maruel@chromium.org4860f052011-03-25 20:34:38 +000081 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.comef77f9e2011-11-24 15:24:02 +000099class Popen(subprocess.Popen):
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000100 """Wraps subprocess.Popen() with various workarounds.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000101
maruel@chromium.org421982f2011-04-01 17:38:06 +0000102 - 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.orgdd9837f2011-11-30 01:55:22 +0000107 - Adds self.start property.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000108
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000109 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.org4860f052011-03-25 20:34:38 +0000111 """
torne@chromium.org434e7902015-09-15 09:57:01 +0000112 # 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.comef77f9e2011-11-24 15:24:02 +0000120 def __init__(self, args, **kwargs):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000121 env = get_english_env(kwargs.get('env'))
122 if env:
123 kwargs['env'] = env
124 if kwargs.get('shell') is None:
125 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for
126 # the executable, but shell=True makes subprocess on Linux fail when it's
127 # called with a list because it only tries to execute the first item in
128 # the list.
129 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000130
Aaron Gableac9b0f32019-04-18 17:38:37 +0000131 if isinstance(args, basestring):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000132 tmp_str = args
133 elif isinstance(args, (list, tuple)):
134 tmp_str = ' '.join(args)
135 else:
136 raise CalledProcessError(None, args, kwargs.get('cwd'), None, None)
137 if kwargs.get('cwd', None):
138 tmp_str += '; cwd=%s' % kwargs['cwd']
139 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000140
maruel@google.comef77f9e2011-11-24 15:24:02 +0000141 try:
torne@chromium.org434e7902015-09-15 09:57:01 +0000142 with self.popen_lock:
143 super(Popen, self).__init__(args, **kwargs)
Raul Tambreb946b232019-03-26 14:48:46 +0000144 except OSError as e:
maruel@google.comef77f9e2011-11-24 15:24:02 +0000145 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
146 # Convert fork() emulation failure into a CygwinRebaseError().
147 raise CygwinRebaseError(
148 e.errno,
149 args,
150 kwargs.get('cwd'),
151 None,
152 'Visit '
153 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure '
154 'to learn how to fix this error; you need to rebase your cygwin '
155 'dlls')
luqui@chromium.org7f627a92014-03-28 00:57:44 +0000156 # Popen() can throw OSError when cwd or args[0] doesn't exist.
pgervais@chromium.orgfb653b62014-04-29 17:29:18 +0000157 raise OSError('Execution failed with error: %s.\n'
158 'Check that %s or %s exist and have execution permission.'
159 % (str(e), kwargs.get('cwd'), args[0]))
maruel@chromium.org4860f052011-03-25 20:34:38 +0000160
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000161
Edward Lemur1556fbc2019-08-09 15:24:48 +0000162def communicate(args, **kwargs):
163 """Wraps subprocess.Popen().communicate().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000164
maruel@chromium.org421982f2011-04-01 17:38:06 +0000165 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000166
szager@chromium.orge0558e62013-05-02 02:48:51 +0000167 - If the subprocess runs for |nag_timer| seconds without producing terminal
168 output, print a warning to stderr.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000169 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000170 """
Edward Lemur1556fbc2019-08-09 15:24:48 +0000171 stdin = None
172 # When stdin is passed as an argument, use it as the actual input data and
173 # set the Popen() parameter accordingly.
174 if 'stdin' in kwargs and isinstance(kwargs['stdin'], basestring):
175 stdin = kwargs['stdin']
176 kwargs['stdin'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000177
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000178 proc = Popen(args, **kwargs)
Edward Lemur1556fbc2019-08-09 15:24:48 +0000179 return proc.communicate(stdin), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000180
181
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000182def call(args, **kwargs):
183 """Emulates subprocess.call().
184
185 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000186 In no case they can be returned since no code path raises
187 subprocess2.CalledProcessError.
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000188 """
189 if kwargs.get('stdout') == PIPE:
190 kwargs['stdout'] = VOID
191 if kwargs.get('stderr') == PIPE:
192 kwargs['stderr'] = VOID
193 return communicate(args, **kwargs)[1]
194
195
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000196def check_call_out(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000197 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000198
maruel@chromium.org421982f2011-04-01 17:38:06 +0000199 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000200 """
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000201 out, returncode = communicate(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000202 if returncode:
203 raise CalledProcessError(
204 returncode, args, kwargs.get('cwd'), out[0], out[1])
205 return out
206
207
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000208def check_call(args, **kwargs):
209 """Emulate subprocess.check_call()."""
210 check_call_out(args, **kwargs)
211 return 0
212
213
maruel@chromium.org4860f052011-03-25 20:34:38 +0000214def capture(args, **kwargs):
215 """Captures stdout of a process call and returns it.
216
maruel@chromium.org421982f2011-04-01 17:38:06 +0000217 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000218
maruel@chromium.org421982f2011-04-01 17:38:06 +0000219 - Discards returncode.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000220 - Blocks stdin by default if not specified since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000221 """
Edward Lemur1556fbc2019-08-09 15:24:48 +0000222 kwargs.setdefault('stdin', VOID_INPUT)
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000223
224 # Like check_output, deny the caller from using stdout arg.
225 return communicate(args, stdout=PIPE, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000226
227
228def check_output(args, **kwargs):
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000229 """Emulates subprocess.check_output().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000230
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000231 Captures stdout of a process call and returns stdout only.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000232
maruel@chromium.org421982f2011-04-01 17:38:06 +0000233 - Throws if return code is not 0.
234 - Works even prior to python 2.7.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000235 - Blocks stdin by default if not specified since no output will be visible.
236 - As per doc, "The stdout argument is not allowed as it is used internally."
maruel@chromium.org4860f052011-03-25 20:34:38 +0000237 """
Edward Lemur1556fbc2019-08-09 15:24:48 +0000238 kwargs.setdefault('stdin', VOID_INPUT)
maruel@chromium.orgdb59bfc2011-11-30 14:03:14 +0000239 if 'stdout' in kwargs:
pgervais@chromium.org022d06e2014-04-29 17:08:12 +0000240 raise ValueError('stdout argument not allowed, it would be overridden.')
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000241 return check_call_out(args, stdout=PIPE, **kwargs)[0]