regioninfo.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. # Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/
  2. # Copyright (c) 2010, Eucalyptus Systems, Inc.
  3. # All rights reserved.
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the
  7. # "Software"), to deal in the Software without restriction, including
  8. # without limitation the rights to use, copy, modify, merge, publish, dis-
  9. # tribute, sublicense, and/or sell copies of the Software, and to permit
  10. # persons to whom the Software is furnished to do so, subject to the fol-
  11. # lowing conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included
  14. # in all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  18. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  19. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  20. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. # IN THE SOFTWARE.
  23. import os
  24. import boto
  25. from boto.compat import json
  26. from boto.exception import BotoClientError
  27. from boto.endpoints import BotoEndpointResolver
  28. from boto.endpoints import StaticEndpointBuilder
  29. _endpoints_cache = {}
  30. def load_endpoint_json(path):
  31. """
  32. Loads a given JSON file & returns it.
  33. :param path: The path to the JSON file
  34. :type path: string
  35. :returns: The loaded data
  36. """
  37. return _load_json_file(path)
  38. def _load_json_file(path):
  39. """
  40. Loads a given JSON file & returns it.
  41. :param path: The path to the JSON file
  42. :type path: string
  43. :returns: The loaded data
  44. """
  45. with open(path, 'r') as endpoints_file:
  46. return json.load(endpoints_file)
  47. def merge_endpoints(defaults, additions):
  48. """
  49. Given an existing set of endpoint data, this will deep-update it with
  50. any similarly structured data in the additions.
  51. :param defaults: The existing endpoints data
  52. :type defaults: dict
  53. :param defaults: The additional endpoints data
  54. :type defaults: dict
  55. :returns: The modified endpoints data
  56. :rtype: dict
  57. """
  58. # We can't just do an ``defaults.update(...)`` here, as that could
  59. # *overwrite* regions if present in both.
  60. # We'll iterate instead, essentially doing a deeper merge.
  61. for service, region_info in additions.items():
  62. # Set the default, if not present, to an empty dict.
  63. defaults.setdefault(service, {})
  64. defaults[service].update(region_info)
  65. return defaults
  66. def load_regions():
  67. """
  68. Actually load the region/endpoint information from the JSON files.
  69. By default, this loads from the default included ``boto/endpoints.json``
  70. file.
  71. Users can override/extend this by supplying either a ``BOTO_ENDPOINTS``
  72. environment variable or a ``endpoints_path`` config variable, either of
  73. which should be an absolute path to the user's JSON file.
  74. :returns: The endpoints data
  75. :rtype: dict
  76. """
  77. # Load the defaults first.
  78. endpoints = _load_builtin_endpoints()
  79. additional_path = None
  80. # Try the ENV var. If not, check the config file.
  81. if os.environ.get('BOTO_ENDPOINTS'):
  82. additional_path = os.environ['BOTO_ENDPOINTS']
  83. elif boto.config.get('Boto', 'endpoints_path'):
  84. additional_path = boto.config.get('Boto', 'endpoints_path')
  85. # If there's a file provided, we'll load it & additively merge it into
  86. # the endpoints.
  87. if additional_path:
  88. additional = load_endpoint_json(additional_path)
  89. endpoints = merge_endpoints(endpoints, additional)
  90. return endpoints
  91. def _load_resource_endpoints():
  92. import pkgutil
  93. return json.loads(pkgutil.get_data('boto', 'endpoints.json'))
  94. def _load_builtin_endpoints(_cache=_endpoints_cache):
  95. """Loads the builtin endpoints in the legacy format."""
  96. # If there's a cached response, return it
  97. if _cache:
  98. return _cache
  99. # Load the endpoints from resouces
  100. endpoints = _load_resource_endpoints()
  101. # Build the endpoints into the legacy format
  102. resolver = BotoEndpointResolver(endpoints)
  103. builder = StaticEndpointBuilder(resolver)
  104. endpoints = builder.build_static_endpoints()
  105. # Cache the endpoints and then return them
  106. _cache.update(endpoints)
  107. return _cache
  108. def get_regions(service_name, region_cls=None, connection_cls=None):
  109. """
  110. Given a service name (like ``ec2``), returns a list of ``RegionInfo``
  111. objects for that service.
  112. This leverages the ``endpoints.json`` file (+ optional user overrides) to
  113. configure/construct all the objects.
  114. :param service_name: The name of the service to construct the ``RegionInfo``
  115. objects for. Ex: ``ec2``, ``s3``, ``sns``, etc.
  116. :type service_name: string
  117. :param region_cls: (Optional) The class to use when constructing. By
  118. default, this is ``RegionInfo``.
  119. :type region_cls: class
  120. :param connection_cls: (Optional) The connection class for the
  121. ``RegionInfo`` object. Providing this allows the ``connect`` method on
  122. the ``RegionInfo`` to work. Default is ``None`` (no connection).
  123. :type connection_cls: class
  124. :returns: A list of configured ``RegionInfo`` objects
  125. :rtype: list
  126. """
  127. endpoints = load_regions()
  128. if service_name not in endpoints:
  129. raise BotoClientError(
  130. "Service '%s' not found in endpoints." % service_name
  131. )
  132. if region_cls is None:
  133. region_cls = RegionInfo
  134. region_objs = []
  135. for region_name, endpoint in endpoints.get(service_name, {}).items():
  136. region_objs.append(
  137. region_cls(
  138. name=region_name,
  139. endpoint=endpoint,
  140. connection_cls=connection_cls
  141. )
  142. )
  143. return region_objs
  144. def connect(service_name, region_name, region_cls=None,
  145. connection_cls=None, **kw_params):
  146. """Create a connection class for a given service in a given region.
  147. :param service_name: The name of the service to construct the
  148. ``RegionInfo`` object for, e.g. ``ec2``, ``s3``, etc.
  149. :type service_name: str
  150. :param region_name: The name of the region to connect to, e.g.
  151. ``us-west-2``, ``eu-central-1``, etc.
  152. :type region_name: str
  153. :param region_cls: (Optional) The class to use when constructing. By
  154. default, this is ``RegionInfo``.
  155. :type region_cls: class
  156. :param connection_cls: (Optional) The connection class for the
  157. ``RegionInfo`` object. Providing this allows the ``connect`` method on
  158. the ``RegionInfo`` to work. Default is ``None`` (no connection).
  159. :type connection_cls: class
  160. :returns: A configured connection class.
  161. """
  162. if region_cls is None:
  163. region_cls = RegionInfo
  164. region = _get_region(service_name, region_name, region_cls, connection_cls)
  165. if region is None and _use_endpoint_heuristics():
  166. region = _get_region_with_heuristics(
  167. service_name, region_name, region_cls, connection_cls
  168. )
  169. if region is None:
  170. return None
  171. return region.connect(**kw_params)
  172. def _get_region(service_name, region_name, region_cls=None,
  173. connection_cls=None):
  174. """Finds the region by searching through the known regions."""
  175. for region in get_regions(service_name, region_cls, connection_cls):
  176. if region.name == region_name:
  177. return region
  178. return None
  179. def _get_region_with_heuristics(service_name, region_name, region_cls=None,
  180. connection_cls=None):
  181. """Finds the region using known regions and heuristics."""
  182. endpoints = load_endpoint_json(boto.ENDPOINTS_PATH)
  183. resolver = BotoEndpointResolver(endpoints)
  184. hostname = resolver.resolve_hostname(service_name, region_name)
  185. return region_cls(
  186. name=region_name,
  187. endpoint=hostname,
  188. connection_cls=connection_cls
  189. )
  190. def _use_endpoint_heuristics():
  191. env_var = os.environ.get('BOTO_USE_ENDPOINT_HEURISTICS', 'false').lower()
  192. config_var = boto.config.getbool('Boto', 'use_endpoint_heuristics', False)
  193. return env_var == 'true' or config_var
  194. class RegionInfo(object):
  195. """
  196. Represents an AWS Region
  197. """
  198. def __init__(self, connection=None, name=None, endpoint=None,
  199. connection_cls=None):
  200. self.connection = connection
  201. self.name = name
  202. self.endpoint = endpoint
  203. self.connection_cls = connection_cls
  204. def __repr__(self):
  205. return 'RegionInfo:%s' % self.name
  206. def startElement(self, name, attrs, connection):
  207. return None
  208. def endElement(self, name, value, connection):
  209. if name == 'regionName':
  210. self.name = value
  211. elif name == 'regionEndpoint':
  212. self.endpoint = value
  213. else:
  214. setattr(self, name, value)
  215. def connect(self, **kw_params):
  216. """
  217. Connect to this Region's endpoint. Returns an connection
  218. object pointing to the endpoint associated with this region.
  219. You may pass any of the arguments accepted by the connection
  220. class's constructor as keyword arguments and they will be
  221. passed along to the connection object.
  222. :rtype: Connection object
  223. :return: The connection to this regions endpoint
  224. """
  225. if self.connection_cls:
  226. return self.connection_cls(region=self, **kw_params)