root / kamaki / cli / commands / __init__.py @ ff1c0296
History | View | Annotate | Download (10.3 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 print_json, print_items, filter_dicts_by_dict |
36 |
from kamaki.cli.argument import FlagArgument, ValueArgument |
37 |
from sys import stdin, stdout, stderr |
38 |
|
39 |
log = get_logger(__name__) |
40 |
|
41 |
|
42 |
def DontRaiseKeyError(foo): |
43 |
def wrap(*args, **kwargs): |
44 |
try:
|
45 |
return foo(*args, **kwargs)
|
46 |
except KeyError: |
47 |
return None |
48 |
return wrap
|
49 |
|
50 |
|
51 |
def addLogSettings(foo): |
52 |
def wrap(self, *args, **kwargs): |
53 |
try:
|
54 |
return foo(self, *args, **kwargs) |
55 |
finally:
|
56 |
self._set_log_params()
|
57 |
self._update_max_threads
|
58 |
return wrap
|
59 |
|
60 |
|
61 |
class _command_init(object): |
62 |
|
63 |
def __init__( |
64 |
self,
|
65 |
arguments={}, auth_base=None, cloud=None, |
66 |
_in=None, _out=None, _err=None): |
67 |
self._in, self._out, self._err = ( |
68 |
_in or stdin, _out or stdout, _err or stderr) |
69 |
if hasattr(self, 'arguments'): |
70 |
arguments.update(self.arguments)
|
71 |
if isinstance(self, _optional_output_cmd): |
72 |
arguments.update(self.oo_arguments)
|
73 |
if isinstance(self, _optional_json): |
74 |
arguments.update(self.oj_arguments)
|
75 |
if isinstance(self, _name_filter): |
76 |
arguments.update(self.nf_arguments)
|
77 |
if isinstance(self, _id_filter): |
78 |
arguments.update(self.if_arguments)
|
79 |
try:
|
80 |
arguments.update(self.wait_arguments)
|
81 |
except AttributeError: |
82 |
pass
|
83 |
self.arguments = dict(arguments) |
84 |
try:
|
85 |
self.config = self['config'] |
86 |
except KeyError: |
87 |
pass
|
88 |
self.auth_base = auth_base or getattr(self, 'auth_base', None) |
89 |
self.cloud = cloud or getattr(self, 'cloud', None) |
90 |
|
91 |
def write(self, s): |
92 |
self._out.write(u'%s' % s) |
93 |
self._out.flush()
|
94 |
|
95 |
def writeln(self, s=''): |
96 |
self.write(u'%s\n' % s) |
97 |
|
98 |
def error(self, s=''): |
99 |
self._err.write(u'%s\n' % s) |
100 |
self._err.flush()
|
101 |
|
102 |
@DontRaiseKeyError
|
103 |
def _custom_url(self, service): |
104 |
return self.config.get_cloud(self.cloud, '%s_url' % service) |
105 |
|
106 |
@DontRaiseKeyError
|
107 |
def _custom_token(self, service): |
108 |
return self.config.get_cloud(self.cloud, '%s_token' % service) |
109 |
|
110 |
@DontRaiseKeyError
|
111 |
def _custom_type(self, service): |
112 |
return self.config.get_cloud(self.cloud, '%s_type' % service) |
113 |
|
114 |
@DontRaiseKeyError
|
115 |
def _custom_version(self, service): |
116 |
return self.config.get_cloud(self.cloud, '%s_version' % service) |
117 |
|
118 |
def _uuids2usernames(self, uuids): |
119 |
return self.auth_base.post_user_catalogs(uuids).json['uuid_catalog'] |
120 |
|
121 |
def _usernames2uuids(self, username): |
122 |
return self.auth_base.post_user_catalogs( |
123 |
displaynames=username).json['displayname_catalog']
|
124 |
|
125 |
def _uuid2username(self, uuid): |
126 |
return self._uuids2usernames([uuid]).get(uuid, None) |
127 |
|
128 |
def _username2uuid(self, username): |
129 |
return self._usernames2uuids([username]).get(username, None) |
130 |
|
131 |
def _set_log_params(self): |
132 |
try:
|
133 |
self.client.LOG_TOKEN = (
|
134 |
self['config'].get_global('log_token').lower() == 'on') |
135 |
except Exception as e: |
136 |
log.debug('Failed to read custom log_token setting:'
|
137 |
'%s\n default for log_token is off' % e)
|
138 |
try:
|
139 |
self.client.LOG_DATA = (
|
140 |
self['config'].get_global('log_data').lower() == 'on') |
141 |
except Exception as e: |
142 |
log.debug('Failed to read custom log_data setting:'
|
143 |
'%s\n default for log_data is off' % e)
|
144 |
try:
|
145 |
self.client.LOG_PID = (
|
146 |
self['config'].get_global('log_pid').lower() == 'on') |
147 |
except Exception as e: |
148 |
log.debug('Failed to read custom log_pid setting:'
|
149 |
'%s\n default for log_pid is off' % e)
|
150 |
|
151 |
def _update_max_threads(self): |
152 |
if getattr(self, 'client', None): |
153 |
max_threads = int(self['config'].get_global('max_threads')) |
154 |
assert max_threads > 0, 'invalid max_threads config option' |
155 |
self.client.MAX_THREADS = max_threads
|
156 |
|
157 |
def _safe_progress_bar(self, msg, arg='progress_bar'): |
158 |
"""Try to get a progress bar, but do not raise errors"""
|
159 |
try:
|
160 |
progress_bar = self.arguments[arg]
|
161 |
progress_bar.file = self._err
|
162 |
gen = progress_bar.get_generator(msg) |
163 |
except Exception: |
164 |
return (None, None) |
165 |
return (progress_bar, gen)
|
166 |
|
167 |
def _safe_progress_bar_finish(self, progress_bar): |
168 |
try:
|
169 |
progress_bar.finish() |
170 |
except Exception: |
171 |
pass
|
172 |
|
173 |
def __getitem__(self, argterm): |
174 |
"""
|
175 |
:param argterm: (str) the name/label of an argument in self.arguments
|
176 |
|
177 |
:returns: the value of the corresponding Argument (not the argument
|
178 |
object)
|
179 |
|
180 |
:raises KeyError: if argterm not in self.arguments of this object
|
181 |
"""
|
182 |
return self.arguments[argterm].value |
183 |
|
184 |
def __setitem__(self, argterm, arg): |
185 |
"""Install an argument as argterm
|
186 |
If argterm points to another argument, the other argument is lost
|
187 |
|
188 |
:param argterm: (str)
|
189 |
|
190 |
:param arg: (Argument)
|
191 |
"""
|
192 |
if not hasattr(self, 'arguments'): |
193 |
self.arguments = {}
|
194 |
self.arguments[argterm] = arg
|
195 |
|
196 |
def get_argument_object(self, argterm): |
197 |
"""
|
198 |
:param argterm: (str) the name/label of an argument in self.arguments
|
199 |
|
200 |
:returns: the arument object
|
201 |
|
202 |
:raises KeyError: if argterm not in self.arguments of this object
|
203 |
"""
|
204 |
return self.arguments[argterm] |
205 |
|
206 |
def get_argument(self, argterm): |
207 |
"""
|
208 |
:param argterm: (str) the name/label of an argument in self.arguments
|
209 |
|
210 |
:returns: the value of the arument object
|
211 |
|
212 |
:raises KeyError: if argterm not in self.arguments of this object
|
213 |
"""
|
214 |
return self[argterm] |
215 |
|
216 |
|
217 |
# feature classes - inherit them to get special features for your commands
|
218 |
|
219 |
|
220 |
class _optional_output_cmd(object): |
221 |
|
222 |
oo_arguments = dict(
|
223 |
with_output=FlagArgument('show response headers', ('--with-output')), |
224 |
json_output=FlagArgument('show headers in json', ('-j', '--json')) |
225 |
) |
226 |
|
227 |
def _optional_output(self, r): |
228 |
if self['json_output']: |
229 |
print_json(r, out=self._out)
|
230 |
elif self['with_output']: |
231 |
print_items([r] if isinstance(r, dict) else r, out=self._out) |
232 |
|
233 |
|
234 |
class _optional_json(object): |
235 |
|
236 |
oj_arguments = dict(
|
237 |
json_output=FlagArgument('show headers in json', ('-j', '--json')) |
238 |
) |
239 |
|
240 |
def _print(self, output, print_method=print_items, **print_method_kwargs): |
241 |
if self['json_output']: |
242 |
print_json(output, out=self._out)
|
243 |
else:
|
244 |
print_method(output, out=self._out, **print_method_kwargs)
|
245 |
|
246 |
|
247 |
class _name_filter(object): |
248 |
|
249 |
nf_arguments = dict(
|
250 |
name=ValueArgument('filter by name', '--name'), |
251 |
name_pref=ValueArgument( |
252 |
'filter by name prefix (case insensitive)', '--name-prefix'), |
253 |
name_suff=ValueArgument( |
254 |
'filter by name suffix (case insensitive)', '--name-suffix'), |
255 |
name_like=ValueArgument( |
256 |
'print only if name contains this (case insensitive)',
|
257 |
'--name-like')
|
258 |
) |
259 |
|
260 |
def _non_exact_name_filter(self, items): |
261 |
np, ns, nl = self['name_pref'], self['name_suff'], self['name_like'] |
262 |
return [item for item in items if ( |
263 |
(not np) or item['name'].lower().startswith(np.lower())) and ( |
264 |
(not ns) or item['name'].lower().endswith(ns.lower())) and ( |
265 |
(not nl) or nl.lower() in item['name'].lower())] |
266 |
|
267 |
def _exact_name_filter(self, items): |
268 |
return filter_dicts_by_dict(items, dict(name=self['name'])) if ( |
269 |
self['name']) else items |
270 |
|
271 |
def _filter_by_name(self, items): |
272 |
return self._non_exact_name_filter(self._exact_name_filter(items)) |
273 |
|
274 |
|
275 |
class _id_filter(object): |
276 |
|
277 |
if_arguments = dict(
|
278 |
id=ValueArgument('filter by id', '--id'), |
279 |
id_pref=ValueArgument( |
280 |
'filter by id prefix (case insensitive)', '--id-prefix'), |
281 |
id_suff=ValueArgument( |
282 |
'filter by id suffix (case insensitive)', '--id-suffix'), |
283 |
id_like=ValueArgument( |
284 |
'print only if id contains this (case insensitive)',
|
285 |
'--id-like')
|
286 |
) |
287 |
|
288 |
def _non_exact_id_filter(self, items): |
289 |
np, ns, nl = self['id_pref'], self['id_suff'], self['id_like'] |
290 |
return [item for item in items if ( |
291 |
(not np) or ( |
292 |
'%s' % item['id']).lower().startswith(np.lower())) and ( |
293 |
(not ns) or ('%s' % item['id']).lower().endswith(ns.lower())) and ( |
294 |
(not nl) or nl.lower() in ('%s' % item['id']).lower())] |
295 |
|
296 |
def _exact_id_filter(self, items): |
297 |
return filter_dicts_by_dict(items, dict(id=self['id'])) if ( |
298 |
self['id']) else items |
299 |
|
300 |
def _filter_by_id(self, items): |
301 |
return self._non_exact_id_filter(self._exact_id_filter(items)) |