summaryrefslogtreecommitdiffstats
path: root/python/redo/redo/cmd.py
blob: afd98e7447e17d9dbda480f2ae41438bab918d22 (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
# ***** 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():
    from argparse import ArgumentParser

    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="+", help="Command to run. Eg: wget http://blah")

    args = parser.parse_args()

    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()