Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / __init__.py @ 90c22848

History | View | Annotate | Download (13 kB)

1
# Copyright 2011-2014 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, DontRaiseUnicodeError, pref_enc)
38
from kamaki.cli.argument import FlagArgument, ValueArgument
39
from kamaki.cli.errors import CLIInvalidArgument
40
from sys import stdin, stdout, stderr
41
import codecs
42

    
43

    
44
log = get_logger(__name__)
45

    
46

    
47
def DontRaiseKeyError(func):
48
    def wrap(*args, **kwargs):
49
        try:
50
            return func(*args, **kwargs)
51
        except KeyError:
52
            return None
53
    return wrap
54

    
55

    
56
def addLogSettings(func):
57
    def wrap(self, *args, **kwargs):
58
        try:
59
            return func(self, *args, **kwargs)
60
        finally:
61
            self._set_log_params()
62
    return wrap
63

    
64

    
65
def dataModification(func):
66
    def wrap(self, inp):
67
        try:
68
            inp = func(self, inp)
69
        except Exception as e:
70
            log.warning('WARNING: Error while running %s: %s' % (func, e))
71
            log.warning('\tWARNING: Kamaki will use original data to go on')
72
        finally:
73
            return inp
74
    return wrap
75

    
76

    
77
class _command_init(object):
78

    
79
    # self.arguments (dict) contains all non-positional arguments
80
    # self.required (list or tuple) contains required argument keys
81
    #     if it is a list, at least one of these arguments is required
82
    #     if it is a tuple, all arguments are required
83
    #     Lists and tuples can nest other lists and/or tuples
84

    
85
    def __init__(
86
            self,
87
            arguments={}, auth_base=None, cloud=None,
88
            _in=None, _out=None, _err=None):
89
        self._in, self._out, self._err = (
90
            _in or stdin, _out or stdout, _err or stderr)
91
        self._in = codecs.getreader('utf-8')(_in or stdin)
92
        self._out = codecs.getwriter(pref_enc)(_out or stdout)
93
        self._err = codecs.getwriter(pref_enc)(_err or stderr)
94
        self.required = getattr(self, 'required', None)
95
        if hasattr(self, 'arguments'):
96
            arguments.update(self.arguments)
97
        if isinstance(self, _optional_output_cmd):
98
            arguments.update(self.oo_arguments)
99
        if isinstance(self, _optional_json):
100
            arguments.update(self.oj_arguments)
101
        if isinstance(self, _name_filter):
102
            arguments.update(self.nf_arguments)
103
        if isinstance(self, _id_filter):
104
            arguments.update(self.if_arguments)
105
        try:
106
            arguments.update(self.wait_arguments)
107
        except AttributeError:
108
            pass
109
        self.arguments = dict(arguments)
110
        try:
111
            self.config = self['config']
112
        except KeyError:
113
            pass
114
        self.auth_base = auth_base or getattr(self, 'auth_base', None)
115
        self.cloud = cloud or getattr(self, 'cloud', None)
116

    
117
    @DontRaiseUnicodeError
118
    def write(self, s):
119
        self._out.write(s)
120
        self._out.flush()
121

    
122
    @DontRaiseUnicodeError
123
    def writeln(self, s=''):
124
        self.write('%s\n' % s)
125

    
126
    @DontRaiseUnicodeError
127
    def error(self, s=''):
128
        self._err.write('%s\n' % s)
129
        self._err.flush()
130

    
131
    def print_list(self, *args, **kwargs):
132
        kwargs.setdefault('out', self._out)
133
        return print_list(*args, **kwargs)
134

    
135
    def print_dict(self, *args, **kwargs):
136
        kwargs.setdefault('out', self)
137
        return print_dict(*args, **kwargs)
138

    
139
    def print_json(self, *args, **kwargs):
140
        kwargs.setdefault('out', self)
141
        return print_json(*args, **kwargs)
142

    
143
    def print_items(self, *args, **kwargs):
144
        kwargs.setdefault('out', self)
145
        return print_items(*args, **kwargs)
146

    
147
    def ask_user(self, *args, **kwargs):
148
        kwargs.setdefault('user_in', self._in)
149
        kwargs.setdefault('out', self)
150
        return ask_user(*args, **kwargs)
151

    
152
    @DontRaiseKeyError
