Debian Codegraph @

neutronclient/common/exceptions.py

raw
1 # Copyright 2011 VMware, Inc
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 from oslo_utils import encodeutils
17
18 from neutronclient._i18n import _
19
20 """
21 Neutron base exception handling.
22
23 Exceptions are classified into three categories:
24 * Exceptions corresponding to exceptions from neutron server:
25 This type of exceptions should inherit one of exceptions
26 in HTTP_EXCEPTION_MAP.
27 * Exceptions from client library:
28 This type of exceptions should inherit NeutronClientException.
29 * Exceptions from CLI code:
30 This type of exceptions should inherit NeutronCLIError.
31 """
32
33
34 # NOTE: This method is defined here to avoid
35 # an import loop between common.utils and this module.
36 def _safe_decode_dict(kwargs):
37 for k, v in kwargs.items():
38 kwargs[k] = encodeutils.safe_decode(v)
39 return kwargs
40
41
42 class NeutronException(Exception):
43 """Base Neutron Exception.
44
45 To correctly use this class, inherit from it and define
46 a 'message' property. That message will get printf'd
47 with the keyword arguments provided to the constructor.
48 """
49 message = _("An unknown exception occurred.")
50
51 def __init__(self, message=None, **kwargs):
52 if message:
53 self.message = message
54 try:
55 self._error_string = self.message % _safe_decode_dict(kwargs)
56 except Exception:
57 # at least get the core message out if something happened
58 self._error_string = self.message
59
60 def __str__(self):
61 return self._error_string
62
63
64 class NeutronClientException(NeutronException):
65 """Base exception which exceptions from Neutron are mapped into.
66
67 NOTE: on the client side, we use different exception types in order
68 to allow client library users to handle server exceptions in try...except
69 blocks. The actual error message is the one generated on the server side.
70 """
71
72 status_code = 0
73 req_ids_msg = _("Neutron server returns request_ids: %s")
74 request_ids = []
75
76 def __init__(self, message=None, **kwargs):
77 self.request_ids = kwargs.get('request_ids')
78 if 'status_code' in kwargs:
79 self.status_code = kwargs['status_code']
80 if self.request_ids:
81 req_ids_msg = self.req_ids_msg % self.request_ids
82 if message:
83 message = _('%(msg)s\n%(id)s') % {'msg': message,
84 'id': req_ids_msg}
85 else:
86 message = req_ids_msg
87 super(NeutronClientException, self).__init__(message, **kwargs)
88
89
90 # Base exceptions from Neutron
91
92 class BadRequest(NeutronClientException):
93 status_code = 400
94
95
96 class Unauthorized(NeutronClientException):
97 status_code = 401
98 message = _("Unauthorized: bad credentials.")
99
100
101 class Forbidden(NeutronClientException):
102 status_code = 403
103 message = _("Forbidden: your credentials don't give you access to this "
104 "resource.")
105
106
107 class NotFound(NeutronClientException):
108 status_code = 404
109
110
111 class Conflict(NeutronClientException):
112 status_code = 409
113
114
115 class InternalServerError(NeutronClientException):
116 status_code = 500
117
118
119 class ServiceUnavailable(NeutronClientException):
120 status_code = 503
121
122
123 HTTP_EXCEPTION_MAP = {
124 400: BadRequest,
125 401: Unauthorized,
126 403: Forbidden,
127 404: NotFound,
128 409: Conflict,
129 500: InternalServerError,
130 503: ServiceUnavailable,
131 }
132
133
134 # Exceptions mapped to Neutron server exceptions
135 # These are defined if a user of client library needs specific exception.
136 # Exception name should be <Neutron Exception Name> + 'Client'
137 # e.g., NetworkNotFound -> NetworkNotFoundClient
138
139 class NetworkNotFoundClient(NotFound):
140 pass
141
142
143 class PortNotFoundClient(NotFound):
144 pass
145
146
147 class StateInvalidClient(BadRequest):
148 pass
149
150
151 class NetworkInUseClient(Conflict):
152 pass
153
154
155 class PortInUseClient(Conflict):
156 pass
157
158
159 class IpAddressInUseClient(Conflict):
160 pass
161
162
163 class IpAddressAlreadyAllocatedClient(Conflict):
164 pass
165
166
167 class InvalidIpForNetworkClient(BadRequest):
168 pass
169
170
171 class InvalidIpForSubnetClient(BadRequest):
172 pass
173
174
175 class OverQuotaClient(Conflict):
176 pass
177
178
179 class IpAddressGenerationFailureClient(Conflict):
180 pass
181
182
183 class MacAddressInUseClient(Conflict):
184 pass
185
186
187 class HostNotCompatibleWithFixedIpsClient(Conflict):
188 pass
189
190
191 class ExternalIpAddressExhaustedClient(BadRequest):
192 pass
193
194
195 # Exceptions from client library
196
197 class NoAuthURLProvided(Unauthorized):
198 message = _("auth_url was not provided to the Neutron client")
199
200
201 class EndpointNotFound(NeutronClientException):
202 message = _("Could not find Service or Region in Service Catalog.")
203
204
205 class EndpointTypeNotFound(NeutronClientException):
206 message = _("Could not find endpoint type %(type_)s in Service Catalog.")
207
208
209 class AmbiguousEndpoints(NeutronClientException):
210 message = _("Found more than one matching endpoint in Service Catalog: "
211 "%(matching_endpoints)")
212
213
214 class RequestURITooLong(NeutronClientException):
215 """Raised when a request fails with HTTP error 414."""
216
217 def __init__(self, **kwargs):
218 self.excess = kwargs.get('excess', 0)
219 super(RequestURITooLong, self).__init__(**kwargs)
220
221
222 class ConnectionFailed(NeutronClientException):
223 message = _("Connection to neutron failed: %(reason)s")
224
225
226 class SslCertificateValidationError(NeutronClientException):
227 message = _("SSL certificate validation has failed: %(reason)s")
228
229
230 class MalformedResponseBody(NeutronClientException):
231 message = _("Malformed response body: %(reason)s")
232
233
234 class InvalidContentType(NeutronClientException):
235 message = _("Invalid content type %(content_type)s.")
236
237
238 # Command line exceptions
239
240 class NeutronCLIError(NeutronException):
241 """Exception raised when command line parsing fails."""
242 pass
243
244
245 class CommandError(NeutronCLIError):
246 pass
247
248
249 class UnsupportedVersion(NeutronCLIError):
250 """Indicates usage of an unsupported API version
251
252 Indicates that the user is trying to use an unsupported version of
253 the API.
254 """
255 pass
256
257
258 class NeutronClientNoUniqueMatch(NeutronCLIError):
259 message = _("Multiple %(resource)s matches found for name '%(name)s',"
260 " use an ID to be more specific.")