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.

430 lines
17 KiB

  1. #!/usr/bin/env 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. # Add range of hosts: inventory.py 10.10.1.3-10.10.1.5
  21. # Add hosts with different ip and access ip:
  22. # inventory.py 10.0.0.1,192.168.10.1 10.0.0.2,192.168.10.2 10.0.0.3,192.168.1.3
  23. # Add hosts with a specific hostname, ip, and optional access ip:
  24. # inventory.py first,10.0.0.1,192.168.10.1 second,10.0.0.2 last,10.0.0.3
  25. # Delete a host: inventory.py -10.10.1.3
  26. # Delete a host by id: inventory.py -node1
  27. #
  28. # Load a YAML or JSON file with inventory data: inventory.py load hosts.yaml
  29. # YAML file should be in the following format:
  30. # group1:
  31. # host1:
  32. # ip: X.X.X.X
  33. # var: val
  34. # group2:
  35. # host2:
  36. # ip: X.X.X.X
  37. from collections import OrderedDict
  38. from ipaddress import ip_address
  39. from ruamel.yaml import YAML
  40. import os
  41. import re
  42. import subprocess
  43. import sys
  44. ROLES = ['all', 'kube-master', 'kube-node', 'etcd', 'k8s-cluster',
  45. 'calico-rr']
  46. PROTECTED_NAMES = ROLES
  47. AVAILABLE_COMMANDS = ['help', 'print_cfg', 'print_ips', 'print_hostnames',
  48. 'load']
  49. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  50. '0': False, 'no': False, 'false': False, 'off': False}
  51. yaml = YAML()
  52. yaml.Representer.add_representer(OrderedDict, yaml.Representer.represent_dict)
  53. def get_var_as_bool(name, default):
  54. value = os.environ.get(name, '')
  55. return _boolean_states.get(value.lower(), default)
  56. # Configurable as shell vars start
  57. CONFIG_FILE = os.environ.get("CONFIG_FILE", "./inventory/sample/hosts.yaml")
  58. KUBE_MASTERS = int(os.environ.get("KUBE_MASTERS_MASTERS", 2))
  59. # Reconfigures cluster distribution at scale
  60. SCALE_THRESHOLD = int(os.environ.get("SCALE_THRESHOLD", 50))
  61. MASSIVE_SCALE_THRESHOLD = int(os.environ.get("SCALE_THRESHOLD", 200))
  62. DEBUG = get_var_as_bool("DEBUG", True)
  63. HOST_PREFIX = os.environ.get("HOST_PREFIX", "node")
  64. USE_REAL_HOSTNAME = get_var_as_bool("USE_REAL_HOSTNAME", False)
  65. # Configurable as shell vars end
  66. class KubesprayInventory(object):
  67. def __init__(self, changed_hosts=None, config_file=None):
  68. self.config_file = config_file
  69. self.yaml_config = {}
  70. if self.config_file:
  71. try:
  72. self.hosts_file = open(config_file, 'r')
  73. self.yaml_config = yaml.load_all(self.hosts_file)
  74. except OSError:
  75. pass
  76. if changed_hosts and changed_hosts[0] in AVAILABLE_COMMANDS:
  77. self.parse_command(changed_hosts[0], changed_hosts[1:])
  78. sys.exit(0)
  79. self.ensure_required_groups(ROLES)
  80. if changed_hosts:
  81. changed_hosts = self.range2ips(changed_hosts)
  82. self.hosts = self.build_hostnames(changed_hosts)
  83. self.purge_invalid_hosts(self.hosts.keys(), PROTECTED_NAMES)
  84. self.set_all(self.hosts)
  85. self.set_k8s_cluster()
  86. etcd_hosts_count = 3 if len(self.hosts.keys()) >= 3 else 1
  87. self.set_etcd(list(self.hosts.keys())[:etcd_hosts_count])
  88. if len(self.hosts) >= SCALE_THRESHOLD:
  89. self.set_kube_master(list(self.hosts.keys())[
  90. etcd_hosts_count:(etcd_hosts_count + KUBE_MASTERS)])
  91. else:
  92. self.set_kube_master(list(self.hosts.keys())[:KUBE_MASTERS])
  93. self.set_kube_node(self.hosts.keys())
  94. if len(self.hosts) >= SCALE_THRESHOLD:
  95. self.set_calico_rr(list(self.hosts.keys())[:etcd_hosts_count])
  96. else: # Show help if no options
  97. self.show_help()
  98. sys.exit(0)
  99. self.write_config(self.config_file)
  100. def write_config(self, config_file):
  101. if config_file:
  102. with open(self.config_file, 'w') as f:
  103. yaml.dump(self.yaml_config, f)
  104. else:
  105. print("WARNING: Unable to save config. Make sure you set "
  106. "CONFIG_FILE env var.")
  107. def debug(self, msg):
  108. if DEBUG:
  109. print("DEBUG: {0}".format(msg))
  110. def get_ip_from_opts(self, optstring):
  111. if 'ip' in optstring:
  112. return optstring['ip']
  113. else:
  114. raise ValueError("IP parameter not found in options")
  115. def ensure_required_groups(self, groups):
  116. for group in groups:
  117. if group == 'all':
  118. self.debug("Adding group {0}".format(group))
  119. if group not in self.yaml_config:
  120. all_dict = OrderedDict([('hosts', OrderedDict({})),
  121. ('children', OrderedDict({}))])
  122. self.yaml_config = {'all': all_dict}
  123. else:
  124. self.debug("Adding group {0}".format(group))
  125. if group not in self.yaml_config['all']['children']:
  126. self.yaml_config['all']['children'][group] = {'hosts': {}}
  127. def get_host_id(self, host):
  128. '''Returns integer host ID (without padding) from a given hostname.'''
  129. try:
  130. short_hostname = host.split('.')[0]
  131. return int(re.findall("\\d+$", short_hostname)[-1])
  132. except IndexError:
  133. raise ValueError("Host name must end in an integer")
  134. def build_hostnames(self, changed_hosts):
  135. existing_hosts = OrderedDict()
  136. highest_host_id = 0
  137. try:
  138. for host in self.yaml_config['all']['hosts']:
  139. existing_hosts[host] = self.yaml_config['all']['hosts'][host]
  140. host_id = self.get_host_id(host)
  141. if host_id > highest_host_id:
  142. highest_host_id = host_id
  143. except Exception:
  144. pass
  145. # FIXME(mattymo): Fix condition where delete then add reuses highest id
  146. next_host_id = highest_host_id + 1
  147. next_host = ""
  148. all_hosts = existing_hosts.copy()
  149. for host in changed_hosts:
  150. if host[0] == "-":
  151. realhost = host[1:]
  152. if self.exists_hostname(all_hosts, realhost):
  153. self.debug("Marked {0} for deletion.".format(realhost))
  154. all_hosts.pop(realhost)
  155. elif self.exists_ip(all_hosts, realhost):
  156. self.debug("Marked {0} for deletion.".format(realhost))
  157. self.delete_host_by_ip(all_hosts, realhost)
  158. elif host[0].isdigit():
  159. if ',' in host:
  160. ip, access_ip = host.split(',')
  161. else:
  162. ip = host
  163. access_ip = host
  164. if self.exists_hostname(all_hosts, host):
  165. self.debug("Skipping existing host {0}.".format(host))
  166. continue
  167. elif self.exists_ip(all_hosts, ip):
  168. self.debug("Skipping existing host {0}.".format(ip))
  169. continue
  170. if USE_REAL_HOSTNAME:
  171. cmd = ("ssh -oStrictHostKeyChecking=no "
  172. + access_ip + " 'hostname -s'")
  173. next_host = subprocess.check_output(cmd, shell=True)
  174. next_host = next_host.strip().decode('ascii')
  175. else:
  176. next_host = "{0}{1}".format(HOST_PREFIX, next_host_id)
  177. next_host_id += 1
  178. all_hosts[next_host] = {'ansible_host': access_ip,
  179. 'ip': ip,
  180. 'access_ip': access_ip}
  181. elif host[0].isalpha():
  182. if ',' in host:
  183. try:
  184. hostname, ip, access_ip = host.split(',')
  185. except Exception:
  186. hostname, ip = host.split(',')
  187. access_ip = ip
  188. if self.exists_hostname(all_hosts, host):
  189. self.debug("Skipping existing host {0}.".format(host))
  190. continue
  191. elif self.exists_ip(all_hosts, ip):
  192. self.debug("Skipping existing host {0}.".format(ip))
  193. continue
  194. all_hosts[hostname] = {'ansible_host': access_ip,
  195. 'ip': ip,
  196. 'access_ip': access_ip}
  197. return all_hosts
  198. def range2ips(self, hosts):
  199. reworked_hosts = []
  200. def ips(start_address, end_address):
  201. try:
  202. # Python 3.x
  203. start = int(ip_address(start_address))
  204. end = int(ip_address(end_address))
  205. except Exception:
  206. # Python 2.7
  207. start = int(ip_address(str(start_address)))
  208. end = int(ip_address(str(end_address)))
  209. return [ip_address(ip).exploded for ip in range(start, end + 1)]
  210. for host in hosts:
  211. if '-' in host and not (host.startswith('-') or host[0].isalpha()):
  212. start, end = host.strip().split('-')
  213. try:
  214. reworked_hosts.extend(ips(start, end))
  215. except ValueError:
  216. raise Exception("Range of ip_addresses isn't valid")
  217. else:
  218. reworked_hosts.append(host)
  219. return reworked_hosts
  220. def exists_hostname(self, existing_hosts, hostname):
  221. return hostname in existing_hosts.keys()
  222. def exists_ip(self, existing_hosts, ip):
  223. for host_opts in existing_hosts.values():
  224. if ip == self.get_ip_from_opts(host_opts):
  225. return True
  226. return False
  227. def delete_host_by_ip(self, existing_hosts, ip):
  228. for hostname, host_opts in existing_hosts.items():
  229. if ip == self.get_ip_from_opts(host_opts):
  230. del existing_hosts[hostname]
  231. return
  232. raise ValueError("Unable to find host by IP: {0}".format(ip))
  233. def purge_invalid_hosts(self, hostnames, protected_names=[]):
  234. for role in self.yaml_config['all']['children']:
  235. if role != 'k8s-cluster' and self.yaml_config['all']['children'][role]['hosts']: # noqa
  236. all_hosts = self.yaml_config['all']['children'][role]['hosts'].copy() # noqa
  237. for host in all_hosts.keys():
  238. if host not in hostnames and host not in protected_names:
  239. self.debug(
  240. "Host {0} removed from role {1}".format(host, role)) # noqa
  241. del self.yaml_config['all']['children'][role]['hosts'][host] # noqa
  242. # purge from all
  243. if self.yaml_config['all']['hosts']:
  244. all_hosts = self.yaml_config['all']['hosts'].copy()
  245. for host in all_hosts.keys():
  246. if host not in hostnames and host not in protected_names:
  247. self.debug("Host {0} removed from role all".format(host))
  248. del self.yaml_config['all']['hosts'][host]
  249. def add_host_to_group(self, group, host, opts=""):
  250. self.debug("adding host {0} to group {1}".format(host, group))
  251. if group == 'all':
  252. if self.yaml_config['all']['hosts'] is None:
  253. self.yaml_config['all']['hosts'] = {host: None}
  254. self.yaml_config['all']['hosts'][host] = opts
  255. elif group != 'k8s-cluster:children':
  256. if self.yaml_config['all']['children'][group]['hosts'] is None:
  257. self.yaml_config['all']['children'][group]['hosts'] = {
  258. host: None}
  259. else:
  260. self.yaml_config['all']['children'][group]['hosts'][host] = None # noqa
  261. def set_kube_master(self, hosts):
  262. for host in hosts:
  263. self.add_host_to_group('kube-master', host)
  264. def set_all(self, hosts):
  265. for host, opts in hosts.items():
  266. self.add_host_to_group('all', host, opts)
  267. def set_k8s_cluster(self):
  268. k8s_cluster = {'children': {'kube-master': None, 'kube-node': None}}
  269. self.yaml_config['all']['children']['k8s-cluster'] = k8s_cluster
  270. def set_calico_rr(self, hosts):
  271. for host in hosts:
  272. if host in self.yaml_config['all']['children']['kube-master']:
  273. self.debug("Not adding {0} to calico-rr group because it "
  274. "conflicts with kube-master group".format(host))
  275. continue
  276. if host in self.yaml_config['all']['children']['kube-node']:
  277. self.debug("Not adding {0} to calico-rr group because it "
  278. "conflicts with kube-node group".format(host))
  279. continue
  280. self.add_host_to_group('calico-rr', host)
  281. def set_kube_node(self, hosts):
  282. for host in hosts:
  283. if len(self.yaml_config['all']['hosts']) >= SCALE_THRESHOLD:
  284. if host in self.yaml_config['all']['children']['etcd']['hosts']: # noqa
  285. self.debug("Not adding {0} to kube-node group because of "
  286. "scale deployment and host is in etcd "
  287. "group.".format(host))
  288. continue
  289. if len(self.yaml_config['all']['hosts']) >= MASSIVE_SCALE_THRESHOLD: # noqa
  290. if host in self.yaml_config['all']['children']['kube-master']['hosts']: # noqa
  291. self.debug("Not adding {0} to kube-node group because of "
  292. "scale deployment and host is in kube-master "
  293. "group.".format(host))
  294. continue
  295. self.add_host_to_group('kube-node', host)
  296. def set_etcd(self, hosts):
  297. for host in hosts:
  298. self.add_host_to_group('etcd', host)
  299. def load_file(self, files=None):
  300. '''Directly loads JSON to inventory.'''
  301. if not files:
  302. raise Exception("No input file specified.")
  303. import json
  304. for filename in list(files):
  305. # Try JSON
  306. try:
  307. with open(filename, 'r') as f:
  308. data = json.load(f)
  309. except ValueError:
  310. raise Exception("Cannot read %s as JSON, or CSV", filename)
  311. self.ensure_required_groups(ROLES)
  312. self.set_k8s_cluster()
  313. for group, hosts in data.items():
  314. self.ensure_required_groups([group])
  315. for host, opts in hosts.items():
  316. optstring = {'ansible_host': opts['ip'],
  317. 'ip': opts['ip'],
  318. 'access_ip': opts['ip']}
  319. self.add_host_to_group('all', host, optstring)
  320. self.add_host_to_group(group, host)
  321. self.write_config(self.config_file)
  322. def parse_command(self, command, args=None):
  323. if command == 'help':
  324. self.show_help()
  325. elif command == 'print_cfg':
  326. self.print_config()
  327. elif command == 'print_ips':
  328. self.print_ips()
  329. elif command == 'print_hostnames':
  330. self.print_hostnames()
  331. elif command == 'load':
  332. self.load_file(args)
  333. else:
  334. raise Exception("Invalid command specified.")
  335. def show_help(self):
  336. help_text = '''Usage: inventory.py ip1 [ip2 ...]
  337. Examples: inventory.py 10.10.1.3 10.10.1.4 10.10.1.5
  338. Available commands:
  339. help - Display this message
  340. print_cfg - Write inventory file to stdout
  341. print_ips - Write a space-delimited list of IPs from "all" group
  342. print_hostnames - Write a space-delimited list of Hostnames from "all" group
  343. Advanced usage:
  344. Add another host after initial creation: inventory.py 10.10.1.5
  345. Add range of hosts: inventory.py 10.10.1.3-10.10.1.5
  346. Add hosts with different ip and access ip: inventory.py 10.0.0.1,192.168.10.1 10.0.0.2,192.168.10.2 10.0.0.3,192.168.10.3
  347. Add hosts with a specific hostname, ip, and optional access ip: first,10.0.0.1,192.168.10.1 second,10.0.0.2 last,10.0.0.3
  348. Delete a host: inventory.py -10.10.1.3
  349. Delete a host by id: inventory.py -node1
  350. Configurable env vars:
  351. DEBUG Enable debug printing. Default: True
  352. CONFIG_FILE File to write config to Default: ./inventory/sample/hosts.yaml
  353. HOST_PREFIX Host prefix for generated hosts. Default: node
  354. SCALE_THRESHOLD Separate ETCD role if # of nodes >= 50
  355. MASSIVE_SCALE_THRESHOLD Separate K8s master and ETCD if # of nodes >= 200
  356. ''' # noqa
  357. print(help_text)
  358. def print_config(self):
  359. yaml.dump(self.yaml_config, sys.stdout)
  360. def print_hostnames(self):
  361. print(' '.join(self.yaml_config['all']['hosts'].keys()))
  362. def print_ips(self):
  363. ips = []
  364. for host, opts in self.yaml_config['all']['hosts'].items():
  365. ips.append(self.get_ip_from_opts(opts))
  366. print(' '.join(ips))
  367. def main(argv=None):
  368. if not argv:
  369. argv = sys.argv[1:]
  370. KubesprayInventory(argv, CONFIG_FILE)
  371. if __name__ == "__main__":
  372. sys.exit(main())