root / kamaki / cli / commands / __init__.py @ 00b1248e
History | View | Annotate | Download (12.6 kB)
1 |
# Copyright 2011-2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.command
|
33 |
|
34 |
from kamaki.cli.logger import get_logger |
35 |
from kamaki.cli.utils import ( |
36 |
print_list, print_dict, print_json, print_items, ask_user, |
37 |
filter_dicts_by_dict) |
38 |
from kamaki.cli.argument import FlagArgument, ValueArgument |
39 |
from kamaki.cli.errors import CLIInvalidArgument |
40 |
from sys import stdin, stdout, stderr |
41 |
|
42 |
log = get_logger(__name__) |
43 |
|
44 |
|
45 |
def DontRaiseKeyError(foo): |
46 |
def wrap(*args, **kwargs): |
47 |
try:
|
48 |
return foo(*args, **kwargs)
|
49 |
except KeyError: |
50 |
return None |
51 |
return wrap
|
52 |
|
53 |
|
54 |
def addLogSettings(foo): |
55 |
def wrap(self, *args, **kwargs): |
56 |
try:
|
57 |
return foo(self, *args, **kwargs) |
58 |
finally:
|
59 |
self._set_log_params()
|
60 |
self._update_max_threads
|
61 |
return wrap
|
62 |
|
63 |
|
64 |
class _command_init(object): |
65 |
|
66 |
# self.arguments (dict) contains all non-positional arguments
|
67 |
# self.required (list or tuple) contains required argument keys
|
68 |
# if it is a list, at least one of these arguments is required
|
69 |
# if it is a tuple, all arguments are required
|
70 |
# Lists and tuples can nest other lists and/or tuples
|
71 |
required = None
|
72 |
|
73 |
def __init__( |
74 |
self,
|
75 |
arguments={}, auth_base=None, cloud=None, |
76 |
_in=None, _out=None, _err=None): |
77 |
self._in, self._out, self._err = ( |
78 |
_in or stdin, _out or stdout, _err or stderr) |
79 |
if hasattr(self, 'arguments'): |
80 |
arguments.update(self.arguments)
|
81 |
if isinstance(self, _optional_output_cmd): |
82 |
arguments.update(self.oo_arguments)
|
83 |
if isinstance(self, _optional_json): |
84 |
arguments.update(self.oj_arguments)
|
85 |
if isinstance(self, _name_filter): |
86 |
arguments.update(self.nf_arguments)
|
87 |
if isinstance(self, _id_filter): |
88 |
arguments.update(self.if_arguments)
|
89 |
try:
|
90 |
arguments.update(self.wait_arguments)
|
91 |
except AttributeError: |
92 |
pass
|
93 |
self.arguments = dict(arguments) |
94 |
try:
|
95 |
self.config = self['config'] |
96 |
except KeyError: |
97 |
pass
|
98 |
self.auth_base = auth_base or getattr(self, 'auth_base', None) |
99 |
self.cloud = cloud or getattr(self, 'cloud', None) |
100 |
|
101 |
def write(self, s): |
102 |
self._out.write(u'%s' % s) |
103 |
self._out.flush()
|
104 |
|
105 |
def writeln(self, s=''): |
106 |
self.write(u'%s\n' % s) |
107 |
|
108 |
def error(self, s=''): |
109 |
self._err.write(u'%s\n' % s) |
110 |
self._err.flush()
|
111 |
|
112 |
def print_list(self, *args, **kwargs): |
113 |
kwargs.setdefault('out', self._out) |
114 |
return print_list(*args, **kwargs)
|
115 |
|
116 |
def print_dict(self, *args, **kwargs): |
117 |
kwargs.setdefault('out', self._out) |
118 |
return print_dict(*args, **kwargs)
|
119 |
|
120 |
def print_json(self, *args, **kwargs): |
121 |
kwargs.setdefault('out', self._out) |
122 |
return print_json(*args, **kwargs)
|
123 |
|
124 |
def print_items(self, *args, **kwargs): |
125 |
kwargs.setdefault('out', self._out) |
126 |
return print_items(*args, **kwargs)
|
127 |
|
128 |
def ask_user(self, *args, **kwargs): |
129 |
kwargs.setdefault('user_in', self._in) |
130 |
kwargs.setdefault('out', self._out) |
131 |
return ask_user(*args, **kwargs)
|
132 |
|
133 |
@DontRaiseKeyError
|
134 |
def _custom_url(self, service): |
135 |
return self.config.get_cloud(self.cloud, '%s_url' % service) |
136 |
|
137 |
@DontRaiseKeyError
|
138 |
def _custom_token(self, service): |
139 |
return self.config.get_cloud(self.cloud, '%s_token' % service) |
140 |
|
141 |
@DontRaiseKeyError
|
142 |
def _custom_type(self, service): |
143 |
return self.config.get_cloud(self.cloud, '%s_type' % service) |
144 |
|
145 |
@DontRaiseKeyError
|
146 |
def _custom_version(self, service): |
147 |
return self.config.get_cloud(self.cloud, '%s_version' % service) |
148 |
|
149 |
def _uuids2usernames(self, uuids): |
150 |
return self.auth_base.post_user_catalogs(uuids) |
151 |
|
152 |
def _usernames2uuids(self, username): |
153 |
return self.auth_base.post_user_catalogs(displaynames=username) |
154 |
|
155 |
def _uuid2username(self, uuid): |
156 |
return self._uuids2usernames([uuid]).get(uuid, None) |
157 |
|
158 |
def _username2uuid(self, username): |
159 |
return self._usernames2uuids([username]).get(username, None) |
160 |
|
161 |
def _set_log_params(self): |
162 |
try:
|
163 |
self.client.LOG_TOKEN = (
|
164 |
self['config'].get('global', 'log_token').lower() == 'on') |
165 |
except Exception as e: |
166 |
log.debug('Failed to read custom log_token setting:'
|
167 |
'%s\n default for log_token is off' % e)
|
168 |
try:
|
169 |
self.client.LOG_DATA = (
|
170 |
self['config'].get('global', 'log_data').lower() == 'on') |
171 |
except Exception as e: |
172 |
log.debug('Failed to read custom log_data setting:'
|
173 |
'%s\n default for log_data is off' % e)
|
174 |
try:
|
175 |
self.client.LOG_PID = (
|
176 |
self['config'].get('global', 'log_pid').lower() == 'on') |
177 |
except Exception as e: |
178 |
log.debug('Failed to read custom log_pid setting:'
|
179 |
'%s\n default for log_pid is off' % e)
|
180 |
|
181 |
def _update_max_threads(self): |
182 |
if getattr(self, 'client', None): |
183 |
max_threads = int(self['config'].get('global', 'max_threads')) |
184 |
assert max_threads > 0, 'invalid max_threads config option' |
185 |
self.client.MAX_THREADS = max_threads
|
186 |
|
187 |
def _safe_progress_bar( |
188 |
self, msg, arg='progress_bar', countdown=False, timeout=100): |
189 |
"""Try to get a progress bar, but do not raise errors"""
|
190 |
try:
|
191 |
progress_bar = self.arguments[arg]
|
192 |
progress_bar.file = self._err
|
193 |
gen = progress_bar.get_generator( |
194 |
msg, countdown=countdown, timeout=timeout) |
195 |
except Exception: |
196 |
return (None, None) |
197 |
return (progress_bar, gen)
|
198 |
|
199 |
def _safe_progress_bar_finish(self, progress_bar): |
200 |
try:
|
201 |
progress_bar.finish() |
202 |
except Exception: |
203 |
pass
|
204 |
|
205 |
def __getitem__(self, argterm): |
206 |
"""
|
207 |
:param argterm: (str) the name/label of an argument in self.arguments
|
208 |
|
209 |
:returns: the value of the corresponding Argument (not the argument
|
210 |
object)
|
211 |
|
212 |
:raises KeyError: if argterm not in self.arguments of this object
|
213 |
"""
|
214 |
return self.arguments[argterm].value |
215 |
|
216 |
def __setitem__(self, argterm, arg): |
217 |
"""Install an argument as argterm
|
218 |
If argterm points to another argument, the other argument is lost
|
219 |
|
220 |
:param argterm: (str)
|
221 |
|
222 |
:param arg: (Argument)
|
223 |
"""
|
224 |
if not hasattr(self, 'arguments'): |
225 |
self.arguments = {}
|
226 |
self.arguments[argterm] = arg
|
227 |
|
228 |
def get_argument_object(self, argterm): |
229 |
"""
|
230 |
:param argterm: (str) the name/label of an argument in self.arguments
|
231 |
|
232 |
:returns: the arument object
|
233 |
|
234 |
:raises KeyError: if argterm not in self.arguments of this object
|
235 |
"""
|
236 |
return self.arguments[argterm] |
237 |
|
238 |
def get_argument(self, argterm): |
239 |
"""
|
240 |
:param argterm: (str) the name/label of an argument in self.arguments
|
241 |
|
242 |
:returns: the value of the arument object
|
243 |
|
244 |
:raises KeyError: if argterm not in self.arguments of this object
|
245 |
"""
|
246 |
return self[argterm] |
247 |
|
248 |
|
249 |
# feature classes - inherit them to get special features for your commands
|
250 |
|
251 |
|
252 |
class OutputFormatArgument(ValueArgument): |
253 |
"""Accepted output formats: json (default)"""
|
254 |
|
255 |
formats = ('json', )
|
256 |
|
257 |
def ___init__(self, *args, **kwargs): |
258 |
super(OutputFormatArgument, self).___init__(*args, **kwargs) |
259 |
|
260 |
@property
|
261 |
def value(self): |
262 |
return self._value |
263 |
|
264 |
@value.setter
|
265 |
def value(self, newvalue): |
266 |
if not newvalue: |
267 |
self._value = self.default |
268 |
elif newvalue.lower() in self.formats: |
269 |
self._value = newvalue.lower
|
270 |
else:
|
271 |
raise CLIInvalidArgument(
|
272 |
'Invalid value %s for argument %s' % (
|
273 |
newvalue, '/'.join(self.parsed_name)), |
274 |
details=['Valid output formats: %s' % ', '.join(self.formats)]) |
275 |
|
276 |
|
277 |
class _optional_output_cmd(object): |
278 |
|
279 |
oo_arguments = dict(
|
280 |
with_output=FlagArgument('show response headers', ('--with-output')), |
281 |
json_output=FlagArgument( |
282 |
'show headers in json (DEPRECATED from v0.12,'
|
283 |
' please use --output-format=json instead)', ('-j', '--json')) |
284 |
) |
285 |
|
286 |
def _optional_output(self, r): |
287 |
if self['json_output']: |
288 |
print_json(r, out=self._out)
|
289 |
elif self['with_output']: |
290 |
print_items([r] if isinstance(r, dict) else r, out=self._out) |
291 |
|
292 |
|
293 |
class _optional_json(object): |
294 |
|
295 |
oj_arguments = dict(
|
296 |
output_format=OutputFormatArgument( |
297 |
'Show output in chosen output format (%s)' % ', '.join( |
298 |
OutputFormatArgument.formats), |
299 |
'--output-format'),
|
300 |
json_output=FlagArgument( |
301 |
'show output in json (DEPRECATED from v0.12,'
|
302 |
' please use --output-format instead)', ('-j', '--json')) |
303 |
) |
304 |
|
305 |
def _print(self, output, print_method=print_items, **print_method_kwargs): |
306 |
if self['json_output'] or self['output_format']: |
307 |
print_json(output, out=self._out)
|
308 |
else:
|
309 |
print_method_kwargs.setdefault('out', self._out) |
310 |
print_method(output, **print_method_kwargs) |
311 |
|
312 |
|
313 |
class _name_filter(object): |
314 |
|
315 |
nf_arguments = dict(
|
316 |
name=ValueArgument('filter by name', '--name'), |
317 |
name_pref=ValueArgument( |
318 |
'filter by name prefix (case insensitive)', '--name-prefix'), |
319 |
name_suff=ValueArgument( |
320 |
'filter by name suffix (case insensitive)', '--name-suffix'), |
321 |
name_like=ValueArgument( |
322 |
'print only if name contains this (case insensitive)',
|
323 |
'--name-like')
|
324 |
) |
325 |
|
326 |
def _non_exact_name_filter(self, items): |
327 |
np, ns, nl = self['name_pref'], self['name_suff'], self['name_like'] |
328 |
return [item for item in items if ( |
329 |
(not np) or item['name'].lower().startswith(np.lower())) and ( |
330 |
(not ns) or item['name'].lower().endswith(ns.lower())) and ( |
331 |
(not nl) or nl.lower() in item['name'].lower())] |
332 |
|
333 |
def _exact_name_filter(self, items): |
334 |
return filter_dicts_by_dict(items, dict(name=self['name'])) if ( |
335 |
self['name']) else items |
336 |
|
337 |
def _filter_by_name(self, items): |
338 |
return self._non_exact_name_filter(self._exact_name_filter(items)) |
339 |
|
340 |
|
341 |
class _id_filter(object): |
342 |
|
343 |
if_arguments = dict(
|
344 |
id=ValueArgument('filter by id', '--id'), |
345 |
id_pref=ValueArgument( |
346 |
'filter by id prefix (case insensitive)', '--id-prefix'), |
347 |
id_suff=ValueArgument( |
348 |
'filter by id suffix (case insensitive)', '--id-suffix'), |
349 |
id_like=ValueArgument( |
350 |
'print only if id contains this (case insensitive)', '--id-like') |
351 |
) |
352 |
|
353 |
def _non_exact_id_filter(self, items): |
354 |
np, ns, nl = self['id_pref'], self['id_suff'], self['id_like'] |
355 |
return [item for item in items if ( |
356 |
(not np) or ( |
357 |
'%s' % item['id']).lower().startswith(np.lower())) and ( |
358 |
(not ns) or ('%s' % item['id']).lower().endswith(ns.lower())) and ( |
359 |
(not nl) or nl.lower() in ('%s' % item['id']).lower())] |
360 |
|
361 |
def _exact_id_filter(self, items): |
362 |
return filter_dicts_by_dict(items, dict(id=self['id'])) if ( |
363 |
self['id']) else items |
364 |
|
365 |
def _filter_by_id(self, items): |
366 |
return self._non_exact_id_filter(self._exact_id_filter(items)) |