u_boot_spawn.py 6.3 KB

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