Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / errors.py @ 8cec3671

History | View | Annotate | Download (5.5 kB)

1
# Copyright 2011 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.
33

    
34
from kamaki.cli.logger import get_logger
35

    
36
log = get_logger('kamaki.cli')
37

    
38

    
39
class CLIError(Exception):
40

    
41
    def __init__(self, message, details=[], importance=0):
42
        """
43
        @message is the main message of the Error
44
        @detauls is a list of previous errors
45
        @importance of the output for the user
46
            Suggested values: 0, 1, 2, 3
47
        """
48
        message += '' if message and message[-1] == '\n' else '\n'
49
        super(CLIError, self).__init__(message)
50
        self.details = list(details) if isinstance(details, list)\
51
            else [] if details is None else ['%s' % details]
52
        try:
53
            self.importance = int(importance)
54
        except ValueError:
55
            self.importance = 0
56

    
57

    
58
class CLIBaseUrlError(CLIError):
59
    def __init__(self, message='', details=[], importance=2, service=None):
60
        message = message or 'No url for %s' % service.lower()
61
        details = details or [
62
            'Two options to resolve this:',
63
            'A. (recommended) Let kamaki discover the endpoint URLs for all',
64
            'services by setting a single Authentication URL:',
65
            '  /config set auth_url <AUTH_URL>',
66
            'B. (advanced users) Explicitly set a valid %s endpoint URL' % (
67
                service.upper()),
68
            'Note: auth_url option has a higher priority, so delete it to',
69
            'make that work',
70
            '  /config delete auth_url',
71
            '  /config set %s.url <%s_URL>' % (service, service.upper())]
72
        super(CLIBaseUrlError, self).__init__(message, details, importance)
73

    
74

    
75
class CLISyntaxError(CLIError):
76
    def __init__(self, message='Syntax Error', details=[], importance=1):
77
        super(CLISyntaxError, self).__init__(message, details, importance)
78

    
79

    
80
class CLIUnknownCommand(CLIError):
81
    def __init__(self, message='Unknown Command', details=[], importance=1):
82
        super(CLIUnknownCommand, self).__init__(message, details, importance)
83

    
84

    
85
class CLICmdSpecError(CLIError):
86
    def __init__(
87
            self, message='Command Specification Error',
88
            details=[], importance=0):
89
        super(CLICmdSpecError, self).__init__(message, details, importance)
90

    
91

    
92
class CLICmdIncompleteError(CLICmdSpecError):
93
    def __init__(
94
            self, message='Incomplete Command Error',
95
            details=[], importance=1):
96
        super(CLICmdSpecError, self).__init__(message, details, importance)
97

    
98

    
99
def raiseCLIError(err, message='', importance=0, details=[]):
100
    """
101
    :param err: (Exception) the original error message, if None, a new
102
        CLIError is born which is conceptually bind to raiser
103

104
    :param message: (str) a custom error message that overrides err's
105

106
    :param importance: (int) instruction to called application (e.g. for
107
        coloring printed error messages)
108

109
    :param details: (list) various information on the error
110

111
    :raises CLIError: it is the purpose of this method
112
    """
113
    from traceback import format_stack
114

    
115
    stack = ['%s' % type(err)] if err else ['<kamaki.cli.errors.CLIError>']
116
    stack += format_stack()
117
    try:
118
        stack = [e for e in stack if e != stack[1]]
119
    except KeyError:
120
        log.debug('\n   < '.join(stack))
121

    
122
    details = ['%s' % details] if not isinstance(details, list)\
123
        else list(details)
124
    details += getattr(err, 'details', [])
125

    
126
    if err:
127
        origerr = '%s' % err
128
        origerr = origerr if origerr else '%s' % type(err)
129
    else:
130
        origerr = stack[0]
131

    
132
    message = '%s' % (message if message else origerr)
133

    
134
    try:
135
        status = err.status or err.errno
136
    except AttributeError:
137
        status = None
138

    
139
    if origerr not in details + [message]:
140
        details.append(origerr)
141

    
142
    message += '' if message and message[-1] == '\n' else '\n'
143
    if status:
144
        message = '(%s) %s' % (err.status, message)
145
        try:
146
            status = int(err.status)
147
        except ValueError:
148
            raise CLIError(message, details, importance)
149
        importance = importance if importance else status // 100
150
    importance = getattr(err, 'importance', importance)
151
    raise CLIError(message, details, importance)