File size: 3,027 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"""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())