blob: e69697cb68b45cc4409367930acdf53bc58d9695 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001import logging
2import signal
3import subprocess
4import errno
5import select
6
7logger = logging.getLogger('BitBake.Process')
8
9def 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
14class CmdError(RuntimeError):
15 def __init__(self, command, msg=None):
16 self.command = command
17 self.msg = msg
18
19 def __str__(self):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060020 if not isinstance(self.command, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050021 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
30class NotFoundError(CmdError):
31 def __str__(self):
32 return CmdError.__str__(self) + ": command not found"
33
34class 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
52class 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
67def _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 Bishopd7bf8c12018-02-25 22:55:05 -050097 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 Williamsc124f4f2015-09-15 14:41:29 -0500134 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500135 # Read all pipes while the process is open
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500136 while pipe.poll() is None:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500137 read_all_pipes(log, rin, outdata, errdata)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500138
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500139 # Pocess closed, drain all pipes...
140 read_all_pipes(log, rin, outdata, errdata)
141 finally:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500142 log.flush()
143
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500144 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
150def 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 Williamsc0f7c042017-02-23 20:41:17 -0600157 if isinstance(cmd, str) and not "shell" in options:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500158 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 Bishop6e60e8b2018-02-01 10:27:11 -0500172 if not stdout is None:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600173 stdout = stdout.decode("utf-8")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500174 if not stderr is None:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600175 stderr = stderr.decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500176
177 if pipe.returncode != 0:
178 raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
179 return stdout, stderr