summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/tools/docker/retry.py
blob: 8ecf5874fed877235941086736772a3b39083c6b (plain)
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
#!/usr/bin/env python3
import argparse
import subprocess
import time
import sys


def get_args() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    parser.add_argument("--delay", action="store", type=float, default=3, help="Initial delay before retry, in seconds")
    parser.add_argument("--count", action="store", type=int, default=5, help="Total number of tries")
    parser.add_argument("--factor", action="store", type=float, default=2, help="Exponential backoff factor")
    parser.add_argument("cmd", nargs=argparse.REMAINDER)
    return parser


def log(value: str) -> None:
    print(value)
    sys.stdout.flush()


def main() -> None:
    args = get_args().parse_args()

    if not args.cmd:
        log("No command supplied")
        sys.exit(1)

    retcode = None

    for n in range(args.count):
        try:
            log("Running %s [try %d/%d]" % (" ".join(args.cmd), (n+1), args.count))
            subprocess.check_call(args.cmd)
        except subprocess.CalledProcessError as e:
            retcode = e.returncode
        else:
            log("Command succeeded")
            retcode = 0
            break

        if args.factor == 0:
            wait_time = (n+1) * args.delay
        else:
            wait_time = args.factor**n * args.delay
        if n < args.count - 1:
            log("Command failed, waiting %s seconds to retry" % wait_time)
            time.sleep(wait_time)
        else:
            log("Command failed, out of retries")

    sys.exit(retcode)


if __name__ == "__main__":
    main()