| 1 |
# |
| 2 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 3 |
# not use this file except in compliance with the License. You may obtain |
| 4 |
# a copy of the License at |
| 5 |
# |
| 6 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
# |
| 8 |
# Unless required by applicable law or agreed to in writing, software |
| 9 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 10 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 11 |
# License for the specific language governing permissions and limitations |
| 12 |
# under the License. |
| 13 |
|
| 14 |
|
| 15 |
class ClientException(Exception): |
| 16 |
"""The base exception class for all exceptions this library raises.""" |
| 17 |
message = 'Unknown Error' |
| 18 |
http_status = 'N/A' |
| 19 |
|
| 20 |
def __init__(self, message=None, request_id=None, |
| 21 |
url=None, method=None): |
| 22 |
self.message = message or self.__class__.message |
| 23 |
self.request_id = request_id |
| 24 |
self.url = url |
| 25 |
self.method = method |
| 26 |
|
| 27 |
# NOTE(jd) for backward compat |
| 28 |
@property |
| 29 |
def code(self): |
| 30 |
return self.http_status |
| 31 |
|
| 32 |
def __str__(self): |
| 33 |
formatted_string = "{} (HTTP {})".format( |
| 34 |
self.message, self.http_status) |
| 35 |
if self.request_id: |
| 36 |
formatted_string += f" (Request-ID: {self.request_id})" |
| 37 |
|
| 38 |
return formatted_string |
| 39 |
|
| 40 |
|
| 41 |
class RetryAfterException(ClientException): |
| 42 |
"""The base exception for ClientExceptions that use Retry-After header.""" |
| 43 |
def __init__(self, *args, **kwargs): |
| 44 |
try: |
| 45 |
self.retry_after = int(kwargs.pop('retry_after')) |
| 46 |
except (KeyError, ValueError): |
| 47 |
self.retry_after = 0 |
| 48 |
|
| 49 |
super().__init__(*args, **kwargs) |
| 50 |
|
| 51 |
|
| 52 |
class MutipleMeaningException: |
| 53 |
"""An mixin for exception that can be enhanced by reading the details""" |
| 54 |
|
| 55 |
|
| 56 |
class CommandError(Exception): |
| 57 |
pass |
| 58 |
|
| 59 |
|
| 60 |
class BadRequest(ClientException): |
| 61 |
"""HTTP 400 - Bad request: you sent some malformed data.""" |
| 62 |
http_status = 400 |
| 63 |
message = "Bad request" |
| 64 |
|
| 65 |
|
| 66 |
class Unauthorized(ClientException): |
| 67 |
"""HTTP 401 - Unauthorized: bad credentials.""" |
| 68 |
http_status = 401 |
| 69 |
message = "Unauthorized" |
| 70 |
|
| 71 |
|
| 72 |
class Forbidden(ClientException): |
| 73 |
"""HTTP 403 - Forbidden: |
| 74 |
|
| 75 |
your credentials don't give you access to this resource. |
| 76 |
""" |
| 77 |
http_status = 403 |
| 78 |
message = "Forbidden" |
| 79 |
|
| 80 |
|
| 81 |
class NotFound(ClientException): |
| 82 |
"""HTTP 404 - Not found""" |
| 83 |
http_status = 404 |
| 84 |
message = "Not found" |
| 85 |
|
| 86 |
|
| 87 |
class MethodNotAllowed(ClientException): |
| 88 |
"""HTTP 405 - Method Not Allowed""" |
| 89 |
http_status = 405 |
| 90 |
message = "Method Not Allowed" |
| 91 |
|
| 92 |
|
| 93 |
class NotAcceptable(ClientException): |
| 94 |
"""HTTP 406 - Not Acceptable""" |
| 95 |
http_status = 406 |
| 96 |
message = "Not Acceptable" |
| 97 |
|
| 98 |
|
| 99 |
class Conflict(ClientException): |
| 100 |
"""HTTP 409 - Conflict""" |
| 101 |
http_status = 409 |
| 102 |
message = "Conflict" |
| 103 |
|
| 104 |
|
| 105 |
class OverLimit(RetryAfterException): |
| 106 |
"""HTTP 413 - Over limit: |
| 107 |
|
| 108 |
you're over the API limits for this time period. |
| 109 |
""" |
| 110 |
http_status = 413 |
| 111 |
message = "Over limit" |
| 112 |
|
| 113 |
|
| 114 |
class RateLimit(RetryAfterException): |
| 115 |
"""HTTP 429 - Rate limit: |
| 116 |
|
| 117 |
you've sent too many requests for this time period. |
| 118 |
""" |
| 119 |
http_status = 429 |
| 120 |
message = "Rate limit" |
| 121 |
|
| 122 |
|
| 123 |
class NoUniqueMatch(Exception): |
| 124 |
pass |
| 125 |
|
| 126 |
|
| 127 |
class NotImplemented(ClientException): |
| 128 |
"""HTTP 501 - Not Implemented: |
| 129 |
|
| 130 |
the server does not support this operation. |
| 131 |
""" |
| 132 |
http_status = 501 |
| 133 |
message = "Not Implemented" |
| 134 |
|
| 135 |
|
| 136 |
_error_classes = [BadRequest, Unauthorized, Forbidden, NotFound, |
| 137 |
MethodNotAllowed, NotAcceptable, Conflict, OverLimit, |
| 138 |
RateLimit, NotImplemented] |
| 139 |
_error_classes_enhanced = {} |
| 140 |
_code_map = { |
| 141 |
c.http_status: (c, _error_classes_enhanced.get(c, [])) |
| 142 |
for c in _error_classes} |
| 143 |
|
| 144 |
|
| 145 |
def from_response(response, url, method=None): |
| 146 |
"""Return an instance of ClientException on an requests response. |
| 147 |
|
| 148 |
Usage:: |
| 149 |
|
| 150 |
resp, body = requests.request(...) |
| 151 |
if resp.status_code != 200: |
| 152 |
raise exception_from_response(resp) |
| 153 |
""" |
| 154 |
|
| 155 |
if response.status_code: |
| 156 |
cls, enhanced_classes = _code_map.get(response.status_code, |
| 157 |
(ClientException, [])) |
| 158 |
|
| 159 |
req_id = response.headers.get("x-openstack-request-id") |
| 160 |
content_type = response.headers.get("Content-Type", "").split(";")[0] |
| 161 |
|
| 162 |
kwargs = { |
| 163 |
'method': method, |
| 164 |
'url': url, |
| 165 |
'request_id': req_id, |
| 166 |
} |
| 167 |
|
| 168 |
if "retry-after" in response.headers: |
| 169 |
kwargs['retry_after'] = response.headers.get('retry-after') |
| 170 |
|
| 171 |
if content_type == "application/json": |
| 172 |
try: |
| 173 |
body = response.json() |
| 174 |
except ValueError: |
| 175 |
pass |
| 176 |
else: |
| 177 |
desc = body.get('error_message', {}).get('faultstring') |
| 178 |
for enhanced_cls in enhanced_classes: |
| 179 |
if enhanced_cls.match.match(desc): |
| 180 |
cls = enhanced_cls |
| 181 |
break |
| 182 |
kwargs['message'] = desc |
| 183 |
elif content_type.startswith("text/"): |
| 184 |
kwargs['message'] = response.text |
| 185 |
|
| 186 |
if not kwargs.get('message'): |
| 187 |
kwargs.pop('message', None) |
| 188 |
|
| 189 |
exception = cls(**kwargs) |
| 190 |
if isinstance(exception, ClientException) and response.status_code: |
| 191 |
exception.http_status = response.status_code |
| 192 |
return exception |