summaryrefslogtreecommitdiffstats
path: root/third_party/python/redo/redo/cmd.py
blob: aeb65dbb3e2fe3a5caee5cb4c5d1f92d7a2d84dd (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
import logging
from subprocess import check_call, CalledProcessError
import sys

from redo import retrying

log = logging.getLogger(__name__)


def main(argv):
    from argparse import ArgumentParser, REMAINDER

    parser = ArgumentParser()
    parser.add_argument(
        "-a", "--attempts", type=int, default=5, help="How many times to retry."
    )
    parser.add_argument(
        "-s",
        "--sleeptime",
        type=int,
        default=60,
        help="How long to sleep between attempts. Sleeptime doubles after each attempt.",
    )
    parser.add_argument(
        "-m",
        "--max-sleeptime",
        type=int,
        default=5 * 60,
        help="Maximum length of time to sleep between attempts (limits backoff length).",
    )
    parser.add_argument("-v", "--verbose", action="store_true", default=False)
    parser.add_argument(
        "cmd", nargs=REMAINDER, help="Command to run. Eg: wget http://blah"
    )

    args = parser.parse_args(argv[1:])

    if args.verbose:
        logging.basicConfig(level=logging.INFO)
        logging.getLogger("retry").setLevel(logging.INFO)
    else:
        logging.basicConfig(level=logging.ERROR)
        logging.getLogger("retry").setLevel(logging.ERROR)

    try:
        with retrying(
            check_call,
            attempts=args.attempts,
            sleeptime=args.sleeptime,
            max_sleeptime=args.max_sleeptime,
            retry_exceptions=(CalledProcessError,),
        ) as r_check_call:
            r_check_call(args.cmd)
    except KeyboardInterrupt:
        sys.exit(-1)
    except Exception as e:
        log.error(
            "Unable to run command after %d attempts" % args.attempts, exc_info=True
        )
        rc = getattr(e, "returncode", -2)
        sys.exit(rc)


if __name__ == "__main__":
    main(sys.argv)