__init__.py 9.79 KB
Newer Older
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.command

34
from kamaki.cli.logger import get_logger
35
36
from kamaki.cli.utils import print_json, print_items, filter_dicts_by_dict
from kamaki.cli.argument import FlagArgument, ValueArgument
37

38
log = get_logger(__name__)
39

Stavros Sachtouris's avatar
Stavros Sachtouris committed
40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def DontRaiseKeyError(foo):
    def wrap(*args, **kwargs):
        try:
            return foo(*args, **kwargs)
        except KeyError:
            return None
    return wrap


def addLogSettings(foo):
    def wrap(self, *args, **kwargs):
        try:
            return foo(self, *args, **kwargs)
        finally:
            self._set_log_params()
            self._update_max_threads
    return wrap


60
class _command_init(object):
61

62
    def __init__(self, arguments={}, auth_base=None, cloud=None):
63
64
        if hasattr(self, 'arguments'):
            arguments.update(self.arguments)
65
66
        if isinstance(self, _optional_output_cmd):
            arguments.update(self.oo_arguments)
67
68
        if isinstance(self, _optional_json):
            arguments.update(self.oj_arguments)
69
70
71
72
        if isinstance(self, _name_filter):
            arguments.update(self.nf_arguments)
        if isinstance(self, _id_filter):
            arguments.update(self.if_arguments)
73
74
75
76
        try:
            arguments.update(self.wait_arguments)
        except AttributeError:
            pass
77
        self.arguments = dict(arguments)
78
        try:
79
            self.config = self['config']
80
81
        except KeyError:
            pass
82
83
        self.auth_base = auth_base or getattr(self, 'auth_base', None)
        self.cloud = cloud or getattr(self, 'cloud', None)
84

85
86
    @DontRaiseKeyError
    def _custom_url(self, service):
87
        return self.config.get_cloud(self.cloud, '%s_url' % service)
88
89
90

    @DontRaiseKeyError
    def _custom_token(self, service):
91
        return self.config.get_cloud(self.cloud, '%s_token' % service)
92
93
94

    @DontRaiseKeyError
    def _custom_type(self, service):
95
        return self.config.get_cloud(self.cloud, '%s_type' % service)
96
97
98

    @DontRaiseKeyError
    def _custom_version(self, service):
99
        return self.config.get_cloud(self.cloud, '%s_version' % service)
100

101
102
103
104
105
106
107
    def _uuids2usernames(self, uuids):
        return self.auth_base.post_user_catalogs(uuids).json['uuid_catalog']

    def _usernames2uuids(self, username):
        return self.auth_base.post_user_catalogs(
            displaynames=username).json['displayname_catalog']

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
117
118
119
120
121
122
            self.client.LOG_TOKEN = (
                self['config'].get_global('log_token').lower() == 'on')
        except Exception as e:
            log.debug('Failed to read custom log_token setting:'
                '%s\n default for log_token is off' % e)
        try:
            self.client.LOG_DATA = (
123
                self['config'].get_global('log_data').lower() == 'on')
124
        except Exception as e:
125
126
127
128
129
130
131
132
            log.debug('Failed to read custom log_data setting:'
                '%s\n default for log_data is off' % e)
        try:
            self.client.LOG_PID = (
                self['config'].get_global('log_pid').lower() == 'on')
        except Exception as e:
            log.debug('Failed to read custom log_pid setting:'
                '%s\n default for log_pid is off' % e)
133
134

    def _update_max_threads(self):
135
        if getattr(self, 'client', None):
136
            max_threads = int(self['config'].get_global('max_threads'))
137
            assert max_threads > 0, 'invalid max_threads config option'
138
            self.client.MAX_THREADS = max_threads
139

Stavros Sachtouris's avatar
Stavros Sachtouris committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    def _safe_progress_bar(self, msg, arg='progress_bar'):
        """Try to get a progress bar, but do not raise errors"""
        try:
            progress_bar = self.arguments[arg]
            gen = progress_bar.get_generator(msg)
        except Exception:
            return (None, None)
        return (progress_bar, gen)

    def _safe_progress_bar_finish(self, progress_bar):
        try:
            progress_bar.finish()
        except Exception:
            pass

155
156
157
158
    def __getitem__(self, argterm):
        """
        :param argterm: (str) the name/label of an argument in self.arguments

159
160
        :returns: the value of the corresponding Argument (not the argument
            object)
161
162
163

        :raises KeyError: if argterm not in self.arguments of this object
        """
164
        return self.arguments[argterm].value
165
166
167
168
169
170
171
172
173
174
175
176
177

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

        :param argterm: (str)

        :param arg: (Argument)
        """
        if not hasattr(self, 'arguments'):
            self.arguments = {}
        self.arguments[argterm] = arg

178
179
180
181
182
183
184
185
186
187
    def get_argument_object(self, argterm):
        """
        :param argterm: (str) the name/label of an argument in self.arguments

        :returns: the arument object

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

188
    def get_argument(self, argterm):
189
190
191
192
193
194
195
        """
        :param argterm: (str) the name/label of an argument in self.arguments

        :returns: the value of the arument object

        :raises KeyError: if argterm not in self.arguments of this object
        """
196
        return self[argterm]
197
198


199
200
201
#  feature classes - inherit them to get special features for your commands


202
203
204
205
206
207
208
209
210
211
212
213
class _optional_output_cmd(object):

    oo_arguments = dict(
        with_output=FlagArgument('show response headers', ('--with-output')),
        json_output=FlagArgument('show headers in json', ('-j', '--json'))
    )

    def _optional_output(self, r):
        if self['json_output']:
            print_json(r)
        elif self['with_output']:
            print_items([r] if isinstance(r, dict) else r)
214
215
216
217
218
219
220
221
222
223
224
225
226


class _optional_json(object):

    oj_arguments = dict(
        json_output=FlagArgument('show headers in json', ('-j', '--json'))
    )

    def _print(self, output, print_method=print_items, **print_method_kwargs):
        if self['json_output']:
            print_json(output)
        else:
            print_method(output, **print_method_kwargs)
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283


class _name_filter(object):

    nf_arguments = dict(
        name=ValueArgument('filter by name', '--name'),
        name_pref=ValueArgument(
            'filter by name prefix (case insensitive)', '--name-prefix'),
        name_suff=ValueArgument(
            'filter by name suffix (case insensitive)', '--name-suffix'),
        name_like=ValueArgument(
            'print only if name contains this (case insensitive)',
            '--name-like')
    )

    def _non_exact_name_filter(self, items):
        np, ns, nl = self['name_pref'], self['name_suff'], self['name_like']
        return [item for item in items if (
            (not np) or item['name'].lower().startswith(np.lower())) and (
            (not ns) or item['name'].lower().endswith(ns.lower())) and (
            (not nl) or nl.lower() in item['name'].lower())]

    def _exact_name_filter(self, items):
        return filter_dicts_by_dict(items, dict(name=self['name'])) if (
            self['name']) else items

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


class _id_filter(object):

    if_arguments = dict(
        id=ValueArgument('filter by id', '--id'),
        id_pref=ValueArgument(
            'filter by id prefix (case insensitive)', '--id-prefix'),
        id_suff=ValueArgument(
            'filter by id suffix (case insensitive)', '--id-suffix'),
        id_like=ValueArgument(
            'print only if id contains this (case insensitive)',
            '--id-like')
    )

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

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

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