discovery.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import time
  14. import logging
  15. import weakref
  16. from botocore import xform_name
  17. from botocore.exceptions import BotoCoreError, HTTPClientError, ConnectionError
  18. from botocore.model import OperationNotFoundError
  19. from botocore.utils import CachedProperty
  20. logger = logging.getLogger(__name__)
  21. class EndpointDiscoveryException(BotoCoreError):
  22. pass
  23. class EndpointDiscoveryRequired(EndpointDiscoveryException):
  24. """ Endpoint Discovery is disabled but is required for this operation. """
  25. fmt = 'Endpoint Discovery is not enabled but this operation requires it.'
  26. class EndpointDiscoveryRefreshFailed(EndpointDiscoveryException):
  27. """ Endpoint Discovery failed to the refresh the known endpoints. """
  28. fmt = 'Endpoint Discovery failed to refresh the required endpoints.'
  29. def block_endpoint_discovery_required_operations(model, **kwargs):
  30. endpoint_discovery = model.endpoint_discovery
  31. if endpoint_discovery and endpoint_discovery.get('required'):
  32. raise EndpointDiscoveryRequired()
  33. class EndpointDiscoveryModel(object):
  34. def __init__(self, service_model):
  35. self._service_model = service_model
  36. @CachedProperty
  37. def discovery_operation_name(self):
  38. discovery_operation = self._service_model.endpoint_discovery_operation
  39. return xform_name(discovery_operation.name)
  40. @CachedProperty
  41. def discovery_operation_keys(self):
  42. discovery_operation = self._service_model.endpoint_discovery_operation
  43. keys = []
  44. if discovery_operation.input_shape:
  45. keys = list(discovery_operation.input_shape.members.keys())
  46. return keys
  47. def discovery_required_for(self, operation_name):
  48. try:
  49. operation_model = self._service_model.operation_model(operation_name)
  50. return operation_model.endpoint_discovery.get('required', False)
  51. except OperationNotFoundError:
  52. return False
  53. def discovery_operation_kwargs(self, **kwargs):
  54. input_keys = self.discovery_operation_keys
  55. # Operation and Identifiers are only sent if there are Identifiers
  56. if not kwargs.get('Identifiers'):
  57. kwargs.pop('Operation', None)
  58. kwargs.pop('Identifiers', None)
  59. return dict((k, v) for k, v in kwargs.items() if k in input_keys)
  60. def gather_identifiers(self, operation, params):
  61. return self._gather_ids(operation.input_shape, params)
  62. def _gather_ids(self, shape, params, ids=None):
  63. # Traverse the input shape and corresponding parameters, gathering
  64. # any input fields labeled as an endpoint discovery id
  65. if ids is None:
  66. ids = {}
  67. for member_name, member_shape in shape.members.items():
  68. if member_shape.metadata.get('endpointdiscoveryid'):
  69. ids[member_name] = params[member_name]
  70. elif member_shape.type_name == 'structure' and member_name in params:
  71. self._gather_ids(member_shape, params[member_name], ids)
  72. return ids
  73. class EndpointDiscoveryManager(object):
  74. def __init__(self, client, cache=None, current_time=None, always_discover=True):
  75. if cache is None:
  76. cache = {}
  77. self._cache = cache
  78. self._failed_attempts = {}
  79. if current_time is None:
  80. current_time = time.time
  81. self._time = current_time
  82. self._always_discover = always_discover
  83. # This needs to be a weak ref in order to prevent memory leaks on
  84. # python 2.6
  85. self._client = weakref.proxy(client)
  86. self._model = EndpointDiscoveryModel(client.meta.service_model)
  87. def _parse_endpoints(self, response):
  88. endpoints = response['Endpoints']
  89. current_time = self._time()
  90. for endpoint in endpoints:
  91. cache_time = endpoint.get('CachePeriodInMinutes')
  92. endpoint['Expiration'] = current_time + cache_time * 60
  93. return endpoints
  94. def _cache_item(self, value):
  95. if isinstance(value, dict):
  96. return tuple(sorted(value.items()))
  97. else:
  98. return value
  99. def _create_cache_key(self, **kwargs):
  100. kwargs = self._model.discovery_operation_kwargs(**kwargs)
  101. return tuple(self._cache_item(v) for k, v in sorted(kwargs.items()))
  102. def gather_identifiers(self, operation, params):
  103. return self._model.gather_identifiers(operation, params)
  104. def delete_endpoints(self, **kwargs):
  105. cache_key = self._create_cache_key(**kwargs)
  106. if cache_key in self._cache:
  107. del self._cache[cache_key]
  108. def _describe_endpoints(self, **kwargs):
  109. # This is effectively a proxy to whatever name/kwargs the service
  110. # supports for endpoint discovery.
  111. kwargs = self._model.discovery_operation_kwargs(**kwargs)
  112. operation_name = self._model.discovery_operation_name
  113. discovery_operation = getattr(self._client, operation_name)
  114. logger.debug('Discovering endpoints with kwargs: %s', kwargs)
  115. return discovery_operation(**kwargs)
  116. def _get_current_endpoints(self, key):
  117. if key not in self._cache:
  118. return None
  119. now = self._time()
  120. return [e for e in self._cache[key] if now < e['Expiration']]
  121. def _refresh_current_endpoints(self, **kwargs):
  122. cache_key = self._create_cache_key(**kwargs)
  123. try:
  124. response = self._describe_endpoints(**kwargs)
  125. endpoints = self._parse_endpoints(response)
  126. self._cache[cache_key] = endpoints
  127. self._failed_attempts.pop(cache_key, None)
  128. return endpoints
  129. except (ConnectionError, HTTPClientError):
  130. self._failed_attempts[cache_key] = self._time() + 60
  131. return None
  132. def _recently_failed(self, cache_key):
  133. if cache_key in self._failed_attempts:
  134. now = self._time()
  135. if now < self._failed_attempts[cache_key]:
  136. return True
  137. del self._failed_attempts[cache_key]
  138. return False
  139. def _select_endpoint(self, endpoints):
  140. return endpoints[0]['Address']
  141. def describe_endpoint(self, **kwargs):
  142. operation = kwargs['Operation']
  143. discovery_required = self._model.discovery_required_for(operation)
  144. if not self._always_discover and not discovery_required:
  145. # Discovery set to only run on required operations
  146. logger.debug(
  147. 'Optional discovery disabled. Skipping discovery for Operation: %s'
  148. % operation
  149. )
  150. return None
  151. # Get the endpoint for the provided operation and identifiers
  152. cache_key = self._create_cache_key(**kwargs)
  153. endpoints = self._get_current_endpoints(cache_key)
  154. if endpoints:
  155. return self._select_endpoint(endpoints)
  156. # All known endpoints are stale
  157. recently_failed = self._recently_failed(cache_key)
  158. if not recently_failed:
  159. # We haven't failed to discover recently, go ahead and refresh
  160. endpoints = self._refresh_current_endpoints(**kwargs)
  161. if endpoints:
  162. return self._select_endpoint(endpoints)
  163. # Discovery has failed recently, do our best to get an endpoint
  164. logger.debug('Endpoint Discovery has failed for: %s', kwargs)
  165. stale_entries = self._cache.get(cache_key, None)
  166. if stale_entries:
  167. # We have stale entries, use those while discovery is failing
  168. return self._select_endpoint(stale_entries)
  169. if discovery_required:
  170. # It looks strange to be checking recently_failed again but,
  171. # this informs us as to whether or not we tried to refresh earlier
  172. if recently_failed:
  173. # Discovery is required and we haven't already refreshed
  174. endpoints = self._refresh_current_endpoints(**kwargs)
  175. if endpoints:
  176. return self._select_endpoint(endpoints)
  177. # No endpoints even refresh, raise hard error
  178. raise EndpointDiscoveryRefreshFailed()
  179. # Discovery is optional, just use the default endpoint for now
  180. return None
  181. class EndpointDiscoveryHandler(object):
  182. def __init__(self, manager):
  183. self._manager = manager
  184. def register(self, events, service_id):
  185. events.register(
  186. 'before-parameter-build.%s' % service_id, self.gather_identifiers
  187. )
  188. events.register_first(
  189. 'request-created.%s' % service_id, self.discover_endpoint
  190. )
  191. events.register('needs-retry.%s' % service_id, self.handle_retries)
  192. def gather_identifiers(self, params, model, context, **kwargs):
  193. endpoint_discovery = model.endpoint_discovery
  194. # Only continue if the operation supports endpoint discovery
  195. if endpoint_discovery is None:
  196. return
  197. ids = self._manager.gather_identifiers(model, params)
  198. context['discovery'] = {'identifiers': ids}
  199. def discover_endpoint(self, request, operation_name, **kwargs):
  200. ids = request.context.get('discovery', {}).get('identifiers')
  201. if ids is None:
  202. return
  203. endpoint = self._manager.describe_endpoint(
  204. Operation=operation_name, Identifiers=ids
  205. )
  206. if endpoint is None:
  207. logger.debug('Failed to discover and inject endpoint')
  208. return
  209. if not endpoint.startswith('http'):
  210. endpoint = 'https://' + endpoint
  211. logger.debug('Injecting discovered endpoint: %s', endpoint)
  212. request.url = endpoint
  213. def handle_retries(self, request_dict, response, operation, **kwargs):
  214. if response is None:
  215. return None
  216. _, response = response
  217. status = response.get('ResponseMetadata', {}).get('HTTPStatusCode')
  218. error_code = response.get('Error', {}).get('Code')
  219. if status != 421 and error_code != 'InvalidEndpointException':
  220. return None
  221. context = request_dict.get('context', {})
  222. ids = context.get('discovery', {}).get('identifiers')
  223. if ids is None:
  224. return None
  225. # Delete the cached endpoints, forcing a refresh on retry
  226. # TODO: Improve eviction behavior to only evict the bad endpoint if
  227. # there are multiple. This will almost certainly require a lock.
  228. self._manager.delete_endpoints(
  229. Operation=operation.name, Identifiers=ids
  230. )
  231. return 0