Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / __init__.py @ fd9457bd

History | View | Annotate | Download (13 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
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.getreader('utf-8')(_out or stdout)
93
        self._err = codecs.getreader('utf-8')(_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
    def write(self, s):
118
        self._out.write('%s' % s)
119
        self._out.flush()
120

    
121
    def writeln(self, s=''):
122
        self.write('%s\n' % s)
123

    
124
    def error(self, s=''):
125
        self._err.write('%s\n' % s)
126
        self._err.flush()
127

    
128
    def print_list(self, *args, **kwargs):
129
        kwargs.setdefault('out', self._out)
130
        return print_list(*args, **kwargs)
131

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

    
136
    def print_json(self, *args, **kwargs):
137
        kwargs.setdefault('out', self._out)
138
        return print_json(*args, **kwargs)
139

    
140
    def print_items(self, *args, **kwargs):
141
        kwargs.setdefault('out', self._out)
142
        return print_items(*args, **kwargs)
143

    
144
    def ask_user(self, *args, **kwargs):
145
        kwargs.setdefault('user_in', self._in)
146
        kwargs.setdefault('out', self._out)
147
        return ask_user(*args, **kwargs)
148

    
149
    @DontRaiseKeyError
150
    def _custom_url(self, service):
151
        return self.config.get_cloud(self.cloud, '%s_url' % service)
152

    
153
    @DontRaiseKeyError
154
    def _custom_token(self, service):
155
        return self.config.get_cloud(self.cloud, '%s_token' % service)
156

    
157
    @DontRaiseKeyError
158
    def _custom_type(self, service):
159
        return self.config.get_cloud(self.cloud, '%s_type' % service)
160

    
161
    @DontRaiseKeyError
162
    def _custom_version(self, service):
163
        return self.config.get_cloud(self.cloud, '%s_version' % service)
164

    
165
    def _uuids2usernames(self, uuids):
166
        return self.auth_base.post_user_catalogs(uuids)
167

    
168
    def _usernames2uuids(self, username):
169
        return self.auth_base.post_user_catalogs(displaynames=username)
170

    
171
    def _uuid2username(self, uuid):
172
        return self._uuids2usernames([uuid]).get(uuid, None)
173

    
174
    def _username2uuid(self, username):
175
        return self._usernames2uuids([username]).get(username, None)
176

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

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

    
209
    def _safe_progress_bar_finish(self, progress_bar):
210
        try:
211
            progress_bar.finish()
212
        except Exception:
213
            pass
214

    
215
    def __getitem__(self, argterm):
216
        """
217
        :param argterm: (str) the name/label of an argument in self.arguments
218

219
        :returns: the value of the corresponding Argument (not the argument
220
            object)
221

222
        :raises KeyError: if argterm not in self.arguments of this object
223
        """
224
        return self.arguments[argterm].value
225

    
226
    def __setitem__(self, argterm, arg):
227
        """Install an argument as argterm
228
        If argterm points to another argument, the other argument is lost
229

230
        :param argterm: (str)
231

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

    
238
    def get_argument_object(self, argterm):
239
        """
240
        :param argterm: (str) the name/label of an argument in self.arguments
241

242
        :returns: the arument object
243

244
        :raises KeyError: if argterm not in self.arguments of this object
245
        """
246
        return self.arguments[argterm]
247

    
248
    def get_argument(self, argterm):
249
        """
250
        :param argterm: (str) the name/label of an argument in self.arguments
251

252
        :returns: the value of the arument object
253

254
        :raises KeyError: if argterm not in self.arguments of this object
255
        """
256
        return self[argterm]
257

    
258

    
259
#  feature classes - inherit them to get special features for your commands
260

    
261

    
262
class OutputFormatArgument(ValueArgument):
263
    """Accepted output formats: json (default)"""
264

    
265
    formats = ('json', )
266

    
267
    def ___init__(self, *args, **kwargs):
268
        super(OutputFormatArgument, self).___init__(*args, **kwargs)
269

    
270
    @property
271
    def value(self):
272
        return getattr(self, '_value', None)
273

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

    
286

    
287
class _optional_output_cmd(object):
288

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

    
296
    def _optional_output(self, r):
297
        if self['json_output']:
298
            print_json(r, out=self._out)
299
        elif self['with_output']:
300
            print_items([r] if isinstance(r, dict) else r, out=self._out)
301

    
302

    
303
class _optional_json(object):
304

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

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

    
322

    
323
class _name_filter(object):
324

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

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

    
345
    def _exact_name_filter(self, items):
346
        return filter_dicts_by_dict(items, dict(name=self['name'] or '')) if (
347
            self['name']) else items
348

    
349
    def _filter_by_name(self, items):
350
        return self._non_exact_name_filter(self._exact_name_filter(items))
351

    
352

    
353
class _id_filter(object):
354

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

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

    
373
    def _exact_id_filter(self, items):
374
        return filter_dicts_by_dict(items, dict(id=self['id'])) if (
375
            self['id']) else items
376

    
377
    def _filter_by_id(self, items):
378
        return self._non_exact_id_filter(self._exact_id_filter(items))