Support general configuration file
[yardstick.git] / yardstick / cmd / cli.py
1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 '''
11 Command-line interface to yardstick
12 '''
13
14 import logging
15 import os
16 import sys
17
18 from pkg_resources import get_distribution
19 from argparse import RawDescriptionHelpFormatter
20 from oslo_config import cfg
21
22 from yardstick.cmd.commands import task
23 from yardstick.cmd.commands import runner
24 from yardstick.cmd.commands import scenario
25
26 CONF = cfg.CONF
27 cli_opts = [
28     cfg.BoolOpt('debug',
29                 short='d',
30                 default=False,
31                 help='increase output verbosity to debug'),
32     cfg.BoolOpt('verbose',
33                 short='v',
34                 default=False,
35                 help='increase output verbosity to info')
36 ]
37 CONF.register_cli_opts(cli_opts)
38
39 CONFIG_SEARCH_PATHS = [sys.prefix + "/etc/yardstick",
40                        "~/.yardstick",
41                        "/etc/yardstick"]
42
43
44 def find_config_files(path_list):
45     for path in path_list:
46         abspath = os.path.abspath(os.path.expanduser(path))
47         confname = abspath + "/yardstick.conf"
48         if os.path.isfile(confname):
49             return [confname]
50
51     return None
52
53
54 class YardstickCLI():
55     '''Command-line interface to yardstick'''
56
57     # Command categories
58     categories = {
59         'task': task.TaskCommands,
60         'runner': runner.RunnerCommands,
61         'scenario': scenario.ScenarioCommands
62     }
63
64     def __init__(self):
65         self._version = 'yardstick version %s ' % \
66             get_distribution('yardstick').version
67
68     def _find_actions(self, subparsers, actions_module):
69         '''find action methods'''
70         # Find action methods inside actions_module and
71         # add them to the command parser.
72         # The 'actions_module' argument may be a class
73         # or module. Action methods start with 'do_'
74         for attr in (a for a in dir(actions_module) if a.startswith('do_')):
75             command = attr[3:].replace('_', '-')
76             callback = getattr(actions_module, attr)
77             desc = callback.__doc__ or ''
78             arguments = getattr(callback, 'arguments', [])
79             subparser = subparsers.add_parser(
80                 command,
81                 description=desc
82             )
83             for (args, kwargs) in arguments:
84                 subparser.add_argument(*args, **kwargs)
85             subparser.set_defaults(func=callback)
86
87     def _add_command_parsers(self, categories, subparsers):
88         '''add commands to command-line parser'''
89         for category in categories:
90             command_object = categories[category]()
91             desc = command_object.__doc__ or ''
92             subparser = subparsers.add_parser(
93                 category, description=desc,
94                 formatter_class=RawDescriptionHelpFormatter
95             )
96             subparser.set_defaults(command_object=command_object)
97             cmd_subparsers = subparser.add_subparsers(title='subcommands')
98             self._find_actions(cmd_subparsers, command_object)
99
100     def main(self, argv):
101         '''run the command line interface'''
102
103         # register subcommands to parse additional command line arguments
104         parser = lambda subparsers: self._add_command_parsers(
105             YardstickCLI.categories, subparsers)
106         category_opt = cfg.SubCommandOpt("category",
107                                          title="Command categories",
108                                          help="Available categories",
109                                          handler=parser)
110         CONF.register_cli_opt(category_opt)
111
112         # load CLI args and config files
113         CONF(argv, project="yardstick", version=self._version,
114              default_config_files=find_config_files(CONFIG_SEARCH_PATHS))
115
116         # handle global opts
117         logger = logging.getLogger('yardstick')
118         logger.setLevel(logging.WARNING)
119
120         if CONF.verbose:
121             logger.setLevel(logging.INFO)
122
123         if CONF.debug:
124             logger.setLevel(logging.DEBUG)
125
126         # dispatch to category parser
127         func = CONF.category.func
128         func(CONF.category)