blob: c743b039007e2a96dd505b2b58d1b6fb1a38200a [file] [log] [blame]
maruel@chromium.org4860f052011-03-25 20:34:38 +00001# 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
7In theory you shouldn't need anything else in subprocess, or this module failed.
8"""
9
maruel@chromium.org45d8db02011-03-31 20:43:56 +000010from __future__ import with_statement
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000011import errno
maruel@chromium.org4860f052011-03-25 20:34:38 +000012import logging
13import os
14import subprocess
15import sys
16import tempfile
17import time
18import threading
19
20# Constants forwarded from subprocess.
21PIPE = subprocess.PIPE
22STDOUT = subprocess.STDOUT
maruel@chromium.org421982f2011-04-01 17:38:06 +000023# Sends stdout or stderr to os.devnull.
maruel@chromium.org0d5ef242011-04-18 13:52:58 +000024VOID = object()
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000025# Error code when a process was killed because it timed out.
26TIMED_OUT = -2001
maruel@chromium.org4860f052011-03-25 20:34:38 +000027
28# Globals.
29# Set to True if you somehow need to disable this hack.
30SUBPROCESS_CLEANUP_HACKED = False
31
32
33class 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.org1d9f6292011-04-07 14:15:36 +000049class CygwinRebaseError(CalledProcessError):
50 """Occurs when cygwin's fork() emulation fails due to rebased dll."""
51
52
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000053## Utility functions
54
55
56def kill_pid(pid):
57 """Kills a process by its process id."""
58 try:
59 # Unable to import 'module'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000060 # pylint: disable=E1101,F0401
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000061 import signal
62 return os.kill(pid, signal.SIGKILL)
63 except ImportError:
64 pass
65
66
67def 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
83def 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.org4860f052011-03-25 20:34:38 +000094def 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
107def 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.orgc98c0c52011-04-06 13:39:43 +0000114 if sys.platform == 'win32':
115 return None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000116 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
134def Popen(args, **kwargs):
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000135 """Wraps subprocess.Popen().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000136
maruel@chromium.org421982f2011-04-01 17:38:06 +0000137 Returns a subprocess.Popen object.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000138
maruel@chromium.org421982f2011-04-01 17:38:06 +0000139 - 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.org4860f052011-03-25 20:34:38 +0000144
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000145 Note: Popen() can throw OSError when cwd or args[0] doesn't exist.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000146 """
147 # Make sure we hack subprocess if necessary.
148 hack_subprocess()
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +0000149 add_kill()
maruel@chromium.org4860f052011-03-25 20:34:38 +0000150
151 env = get_english_env(kwargs.get('env'))
152 if env:
153 kwargs['env'] = env
maruel@chromium.orgf08b09c2011-04-06 13:14:27 +0000154 if kwargs.get('shell') is None:
maruel@chromium.org4860f052011-03-25 20:34:38 +0000155 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the
156 # executable, but shell=True makes subprocess on Linux fail when it's called
157 # with a list because it only tries to execute the first item in the list.
maruel@chromium.orgf08b09c2011-04-06 13:14:27 +0000158 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000159
160 tmp_str = ' '.join(args)
161 if kwargs.get('cwd', None):
162 tmp_str += '; cwd=%s' % kwargs['cwd']
163 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000164
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000165 def fix(stream):
166 if kwargs.get(stream) in (VOID, os.devnull):
167 # Replaces VOID with handle to /dev/null.
168 # Create a temporary file to workaround python's deadlock.
169 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
170 # When the pipe fills up, it will deadlock this process. Using a real file
171 # works around that issue.
172 kwargs[stream] = open(os.devnull, 'w')
173
174 fix('stdout')
175 fix('stderr')
176
177 try:
178 return subprocess.Popen(args, **kwargs)
179 except OSError, e:
180 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
181 # Convert fork() emulation failure into a CygwinRebaseError().
182 raise CygwinRebaseError(
183 e.errno,
184 args,
185 kwargs.get('cwd'),
186 None,
187 'Visit '
188 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure to '
189 'learn how to fix this error; you need to rebase your cygwin dlls')
190 # Popen() can throw OSError when cwd or args[0] doesn't exist. Let it go
191 # through
192 raise
maruel@chromium.org4860f052011-03-25 20:34:38 +0000193
194
195def call(args, timeout=None, **kwargs):
196 """Wraps subprocess.Popen().communicate().
197
maruel@chromium.org421982f2011-04-01 17:38:06 +0000198 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000199
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000200 - The process will be killed after |timeout| seconds and returncode set to
201 TIMED_OUT.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000202 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000203 """
204 stdin = kwargs.pop('stdin', None)
205 if stdin is not None:
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000206 if stdin is VOID:
207 kwargs['stdin'] = open(os.devnull, 'r')
208 stdin = None
209 else:
210 assert isinstance(stdin, str)
211 # When stdin is passed as an argument, use it as the actual input data and
212 # set the Popen() parameter accordingly.
213 kwargs['stdin'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000214
215 if not timeout:
216 # Normal workflow.
217 proc = Popen(args, **kwargs)
218 if stdin is not None:
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000219 return proc.communicate(stdin), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000220 else:
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000221 return proc.communicate(), proc.returncode
222
223 # Create a temporary file to workaround python's deadlock.
224 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
225 # When the pipe fills up, it will deadlock this process. Using a real file
226 # works around that issue.
227 with tempfile.TemporaryFile() as buff:
228 start = time.time()
229 kwargs['stdout'] = buff
230 proc = Popen(args, **kwargs)
231 if stdin is not None:
232 proc.stdin.write(stdin)
233 while proc.returncode is None:
234 proc.poll()
235 if timeout and (time.time() - start) > timeout:
236 proc.kill()
237 proc.wait()
238 # It's -9 on linux and 1 on Windows. Standardize to TIMED_OUT.
239 proc.returncode = TIMED_OUT
240 time.sleep(0.001)
241 # Now that the process died, reset the cursor and read the file.
242 buff.seek(0)
243 out = [buff.read(), None]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000244 return out, proc.returncode
245
246
247def check_call(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000248 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000249
maruel@chromium.org421982f2011-04-01 17:38:06 +0000250 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000251 """
252 out, returncode = call(args, **kwargs)
253 if returncode:
254 raise CalledProcessError(
255 returncode, args, kwargs.get('cwd'), out[0], out[1])
256 return out
257
258
259def capture(args, **kwargs):
260 """Captures stdout of a process call and returns it.
261
maruel@chromium.org421982f2011-04-01 17:38:06 +0000262 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000263
maruel@chromium.org421982f2011-04-01 17:38:06 +0000264 - Discards returncode.
265 - Discards stderr. By default sets stderr=STDOUT.
maruel@chromium.org4a982272011-04-12 20:49:37 +0000266 - Blocks stdin by default since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000267 """
maruel@chromium.org4a982272011-04-12 20:49:37 +0000268 if kwargs.get('stdin') is None:
269 kwargs['stdin'] = VOID
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000270 if kwargs.get('stdout') is None:
271 kwargs['stdout'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000272 if kwargs.get('stderr') is None:
273 kwargs['stderr'] = STDOUT
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000274 return call(args, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000275
276
277def check_output(args, **kwargs):
278 """Captures stdout of a process call and returns it.
279
maruel@chromium.org421982f2011-04-01 17:38:06 +0000280 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000281
maruel@chromium.org421982f2011-04-01 17:38:06 +0000282 - Discards stderr. By default sets stderr=STDOUT.
283 - Throws if return code is not 0.
284 - Works even prior to python 2.7.
maruel@chromium.org4a982272011-04-12 20:49:37 +0000285 - Blocks stdin by default since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000286 """
maruel@chromium.org4a982272011-04-12 20:49:37 +0000287 if kwargs.get('stdin') is None:
288 kwargs['stdin'] = VOID
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000289 if kwargs.get('stdout') is None:
290 kwargs['stdout'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000291 if kwargs.get('stderr') is None:
292 kwargs['stderr'] = STDOUT
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000293 return check_call(args, **kwargs)[0]