~doanac/+junk/rftd

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python

# Ubuntu Testing Automation Harness
# Copyright 2012 Canonical Ltd.

# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

"UTAH client used to run tests."""


import logging
import platform
import sys
import os

from utah import logger
from utah.url import url_argument
from utah.client.probe import probes
from utah.client.probe.battery import battery
from utah.client.runner import Runner
from utah.client.state_agent import StateAgentYAML
from utah.client.result import classes as result_classes

from utah.client.common import (
    DEFAULT_STATE_FILE,
    get_install_type,
    ReturnCodes,
)
from utah.client.exceptions import UTAHClientError


def get_parser():
    """Process the command line arguments."""
    # requires Python2.7+
    import argparse

    parser = argparse.ArgumentParser(
        description='''Run test cases locally and write results to a file.

Note: This is expected to be used only for development purposes on a machine
that has been provisioned using run_utah_tests.py''',
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--resume', action='store_true',
                        help='Continue a previous run.  Used after a reboot')
    parser.add_argument('-s', '--state-file',
                        help=('File to use for storing state (default "{}")'
                              .format(DEFAULT_STATE_FILE)))
    parser.add_argument('-f', '--format',
                        choices=['text', 'yaml', 'json'],
                        default='yaml',
                        help='Output format (default "%(default)s")')
    parser.add_argument('-t', '--testdir',
                        default='/var/lib/utah', help='Main test directory')
    parser.add_argument('-i', '--install-type',
                        choices=['desktop', 'server', 'mini', 'alternate'],
                        default=get_install_type(),
                        help=('Installation Variant '
                              '(i.e. server, desktop, etc.)'))
    parser.add_argument('-r', '--runlist', type=url_argument,
                        # Having a default here means that if a resume happens
                        # post-reboot without a runlist specified, it will
                        # run the default runlist instead of erroring
                        #default='/usr/share/utah/client/examples/master.run',
                        help='runlist file name')
    parser.add_argument('-o', '--output', help='write output to this file')
    parser.add_argument('-a', '--append', action='store_true',
                        help='append to output')
    parser.add_argument('-d', '--debug', action='store_true',
                        help='Print debugging output')
    parser.add_argument('-b', '--battery',
                        default=battery.implementation,
                        choices=battery.implementations(),
                        help='Choose which battery implementation to use.')
    parser.add_argument('-p', '--probe-dir', default='/tmp',
                        help='Directory to store probe files.')

    return parser


def setup_logging(debug=False):
    if debug:
        level = logging.DEBUG
    else:
        level = logging.WARNING

    logging.basicConfig(level=level,
                        format='%(asctime)s - %(levelname)s - %(message)s')


def setup_probes(args):
    os.environ['UTAH_PROBE_DIR'] = args.probe_dir
    battery.implementation = args.battery
    probes.output_dir = args.probe_dir


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    """Interpret command line arguments and run tests."""
    # TODO: write <2.7 optparse version and set based on version of python
    #       being used.
    parser = get_parser()

    # Capture parsing error and use the returncode defined
    # in utah.client.common, not the one that argparse uses by default
    try:
        args = parser.parse_args(argv)
    except SystemExit:
        sys.exit(ReturnCodes.CMD_PARSING_ERROR)

    if not os.getuid() == 0:
        parser.print_usage()
        msg = ('{}: UTAH client is expected to be executed as root user\n'
               .format(parser.prog))
        sys.stderr.write(msg)
        logger.log_error(msg)
        sys.exit(ReturnCodes.INVALID_USER)

    setup_logging(args.debug)
    setup_probes(args)

    logging.debug(args)
    logging.info(platform.uname())

    resume = args.resume
    state_file = args.state_file
    testdir = args.testdir
    runlist = args.runlist
    output = args.output
    install_type = args.install_type

    # Read results before last reboot so that they can be properly merged
    if resume and output:
        with open(output) as f:
            old_results = f.read()
    else:
        old_results = None

    result = result_classes[args.format](output, args.append)
    try:
        state_agent = StateAgentYAML(state_file=state_file)
        runner = Runner(install_type=install_type, state_agent=state_agent,
                        result=result, runlist=runlist,
                        resume=resume, old_results=old_results,
                        testdir=testdir, output=args.output)
        if resume:
            runner.load_state()

        for x in xrange(runner.repeat_count + 1):
            returncode = runner.run(x)
            if returncode:
                break

        if returncode != ReturnCodes.REBOOT:
            returncode = runner.process_results()
    except UTAHClientError as e:
        sys.stderr.write(str(e))
        sys.stderr.write('\n')
        logger.log_error(str(e))
        sys.exit(ReturnCodes.EXCEPTION_ERROR)

    sys.exit(returncode)

if __name__ == "__main__":
    main()