runner.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # Copyright (c) 2021 Project CHIP Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import os
  16. import pty
  17. import queue
  18. import re
  19. import subprocess
  20. import sys
  21. import threading
  22. import typing
  23. class LogPipe(threading.Thread):
  24. """Create PTY-based PIPE for IPC.
  25. Python provides a built-in mechanism for creating comunication PIPEs for
  26. subprocesses spawned with Popen(). However, created PIPEs will most likely
  27. enable IO buffering in the spawned process. In order to trick such process
  28. to flush its streams immediately, we are going to create a PIPE based on
  29. pseudoterminal (PTY).
  30. """
  31. def __init__(self, level, capture_delegate=None, name=None):
  32. """
  33. Setup the object with a logger and a loglevel and start the thread.
  34. """
  35. threading.Thread.__init__(self)
  36. self.daemon = False
  37. self.level = level
  38. self.fd_read, self.fd_write = pty.openpty()
  39. self.reader = open(self.fd_read, encoding='utf-8', errors='ignore')
  40. self.captured_logs = []
  41. self.capture_delegate = capture_delegate
  42. self.name = name
  43. self.start()
  44. def CapturedLogContains(self, txt: str, index=0):
  45. for i, line in enumerate(self.captured_logs[index:]):
  46. if txt in line:
  47. return True, i
  48. return False, len(self.captured_logs)
  49. def FindLastMatchingLine(self, matcher):
  50. for line in reversed(self.captured_logs):
  51. match = re.match(matcher, line)
  52. if match:
  53. return match
  54. return None
  55. def fileno(self):
  56. """Return the write file descriptor of the pipe."""
  57. return self.fd_write
  58. def run(self):
  59. """Run the thread, logging everything."""
  60. while True:
  61. try:
  62. line = self.reader.readline()
  63. # It seems that Darwin platform returns empty string in case
  64. # when writing side of PTY is closed (Linux raises OSError).
  65. if line == '':
  66. break
  67. except OSError:
  68. break
  69. logging.log(self.level, line.strip('\n'))
  70. self.captured_logs.append(line)
  71. if self.capture_delegate:
  72. self.capture_delegate.Log(self.name, line)
  73. self.reader.close()
  74. def close(self):
  75. """Close the write end of the pipe."""
  76. os.close(self.fd_write)
  77. class RunnerWaitQueue:
  78. def __init__(self, timeout_seconds: typing.Optional[int]):
  79. self.queue = queue.Queue()
  80. self.timeout_seconds = timeout_seconds
  81. self.timed_out = False
  82. def __wait(self, process, userdata):
  83. if userdata is None:
  84. # We're the main process for this wait queue.
  85. timeout = self.timeout_seconds
  86. else:
  87. timeout = None
  88. try:
  89. process.wait(timeout)
  90. except subprocess.TimeoutExpired:
  91. self.timed_out = True
  92. process.kill()
  93. # And wait for the kill() to kill it.
  94. process.wait()
  95. self.queue.put((process, userdata))
  96. def add_process(self, process, userdata=None):
  97. t = threading.Thread(target=self.__wait, args=(process, userdata))
  98. t.daemon = True
  99. t.start()
  100. def get(self):
  101. return self.queue.get()
  102. class Runner:
  103. def __init__(self, capture_delegate=None):
  104. self.capture_delegate = capture_delegate
  105. def RunSubprocess(self, cmd, name, wait=True, dependencies=[], timeout_seconds: typing.Optional[int] = None, stdin=None):
  106. outpipe = LogPipe(
  107. logging.DEBUG, capture_delegate=self.capture_delegate,
  108. name=name + ' OUT')
  109. errpipe = LogPipe(
  110. logging.INFO, capture_delegate=self.capture_delegate,
  111. name=name + ' ERR')
  112. if sys.platform == 'darwin':
  113. # Try harder to avoid any stdout buffering in our tests
  114. cmd = ['stdbuf', '-o0', '-i0'] + cmd
  115. if self.capture_delegate:
  116. self.capture_delegate.Log(name, 'EXECUTING %r' % cmd)
  117. s = subprocess.Popen(cmd, stdin=stdin, stdout=outpipe, stderr=errpipe)
  118. outpipe.close()
  119. errpipe.close()
  120. if not wait:
  121. return s, outpipe, errpipe
  122. wait = RunnerWaitQueue(timeout_seconds=timeout_seconds)
  123. wait.add_process(s)
  124. for dependency in dependencies:
  125. for accessory in dependency.accessories:
  126. wait.add_process(accessory, dependency)
  127. for process, userdata in iter(wait.queue.get, None):
  128. if process == s:
  129. break
  130. # dependencies MUST NOT be done
  131. s.kill()
  132. raise Exception("Unexpected return %d for %r" %
  133. (process.returncode, userdata))
  134. if s.returncode != 0:
  135. if wait.timed_out:
  136. raise Exception("Command %r exceeded test timeout (%d seconds)" % (cmd, wait.timeout_seconds))
  137. else:
  138. raise Exception('Command %r failed: %d' % (cmd, s.returncode))
  139. logging.debug('Command %r completed with error code 0', cmd)