| 1 |
#!/usr/bin/env python |
| 2 |
""" |
| 3 |
Use to put a timeout on the length of time a script can run. This is |
| 4 |
especially useful for checking for scripts that hang. |
| 5 |
|
| 6 |
Usage |
| 7 |
===== |
| 8 |
|
| 9 |
NOTE: Make sure you run ``pip install -r requirements-dev.txt`` before running. |
| 10 |
|
| 11 |
To use the script, run:: |
| 12 |
|
| 13 |
./timeout "./my-script-to-run" --timeout-after 5 |
| 14 |
|
| 15 |
""" |
| 16 |
|
| 17 |
import argparse |
| 18 |
import os |
| 19 |
import subprocess |
| 20 |
import sys |
| 21 |
import time |
| 22 |
|
| 23 |
import psutil |
| 24 |
|
| 25 |
|
| 26 |
class TimeoutException(Exception): |
| 27 |
def __init__(self, timeout_len): |
| 28 |
msg = f'Script failed to complete within {timeout_len} seconds' |
| 29 |
Exception.__init__(self, msg) |
| 30 |
|
| 31 |
|
| 32 |
def timeout(args): |
| 33 |
parent_pid = os.getpid() |
| 34 |
child_p = run_script(args) |
| 35 |
try: |
| 36 |
run_timeout(child_p.pid, args.timeout_after) |
| 37 |
except (TimeoutException, KeyboardInterrupt) as e: |
| 38 |
proc = psutil.Process(parent_pid) |
| 39 |
procs = proc.children(recursive=True) |
| 40 |
|
| 41 |
for child in procs: |
| 42 |
child.terminate() |
| 43 |
|
| 44 |
gone, alive = psutil.wait_procs(procs, timeout=1) |
| 45 |
for child in alive: |
| 46 |
child.kill() |
| 47 |
raise e |
| 48 |
|
| 49 |
|
| 50 |
def run_timeout(pid, timeout_len): |
| 51 |
p = psutil.Process(pid) |
| 52 |
start_time = time.time() |
| 53 |
while p.is_running(): |
| 54 |
if p.status() == psutil.STATUS_ZOMBIE: |
| 55 |
p.kill() |
| 56 |
break |
| 57 |
current_time = time.time() |
| 58 |
# Raise a timeout if the duration of the process is longer than |
| 59 |
# the desired timeout. |
| 60 |
if current_time - start_time > timeout_len: |
| 61 |
raise TimeoutException(timeout_len) |
| 62 |
time.sleep(1) |
| 63 |
|
| 64 |
|
| 65 |
def run_script(args): |
| 66 |
return subprocess.Popen(args.script, shell=True) |
| 67 |
|
| 68 |
|
| 69 |
def main(): |
| 70 |
parser = argparse.ArgumentParser(usage=__doc__) |
| 71 |
parser.add_argument('script', help='The script to run for benchmarking') |
| 72 |
parser.add_argument( |
| 73 |
'--timeout-after', |
| 74 |
required=True, |
| 75 |
type=float, |
| 76 |
help=( |
| 77 |
'The length of time in seconds allowed for the script to run ' |
| 78 |
'before it time\'s out.' |
| 79 |
), |
| 80 |
) |
| 81 |
args = parser.parse_args() |
| 82 |
return timeout(args) |
| 83 |
|
| 84 |
|
| 85 |
if __name__ == '__main__': |
| 86 |
sys.exit(main()) |