regioninfo.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. def load_endpoint_json(path):
  28. """
  29. Loads a given JSON file & returns it.
  30. :param path: The path to the JSON file
  31. :type path: string
  32. :returns: The loaded data
  33. """
  34. with open(path, 'r') as endpoints_file:
  35. return json.load(endpoints_file)
  36. def merge_endpoints(defaults, additions):
  37. """
  38. Given an existing set of endpoint data, this will deep-update it with
  39. any similarly structured data in the additions.
  40. :param defaults: The existing endpoints data
  41. :type defaults: dict
  42. :param defaults: The additional endpoints data
  43. :type defaults: dict
  44. :returns: The modified endpoints data
  45. :rtype: dict
  46. """
  47. # We can't just do an ``defaults.update(...)`` here, as that could
  48. # *overwrite* regions if present in both.
  49. # We'll iterate instead, essentially doing a deeper merge.
  50. for service, region_info in additions.items():
  51. # Set the default, if not present, to an empty dict.
  52. defaults.setdefault(service, {})
  53. defaults[service].update(region_info)
  54. return defaults
  55. def load_regions():
  56. """
  57. Actually load the region/endpoint information from the JSON files.
  58. By default, this loads from the default included ``boto/endpoints.json``
  59. file.
  60. Users can override/extend this by supplying either a ``BOTO_ENDPOINTS``
  61. environment variable or a ``endpoints_path`` config variable, either of
  62. which should be an absolute path to the user's JSON file.
  63. :returns: The endpoints data
  64. :rtype: dict
  65. """
  66. # Load the defaults first.
  67. endpoints = load_endpoint_json(boto.ENDPOINTS_PATH)
  68. additional_path = None
  69. # Try the ENV var. If not, check the config file.
  70. if os.environ.get('BOTO_ENDPOINTS'):
  71. additional_path = os.environ['BOTO_ENDPOINTS']
  72. elif boto.config.get('Boto', 'endpoints_path'):
  73. additional_path = boto.config.get('Boto', 'endpoints_path')
  74. # If there's a file provided, we'll load it & additively merge it into
  75. # the endpoints.
  76. if additional_path:
  77. additional = load_endpoint_json(additional_path)
  78. endpoints = merge_endpoints(endpoints, additional)
  79. return endpoints
  80. def get_regions(service_name, region_cls=None, connection_cls=None):
  81. """
  82. Given a service name (like ``ec2``), returns a list of ``RegionInfo``
  83. objects for that service.
  84. This leverages the ``endpoints.json`` file (+ optional user overrides) to
  85. configure/construct all the objects.
  86. :param service_name: The name of the service to construct the ``RegionInfo``
  87. objects for. Ex: ``ec2``, ``s3``, ``sns``, etc.
  88. :type service_name: string
  89. :param region_cls: (Optional) The class to use when constructing. By
  90. default, this is ``RegionInfo``.
  91. :type region_cls: class
  92. :param connection_cls: (Optional) The connection class for the
  93. ``RegionInfo`` object. Providing this allows the ``connect`` method on
  94. the ``RegionInfo`` to work. Default is ``None`` (no connection).
  95. :type connection_cls: class
  96. :returns: A list of configured ``RegionInfo`` objects
  97. :rtype: list
  98. """
  99. endpoints = load_regions()
  100. if service_name not in endpoints:
  101. raise BotoClientError(
  102. "Service '%s' not found in endpoints." % service_name
  103. )
  104. if region_cls is None:
  105. region_cls = RegionInfo
  106. region_objs = []
  107. for region_name, endpoint in endpoints.get(service_name, {}).items():
  108. region_objs.append(
  109. region_cls(
  110. name=region_name,
  111. endpoint=endpoint,
  112. connection_cls=connection_cls
  113. )
  114. )
  115. return region_objs
  116. class RegionInfo(object):
  117. """
  118. Represents an AWS Region
  119. """
  120. def __init__(self, connection=None, name=None, endpoint=None,
  121. connection_cls=None):
  122. self.connection = connection
  123. self.name = name
  124. self.endpoint = endpoint
  125. self.connection_cls = connection_cls
  126. def __repr__(self):
  127. return 'RegionInfo:%s' % self.name
  128. def startElement(self, name, attrs, connection):
  129. return None
  130. def endElement(self, name, value, connection):
  131. if name == 'regionName':
  132. self.name = value
  133. elif name == 'regionEndpoint':
  134. self.endpoint = value
  135. else:
  136. setattr(self, name, value)
  137. def connect(self, **kw_params):
  138. """
  139. Connect to this Region's endpoint. Returns an connection
  140. object pointing to the endpoint associated with this region.
  141. You may pass any of the arguments accepted by the connection
  142. class's constructor as keyword arguments and they will be
  143. passed along to the connection object.
  144. :rtype: Connection object
  145. :return: The connection to this regions endpoint
  146. """
  147. if self.connection_cls:
  148. return self.connection_cls(region=self, **kw_params)