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