Debian Codegraph @

lib/ClusterShell/Worker/fastsubprocess.py

raw symbols SCIP
1 # fastsubprocess - POSIX relaxed revision of subprocess.py
2 # Based on Python 2.6.4 subprocess.py
3 # This is a performance oriented version of subprocess module.
4 # Modified by Stephane Thiell
5 # Changes:
6 # * removed Windows specific code parts
7 # * removed pipe for transferring possible exec failure from child to
8 # parent, to avoid os.read() blocking call after each fork.
9 # * child returns status code 255 on execv failure, which can be
10 # handled with Popen.wait().
11 # * removed file objects creation using costly fdopen(): this version
12 # returns non-blocking file descriptors bound to child
13 # * added module method set_nonblock_flag() and used it in Popen().
14 ##
15 # Original Disclaimer:
16 #
17 # For more information about this module, see PEP 324.
18 #
19 # This module should remain compatible with Python 2.2, see PEP 291.
20 #
21 # Copyright (c) 2003-2005 by Peter Astrand <[email protected]>
22 #
23 # Licensed to PSF under a Contributor Agreement.
24 # See http://www.python.org/2.4/license for licensing details.
25
26 """_subprocess - Subprocesses with accessible I/O non-blocking file
27 descriptors
28
29 Faster revision of subprocess-like module.
30 """
31
32 import gc
33 import os
34 import signal
35 import sys
36 import types
37
38 # Python 3 compatibility
39 try:
40 basestring
41 except NameError:
42 basestring = str
43
44 # Exception classes used by this module.
45 class CalledProcessError(Exception):
46 """This exception is raised when a process run by check_call() returns
47 a non-zero exit status. The exit status will be stored in the
48 returncode attribute."""
49 def __init__(self, returncode, cmd):
50 self.returncode = returncode
51 self.cmd = cmd
52 def __str__(self):
53 return "Command '%s' returned non-zero exit status %d" % (self.cmd,
54 self.returncode)
55
56 import select
57 import errno
58 import fcntl
59
60 __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", \
61 "CalledProcessError"]
62
63 try:
64 MAXFD = os.sysconf("SC_OPEN_MAX")
65 except:
66 MAXFD = 256
67
68 _active = []
69
70 def _cleanup():
71 for inst in _active[:]:
72 if inst._internal_poll(_deadstate=sys.maxsize) >= 0:
73 try:
74 _active.remove(inst)
75 except ValueError:
76 # This can happen if two threads create a new Popen instance.
77 # It's harmless that it was already removed, so ignore.
78 pass
79
80 PIPE = -1
81 STDOUT = -2
82
83
84 def call(*popenargs, **kwargs):
85 """Run command with arguments. Wait for command to complete, then
86 return the returncode attribute.
87
88 The arguments are the same as for the Popen constructor. Example:
89
90 retcode = call(["ls", "-l"])
91 """
92 return Popen(*popenargs, **kwargs).wait()
93
94
95 def check_call(*popenargs, **kwargs):
96 """Run command with arguments. Wait for command to complete. If
97 the exit code was zero then return, otherwise raise
98 CalledProcessError. The CalledProcessError object will have the
99 return code in the returncode attribute.
100
101 The arguments are the same as for the Popen constructor. Example:
102
103 check_call(["ls", "-l"])
104 """
105 retcode = call(*popenargs, **kwargs)
106 cmd = kwargs.get("args")
107 if cmd is None:
108 cmd = popenargs[0]
109 if retcode:
110 raise CalledProcessError(retcode, cmd)
111 return retcode
112
113
114 def set_nonblock_flag(fd):
115 """Set non blocking flag to file descriptor fd"""
116 old = fcntl.fcntl(fd, fcntl.F_GETFL)
117 fcntl.fcntl(fd, fcntl.F_SETFL, old | os.O_NDELAY)
118
119
120 class Popen(object):
121 """A faster Popen"""
122 def __init__(self, args, bufsize=0, executable=None,
123 stdin=None, stdout=None, stderr=None,
124 preexec_fn=None, shell=False,
125 cwd=None, env=None, universal_newlines=False):
126 """Create new Popen instance."""
127 _cleanup()
128
129 self._child_created = False
130 if not isinstance(bufsize, int):
131 raise TypeError("bufsize must be an integer")
132
133 self.pid = None
134 self.returncode = None
135 self.universal_newlines = universal_newlines
136
137 # Input and output objects. The general principle is like
138 # this:
139 #
140 # Parent Child
141 # ------ -----
142 # p2cwrite ---stdin---> p2cread
143 # c2pread <--stdout--- c2pwrite
144 # errread <--stderr--- errwrite
145 #
146 # On POSIX, the child objects are file descriptors. On
147 # Windows, these are Windows file handles. The parent objects
148 # are file descriptors on both platforms. The parent objects
149 # are None when not using PIPEs. The child objects are None
150 # when not redirecting.
151
152 (p2cread, p2cwrite,
153 c2pread, c2pwrite,
154 errread, errwrite) = self._get_handles(stdin, stdout, stderr)
155
156 self._execute_child(args, executable, preexec_fn,
157 cwd, env, universal_newlines, shell,
158 p2cread, p2cwrite,
159 c2pread, c2pwrite,
160 errread, errwrite)
161
162 if p2cwrite is not None:
163 set_nonblock_flag(p2cwrite)
164 self.stdin = p2cwrite
165 if c2pread is not None:
166 set_nonblock_flag(c2pread)
167 self.stdout = c2pread
168 if errread is not None:
169 set_nonblock_flag(errread)
170 self.stderr = errread
171
172
173 def _translate_newlines(self, data):
174 data = data.replace("\r\n", "\n")
175 data = data.replace("\r", "\n")
176 return data
177
178
179 def __del__(self, sys=sys):
180 if not self._child_created:
181 # We didn't get to successfully create a child process.
182 return
183 # In case the child hasn't been waited on, check if it's done.
184 self._internal_poll(_deadstate=sys.maxsize)
185 if self.returncode is None and _active is not None:
186 # Child is still running, keep us alive until we can wait on it.
187 _active.append(self)
188
189
190 def communicate(self, input=None):
191 """Interact with process: Send data to stdin. Read data from
192 stdout and stderr, until end-of-file is reached. Wait for
193 process to terminate. The optional input argument should be a
194 string to be sent to the child process, or None, if no data
195 should be sent to the child.
196
197 communicate() returns a tuple (stdout, stderr)."""
198
199 # Optimization: If we are only using one pipe, or no pipe at
200 # all, using select() or threads is unnecessary.
201 if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
202 stdout = None
203 stderr = None
204 if self.stdin:
205 if input:
206 self.stdin.write(input)
207 self.stdin.close()
208 elif self.stdout:
209 stdout = self.stdout.read()
210 self.stdout.close()
211 elif self.stderr:
212 stderr = self.stderr.read()
213 self.stderr.close()
214 self.wait()
215 return (stdout, stderr)
216
217 return self._communicate(input)
218
219
220 def poll(self):
221 return self._internal_poll()
222
223
224 def _get_handles(self, stdin, stdout, stderr):
225 """Construct and return tuple with IO objects:
226 p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
227 """
228 p2cread, p2cwrite = None, None
229 c2pread, c2pwrite = None, None
230 errread, errwrite = None, None
231
232 if stdin is None:
233 pass
234 elif stdin == PIPE:
235 p2cread, p2cwrite = os.pipe()
236 elif isinstance(stdin, int):
237 p2cread = stdin
238 else:
239 # Assuming file-like object
240 p2cread = stdin.fileno()
241
242 if stdout is None:
243 pass
244 elif stdout == PIPE:
245 try:
246 c2pread, c2pwrite = os.pipe()
247 except:
248 # Cleanup of previous pipe() descriptors
249 if stdin == PIPE:
250 os.close(p2cread)
251 os.close(p2cwrite)
252 raise
253 elif isinstance(stdout, int):
254 c2pwrite = stdout
255 else:
256 # Assuming file-like object
257 c2pwrite = stdout.fileno()
258
259 if stderr is None:
260 pass
261 elif stderr == PIPE:
262 try:
263 errread, errwrite = os.pipe()
264 except:
265 # Cleanup of previous pipe() descriptors
266 if stdin == PIPE:
267 os.close(p2cread)
268 os.close(p2cwrite)
269 if stdout == PIPE:
270 os.close(c2pread)
271 os.close(c2pwrite)
272 raise
273 elif stderr == STDOUT:
274 errwrite = c2pwrite
275 elif isinstance(stderr, int):
276 errwrite = stderr
277 else:
278 # Assuming file-like object
279 errwrite = stderr.fileno()
280
281 return (p2cread, p2cwrite,
282 c2pread, c2pwrite,
283 errread, errwrite)
284
285
286 def _execute_child(self, args, executable, preexec_fn,
287 cwd, env, universal_newlines, shell,
288 p2cread, p2cwrite,
289 c2pread, c2pwrite,
290 errread, errwrite):
291 """Execute program (POSIX version)"""
292
293 if isinstance(args, basestring):
294 args = [args]
295 else:
296 args = list(args)
297
298 if shell:
299 args = ["/bin/sh", "-c"] + args
300
301 if executable is None:
302 executable = args[0]
303
304 gc_was_enabled = gc.isenabled()
305 # Disable gc to avoid bug where gc -> file_dealloc ->
306 # write to stderr -> hang. http://bugs.python.org/issue1336
307 gc.disable()
308 try:
309 self.pid = os.fork()
310 except:
311 if gc_was_enabled:
312 gc.enable()
313 raise
314 self._child_created = True
315 if self.pid == 0:
316 # Child
317 try:
318 # Close parent's pipe ends
319 if p2cwrite is not None:
320 os.close(p2cwrite)
321 if c2pread is not None:
322 os.close(c2pread)
323 if errread is not None:
324 os.close(errread)
325
326 # Dup fds for child
327 if p2cread is not None:
328 os.dup2(p2cread, 0)
329 if c2pwrite is not None:
330 os.dup2(c2pwrite, 1)
331 if errwrite is not None:
332 os.dup2(errwrite, 2)
333
334 # Close pipe fds. Make sure we don't close the same
335 # fd more than once, or standard fds.
336 if p2cread is not None and p2cread not in (0,):
337 os.close(p2cread)
338 if c2pwrite is not None and c2pwrite not in (p2cread, 1):
339 os.close(c2pwrite)
340 if errwrite is not None and errwrite not in \
341 (p2cread, c2pwrite, 2):
342 os.close(errwrite)
343
344 if cwd is not None:
345 os.chdir(cwd)
346
347 if preexec_fn:
348 preexec_fn()
349
350 if env is None:
351 os.execvp(executable, args)
352 else:
353 os.execvpe(executable, args, env)
354 except:
355 # Child execution failure
356 os._exit(255)
357
358 # Parent
359 if gc_was_enabled:
360 gc.enable()
361
362 if p2cread is not None and p2cwrite is not None:
363 os.close(p2cread)
364 if c2pwrite is not None and c2pread is not None:
365 os.close(c2pwrite)
366 if errwrite is not None and errread is not None:
367 os.close(errwrite)
368
369
370 def _handle_exitstatus(self, sts):
371 if os.WIFSIGNALED(sts):
372 self.returncode = -os.WTERMSIG(sts)
373 elif os.WIFEXITED(sts):
374 self.returncode = os.WEXITSTATUS(sts)
375 else:
376 # Should never happen
377 raise RuntimeError("Unknown child exit status!")
378
379
380 def _internal_poll(self, _deadstate=None):
381 """Check if child process has terminated. Returns returncode
382 attribute."""
383 if self.returncode is None:
384 try:
385 pid, sts = os.waitpid(self.pid, os.WNOHANG)
386 if pid == self.pid:
387 self._handle_exitstatus(sts)
388 except os.error:
389 if _deadstate is not None:
390 self.returncode = _deadstate
391 return self.returncode
392
393
394 def wait(self):
395 """Wait for child process to terminate. Returns returncode
396 attribute."""
397 if self.returncode is None:
398 pid, sts = os.waitpid(self.pid, 0)
399 self._handle_exitstatus(sts)
400 return self.returncode
401
402
403 def _communicate(self, input):
404 read_set = []
405 write_set = []
406 stdout = None # Return
407 stderr = None # Return
408
409 if self.stdin:
410 # Flush stdio buffer. This might block, if the user has
411 # been writing to .stdin in an uncontrolled fashion.
412 self.stdin.flush()
413 if input:
414 write_set.append(self.stdin)
415 else:
416 self.stdin.close()
417 if self.stdout:
418 read_set.append(self.stdout)
419 stdout = []
420 if self.stderr:
421 read_set.append(self.stderr)
422 stderr = []
423
424 input_offset = 0
425 while read_set or write_set:
426 try:
427 rlist, wlist, xlist = select.select(read_set, write_set, [])
428 except select.error as ex:
429 if ex.args[0] == errno.EINTR:
430 continue
431 raise
432
433 if self.stdin in wlist:
434 # When select has indicated that the file is writable,
435 # we can write up to PIPE_BUF bytes without risk
436 # blocking. POSIX defines PIPE_BUF >= 512
437 chunk = input[input_offset : input_offset + 512]
438 bytes_written = os.write(self.stdin.fileno(), chunk)
439 input_offset += bytes_written
440 if input_offset >= len(input):
441 self.stdin.close()
442 write_set.remove(self.stdin)
443
444 if self.stdout in rlist:
445 data = os.read(self.stdout.fileno(), 1024)
446 if data == "":
447 self.stdout.close()
448 read_set.remove(self.stdout)
449 stdout.append(data)
450
451 if self.stderr in rlist:
452 data = os.read(self.stderr.fileno(), 1024)
453 if data == "":
454 self.stderr.close()
455 read_set.remove(self.stderr)
456 stderr.append(data)
457
458 # All data exchanged. Translate lists into strings.
459 if stdout is not None:
460 stdout = ''.join(stdout)
461 if stderr is not None:
462 stderr = ''.join(stderr)
463
464 # Translate newlines, if requested. We cannot let the file
465 # object do the translation: It is based on stdio, which is
466 # impossible to combine with select (unless forcing no
467 # buffering).
468 if self.universal_newlines and hasattr(file, 'newlines'):
469 if stdout:
470 stdout = self._translate_newlines(stdout)
471 if stderr:
472 stderr = self._translate_newlines(stderr)
473
474 self.wait()
475 return (stdout, stderr)
476
477 def send_signal(self, sig):
478 """Send a signal to the process
479 """
480 os.kill(self.pid, sig)
481
482 def terminate(self):
483 """Terminate the process with SIGTERM
484 """
485 self.send_signal(signal.SIGTERM)
486
487 def kill(self):
488 """Kill the process with SIGKILL
489 """
490 self.send_signal(signal.SIGKILL)
491