153
    def _custom_url(self, service):
154
        return self.config.get_cloud(self.cloud, '%s_url' % service)
155

    
156
    @DontRaiseKeyError
157
    def _custom_token(self, service):
158
        return self.config.get_cloud(self.cloud, '%s_token' % service)
159

    
160
    @DontRaiseKeyError
161
    def _custom_type(self, service):
162
        return self.config.get_cloud(self.cloud, '%s_type' % service)
163

    
164
    @DontRaiseKeyError
165
    def _custom_version(self, service):
166
        return self.config.get_cloud(self.cloud, '%s_version' % service)
167

    
168
    def _uuids2usernames(self, uuids):
169
        return self.auth_base.post_user_catalogs(uuids)
170

    
171
    def _usernames2uuids(self, username):
172
        return self.auth_base.post_user_catalogs(displaynames=username)
173

    
174
    def _uuid2username(self, uuid):
175
        return self._uuids2usernames([uuid]).get(uuid, None)
176

    
177
    def _username2uuid(self, username):
178
        return self._usernames2uuids([username]).get(username, None)
179

    
180
    def _set_log_params(self):
181
        try:
182
            self.client.LOG_TOKEN = (
183
                self['config'].get('global', 'log_token').lower() == 'on')
184
        except Exception as e:
185
            log.debug('Failed to read custom log_token setting:'
186
                '%s\n default for log_token is off' % e)
187
        try:
188
            self.client.LOG_DATA = (
189
                self['config'].get('global', 'log_data').lower() == 'on')
190
        except Exception as e:
191
            log.debug('Failed to read custom log_data setting:'
192
                '%s\n default for log_data is off' % e)
193
        try:
194
            self.client.LOG_PID = (
195
                self['config'].get('global', 'log_pid').lower() == 'on')
196
        except Exception as e:
197
            log.debug('Failed to read custom log_pid setting:'
198
                '%s\n default for log_pid is off' % e)
199

    
200
    def _safe_progress_bar(
201
            self, msg, arg='progress_bar', countdown=False, timeout=100):
202
        """Try to get a progress bar, but do not raise errors"""
203
        try:
204
            progress_bar = self.arguments[arg]
205
            progress_bar.file = self._err
206
            gen = progress_bar.get_generator(
207
                msg, countdown=countdown, timeout=timeout)
208
        except Exception:
209
            return (None, None)
210
        return (progress_bar, gen)
211

    
212
    def _safe_progress_bar_finish(self, progress_bar):
213
        try:
214
            progress_bar.finish()
215
        except Exception:
216
            pass
217

    
218
    def __getitem__(self, argterm):
219
        """
220
        :param argterm: (str) the name/label of an argument in self.arguments
221

222
        :returns: the value of the corresponding Argument (not the argument
223
            object)
224

225
        :raises KeyError: if argterm not in self.arguments of this object
226
        """
227
        return self.arguments[argterm].value
228

    
229
    def __setitem__(self, argterm, arg):
230
        """Install an argument as argterm
231
        If argterm points to another argument, the other argument is lost
232

233
        :param argterm: (str)
234

235
        :param arg: (Argument)
236
        """
237
        if not hasattr(self, 'arguments'):
238
            self.arguments = {}
239
        self.arguments[argterm] = arg
240

    
241
    def get_argument_object(self, argterm):
242
        """
243
        :param argterm: (str) the name/label of an argument in self.arguments
244

245
        :returns: the arument object
246

247
        :raises KeyError: if argterm not in self.arguments of this object
248
        """
249
        return self.arguments[argterm]
250

    
251
    def get_argument(self, argterm):
252
        """
253
        :param argterm: (str) the name/label of an argument in self.arguments
254

255
        :returns: the value of the arument object
256

257
        :raises KeyError: if argterm not in self.arguments of this object
258
        """
259
        return self[argterm]
260

    
261

    
262
#  feature classes - inherit them to get special features for your commands
263

    
264

    
265
class OutputFormatArgument(ValueArgument):
266
    """Accepted output formats: json (default)"""
267

    
268
    formats = ('json', )
269

    
270
    def ___init__(self, *args, **kwargs):
271
        super(OutputFormatArgument, self).___init__(*args, **kwargs)
272

    
273
    @property
274
    def value(self):
