u_boot_spawn.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # SPDX-License-Identifier: GPL-2.0
  2. # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
  3. # Logic to spawn a sub-process and interact with its stdio.
  4. import os
  5. import re
  6. import pty
  7. import signal
  8. import select
  9. import time
  10. class Timeout(Exception):
  11. """An exception sub-class that indicates that a timeout occurred."""
  12. pass
  13. class Spawn(object):
  14. """Represents the stdio of a freshly created sub-process. Commands may be
  15. sent to the process, and responses waited for.
  16. Members:
  17. output: accumulated output from expect()
  18. """
  19. def __init__(self, args, cwd=None):
  20. """Spawn (fork/exec) the sub-process.
  21. Args:
  22. args: array of processs arguments. argv[0] is the command to
  23. execute.
  24. cwd: the directory to run the process in, or None for no change.
  25. Returns:
  26. Nothing.
  27. """
  28. self.waited = False
  29. self.buf = ''
  30. self.output = ''
  31. self.logfile_read = None
  32. self.before = ''
  33. self.after = ''
  34. self.timeout = None
  35. # http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
  36. self.re_vt100 = re.compile(r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]', re.I)
  37. (self.pid, self.fd) = pty.fork()
  38. if self.pid == 0:
  39. try:
  40. # For some reason, SIGHUP is set to SIG_IGN at this point when
  41. # run under "go" (www.go.cd). Perhaps this happens under any
  42. # background (non-interactive) system?
  43. signal.signal(signal.SIGHUP, signal.SIG_DFL)
  44. if cwd:
  45. os.chdir(cwd)
  46. os.execvp(args[0], args)
  47. except:
  48. print('CHILD EXECEPTION:')
  49. import traceback
  50. traceback.print_exc()
  51. finally:
  52. os._exit(255)
  53. try:
  54. self.poll = select.poll()
  55. self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
  56. except:
  57. self.close()
  58. raise
  59. def kill(self, sig):
  60. """Send unix signal "sig" to the child process.
  61. Args:
  62. sig: The signal number to send.
  63. Returns:
  64. Nothing.
  65. """
  66. os.kill(self.pid, sig)
  67. def isalive(self):
  68. """Determine whether the child process is still running.
  69. Args:
  70. None.
  71. Returns:
  72. Boolean indicating whether process is alive.
  73. """
  74. if self.waited:
  75. return False
  76. w = os.waitpid(self.pid, os.WNOHANG)
  77. if w[0] == 0:
  78. return True
  79. self.waited = True
  80. return False
  81. def send(self, data):
  82. """Send data to the sub-process's stdin.
  83. Args:
  84. data: The data to send to the process.
  85. Returns:
  86. Nothing.
  87. """
  88. os.write(self.fd, data.encode(errors='replace'))
  89. def expect(self, patterns):
  90. """Wait for the sub-process to emit specific data.
  91. This function waits for the process to emit one pattern from the
  92. supplied list of patterns, or for a timeout to occur.
  93. Args:
  94. patterns: A list of strings or regex objects that we expect to
  95. see in the sub-process' stdout.
  96. Returns:
  97. The index within the patterns array of the pattern the process
  98. emitted.
  99. Notable exceptions:
  100. Timeout, if the process did not emit any of the patterns within
  101. the expected time.
  102. """
  103. for pi in range(len(patterns)):
  104. if type(patterns[pi]) == type(''):
  105. patterns[pi] = re.compile(patterns[pi])
  106. tstart_s = time.time()
  107. try:
  108. while True:
  109. earliest_m = None
  110. earliest_pi = None
  111. for pi in range(len(patterns)):
  112. pattern = patterns[pi]
  113. m = pattern.search(self.buf)
  114. if not m:
  115. continue
  116. if earliest_m and m.start() >= earliest_m.start():
  117. continue
  118. earliest_m = m
  119. earliest_pi = pi
  120. if earliest_m:
  121. pos = earliest_m.start()
  122. posafter = earliest_m.end()
  123. self.before = self.buf[:pos]
  124. self.after = self.buf[pos:posafter]
  125. self.output += self.buf[:posafter]
  126. self.buf = self.buf[posafter:]
  127. return earliest_pi
  128. tnow_s = time.time()
  129. if self.timeout:
  130. tdelta_ms = (tnow_s - tstart_s) * 1000
  131. poll_maxwait = self.timeout - tdelta_ms
  132. if tdelta_ms > self.timeout:
  133. raise Timeout()
  134. else:
  135. poll_maxwait = None
  136. events = self.poll.poll(poll_maxwait)
  137. if not events:
  138. raise Timeout()
  139. c = os.read(self.fd, 1024).decode(errors='replace')
  140. if not c:
  141. raise EOFError()
  142. if self.logfile_read:
  143. self.logfile_read.write(c)
  144. self.buf += c
  145. # count=0 is supposed to be the default, which indicates
  146. # unlimited substitutions, but in practice the version of
  147. # Python in Ubuntu 14.04 appears to default to count=2!
  148. self.buf = self.re_vt100.sub('', self.buf, count=1000000)
  149. finally:
  150. if self.logfile_read:
  151. self.logfile_read.flush()
  152. def close(self):
  153. """Close the stdio connection to the sub-process.
  154. This also waits a reasonable time for the sub-process to stop running.
  155. Args:
  156. None.
  157. Returns:
  158. Nothing.
  159. """
  160. os.close(self.fd)
  161. for i in range(100):
  162. if not self.isalive():
  163. break
  164. time.sleep(0.1)
  165. def get_expect_output(self):
  166. """Return the output read by expect()
  167. Returns:
  168. The output processed by expect(), as a string.
  169. """
  170. return self.output