u_boot_spawn.py 5.0 KB

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