Merge branch 'release-0.10'
[kamaki] / kamaki / cli / errors.py
1 # Copyright 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.
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         @defaults 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 CLIUnimplemented(CLIError):
59     def __init__(
60             self,
61             message='I \'M SORRY, DAVE.\nI \'M AFRAID I CAN\'T DO THAT.',
62             details=[
63                 '      _        |',
64                 '   _-- --_     |',
65                 '  --     --    |',
66                 ' --   .   --   |',
67                 ' -_       _-   |',
68                 '   -_   _-     |',
69                 '      -        |'],
70             importance=3):
71         super(CLIUnimplemented, self).__init__(message, details, importance)
72
73
74 class CLIBaseUrlError(CLIError):
75     def __init__(self, message='', details=[], importance=2, service=None):
76         message = message or 'No URL for %s' % service.lower()
77         details = details or [
78             'Two options to resolve this:',
79             '(Use the correct cloud name, instead of "default")',
80             'A. (recommended) Let kamaki discover the endpoint URLs for all',
81
82             'services by setting a single Authentication URL and token:',
83             '  /config set cloud.default.url <AUTH_URL>',
84             '  /config set cloud.default.token <t0k3n>',
85             'B. (advanced users) Explicitly set a valid %s endpoint URL' % (
86                 service.upper()),
87             'Note: URL option has a higher priority, so delete it to',
88             'make that work',
89             '  /config delete cloud.default.url',
90             '  /config set cloud.%s.url <%s_URL>' % (
91                 service, service.upper())]
92         super(CLIBaseUrlError, self).__init__(message, details, importance)
93
94
95 class CLISyntaxError(CLIError):
96     def __init__(self, message='Syntax Error', details=[], importance=1):
97         super(CLISyntaxError, self).__init__(message, details, importance)
98
99
100 class CLIUnknownCommand(CLIError):
101     def __init__(self, message='Unknown Command', details=[], importance=1):
102         super(CLIUnknownCommand, self).__init__(message, details, importance)
103
104
105 class CLICmdSpecError(CLIError):
106     def __init__(
107             self, message='Command Specification Error',
108             details=[], importance=0):
109         super(CLICmdSpecError, self).__init__(message, details, importance)
110
111
112 class CLICmdIncompleteError(CLICmdSpecError):
113     def __init__(
114             self, message='Incomplete Command Error',
115             details=[], importance=1):
116         super(CLICmdSpecError, self).__init__(message, details, importance)
117
118
119 def raiseCLIError(err, message='', importance=0, details=[]):
120     """
121     :param err: (Exception) the original error message, if None, a new
122         CLIError is born which is conceptually bind to raiser
123
124     :param message: (str) a custom error message that overrides err's
125
126     :param importance: (int) instruction to called application (e.g. for
127         coloring printed error messages)
128
129     :param details: (list) various information on the error
130
131     :raises CLIError: it is the purpose of this method
132     """
133     from traceback import format_stack
134
135     stack = ['%s' % type(err)] if err else ['<kamaki.cli.errors.CLIError>']
136     stack += format_stack()
137     try:
138         stack = [e for e in stack if e != stack[1]]
139     except KeyError:
140         log.debug('\n   < '.join(stack))
141
142     details = ['%s' % details] if not isinstance(details, list)\
143         else list(details)
144     details += getattr(err, 'details', [])
145
146     if err:
147         origerr = '%s' % err
148         origerr = origerr if origerr else '%s' % type(err)
149     else:
150         origerr = stack[0]
151
152     message = '%s' % (message if message else origerr)
153
154     try:
155         status = err.status or err.errno
156     except AttributeError:
157         status = None
158
159     if origerr not in details + [message]:
160         details.append(origerr)
161
162     message += '' if message and message[-1] == '\n' else '\n'
163     if status:
164         message = '(%s) %s' % (err.status, message)
165         try:
166             status = int(err.status)
167         except ValueError:
168             raise CLIError(message, details, importance)
169         importance = importance if importance else status // 100
170     importance = getattr(err, 'importance', importance)
171     raise CLIError(message, details, importance)