blob: 8964aad7d495b9bcc2e10e1ffc12f6bb6b61b5d7 [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
maruel@chromium.org7eda8622011-11-10 02:23:43 +000016import tempfile
maruel@chromium.org4860f052011-03-25 20:34:38 +000017import 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
maruel@google.comef77f9e2011-11-24 15:24:02 +0000134class Popen(subprocess.Popen):
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000135 """Wraps subprocess.Popen() with various workarounds.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000136
maruel@chromium.org421982f2011-04-01 17:38:06 +0000137 - Forces English output since it's easier to parse the stdout if it is always
138 in English.
139 - Sets shell=True on windows by default. You can override this by forcing
140 shell parameter to a value.
141 - Adds support for VOID to not buffer when not needed.
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000142 - Adds self.start property.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000143
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000144 Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate
145 exceptions generated by cygwin when it fails trying to emulate fork().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000146 """
maruel@google.comef77f9e2011-11-24 15:24:02 +0000147 def __init__(self, args, **kwargs):
148 # Make sure we hack subprocess if necessary.
149 hack_subprocess()
150 add_kill()
maruel@chromium.org4860f052011-03-25 20:34:38 +0000151
maruel@google.comef77f9e2011-11-24 15:24:02 +0000152 env = get_english_env(kwargs.get('env'))
153 if env:
154 kwargs['env'] = env
155 if kwargs.get('shell') is None:
156 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for
157 # the executable, but shell=True makes subprocess on Linux fail when it's
158 # called with a list because it only tries to execute the first item in
159 # the list.
160 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000161
maruel@google.comef77f9e2011-11-24 15:24:02 +0000162 if isinstance(args, basestring):
163 tmp_str = args
164 elif isinstance(args, (list, tuple)):
165 tmp_str = ' '.join(args)
166 else:
167 raise CalledProcessError(None, args, kwargs.get('cwd'), None, None)
168 if kwargs.get('cwd', None):
169 tmp_str += '; cwd=%s' % kwargs['cwd']
170 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000171
maruel@google.comef77f9e2011-11-24 15:24:02 +0000172 def fix(stream):
173 if kwargs.get(stream) in (VOID, os.devnull):
174 # Replaces VOID with handle to /dev/null.
175 # Create a temporary file to workaround python's deadlock.
176 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
177 # When the pipe fills up, it will deadlock this process. Using a real
178 # file works around that issue.
179 kwargs[stream] = open(os.devnull, 'w')
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000180
maruel@google.comef77f9e2011-11-24 15:24:02 +0000181 fix('stdout')
182 fix('stderr')
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000183
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000184 self.start = time.time()
185
maruel@google.comef77f9e2011-11-24 15:24:02 +0000186 try:
187 super(Popen, self).__init__(args, **kwargs)
188 except OSError, e:
189 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
190 # Convert fork() emulation failure into a CygwinRebaseError().
191 raise CygwinRebaseError(
192 e.errno,
193 args,
194 kwargs.get('cwd'),
195 None,
196 'Visit '
197 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure '
198 'to learn how to fix this error; you need to rebase your cygwin '
199 'dlls')
200 # Popen() can throw OSError when cwd or args[0] doesn't exist. Let it go
201 # through
202 raise
maruel@chromium.org4860f052011-03-25 20:34:38 +0000203
204
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000205def communicate(args, timeout=None, **kwargs):
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000206 """Wraps subprocess.Popen().communicate() and add timeout support.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000207
maruel@chromium.org421982f2011-04-01 17:38:06 +0000208 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000209
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000210 - The process will be killed after |timeout| seconds and returncode set to
211 TIMED_OUT.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000212 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000213 """
214 stdin = kwargs.pop('stdin', None)
215 if stdin is not None:
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000216 if stdin is VOID:
217 kwargs['stdin'] = open(os.devnull, 'r')
218 stdin = None
219 else:
maruel@chromium.org39f645f2011-04-21 00:07:53 +0000220 assert isinstance(stdin, basestring)
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000221 # When stdin is passed as an argument, use it as the actual input data and
222 # set the Popen() parameter accordingly.
223 kwargs['stdin'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000224
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000225 if not timeout:
maruel@chromium.org4860f052011-03-25 20:34:38 +0000226 # Normal workflow.
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000227 proc = Popen(args, **kwargs)
228 if stdin is not None:
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000229 return proc.communicate(stdin), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000230 else:
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000231 return proc.communicate(), proc.returncode
232
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000233 # Create a temporary file to workaround python's deadlock.
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000234 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000235 # When the pipe fills up, it will deadlock this process. Using a real file
236 # works around that issue.
237 with tempfile.TemporaryFile() as buff:
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000238 kwargs['stdout'] = buff
239 proc = Popen(args, **kwargs)
240 if stdin is not None:
241 proc.stdin.write(stdin)
242 while proc.returncode is None:
243 proc.poll()
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000244 if timeout and (time.time() - proc.start) > timeout:
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000245 proc.kill()
246 proc.wait()
247 # It's -9 on linux and 1 on Windows. Standardize to TIMED_OUT.
248 proc.returncode = TIMED_OUT
249 time.sleep(0.001)
250 # Now that the process died, reset the cursor and read the file.
251 buff.seek(0)
maruel@chromium.org4942e4a2011-11-15 15:50:50 +0000252 out = (buff.read(), None)
maruel@chromium.org7eda8622011-11-10 02:23:43 +0000253 return out, proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000254
255
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000256def call(args, **kwargs):
257 """Emulates subprocess.call().
258
259 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000260 In no case they can be returned since no code path raises
261 subprocess2.CalledProcessError.
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000262 """
263 if kwargs.get('stdout') == PIPE:
264 kwargs['stdout'] = VOID
265 if kwargs.get('stderr') == PIPE:
266 kwargs['stderr'] = VOID
267 return communicate(args, **kwargs)[1]
268
269
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000270def check_call_out(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000271 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000272
maruel@chromium.org421982f2011-04-01 17:38:06 +0000273 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000274 """
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000275 out, returncode = communicate(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000276 if returncode:
277 raise CalledProcessError(
278 returncode, args, kwargs.get('cwd'), out[0], out[1])
279 return out
280
281
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000282def check_call(args, **kwargs):
283 """Emulate subprocess.check_call()."""
284 check_call_out(args, **kwargs)
285 return 0
286
287
maruel@chromium.org4860f052011-03-25 20:34:38 +0000288def capture(args, **kwargs):
289 """Captures stdout of a process call and returns it.
290
maruel@chromium.org421982f2011-04-01 17:38:06 +0000291 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000292
maruel@chromium.org421982f2011-04-01 17:38:06 +0000293 - Discards returncode.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000294 - Blocks stdin by default if not specified since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000295 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000296 kwargs.setdefault('stdin', VOID)
297
298 # Like check_output, deny the caller from using stdout arg.
299 return communicate(args, stdout=PIPE, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000300
301
302def check_output(args, **kwargs):
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000303 """Emulates subprocess.check_output().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000304
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000305 Captures stdout of a process call and returns stdout only.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000306
maruel@chromium.org421982f2011-04-01 17:38:06 +0000307 - Throws if return code is not 0.
308 - Works even prior to python 2.7.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000309 - Blocks stdin by default if not specified since no output will be visible.
310 - As per doc, "The stdout argument is not allowed as it is used internally."
maruel@chromium.org4860f052011-03-25 20:34:38 +0000311 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000312 kwargs.setdefault('stdin', VOID)
313 return check_call_out(args, stdout=PIPE, **kwargs)[0]