u_boot_spawn.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. (self.pid, self.fd) = pty.fork()
  34. if self.pid == 0:
  35. try:
  36. # For some reason, SIGHUP is set to SIG_IGN at this point when
  37. # run under "go" (www.go.cd). Perhaps this happens under any
  38. # background (non-interactive) system?
  39. signal.signal(signal.SIGHUP, signal.SIG_DFL)
  40. if cwd:
  41. os.chdir(cwd)
  42. os.execvp(args[0], args)
  43. except:
  44. print 'CHILD EXECEPTION:'
  45. import traceback
  46. traceback.print_exc()
  47. finally:
  48. os._exit(255)
  49. self.poll = select.poll()
  50. self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
  51. def kill(self, sig):
  52. """Send unix signal "sig" to the child process.
  53. Args:
  54. sig: The signal number to send.
  55. Returns:
  56. Nothing.
  57. """
  58. os.kill(self.pid, sig)
  59. def isalive(self):
  60. """Determine whether the child process is still running.
  61. Args:
  62. None.
  63. Returns:
  64. Boolean indicating whether process is alive.
  65. """
  66. if self.waited:
  67. return False
  68. w = os.waitpid(self.pid, os.WNOHANG)
  69. if w[0] == 0:
  70. return True
  71. self.waited = True
  72. return False
  73. def send(self, data):
  74. """Send data to the sub-process's stdin.
  75. Args:
  76. data: The data to send to the process.
  77. Returns:
  78. Nothing.
  79. """
  80. os.write(self.fd, data)
  81. def expect(self, patterns):
  82. """Wait for the sub-process to emit specific data.
  83. This function waits for the process to emit one pattern from the
  84. supplied list of patterns, or for a timeout to occur.
  85. Args:
  86. patterns: A list of strings or regex objects that we expect to
  87. see in the sub-process' stdout.
  88. Returns:
  89. The index within the patterns array of the pattern the process
  90. emitted.
  91. Notable exceptions:
  92. Timeout, if the process did not emit any of the patterns within
  93. the expected time.
  94. """
  95. for pi in xrange(len(patterns)):
  96. if type(patterns[pi]) == type(''):
  97. patterns[pi] = re.compile(patterns[pi])
  98. tstart_s = time.time()
  99. try:
  100. while True:
  101. earliest_m = None
  102. earliest_pi = None
  103. for pi in xrange(len(patterns)):
  104. pattern = patterns[pi]
  105. m = pattern.search(self.buf)
  106. if not m:
  107. continue
  108. if earliest_m and m.start() >= earliest_m.start():
  109. continue
  110. earliest_m = m
  111. earliest_pi = pi
  112. if earliest_m:
  113. pos = earliest_m.start()
  114. posafter = earliest_m.end() + 1
  115. self.before = self.buf[:pos]
  116. self.after = self.buf[pos:posafter]
  117. self.buf = self.buf[posafter:]
  118. return earliest_pi
  119. tnow_s = time.time()
  120. if self.timeout:
  121. tdelta_ms = (tnow_s - tstart_s) * 1000
  122. poll_maxwait = self.timeout - tdelta_ms
  123. if tdelta_ms > self.timeout:
  124. raise Timeout()
  125. else:
  126. poll_maxwait = None
  127. events = self.poll.poll(poll_maxwait)
  128. if not events:
  129. raise Timeout()
  130. c = os.read(self.fd, 1024)
  131. if not c:
  132. raise EOFError()
  133. if self.logfile_read:
  134. self.logfile_read.write(c)
  135. self.buf += c
  136. finally:
  137. if self.logfile_read:
  138. self.logfile_read.flush()
  139. def close(self):
  140. """Close the stdio connection to the sub-process.
  141. This also waits a reasonable time for the sub-process to stop running.
  142. Args:
  143. None.
  144. Returns:
  145. Nothing.
  146. """
  147. os.close(self.fd)
  148. for i in xrange(100):
  149. if not self.isalive():
  150. break
  151. time.sleep(0.1)