u_boot_spawn.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. try:
  95. while True:
  96. earliest_m = None
  97. earliest_pi = None
  98. for pi in xrange(len(patterns)):
  99. pattern = patterns[pi]
  100. m = pattern.search(self.buf)
  101. if not m:
  102. continue
  103. if earliest_m and m.start() > earliest_m.start():
  104. continue
  105. earliest_m = m
  106. earliest_pi = pi
  107. if earliest_m:
  108. pos = earliest_m.start()
  109. posafter = earliest_m.end() + 1
  110. self.before = self.buf[:pos]
  111. self.after = self.buf[pos:posafter]
  112. self.buf = self.buf[posafter:]
  113. return earliest_pi
  114. events = self.poll.poll(self.timeout)
  115. if not events:
  116. raise Timeout()
  117. c = os.read(self.fd, 1024)
  118. if not c:
  119. raise EOFError()
  120. if self.logfile_read:
  121. self.logfile_read.write(c)
  122. self.buf += c
  123. finally:
  124. if self.logfile_read:
  125. self.logfile_read.flush()
  126. def close(self):
  127. '''Close the stdio connection to the sub-process.
  128. This also waits a reasonable time for the sub-process to stop running.
  129. Args:
  130. None.
  131. Returns:
  132. Nothing.
  133. '''
  134. os.close(self.fd)
  135. for i in xrange(100):
  136. if not self.isalive():
  137. break
  138. time.sleep(0.1)