exception.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # Copyright 2010 United States Government as represented by the
  2. # Administrator of the National Aeronautics and Space Administration.
  3. # All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. import sys
  17. from oslo_config import cfg
  18. from oslo_log import log as logging
  19. from oslo_versionedobjects import exception as obj_exc
  20. import six
  21. import webob.exc
  22. from webob.util import status_generic_reasons
  23. from webob.util import status_reasons
  24. from coriolis.i18n import _, _LE
  25. LOG = logging.getLogger(__name__)
  26. CONF = cfg.CONF
  27. class ConvertedException(webob.exc.WSGIHTTPException):
  28. def __init__(self, code=500, title="", explanation=""):
  29. self.code = code
  30. # There is a strict rule about constructing status line for HTTP:
  31. # '...Status-Line, consisting of the protocol version followed by a
  32. # numeric status code and its associated textual phrase, with each
  33. # element separated by SP characters'
  34. # (http://www.faqs.org/rfcs/rfc2616.html)
  35. # 'code' and 'title' can not be empty because they correspond
  36. # to numeric status code and its associated text
  37. if title:
  38. self.title = title
  39. else:
  40. try:
  41. self.title = status_reasons[self.code]
  42. except KeyError:
  43. generic_code = self.code // 100
  44. self.title = status_generic_reasons[generic_code]
  45. self.explanation = explanation
  46. super(ConvertedException, self).__init__()
  47. class Error(Exception):
  48. pass
  49. class CoriolisException(Exception):
  50. """Base Coriolis Exception
  51. To correctly use this class, inherit from it and define
  52. a 'message' property. That message will get printf'd
  53. with the keyword arguments provided to the constructor.
  54. """
  55. message = _("An unknown exception occurred.")
  56. code = 500
  57. headers = {}
  58. safe = False
  59. def __init__(self, message=None, **kwargs):
  60. self.kwargs = kwargs
  61. self.kwargs['message'] = message
  62. if 'code' not in self.kwargs:
  63. try:
  64. self.kwargs['code'] = self.code
  65. except AttributeError:
  66. pass
  67. for k, v in self.kwargs.items():
  68. if isinstance(v, Exception):
  69. self.kwargs[k] = six.text_type(v)
  70. if self._should_format():
  71. try:
  72. message = self.message % kwargs
  73. except Exception:
  74. exc_info = sys.exc_info()
  75. # kwargs doesn't match a variable in the message
  76. # log the issue and the kwargs
  77. LOG.exception(_LE('Exception in string format operation'))
  78. for name, value in kwargs.items():
  79. LOG.error(_LE("%(name)s: %(value)s"),
  80. {'name': name, 'value': value})
  81. if CONF.fatal_exception_format_errors:
  82. six.reraise(*exc_info)
  83. # at least get the core message out if something happened
  84. message = self.message
  85. elif isinstance(message, Exception):
  86. message = six.text_type(message)
  87. # NOTE(luisg): We put the actual message in 'msg' so that we can access
  88. # it, because if we try to access the message via 'message' it will be
  89. # overshadowed by the class' message attribute
  90. self.msg = message
  91. super(CoriolisException, self).__init__(message)
  92. def _should_format(self):
  93. return self.kwargs['message'] is None or '%(message)' in self.message
  94. def __unicode__(self):
  95. return six.text_type(self.msg)
  96. class NotAuthorized(CoriolisException):
  97. message = _("Not authorized.")
  98. code = 403
  99. class AdminRequired(NotAuthorized):
  100. message = _("User does not have admin privileges")
  101. class PolicyNotAuthorized(NotAuthorized):
  102. message = _("Policy doesn't allow %(action)s to be performed.")
  103. class Invalid(CoriolisException):
  104. message = _("Unacceptable parameters.")
  105. code = 400
  106. class InvalidResults(Invalid):
  107. message = _("The results are invalid.")
  108. class InvalidInput(Invalid):
  109. message = _("Invalid input received: %(reason)s")
  110. class InvalidContentType(Invalid):
  111. message = _("Invalid content type %(content_type)s.")
  112. class InvalidHost(Invalid):
  113. message = _("Invalid host: %(reason)s")
  114. # Cannot be templated as the error syntax varies.
  115. # msg needs to be constructed when raised.
  116. class InvalidParameterValue(Invalid):
  117. message = _("%(err)s")
  118. class InvalidAuthKey(Invalid):
  119. message = _("Invalid auth key: %(reason)s")
  120. class InvalidConfigurationValue(Invalid):
  121. message = _('Value "%(value)s" is not valid for '
  122. 'configuration option "%(option)s"')
  123. class ServiceUnavailable(Invalid):
  124. message = _("Service is unavailable at this time.")
  125. class APIException(CoriolisException):
  126. message = _("Error while requesting %(service)s API.")
  127. def __init__(self, message=None, **kwargs):
  128. if 'service' not in kwargs:
  129. kwargs['service'] = 'unknown'
  130. super(APIException, self).__init__(message, **kwargs)
  131. class APITimeout(APIException):
  132. message = _("Timeout while requesting %(service)s API.")
  133. class NotFound(CoriolisException):
  134. message = _("Resource could not be found.")
  135. code = 404
  136. safe = True
  137. class FileNotFound(NotFound):
  138. message = _("File %(file_path)s could not be found.")
  139. class Duplicate(CoriolisException):
  140. pass
  141. class MalformedRequestBody(CoriolisException):
  142. message = _("Malformed message body: %(reason)s")
  143. class ConfigNotFound(NotFound):
  144. message = _("Could not find config at %(path)s")
  145. class ParameterNotFound(NotFound):
  146. message = _("Could not find parameter %(param)s")
  147. class PasteAppNotFound(NotFound):
  148. message = _("Could not load paste app '%(name)s' from %(path)s")
  149. class NoValidHost(CoriolisException):
  150. message = _("No valid host was found. %(reason)s")
  151. UnsupportedObjectError = obj_exc.UnsupportedObjectError
  152. OrphanedObjectError = obj_exc.OrphanedObjectError
  153. IncompatibleObjectVersion = obj_exc.IncompatibleObjectVersion
  154. ReadOnlyFieldError = obj_exc.ReadOnlyFieldError
  155. ObjectActionError = obj_exc.ObjectActionError
  156. ObjectFieldInvalid = obj_exc.ObjectFieldInvalid
  157. class NotSupportedOperation(Invalid):
  158. message = _("Operation not supported: %(operation)s.")
  159. code = 405
  160. class TaskProcessException(CoriolisException):
  161. pass
  162. class OperatingSystemNotFound(NotFound):
  163. pass