awsutil.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # vim: expandtab:tabstop=4:shiftwidth=4
  2. """This module comprises Aws specific utility functions."""
  3. import os
  4. import re
  5. # Buildbot does not have multi_inventory installed
  6. #pylint: disable=no-name-in-module
  7. from openshift_ansible import multi_inventory
  8. class ArgumentError(Exception):
  9. """This class is raised when improper arguments are passed."""
  10. def __init__(self, message):
  11. """Initialize an ArgumentError.
  12. Keyword arguments:
  13. message -- the exact error message being raised
  14. """
  15. super(ArgumentError, self).__init__()
  16. self.message = message
  17. class AwsUtil(object):
  18. """This class contains the AWS utility functions."""
  19. def __init__(self, host_type_aliases=None):
  20. """Initialize the AWS utility class.
  21. Keyword arguments:
  22. host_type_aliases -- a list of aliases to common host-types (e.g. ex-node)
  23. """
  24. host_type_aliases = host_type_aliases or {}
  25. self.host_type_aliases = host_type_aliases
  26. self.file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)))
  27. self.setup_host_type_alias_lookup()
  28. def setup_host_type_alias_lookup(self):
  29. """Sets up the alias to host-type lookup table."""
  30. self.alias_lookup = {}
  31. for key, values in self.host_type_aliases.iteritems():
  32. for value in values:
  33. self.alias_lookup[value] = key
  34. @staticmethod
  35. def get_inventory(args=None, cached=False):
  36. """Calls the inventory script and returns a dictionary containing the inventory."
  37. Keyword arguments:
  38. args -- optional arguments to pass to the inventory script
  39. """
  40. minv = multi_inventory.MultiInventory(args)
  41. if cached:
  42. minv.get_inventory_from_cache()
  43. else:
  44. minv.run()
  45. return minv.result
  46. def get_clusters(self):
  47. """Searches for cluster tags in the inventory and returns all of the clusters found."""
  48. pattern = re.compile(r'^oo_clusterid_(.*)')
  49. clusters = []
  50. inv = self.get_inventory()
  51. for key in inv.keys():
  52. matched = pattern.match(key)
  53. if matched:
  54. clusters.append(matched.group(1))
  55. clusters.sort()
  56. return clusters
  57. def get_environments(self):
  58. """Searches for env tags in the inventory and returns all of the envs found."""
  59. pattern = re.compile(r'^oo_environment_(.*)')
  60. envs = []
  61. inv = self.get_inventory()
  62. for key in inv.keys():
  63. matched = pattern.match(key)
  64. if matched:
  65. envs.append(matched.group(1))
  66. envs.sort()
  67. return envs
  68. def get_host_types(self):
  69. """Searches for host-type tags in the inventory and returns all host-types found."""
  70. pattern = re.compile(r'^oo_hosttype_(.*)')
  71. host_types = []
  72. inv = self.get_inventory()
  73. for key in inv.keys():
  74. matched = pattern.match(key)
  75. if matched:
  76. host_types.append(matched.group(1))
  77. host_types.sort()
  78. return host_types
  79. def get_security_groups(self):
  80. """Searches for security_groups in the inventory and returns all SGs found."""
  81. pattern = re.compile(r'^security_group_(.*)')
  82. groups = []
  83. inv = self.get_inventory()
  84. for key in inv.keys():
  85. matched = pattern.match(key)
  86. if matched:
  87. groups.append(matched.group(1))
  88. groups.sort()
  89. return groups
  90. def build_host_dict_by_env(self, args=None):
  91. """Searches the inventory for hosts in an env and returns their hostvars."""
  92. args = args or []
  93. inv = self.get_inventory(args)
  94. inst_by_env = {}
  95. for _, host in inv['_meta']['hostvars'].items():
  96. # If you don't have an environment tag, we're going to ignore you
  97. if 'ec2_tag_environment' not in host:
  98. continue
  99. if host['ec2_tag_environment'] not in inst_by_env:
  100. inst_by_env[host['ec2_tag_environment']] = {}
  101. host_id = "%s:%s" % (host['ec2_tag_Name'], host['ec2_id'])
  102. inst_by_env[host['ec2_tag_environment']][host_id] = host
  103. return inst_by_env
  104. def print_host_types(self):
  105. """Gets the list of host types and aliases and outputs them in columns."""
  106. host_types = self.get_host_types()
  107. ht_format_str = "%35s"
  108. alias_format_str = "%-20s"
  109. combined_format_str = ht_format_str + " " + alias_format_str
  110. print
  111. print combined_format_str % ('Host Types', 'Aliases')
  112. print combined_format_str % ('----------', '-------')
  113. for host_type in host_types:
  114. aliases = []
  115. if host_type in self.host_type_aliases:
  116. aliases = self.host_type_aliases[host_type]
  117. print combined_format_str % (host_type, ", ".join(aliases))
  118. else:
  119. print ht_format_str % host_type
  120. print
  121. def resolve_host_type(self, host_type):
  122. """Converts a host-type alias into a host-type.
  123. Keyword arguments:
  124. host_type -- The alias or host_type to look up.
  125. Example (depends on aliases defined in config file):
  126. host_type = ex-node
  127. returns: openshift-node
  128. """
  129. if self.alias_lookup.has_key(host_type):
  130. return self.alias_lookup[host_type]
  131. return host_type
  132. @staticmethod
  133. def gen_version_tag(ver):
  134. """Generate the version tag
  135. """
  136. return "oo_version_%s" % ver
  137. @staticmethod
  138. def gen_clusterid_tag(clu):
  139. """Generate the clusterid tag
  140. """
  141. return "oo_clusterid_%s" % clu
  142. @staticmethod
  143. def gen_env_tag(env):
  144. """Generate the environment tag
  145. """
  146. return "oo_environment_%s" % env
  147. def gen_host_type_tag(self, host_type, version):
  148. """Generate the host type tag
  149. """
  150. if version == '2':
  151. host_type = self.resolve_host_type(host_type)
  152. return "oo_hosttype_%s" % host_type
  153. # This function uses all of these params to perform a filters on our host inventory.
  154. # pylint: disable=too-many-arguments
  155. def get_host_list(self, clusters=None, host_type=None, envs=None, version=None, cached=False):
  156. """Get the list of hosts from the inventory using host-type and environment
  157. """
  158. retval = set([])
  159. envs = envs or []
  160. inv = self.get_inventory(cached=cached)
  161. retval.update(inv.get('all_hosts', []))
  162. if clusters:
  163. cluster_hosts = set([])
  164. if len(clusters) > 1:
  165. for cluster in clusters:
  166. clu_tag = AwsUtil.gen_clusterid_tag(cluster)
  167. cluster_hosts.update(inv.get(clu_tag, []))
  168. else:
  169. cluster_hosts.update(inv.get(AwsUtil.gen_clusterid_tag(clusters[0]), []))
  170. retval.intersection_update(cluster_hosts)
  171. if envs:
  172. env_hosts = set([])
  173. if len(envs) > 1:
  174. for env in envs:
  175. env_tag = AwsUtil.gen_env_tag(env)
  176. env_hosts.update(inv.get(env_tag, []))
  177. else:
  178. env_hosts.update(inv.get(AwsUtil.gen_env_tag(envs[0]), []))
  179. retval.intersection_update(env_hosts)
  180. if host_type:
  181. retval.intersection_update(inv.get(self.gen_host_type_tag(host_type, version), []))
  182. if version != 'all':
  183. retval.intersection_update(inv.get(AwsUtil.gen_version_tag(version), []))
  184. return retval