exception.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 # noqa
  25. LOG = logging.getLogger(__name__)
  26. CONF = cfg.CONF
  27. TASK_ALREADY_CANCELLING_EXCEPTION_FMT = (
  28. "Task %(task_id)s is in CANCELLING status.")
  29. class ConvertedException(webob.exc.WSGIHTTPException):
  30. def __init__(self, code=500, title="", explanation=""):
  31. self.code = code
  32. # There is a strict rule about constructing status line for HTTP:
  33. # '...Status-Line, consisting of the protocol version followed by a
  34. # numeric status code and its associated textual phrase, with each
  35. # element separated by SP characters'
  36. # (http://www.faqs.org/rfcs/rfc2616.html)
  37. # 'code' and 'title' can not be empty because they correspond
  38. # to numeric status code and its associated text
  39. if title:
  40. self.title = title
  41. else:
  42. try:
  43. self.title = status_reasons[self.code]
  44. except KeyError:
  45. generic_code = self.code // 100
  46. self.title = status_generic_reasons[generic_code]
  47. self.explanation = explanation
  48. super(ConvertedException, self).__init__()
  49. class Error(Exception):
  50. pass
  51. class CoriolisException(Exception):
  52. """Base Coriolis Exception
  53. To correctly use this class, inherit from it and define
  54. a 'message' property. That message will get printf'd
  55. with the keyword arguments provided to the constructor.
  56. """
  57. message = _("An unknown exception occurred.")
  58. code = 500
  59. headers = {}
  60. safe = False
  61. def __init__(self, message=None, **kwargs):
  62. self.kwargs = kwargs
  63. if 'code' not in self.kwargs:
  64. try:
  65. self.kwargs['code'] = self.code
  66. except AttributeError:
  67. pass
  68. for k, v in self.kwargs.items():
  69. if isinstance(v, Exception):
  70. self.kwargs[k] = six.text_type(v)
  71. if self._should_format(message):
  72. try:
  73. message = self.message % kwargs
  74. except Exception:
  75. exc_info = sys.exc_info()
  76. # kwargs doesn't match a variable in the message
  77. # log the issue and the kwargs
  78. LOG.exception(_LE('Exception in string format operation'))
  79. for name, value in kwargs.items():
  80. LOG.error(_LE("%(name)s: %(value)s"),
  81. {'name': name, 'value': value})
  82. if CONF.fatal_exception_format_errors:
  83. six.reraise(*exc_info)
  84. # at least get the core message out if something happened
  85. message = self.message
  86. elif isinstance(message, Exception):
  87. message = six.text_type(message)
  88. # NOTE(luisg): We put the actual message in 'msg' so that we can access
  89. # it, because if we try to access the message via 'message' it will be
  90. # overshadowed by the class' message attribute
  91. self.msg = message
  92. super(CoriolisException, self).__init__(message)
  93. def _should_format(self, message):
  94. return message is None or '%(message)' in self.message
  95. def __unicode__(self):
  96. return six.text_type(self.msg)
  97. class NotAuthorized(CoriolisException):
  98. message = _("Not authorized.")
  99. code = 403
  100. safe = True
  101. class PolicyNotAuthorized(CoriolisException):
  102. message = _("Policy doesn't allow %(action)s to be performed.")
  103. code = 403
  104. safe = True
  105. class Conflict(CoriolisException):
  106. message = _("Conflict")
  107. code = 409
  108. safe = True
  109. class AdminRequired(NotAuthorized):
  110. message = _("User does not have admin privileges")
  111. class Invalid(CoriolisException):
  112. message = _("Unacceptable parameters.")
  113. code = 400
  114. safe = True
  115. class InvalidResults(Invalid):
  116. message = _("The results are invalid.")
  117. class InvalidInput(Invalid):
  118. message = _("Invalid input received: %(reason)s")
  119. class InvalidContentType(Invalid):
  120. message = _("Invalid content type %(content_type)s.")
  121. class InvalidHost(Invalid):
  122. message = _("Invalid host: %(reason)s")
  123. class SameDestination(Invalid):
  124. message = _("Origin and destination cannot be the same")
  125. # Cannot be templated as the error syntax varies.
  126. # msg needs to be constructed when raised.
  127. class InvalidParameterValue(Invalid):
  128. message = _("%(err)s")
  129. class InvalidAuthKey(Invalid):
  130. message = _("Invalid auth key: %(reason)s")
  131. class InvalidConfigurationValue(Invalid):
  132. message = _('Value "%(value)s" is not valid for '
  133. 'configuration option "%(option)s"')
  134. class InvalidTaskState(Invalid):
  135. message = _(
  136. 'Task "%(task_id)s" in in an invalid state: %(task_state)s')
  137. class TaskIsCancelling(InvalidTaskState):
  138. message = _(TASK_ALREADY_CANCELLING_EXCEPTION_FMT)
  139. class InvalidTaskResult(InvalidTaskState):
  140. message = _('Task returned an invalid result.')
  141. class InvalidActionTasksExecutionState(Invalid):
  142. message = _("Invalid tasks execution state: %(reason)s")
  143. class InvalidMigrationState(Invalid):
  144. message = _("Invalid migration state: %(reason)s")
  145. class InvalidReplicaState(Invalid):
  146. message = _("Invalid replica state: %(reason)s")
  147. class ServiceUnavailable(Invalid):
  148. message = _("Service is unavailable at this time.")
  149. class APIException(CoriolisException):
  150. message = _("Error while requesting %(service)s API.")
  151. safe = True
  152. def __init__(self, message=None, **kwargs):
  153. if 'service' not in kwargs:
  154. kwargs['service'] = 'unknown'
  155. super(APIException, self).__init__(message, **kwargs)
  156. class APITimeout(APIException):
  157. message = _("Timeout while requesting %(service)s API.")
  158. class NotFound(CoriolisException):
  159. message = _("Resource could not be found.")
  160. code = 404
  161. safe = True
  162. class OSMorphingToolsNotFound(NotFound):
  163. message = _("Couldn't find any morphing tools for this OS.")
  164. class FileNotFound(NotFound):
  165. message = _("File %(file_path)s could not be found.")
  166. class InstanceNotFound(NotFound):
  167. message = _("Instance \"%(instance_name)s\" could not be found.")
  168. class NetworkNotFound(NotFound):
  169. message = _("Network \"%(network_name)s\" could not be found.")
  170. class DiskStorageMappingNotFound(NotFound):
  171. message = _('No storage mapping for disk with ID "%(id)s" could be found.')
  172. class StorageBackendNotFound(NotFound):
  173. message = _(
  174. 'Storage backend with name "%(storage_name)s" could not be found.')
  175. class ImageNotFound(NotFound):
  176. message = _("Image \"%(image_name)s\" could not be found.")
  177. class FlavorNotFound(NotFound):
  178. message = _("Flavor \"%(flavor_name)s\" could not be found.")
  179. class FloatingIPPoolNotFound(NotFound):
  180. message = _("Floating IP pool \"%(pool_name)s\" could not be found.")
  181. class VolumeNotFound(NotFound):
  182. message = _("Volume \"%(volume_id)s\" could not be found.")
  183. class VolumeSnapshotNotFound(NotFound):
  184. message = _("Volume snapshot \"%(snapshot_id)s\" could not be found.")
  185. class VolumeBackupNotFound(NotFound):
  186. message = _("Volume backup \"%(backup_id)s\" could not be found.")
  187. class Duplicate(CoriolisException):
  188. safe = True
  189. class MalformedRequestBody(CoriolisException):
  190. message = _("Malformed message body: %(reason)s")
  191. code = 400
  192. safe = True
  193. class ConfigNotFound(NotFound):
  194. message = _("Could not find config at %(path)s")
  195. class ParameterNotFound(NotFound):
  196. message = _("Could not find parameter %(param)s")
  197. class PasteAppNotFound(NotFound):
  198. message = _("Could not load paste app '%(name)s' from %(path)s")
  199. class NoValidHost(CoriolisException):
  200. message = _("No valid host was found. %(reason)s")
  201. safe = True
  202. UnsupportedObjectError = obj_exc.UnsupportedObjectError
  203. OrphanedObjectError = obj_exc.OrphanedObjectError
  204. IncompatibleObjectVersion = obj_exc.IncompatibleObjectVersion
  205. ReadOnlyFieldError = obj_exc.ReadOnlyFieldError
  206. ObjectActionError = obj_exc.ObjectActionError
  207. ObjectFieldInvalid = obj_exc.ObjectFieldInvalid
  208. class NotSupportedOperation(Invalid):
  209. message = _("Operation not supported: %(operation)s.")
  210. code = 405
  211. class TaskProcessException(CoriolisException):
  212. safe = True
  213. class OperatingSystemNotFound(NotFound):
  214. pass
  215. class ConnectionValidationException(CoriolisException):
  216. safe = True
  217. class SchemaValidationException(CoriolisException):
  218. safe = True
  219. class QEMUException(Exception):
  220. pass
  221. if six.PY2:
  222. class ConnectionRefusedError(OSError):
  223. pass
  224. else:
  225. ConnectionRefusedError = six.moves.builtins.ConnectionRefusedError