blob: ac44555dcf5a038478ca172669035d974910382d [file] [log] [blame]
[email protected]4860f052011-03-25 20:34:381# coding=utf8
[email protected]4f6852c2012-04-20 20:39:202# Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]4860f052011-03-25 20:34:383# 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
[email protected]94c712f2011-12-01 15:04:5710import cStringIO
[email protected]1d9f6292011-04-07 14:15:3611import errno
[email protected]4860f052011-03-25 20:34:3812import logging
13import os
[email protected]94c712f2011-12-01 15:04:5714import Queue
[email protected]4860f052011-03-25 20:34:3815import subprocess
16import sys
[email protected]4860f052011-03-25 20:34:3817import time
18import threading
19
[email protected]a8e81632011-12-01 00:35:2420
[email protected]4860f052011-03-25 20:34:3821# Constants forwarded from subprocess.
22PIPE = subprocess.PIPE
23STDOUT = subprocess.STDOUT
[email protected]421982f2011-04-01 17:38:0624# Sends stdout or stderr to os.devnull.
[email protected]0d5ef242011-04-18 13:52:5825VOID = object()
[email protected]1d9f6292011-04-07 14:15:3626# Error code when a process was killed because it timed out.
27TIMED_OUT = -2001
[email protected]4860f052011-03-25 20:34:3828
29# Globals.
30# Set to True if you somehow need to disable this hack.
31SUBPROCESS_CLEANUP_HACKED = False
32
33
34class CalledProcessError(subprocess.CalledProcessError):
35 """Augment the standard exception with more data."""
36 def __init__(self, returncode, cmd, cwd, stdout, stderr):
37 super(CalledProcessError, self).__init__(returncode, cmd)
38 self.stdout = stdout
39 self.stderr = stderr
40 self.cwd = cwd
41
42 def __str__(self):
43 out = 'Command %s returned non-zero exit status %s' % (
44 ' '.join(self.cmd), self.returncode)
45 if self.cwd:
46 out += ' in ' + self.cwd
47 return '\n'.join(filter(None, (out, self.stdout, self.stderr)))
48
49
[email protected]1d9f6292011-04-07 14:15:3650class CygwinRebaseError(CalledProcessError):
51 """Occurs when cygwin's fork() emulation fails due to rebased dll."""
52
53
[email protected]fb3d3242011-04-01 14:03:0854## Utility functions
55
56
57def kill_pid(pid):
58 """Kills a process by its process id."""
59 try:
60 # Unable to import 'module'
[email protected]c98c0c52011-04-06 13:39:4361 # pylint: disable=E1101,F0401
[email protected]fb3d3242011-04-01 14:03:0862 import signal
63 return os.kill(pid, signal.SIGKILL)
64 except ImportError:
65 pass
66
67
68def kill_win(process):
69 """Kills a process with its windows handle.
70
71 Has no effect on other platforms.
72 """
73 try:
74 # Unable to import 'module'
75 # pylint: disable=F0401
76 import win32process
77 # Access to a protected member _handle of a client class
78 # pylint: disable=W0212
79 return win32process.TerminateProcess(process._handle, -1)
80 except ImportError:
81 pass
82
83
84def add_kill():
85 """Adds kill() method to subprocess.Popen for python <2.6"""
86 if hasattr(subprocess.Popen, 'kill'):
87 return
88
89 if sys.platform == 'win32':
90 subprocess.Popen.kill = kill_win
91 else:
92 subprocess.Popen.kill = lambda process: kill_pid(process.pid)
93
94
[email protected]4860f052011-03-25 20:34:3895def hack_subprocess():
96 """subprocess functions may throw exceptions when used in multiple threads.
97
98 See http://bugs.python.org/issue1731717 for more information.
99 """
100 global SUBPROCESS_CLEANUP_HACKED
101 if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1:
102 # Only hack if there is ever multiple threads.
103 # There is no point to leak with only one thread.
104 subprocess._cleanup = lambda: None
105 SUBPROCESS_CLEANUP_HACKED = True
106
107
108def get_english_env(env):
109 """Forces LANG and/or LANGUAGE to be English.
110
111 Forces encoding to utf-8 for subprocesses.
112
113 Returns None if it is unnecessary.
114 """
[email protected]c98c0c52011-04-06 13:39:43115 if sys.platform == 'win32':
116 return None
[email protected]4860f052011-03-25 20:34:38117 env = env or os.environ
118
119 # Test if it is necessary at all.
120 is_english = lambda name: env.get(name, 'en').startswith('en')
121
122 if is_english('LANG') and is_english('LANGUAGE'):
123 return None
124
125 # Requires modifications.
126 env = env.copy()
127 def fix_lang(name):
128 if not is_english(name):
129 env[name] = 'en_US.UTF-8'
130 fix_lang('LANG')
131 fix_lang('LANGUAGE')
132 return env
133
134
[email protected]12b07e72013-05-03 22:06:34135class NagTimer(object):
136 """
137 Triggers a callback when a time interval passes without an event being fired.
138
139 For example, the event could be receiving terminal output from a subprocess;
140 and the callback could print a warning to stderr that the subprocess appeared
141 to be hung.
142 """
143 def __init__(self, interval, cb):
144 self.interval = interval
145 self.cb = cb
146 self.timer = threading.Timer(self.interval, self.fn)
147 self.last_output = self.previous_last_output = 0
148
149 def start(self):
150 self.last_output = self.previous_last_output = time.time()
151 self.timer.start()
152
153 def event(self):
154 self.last_output = time.time()
155
156 def fn(self):
157 now = time.time()
158 if self.last_output == self.previous_last_output:
159 self.cb(now - self.previous_last_output)
160 # Use 0.1 fudge factor, just in case
161 # (self.last_output - now) is very close to zero.
162 sleep_time = (self.last_output - now - 0.1) % self.interval
163 self.previous_last_output = self.last_output
164 self.timer = threading.Timer(sleep_time + 0.1, self.fn)
165 self.timer.start()
166
167 def cancel(self):
168 self.timer.cancel()
169
170
[email protected]ef77f9e2011-11-24 15:24:02171class Popen(subprocess.Popen):
[email protected]57bf78d2011-09-08 18:57:33172 """Wraps subprocess.Popen() with various workarounds.
[email protected]4860f052011-03-25 20:34:38173
[email protected]421982f2011-04-01 17:38:06174 - Forces English output since it's easier to parse the stdout if it is always
175 in English.
176 - Sets shell=True on windows by default. You can override this by forcing
177 shell parameter to a value.
178 - Adds support for VOID to not buffer when not needed.
[email protected]dd9837f2011-11-30 01:55:22179 - Adds self.start property.
[email protected]4860f052011-03-25 20:34:38180
[email protected]57bf78d2011-09-08 18:57:33181 Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate
182 exceptions generated by cygwin when it fails trying to emulate fork().
[email protected]4860f052011-03-25 20:34:38183 """
[email protected]ef77f9e2011-11-24 15:24:02184 def __init__(self, args, **kwargs):
185 # Make sure we hack subprocess if necessary.
186 hack_subprocess()
187 add_kill()
[email protected]4860f052011-03-25 20:34:38188
[email protected]ef77f9e2011-11-24 15:24:02189 env = get_english_env(kwargs.get('env'))
190 if env:
191 kwargs['env'] = env
192 if kwargs.get('shell') is None:
193 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for
194 # the executable, but shell=True makes subprocess on Linux fail when it's
195 # called with a list because it only tries to execute the first item in
196 # the list.
197 kwargs['shell'] = bool(sys.platform=='win32')
[email protected]4860f052011-03-25 20:34:38198
[email protected]ef77f9e2011-11-24 15:24:02199 if isinstance(args, basestring):
200 tmp_str = args
201 elif isinstance(args, (list, tuple)):
202 tmp_str = ' '.join(args)
203 else:
204 raise CalledProcessError(None, args, kwargs.get('cwd'), None, None)
205 if kwargs.get('cwd', None):
206 tmp_str += '; cwd=%s' % kwargs['cwd']
207 logging.debug(tmp_str)
[email protected]421982f2011-04-01 17:38:06208
[email protected]94c712f2011-12-01 15:04:57209 self.stdout_cb = None
210 self.stderr_cb = None
[email protected]740a6c02011-12-05 23:46:44211 self.stdin_is_void = False
212 self.stdout_is_void = False
213 self.stderr_is_void = False
[email protected]e0558e62013-05-02 02:48:51214 self.cmd_str = tmp_str
[email protected]740a6c02011-12-05 23:46:44215
216 if kwargs.get('stdin') is VOID:
217 kwargs['stdin'] = open(os.devnull, 'r')
218 self.stdin_is_void = True
219
220 for stream in ('stdout', 'stderr'):
[email protected]ef77f9e2011-11-24 15:24:02221 if kwargs.get(stream) in (VOID, os.devnull):
[email protected]ef77f9e2011-11-24 15:24:02222 kwargs[stream] = open(os.devnull, 'w')
[email protected]740a6c02011-12-05 23:46:44223 setattr(self, stream + '_is_void', True)
[email protected]94c712f2011-12-01 15:04:57224 if callable(kwargs.get(stream)):
[email protected]94c712f2011-12-01 15:04:57225 setattr(self, stream + '_cb', kwargs[stream])
226 kwargs[stream] = PIPE
[email protected]1d9f6292011-04-07 14:15:36227
[email protected]dd9837f2011-11-30 01:55:22228 self.start = time.time()
[email protected]94c712f2011-12-01 15:04:57229 self.timeout = None
[email protected]e0558e62013-05-02 02:48:51230 self.nag_timer = None
[email protected]12b07e72013-05-03 22:06:34231 self.nag_max = None
[email protected]a8e81632011-12-01 00:35:24232 self.shell = kwargs.get('shell', None)
[email protected]14e37ad2011-11-30 20:26:16233 # Silence pylint on MacOSX
234 self.returncode = None
[email protected]a8e81632011-12-01 00:35:24235
[email protected]ef77f9e2011-11-24 15:24:02236 try:
237 super(Popen, self).__init__(args, **kwargs)
238 except OSError, e:
239 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
240 # Convert fork() emulation failure into a CygwinRebaseError().
241 raise CygwinRebaseError(
242 e.errno,
243 args,
244 kwargs.get('cwd'),
245 None,
246 'Visit '
247 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure '
248 'to learn how to fix this error; you need to rebase your cygwin '
249 'dlls')
250 # Popen() can throw OSError when cwd or args[0] doesn't exist. Let it go
251 # through
252 raise
[email protected]4860f052011-03-25 20:34:38253
[email protected]94c712f2011-12-01 15:04:57254 def _tee_threads(self, input): # pylint: disable=W0622
255 """Does I/O for a process's pipes using threads.
256
257 It's the simplest and slowest implementation. Expect very slow behavior.
258
259 If there is a callback and it doesn't keep up with the calls, the timeout
260 effectiveness will be delayed accordingly.
261 """
262 # Queue of either of <threadname> when done or (<threadname>, data). In
263 # theory we would like to limit to ~64kb items to not cause large memory
264 # usage when the callback blocks. It is not done because it slows down
265 # processing on OSX10.6 by a factor of 2x, making it even slower than
266 # Windows! Revisit this decision if it becomes a problem, e.g. crash
267 # because of memory exhaustion.
268 queue = Queue.Queue()
269 done = threading.Event()
[email protected]12b07e72013-05-03 22:06:34270 nag = None
[email protected]94c712f2011-12-01 15:04:57271
272 def write_stdin():
273 try:
274 stdin_io = cStringIO.StringIO(input)
275 while True:
276 data = stdin_io.read(1024)
277 if data:
278 self.stdin.write(data)
279 else:
280 self.stdin.close()
281 break
282 finally:
283 queue.put('stdin')
284
285 def _queue_pipe_read(pipe, name):
286 """Queues characters read from a pipe into a queue."""
287 try:
288 while True:
289 data = pipe.read(1)
290 if not data:
291 break
[email protected]12b07e72013-05-03 22:06:34292 if nag:
293 nag.event()
[email protected]94c712f2011-12-01 15:04:57294 queue.put((name, data))
295 finally:
296 queue.put(name)
297
298 def timeout_fn():
299 try:
300 done.wait(self.timeout)
301 finally:
302 queue.put('timeout')
303
304 def wait_fn():
305 try:
306 self.wait()
307 finally:
308 queue.put('wait')
309
310 # Starts up to 5 threads:
311 # Wait for the process to quit
312 # Read stdout
313 # Read stderr
314 # Write stdin
315 # Timeout
316 threads = {
317 'wait': threading.Thread(target=wait_fn),
318 }
319 if self.timeout is not None:
320 threads['timeout'] = threading.Thread(target=timeout_fn)
321 if self.stdout_cb:
322 threads['stdout'] = threading.Thread(
323 target=_queue_pipe_read, args=(self.stdout, 'stdout'))
324 if self.stderr_cb:
325 threads['stderr'] = threading.Thread(
326 target=_queue_pipe_read, args=(self.stderr, 'stderr'))
327 if input:
328 threads['stdin'] = threading.Thread(target=write_stdin)
[email protected]740a6c02011-12-05 23:46:44329 elif self.stdin:
330 # Pipe but no input, make sure it's closed.
331 self.stdin.close()
[email protected]94c712f2011-12-01 15:04:57332 for t in threads.itervalues():
333 t.start()
334
[email protected]e0558e62013-05-02 02:48:51335 if self.nag_timer:
[email protected]12b07e72013-05-03 22:06:34336 def _nag_cb(elapsed):
337 logging.warn(' No output for %.0f seconds from command:' % elapsed)
338 logging.warn(' %s' % self.cmd_str)
339 if (self.nag_max and
340 int('%.0f' % (elapsed / self.nag_timer)) >= self.nag_max):
341 queue.put('timeout')
342 done.set() # Must do this so that timeout thread stops waiting.
343 nag = NagTimer(self.nag_timer, _nag_cb)
344 nag.start()
[email protected]e0558e62013-05-02 02:48:51345
[email protected]94c712f2011-12-01 15:04:57346 timed_out = False
347 try:
348 # This thread needs to be optimized for speed.
349 while threads:
350 item = queue.get()
[email protected]cd8d8e12012-10-03 17:16:25351 if item[0] == 'stdout':
[email protected]94c712f2011-12-01 15:04:57352 self.stdout_cb(item[1])
[email protected]cd8d8e12012-10-03 17:16:25353 elif item[0] == 'stderr':
[email protected]94c712f2011-12-01 15:04:57354 self.stderr_cb(item[1])
355 else:
356 # A thread terminated.
[email protected]12b07e72013-05-03 22:06:34357 if item in threads:
358 threads[item].join()
359 del threads[item]
[email protected]94c712f2011-12-01 15:04:57360 if item == 'wait':
361 # Terminate the timeout thread if necessary.
362 done.set()
363 elif item == 'timeout' and not timed_out and self.poll() is None:
[email protected]12b07e72013-05-03 22:06:34364 logging.debug('Timed out after %.0fs: killing' % (
365 time.time() - self.start))
[email protected]94c712f2011-12-01 15:04:57366 self.kill()
367 timed_out = True
368 finally:
369 # Stop the threads.
370 done.set()
[email protected]12b07e72013-05-03 22:06:34371 if nag:
372 nag.cancel()
[email protected]94c712f2011-12-01 15:04:57373 if 'wait' in threads:
374 # Accelerate things, otherwise it would hang until the child process is
375 # done.
376 logging.debug('Killing child because of an exception')
377 self.kill()
378 # Join threads.
379 for thread in threads.itervalues():
380 thread.join()
381 if timed_out:
382 self.returncode = TIMED_OUT
383
[email protected]e0558e62013-05-02 02:48:51384 # pylint: disable=W0221,W0622
[email protected]12b07e72013-05-03 22:06:34385 def communicate(self, input=None, timeout=None, nag_timer=None,
386 nag_max=None):
[email protected]94c712f2011-12-01 15:04:57387 """Adds timeout and callbacks support.
388
389 Returns (stdout, stderr) like subprocess.Popen().communicate().
390
391 - The process will be killed after |timeout| seconds and returncode set to
392 TIMED_OUT.
[email protected]e0558e62013-05-02 02:48:51393 - If the subprocess runs for |nag_timer| seconds without producing terminal
394 output, print a warning to stderr.
[email protected]94c712f2011-12-01 15:04:57395 """
396 self.timeout = timeout
[email protected]e0558e62013-05-02 02:48:51397 self.nag_timer = nag_timer
[email protected]12b07e72013-05-03 22:06:34398 self.nag_max = nag_max
[email protected]e0558e62013-05-02 02:48:51399 if (not self.timeout and not self.nag_timer and
400 not self.stdout_cb and not self.stderr_cb):
[email protected]94c712f2011-12-01 15:04:57401 return super(Popen, self).communicate(input)
402
403 if self.timeout and self.shell:
404 raise TypeError(
405 'Using timeout and shell simultaneously will cause a process leak '
406 'since the shell will be killed instead of the child process.')
407
408 stdout = None
409 stderr = None
410 # Convert to a lambda to workaround python's deadlock.
411 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
[email protected]740a6c02011-12-05 23:46:44412 # When the pipe fills up, it would deadlock this process.
413 if self.stdout and not self.stdout_cb and not self.stdout_is_void:
414 stdout = []
415 self.stdout_cb = stdout.append
416 if self.stderr and not self.stderr_cb and not self.stderr_is_void:
417 stderr = []
418 self.stderr_cb = stderr.append
[email protected]94c712f2011-12-01 15:04:57419 self._tee_threads(input)
[email protected]740a6c02011-12-05 23:46:44420 if stdout is not None:
421 stdout = ''.join(stdout)
[email protected]740a6c02011-12-05 23:46:44422 if stderr is not None:
423 stderr = ''.join(stderr)
[email protected]94c712f2011-12-01 15:04:57424 return (stdout, stderr)
425
[email protected]4860f052011-03-25 20:34:38426
[email protected]12b07e72013-05-03 22:06:34427def communicate(args, timeout=None, nag_timer=None, nag_max=None, **kwargs):
[email protected]dd9837f2011-11-30 01:55:22428 """Wraps subprocess.Popen().communicate() and add timeout support.
[email protected]4860f052011-03-25 20:34:38429
[email protected]421982f2011-04-01 17:38:06430 Returns ((stdout, stderr), returncode).
[email protected]4860f052011-03-25 20:34:38431
[email protected]1d9f6292011-04-07 14:15:36432 - The process will be killed after |timeout| seconds and returncode set to
433 TIMED_OUT.
[email protected]e0558e62013-05-02 02:48:51434 - If the subprocess runs for |nag_timer| seconds without producing terminal
435 output, print a warning to stderr.
[email protected]421982f2011-04-01 17:38:06436 - Automatically passes stdin content as input so do not specify stdin=PIPE.
[email protected]4860f052011-03-25 20:34:38437 """
438 stdin = kwargs.pop('stdin', None)
439 if stdin is not None:
[email protected]740a6c02011-12-05 23:46:44440 if isinstance(stdin, basestring):
[email protected]0d5ef242011-04-18 13:52:58441 # When stdin is passed as an argument, use it as the actual input data and
442 # set the Popen() parameter accordingly.
443 kwargs['stdin'] = PIPE
[email protected]740a6c02011-12-05 23:46:44444 else:
445 kwargs['stdin'] = stdin
446 stdin = None
[email protected]4860f052011-03-25 20:34:38447
[email protected]94c712f2011-12-01 15:04:57448 proc = Popen(args, **kwargs)
[email protected]740a6c02011-12-05 23:46:44449 if stdin:
[email protected]e0558e62013-05-02 02:48:51450 return proc.communicate(stdin, timeout, nag_timer), proc.returncode
[email protected]94c712f2011-12-01 15:04:57451 else:
[email protected]e0558e62013-05-02 02:48:51452 return proc.communicate(None, timeout, nag_timer), proc.returncode
[email protected]4860f052011-03-25 20:34:38453
454
[email protected]1f063db2011-04-18 19:04:52455def call(args, **kwargs):
456 """Emulates subprocess.call().
457
458 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
[email protected]87e6d332011-09-09 19:01:28459 In no case they can be returned since no code path raises
460 subprocess2.CalledProcessError.
[email protected]1f063db2011-04-18 19:04:52461 """
462 if kwargs.get('stdout') == PIPE:
463 kwargs['stdout'] = VOID
464 if kwargs.get('stderr') == PIPE:
465 kwargs['stderr'] = VOID
466 return communicate(args, **kwargs)[1]
467
468
[email protected]0bcd1d32011-04-26 15:55:49469def check_call_out(args, **kwargs):
[email protected]421982f2011-04-01 17:38:06470 """Improved version of subprocess.check_call().
[email protected]4860f052011-03-25 20:34:38471
[email protected]421982f2011-04-01 17:38:06472 Returns (stdout, stderr), unlike subprocess.check_call().
[email protected]4860f052011-03-25 20:34:38473 """
[email protected]1f063db2011-04-18 19:04:52474 out, returncode = communicate(args, **kwargs)
[email protected]4860f052011-03-25 20:34:38475 if returncode:
476 raise CalledProcessError(
477 returncode, args, kwargs.get('cwd'), out[0], out[1])
478 return out
479
480
[email protected]0bcd1d32011-04-26 15:55:49481def check_call(args, **kwargs):
482 """Emulate subprocess.check_call()."""
483 check_call_out(args, **kwargs)
484 return 0
485
486
[email protected]4860f052011-03-25 20:34:38487def capture(args, **kwargs):
488 """Captures stdout of a process call and returns it.
489
[email protected]421982f2011-04-01 17:38:06490 Returns stdout.
[email protected]4860f052011-03-25 20:34:38491
[email protected]421982f2011-04-01 17:38:06492 - Discards returncode.
[email protected]87e6d332011-09-09 19:01:28493 - Blocks stdin by default if not specified since no output will be visible.
[email protected]4860f052011-03-25 20:34:38494 """
[email protected]87e6d332011-09-09 19:01:28495 kwargs.setdefault('stdin', VOID)
496
497 # Like check_output, deny the caller from using stdout arg.
498 return communicate(args, stdout=PIPE, **kwargs)[0][0]
[email protected]4860f052011-03-25 20:34:38499
500
501def check_output(args, **kwargs):
[email protected]0bcd1d32011-04-26 15:55:49502 """Emulates subprocess.check_output().
[email protected]4860f052011-03-25 20:34:38503
[email protected]0bcd1d32011-04-26 15:55:49504 Captures stdout of a process call and returns stdout only.
[email protected]4860f052011-03-25 20:34:38505
[email protected]421982f2011-04-01 17:38:06506 - Throws if return code is not 0.
507 - Works even prior to python 2.7.
[email protected]87e6d332011-09-09 19:01:28508 - Blocks stdin by default if not specified since no output will be visible.
509 - As per doc, "The stdout argument is not allowed as it is used internally."
[email protected]4860f052011-03-25 20:34:38510 """
[email protected]87e6d332011-09-09 19:01:28511 kwargs.setdefault('stdin', VOID)
[email protected]db59bfc2011-11-30 14:03:14512 if 'stdout' in kwargs:
513 raise ValueError('stdout argument not allowed, it will be overridden.')
[email protected]87e6d332011-09-09 19:01:28514 return check_call_out(args, stdout=PIPE, **kwargs)[0]