Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | import logging |
| 2 | import signal |
| 3 | import subprocess |
| 4 | import errno |
| 5 | import select |
| 6 | |
| 7 | logger = logging.getLogger('BitBake.Process') |
| 8 | |
| 9 | def subprocess_setup(): |
| 10 | # Python installs a SIGPIPE handler by default. This is usually not what |
| 11 | # non-Python subprocesses expect. |
| 12 | signal.signal(signal.SIGPIPE, signal.SIG_DFL) |
| 13 | |
| 14 | class CmdError(RuntimeError): |
| 15 | def __init__(self, command, msg=None): |
| 16 | self.command = command |
| 17 | self.msg = msg |
| 18 | |
| 19 | def __str__(self): |
| 20 | if not isinstance(self.command, basestring): |
| 21 | cmd = subprocess.list2cmdline(self.command) |
| 22 | else: |
| 23 | cmd = self.command |
| 24 | |
| 25 | msg = "Execution of '%s' failed" % cmd |
| 26 | if self.msg: |
| 27 | msg += ': %s' % self.msg |
| 28 | return msg |
| 29 | |
| 30 | class NotFoundError(CmdError): |
| 31 | def __str__(self): |
| 32 | return CmdError.__str__(self) + ": command not found" |
| 33 | |
| 34 | class ExecutionError(CmdError): |
| 35 | def __init__(self, command, exitcode, stdout = None, stderr = None): |
| 36 | CmdError.__init__(self, command) |
| 37 | self.exitcode = exitcode |
| 38 | self.stdout = stdout |
| 39 | self.stderr = stderr |
| 40 | |
| 41 | def __str__(self): |
| 42 | message = "" |
| 43 | if self.stderr: |
| 44 | message += self.stderr |
| 45 | if self.stdout: |
| 46 | message += self.stdout |
| 47 | if message: |
| 48 | message = ":\n" + message |
| 49 | return (CmdError.__str__(self) + |
| 50 | " with exit code %s" % self.exitcode + message) |
| 51 | |
| 52 | class Popen(subprocess.Popen): |
| 53 | defaults = { |
| 54 | "close_fds": True, |
| 55 | "preexec_fn": subprocess_setup, |
| 56 | "stdout": subprocess.PIPE, |
| 57 | "stderr": subprocess.STDOUT, |
| 58 | "stdin": subprocess.PIPE, |
| 59 | "shell": False, |
| 60 | } |
| 61 | |
| 62 | def __init__(self, *args, **kwargs): |
| 63 | options = dict(self.defaults) |
| 64 | options.update(kwargs) |
| 65 | subprocess.Popen.__init__(self, *args, **options) |
| 66 | |
| 67 | def _logged_communicate(pipe, log, input, extrafiles): |
| 68 | if pipe.stdin: |
| 69 | if input is not None: |
| 70 | pipe.stdin.write(input) |
| 71 | pipe.stdin.close() |
| 72 | |
| 73 | outdata, errdata = [], [] |
| 74 | rin = [] |
| 75 | |
| 76 | if pipe.stdout is not None: |
| 77 | bb.utils.nonblockingfd(pipe.stdout.fileno()) |
| 78 | rin.append(pipe.stdout) |
| 79 | if pipe.stderr is not None: |
| 80 | bb.utils.nonblockingfd(pipe.stderr.fileno()) |
| 81 | rin.append(pipe.stderr) |
| 82 | for fobj, _ in extrafiles: |
| 83 | bb.utils.nonblockingfd(fobj.fileno()) |
| 84 | rin.append(fobj) |
| 85 | |
| 86 | def readextras(selected): |
| 87 | for fobj, func in extrafiles: |
| 88 | if fobj in selected: |
| 89 | try: |
| 90 | data = fobj.read() |
| 91 | except IOError as err: |
| 92 | if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK: |
| 93 | data = None |
| 94 | if data is not None: |
| 95 | func(data) |
| 96 | |
| 97 | try: |
| 98 | while pipe.poll() is None: |
| 99 | rlist = rin |
| 100 | try: |
| 101 | r,w,e = select.select (rlist, [], [], 1) |
| 102 | except OSError as e: |
| 103 | if e.errno != errno.EINTR: |
| 104 | raise |
| 105 | |
| 106 | if pipe.stdout in r: |
| 107 | data = pipe.stdout.read() |
| 108 | if data is not None: |
| 109 | outdata.append(data) |
| 110 | log.write(data) |
| 111 | |
| 112 | if pipe.stderr in r: |
| 113 | data = pipe.stderr.read() |
| 114 | if data is not None: |
| 115 | errdata.append(data) |
| 116 | log.write(data) |
| 117 | |
| 118 | readextras(r) |
| 119 | |
| 120 | finally: |
| 121 | log.flush() |
| 122 | |
| 123 | readextras([fobj for fobj, _ in extrafiles]) |
| 124 | |
| 125 | if pipe.stdout is not None: |
| 126 | pipe.stdout.close() |
| 127 | if pipe.stderr is not None: |
| 128 | pipe.stderr.close() |
| 129 | return ''.join(outdata), ''.join(errdata) |
| 130 | |
| 131 | def run(cmd, input=None, log=None, extrafiles=None, **options): |
| 132 | """Convenience function to run a command and return its output, raising an |
| 133 | exception when the command fails""" |
| 134 | |
| 135 | if not extrafiles: |
| 136 | extrafiles = [] |
| 137 | |
| 138 | if isinstance(cmd, basestring) and not "shell" in options: |
| 139 | options["shell"] = True |
| 140 | |
| 141 | try: |
| 142 | pipe = Popen(cmd, **options) |
| 143 | except OSError as exc: |
| 144 | if exc.errno == 2: |
| 145 | raise NotFoundError(cmd) |
| 146 | else: |
| 147 | raise CmdError(cmd, exc) |
| 148 | |
| 149 | if log: |
| 150 | stdout, stderr = _logged_communicate(pipe, log, input, extrafiles) |
| 151 | else: |
| 152 | stdout, stderr = pipe.communicate(input) |
| 153 | |
| 154 | if pipe.returncode != 0: |
| 155 | raise ExecutionError(cmd, pipe.returncode, stdout, stderr) |
| 156 | return stdout, stderr |