1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
5 Logic to spawn a sub-process and interact with its stdio.
16 class Timeout(Exception):
17 """An exception sub-class that indicates that a timeout occurred."""
20 """Represents the stdio of a freshly created sub-process. Commands may be
21 sent to the process, and responses waited for.
24 output: accumulated output from expect()
27 def __init__(self, args, cwd=None):
28 """Spawn (fork/exec) the sub-process.
31 args: array of processs arguments. argv[0] is the command to
33 cwd: the directory to run the process in, or None for no change.
44 self.logfile_read = None
48 # http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
49 self.re_vt100 = re.compile(r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]', re.I)
51 (self.pid, self.fd) = pty.fork()
54 # For some reason, SIGHUP is set to SIG_IGN at this point when
55 # run under "go" (www.go.cd). Perhaps this happens under any
56 # background (non-interactive) system?
57 signal.signal(signal.SIGHUP, signal.SIG_DFL)
60 os.execvp(args[0], args)
62 print('CHILD EXECEPTION:')
68 self.poll = select.poll()
69 self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR |
70 select.POLLHUP | select.POLLNVAL)
76 """Send unix signal "sig" to the child process.
79 sig: The signal number to send.
85 os.kill(self.pid, sig)
88 """Determine whether the child process is still running.
92 True if process is alive, else False
93 0 if process is alive, else exit code of process
94 string describing what happened ('' or 'status/signal n')
98 return False, self.exit_code, self.exit_info
100 w = os.waitpid(self.pid, os.WNOHANG)
102 return True, 0, 'running'
105 if os.WIFEXITED(status):
106 self.exit_code = os.WEXITSTATUS(status)
107 self.exit_info = 'status %d' % self.exit_code
108 elif os.WIFSIGNALED(status):
109 signum = os.WTERMSIG(status)
110 self.exit_code = -signum
111 self.exit_info = 'signal %d (%s)' % (signum, signal.Signals(signum).name)
113 return False, self.exit_code, self.exit_info
116 """Determine whether the child process is still running.
122 Boolean indicating whether process is alive.
124 return self.checkalive()[0]
126 def send(self, data):
127 """Send data to the sub-process's stdin.
130 data: The data to send to the process.
136 os.write(self.fd, data.encode(errors='replace'))
138 def expect(self, patterns):
139 """Wait for the sub-process to emit specific data.
141 This function waits for the process to emit one pattern from the
142 supplied list of patterns, or for a timeout to occur.
145 patterns: A list of strings or regex objects that we expect to
146 see in the sub-process' stdout.
149 The index within the patterns array of the pattern the process
153 Timeout, if the process did not emit any of the patterns within
157 for pi in range(len(patterns)):
158 if type(patterns[pi]) == type(''):
159 patterns[pi] = re.compile(patterns[pi])
161 tstart_s = time.time()
166 for pi in range(len(patterns)):
167 pattern = patterns[pi]
168 m = pattern.search(self.buf)
171 if earliest_m and m.start() >= earliest_m.start():
176 pos = earliest_m.start()
177 posafter = earliest_m.end()
178 self.before = self.buf[:pos]
179 self.after = self.buf[pos:posafter]
180 self.output += self.buf[:posafter]
181 self.buf = self.buf[posafter:]
185 tdelta_ms = (tnow_s - tstart_s) * 1000
186 poll_maxwait = self.timeout - tdelta_ms
187 if tdelta_ms > self.timeout:
191 events = self.poll.poll(poll_maxwait)
195 c = os.read(self.fd, 1024).decode(errors='replace')
196 except OSError as err:
197 # With sandbox, try to detect when U-Boot exits when it
198 # shouldn't and explain why. This is much more friendly than
199 # just dying with an I/O error
200 if err.errno == 5: # Input/output error
201 alive, _, info = self.checkalive()
204 raise ValueError('U-Boot exited with %s' % info)
206 if self.logfile_read:
207 self.logfile_read.write(c)
209 # 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)
214 if self.logfile_read:
215 self.logfile_read.flush()
218 """Close the stdio connection to the sub-process.
220 This also waits a reasonable time for the sub-process to stop running.
231 if not self.isalive():
235 def get_expect_output(self):
236 """Return the output read by expect()
239 The output processed by expect(), as a string.