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