You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

297 lines
10 KiB

  1. #!/usr/bin/python3
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  11. # implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # Usage: inventory.py ip1 [ip2 ...]
  16. # Examples: inventory.py 10.10.1.3 10.10.1.4 10.10.1.5
  17. #
  18. # Advanced usage:
  19. # Add another host after initial creation: inventory.py 10.10.1.5
  20. # Delete a host: inventory.py -10.10.1.3
  21. # Delete a host by id: inventory.py -node1
  22. #
  23. # Load a YAML or JSON file with inventory data: inventory.py load hosts.yaml
  24. # YAML file should be in the following format:
  25. # group1:
  26. # host1:
  27. # ip: X.X.X.X
  28. # var: val
  29. # group2:
  30. # host2:
  31. # ip: X.X.X.X
  32. from collections import OrderedDict
  33. try:
  34. import configparser
  35. except ImportError:
  36. import ConfigParser as configparser
  37. import os
  38. import re
  39. import sys
  40. ROLES = ['kube-master', 'all', 'k8s-cluster:children', 'kube-node', 'etcd']
  41. PROTECTED_NAMES = ROLES
  42. AVAILABLE_COMMANDS = ['help', 'print_cfg', 'print_ips', 'load']
  43. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  44. '0': False, 'no': False, 'false': False, 'off': False}
  45. def get_var_as_bool(name, default):
  46. value = os.environ.get(name, '')
  47. return _boolean_states.get(value.lower(), default)
  48. CONFIG_FILE = os.environ.get("CONFIG_FILE", "./inventory.cfg")
  49. DEBUG = get_var_as_bool("DEBUG", True)
  50. HOST_PREFIX = os.environ.get("HOST_PREFIX", "node")
  51. class KargoInventory(object):
  52. def __init__(self, changed_hosts=None, config_file=None):
  53. self.config = configparser.ConfigParser(allow_no_value=True,
  54. delimiters=('\t', ' '))
  55. self.config_file = config_file
  56. if self.config_file:
  57. self.config.read(self.config_file)
  58. if changed_hosts and changed_hosts[0] in AVAILABLE_COMMANDS:
  59. self.parse_command(changed_hosts[0], changed_hosts[1:])
  60. sys.exit(0)
  61. self.ensure_required_groups(ROLES)
  62. if changed_hosts:
  63. self.hosts = self.build_hostnames(changed_hosts)
  64. self.purge_invalid_hosts(self.hosts.keys(), PROTECTED_NAMES)
  65. self.set_kube_master(list(self.hosts.keys())[:2])
  66. self.set_all(self.hosts)
  67. self.set_k8s_cluster()
  68. self.set_kube_node(self.hosts.keys())
  69. self.set_etcd(list(self.hosts.keys())[:3])
  70. else: # Show help if no options
  71. self.show_help()
  72. sys.exit(0)
  73. self.write_config(self.config_file)
  74. def write_config(self, config_file):
  75. if config_file:
  76. with open(config_file, 'w') as f:
  77. self.config.write(f)
  78. else:
  79. print("WARNING: Unable to save config. Make sure you set "
  80. "CONFIG_FILE env var.")
  81. def debug(self, msg):
  82. if DEBUG:
  83. print("DEBUG: {0}".format(msg))
  84. def get_ip_from_opts(self, optstring):
  85. opts = optstring.split(' ')
  86. for opt in opts:
  87. if '=' not in opt:
  88. continue
  89. k, v = opt.split('=')
  90. if k == "ip":
  91. return v
  92. raise ValueError("IP parameter not found in options")
  93. def ensure_required_groups(self, groups):
  94. for group in groups:
  95. try:
  96. self.debug("Adding group {0}".format(group))
  97. self.config.add_section(group)
  98. except configparser.DuplicateSectionError:
  99. pass
  100. def get_host_id(self, host):
  101. '''Returns integer host ID (without padding) from a given hostname.'''
  102. try:
  103. short_hostname = host.split('.')[0]
  104. return int(re.findall("\d+$", short_hostname)[-1])
  105. except IndexError:
  106. raise ValueError("Host name must end in an integer")
  107. def build_hostnames(self, changed_hosts):
  108. existing_hosts = OrderedDict()
  109. highest_host_id = 0
  110. try:
  111. for host, opts in self.config.items('all'):
  112. existing_hosts[host] = opts
  113. host_id = self.get_host_id(host)
  114. if host_id > highest_host_id:
  115. highest_host_id = host_id
  116. except configparser.NoSectionError:
  117. pass
  118. # FIXME(mattymo): Fix condition where delete then add reuses highest id
  119. next_host_id = highest_host_id + 1
  120. all_hosts = existing_hosts.copy()
  121. for host in changed_hosts:
  122. if host[0] == "-":
  123. realhost = host[1:]
  124. if self.exists_hostname(all_hosts, realhost):
  125. self.debug("Marked {0} for deletion.".format(realhost))
  126. all_hosts.pop(realhost)
  127. elif self.exists_ip(all_hosts, realhost):
  128. self.debug("Marked {0} for deletion.".format(realhost))
  129. self.delete_host_by_ip(all_hosts, realhost)
  130. elif host[0].isdigit():
  131. if self.exists_hostname(all_hosts, host):
  132. self.debug("Skipping existing host {0}.".format(host))
  133. continue
  134. elif self.exists_ip(all_hosts, host):
  135. self.debug("Skipping existing host {0}.".format(host))
  136. continue
  137. next_host = "{0}{1}".format(HOST_PREFIX, next_host_id)
  138. next_host_id += 1
  139. all_hosts[next_host] = "ansible_host={0} ip={1}".format(
  140. host, host)
  141. elif host[0].isalpha():
  142. raise Exception("Adding hosts by hostname is not supported.")
  143. return all_hosts
  144. def exists_hostname(self, existing_hosts, hostname):
  145. return hostname in existing_hosts.keys()
  146. def exists_ip(self, existing_hosts, ip):
  147. for host_opts in existing_hosts.values():
  148. if ip == self.get_ip_from_opts(host_opts):
  149. return True
  150. return False
  151. def delete_host_by_ip(self, existing_hosts, ip):
  152. for hostname, host_opts in existing_hosts.items():
  153. if ip == self.get_ip_from_opts(host_opts):
  154. del existing_hosts[hostname]
  155. return
  156. raise ValueError("Unable to find host by IP: {0}".format(ip))
  157. def purge_invalid_hosts(self, hostnames, protected_names=[]):
  158. for role in self.config.sections():
  159. for host, _ in self.config.items(role):
  160. if host not in hostnames and host not in protected_names:
  161. self.debug("Host {0} removed from role {1}".format(host,
  162. role))
  163. self.config.remove_option(role, host)
  164. def add_host_to_group(self, group, host, opts=""):
  165. self.debug("adding host {0} to group {1}".format(host, group))
  166. self.config.set(group, host, opts)
  167. def set_kube_master(self, hosts):
  168. for host in hosts:
  169. self.add_host_to_group('kube-master', host)
  170. def set_all(self, hosts):
  171. for host, opts in hosts.items():
  172. self.add_host_to_group('all', host, opts)
  173. def set_k8s_cluster(self):
  174. self.add_host_to_group('k8s-cluster:children', 'kube-node')
  175. self.add_host_to_group('k8s-cluster:children', 'kube-master')
  176. def set_kube_node(self, hosts):
  177. for host in hosts:
  178. self.add_host_to_group('kube-node', host)
  179. def set_etcd(self, hosts):
  180. for host in hosts:
  181. self.add_host_to_group('etcd', host)
  182. def load_file(self, files=None):
  183. '''Directly loads JSON, or YAML file to inventory.'''
  184. if not files:
  185. raise Exception("No input file specified.")
  186. import json
  187. import yaml
  188. for filename in list(files):
  189. # Try JSON, then YAML
  190. try:
  191. with open(filename, 'r') as f:
  192. data = json.load(f)
  193. except ValueError:
  194. try:
  195. with open(filename, 'r') as f:
  196. data = yaml.load(f)
  197. print("yaml")
  198. except ValueError:
  199. raise Exception("Cannot read %s as JSON, YAML, or CSV",
  200. filename)
  201. self.ensure_required_groups(ROLES)
  202. self.set_k8s_cluster()
  203. for group, hosts in data.items():
  204. self.ensure_required_groups([group])
  205. for host, opts in hosts.items():
  206. optstring = "ansible_host={0} ip={0}".format(opts['ip'])
  207. for key, val in opts.items():
  208. if key == "ip":
  209. continue
  210. optstring += " {0}={1}".format(key, val)
  211. self.add_host_to_group('all', host, optstring)
  212. self.add_host_to_group(group, host)
  213. self.write_config(self.config_file)
  214. def parse_command(self, command, args=None):
  215. if command == 'help':
  216. self.show_help()
  217. elif command == 'print_cfg':
  218. self.print_config()
  219. elif command == 'print_ips':
  220. self.print_ips()
  221. elif command == 'load':
  222. self.load_file(args)
  223. else:
  224. raise Exception("Invalid command specified.")
  225. def show_help(self):
  226. help_text = '''Usage: inventory.py ip1 [ip2 ...]
  227. Examples: inventory.py 10.10.1.3 10.10.1.4 10.10.1.5
  228. Available commands:
  229. help - Display this message
  230. print_cfg - Write inventory file to stdout
  231. print_ips - Write a space-delimited list of IPs from "all" group
  232. Advanced usage:
  233. Add another host after initial creation: inventory.py 10.10.1.5
  234. Delete a host: inventory.py -10.10.1.3
  235. Delete a host by id: inventory.py -node1'''
  236. print(help_text)
  237. def print_config(self):
  238. self.config.write(sys.stdout)
  239. def print_ips(self):
  240. ips = []
  241. for host, opts in self.config.items('all'):
  242. ips.append(self.get_ip_from_opts(opts))
  243. print(' '.join(ips))
  244. def main(argv=None):
  245. if not argv:
  246. argv = sys.argv[1:]
  247. KargoInventory(argv, CONFIG_FILE)
  248. if __name__ == "__main__":
  249. sys.exit(main())