blob: e34cb217e84a1995fcd30db2740e62ac3aa19448 [file] [log] [blame]
Stephen Warren10e50632016-01-15 11:15:24 -07001# SPDX-License-Identifier: GPL-2.0
Tom Rini10e47792018-05-06 17:58:06 -04002# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
Stephen Warren10e50632016-01-15 11:15:24 -07003
4# Logic to spawn a sub-process and interact with its stdio.
5
6import os
7import re
8import pty
9import signal
10import select
11import time
12
13class Timeout(Exception):
Stephen Warren75e731e2016-01-26 13:41:30 -070014 """An exception sub-class that indicates that a timeout occurred."""
Stephen Warren10e50632016-01-15 11:15:24 -070015 pass
16
17class Spawn(object):
Stephen Warren75e731e2016-01-26 13:41:30 -070018 """Represents the stdio of a freshly created sub-process. Commands may be
Stephen Warren10e50632016-01-15 11:15:24 -070019 sent to the process, and responses waited for.
Simon Glass9bc20832016-07-04 11:58:39 -060020
21 Members:
22 output: accumulated output from expect()
Stephen Warren75e731e2016-01-26 13:41:30 -070023 """
Stephen Warren10e50632016-01-15 11:15:24 -070024
Stephen Warrena85fce92016-01-27 23:57:53 -070025 def __init__(self, args, cwd=None):
Stephen Warren75e731e2016-01-26 13:41:30 -070026 """Spawn (fork/exec) the sub-process.
Stephen Warren10e50632016-01-15 11:15:24 -070027
28 Args:
Stephen Warrena85fce92016-01-27 23:57:53 -070029 args: array of processs arguments. argv[0] is the command to
30 execute.
31 cwd: the directory to run the process in, or None for no change.
Stephen Warren10e50632016-01-15 11:15:24 -070032
33 Returns:
34 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070035 """
Stephen Warren10e50632016-01-15 11:15:24 -070036
37 self.waited = False
Simon Glassafd00042021-10-08 09:15:23 -060038 self.exit_code = 0
39 self.exit_info = ''
Stephen Warren10e50632016-01-15 11:15:24 -070040 self.buf = ''
Simon Glass9bc20832016-07-04 11:58:39 -060041 self.output = ''
Stephen Warren10e50632016-01-15 11:15:24 -070042 self.logfile_read = None
43 self.before = ''
44 self.after = ''
45 self.timeout = None
Stephen Warren8e7c3ec2016-07-06 10:34:30 -060046 # http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
Tom Rini649bdaf2019-10-24 11:59:28 -040047 self.re_vt100 = re.compile(r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]', re.I)
Stephen Warren10e50632016-01-15 11:15:24 -070048
49 (self.pid, self.fd) = pty.fork()
50 if self.pid == 0:
51 try:
52 # For some reason, SIGHUP is set to SIG_IGN at this point when
53 # run under "go" (www.go.cd). Perhaps this happens under any
54 # background (non-interactive) system?
55 signal.signal(signal.SIGHUP, signal.SIG_DFL)
Stephen Warrena85fce92016-01-27 23:57:53 -070056 if cwd:
57 os.chdir(cwd)
Stephen Warren10e50632016-01-15 11:15:24 -070058 os.execvp(args[0], args)
59 except:
Paul Burton00f2d202017-09-14 14:34:43 -070060 print('CHILD EXECEPTION:')
Stephen Warren10e50632016-01-15 11:15:24 -070061 import traceback
62 traceback.print_exc()
63 finally:
64 os._exit(255)
65
Stephen Warren65503db2016-02-10 16:54:37 -070066 try:
67 self.poll = select.poll()
68 self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
69 except:
70 self.close()
71 raise
Stephen Warren10e50632016-01-15 11:15:24 -070072
73 def kill(self, sig):
Stephen Warren75e731e2016-01-26 13:41:30 -070074 """Send unix signal "sig" to the child process.
Stephen Warren10e50632016-01-15 11:15:24 -070075
76 Args:
77 sig: The signal number to send.
78
79 Returns:
80 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070081 """
Stephen Warren10e50632016-01-15 11:15:24 -070082
83 os.kill(self.pid, sig)
84
Simon Glassafd00042021-10-08 09:15:23 -060085 def checkalive(self):
Stephen Warren75e731e2016-01-26 13:41:30 -070086 """Determine whether the child process is still running.
Stephen Warren10e50632016-01-15 11:15:24 -070087
Stephen Warren10e50632016-01-15 11:15:24 -070088 Returns:
Simon Glassafd00042021-10-08 09:15:23 -060089 tuple:
90 True if process is alive, else False
91 0 if process is alive, else exit code of process
92 string describing what happened ('' or 'status/signal n')
Stephen Warren75e731e2016-01-26 13:41:30 -070093 """
Stephen Warren10e50632016-01-15 11:15:24 -070094
95 if self.waited:
Simon Glassafd00042021-10-08 09:15:23 -060096 return False, self.exit_code, self.exit_info
Stephen Warren10e50632016-01-15 11:15:24 -070097
98 w = os.waitpid(self.pid, os.WNOHANG)
99 if w[0] == 0:
Simon Glassafd00042021-10-08 09:15:23 -0600100 return True, 0, 'running'
101 status = w[1]
Stephen Warren10e50632016-01-15 11:15:24 -0700102
Simon Glassafd00042021-10-08 09:15:23 -0600103 if os.WIFEXITED(status):
104 self.exit_code = os.WEXITSTATUS(status)
105 self.exit_info = 'status %d' % self.exit_code
106 elif os.WIFSIGNALED(status):
107 signum = os.WTERMSIG(status)
108 self.exit_code = -signum
109 self.exit_info = 'signal %d (%s)' % (signum, signal.Signals(signum))
Stephen Warren10e50632016-01-15 11:15:24 -0700110 self.waited = True
Simon Glassafd00042021-10-08 09:15:23 -0600111 return False, self.exit_code, self.exit_info
112
113 def isalive(self):
114 """Determine whether the child process is still running.
115
116 Args:
117 None.
118
119 Returns:
120 Boolean indicating whether process is alive.
121 """
122 return self.checkalive()[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700123
124 def send(self, data):
Stephen Warren75e731e2016-01-26 13:41:30 -0700125 """Send data to the sub-process's stdin.
Stephen Warren10e50632016-01-15 11:15:24 -0700126
127 Args:
128 data: The data to send to the process.
129
130 Returns:
131 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700132 """
Stephen Warren10e50632016-01-15 11:15:24 -0700133
Tom Rini6a990412019-10-24 11:59:21 -0400134 os.write(self.fd, data.encode(errors='replace'))
Stephen Warren10e50632016-01-15 11:15:24 -0700135
136 def expect(self, patterns):
Stephen Warren75e731e2016-01-26 13:41:30 -0700137 """Wait for the sub-process to emit specific data.
Stephen Warren10e50632016-01-15 11:15:24 -0700138
139 This function waits for the process to emit one pattern from the
140 supplied list of patterns, or for a timeout to occur.
141
142 Args:
143 patterns: A list of strings or regex objects that we expect to
144 see in the sub-process' stdout.
145
146 Returns:
147 The index within the patterns array of the pattern the process
148 emitted.
149
150 Notable exceptions:
151 Timeout, if the process did not emit any of the patterns within
152 the expected time.
Stephen Warren75e731e2016-01-26 13:41:30 -0700153 """
Stephen Warren10e50632016-01-15 11:15:24 -0700154
Paul Burtond2849ed2017-09-14 14:34:44 -0700155 for pi in range(len(patterns)):
Stephen Warren10e50632016-01-15 11:15:24 -0700156 if type(patterns[pi]) == type(''):
157 patterns[pi] = re.compile(patterns[pi])
158
Stephen Warren22eba122016-01-22 12:30:07 -0700159 tstart_s = time.time()
Stephen Warren10e50632016-01-15 11:15:24 -0700160 try:
161 while True:
162 earliest_m = None
163 earliest_pi = None
Paul Burtond2849ed2017-09-14 14:34:44 -0700164 for pi in range(len(patterns)):
Stephen Warren10e50632016-01-15 11:15:24 -0700165 pattern = patterns[pi]
166 m = pattern.search(self.buf)
167 if not m:
168 continue
Stephen Warren3880dec2016-01-27 23:57:47 -0700169 if earliest_m and m.start() >= earliest_m.start():
Stephen Warren10e50632016-01-15 11:15:24 -0700170 continue
171 earliest_m = m
172 earliest_pi = pi
173 if earliest_m:
174 pos = earliest_m.start()
Stephen Warren4223a2f2016-02-05 18:04:42 -0700175 posafter = earliest_m.end()
Stephen Warren10e50632016-01-15 11:15:24 -0700176 self.before = self.buf[:pos]
177 self.after = self.buf[pos:posafter]
Simon Glass9bc20832016-07-04 11:58:39 -0600178 self.output += self.buf[:posafter]
Stephen Warren10e50632016-01-15 11:15:24 -0700179 self.buf = self.buf[posafter:]
180 return earliest_pi
Stephen Warren22eba122016-01-22 12:30:07 -0700181 tnow_s = time.time()
Stephen Warren33db1ee2016-02-04 16:11:50 -0700182 if self.timeout:
183 tdelta_ms = (tnow_s - tstart_s) * 1000
184 poll_maxwait = self.timeout - tdelta_ms
185 if tdelta_ms > self.timeout:
186 raise Timeout()
187 else:
188 poll_maxwait = None
189 events = self.poll.poll(poll_maxwait)
Stephen Warren10e50632016-01-15 11:15:24 -0700190 if not events:
191 raise Timeout()
Simon Glassafd00042021-10-08 09:15:23 -0600192 try:
193 c = os.read(self.fd, 1024).decode(errors='replace')
194 except OSError as err:
195 # With sandbox, try to detect when U-Boot exits when it
196 # shouldn't and explain why. This is much more friendly than
197 # just dying with an I/O error
198 if err.errno == 5: # Input/output error
199 alive, exit_code, info = self.checkalive()
200 if alive:
201 raise
202 else:
203 raise ValueError('U-Boot exited with %s' % info)
204 else:
205 raise
Stephen Warren10e50632016-01-15 11:15:24 -0700206 if self.logfile_read:
207 self.logfile_read.write(c)
208 self.buf += c
Stephen Warren8e7c3ec2016-07-06 10:34:30 -0600209 # count=0 is supposed to be the default, which indicates
210 # unlimited substitutions, but in practice the version of
211 # Python in Ubuntu 14.04 appears to default to count=2!
212 self.buf = self.re_vt100.sub('', self.buf, count=1000000)
Stephen Warren10e50632016-01-15 11:15:24 -0700213 finally:
214 if self.logfile_read:
215 self.logfile_read.flush()
216
217 def close(self):
Stephen Warren75e731e2016-01-26 13:41:30 -0700218 """Close the stdio connection to the sub-process.
Stephen Warren10e50632016-01-15 11:15:24 -0700219
220 This also waits a reasonable time for the sub-process to stop running.
221
222 Args:
223 None.
224
225 Returns:
226 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700227 """
Stephen Warren10e50632016-01-15 11:15:24 -0700228
229 os.close(self.fd)
Paul Burtond2849ed2017-09-14 14:34:44 -0700230 for i in range(100):
Stephen Warren10e50632016-01-15 11:15:24 -0700231 if not self.isalive():
232 break
233 time.sleep(0.1)
Simon Glass9bc20832016-07-04 11:58:39 -0600234
235 def get_expect_output(self):
236 """Return the output read by expect()
237
238 Returns:
239 The output processed by expect(), as a string.
240 """
241 return self.output