summaryrefslogtreecommitdiff
path: root/contrib/python/pypodman/lib/pypodman.py
blob: 4bc71a9cc70fb2373166c2e04c6f141064a92e83 (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
71
72
73
74
75
76
#!/usr/bin/env python3
"""Remote podman client."""

import logging
import os
import sys

import lib.actions
from lib import PodmanArgumentParser

assert lib.actions  # silence pyflakes


def main():
    """Entry point."""
    # Setup logging so we use stderr and can change logging level later
    # Do it now before there is any chance of a default setup hardcoding crap.
    log = logging.getLogger()
    fmt = logging.Formatter('%(asctime)s | %(levelname)-8s | %(message)s',
                            '%Y-%m-%d %H:%M:%S %Z')
    stderr = logging.StreamHandler(stream=sys.stderr)
    stderr.setFormatter(fmt)
    log.addHandler(stderr)
    log.setLevel(logging.WARNING)

    parser = PodmanArgumentParser()
    args = parser.parse_args()

    log.setLevel(args.log_level)
    logging.debug('Logging initialized at level {}'.format(
        logging.getLevelName(logging.getLogger().getEffectiveLevel())))

    def want_tb():
        """Add traceback when logging events."""
        return log.getEffectiveLevel() == logging.DEBUG

    try:
        if not os.path.exists(args.run_dir):
            os.makedirs(args.run_dir)
    except PermissionError as e:
        logging.critical(e, exc_info=want_tb())
        sys.exit(6)

    # class_(args).method() are set by the sub-command's parser
    returncode = None
    try:
        obj = args.class_(args)
    except Exception as e:
        logging.critical(repr(e), exc_info=want_tb())
        logging.warning('See subparser "{}" configuration.'.format(
            args.subparser_name))
        sys.exit(5)

    try:
        returncode = getattr(obj, args.method)()
    except AttributeError as e:
        logging.critical(e, exc_info=want_tb())
        logging.warning('See subparser "{}" configuration.'.format(
            args.subparser_name))
        returncode = 3
    except KeyboardInterrupt:
        pass
    except (
            ConnectionRefusedError,
            ConnectionResetError,
            TimeoutError,
    ) as e:
        logging.critical(e, exc_info=want_tb())
        logging.info('Review connection arguments for correctness.')
        returncode = 4

    return 0 if returncode is None else returncode


if __name__ == '__main__':
    sys.exit(main())