blob: 2dc472a86fa8b8979da217a888eaf99d08605eec [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
Patrick Williamsc124f4f2015-09-15 14:41:29 -05005import logging
6import signal
7import subprocess
8import errno
9import select
10
11logger = logging.getLogger('BitBake.Process')
12
13def subprocess_setup():
14 # Python installs a SIGPIPE handler by default. This is usually not what
15 # non-Python subprocesses expect.
16 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
17
18class CmdError(RuntimeError):
19 def __init__(self, command, msg=None):
20 self.command = command
21 self.msg = msg
22
23 def __str__(self):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060024 if not isinstance(self.command, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025 cmd = subprocess.list2cmdline(self.command)
26 else:
27 cmd = self.command
28
29 msg = "Execution of '%s' failed" % cmd
30 if self.msg:
31 msg += ': %s' % self.msg
32 return msg
33
34class NotFoundError(CmdError):
35 def __str__(self):
36 return CmdError.__str__(self) + ": command not found"
37
38class ExecutionError(CmdError):
39 def __init__(self, command, exitcode, stdout = None, stderr = None):
40 CmdError.__init__(self, command)
41 self.exitcode = exitcode
42 self.stdout = stdout
43 self.stderr = stderr
44
45 def __str__(self):
46 message = ""
47 if self.stderr:
48 message += self.stderr
49 if self.stdout:
50 message += self.stdout
51 if message:
52 message = ":\n" + message
53 return (CmdError.__str__(self) +
54 " with exit code %s" % self.exitcode + message)
55
56class Popen(subprocess.Popen):
57 defaults = {
58 "close_fds": True,
59 "preexec_fn": subprocess_setup,
60 "stdout": subprocess.PIPE,
61 "stderr": subprocess.STDOUT,
62 "stdin": subprocess.PIPE,
63 "shell": False,
64 }
65
66 def __init__(self, *args, **kwargs):
67 options = dict(self.defaults)
68 options.update(kwargs)
69 subprocess.Popen.__init__(self, *args, **options)
70
71def _logged_communicate(pipe, log, input, extrafiles):
72 if pipe.stdin:
73 if input is not None:
74 pipe.stdin.write(input)
75 pipe.stdin.close()
76
77 outdata, errdata = [], []
78 rin = []
79
80 if pipe.stdout is not None:
81 bb.utils.nonblockingfd(pipe.stdout.fileno())
82 rin.append(pipe.stdout)
83 if pipe.stderr is not None:
84 bb.utils.nonblockingfd(pipe.stderr.fileno())
85 rin.append(pipe.stderr)
86 for fobj, _ in extrafiles:
87 bb.utils.nonblockingfd(fobj.fileno())
88 rin.append(fobj)
89
90 def readextras(selected):
91 for fobj, func in extrafiles:
92 if fobj in selected:
93 try:
94 data = fobj.read()
95 except IOError as err:
96 if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
97 data = None
98 if data is not None:
99 func(data)
100
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500101 def read_all_pipes(log, rin, outdata, errdata):
102 rlist = rin
103 stdoutbuf = b""
104 stderrbuf = b""
105
106 try:
107 r,w,e = select.select (rlist, [], [], 1)
108 except OSError as e:
109 if e.errno != errno.EINTR:
110 raise
111
112 readextras(r)
113
114 if pipe.stdout in r:
115 data = stdoutbuf + pipe.stdout.read()
116 if data is not None and len(data) > 0:
117 try:
118 data = data.decode("utf-8")
119 outdata.append(data)
120 log.write(data)
121 log.flush()
122 stdoutbuf = b""
123 except UnicodeDecodeError:
124 stdoutbuf = data
125
126 if pipe.stderr in r:
127 data = stderrbuf + pipe.stderr.read()
128 if data is not None and len(data) > 0:
129 try:
130 data = data.decode("utf-8")
131 errdata.append(data)
132 log.write(data)
133 log.flush()
134 stderrbuf = b""
135 except UnicodeDecodeError:
136 stderrbuf = data
137
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500138 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500139 # Read all pipes while the process is open
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500140 while pipe.poll() is None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500141 read_all_pipes(log, rin, outdata, errdata)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500142
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500143 # Pocess closed, drain all pipes...
144 read_all_pipes(log, rin, outdata, errdata)
145 finally:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500146 log.flush()
147
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500148 if pipe.stdout is not None:
149 pipe.stdout.close()
150 if pipe.stderr is not None:
151 pipe.stderr.close()
152 return ''.join(outdata), ''.join(errdata)
153
154def run(cmd, input=None, log=None, extrafiles=None, **options):
155 """Convenience function to run a command and return its output, raising an
156 exception when the command fails"""
157
158 if not extrafiles:
159 extrafiles = []
160
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600161 if isinstance(cmd, str) and not "shell" in options:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500162 options["shell"] = True
163
164 try:
165 pipe = Popen(cmd, **options)
166 except OSError as exc:
167 if exc.errno == 2:
168 raise NotFoundError(cmd)
169 else:
170 raise CmdError(cmd, exc)
171
172 if log:
173 stdout, stderr = _logged_communicate(pipe, log, input, extrafiles)
174 else:
175 stdout, stderr = pipe.communicate(input)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500176 if not stdout is None:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600177 stdout = stdout.decode("utf-8")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500178 if not stderr is None:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600179 stderr = stderr.decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180
181 if pipe.returncode != 0:
182 raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
183 return stdout, stderr