Debian Codegraph @

glanceclient/v1/apiclient/exceptions.py

raw symbols SCIP
1 # Copyright 2010 Jacob Kaplan-Moss
2 # Copyright 2011 Nebula, Inc.
3 # Copyright 2013 Alessio Ababilov
4 # Copyright 2013 OpenStack Foundation
5 # All Rights Reserved.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 """
20 Exception definitions.
21 """
22
23 ########################################################################
24 #
25 # THIS MODULE IS DEPRECATED
26 #
27 # Please refer to
28 # https://etherpad.openstack.org/p/kilo-glanceclient-library-proposals for
29 # the discussion leading to this deprecation.
30 #
31 # We recommend checking out the python-openstacksdk project
32 # (https://launchpad.net/python-openstacksdk) instead.
33 #
34 ########################################################################
35
36 import inspect
37 import sys
38
39 from glanceclient._i18n import _
40
41
42 class ClientException(Exception):
43 """The base exception class for all exceptions this library raises."""
44 pass
45
46
47 class ValidationError(ClientException):
48 """Error in validation on API client side."""
49 pass
50
51
52 class UnsupportedVersion(ClientException):
53 """User is trying to use an unsupported version of the API."""
54 pass
55
56
57 class CommandError(ClientException):
58 """Error in CLI tool."""
59 pass
60
61
62 class AuthorizationFailure(ClientException):
63 """Cannot authorize API client."""
64 pass
65
66
67 class ConnectionError(ClientException):
68 """Cannot connect to API service."""
69 pass
70
71
72 class ConnectionRefused(ConnectionError):
73 """Connection refused while trying to connect to API service."""
74 pass
75
76
77 class AuthPluginOptionsMissing(AuthorizationFailure):
78 """Auth plugin misses some options."""
79 def __init__(self, opt_names):
80 super(AuthPluginOptionsMissing, self).__init__(
81 _("Authentication failed. Missing options: %s") %
82 ", ".join(opt_names))
83 self.opt_names = opt_names
84
85
86 class AuthSystemNotFound(AuthorizationFailure):
87 """User has specified an AuthSystem that is not installed."""
88 def __init__(self, auth_system):
89 super(AuthSystemNotFound, self).__init__(
90 _("AuthSystemNotFound: %r") % auth_system)
91 self.auth_system = auth_system
92
93
94 class NoUniqueMatch(ClientException):
95 """Multiple entities found instead of one."""
96 pass
97
98
99 class EndpointException(ClientException):
100 """Something is rotten in Service Catalog."""
101 pass
102
103
104 class EndpointNotFound(EndpointException):
105 """Could not find requested endpoint in Service Catalog."""
106 pass
107
108
109 class AmbiguousEndpoints(EndpointException):
110 """Found more than one matching endpoint in Service Catalog."""
111 def __init__(self, endpoints=None):
112 super(AmbiguousEndpoints, self).__init__(
113 _("AmbiguousEndpoints: %r") % endpoints)
114 self.endpoints = endpoints
115
116
117 class HttpError(ClientException):
118 """The base exception class for all HTTP exceptions."""
119 http_status = 0
120 message = _("HTTP Error")
121
122 def __init__(self, message=None, details=None,
123 response=None, request_id=None,
124 url=None, method=None, http_status=None):
125 self.http_status = http_status or self.http_status
126 self.message = message or self.message
127 self.details = details
128 self.request_id = request_id
129 self.response = response
130 self.url = url
131 self.method = method
132 formatted_string = "%s (HTTP %s)" % (self.message, self.http_status)
133 if request_id:
134 formatted_string += " (Request-ID: %s)" % request_id
135 super(HttpError, self).__init__(formatted_string)
136
137
138 class HTTPRedirection(HttpError):
139 """HTTP Redirection."""
140 message = _("HTTP Redirection")
141
142
143 class HTTPClientError(HttpError):
144 """Client-side HTTP error.
145
146 Exception for cases in which the client seems to have erred.
147 """
148 message = _("HTTP Client Error")
149
150
151 class HttpServerError(HttpError):
152 """Server-side HTTP error.
153
154 Exception for cases in which the server is aware that it has
155 erred or is incapable of performing the request.
156 """
157 message = _("HTTP Server Error")
158
159
160 class MultipleChoices(HTTPRedirection):
161 """HTTP 300 - Multiple Choices.
162
163 Indicates multiple options for the resource that the client may follow.
164 """
165
166 http_status = 300
167 message = _("Multiple Choices")
168
169
170 class BadRequest(HTTPClientError):
171 """HTTP 400 - Bad Request.
172
173 The request cannot be fulfilled due to bad syntax.
174 """
175 http_status = 400
176 message = _("Bad Request")
177
178
179 class Unauthorized(HTTPClientError):
180 """HTTP 401 - Unauthorized.
181
182 Similar to 403 Forbidden, but specifically for use when authentication
183 is required and has failed or has not yet been provided.
184 """
185 http_status = 401
186 message = _("Unauthorized")
187
188
189 class PaymentRequired(HTTPClientError):
190 """HTTP 402 - Payment Required.
191
192 Reserved for future use.
193 """
194 http_status = 402
195 message = _("Payment Required")
196
197
198 class Forbidden(HTTPClientError):
199 """HTTP 403 - Forbidden.
200
201 The request was a valid request, but the server is refusing to respond
202 to it.
203 """
204 http_status = 403
205 message = _("Forbidden")
206
207
208 class NotFound(HTTPClientError):
209 """HTTP 404 - Not Found.
210
211 The requested resource could not be found but may be available again
212 in the future.
213 """
214 http_status = 404
215 message = _("Not Found")
216
217
218 class MethodNotAllowed(HTTPClientError):
219 """HTTP 405 - Method Not Allowed.
220
221 A request was made of a resource using a request method not supported
222 by that resource.
223 """
224 http_status = 405
225 message = _("Method Not Allowed")
226
227
228 class NotAcceptable(HTTPClientError):
229 """HTTP 406 - Not Acceptable.
230
231 The requested resource is only capable of generating content not
232 acceptable according to the Accept headers sent in the request.
233 """
234 http_status = 406
235 message = _("Not Acceptable")
236
237
238 class ProxyAuthenticationRequired(HTTPClientError):
239 """HTTP 407 - Proxy Authentication Required.
240
241 The client must first authenticate itself with the proxy.
242 """
243 http_status = 407
244 message = _("Proxy Authentication Required")
245
246
247 class RequestTimeout(HTTPClientError):
248 """HTTP 408 - Request Timeout.
249
250 The server timed out waiting for the request.
251 """
252 http_status = 408
253 message = _("Request Timeout")
254
255
256 class Conflict(HTTPClientError):
257 """HTTP 409 - Conflict.
258
259 Indicates that the request could not be processed because of conflict
260 in the request, such as an edit conflict.
261 """
262 http_status = 409
263 message = _("Conflict")
264
265
266 class Gone(HTTPClientError):
267 """HTTP 410 - Gone.
268
269 Indicates that the resource requested is no longer available and will
270 not be available again.
271 """
272 http_status = 410
273 message = _("Gone")
274
275
276 class LengthRequired(HTTPClientError):
277 """HTTP 411 - Length Required.
278
279 The request did not specify the length of its content, which is
280 required by the requested resource.
281 """
282 http_status = 411
283 message = _("Length Required")
284
285
286 class PreconditionFailed(HTTPClientError):
287 """HTTP 412 - Precondition Failed.
288
289 The server does not meet one of the preconditions that the requester
290 put on the request.
291 """
292 http_status = 412
293 message = _("Precondition Failed")
294
295
296 class RequestEntityTooLarge(HTTPClientError):
297 """HTTP 413 - Request Entity Too Large.
298
299 The request is larger than the server is willing or able to process.
300 """
301 http_status = 413
302 message = _("Request Entity Too Large")
303
304 def __init__(self, *args, **kwargs):
305 try:
306 self.retry_after = int(kwargs.pop('retry_after'))
307 except (KeyError, ValueError):
308 self.retry_after = 0
309
310 super(RequestEntityTooLarge, self).__init__(*args, **kwargs)
311
312
313 class RequestUriTooLong(HTTPClientError):
314 """HTTP 414 - Request-URI Too Long.
315
316 The URI provided was too long for the server to process.
317 """
318 http_status = 414
319 message = _("Request-URI Too Long")
320
321
322 class UnsupportedMediaType(HTTPClientError):
323 """HTTP 415 - Unsupported Media Type.
324
325 The request entity has a media type which the server or resource does
326 not support.
327 """
328 http_status = 415
329 message = _("Unsupported Media Type")
330
331
332 class RequestedRangeNotSatisfiable(HTTPClientError):
333 """HTTP 416 - Requested Range Not Satisfiable.
334
335 The client has asked for a portion of the file, but the server cannot
336 supply that portion.
337 """
338 http_status = 416
339 message = _("Requested Range Not Satisfiable")
340
341
342 class ExpectationFailed(HTTPClientError):
343 """HTTP 417 - Expectation Failed.
344
345 The server cannot meet the requirements of the Expect request-header field.
346 """
347 http_status = 417
348 message = _("Expectation Failed")
349
350
351 class UnprocessableEntity(HTTPClientError):
352 """HTTP 422 - Unprocessable Entity.
353
354 The request was well-formed but was unable to be followed due to semantic
355 errors.
356 """
357 http_status = 422
358 message = _("Unprocessable Entity")
359
360
361 class InternalServerError(HttpServerError):
362 """HTTP 500 - Internal Server Error.
363
364 A generic error message, given when no more specific message is suitable.
365 """
366 http_status = 500
367 message = _("Internal Server Error")
368
369
370 # NotImplemented is a python keyword.
371 class HttpNotImplemented(HttpServerError):
372 """HTTP 501 - Not Implemented.
373
374 The server either does not recognize the request method, or it lacks
375 the ability to fulfill the request.
376 """
377 http_status = 501
378 message = _("Not Implemented")
379
380
381 class BadGateway(HttpServerError):
382 """HTTP 502 - Bad Gateway.
383
384 The server was acting as a gateway or proxy and received an invalid
385 response from the upstream server.
386 """
387 http_status = 502
388 message = _("Bad Gateway")
389
390
391 class ServiceUnavailable(HttpServerError):
392 """HTTP 503 - Service Unavailable.
393
394 The server is currently unavailable.
395 """
396 http_status = 503
397 message = _("Service Unavailable")
398
399
400 class GatewayTimeout(HttpServerError):
401 """HTTP 504 - Gateway Timeout.
402
403 The server was acting as a gateway or proxy and did not receive a timely
404 response from the upstream server.
405 """
406 http_status = 504
407 message = _("Gateway Timeout")
408
409
410 class HttpVersionNotSupported(HttpServerError):
411 """HTTP 505 - HttpVersion Not Supported.
412
413 The server does not support the HTTP protocol version used in the request.
414 """
415 http_status = 505
416 message = _("HTTP Version Not Supported")
417
418
419 # _code_map contains all the classes that have http_status attribute.
420 _code_map = dict(
421 (getattr(obj, 'http_status', None), obj)
422 for name, obj in vars(sys.modules[__name__]).items()
423 if inspect.isclass(obj) and getattr(obj, 'http_status', False)
424 )
425
426
427 def from_response(response, method, url):
428 """Returns an instance of :class:`HttpError` or subclass based on response.
429
430 :param response: instance of `requests.Response` class
431 :param method: HTTP method used for request
432 :param url: URL used for request
433 """
434
435 req_id = response.headers.get("x-openstack-request-id")
436 # NOTE(hdd) true for older versions of nova and cinder
437 if not req_id:
438 req_id = response.headers.get("x-compute-request-id")
439 kwargs = {
440 "http_status": response.status_code,
441 "response": response,
442 "method": method,
443 "url": url,
444 "request_id": req_id,
445 }
446 if "retry-after" in response.headers:
447 kwargs["retry_after"] = response.headers["retry-after"]
448
449 content_type = response.headers.get("Content-Type", "")
450 if content_type.startswith("application/json"):
451 try:
452 body = response.json()
453 except ValueError:
454 pass
455 else:
456 if isinstance(body, dict):
457 error = body.get(list(body)[0])
458 if isinstance(error, dict):
459 kwargs["message"] = (error.get("message") or
460 error.get("faultstring"))
461 kwargs["details"] = (error.get("details") or
462 str(body))
463 elif content_type.startswith("text/"):
464 kwargs["details"] = getattr(response, 'text', '')
465
466 try:
467 cls = _code_map[response.status_code]
468 except KeyError:
469 if 500 <= response.status_code < 600:
470 cls = HttpServerError
471 elif 400 <= response.status_code < 500:
472 cls = HTTPClientError
473 else:
474 cls = HttpError
475 return cls(**kwargs)