"""CPU accounting and generous wall-clock hang guards for tests only.""" import argparse from contextlib import contextmanager import os import resource import signal import subprocess import sys import time import unittest HANG_TIMEOUT = 600 def children_cpu(): usage = resource.getrusage(resource.RUSAGE_CHILDREN) return usage.ru_utime + usage.ru_stime class Timing: def __init__(self): self.start_cpu = time.process_time() self.start_children = children_cpu() self.start_wall = time.monotonic() @property def cpu(self): return time.process_time() - self.start_cpu @property def child_cpu(self): # RUSAGE_CHILDREN includes children only after they have been reaped. return children_cpu() - self.start_children @property def wall(self): return time.monotonic() - self.start_wall def __str__(self): return f'CPU self={self.cpu:.3f}s children={self.child_cpu:.3f}s; wall={self.wall:.3f}s' @contextmanager def hang_diagnostics(): timing = Timing() try: yield timing except unittest.SkipTest: raise except Exception as exc: raise AssertionError(f'{exc}\n{timing}') from exc def run_with_timeout(command, *, timeout=HANG_TIMEOUT, check=False, capture_output=False, **kwargs): with hang_diagnostics(): if capture_output: kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE) with subprocess.Popen(command, start_new_session=True, **kwargs) as child: try: stdout, stderr = child.communicate(timeout=timeout) except subprocess.TimeoutExpired: os.killpg(child.pid, signal.SIGKILL) child.communicate() raise result = subprocess.CompletedProcess(command, child.returncode, stdout, stderr) if check: result.check_returncode() return result def communicate_with_timeout(child, timeout=HANG_TIMEOUT): with hang_diagnostics(): try: return child.communicate(timeout=timeout) except subprocess.TimeoutExpired: child.kill() child.communicate() raise def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--timeout', type=float, default=HANG_TIMEOUT) parser.add_argument('command', nargs=argparse.REMAINDER) args = parser.parse_args() timing = Timing() child = subprocess.Popen(args.command, start_new_session=True) try: returncode = child.wait(timeout=args.timeout) except subprocess.TimeoutExpired: os.killpg(child.pid, signal.SIGKILL) child.wait() print(f'hang guard expired: {args.command!r}; {timing}', file=sys.stderr) return 124 if returncode: print(f'{args.command!r}: {timing}', file=sys.stderr) return returncode if returncode >= 0 else 128 - returncode if __name__ == '__main__': sys.exit(main())