1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneauth1.exceptions import base as kae_base
from keystoneauth1.exceptions import http as kae_http
from openstack import exceptions as sdkexc
from oslo_serialization import jsonutils
from requests import exceptions as reqexc
from senlinclient.common.i18n import _
verbose = False
class BaseException(Exception):
"""An error occurred."""
def __init__(self, message=None):
self.message = message
def __str__(self):
return self.message or self.__class__.__doc__
class CommandError(BaseException):
"""Invalid usage of CLI."""
class FileFormatError(BaseException):
"""Illegal file format detected."""
class PollingExceededError(BaseException):
"""Desired resource state not achived within polling period."""
class HTTPException(BaseException):
"""Base exception for all HTTP-derived exceptions."""
code = 'N/A'
def __init__(self, error=None):
super(HTTPException, self).__init__(error)
try:
self.error = error
if 'error' not in self.error:
raise KeyError(_('Key "error" not exists'))
except KeyError:
# If key 'error' does not exist, self.message becomes
# no sense. In this case, we return doc of current
# exception class instead.
self.error = {'error': {'message': self.__class__.__doc__}}
except Exception:
self.error = {'error':
{'message': self.message or self.__class__.__doc__}}
def __str__(self):
message = self.error['error'].get('message', 'Internal Error')
if verbose:
traceback = self.error['error'].get('traceback', '')
return (_('ERROR: %(message)s\n%(traceback)s') %
{'message': message, 'traceback': traceback})
else:
code = self.error['error'].get('code', 'Unknown')
return _('ERROR(%(code)s): %(message)s') % {'code': code,
'message': message}
class ClientError(HTTPException):
pass
class ServerError(HTTPException):
pass
class HTTPBadRequest(ClientError):
# 400
pass
class HTTPUnauthorized(ClientError):
# 401
pass
class HTTPForbidden(ClientError):
# 403
pass
class HTTPNotFound(ClientError):
# 404
pass
class HTTPMethodNotAllowed(ClientError):
# 405
pass
class HTTPNotAcceptable(ClientError):
# 406
pass
class HTTPProxyAuthenticationRequired(ClientError):
# 407
pass
class HTTPRequestTimeout(ClientError):
# 408
pass
class HTTPConflict(ClientError):
# 409
pass
class HTTPGone(ClientError):
# 410
pass
class HTTPLengthRequired(ClientError):
# 411
pass
class HTTPPreconditionFailed(ClientError):
# 412
pass
class HTTPRequestEntityTooLarge(ClientError):
# 413
pass
class HTTPRequestURITooLong(ClientError):
# 414
pass
class HTTPUnsupportedMediaType(ClientError):
# 415
pass
class HTTPRequestRangeNotSatisfiable(ClientError):
# 416
pass
class HTTPExpectationFailed(ClientError):
# 417
pass
class HTTPInternalServerError(ServerError):
# 500
pass
class HTTPNotImplemented(ServerError):
# 501
pass
class HTTPBadGateway(ServerError):
# 502
pass
class HTTPServiceUnavailable(ServerError):
# 503
pass
class HTTPGatewayTimeout(ServerError):
# 504
pass
class HTTPVersionNotSupported(ServerError):
# 505
pass
class ConnectionRefused(HTTPException):
# 111
pass
_EXCEPTION_MAP = {
111: ConnectionRefused,
400: HTTPBadRequest,
401: HTTPUnauthorized,
403: HTTPForbidden,
404: HTTPNotFound,
405: HTTPMethodNotAllowed,
406: HTTPNotAcceptable,
407: HTTPProxyAuthenticationRequired,
408: HTTPRequestTimeout,
409: HTTPConflict,
410: HTTPGone,
411: HTTPLengthRequired,
412: HTTPPreconditionFailed,
413: HTTPRequestEntityTooLarge,
414: HTTPRequestURITooLong,
415: HTTPUnsupportedMediaType,
416: HTTPRequestRangeNotSatisfiable,
417: HTTPExpectationFailed,
500: HTTPInternalServerError,
501: HTTPNotImplemented,
502: HTTPBadGateway,
503: HTTPServiceUnavailable,
504: HTTPGatewayTimeout,
505: HTTPVersionNotSupported,
}
def parse_exception(exc):
"""Parse exception code and yield useful information.
:param exc: details of the exception.
"""
if isinstance(exc, sdkexc.HttpException):
if exc.details is None:
data = exc.response.json()
code = data.get('code', None)
message = data.get('message', None)
error = data.get('error', None)
if error:
record = {
'error': {
'code': exc.http_status,
'message': message or exc.message
}
}
else:
info = data.values()[0]
record = {
'error': {
'code': info.get('code', code),
'message': info.get('message', message)
}
}
else:
try:
record = jsonutils.loads(exc.details)
except Exception:
# If the exc.details is not in JSON format
record = {
'error': {
'code': exc.http_status,
'message': exc,
}
}
elif isinstance(exc, reqexc.RequestException):
# Exceptions that are not captured by SDK
record = {
'error': {
'code': exc.message[1].errno,
'message': exc.message[0],
}
}
elif isinstance(exc, str):
record = jsonutils.loads(exc)
# some exception from keystoneauth1 is not shaped by SDK
elif isinstance(exc, kae_http.HttpError):
record = {
'error': {
'code': exc.http_status,
'message': exc.message
}
}
elif isinstance(exc, kae_base.ClientException):
record = {
'error': {
# other exceptions from keystoneauth1 is an internal
# error to senlin, so set status code to 500
'code': 500,
'message': exc.message
}
}
else:
print(_('Unknown exception: %s') % exc)
return
try:
code = record['error']['code']
except KeyError as err:
print(_('Malformed exception record, missing field "%s"') % err)
print(_('Original error record: %s') % record)
return
if code in _EXCEPTION_MAP:
inst = _EXCEPTION_MAP.get(code)
raise inst(record)
else:
raise HTTPException(record)
|