awsutil.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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):
  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. minv.run()
  42. return minv.result
  43. def get_environments(self):
  44. """Searches for env tags in the inventory and returns all of the envs found."""
  45. pattern = re.compile(r'^tag_environment_(.*)')
  46. envs = []
  47. inv = self.get_inventory()
  48. for key in inv.keys():
  49. matched = pattern.match(key)
  50. if matched:
  51. envs.append(matched.group(1))
  52. envs.sort()
  53. return envs
  54. def get_host_types(self):
  55. """Searches for host-type tags in the inventory and returns all host-types found."""
  56. pattern = re.compile(r'^tag_host-type_(.*)')
  57. host_types = []
  58. inv = self.get_inventory()
  59. for key in inv.keys():
  60. matched = pattern.match(key)
  61. if matched:
  62. host_types.append(matched.group(1))
  63. host_types.sort()
  64. return host_types
  65. def get_security_groups(self):
  66. """Searches for security_groups in the inventory and returns all SGs found."""
  67. pattern = re.compile(r'^security_group_(.*)')
  68. groups = []
  69. inv = self.get_inventory()
  70. for key in inv.keys():
  71. matched = pattern.match(key)
  72. if matched:
  73. groups.append(matched.group(1))
  74. groups.sort()
  75. return groups
  76. def build_host_dict_by_env(self, args=None):
  77. """Searches the inventory for hosts in an env and returns their hostvars."""
  78. args = args or []
  79. inv = self.get_inventory(args)
  80. inst_by_env = {}
  81. for _, host in inv['_meta']['hostvars'].items():
  82. # If you don't have an environment tag, we're going to ignore you
  83. if 'ec2_tag_environment' not in host:
  84. continue
  85. if host['ec2_tag_environment'] not in inst_by_env:
  86. inst_by_env[host['ec2_tag_environment']] = {}
  87. host_id = "%s:%s" % (host['ec2_tag_Name'], host['ec2_id'])
  88. inst_by_env[host['ec2_tag_environment']][host_id] = host
  89. return inst_by_env
  90. def print_host_types(self):
  91. """Gets the list of host types and aliases and outputs them in columns."""
  92. host_types = self.get_host_types()
  93. ht_format_str = "%35s"
  94. alias_format_str = "%-20s"
  95. combined_format_str = ht_format_str + " " + alias_format_str
  96. print
  97. print combined_format_str % ('Host Types', 'Aliases')
  98. print combined_format_str % ('----------', '-------')
  99. for host_type in host_types:
  100. aliases = []
  101. if host_type in self.host_type_aliases:
  102. aliases = self.host_type_aliases[host_type]
  103. print combined_format_str % (host_type, ", ".join(aliases))
  104. else:
  105. print ht_format_str % host_type
  106. print
  107. def resolve_host_type(self, host_type):
  108. """Converts a host-type alias into a host-type.
  109. Keyword arguments:
  110. host_type -- The alias or host_type to look up.
  111. Example (depends on aliases defined in config file):
  112. host_type = ex-node
  113. returns: openshift-node
  114. """
  115. if self.alias_lookup.has_key(host_type):
  116. return self.alias_lookup[host_type]
  117. return host_type
  118. @staticmethod
  119. def gen_env_tag(env):
  120. """Generate the environment tag
  121. """
  122. return "tag_environment_%s" % env
  123. def gen_host_type_tag(self, host_type):
  124. """Generate the host type tag
  125. """
  126. host_type = self.resolve_host_type(host_type)
  127. return "tag_host-type_%s" % host_type
  128. def gen_env_host_type_tag(self, host_type, env):
  129. """Generate the environment host type tag
  130. """
  131. host_type = self.resolve_host_type(host_type)
  132. return "tag_env-host-type_%s-%s" % (env, host_type)
  133. def get_host_list(self, host_type=None, envs=None):
  134. """Get the list of hosts from the inventory using host-type and environment
  135. """
  136. envs = envs or []
  137. inv = self.get_inventory()
  138. # We prefer to deal with a list of environments
  139. if issubclass(type(envs), basestring):
  140. if envs == 'all':
  141. envs = self.get_environments()
  142. else:
  143. envs = [envs]
  144. if host_type and envs:
  145. # Both host type and environment were specified
  146. retval = []
  147. for env in envs:
  148. env_host_type_tag = self.gen_env_host_type_tag(host_type, env)
  149. if env_host_type_tag in inv.keys():
  150. retval += inv[env_host_type_tag]
  151. return set(retval)
  152. if envs and not host_type:
  153. # Just environment was specified
  154. retval = []
  155. for env in envs:
  156. env_tag = AwsUtil.gen_env_tag(env)
  157. if env_tag in inv.keys():
  158. retval += inv[env_tag]
  159. return set(retval)
  160. if host_type and not envs:
  161. # Just host-type was specified
  162. retval = []
  163. host_type_tag = self.gen_host_type_tag(host_type)
  164. if host_type_tag in inv.keys():
  165. retval = inv[host_type_tag]
  166. return set(retval)
  167. # We should never reach here!
  168. raise ArgumentError("Invalid combination of parameters")