Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / __init__.py @ 27d3b17d

History | View | Annotate | Download (12.8 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)
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(func):
46
    def wrap(*args, **kwargs):
47
        try:
48
            return func(*args, **kwargs)
49
        except KeyError:
50
            return None
51
    return wrap
52

    
53

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

    
62

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

    
74

    
75
class _command_init(object):
76

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

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

    
112
    def write(self, s):
113
        self._out.write('%s' % s)
114
        self._out.flush()
115

    
116
    def writeln(self, s=''):
117
        self.write('%s\n' % s)
118

    
119
    def error(self, s=''):
120
        self._err.write('%s\n' % s)
121
        self._err.flush()
122

    
123
    def print_list(self, *args, **kwargs):
124
        kwargs.setdefault('out', self._out)
125
        return print_list(*args, **kwargs)
126

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

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

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

    
139
    def ask_user(self, *args, **kwargs):
140
        kwargs.setdefault('user_in', self._in)
141
        kwargs.setdefault('out', self._out)
142
        return ask_user(*args, **kwargs)
143

    
144
    @DontRaiseKeyError
145
    def _custom_url(self, service):
146
        return self.config.get_cloud(self.cloud, '%s_url' % service)
147

    
148
    @DontRaiseKeyError
149
    def _custom_token(self, service):
150
        return self.config.get_cloud(self.cloud, '%s_token' % service)
151

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

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

    
160
    def _uuids2usernames(self, uuids):
161
        return self.auth_base.post_user_catalogs(uuids)
162

    
163
    def _usernames2uuids(self, username):
164
        return self.auth_base.post_user_catalogs(displaynames=username)
165

    
166
    def _uuid2username(self, uuid):
167
        return self._uuids2usernames([uuid]).get(uuid, None)
168

    
169
    def _username2uuid(self, username):
170
        return self._usernames2uuids([username]).get(username, None)
171

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

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

    
204
    def _safe_progress_bar_finish(self, progress_bar):
205
        try:
206
            progress_bar.finish()
207
        except Exception:
208
            pass
209

    
210
    def __getitem__(self, argterm):
211
        """
212
        :param argterm: (str) the name/label of an argument in self.arguments
213

214
        :returns: the value of the corresponding Argument (not the argument
215
            object)
216

217
        :raises KeyError: if argterm not in self.arguments of this object
218
        """
219
        return self.arguments[argterm].value
220

    
221
    def __setitem__(self, argterm, arg):
222
        """Install an argument as argterm
223
        If argterm points to another argument, the other argument is lost
224

225
        :param argterm: (str)
226

227
        :param arg: (Argument)
228
        """
229
        if not hasattr(self, 'arguments'):
230
            self.arguments = {}
231
        self.arguments[argterm] = arg
232

    
233
    def get_argument_object(self, argterm):
234
        """
235
        :param argterm: (str) the name/label of an argument in self.arguments
236

237
        :returns: the arument object
238

239
        :raises KeyError: if argterm not in self.arguments of this object
240
        """
241
        return self.arguments[argterm]
242

    
243
    def get_argument(self, argterm):
244
        """
245
        :param argterm: (str) the name/label of an argument in self.arguments
246

247
        :returns: the value of the arument object
248

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

    
253

    
254
#  feature classes - inherit them to get special features for your commands
255

    
256

    
257
class OutputFormatArgument(ValueArgument):
258
    """Accepted output formats: json (default)"""
259

    
260
    formats = ('json', )
261

    
262
    def ___init__(self, *args, **kwargs):
263
        super(OutputFormatArgument, self).___init__(*args, **kwargs)
264

    
265
    @property
266
    def value(self):
267
        return getattr(self, '_value', None)
268

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

    
281

    
282
class _optional_output_cmd(object):
283

    
284
    oo_arguments = dict(
285
        with_output=FlagArgument('show response headers', ('--with-output')),
286
        json_output=FlagArgument(
287
            'show headers in json (DEPRECATED from v0.12,'
288
            '  please use --output-format=json instead)', ('-j', '--json'))
289
    )
290

    
291
    def _optional_output(self, r):
292
        if self['json_output']:
293
            print_json(r, out=self._out)
294
        elif self['with_output']:
295
            print_items([r] if isinstance(r, dict) else r, out=self._out)
296

    
297

    
298
class _optional_json(object):
299

    
300
    oj_arguments = dict(
301
        output_format=OutputFormatArgument(
302
            'Show output in chosen output format (%s)' % ', '.join(
303
                OutputFormatArgument.formats),
304
            '--output-format'),
305
        json_output=FlagArgument(
306
            'show output in json (DEPRECATED from v0.12,'
307
            ' please use --output-format instead)', ('-j', '--json'))
308
    )
309

    
310
    def _print(self, output, print_method=print_items, **print_method_kwargs):
311
        if self['json_output'] or self['output_format']:
312
            print_json(output, out=self._out)
313
        else:
314
            print_method_kwargs.setdefault('out', self._out)
315
            print_method(output, **print_method_kwargs)
316

    
317

    
318
class _name_filter(object):
319

    
320
    nf_arguments = dict(
321
        name=ValueArgument('filter by name', '--name'),
322
        name_pref=ValueArgument(
323
            'filter by name prefix (case insensitive)', '--name-prefix'),
324
        name_suff=ValueArgument(
325
            'filter by name suffix (case insensitive)', '--name-suffix'),
326
        name_like=ValueArgument(
327
            'print only if name contains this (case insensitive)',
328
            '--name-like')
329
    )
330

    
331
    def _non_exact_name_filter(self, items):
332
        np, ns, nl = self['name_pref'], self['name_suff'], self['name_like']
333
        return [item for item in items if (
334
            (not np) or (item['name'] or '').lower().startswith(
335
                np.lower())) and (
336
            (not ns) or (item['name'] or '').lower().endswith(
337
                ns.lower())) and (
338
            (not nl) or nl.lower() in (item['name'] or '').lower())]
339

    
340
    def _exact_name_filter(self, items):
341
        return filter_dicts_by_dict(items, dict(name=self['name'] or '')) if (
342
            self['name']) else items
343

    
344
    def _filter_by_name(self, items):
345
        return self._non_exact_name_filter(self._exact_name_filter(items))
346

    
347

    
348
class _id_filter(object):
349

    
350
    if_arguments = dict(
351
        id=ValueArgument('filter by id', '--id'),
352
        id_pref=ValueArgument(
353
            'filter by id prefix (case insensitive)', '--id-prefix'),
354
        id_suff=ValueArgument(
355
            'filter by id suffix (case insensitive)', '--id-suffix'),
356
        id_like=ValueArgument(
357
            'print only if id contains this (case insensitive)', '--id-like')
358
    )
359

    
360
    def _non_exact_id_filter(self, items):
361
        np, ns, nl = self['id_pref'], self['id_suff'], self['id_like']
362
        return [item for item in items if (
363
            (not np) or (
364
                '%s' % item['id']).lower().startswith(np.lower())) and (
365
            (not ns) or ('%s' % item['id']).lower().endswith(ns.lower())) and (
366
            (not nl) or nl.lower() in ('%s' % item['id']).lower())]
367

    
368
    def _exact_id_filter(self, items):
369
        return filter_dicts_by_dict(items, dict(id=self['id'])) if (
370
            self['id']) else items
371

    
372
    def _filter_by_id(self, items):
373
        return self._non_exact_id_filter(self._exact_id_filter(items))