1# Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
2# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"). You
5# may not use this file except in compliance with the License. A copy of
6# the License is located at
7#
8# http://aws.amazon.com/apache2.0/
9#
10# or in the "license" file accompanying this file. This file is
11# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
12# ANY KIND, either express or implied. See the License for the specific
13# language governing permissions and limitations under the License.
14
15from botocore.vendored import requests
16from botocore.vendored.requests.packages import urllib3
17
18
19def _exception_from_packed_args(exception_cls, args=None, kwargs=None):
20 # This is helpful for reducing Exceptions that only accept kwargs as
21 # only positional arguments can be provided for __reduce__
22 # Ideally, this would also be a class method on the BotoCoreError
23 # but instance methods cannot be pickled.
24 if args is None:
25 args = ()
26 if kwargs is None:
27 kwargs = {}
28 return exception_cls(*args, **kwargs)
29
30
31class BotoCoreError(Exception):
32 """
33 The base exception class for BotoCore exceptions.
34
35 :ivar msg: The descriptive message associated with the error.
36 """
37
38 fmt = 'An unspecified error occurred'
39
40 def __init__(self, **kwargs):
41 msg = self.fmt.format(**kwargs)
42 Exception.__init__(self, msg)
43 self.kwargs = kwargs
44
45 def __reduce__(self):
46 return _exception_from_packed_args, (self.__class__, None, self.kwargs)
47
48
49class DataNotFoundError(BotoCoreError):
50 """
51 The data associated with a particular path could not be loaded.
52
53 :ivar data_path: The data path that the user attempted to load.
54 """
55
56 fmt = 'Unable to load data for: {data_path}'
57
58
59class UnknownServiceError(DataNotFoundError):
60 """Raised when trying to load data for an unknown service.
61
62 :ivar service_name: The name of the unknown service.
63
64 """
65
66 fmt = (
67 "Unknown service: '{service_name}'. Valid service names are: "
68 "{known_service_names}"
69 )
70
71
72class UnknownRegionError(BotoCoreError):
73 """Raised when trying to load data for an unknown region.
74
75 :ivar region_name: The name of the unknown region.
76
77 """
78
79 fmt = "Unknown region: '{region_name}'. {error_msg}"
80
81
82class ApiVersionNotFoundError(BotoCoreError):
83 """
84 The data associated with either the API version or a compatible one
85 could not be loaded.
86
87 :ivar data_path: The data path that the user attempted to load.
88 :ivar api_version: The API version that the user attempted to load.
89 """
90
91 fmt = 'Unable to load data {data_path} for: {api_version}'
92
93
94class HTTPClientError(BotoCoreError):
95 fmt = 'An HTTP Client raised an unhandled exception: {error}'
96
97 def __init__(self, request=None, response=None, **kwargs):
98 self.request = request
99 self.response = response
100 super().__init__(**kwargs)
101
102 def __reduce__(self):
103 return _exception_from_packed_args, (
104 self.__class__,
105 (self.request, self.response),
106 self.kwargs,
107 )
108
109
110class ConnectionError(BotoCoreError):
111 fmt = 'An HTTP Client failed to establish a connection: {error}'
112
113
114class InvalidIMDSEndpointError(BotoCoreError):
115 fmt = 'Invalid endpoint EC2 Instance Metadata endpoint: {endpoint}'
116
117
118class InvalidIMDSEndpointModeError(BotoCoreError):
119 fmt = (
120 'Invalid EC2 Instance Metadata endpoint mode: {mode}'
121 ' Valid endpoint modes (case-insensitive): {valid_modes}.'
122 )
123
124
125class EndpointConnectionError(ConnectionError):
126 fmt = 'Could not connect to the endpoint URL: "{endpoint_url}"'
127
128
129class SSLError(ConnectionError, requests.exceptions.SSLError):
130 fmt = 'SSL validation failed for {endpoint_url} {error}'
131
132
133class ConnectionClosedError(HTTPClientError):
134 fmt = (
135 'Connection was closed before we received a valid response '
136 'from endpoint URL: "{endpoint_url}".'
137 )
138
139
140class ReadTimeoutError(
141 HTTPClientError,
142 requests.exceptions.ReadTimeout,
143 urllib3.exceptions.ReadTimeoutError,
144):
145 fmt = 'Read timeout on endpoint URL: "{endpoint_url}"'
146
147
148class ConnectTimeoutError(ConnectionError, requests.exceptions.ConnectTimeout):
149 fmt = 'Connect timeout on endpoint URL: "{endpoint_url}"'
150
151
152class ProxyConnectionError(ConnectionError, requests.exceptions.ProxyError):
153 fmt = 'Failed to connect to proxy URL: "{proxy_url}"'
154
155
156class ResponseStreamingError(HTTPClientError):
157 fmt = 'An error occurred while reading from response stream: {error}'
158
159
160class NoCredentialsError(BotoCoreError):
161 """
162 No credentials could be found.
163 """
164
165 fmt = 'Unable to locate credentials'
166
167
168class NoAuthTokenError(BotoCoreError):
169 """
170 No authorization token could be found.
171 """
172
173 fmt = 'Unable to locate authorization token'
174
175
176class TokenRetrievalError(BotoCoreError):
177 """
178 Error attempting to retrieve a token from a remote source.
179
180 :ivar provider: The name of the token provider.
181 :ivar error_msg: The msg explaining why the token could not be retrieved.
182
183 """
184
185 fmt = 'Error when retrieving token from {provider}: {error_msg}'
186
187
188class PartialCredentialsError(BotoCoreError):
189 """
190 Only partial credentials were found.
191
192 :ivar cred_var: The missing credential variable name.
193
194 """
195
196 fmt = 'Partial credentials found in {provider}, missing: {cred_var}'
197
198
199class CredentialRetrievalError(BotoCoreError):
200 """
201 Error attempting to retrieve credentials from a remote source.
202
203 :ivar provider: The name of the credential provider.
204 :ivar error_msg: The msg explaining why credentials could not be
205 retrieved.
206
207 """
208
209 fmt = 'Error when retrieving credentials from {provider}: {error_msg}'
210
211
212class UnknownSignatureVersionError(BotoCoreError):
213 """
214 Requested Signature Version is not known.
215
216 :ivar signature_version: The name of the requested signature version.
217 """
218
219 fmt = 'Unknown Signature Version: {signature_version}.'
220
221
222class ServiceNotInRegionError(BotoCoreError):
223 """
224 The service is not available in requested region.
225
226 :ivar service_name: The name of the service.
227 :ivar region_name: The name of the region.
228 """
229
230 fmt = 'Service {service_name} not available in region {region_name}'
231
232
233class BaseEndpointResolverError(BotoCoreError):
234 """Base error for endpoint resolving errors.
235
236 Should never be raised directly, but clients can catch
237 this exception if they want to generically handle any errors
238 during the endpoint resolution process.
239
240 """
241
242
243class NoRegionError(BaseEndpointResolverError):
244 """No region was specified."""
245
246 fmt = 'You must specify a region.'
247
248
249class EndpointVariantError(BaseEndpointResolverError):
250 """
251 Could not construct modeled endpoint variant.
252
253 :ivar error_msg: The message explaining why the modeled endpoint variant
254 is unable to be constructed.
255
256 """
257
258 fmt = (
259 'Unable to construct a modeled endpoint with the following '
260 'variant(s) {tags}: '
261 )
262
263
264class UnknownEndpointError(BaseEndpointResolverError, ValueError):
265 """
266 Could not construct an endpoint.
267
268 :ivar service_name: The name of the service.
269 :ivar region_name: The name of the region.
270 """
271
272 fmt = (
273 'Unable to construct an endpoint for '
274 '{service_name} in region {region_name}'
275 )
276
277
278class UnknownFIPSEndpointError(BaseEndpointResolverError):
279 """
280 Could not construct a FIPS endpoint.
281
282 :ivar service_name: The name of the service.
283 :ivar region_name: The name of the region.
284 """
285
286 fmt = (
287 'The provided FIPS pseudo-region "{region_name}" is not known for '
288 'the service "{service_name}". A FIPS compliant endpoint cannot be '
289 'constructed.'
290 )
291
292
293class ProfileNotFound(BotoCoreError):
294 """
295 The specified configuration profile was not found in the
296 configuration file.
297
298 :ivar profile: The name of the profile the user attempted to load.
299 """
300
301 fmt = 'The config profile ({profile}) could not be found'
302
303
304class ConfigParseError(BotoCoreError):
305 """
306 The configuration file could not be parsed.
307
308 :ivar path: The path to the configuration file.
309 """
310
311 fmt = 'Unable to parse config file: {path}'
312
313
314class ConfigNotFound(BotoCoreError):
315 """
316 The specified configuration file could not be found.
317
318 :ivar path: The path to the configuration file.
319 """
320
321 fmt = 'The specified config file ({path}) could not be found.'
322
323
324class MissingParametersError(BotoCoreError):
325 """
326 One or more required parameters were not supplied.
327
328 :ivar object: The object that has missing parameters.
329 This can be an operation or a parameter (in the
330 case of inner params). The str() of this object
331 will be used so it doesn't need to implement anything
332 other than str().
333 :ivar missing: The names of the missing parameters.
334 """
335
336 fmt = (
337 'The following required parameters are missing for '
338 '{object_name}: {missing}'
339 )
340
341
342class ValidationError(BotoCoreError):
343 """
344 An exception occurred validating parameters.
345
346 Subclasses must accept a ``value`` and ``param``
347 argument in their ``__init__``.
348
349 :ivar value: The value that was being validated.
350 :ivar param: The parameter that failed validation.
351 :ivar type_name: The name of the underlying type.
352 """
353
354 fmt = "Invalid value ('{value}') for param {param} " "of type {type_name} "
355
356
357class ParamValidationError(BotoCoreError):
358 fmt = 'Parameter validation failed:\n{report}'
359
360
361# These exceptions subclass from ValidationError so that code
362# can just 'except ValidationError' to catch any possibly validation
363# error.
364class UnknownKeyError(ValidationError):
365 """
366 Unknown key in a struct parameter.
367
368 :ivar value: The value that was being checked.
369 :ivar param: The name of the parameter.
370 :ivar choices: The valid choices the value can be.
371 """
372
373 fmt = (
374 "Unknown key '{value}' for param '{param}'. Must be one "
375 "of: {choices}"
376 )
377
378
379class RangeError(ValidationError):
380 """
381 A parameter value was out of the valid range.
382
383 :ivar value: The value that was being checked.
384 :ivar param: The parameter that failed validation.
385 :ivar min_value: The specified minimum value.
386 :ivar max_value: The specified maximum value.
387 """
388
389 fmt = (
390 'Value out of range for param {param}: '
391 '{min_value} <= {value} <= {max_value}'
392 )
393
394
395class UnknownParameterError(ValidationError):
396 """
397 Unknown top level parameter.
398
399 :ivar name: The name of the unknown parameter.
400 :ivar operation: The name of the operation.
401 :ivar choices: The valid choices the parameter name can be.
402 """
403
404 fmt = (
405 "Unknown parameter '{name}' for operation {operation}. Must be one "
406 "of: {choices}"
407 )
408
409
410class InvalidRegionError(ValidationError, ValueError):
411 """
412 Invalid region_name provided to client or resource.
413
414 :ivar region_name: region_name that was being validated.
415 """
416
417 fmt = "Provided region_name '{region_name}' doesn't match a supported format."
418
419
420class AliasConflictParameterError(ValidationError):
421 """
422 Error when an alias is provided for a parameter as well as the original.
423
424 :ivar original: The name of the original parameter.
425 :ivar alias: The name of the alias
426 :ivar operation: The name of the operation.
427 """
428
429 fmt = (
430 "Parameter '{original}' and its alias '{alias}' were provided "
431 "for operation {operation}. Only one of them may be used."
432 )
433
434
435class UnknownServiceStyle(BotoCoreError):
436 """
437 Unknown style of service invocation.
438
439 :ivar service_style: The style requested.
440 """
441
442 fmt = 'The service style ({service_style}) is not understood.'
443
444
445class PaginationError(BotoCoreError):
446 fmt = 'Error during pagination: {message}'
447
448
449class OperationNotPageableError(BotoCoreError):
450 fmt = 'Operation cannot be paginated: {operation_name}'
451
452
453class ChecksumError(BotoCoreError):
454 """The expected checksum did not match the calculated checksum."""
455
456 fmt = (
457 'Checksum {checksum_type} failed, expected checksum '
458 '{expected_checksum} did not match calculated checksum '
459 '{actual_checksum}.'
460 )
461
462
463class UnseekableStreamError(BotoCoreError):
464 """Need to seek a stream, but stream does not support seeking."""
465
466 fmt = (
467 'Need to rewind the stream {stream_object}, but stream '
468 'is not seekable.'
469 )
470
471
472class WaiterError(BotoCoreError):
473 """Waiter failed to reach desired state."""
474
475 fmt = 'Waiter {name} failed: {reason}'
476
477 def __init__(self, name, reason, last_response):
478 super().__init__(name=name, reason=reason)
479 self.last_response = last_response
480
481
482class IncompleteReadError(BotoCoreError):
483 """HTTP response did not return expected number of bytes."""
484
485 fmt = (
486 '{actual_bytes} read, but total bytes ' 'expected is {expected_bytes}.'
487 )
488
489
490class InvalidExpressionError(BotoCoreError):
491 """Expression is either invalid or too complex."""
492
493 fmt = 'Invalid expression {expression}: Only dotted lookups are supported.'
494
495
496class UnknownCredentialError(BotoCoreError):
497 """Tried to insert before/after an unregistered credential type."""
498
499 fmt = 'Credential named {name} not found.'
500
501
502class WaiterConfigError(BotoCoreError):
503 """Error when processing waiter configuration."""
504
505 fmt = 'Error processing waiter config: {error_msg}'
506
507
508class UnknownClientMethodError(BotoCoreError):
509 """Error when trying to access a method on a client that does not exist."""
510
511 fmt = 'Client does not have method: {method_name}'
512
513
514class UnsupportedSignatureVersionError(BotoCoreError):
515 """Error when trying to use an unsupported Signature Version."""
516
517 fmt = 'Signature version(s) are not supported: {signature_version}'
518
519
520class ClientError(Exception):
521 MSG_TEMPLATE = (
522 'An error occurred ({error_code}) when calling the {operation_name} '
523 'operation{retry_info}: {error_message}'
524 )
525
526 def __init__(self, error_response, operation_name):
527 retry_info = self._get_retry_info(error_response)
528 error = error_response.get('Error', {})
529 msg = self.MSG_TEMPLATE.format(
530 error_code=error.get('Code', 'Unknown'),
531 error_message=error.get('Message', 'Unknown'),
532 operation_name=operation_name,
533 retry_info=retry_info,
534 )
535 super().__init__(msg)
536 self.response = error_response
537 self.operation_name = operation_name
538
539 def _get_retry_info(self, response):
540 retry_info = ''
541 if 'ResponseMetadata' in response:
542 metadata = response['ResponseMetadata']
543 if metadata.get('MaxAttemptsReached', False):
544 if 'RetryAttempts' in metadata:
545 retry_info = (
546 f" (reached max retries: {metadata['RetryAttempts']})"
547 )
548 return retry_info
549
550 def __reduce__(self):
551 # Subclasses of ClientError's are dynamically generated and
552 # cannot be pickled unless they are attributes of a
553 # module. So at the very least return a ClientError back.
554 return ClientError, (self.response, self.operation_name)
555
556
557class EventStreamError(ClientError):
558 pass
559
560
561class UnsupportedTLSVersionWarning(Warning):
562 """Warn when an openssl version that uses TLS 1.2 is required"""
563
564 pass
565
566
567class ImminentRemovalWarning(Warning):
568 pass
569
570
571class InvalidDNSNameError(BotoCoreError):
572 """Error when virtual host path is forced on a non-DNS compatible bucket"""
573
574 fmt = (
575 'Bucket named {bucket_name} is not DNS compatible. Virtual '
576 'hosted-style addressing cannot be used. The addressing style '
577 'can be configured by removing the addressing_style value '
578 'or setting that value to \'path\' or \'auto\' in the AWS Config '
579 'file or in the botocore.client.Config object.'
580 )
581
582
583class InvalidS3AddressingStyleError(BotoCoreError):
584 """Error when an invalid path style is specified"""
585
586 fmt = (
587 'S3 addressing style {s3_addressing_style} is invalid. Valid options '
588 'are: \'auto\', \'virtual\', and \'path\''
589 )
590
591
592class UnsupportedS3ArnError(BotoCoreError):
593 """Error when S3 ARN provided to Bucket parameter is not supported"""
594
595 fmt = (
596 'S3 ARN {arn} provided to "Bucket" parameter is invalid. Only '
597 'ARNs for S3 access-points are supported.'
598 )
599
600
601class UnsupportedS3ControlArnError(BotoCoreError):
602 """Error when S3 ARN provided to S3 control parameter is not supported"""
603
604 fmt = 'S3 ARN "{arn}" provided is invalid for this operation. {msg}'
605
606
607class InvalidHostLabelError(BotoCoreError):
608 """Error when an invalid host label would be bound to an endpoint"""
609
610 fmt = (
611 'Invalid host label to be bound to the hostname of the endpoint: '
612 '"{label}".'
613 )
614
615
616class UnsupportedOutpostResourceError(BotoCoreError):
617 """Error when S3 Outpost ARN provided to Bucket parameter is incomplete"""
618
619 fmt = (
620 'S3 Outpost ARN resource "{resource_name}" provided to "Bucket" '
621 'parameter is invalid. Only ARNs for S3 Outpost arns with an '
622 'access-point sub-resource are supported.'
623 )
624
625
626class UnsupportedS3ConfigurationError(BotoCoreError):
627 """Error when an unsupported configuration is used with access-points"""
628
629 fmt = 'Unsupported configuration when using S3: {msg}'
630
631
632class UnsupportedS3AccesspointConfigurationError(BotoCoreError):
633 """Error when an unsupported configuration is used with access-points"""
634
635 fmt = 'Unsupported configuration when using S3 access-points: {msg}'
636
637
638class InvalidEndpointDiscoveryConfigurationError(BotoCoreError):
639 """Error when invalid value supplied for endpoint_discovery_enabled"""
640
641 fmt = (
642 'Unsupported configuration value for endpoint_discovery_enabled. '
643 'Expected one of ("true", "false", "auto") but got {config_value}.'
644 )
645
646
647class UnsupportedS3ControlConfigurationError(BotoCoreError):
648 """Error when an unsupported configuration is used with S3 Control"""
649
650 fmt = 'Unsupported configuration when using S3 Control: {msg}'
651
652
653class InvalidRetryConfigurationError(BotoCoreError):
654 """Error when invalid retry configuration is specified"""
655
656 fmt = (
657 'Cannot provide retry configuration for "{retry_config_option}". '
658 'Valid retry configuration options are: {valid_options}'
659 )
660
661
662class InvalidMaxRetryAttemptsError(InvalidRetryConfigurationError):
663 """Error when invalid retry configuration is specified"""
664
665 fmt = (
666 'Value provided to "max_attempts": {provided_max_attempts} must '
667 'be an integer greater than or equal to {min_value}.'
668 )
669
670
671class InvalidRetryModeError(InvalidRetryConfigurationError):
672 """Error when invalid retry mode configuration is specified"""
673
674 fmt = (
675 'Invalid value provided to "mode": "{provided_retry_mode}" must '
676 'be one of: {valid_modes}'
677 )
678
679
680class InvalidS3UsEast1RegionalEndpointConfigError(BotoCoreError):
681 """Error for invalid s3 us-east-1 regional endpoints configuration"""
682
683 fmt = (
684 'S3 us-east-1 regional endpoint option '
685 '{s3_us_east_1_regional_endpoint_config} is '
686 'invalid. Valid options are: "legacy", "regional"'
687 )
688
689
690class InvalidSTSRegionalEndpointsConfigError(BotoCoreError):
691 """Error when invalid sts regional endpoints configuration is specified"""
692
693 fmt = (
694 'STS regional endpoints option {sts_regional_endpoints_config} is '
695 'invalid. Valid options are: "legacy", "regional"'
696 )
697
698
699class StubResponseError(BotoCoreError):
700 fmt = (
701 'Error getting response stub for operation {operation_name}: {reason}'
702 )
703
704
705class StubAssertionError(StubResponseError, AssertionError):
706 pass
707
708
709class UnStubbedResponseError(StubResponseError):
710 pass
711
712
713class InvalidConfigError(BotoCoreError):
714 fmt = '{error_msg}'
715
716
717class InfiniteLoopConfigError(InvalidConfigError):
718 fmt = (
719 'Infinite loop in credential configuration detected. Attempting to '
720 'load from profile {source_profile} which has already been visited. '
721 'Visited profiles: {visited_profiles}'
722 )
723
724
725class RefreshWithMFAUnsupportedError(BotoCoreError):
726 fmt = 'Cannot refresh credentials: MFA token required.'
727
728
729class MD5UnavailableError(BotoCoreError):
730 fmt = "This system does not support MD5 generation."
731
732
733class MissingDependencyException(BotoCoreError):
734 fmt = "Missing Dependency: {msg}"
735
736
737class MetadataRetrievalError(BotoCoreError):
738 fmt = "Error retrieving metadata: {error_msg}"
739
740
741class UndefinedModelAttributeError(Exception):
742 pass
743
744
745class MissingServiceIdError(UndefinedModelAttributeError):
746 fmt = (
747 "The model being used for the service {service_name} is missing the "
748 "serviceId metadata property, which is required."
749 )
750
751 def __init__(self, **kwargs):
752 msg = self.fmt.format(**kwargs)
753 Exception.__init__(self, msg)
754 self.kwargs = kwargs
755
756
757class SSOError(BotoCoreError):
758 fmt = (
759 "An unspecified error happened when resolving AWS credentials or an "
760 "access token from SSO."
761 )
762
763
764class SSOTokenLoadError(SSOError):
765 fmt = "Error loading SSO Token: {error_msg}"
766
767
768class UnauthorizedSSOTokenError(SSOError):
769 fmt = (
770 "The SSO session associated with this profile has expired or is "
771 "otherwise invalid. To refresh this SSO session run aws sso login "
772 "with the corresponding profile."
773 )
774
775
776class CapacityNotAvailableError(BotoCoreError):
777 fmt = 'Insufficient request capacity available.'
778
779
780class InvalidProxiesConfigError(BotoCoreError):
781 fmt = 'Invalid configuration value(s) provided for proxies_config.'
782
783
784class InvalidDefaultsMode(BotoCoreError):
785 fmt = (
786 'Client configured with invalid defaults mode: {mode}. '
787 'Valid defaults modes include: {valid_modes}.'
788 )
789
790
791class AwsChunkedWrapperError(BotoCoreError):
792 fmt = '{error_msg}'
793
794
795class FlexibleChecksumError(BotoCoreError):
796 fmt = '{error_msg}'
797
798
799class InvalidEndpointConfigurationError(BotoCoreError):
800 fmt = 'Invalid endpoint configuration: {msg}'
801
802
803class EndpointProviderError(BotoCoreError):
804 """Base error for the EndpointProvider class"""
805
806 fmt = '{msg}'
807
808
809class EndpointResolutionError(EndpointProviderError):
810 """Error when input parameters resolve to an error rule"""
811
812 fmt = '{msg}'
813
814
815class UnknownEndpointResolutionBuiltInName(EndpointProviderError):
816 fmt = 'Unknown builtin variable name: {name}'