2
0

exceptions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2012-2013 LiuYC https://github.com/liuyichen/
  3. # Copyright 2012-2014 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"). You
  6. # may not use this file except in compliance with the License. A copy of
  7. # the License is located at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # or in the "license" file accompanying this file. This file is
  12. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  13. # ANY KIND, either express or implied. See the License for the specific
  14. # language governing permissions and limitations under the License.
  15. from __future__ import unicode_literals
  16. from kscore.vendored.requests.exceptions import ConnectionError
  17. import sys
  18. if sys.version_info[0] < 3 :
  19. from imp import reload
  20. reload(sys)
  21. sys.setdefaultencoding('utf8')
  22. class KSCoreError(Exception):
  23. """
  24. The base exception class for KSCore exceptions.
  25. :ivar msg: The descriptive message associated with the error.
  26. """
  27. fmt = 'An unspecified error occurred'
  28. def __init__(self, **kwargs):
  29. msg = self.fmt.format(**kwargs)
  30. Exception.__init__(self, msg)
  31. self.kwargs = kwargs
  32. class DataNotFoundError(KSCoreError):
  33. """
  34. The data associated with a particular path could not be loaded.
  35. :ivar path: The data path that the user attempted to load.
  36. """
  37. fmt = 'Unable to load data for: {data_path}'
  38. class UnknownServiceError(DataNotFoundError):
  39. """Raised when trying to load data for an unknown service.
  40. :ivar service_name: The name of the unknown service.
  41. """
  42. fmt = (
  43. "Unknown service: '{service_name}'. Valid service names are: "
  44. "{known_service_names}")
  45. class ApiVersionNotFoundError(KSCoreError):
  46. """
  47. The data associated with either that API version or a compatible one
  48. could not be loaded.
  49. :ivar path: The data path that the user attempted to load.
  50. :ivar path: The API version that the user attempted to load.
  51. """
  52. fmt = 'Unable to load data {data_path} for: {api_version}'
  53. class EndpointConnectionError(KSCoreError):
  54. fmt = (
  55. 'Could not connect to the endpoint URL: "{endpoint_url}"')
  56. class ConnectionClosedError(ConnectionError):
  57. fmt = (
  58. 'Connection was closed before we received a valid response '
  59. 'from endpoint URL: "{endpoint_url}".')
  60. def __init__(self, **kwargs):
  61. msg = self.fmt.format(**kwargs)
  62. kwargs.pop('endpoint_url')
  63. super(ConnectionClosedError, self).__init__(msg, **kwargs)
  64. class NoCredentialsError(KSCoreError):
  65. """
  66. No credentials could be found
  67. """
  68. fmt = 'Unable to locate credentials'
  69. class PartialCredentialsError(KSCoreError):
  70. """
  71. Only partial credentials were found.
  72. :ivar cred_var: The missing credential variable name.
  73. """
  74. fmt = 'Partial credentials found in {provider}, missing: {cred_var}'
  75. class UnknownSignatureVersionError(KSCoreError):
  76. """
  77. Requested Signature Version is not known.
  78. :ivar signature_version: The name of the requested signature version.
  79. """
  80. fmt = 'Unknown Signature Version: {signature_version}.'
  81. class ServiceNotInRegionError(KSCoreError):
  82. """
  83. The service is not available in requested region.
  84. :ivar service_name: The name of the service.
  85. :ivar region_name: The name of the region.
  86. """
  87. fmt = 'Service {service_name} not available in region {region_name}'
  88. class BaseEndpointResolverError(KSCoreError):
  89. """Base error for endpoint resolving errors.
  90. Should never be raised directly, but clients can catch
  91. this exception if they want to generically handle any errors
  92. during the endpoint resolution process.
  93. """
  94. class NoRegionError(BaseEndpointResolverError):
  95. """No region was specified."""
  96. fmt = 'You must specify a region.'
  97. class UnknownEndpointError(BaseEndpointResolverError, ValueError):
  98. """
  99. Could not construct an endpoint.
  100. :ivar service_name: The name of the service.
  101. :ivar region_name: The name of the region.
  102. """
  103. fmt = (
  104. 'Unable to construct an endpoint for '
  105. '{service_name} in region {region_name}')
  106. class ProfileNotFound(KSCoreError):
  107. """
  108. The specified configuration profile was not found in the
  109. configuration file.
  110. :ivar profile: The name of the profile the user attempted to load.
  111. """
  112. fmt = 'The config profile ({profile}) could not be found'
  113. class ConfigParseError(KSCoreError):
  114. """
  115. The configuration file could not be parsed.
  116. :ivar path: The path to the configuration file.
  117. """
  118. fmt = 'Unable to parse config file: {path}'
  119. class ConfigNotFound(KSCoreError):
  120. """
  121. The specified configuration file could not be found.
  122. :ivar path: The path to the configuration file.
  123. """
  124. fmt = 'The specified config file ({path}) could not be found.'
  125. class MissingParametersError(KSCoreError):
  126. """
  127. One or more required parameters were not supplied.
  128. :ivar object: The object that has missing parameters.
  129. This can be an operation or a parameter (in the
  130. case of inner params). The str() of this object
  131. will be used so it doesn't need to implement anything
  132. other than str().
  133. :ivar missing: The names of the missing parameters.
  134. """
  135. fmt = ('The following required parameters are missing for '
  136. '{object_name}: {missing}')
  137. class ValidationError(KSCoreError):
  138. """
  139. An exception occurred validating parameters.
  140. Subclasses must accept a ``value`` and ``param``
  141. argument in their ``__init__``.
  142. :ivar value: The value that was being validated.
  143. :ivar param: The parameter that failed validation.
  144. :ivar type_name: The name of the underlying type.
  145. """
  146. fmt = ("Invalid value ('{value}') for param {param} "
  147. "of type {type_name} ")
  148. class ParamValidationError(KSCoreError):
  149. fmt = 'Parameter validation failed:\n{report}'
  150. # These exceptions subclass from ValidationError so that code
  151. # can just 'except ValidationError' to catch any possibly validation
  152. # error.
  153. class UnknownKeyError(ValidationError):
  154. """
  155. Unknown key in a struct paramster.
  156. :ivar value: The value that was being checked.
  157. :ivar param: The name of the parameter.
  158. :ivar choices: The valid choices the value can be.
  159. """
  160. fmt = ("Unknown key '{value}' for param '{param}'. Must be one "
  161. "of: {choices}")
  162. class RangeError(ValidationError):
  163. """
  164. A parameter value was out of the valid range.
  165. :ivar value: The value that was being checked.
  166. :ivar param: The parameter that failed validation.
  167. :ivar min_value: The specified minimum value.
  168. :ivar max_value: The specified maximum value.
  169. """
  170. fmt = ('Value out of range for param {param}: '
  171. '{min_value} <= {value} <= {max_value}')
  172. class UnknownParameterError(ValidationError):
  173. """
  174. Unknown top level parameter.
  175. :ivar name: The name of the unknown parameter.
  176. :ivar operation: The name of the operation.
  177. :ivar choices: The valid choices the parameter name can be.
  178. """
  179. fmt = (
  180. "Unknown parameter '{name}' for operation {operation}. Must be one "
  181. "of: {choices}"
  182. )
  183. class AliasConflictParameterError(ValidationError):
  184. """
  185. Error when an alias is provided for a parameter as well as the original.
  186. :ivar original: The name of the original parameter.
  187. :ivar alias: The name of the alias
  188. :ivar operation: The name of the operation.
  189. """
  190. fmt = (
  191. "Parameter '{original}' and its alias '{alias}' were provided "
  192. "for operation {operation}. Only one of them may be used."
  193. )
  194. class UnknownServiceStyle(KSCoreError):
  195. """
  196. Unknown style of service invocation.
  197. :ivar service_style: The style requested.
  198. """
  199. fmt = 'The service style ({service_style}) is not understood.'
  200. class PaginationError(KSCoreError):
  201. fmt = 'Error during pagination: {message}'
  202. class OperationNotPageableError(KSCoreError):
  203. fmt = 'Operation cannot be paginated: {operation_name}'
  204. class ChecksumError(KSCoreError):
  205. """The expected checksum did not match the calculated checksum.
  206. """
  207. fmt = ('Checksum {checksum_type} failed, expected checksum '
  208. '{expected_checksum} did not match calculated checksum '
  209. '{actual_checksum}.')
  210. class UnseekableStreamError(KSCoreError):
  211. """Need to seek a stream, but stream does not support seeking.
  212. """
  213. fmt = ('Need to rewind the stream {stream_object}, but stream '
  214. 'is not seekable.')
  215. class WaiterError(KSCoreError):
  216. """Waiter failed to reach desired state."""
  217. fmt = 'Waiter {name} failed: {reason}'
  218. class IncompleteReadError(KSCoreError):
  219. """HTTP response did not return expected number of bytes."""
  220. fmt = ('{actual_bytes} read, but total bytes '
  221. 'expected is {expected_bytes}.')
  222. class InvalidExpressionError(KSCoreError):
  223. """Expression is either invalid or too complex."""
  224. fmt = 'Invalid expression {expression}: Only dotted lookups are supported.'
  225. class UnknownCredentialError(KSCoreError):
  226. """Tried to insert before/after an unregistered credential type."""
  227. fmt = 'Credential named {name} not found.'
  228. class WaiterConfigError(KSCoreError):
  229. """Error when processing waiter configuration."""
  230. fmt = 'Error processing waiter config: {error_msg}'
  231. class UnknownClientMethodError(KSCoreError):
  232. """Error when trying to access a method on a client that does not exist."""
  233. fmt = 'Client does not have method: {method_name}'
  234. class UnsupportedSignatureVersionError(KSCoreError):
  235. """Error when trying to access a method on a client that does not exist."""
  236. fmt = 'Signature version is not supported: {signature_version}'
  237. class ClientError(Exception):
  238. MSG_TEMPLATE = (
  239. 'An error occurred ({error_code}) when calling the {operation_name} '
  240. 'operation: {error_message}')
  241. def __init__(self, error_response, operation_name):
  242. if sys.version_info[0] < 3:
  243. msg = self.MSG_TEMPLATE.format(
  244. error_code=error_response['Error'].get('Code', 'Unknown'),
  245. error_message=error_response['Error'].get('Message', 'Unknown').encode("utf-8"),
  246. operation_name=operation_name)
  247. else:
  248. msg = self.MSG_TEMPLATE.format(
  249. error_code=error_response['Error'].get('Code', 'Unknown'),
  250. error_message=error_response['Error'].get('Message', 'Unknown'),
  251. operation_name=operation_name)
  252. super(ClientError, self).__init__(msg)
  253. self.response = error_response
  254. class UnsupportedTLSVersionWarning(Warning):
  255. """Warn when an openssl version that uses TLS 1.2 is required"""
  256. pass
  257. class ImminentRemovalWarning(Warning):
  258. pass
  259. class InvalidDNSNameError(KSCoreError):
  260. """Error when virtual host path is forced on a non-DNS compatible bucket"""
  261. fmt = (
  262. 'Bucket named {bucket_name} is not DNS compatible. Virtual '
  263. 'hosted-style addressing cannot be used. The addressing style '
  264. 'can be configured by removing the addressing_style value '
  265. 'or setting that value to \'path\' or \'auto\' in the KSYUN Config '
  266. 'file or in the kscore.client.Config object.'
  267. )
  268. class InvalidS3AddressingStyleError(KSCoreError):
  269. """Error when an invalid path style is specified"""
  270. fmt = (
  271. 'S3 addressing style {s3_addressing_style} is invaild. Valid options '
  272. 'are: \'auto\', \'virtual\', and \'path\''
  273. )
  274. class StubResponseError(KSCoreError):
  275. fmt = 'Error getting response stub for operation {operation_name}: {reason}'
  276. class StubAssertionError(StubResponseError, AssertionError):
  277. fmt = 'Error getting response stub for operation {operation_name}: {reason}'
  278. class InvalidConfigError(KSCoreError):
  279. fmt = '{error_msg}'
  280. class RefreshWithMFAUnsupportedError(KSCoreError):
  281. fmt = 'Cannot refresh credentials: MFA token required.'
  282. class MD5UnavailableError(KSCoreError):
  283. fmt = "This system does not support MD5 generation."