Debian Codegraph @

aodhclient/shell.py

raw
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import logging
17 import os
18 import sys
19 import warnings
20
21 from cliff import app
22 from cliff import commandmanager
23 from keystoneauth1 import exceptions
24 from keystoneauth1 import loading
25
26 from aodhclient import __version__
27 from aodhclient import client
28 from aodhclient import noauth
29 from aodhclient.v2 import alarm_cli
30 from aodhclient.v2 import alarm_history_cli
31 from aodhclient.v2 import capabilities_cli
32 from aodhclient.v2 import metrics_cli
33
34
35 class AodhCommandManager(commandmanager.CommandManager):
36 SHELL_COMMANDS = {
37 "alarm create": alarm_cli.CliAlarmCreate,
38 "alarm delete": alarm_cli.CliAlarmDelete,
39 "alarm list": alarm_cli.CliAlarmList,
40 "alarm show": alarm_cli.CliAlarmShow,
41 "alarm update": alarm_cli.CliAlarmUpdate,
42 "alarm state get": alarm_cli.CliAlarmStateGet,
43 "alarm state set": alarm_cli.CliAlarmStateSet,
44 "alarm-history show": alarm_history_cli.CliAlarmHistoryShow,
45 "alarm-history search": alarm_history_cli.CliAlarmHistorySearch,
46 "capabilities list": capabilities_cli.CliCapabilitiesList,
47 "alarm metrics": metrics_cli.CliMetrics,
48 }
49
50 def load_commands(self, namespace):
51 for name, command_class in self.SHELL_COMMANDS.items():
52 self.add_command(name, command_class)
53
54
55 class AodhShell(app.App):
56 def __init__(self):
57 super().__init__(
58 description='Aodh command line client',
59 version=__version__,
60 command_manager=AodhCommandManager('aodhclient'),
61 deferred_help=True,
62 )
63
64 self._client = None
65
66 def build_option_parser(self, description, version):
67 """Return an argparse option parser for this application.
68
69 Subclasses may override this method to extend
70 the parser with more global options.
71
72 :param description: full description of the application
73 :paramtype description: str
74 :param version: version number for the application
75 :paramtype version: str
76 """
77 parser = super().build_option_parser(
78 description, version, argparse_kwargs={'allow_abbrev': False})
79 # Global arguments, one day this should go to keystoneauth1
80 parser.add_argument(
81 '--os-region-name',
82 metavar='<auth-region-name>',
83 dest='region_name',
84 default=os.environ.get('OS_REGION_NAME'),
85 help='Authentication region name (Env: OS_REGION_NAME)')
86 parser.add_argument(
87 '--os-interface',
88 metavar='<interface>',
89 dest='interface',
90 choices=['admin', 'public', 'internal'],
91 default=os.environ.get('OS_INTERFACE'),
92 help='Select an interface type.'
93 ' Valid interface types: [admin, public, internal].'
94 ' (Env: OS_INTERFACE)')
95 parser.add_argument(
96 '--aodh-api-version',
97 default=os.environ.get('AODH_API_VERSION', '2'),
98 help='Defaults to env[AODH_API_VERSION] or 2.')
99 loading.register_session_argparse_arguments(parser=parser)
100 plugin = loading.register_auth_argparse_arguments(
101 parser=parser, argv=sys.argv, default="password")
102
103 if not isinstance(plugin, noauth.AodhNoAuthLoader):
104 parser.add_argument(
105 '--aodh-endpoint',
106 metavar='<endpoint>',
107 dest='endpoint',
108 default=os.environ.get('AODH_ENDPOINT'),
109 help='Aodh endpoint (Env: AODH_ENDPOINT)')
110
111 return parser
112
113 @property
114 def client(self):
115 # NOTE(sileht): we lazy load the client to not
116 # load/connect auth stuffs
117 if self._client is None:
118 if hasattr(self.options, "endpoint"):
119 endpoint_override = self.options.endpoint
120 else:
121 endpoint_override = None
122 auth_plugin = loading.load_auth_from_argparse_arguments(
123 self.options)
124 session = loading.load_session_from_argparse_arguments(
125 self.options, auth=auth_plugin)
126
127 self._client = client.Client(self.options.aodh_api_version,
128 session=session,
129 interface=self.options.interface,
130 region_name=self.options.region_name,
131 endpoint_override=endpoint_override)
132 return self._client
133
134 def clean_up(self, cmd, result, err):
135 if isinstance(err, exceptions.HttpError) and err.details:
136 print(err.details, file=sys.stderr)
137
138 def configure_logging(self):
139 if self.options.debug:
140 # --debug forces verbose_level 3
141 # Set this here so cliff.app.configure_logging() can work
142 self.options.verbose_level = 3
143
144 super().configure_logging()
145 root_logger = logging.getLogger('')
146
147 # Set logging to the requested level
148 if self.options.verbose_level == 0:
149 # --quiet
150 root_logger.setLevel(logging.ERROR)
151 warnings.simplefilter("ignore")
152 elif self.options.verbose_level == 1:
153 # This is the default case, no --debug, --verbose or --quiet
154 root_logger.setLevel(logging.WARNING)
155 warnings.simplefilter("ignore")
156 elif self.options.verbose_level == 2:
157 # One --verbose
158 root_logger.setLevel(logging.INFO)
159 warnings.simplefilter("once")
160 elif self.options.verbose_level >= 3:
161 # Two or more --verbose
162 root_logger.setLevel(logging.DEBUG)
163
164 # Hide some useless message
165 requests_log = logging.getLogger("requests")
166 cliff_log = logging.getLogger('cliff')
167 stevedore_log = logging.getLogger('stevedore')
168 iso8601_log = logging.getLogger("iso8601")
169
170 cliff_log.setLevel(logging.ERROR)
171 stevedore_log.setLevel(logging.ERROR)
172 iso8601_log.setLevel(logging.ERROR)
173
174 if self.options.debug:
175 requests_log.setLevel(logging.DEBUG)
176 else:
177 requests_log.setLevel(logging.ERROR)
178
179
180 def main(args=None):
181 if args is None:
182 args = sys.argv[1:]
183 return AodhShell().run(args)