exception.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 InvalidMinionPoolSelection(Invalid):
  116. message = _("The selected minion pool is incompatible.")
  117. class InvalidMinionMachineState(Invalid):
  118. message = _("The selected minion machine is in an invalid state.")
  119. class MinionMachineAllocationFailure(Invalid):
  120. message = _("No minion machines were available for allocation")
  121. class InvalidCustomOSDetectTools(Invalid):
  122. message = _("The provided custom OS detect tools are invalid.")
  123. class InvalidOSMorphingTools(Invalid):
  124. message = _("Invalid OSMorphing tools received: %(tools_class)s")
  125. class InvalidDetectedOSParams(CoriolisException):
  126. message = _("One or more detected OS parameters were invalid.")
  127. safe = True
  128. class InvalidResults(Invalid):
  129. message = _("The results are invalid.")
  130. class InvalidInput(Invalid):
  131. message = _("Invalid input received: %(reason)s")
  132. class InvalidContentType(Invalid):
  133. message = _("Invalid content type %(content_type)s.")
  134. class InvalidHost(Invalid):
  135. message = _("Invalid host: %(reason)s")
  136. class SameDestination(Invalid):
  137. message = _("Origin and destination cannot be the same")
  138. # Cannot be templated as the error syntax varies.
  139. # msg needs to be constructed when raised.
  140. class InvalidParameterValue(Invalid):
  141. message = _("%(err)s")
  142. class InvalidAuthKey(Invalid):
  143. message = _("Invalid auth key: %(reason)s")
  144. class InvalidConfigurationValue(Invalid):
  145. message = _('Value "%(value)s" is not valid for '
  146. 'configuration option "%(option)s"')
  147. class InvalidTaskState(Invalid):
  148. message = _(
  149. 'Task "%(task_id)s" in in an invalid state: %(task_state)s')
  150. class InvalidMinionPoolState(Invalid):
  151. message = _(
  152. 'Minion pool "%(pool_id)s" in in an invalid state: %(pool_state)s')
  153. class TaskIsCancelling(InvalidTaskState):
  154. message = _(TASK_ALREADY_CANCELLING_EXCEPTION_FMT)
  155. class InvalidTaskResult(InvalidTaskState):
  156. message = _('Task returned an invalid result.')
  157. class InvalidActionTasksExecutionState(Invalid):
  158. message = _("Invalid tasks execution state: %(reason)s")
  159. class InvalidMigrationState(Invalid):
  160. message = _("Invalid migration state: %(reason)s")
  161. class InvalidReplicaState(Invalid):
  162. message = _("Invalid replica state: %(reason)s")
  163. class ServiceUnavailable(Invalid):
  164. message = _("Service is unavailable at this time.")
  165. class APIException(CoriolisException):
  166. message = _("Error while requesting %(service)s API.")
  167. safe = True
  168. def __init__(self, message=None, **kwargs):
  169. if 'service' not in kwargs:
  170. kwargs['service'] = 'unknown'
  171. super(APIException, self).__init__(message, **kwargs)
  172. class APITimeout(APIException):
  173. message = _("Timeout while requesting %(service)s API.")
  174. class NotFound(CoriolisException):
  175. message = _("Resource could not be found.")
  176. code = 404
  177. safe = True
  178. class RegionNotFound(NotFound):
  179. message = _("The specified Coriolis region(s) could not be found.")
  180. class OSMorphingToolsNotFound(NotFound):
  181. message = _(
  182. 'No OSMorphing tools were found for OS type "%(os_type)s" for this VM.'
  183. ' This would indicate that it was either not possible to determine the'
  184. ' exact OS release, or this OS release is not supported by Coriolis. '
  185. 'Suggestions include performing any needed OSMorphing steps manually '
  186. 'within the source VM and then re-syncing with the "Skip OS Morphing" '
  187. 'option enabled to bypass this stage, or contacting Cloudbase support '
  188. 'for further assistance.')
  189. class OSDetectToolsNotFound(NotFound):
  190. message = _(
  191. 'No "%(os_type)s" OS detect tools were able to identify the OS for this VM. '
  192. 'This would indicate that it was either not possible to determine the '
  193. 'exact OS release, or this OS release is not supported by Coriolis. '
  194. 'Suggestions include performing any needed OSMorphing steps manually '
  195. 'within the source VM and then re-syncing with the "Skip OS Morphing" '
  196. 'option enabled to bypass this stage, or contacting Cloudbase support '
  197. 'for further assistance.')
  198. class FileNotFound(NotFound):
  199. message = _("File %(file_path)s could not be found.")
  200. class InstanceNotFound(NotFound):
  201. message = _("Instance \"%(instance_name)s\" could not be found.")
  202. class NetworkNotFound(NotFound):
  203. message = _("Network \"%(network_name)s\" could not be found.")
  204. class DiskStorageMappingNotFound(NotFound):
  205. message = _('No storage mapping for disk with ID "%(id)s" could be found.')
  206. class StorageBackendNotFound(NotFound):
  207. message = _(
  208. 'Storage backend with name "%(storage_name)s" could not be found.')
  209. class ImageNotFound(NotFound):
  210. message = _("Image \"%(image_name)s\" could not be found.")
  211. class FlavorNotFound(NotFound):
  212. message = _("Flavor \"%(flavor_name)s\" could not be found.")
  213. class FloatingIPPoolNotFound(NotFound):
  214. message = _("Floating IP pool \"%(pool_name)s\" could not be found.")
  215. class VolumeNotFound(NotFound):
  216. message = _("Volume \"%(volume_id)s\" could not be found.")
  217. class VolumeSnapshotNotFound(NotFound):
  218. message = _("Volume snapshot \"%(snapshot_id)s\" could not be found.")
  219. class VolumeBackupNotFound(NotFound):
  220. message = _("Volume backup \"%(backup_id)s\" could not be found.")
  221. class Duplicate(CoriolisException):
  222. safe = True
  223. class MalformedRequestBody(CoriolisException):
  224. message = _("Malformed message body: %(reason)s")
  225. code = 400
  226. safe = True
  227. class ConfigNotFound(NotFound):
  228. message = _("Could not find config at %(path)s")
  229. class ParameterNotFound(NotFound):
  230. message = _("Could not find parameter %(param)s")
  231. class PasteAppNotFound(NotFound):
  232. message = _("Could not load paste app '%(name)s' from %(path)s")
  233. class NoValidHost(CoriolisException):
  234. message = _("No valid host was found. %(reason)s")
  235. safe = True
  236. UnsupportedObjectError = obj_exc.UnsupportedObjectError
  237. OrphanedObjectError = obj_exc.OrphanedObjectError
  238. IncompatibleObjectVersion = obj_exc.IncompatibleObjectVersion
  239. ReadOnlyFieldError = obj_exc.ReadOnlyFieldError
  240. ObjectActionError = obj_exc.ObjectActionError
  241. ObjectFieldInvalid = obj_exc.ObjectFieldInvalid
  242. class NotSupportedOperation(Invalid):
  243. message = _("Operation not supported: %(operation)s.")
  244. code = 405
  245. class TaskProcessException(CoriolisException):
  246. safe = True
  247. class TaskProcessCanceledException(TaskProcessException):
  248. pass
  249. class OperatingSystemNotFound(NotFound):
  250. pass
  251. class ConnectionValidationException(CoriolisException):
  252. safe = True
  253. class SchemaValidationException(CoriolisException):
  254. safe = True
  255. class QEMUException(Exception):
  256. pass
  257. if six.PY2:
  258. class ConnectionRefusedError(OSError):
  259. pass
  260. else:
  261. ConnectionRefusedError = six.moves.builtins.ConnectionRefusedError
  262. class UnrecognizedWorkerInitSystem(CoriolisException):
  263. message = _(
  264. "Could not determine init system for temporary worker VM. The image "
  265. "used for the worker VM must use systemd as an init system for "
  266. "Coriolis to be able to use it for data Replication.")
  267. class NoRegionError(CoriolisException):
  268. safe = True
  269. code = 503
  270. message = _(
  271. "No Coriolis region is avaialable to process this request at this "
  272. "time.")
  273. class NoSuitableRegionError(NoRegionError):
  274. message = _(
  275. "No Coriolis Region(s) fitting the criteria of the required operation "
  276. "could be found.")
  277. class NoServiceError(CoriolisException):
  278. safe = True
  279. code = 503
  280. message = _(
  281. "No service is avaialable to process this request at this time.")
  282. class NoWorkerServiceError(NoServiceError):
  283. message = _(
  284. "No Coriolis Worker Service(s) were found. Please ensure that "
  285. "at least one or Coriolis Worker Service(s) are registered "
  286. "within the Coriolis installation.")
  287. class NoSuitableWorkerServiceError(NoServiceError):
  288. message = _(
  289. "No suitable Coriolis Worker service was found which fits the "
  290. "criteria for the required operation.")
  291. class OSMorphingException(CoriolisException):
  292. pass
  293. class PackageManagerOperationException(OSMorphingException):
  294. pass
  295. class FailedPackageInstallationException(PackageManagerOperationException):
  296. message = (
  297. "Failed to install required packages %(package_names)s through "
  298. "%(package_manager)s. Please ensure that the required packages are "
  299. "available within the %(package_manager)s repositories configured "
  300. "within the source machine. If not, please either add or enable "
  301. "additional repositories within the source machine which contain the "
  302. "packages Coriolis requires, or attempt to manually install the "
  303. "packages on the source machine and then migrate the VM using Coriolis"
  304. " with the OSMorphing process disabled. Error was: %(error)s")
  305. class FailedPackageUninstallationException(PackageManagerOperationException):
  306. message = (
  307. "Failed to remove unwanted packages (%(package_names)s) through "
  308. "%(package_manager)s. Error was: %(error)s")
  309. class MinionMachineCommandTimeout(CoriolisException):
  310. pass
  311. class OSMorphingOperationTimeout(MinionMachineCommandTimeout):
  312. pass
  313. class OSMorphingSSHOperationTimeout(OSMorphingOperationTimeout):
  314. message = (
  315. "Pending SSH command %(cmd)s timed out after %(timeout)s seconds. "
  316. "Coriolis may have encountered connection issues to the minion machine"
  317. " or the command execution time exceeds the timeout set. Try extending"
  318. " the timeout by editing the 'default_osmorphing_operation_timeout' "
  319. "in Coriolis' static configuration file."
  320. )
  321. class OSMorphingWinRMOperationTimeout(OSMorphingOperationTimeout):
  322. message = (
  323. "Pending WinRM command %(cmd)s timed out after %(timeout)s seconds. "
  324. "Coriolis may have encountered connection issues to the minion machine"
  325. " or the command execution time exceeds the timeout set. Try extending"
  326. " the timeout by editing the 'default_osmorphing_operation_timeout' "
  327. "in Coriolis' static configuration file."
  328. )