openshift_ansible.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. # pylint: disable=bad-continuation,missing-docstring,no-self-use,invalid-name,global-statement,global-variable-not-assigned
  2. import socket
  3. import subprocess
  4. import sys
  5. import os
  6. import logging
  7. import yaml
  8. from ooinstall.variants import find_variant
  9. from ooinstall.utils import debug_env
  10. installer_log = logging.getLogger('installer')
  11. CFG = None
  12. ROLES_TO_GROUPS_MAP = {
  13. 'master': 'masters',
  14. 'node': 'nodes',
  15. 'etcd': 'etcd',
  16. 'storage': 'nfs',
  17. 'master_lb': 'lb'
  18. }
  19. VARIABLES_MAP = {
  20. 'ansible_ssh_user': 'ansible_ssh_user',
  21. 'deployment_type': 'deployment_type',
  22. 'variant_subtype': 'deployment_subtype',
  23. 'master_routingconfig_subdomain': 'openshift_master_default_subdomain',
  24. 'proxy_http': 'openshift_http_proxy',
  25. 'proxy_https': 'openshift_https_proxy',
  26. 'proxy_exclude_hosts': 'openshift_no_proxy',
  27. }
  28. HOST_VARIABLES_MAP = {
  29. 'ip': 'openshift_ip',
  30. 'public_ip': 'openshift_public_ip',
  31. 'hostname': 'openshift_hostname',
  32. 'public_hostname': 'openshift_public_hostname',
  33. 'containerized': 'containerized',
  34. }
  35. def set_config(cfg):
  36. global CFG
  37. CFG = cfg
  38. def generate_inventory(hosts):
  39. global CFG
  40. new_nodes = [host for host in hosts if host.is_node() and host.new_host]
  41. scaleup = len(new_nodes) > 0
  42. lb = determine_lb_configuration(hosts)
  43. base_inventory_path = CFG.settings['ansible_inventory_path']
  44. base_inventory = open(base_inventory_path, 'w')
  45. write_inventory_children(base_inventory, scaleup)
  46. write_inventory_vars(base_inventory, lb)
  47. # write_inventory_hosts
  48. for role in CFG.deployment.roles:
  49. # write group block
  50. group = ROLES_TO_GROUPS_MAP.get(role, role)
  51. base_inventory.write("\n[{}]\n".format(group))
  52. # write each host
  53. group_hosts = [host for host in hosts if role in host.roles]
  54. for host in group_hosts:
  55. schedulable = host.is_schedulable_node(hosts)
  56. write_host(host, role, base_inventory, schedulable)
  57. if scaleup:
  58. base_inventory.write('\n[new_nodes]\n')
  59. for node in new_nodes:
  60. write_host(node, 'new_nodes', base_inventory)
  61. base_inventory.close()
  62. return base_inventory_path
  63. def determine_lb_configuration(hosts):
  64. lb = next((host for host in hosts if host.is_master_lb()), None)
  65. if lb:
  66. if lb.hostname is None:
  67. lb.hostname = lb.connect_to
  68. lb.public_hostname = lb.connect_to
  69. return lb
  70. def write_inventory_children(base_inventory, scaleup):
  71. global CFG
  72. base_inventory.write('\n[OSEv3:children]\n')
  73. for role in CFG.deployment.roles:
  74. child = ROLES_TO_GROUPS_MAP.get(role, role)
  75. base_inventory.write('{}\n'.format(child))
  76. if scaleup:
  77. base_inventory.write('new_nodes\n')
  78. # pylint: disable=too-many-branches
  79. def write_inventory_vars(base_inventory, lb):
  80. global CFG
  81. base_inventory.write('\n[OSEv3:vars]\n')
  82. for variable, value in CFG.settings.iteritems():
  83. inventory_var = VARIABLES_MAP.get(variable, None)
  84. if inventory_var and value:
  85. base_inventory.write('{}={}\n'.format(inventory_var, value))
  86. for variable, value in CFG.deployment.variables.iteritems():
  87. inventory_var = VARIABLES_MAP.get(variable, variable)
  88. if value:
  89. base_inventory.write('{}={}\n'.format(inventory_var, value))
  90. if CFG.deployment.variables['ansible_ssh_user'] != 'root':
  91. base_inventory.write('ansible_become=yes\n')
  92. if lb is not None:
  93. base_inventory.write('openshift_master_cluster_method=native\n')
  94. base_inventory.write("openshift_master_cluster_hostname={}\n".format(lb.hostname))
  95. base_inventory.write(
  96. "openshift_master_cluster_public_hostname={}\n".format(lb.public_hostname))
  97. if CFG.settings.get('variant_version', None) == '3.1':
  98. # base_inventory.write('openshift_image_tag=v{}\n'.format(CFG.settings.get('variant_version')))
  99. base_inventory.write('openshift_image_tag=v{}\n'.format('3.1.1.6'))
  100. write_proxy_settings(base_inventory)
  101. # Find the correct deployment type for ansible:
  102. ver = find_variant(CFG.settings['variant'],
  103. version=CFG.settings.get('variant_version', None))[1]
  104. base_inventory.write('deployment_type={}\n'.format(ver.ansible_key))
  105. if getattr(ver, 'variant_subtype', False):
  106. base_inventory.write('deployment_subtype={}\n'.format(ver.deployment_subtype))
  107. if 'OO_INSTALL_ADDITIONAL_REGISTRIES' in os.environ:
  108. base_inventory.write('openshift_docker_additional_registries={}\n'.format(
  109. os.environ['OO_INSTALL_ADDITIONAL_REGISTRIES']))
  110. if 'OO_INSTALL_INSECURE_REGISTRIES' in os.environ:
  111. base_inventory.write('openshift_docker_insecure_registries={}\n'.format(
  112. os.environ['OO_INSTALL_INSECURE_REGISTRIES']))
  113. if 'OO_INSTALL_PUDDLE_REPO' in os.environ:
  114. # We have to double the '{' here for literals
  115. base_inventory.write("openshift_additional_repos=[{{'id': 'ose-devel', "
  116. "'name': 'ose-devel', "
  117. "'baseurl': '{}', "
  118. "'enabled': 1, 'gpgcheck': 0}}]\n".format(os.environ['OO_INSTALL_PUDDLE_REPO']))
  119. for name, role_obj in CFG.deployment.roles.iteritems():
  120. if role_obj.variables:
  121. group_name = ROLES_TO_GROUPS_MAP.get(name, name)
  122. base_inventory.write("\n[{}:vars]\n".format(group_name))
  123. for variable, value in role_obj.variables.iteritems():
  124. inventory_var = VARIABLES_MAP.get(variable, variable)
  125. if value:
  126. base_inventory.write('{}={}\n'.format(inventory_var, value))
  127. base_inventory.write("\n")
  128. def write_proxy_settings(base_inventory):
  129. try:
  130. base_inventory.write("openshift_http_proxy={}\n".format(
  131. CFG.settings['openshift_http_proxy']))
  132. except KeyError:
  133. pass
  134. try:
  135. base_inventory.write("openshift_https_proxy={}\n".format(
  136. CFG.settings['openshift_https_proxy']))
  137. except KeyError:
  138. pass
  139. try:
  140. base_inventory.write("openshift_no_proxy={}\n".format(
  141. CFG.settings['openshift_no_proxy']))
  142. except KeyError:
  143. pass
  144. def write_host(host, role, inventory, schedulable=None):
  145. global CFG
  146. if host.preconfigured:
  147. return
  148. facts = ''
  149. for prop in HOST_VARIABLES_MAP:
  150. if getattr(host, prop):
  151. facts += ' {}={}'.format(HOST_VARIABLES_MAP.get(prop), getattr(host, prop))
  152. if host.other_variables:
  153. for variable, value in host.other_variables.iteritems():
  154. facts += " {}={}".format(variable, value)
  155. if host.node_labels and role == 'node':
  156. facts += ' openshift_node_labels="{}"'.format(host.node_labels)
  157. # Distinguish between three states, no schedulability specified (use default),
  158. # explicitly set to True, or explicitly set to False:
  159. if role != 'node' or schedulable is None:
  160. pass
  161. else:
  162. facts += " openshift_schedulable={}".format(schedulable)
  163. installer_host = socket.gethostname()
  164. if installer_host in [host.connect_to, host.hostname, host.public_hostname]:
  165. facts += ' ansible_connection=local'
  166. if os.geteuid() != 0:
  167. no_pwd_sudo = subprocess.call(['sudo', '-n', 'echo', 'openshift'])
  168. if no_pwd_sudo == 1:
  169. print 'The atomic-openshift-installer requires sudo access without a password.'
  170. sys.exit(1)
  171. facts += ' ansible_become=yes'
  172. inventory.write('{} {}\n'.format(host.connect_to, facts))
  173. def load_system_facts(inventory_file, os_facts_path, env_vars, verbose=False):
  174. """
  175. Retrieves system facts from the remote systems.
  176. """
  177. installer_log.debug("Inside load_system_facts")
  178. installer_log.debug("load_system_facts will run with Ansible/Openshift environment variables:")
  179. debug_env(env_vars)
  180. FNULL = open(os.devnull, 'w')
  181. args = ['ansible-playbook', '-v'] if verbose \
  182. else ['ansible-playbook']
  183. args.extend([
  184. '--inventory-file={}'.format(inventory_file),
  185. os_facts_path])
  186. installer_log.debug("Going to subprocess out to ansible now with these args: %s", ' '.join(args))
  187. installer_log.debug("Subprocess will run with Ansible/Openshift environment variables:")
  188. debug_env(env_vars)
  189. status = subprocess.call(args, env=env_vars, stdout=FNULL)
  190. if status != 0:
  191. installer_log.debug("Exit status from subprocess was not 0")
  192. return [], 1
  193. with open(CFG.settings['ansible_callback_facts_yaml'], 'r') as callback_facts_file:
  194. installer_log.debug("Going to try to read this file: %s", CFG.settings['ansible_callback_facts_yaml'])
  195. try:
  196. callback_facts = yaml.safe_load(callback_facts_file)
  197. except yaml.YAMLError, exc:
  198. print "Error in {}".format(CFG.settings['ansible_callback_facts_yaml']), exc
  199. print "Try deleting and rerunning the atomic-openshift-installer"
  200. sys.exit(1)
  201. return callback_facts, 0
  202. def default_facts(hosts, verbose=False):
  203. global CFG
  204. installer_log.debug("Current global CFG vars here: %s", CFG)
  205. inventory_file = generate_inventory(hosts)
  206. os_facts_path = '{}/playbooks/byo/openshift_facts.yml'.format(CFG.ansible_playbook_directory)
  207. facts_env = os.environ.copy()
  208. facts_env["OO_INSTALL_CALLBACK_FACTS_YAML"] = CFG.settings['ansible_callback_facts_yaml']
  209. facts_env["ANSIBLE_CALLBACK_PLUGINS"] = CFG.settings['ansible_plugins_directory']
  210. facts_env["OPENSHIFT_MASTER_CLUSTER_METHOD"] = 'native'
  211. if 'ansible_log_path' in CFG.settings:
  212. facts_env["ANSIBLE_LOG_PATH"] = CFG.settings['ansible_log_path']
  213. if 'ansible_config' in CFG.settings:
  214. facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
  215. installer_log.debug("facts_env: %s", facts_env)
  216. installer_log.debug("Going to 'load_system_facts' next")
  217. return load_system_facts(inventory_file, os_facts_path, facts_env, verbose)
  218. def run_main_playbook(inventory_file, hosts, hosts_to_run_on, verbose=False):
  219. global CFG
  220. if len(hosts_to_run_on) != len(hosts):
  221. main_playbook_path = os.path.join(CFG.ansible_playbook_directory,
  222. 'playbooks/byo/openshift-node/scaleup.yml')
  223. else:
  224. main_playbook_path = os.path.join(CFG.ansible_playbook_directory,
  225. 'playbooks/byo/openshift-cluster/config.yml')
  226. facts_env = os.environ.copy()
  227. if 'ansible_log_path' in CFG.settings:
  228. facts_env['ANSIBLE_LOG_PATH'] = CFG.settings['ansible_log_path']
  229. # override the ansible config for our main playbook run
  230. if 'ansible_quiet_config' in CFG.settings:
  231. facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_quiet_config']
  232. return run_ansible(main_playbook_path, inventory_file, facts_env, verbose)
  233. def run_ansible(playbook, inventory, env_vars, verbose=False):
  234. installer_log.debug("run_ansible will run with Ansible/Openshift environment variables:")
  235. debug_env(env_vars)
  236. args = ['ansible-playbook', '-v'] if verbose \
  237. else ['ansible-playbook']
  238. args.extend([
  239. '--inventory-file={}'.format(inventory),
  240. playbook])
  241. installer_log.debug("Going to subprocess out to ansible now with these args: %s", ' '.join(args))
  242. return subprocess.call(args, env=env_vars)
  243. def run_uninstall_playbook(hosts, verbose=False):
  244. playbook = os.path.join(CFG.settings['ansible_playbook_directory'],
  245. 'playbooks/adhoc/uninstall.yml')
  246. inventory_file = generate_inventory(hosts)
  247. facts_env = os.environ.copy()
  248. if 'ansible_log_path' in CFG.settings:
  249. facts_env['ANSIBLE_LOG_PATH'] = CFG.settings['ansible_log_path']
  250. if 'ansible_config' in CFG.settings:
  251. facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
  252. # override the ansible config for our main playbook run
  253. if 'ansible_quiet_config' in CFG.settings:
  254. facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_quiet_config']
  255. return run_ansible(playbook, inventory_file, facts_env, verbose)
  256. def run_upgrade_playbook(hosts, playbook, verbose=False):
  257. playbook = os.path.join(CFG.settings['ansible_playbook_directory'],
  258. 'playbooks/byo/openshift-cluster/upgrades/{}'.format(playbook))
  259. # TODO: Upgrade inventory for upgrade?
  260. inventory_file = generate_inventory(hosts)
  261. facts_env = os.environ.copy()
  262. if 'ansible_log_path' in CFG.settings:
  263. facts_env['ANSIBLE_LOG_PATH'] = CFG.settings['ansible_log_path']
  264. if 'ansible_config' in CFG.settings:
  265. facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_config']
  266. # override the ansible config for our main playbook run
  267. if 'ansible_quiet_config' in CFG.settings:
  268. facts_env['ANSIBLE_CONFIG'] = CFG.settings['ansible_quiet_config']
  269. return run_ansible(playbook, inventory_file, facts_env, verbose)