Statistics
| Branch: | Tag: | Revision:

root / kamaki / cli / errors.py @ de73876b

History | View | Annotate | Download (4.8 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
import logging
35

    
36
sendlog = logging.getLogger('clients.send')
37
recvlog = logging.getLogger('clients.recv')
38

    
39

    
40
class CLIError(Exception):
41

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

    
58

    
59
class CLISyntaxError(CLIError):
60
    def __init__(self, message='Syntax Error', details=[], importance=1):
61
        super(CLISyntaxError, self).__init__(message, details, importance)
62

    
63

    
64
class CLIUnknownCommand(CLIError):
65
    def __init__(self, message='Unknown Command', details=[], importance=1):
66
        super(CLIUnknownCommand, self).__init__(message, details, importance)
67

    
68

    
69
class CLICmdSpecError(CLIError):
70
    def __init__(
71
        self,
72
        message='Command Specification Error',
73
        details=[],
74
        importance=0):
75
        super(CLICmdSpecError, self).__init__(message, details, importance)
76

    
77

    
78
class CLICmdIncompleteError(CLICmdSpecError):
79
    def __init__(
80
        self,
81
        message='Incomplete Command Error',
82
        details=[],
83
        importance=1):
84
        super(CLICmdSpecError, self).__init__(message, details, importance)
85

    
86

    
87
def raiseCLIError(err, message='', importance=0, details=[]):
88
    """
89
    :param err: (Exception) the original error message, if None, a new
90
        CLIError is born which is conceptually bind to raiser
91

92
    :param message: (str) a custom error message that overrides err's
93

94
    :param importance: (int) instruction to called application (e.g. for
95
        coloring printed error messages)
96

97
    :param details: (list) various information on the error
98

99
    :raises CLIError: it is the purpose of this method
100
    """
101
    from traceback import format_stack
102

    
103
    stack = ['%s' % type(err)] if err else ['<kamaki.cli.errors.CLIError>']
104
    stack += format_stack()
105
    try:
106
        stack = [e for e in stack if e != stack[1]]
107
    except KeyError:
108
        recvlog.debug('\n   < '.join(stack))
109

    
110
    details = ['%s' % details] if not isinstance(details, list)\
111
        else list(details)
112
    details += getattr(err, 'details', [])
113

    
114
    if err:
115
        origerr = '%s' % err
116
        origerr = origerr if origerr else '%s' % type(err)
117
    else:
118
        origerr = stack[0]
119

    
120
    message = unicode(message) if message else unicode(origerr)
121

    
122
    try:
123
        status = err.status or err.errno
124
    except AttributeError:
125
        status = None
126

    
127
    if origerr not in details + [message]:
128
        details.append(origerr)
129

    
130
    message += '' if message and message[-1] == '\n' else '\n'
131
    if status:
132
        message = '(%s) %s' % (err.status, message)
133
        try:
134
            status = int(err.status)
135
        except ValueError:
136
            raise CLIError(message, details, importance)
137
        importance = importance if importance else status // 100
138
    importance = getattr(err, 'importance', importance)
139
    raise CLIError(message, details, importance)