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): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 20 | if not isinstance(self.command, str): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 97 | def read_all_pipes(log, rin, outdata, errdata): |
| 98 | rlist = rin |
| 99 | stdoutbuf = b"" |
| 100 | stderrbuf = b"" |
| 101 | |
| 102 | try: |
| 103 | r,w,e = select.select (rlist, [], [], 1) |
| 104 | except OSError as e: |
| 105 | if e.errno != errno.EINTR: |
| 106 | raise |
| 107 | |
| 108 | readextras(r) |
| 109 | |
| 110 | if pipe.stdout in r: |
| 111 | data = stdoutbuf + pipe.stdout.read() |
| 112 | if data is not None and len(data) > 0: |
| 113 | try: |
| 114 | data = data.decode("utf-8") |
| 115 | outdata.append(data) |
| 116 | log.write(data) |
| 117 | log.flush() |
| 118 | stdoutbuf = b"" |
| 119 | except UnicodeDecodeError: |
| 120 | stdoutbuf = data |
| 121 | |
| 122 | if pipe.stderr in r: |
| 123 | data = stderrbuf + pipe.stderr.read() |
| 124 | if data is not None and len(data) > 0: |
| 125 | try: |
| 126 | data = data.decode("utf-8") |
| 127 | errdata.append(data) |
| 128 | log.write(data) |
| 129 | log.flush() |
| 130 | stderrbuf = b"" |
| 131 | except UnicodeDecodeError: |
| 132 | stderrbuf = data |
| 133 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 134 | try: |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 135 | # Read all pipes while the process is open |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 136 | while pipe.poll() is None: |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 137 | read_all_pipes(log, rin, outdata, errdata) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 138 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 139 | # Pocess closed, drain all pipes... |
| 140 | read_all_pipes(log, rin, outdata, errdata) |
| 141 | finally: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 142 | log.flush() |
| 143 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 144 | if pipe.stdout is not None: |
| 145 | pipe.stdout.close() |
| 146 | if pipe.stderr is not None: |
| 147 | pipe.stderr.close() |
| 148 | return ''.join(outdata), ''.join(errdata) |
| 149 | |
| 150 | def run(cmd, input=None, log=None, extrafiles=None, **options): |
| 151 | """Convenience function to run a command and return its output, raising an |
| 152 | exception when the command fails""" |
| 153 | |
| 154 | if not extrafiles: |
| 155 | extrafiles = [] |
| 156 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 157 | if isinstance(cmd, str) and not "shell" in options: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 158 | options["shell"] = True |
| 159 | |
| 160 | try: |
| 161 | pipe = Popen(cmd, **options) |
| 162 | except OSError as exc: |
| 163 | if exc.errno == 2: |
| 164 | raise NotFoundError(cmd) |
| 165 | else: |
| 166 | raise CmdError(cmd, exc) |
| 167 | |
| 168 | if log: |
| 169 | stdout, stderr = _logged_communicate(pipe, log, input, extrafiles) |
| 170 | else: |
| 171 | stdout, stderr = pipe.communicate(input) |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 172 | if not stdout is None: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 173 | stdout = stdout.decode("utf-8") |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 174 | if not stderr is None: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 175 | stderr = stderr.decode("utf-8") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 176 | |
| 177 | if pipe.returncode != 0: |
| 178 | raise ExecutionError(cmd, pipe.returncode, stdout, stderr) |
| 179 | return stdout, stderr |