275
        return getattr(self, '_value', None)
276

    
277
    @value.setter
278
    def value(self, newvalue):
279
        if not newvalue:
280
            self._value = self.default
281
        elif newvalue.lower() in self.formats:
282
            self._value = newvalue.lower
283
        else:
284
            raise CLIInvalidArgument(
285
                'Invalid value %s for argument %s' % (
286
                    newvalue, self.lvalue),
287
                details=['Valid output formats: %s' % ', '.join(self.formats)])
288

    
289

    
290
class _optional_output_cmd(object):
291

    
292
    oo_arguments = dict(
293
        with_output=FlagArgument('show response headers', ('--with-output')),
294
        json_output=FlagArgument(
295
            'show headers in json (DEPRECATED from v0.12,'
296
            '  please use --output-format=json instead)', ('-j', '--json'))
297
    )
298

    
299
    def _optional_output(self, r):
300
        if self['json_output']:
301
            print_json(r, out=self)
302
        elif self['with_output']:
303
            print_items([r] if isinstance(r, dict) else r, out=self)
304

    
305

    
306
class _optional_json(object):
307

    
308
    oj_arguments = dict(
309
        output_format=OutputFormatArgument(
310
            'Show output in chosen output format (%s)' % ', '.join(
311
                OutputFormatArgument.formats),
312
            '--output-format'),
313
        json_output=FlagArgument(
314
            'show output in json (DEPRECATED from v0.12,'
315
            ' please use --output-format instead)', ('-j', '--json'))
316
    )
317

    
318
    def _print(self, output, print_method=print_items, **print_method_kwargs):
319
        if self['json_output'] or self['output_format']:
320
            print_json(output, out=self)
321
        else:
322
            print_method_kwargs.setdefault('out', self)
323
            print_method(output, **print_method_kwargs)
324

    
325

    
326
class _name_filter(object):
327

    
328
    nf_arguments = dict(
329
        name=ValueArgument('filter by name', '--name'),
330
        name_pref=ValueArgument(
331
            'filter by name prefix (case insensitive)', '--name-prefix'),
332
        name_suff=ValueArgument(
333
            'filter by name suffix (case insensitive)', '--name-suffix'),
334
        name_like=ValueArgument(
335
            'print only if name contains this (case insensitive)',
336
            '--name-like')
337
    )
338

    
339
    def _non_exact_name_filter(self, items):
340
        np, ns, nl = self['name_pref'], self['name_suff'], self['name_like']
341
        return [item for item in items if (
342
            (not np) or (item['name'] or '').lower().startswith(
343
                np.lower())) and (
344
            (not ns) or (item['name'] or '').lower().endswith(
345
                ns.lower())) and (
346
            (not nl) or nl.lower() in (item['name'] or '').lower())]
347

    
348
    def _exact_name_filter(self, items):
349
        return filter_dicts_by_dict(items, dict(name=self['name'] or '')) if (
350
            self['name']) else items
351

    
352
    def _filter_by_name(self, items):
353
        return self._non_exact_name_filter(self._exact_name_filter(items))
354

    
355

    
356
class _id_filter(object):
357

    
358
    if_arguments = dict(
359
        id=ValueArgument('filter by id', '--id'),
360
        id_pref=ValueArgument(
361
            'filter by id prefix (case insensitive)', '--id-prefix'),
362
        id_suff=ValueArgument(
363
            'filter by id suffix (case insensitive)', '--id-suffix'),
364
        id_like=ValueArgument(
365
            'print only if id contains this (case insensitive)', '--id-like')
366
    )
367

    
368
    def _non_exact_id_filter(self, items):
369
        np, ns, nl = self['id_pref'], self['id_suff'], self['id_like']
370
        return [item for item in items if (
371
            (not np) or (
372
                '%s' % item['id']).lower().startswith(np.lower())) and (
373
            (not ns) or ('%s' % item['id']).lower().endswith(ns.lower())) and (
374
            (not nl) or nl.lower() in ('%s' % item['id']).lower())]
375

    
376
    def _exact_id_filter(self, items):
377
        return filter_dicts_by_dict(items, dict(id=self['id'])) if (
378
            self['id']) else items
379

    
380
    def _filter_by_id(self, items):
381
        return self._non_exact_id_filter(self._exact_id_filter(items))