u_boot_spawn.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. """
  18. def __init__(self, args, cwd=None):
  19. """Spawn (fork/exec) the sub-process.
  20. Args:
  21. args: array of processs arguments. argv[0] is the command to
  22. execute.
  23. cwd: the directory to run the process in, or None for no change.
  24. Returns:
  25. Nothing.
  26. """
  27. self.waited = False
  28. self.buf = ''
  29. self.logfile_read = None
  30. self.before = ''
  31. self.after = ''
  32. self.timeout = None
  33. # http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
  34. # Note that re.I doesn't seem to work with this regex (or perhaps the
  35. # version of Python in Ubuntu 14.04), hence the inclusion of a-z inside
  36. # [] instead.
  37. self.re_vt100 = re.compile('(\x1b\[|\x9b)[^@-_a-z]*[@-_a-z]|\x1b[@-_a-z]')
  38. (self.pid, self.fd) = pty.fork()
  39. if self.pid == 0:
  40. try:
  41. # For some reason, SIGHUP is set to SIG_IGN at this point when
  42. # run under "go" (www.go.cd). Perhaps this happens under any
  43. # background (non-interactive) system?
  44. signal.signal(signal.SIGHUP, signal.SIG_DFL)
  45. if cwd:
  46. os.chdir(cwd)
  47. os.execvp(args[0], args)
  48. except:
  49. print 'CHILD EXECEPTION:'
  50. import traceback
  51. traceback.print_exc()
  52. finally:
  53. os._exit(255)
  54. try:
  55. self.poll = select.poll()
  56. self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
  57. except:
  58. self.close()
  59. raise
  60. def kill(self, sig):
  61. """Send unix signal "sig" to the child process.
  62. Args:
  63. sig: The signal number to send.
  64. Returns:
  65. Nothing.
  66. """
  67. os.kill(self.pid, sig)
  68. def isalive(self):
  69. """Determine whether the child process is still running.
  70. Args:
  71. None.
  72. Returns:
  73. Boolean indicating whether process is alive.
  74. """
  75. if self.waited:
  76. return False
  77. w = os.waitpid(self.pid, os.WNOHANG)
  78. if w[0] == 0:
  79. return True
  80. self.waited = True
  81. return False
  82. def send(self, data):
  83. """Send data to the sub-process's stdin.
  84. Args:
  85. data: The data to send to the process.
  86. Returns:
  87. Nothing.
  88. """
  89. os.write(self.fd, data)
  90. def expect(self, patterns):
  91. """Wait for the sub-process to emit specific data.
  92. This function waits for the process to emit one pattern from the
  93. supplied list of patterns, or for a timeout to occur.
  94. Args:
  95. patterns: A list of strings or regex objects that we expect to
  96. see in the sub-process' stdout.
  97. Returns:
  98. The index within the patterns array of the pattern the process
  99. emitted.
  100. Notable exceptions:
  101. Timeout, if the process did not emit any of the patterns within
  102. the expected time.
  103. """
  104. for pi in xrange(len(patterns)):
  105. if type(patterns[pi]) == type(''):
  106. patterns[pi] = re.compile(patterns[pi])
  107. tstart_s = time.time()
  108. try:
  109. while True:
  110. earliest_m = None
  111. earliest_pi = None
  112. for pi in xrange(len(patterns)):
  113. pattern = patterns[pi]
  114. m = pattern.search(self.buf)
  115. if not m:
  116. continue
  117. if earliest_m and m.start() >= earliest_m.start():
  118. continue
  119. earliest_m = m
  120. earliest_pi = pi
  121. if earliest_m:
  122. pos = earliest_m.start()
  123. posafter = earliest_m.end()
  124. self.before = self.buf[:pos]
  125. self.after = self.buf[pos: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)
  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 xrange(100):
  162. if not self.isalive():
  163. break
  164. time.sleep(0.1)