Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / commands / errors.py @ 534e7bbb

History | View | Annotate | Download (21.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 traceback import print_stack, print_exc
35

    
36
from kamaki.clients import ClientError
37
from kamaki.cli.errors import CLIError, raiseCLIError, CLISyntaxError
38
from kamaki.cli import _debug, kloger
39
from kamaki.cli.utils import format_size
40

    
41
CLOUDNAME = [
42
    'Note: If you use a named cloud, use its name instead of "default"']
43

    
44

    
45
class generic(object):
46

    
47
    @classmethod
48
    def all(this, foo):
49
        def _raise(self, *args, **kwargs):
50
            try:
51
                return foo(self, *args, **kwargs)
52
            except Exception as e:
53
                if _debug:
54
                    print_stack()
55
                    print_exc(e)
56
                if isinstance(e, CLIError) or isinstance(e, ClientError):
57
                    raiseCLIError(e)
58
                raiseCLIError(e, details=['%s, -d for debug info' % type(e)])
59
        return _raise
60

    
61
    @classmethod
62
    def _connection(this, foo):
63
        def _raise(self, *args, **kwargs):
64
            try:
65
                foo(self, *args, **kwargs)
66
            except ClientError as ce:
67
                ce_msg = ('%s' % ce).lower()
68
                if ce.status == 401:
69
                    raiseCLIError(ce, 'Authorization failed', details=[
70
                        'Make sure a valid token is provided:',
71
                        '  to check if token is valid: /user authenticate',
72
                        '  to set token:',
73
                        '    /config set cloud.default.token <token>',
74
                        '  to get current token:',
75
                        '    /config get cloud.default.token'] + CLOUDNAME)
76
                elif ce.status in range(-12, 200) + [302, 401, 403, 500]:
77
                    raiseCLIError(ce, importance=3, details=[
78
                        'Check if service is up'])
79
                elif ce.status == 404 and 'kamakihttpresponse' in ce_msg:
80
                    client = getattr(self, 'client', None)
81
                    if not client:
82
                        raise
83
                    url = getattr(client, 'base_url', '<empty>')
84
                    msg = 'Invalid service URL %s' % url
85
                    raiseCLIError(ce, msg, details=[
86
                        'Check if authentication URL is correct',
87
                        '  check current URL:',
88
                        '    /config get cloud.default.url',
89
                        '  set new authentication URL:',
90
                        '    /config set cloud.default.url'] + CLOUDNAME)
91
                raise
92
        return _raise
93

    
94

    
95
class user(object):
96

    
97
    _token_details = [
98
        'To check default token: /config get cloud.default.token',
99
        'If set/update a token:',
100
        '*  (permanent):  /config set cloud.default.token <token>',
101
        '*  (temporary):  re-run with <token> parameter'] + CLOUDNAME
102

    
103
    @classmethod
104
    def load(this, foo):
105
        def _raise(self, *args, **kwargs):
106
            r = foo(self, *args, **kwargs)
107
            try:
108
                client = getattr(self, 'client')
109
            except AttributeError as ae:
110
                raiseCLIError(ae, 'Client setup failure', importance=3)
111
            if not getattr(client, 'token', False):
112
                kloger.warning(
113
                    'No permanent token (try:'
114
                    ' kamaki config set cloud.default.token <tkn>)')
115
            if not getattr(client, 'base_url', False):
116
                msg = 'Missing synnefo authentication URL'
117
                raise CLIError(msg, importance=3, details=[
118
                    'Check if authentication URL is correct',
119
                        '  check current URL:',
120
                        '    /config get cloud.default.url',
121
                        '  set new auth. URL:',
122
                        '    /config set cloud.default.url'] + CLOUDNAME)
123
            return r
124
        return _raise
125

    
126
    @classmethod
127
    def authenticate(this, foo):
128
        def _raise(self, *args, **kwargs):
129
            try:
130
                return foo(self, *args, **kwargs)
131
            except ClientError as ce:
132
                if ce.status == 401:
133
                    token = kwargs.get('custom_token', 0) or self.client.token
134
                    msg = (
135
                        'Authorization failed for token %s' % token
136
                    ) if token else 'No token provided',
137
                    details = [] if token else this._token_details
138
                    raiseCLIError(ce, msg, details=details)
139
                raise ce
140
            self._raise = foo
141
        return _raise
142

    
143

    
144
class history(object):
145
    @classmethod
146
    def init(this, foo):
147
        def _raise(self, *args, **kwargs):
148
            r = foo(self, *args, **kwargs)
149
            if not hasattr(self, 'history'):
150
                raise CLIError('Failed to load history', importance=2)
151
            return r
152
        return _raise
153

    
154
    @classmethod
155
    def _get_cmd_ids(this, foo):
156
        def _raise(self, cmd_ids, *args, **kwargs):
157
            if not cmd_ids:
158
                raise CLISyntaxError(
159
                    'Usage: <id1|id1-id2> [id3|id3-id4] ...',
160
                    details=self.__doc__.split('\n'))
161
            return foo(self, cmd_ids, *args, **kwargs)
162
        return _raise
163

    
164

    
165
class cyclades(object):
166
    about_flavor_id = [
167
        'How to pick a valid flavor id:',
168
        '* get a list of flavor ids: /flavor list',
169
        '* details of flavor: /flavor info <flavor id>']
170

    
171
    about_network_id = [
172
        'How to pick a valid network id:',
173
        '* get a list of network ids: /network list',
174
        '* details of network: /network info <network id>']
175

    
176
    @classmethod
177
    def connection(this, foo):
178
        return generic._connection(foo)
179

    
180
    @classmethod
181
    def date(this, foo):
182
        def _raise(self, *args, **kwargs):
183
            try:
184
                return foo(self, *args, **kwargs)
185
            except ClientError as ce:
186
                if ce.status == 400 and 'changes-since' in ('%s' % ce):
187
                    raise CLIError(
188
                        'Incorrect date format for --since',
189
                        details=['Accepted date format: d/m/y'])
190
                raise
191
        return _raise
192

    
193
    @classmethod
194
    def network_id(this, foo):
195
        def _raise(self, *args, **kwargs):
196
            network_id = kwargs.get('network_id', None)
197
            try:
198
                network_id = int(network_id)
199
                return foo(self, *args, **kwargs)
200
            except ValueError as ve:
201
                msg = 'Invalid network id %s ' % network_id
202
                details = ['network id must be a positive integer']
203
                raiseCLIError(ve, msg, details=details, importance=1)
204
            except ClientError as ce:
205
                if network_id and ce.status == 404 and (
206
                    'network' in ('%s' % ce).lower()
207
                ):
208
                    msg = 'No network with id %s found' % network_id,
209
                    raiseCLIError(ce, msg, details=this.about_network_id)
210
                raise
211
        return _raise
212

    
213
    @classmethod
214
    def network_max(this, foo):
215
        def _raise(self, *args, **kwargs):
216
            try:
217
                return foo(self, *args, **kwargs)
218
            except ClientError as ce:
219
                if ce.status == 413:
220
                    msg = 'Cannot create another network',
221
                    details = [
222
                        'Maximum number of networks reached',
223
                        '* to get a list of networks: /network list',
224
                        '* to delete a network: /network delete <net id>']
225
                    raiseCLIError(ce, msg, details=details)
226
                raise
227
        return _raise
228

    
229
    @classmethod
230
    def network_in_use(this, foo):
231
        def _raise(self, *args, **kwargs):
232
            network_id = kwargs.get('network_id', None)
233
            try:
234
                return foo(self, *args, **kwargs)
235
            except ClientError as ce:
236
                if network_id and ce.status in (400, ):
237
                    msg = 'Network with id %s does not exist' % network_id,
238
                    raiseCLIError(ce, msg, details=this.about_network_id)
239
                elif network_id or ce.status in (421, ):
240
                    msg = 'Network with id %s is in use' % network_id,
241
                    raiseCLIError(ce, msg, details=[
242
                        'Disconnect all nics/servers of this network first',
243
                        '* to get nics: /network info %s' % network_id,
244
                        '.  (under "attachments" section)',
245
                        '* to disconnect: /network disconnect <nic id>'])
246
                raise
247
        return _raise
248

    
249
    @classmethod
250
    def flavor_id(this, foo):
251
        def _raise(self, *args, **kwargs):
252
            flavor_id = kwargs.get('flavor_id', None)
253
            try:
254
                flavor_id = int(flavor_id)
255
                return foo(self, *args, **kwargs)
256
            except ValueError as ve:
257
                msg = 'Invalid flavor id %s ' % flavor_id,
258
                details = 'Flavor id must be a positive integer',
259
                raiseCLIError(ve, msg, details=details, importance=1)
260
            except ClientError as ce:
261
                if flavor_id and ce.status == 404 and (
262
                    'flavor' in ('%s' % ce).lower()
263
                ):
264
                        msg = 'No flavor with id %s found' % flavor_id,
265
                        raiseCLIError(ce, msg, details=this.about_flavor_id)
266
                raise
267
        return _raise
268

    
269
    @classmethod
270
    def server_id(this, foo):
271
        def _raise(self, *args, **kwargs):
272
            server_id = kwargs.get('server_id', None)
273
            try:
274
                server_id = int(server_id)
275
                return foo(self, *args, **kwargs)
276
            except ValueError as ve:
277
                msg = 'Invalid virtual server id %s' % server_id,
278
                details = ['id must be a positive integer'],
279
                raiseCLIError(ve, msg, details=details, importance=1)
280
            except ClientError as ce:
281
                err_msg = ('%s' % ce).lower()
282
                if (
283
                    ce.status == 404 and 'server' in err_msg
284
                ) or (
285
                    ce.status == 400 and 'not found' in err_msg
286
                ):
287
                    msg = 'virtual server with id %s not found' % server_id,
288
                    raiseCLIError(ce, msg, details=[
289
                        '* to get ids of all servers: /server list',
290
                        '* to get server details: /server info <server id>'])
291
                raise
292
        return _raise
293

    
294
    @classmethod
295
    def firewall(this, foo):
296
        def _raise(self, *args, **kwargs):
297
            profile = kwargs.get('profile', None)
298
            try:
299
                return foo(self, *args, **kwargs)
300
            except ClientError as ce:
301
                if ce.status == 400 and profile and (
302
                    'firewall' in ('%s' % ce).lower()
303
                ):
304
                    msg = '%s is an invalid firewall profile term' % profile
305
                    raiseCLIError(ce, msg, details=[
306
                        'Try one of the following:',
307
                        '* DISABLED: Shutdown firewall',
308
                        '* ENABLED: Firewall in normal mode',
309
                        '* PROTECTED: Firewall in secure mode'])
310
                raise
311
        return _raise
312

    
313
    @classmethod
314
    def nic_id(this, foo):
315
        def _raise(self, *args, **kwargs):
316
            try:
317
                return foo(self, *args, **kwargs)
318
            except ClientError as ce:
319
                nic_id = kwargs.get('nic_id', None)
320
                if nic_id and ce.status == 404 and (
321
                    'network interface' in ('%s' % ce).lower()
322
                ):
323
                    server_id = kwargs.get('server_id', '<no server>')
324
                    err_msg = 'No nic %s on virtual server with id %s' % (
325
                        nic_id,
326
                        server_id)
327
                    raiseCLIError(ce, err_msg, details=[
328
                        '* check v. server with id %s: /server info %s' % (
329
                            server_id,
330
                            server_id),
331
                        '* list nics for v. server with id %s:' % server_id,
332
                        '      /server addr %s' % server_id])
333
                raise
334
        return _raise
335

    
336
    @classmethod
337
    def nic_format(this, foo):
338
        def _raise(self, *args, **kwargs):
339
            try:
340
                return foo(self, *args, **kwargs)
341
            except IndexError as ie:
342
                nic_id = kwargs.get('nic_id', None)
343
                msg = 'Invalid format for network interface (nic) %s' % nic_id
344
                raiseCLIError(ie, msg, importance=1, details=[
345
                    'nid_id format: nic-<server id>-<nic id>',
346
                    '* get nics of a network: /network info <net id>',
347
                    '    (listed the "attachments" section)'])
348
        return _raise
349

    
350
    @classmethod
351
    def metadata(this, foo):
352
        def _raise(self, *args, **kwargs):
353
            key = kwargs.get('key', None)
354
            try:
355
                foo(self, *args, **kwargs)
356
            except ClientError as ce:
357
                if key and ce.status == 404 and (
358
                    'metadata' in ('%s' % ce).lower()
359
                ):
360
                        raiseCLIError(
361
                            ce, 'No v. server metadata with key %s' % key)
362
                raise
363
        return _raise
364

    
365

    
366
class plankton(object):
367

    
368
    about_image_id = [
369
        'How to pick a suitable image:',
370
        '* get a list of image ids: /image list',
371
        '* details of image: /image meta <image id>']
372

    
373
    @classmethod
374
    def connection(this, foo):
375
        return generic._connection(foo)
376

    
377
    @classmethod
378
    def id(this, foo):
379
        def _raise(self, *args, **kwargs):
380
            image_id = kwargs.get('image_id', None)
381
            try:
382
                foo(self, *args, **kwargs)
383
            except ClientError as ce:
384
                if image_id and (
385
                    ce.status == 404
386
                    or (
387
                        ce.status == 400
388
                        and 'image not found' in ('%s' % ce).lower())
389
                    or ce.status == 411
390
                ):
391
                        msg = 'No image with id %s found' % image_id
392
                        raiseCLIError(ce, msg, details=this.about_image_id)
393
                raise
394
        return _raise
395

    
396
    @classmethod
397
    def metadata(this, foo):
398
        def _raise(self, *args, **kwargs):
399
            key = kwargs.get('key', None)
400
            try:
401
                return foo(self, *args, **kwargs)
402
            except ClientError as ce:
403
                ce_msg = ('%s' % ce).lower()
404
                if ce.status == 404 or (
405
                        ce.status == 400 and 'metadata' in ce_msg):
406
                    msg = 'No properties with key %s in this image' % key
407
                    raiseCLIError(ce, msg)
408
                raise
409
        return _raise
410

    
411

    
412
class pithos(object):
413
    container_howto = [
414
        'To specify a container:',
415
        '  1. --container=<container> (temporary, overrides all)',
416
        '  2. Use the container:path format (temporary, overrides 3)',
417
        '  3. Set pithos_container variable (permanent)',
418
        '     /config set pithos_container <container>',
419
        'For a list of containers: /file list']
420

    
421
    @classmethod
422
    def connection(this, foo):
423
        return generic._connection(foo)
424

    
425
    @classmethod
426
    def account(this, foo):
427
        def _raise(self, *args, **kwargs):
428
            try:
429
                return foo(self, *args, **kwargs)
430
            except ClientError as ce:
431
                if ce.status == 403:
432
                    raiseCLIError(
433
                        ce,
434
                        'Invalid account credentials for this operation',
435
                        details=['Check user account settings'])
436
                raise
437
        return _raise
438

    
439
    @classmethod
440
    def quota(this, foo):
441
        def _raise(self, *args, **kwargs):
442
            try:
443
                return foo(self, *args, **kwargs)
444
            except ClientError as ce:
445
                if ce.status == 413:
446
                    raiseCLIError(ce, 'User quota exceeded', details=[
447
                        '* get quotas:',
448
                        '  * upper total limit:      /file quota',
449
                        '  * container limit:',
450
                        '    /file containerlimit get <container>',
451
                        '* set a higher container limit:',
452
                        '    /file containerlimit set <limit> <container>'])
453
                raise
454
        return _raise
455

    
456
    @classmethod
457
    def container(this, foo):
458
        def _raise(self, *args, **kwargs):
459
            dst_cont = kwargs.get('dst_cont', None)
460
            try:
461
                return foo(self, *args, **kwargs)
462
            except ClientError as ce:
463
                if ce.status == 404 and 'container' in ('%s' % ce).lower():
464
                        cont = ('%s or %s' % (
465
                            self.container,
466
                            dst_cont)) if dst_cont else self.container
467
                        msg = 'Is container %s in current account?' % (cont),
468
                        raiseCLIError(ce, msg, details=this.container_howto)
469
                raise
470
        return _raise
471

    
472
    @classmethod
473
    def local_path(this, foo):
474
        def _raise(self, *args, **kwargs):
475
            local_path = kwargs.get('local_path', '<None>')
476
            try:
477
                return foo(self, *args, **kwargs)
478
            except IOError as ioe:
479
                msg = 'Failed to access file %s' % local_path,
480
                raiseCLIError(ioe, msg, importance=2)
481
        return _raise
482

    
483
    @classmethod
484
    def object_path(this, foo):
485
        def _raise(self, *args, **kwargs):
486
            try:
487
                return foo(self, *args, **kwargs)
488
            except ClientError as ce:
489
                err_msg = ('%s' % ce).lower()
490
                if (
491
                    ce.status == 404 or ce.status == 500
492
                ) and 'object' in err_msg and 'not' in err_msg:
493
                    msg = 'No object %s in container %s' % (
494
                        self.path,
495
                        self.container)
496
                    raiseCLIError(ce, msg, details=this.container_howto)
497
                raise
498
        return _raise
499

    
500
    @classmethod
501
    def object_size(this, foo):
502
        def _raise(self, *args, **kwargs):
503
            size = kwargs.get('size', None)
504
            start = kwargs.get('start', 0)
505
            end = kwargs.get('end', 0)
506
            if size:
507
                try:
508
                    size = int(size)
509
                except ValueError as ve:
510
                    msg = 'Invalid file size %s ' % size
511
                    details = ['size must be a positive integer']
512
                    raiseCLIError(ve, msg, details=details, importance=1)
513
            else:
514
                try:
515
                    start = int(start)
516
                except ValueError as e:
517
                    msg = 'Invalid start value %s in range' % start,
518
                    details = ['size must be a positive integer'],
519
                    raiseCLIError(e, msg, details=details, importance=1)
520
                try:
521
                    end = int(end)
522
                except ValueError as e:
523
                    msg = 'Invalid end value %s in range' % end
524
                    details = ['size must be a positive integer']
525
                    raiseCLIError(e, msg, details=details, importance=1)
526
                if start > end:
527
                    raiseCLIError(
528
                        'Invalid range %s-%s' % (start, end),
529
                        details=['size must be a positive integer'],
530
                        importance=1)
531
                size = end - start
532
            try:
533
                return foo(self, *args, **kwargs)
534
            except ClientError as ce:
535
                err_msg = ('%s' % ce).lower()
536
                expected = 'object length is smaller than range length'
537
                if size and (
538
                    ce.status == 416 or (
539
                        ce.status == 400 and expected in err_msg)):
540
                    raiseCLIError(ce, 'Remote object %s:%s <= %s %s' % (
541
                        self.container, self.path, format_size(size),
542
                        ('(%sB)' % size) if size >= 1024 else ''))
543
                raise
544
        return _raise