cli_installer.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. # TODO: Temporarily disabled due to importing old code into openshift-ansible
  2. # repo. We will work on these over time.
  3. # pylint: disable=bad-continuation,missing-docstring,no-self-use,invalid-name,no-value-for-parameter
  4. import click
  5. import os
  6. import re
  7. import sys
  8. from ooinstall import openshift_ansible
  9. from ooinstall import OOConfig
  10. from ooinstall.oo_config import Host
  11. from ooinstall.variants import find_variant, get_variant_version_combos
  12. DEFAULT_ANSIBLE_CONFIG = '/usr/share/atomic-openshift-util/ansible.cfg'
  13. DEFAULT_PLAYBOOK_DIR = '/usr/share/ansible/openshift-ansible/'
  14. def validate_ansible_dir(path):
  15. if not path:
  16. raise click.BadParameter('An ansible path must be provided')
  17. return path
  18. # if not os.path.exists(path)):
  19. # raise click.BadParameter("Path \"{}\" doesn't exist".format(path))
  20. def is_valid_hostname(hostname):
  21. if not hostname or len(hostname) > 255:
  22. return False
  23. if hostname[-1] == ".":
  24. hostname = hostname[:-1] # strip exactly one dot from the right, if present
  25. allowed = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
  26. return all(allowed.match(x) for x in hostname.split("."))
  27. def validate_prompt_hostname(hostname):
  28. if '' == hostname or is_valid_hostname(hostname):
  29. return hostname
  30. raise click.BadParameter('"{}" appears to be an invalid hostname. ' \
  31. 'Please double-check this value i' \
  32. 'and re-enter it.'.format(hostname))
  33. def get_ansible_ssh_user():
  34. click.clear()
  35. message = """
  36. This installation process will involve connecting to remote hosts via ssh. Any
  37. account may be used however if a non-root account is used it must have
  38. passwordless sudo access.
  39. """
  40. click.echo(message)
  41. return click.prompt('User for ssh access', default='root')
  42. def list_hosts(hosts):
  43. hosts_idx = range(len(hosts))
  44. for idx in hosts_idx:
  45. click.echo(' {}: {}'.format(idx, hosts[idx]))
  46. def delete_hosts(hosts):
  47. while True:
  48. list_hosts(hosts)
  49. del_idx = click.prompt('Select host to delete, y/Y to confirm, ' \
  50. 'or n/N to add more hosts', default='n')
  51. try:
  52. del_idx = int(del_idx)
  53. hosts.remove(hosts[del_idx])
  54. except IndexError:
  55. click.echo("\"{}\" doesn't match any hosts listed.".format(del_idx))
  56. except ValueError:
  57. try:
  58. response = del_idx.lower()
  59. if response in ['y', 'n']:
  60. return hosts, response
  61. click.echo("\"{}\" doesn't coorespond to any valid input.".format(del_idx))
  62. except AttributeError:
  63. click.echo("\"{}\" doesn't coorespond to any valid input.".format(del_idx))
  64. return hosts, None
  65. def collect_hosts():
  66. """
  67. Collect host information from user. This will later be filled in using
  68. ansible.
  69. Returns: a list of host information collected from the user
  70. """
  71. click.clear()
  72. click.echo('***Host Configuration***')
  73. message = """
  74. The OpenShift Master serves the API and web console. It also coordinates the
  75. jobs that have to run across the environment. It can even run the datastore.
  76. For wizard based installations the database will be embedded. It's possible to
  77. change this later using etcd from Red Hat Enterprise Linux 7.
  78. Any Masters configured as part of this installation process will also be
  79. configured as Nodes. This is so that the Master will be able to proxy to Pods
  80. from the API. By default this Node will be unscheduleable but this can be changed
  81. after installation with 'oadm manage-node'.
  82. The OpenShift Node provides the runtime environments for containers. It will
  83. host the required services to be managed by the Master.
  84. http://docs.openshift.com/enterprise/latest/architecture/infrastructure_components/kubernetes_infrastructure.html#master
  85. http://docs.openshift.com/enterprise/latest/architecture/infrastructure_components/kubernetes_infrastructure.html#node
  86. """
  87. click.echo(message)
  88. hosts = []
  89. more_hosts = True
  90. ip_regex = re.compile(r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$')
  91. while more_hosts:
  92. host_props = {}
  93. hostname_or_ip = click.prompt('Enter hostname or IP address:',
  94. default='',
  95. value_proc=validate_prompt_hostname)
  96. if ip_regex.match(hostname_or_ip):
  97. host_props['ip'] = hostname_or_ip
  98. else:
  99. host_props['hostname'] = hostname_or_ip
  100. host_props['master'] = click.confirm('Will this host be an OpenShift Master?')
  101. host_props['node'] = True
  102. rpm_or_container = click.prompt('Will this host be RPM or Container based (rpm/container)?',
  103. type=click.Choice(['rpm', 'container']),
  104. default='rpm')
  105. if rpm_or_container == 'container':
  106. host_props['containerized'] = True
  107. else:
  108. host_props['containerized'] = False
  109. host = Host(**host_props)
  110. hosts.append(host)
  111. more_hosts = click.confirm('Do you want to add additional hosts?')
  112. return hosts
  113. def confirm_hosts_facts(oo_cfg, callback_facts):
  114. hosts = oo_cfg.hosts
  115. click.clear()
  116. message = """
  117. A list of the facts gathered from the provided hosts follows. Because it is
  118. often the case that the hostname for a system inside the cluster is different
  119. from the hostname that is resolveable from command line or web clients
  120. these settings cannot be validated automatically.
  121. For some cloud providers the installer is able to gather metadata exposed in
  122. the instance so reasonable defaults will be provided.
  123. Plese confirm that they are correct before moving forward.
  124. """
  125. notes = """
  126. Format:
  127. IP,public IP,hostname,public hostname
  128. Notes:
  129. * The installation host is the hostname from the installer's perspective.
  130. * The IP of the host should be the internal IP of the instance.
  131. * The public IP should be the externally accessible IP associated with the instance
  132. * The hostname should resolve to the internal IP from the instances
  133. themselves.
  134. * The public hostname should resolve to the external ip from hosts outside of
  135. the cloud.
  136. """
  137. # For testing purposes we need to click.echo only once, so build up
  138. # the message:
  139. output = message
  140. default_facts_lines = []
  141. default_facts = {}
  142. validated_facts = {}
  143. for h in hosts:
  144. default_facts[h] = {}
  145. h.ip = callback_facts[str(h)]["common"]["ip"]
  146. h.public_ip = callback_facts[str(h)]["common"]["public_ip"]
  147. h.hostname = callback_facts[str(h)]["common"]["hostname"]
  148. h.public_hostname = callback_facts[str(h)]["common"]["public_hostname"]
  149. validated_facts[h] = {}
  150. default_facts_lines.append(",".join([h.ip,
  151. h.public_ip,
  152. h.hostname,
  153. h.public_hostname]))
  154. output = "%s\n%s" % (output, ",".join([h.ip,
  155. h.public_ip,
  156. h.hostname,
  157. h.public_hostname]))
  158. output = "%s\n%s" % (output, notes)
  159. click.echo(output)
  160. facts_confirmed = click.confirm("Do the above facts look correct?")
  161. if not facts_confirmed:
  162. message = """
  163. Edit %s with the desired values and rerun atomic-openshift-installer with --unattended .
  164. """ % oo_cfg.config_path
  165. click.echo(message)
  166. # Make sure we actually write out the config file.
  167. oo_cfg.save_to_disk()
  168. sys.exit(0)
  169. return default_facts
  170. def get_variant_and_version():
  171. message = "\nWhich variant would you like to install?\n\n"
  172. i = 1
  173. combos = get_variant_version_combos()
  174. for (variant, version) in combos:
  175. message = "%s\n(%s) %s %s" % (message, i, variant.description,
  176. version.name)
  177. i = i + 1
  178. click.echo(message)
  179. response = click.prompt("Choose a variant from above: ", default=1)
  180. product, version = combos[response - 1]
  181. return product, version
  182. def confirm_continue(message):
  183. click.echo(message)
  184. click.confirm("Are you ready to continue?", default=False, abort=True)
  185. return
  186. def error_if_missing_info(oo_cfg):
  187. missing_info = False
  188. if not oo_cfg.hosts:
  189. missing_info = True
  190. click.echo('For unattended installs, hosts must be specified on the '
  191. 'command line or in the config file: %s' % oo_cfg.config_path)
  192. sys.exit(1)
  193. if 'ansible_ssh_user' not in oo_cfg.settings:
  194. click.echo("Must specify ansible_ssh_user in configuration file.")
  195. sys.exit(1)
  196. # Lookup a variant based on the key we were given:
  197. if not oo_cfg.settings['variant']:
  198. click.echo("No variant specified in configuration file.")
  199. sys.exit(1)
  200. ver = None
  201. if 'variant_version' in oo_cfg.settings:
  202. ver = oo_cfg.settings['variant_version']
  203. variant, version = find_variant(oo_cfg.settings['variant'], version=ver)
  204. if variant is None or version is None:
  205. err_variant_name = oo_cfg.settings['variant']
  206. if ver:
  207. err_variant_name = "%s %s" % (err_variant_name, ver)
  208. click.echo("%s is not an installable variant." % err_variant_name)
  209. sys.exit(1)
  210. oo_cfg.settings['variant_version'] = version.name
  211. missing_facts = oo_cfg.calc_missing_facts()
  212. if len(missing_facts) > 0:
  213. missing_info = True
  214. click.echo('For unattended installs, facts must be provided for all masters/nodes:')
  215. for host in missing_facts:
  216. click.echo('Host "%s" missing facts: %s' % (host, ", ".join(missing_facts[host])))
  217. if missing_info:
  218. sys.exit(1)
  219. def get_missing_info_from_user(oo_cfg):
  220. """ Prompts the user for any information missing from the given configuration. """
  221. click.clear()
  222. message = """
  223. Welcome to the OpenShift Enterprise 3 installation.
  224. Please confirm that following prerequisites have been met:
  225. * All systems where OpenShift will be installed are running Red Hat Enterprise
  226. Linux 7.
  227. * All systems are properly subscribed to the required OpenShift Enterprise 3
  228. repositories.
  229. * All systems have run docker-storage-setup (part of the Red Hat docker RPM).
  230. * All systems have working DNS that resolves not only from the perspective of
  231. the installer but also from within the cluster.
  232. When the process completes you will have a default configuration for Masters
  233. and Nodes. For ongoing environment maintenance it's recommended that the
  234. official Ansible playbooks be used.
  235. For more information on installation prerequisites please see:
  236. https://docs.openshift.com/enterprise/latest/admin_guide/install/prerequisites.html
  237. """
  238. confirm_continue(message)
  239. click.clear()
  240. if oo_cfg.settings.get('ansible_ssh_user', '') == '':
  241. oo_cfg.settings['ansible_ssh_user'] = get_ansible_ssh_user()
  242. click.clear()
  243. if not oo_cfg.hosts:
  244. oo_cfg.hosts = collect_hosts()
  245. click.clear()
  246. if oo_cfg.settings.get('variant', '') == '':
  247. variant, version = get_variant_and_version()
  248. oo_cfg.settings['variant'] = variant.name
  249. oo_cfg.settings['variant_version'] = version.name
  250. click.clear()
  251. return oo_cfg
  252. def collect_new_nodes():
  253. click.clear()
  254. click.echo('***New Node Configuration***')
  255. message = """
  256. Add new nodes here
  257. """
  258. click.echo(message)
  259. return collect_hosts()
  260. def get_installed_hosts(hosts, callback_facts):
  261. installed_hosts = []
  262. for host in hosts:
  263. if(host.name in callback_facts.keys()
  264. and 'common' in callback_facts[host.name].keys()
  265. and callback_facts[host.name]['common'].get('version', '')
  266. and callback_facts[host.name]['common'].get('version', '') != 'None'):
  267. installed_hosts.append(host)
  268. return installed_hosts
  269. # pylint: disable=too-many-branches
  270. # This pylint error will be corrected shortly in separate PR.
  271. def get_hosts_to_run_on(oo_cfg, callback_facts, unattended, force, verbose):
  272. # Copy the list of existing hosts so we can remove any already installed nodes.
  273. hosts_to_run_on = list(oo_cfg.hosts)
  274. # Check if master or nodes already have something installed
  275. installed_hosts = get_installed_hosts(oo_cfg.hosts, callback_facts)
  276. if len(installed_hosts) > 0:
  277. click.echo('Installed environment detected.')
  278. # This check has to happen before we start removing hosts later in this method
  279. if not force:
  280. if not unattended:
  281. click.echo('By default the installer only adds new nodes to an installed environment.')
  282. response = click.prompt('Do you want to (1) only add additional nodes or ' \
  283. '(2) perform a clean install?', type=int)
  284. # TODO: this should be reworked with error handling.
  285. # Click can certainly do this for us.
  286. # This should be refactored as soon as we add a 3rd option.
  287. if response == 1:
  288. force = False
  289. if response == 2:
  290. force = True
  291. # present a message listing already installed hosts and remove hosts if needed
  292. for host in installed_hosts:
  293. if host.master:
  294. click.echo("{} is already an OpenShift Master".format(host))
  295. # Masters stay in the list, we need to run against them when adding
  296. # new nodes.
  297. elif host.node:
  298. click.echo("{} is already an OpenShift Node".format(host))
  299. # force is only used for reinstalls so we don't want to remove
  300. # anything.
  301. if not force:
  302. hosts_to_run_on.remove(host)
  303. # Handle the cases where we know about uninstalled systems
  304. new_hosts = set(hosts_to_run_on) - set(installed_hosts)
  305. if len(new_hosts) > 0:
  306. for new_host in new_hosts:
  307. click.echo("{} is currently uninstalled".format(new_host))
  308. # Fall through
  309. click.echo('Adding additional nodes...')
  310. else:
  311. if unattended:
  312. if not force:
  313. click.echo('Installed environment detected and no additional nodes specified: ' \
  314. 'aborting. If you want a fresh install, use ' \
  315. '`atomic-openshift-installer install --force`')
  316. sys.exit(1)
  317. else:
  318. if not force:
  319. new_nodes = collect_new_nodes()
  320. hosts_to_run_on.extend(new_nodes)
  321. oo_cfg.hosts.extend(new_nodes)
  322. openshift_ansible.set_config(oo_cfg)
  323. click.echo('Gathering information from hosts...')
  324. callback_facts, error = openshift_ansible.default_facts(oo_cfg.hosts, verbose)
  325. if error:
  326. click.echo("There was a problem fetching the required information. " \
  327. "See {} for details.".format(oo_cfg.settings['ansible_log_path']))
  328. sys.exit(1)
  329. else:
  330. pass # proceeding as normal should do a clean install
  331. return hosts_to_run_on, callback_facts
  332. @click.group()
  333. @click.pass_context
  334. @click.option('--unattended', '-u', is_flag=True, default=False)
  335. @click.option('--configuration', '-c',
  336. type=click.Path(file_okay=True,
  337. dir_okay=False,
  338. writable=True,
  339. readable=True),
  340. default=None)
  341. @click.option('--ansible-playbook-directory',
  342. '-a',
  343. type=click.Path(exists=True,
  344. file_okay=False,
  345. dir_okay=True,
  346. readable=True),
  347. # callback=validate_ansible_dir,
  348. default=DEFAULT_PLAYBOOK_DIR,
  349. envvar='OO_ANSIBLE_PLAYBOOK_DIRECTORY')
  350. @click.option('--ansible-config',
  351. type=click.Path(file_okay=True,
  352. dir_okay=False,
  353. writable=True,
  354. readable=True),
  355. default=None)
  356. @click.option('--ansible-log-path',
  357. type=click.Path(file_okay=True,
  358. dir_okay=False,
  359. writable=True,
  360. readable=True),
  361. default="/tmp/ansible.log")
  362. @click.option('-v', '--verbose',
  363. is_flag=True, default=False)
  364. #pylint: disable=too-many-arguments
  365. # Main CLI entrypoint, not much we can do about too many arguments.
  366. def cli(ctx, unattended, configuration, ansible_playbook_directory, ansible_config, ansible_log_path, verbose):
  367. """
  368. The main click CLI module. Responsible for handling most common CLI options,
  369. assigning any defaults and adding to the context for the sub-commands.
  370. """
  371. ctx.obj = {}
  372. ctx.obj['unattended'] = unattended
  373. ctx.obj['configuration'] = configuration
  374. ctx.obj['ansible_config'] = ansible_config
  375. ctx.obj['ansible_log_path'] = ansible_log_path
  376. ctx.obj['verbose'] = verbose
  377. oo_cfg = OOConfig(ctx.obj['configuration'])
  378. # If no playbook dir on the CLI, check the config:
  379. if not ansible_playbook_directory:
  380. ansible_playbook_directory = oo_cfg.settings.get('ansible_playbook_directory', '')
  381. # If still no playbook dir, check for the default location:
  382. if not ansible_playbook_directory and os.path.exists(DEFAULT_PLAYBOOK_DIR):
  383. ansible_playbook_directory = DEFAULT_PLAYBOOK_DIR
  384. validate_ansible_dir(ansible_playbook_directory)
  385. oo_cfg.settings['ansible_playbook_directory'] = ansible_playbook_directory
  386. oo_cfg.ansible_playbook_directory = ansible_playbook_directory
  387. ctx.obj['ansible_playbook_directory'] = ansible_playbook_directory
  388. if ctx.obj['ansible_config']:
  389. oo_cfg.settings['ansible_config'] = ctx.obj['ansible_config']
  390. elif os.path.exists(DEFAULT_ANSIBLE_CONFIG):
  391. # If we're installed by RPM this file should exist and we can use it as our default:
  392. oo_cfg.settings['ansible_config'] = DEFAULT_ANSIBLE_CONFIG
  393. oo_cfg.settings['ansible_log_path'] = ctx.obj['ansible_log_path']
  394. ctx.obj['oo_cfg'] = oo_cfg
  395. openshift_ansible.set_config(oo_cfg)
  396. @click.command()
  397. @click.pass_context
  398. def uninstall(ctx):
  399. oo_cfg = ctx.obj['oo_cfg']
  400. verbose = ctx.obj['verbose']
  401. if len(oo_cfg.hosts) == 0:
  402. click.echo("No hosts defined in: %s" % oo_cfg['configuration'])
  403. sys.exit(1)
  404. click.echo("OpenShift will be uninstalled from the following hosts:\n")
  405. if not ctx.obj['unattended']:
  406. # Prompt interactively to confirm:
  407. for host in oo_cfg.hosts:
  408. click.echo(" * %s" % host.name)
  409. proceed = click.confirm("\nDo you wish to proceed?")
  410. if not proceed:
  411. click.echo("Uninstall cancelled.")
  412. sys.exit(0)
  413. openshift_ansible.run_uninstall_playbook(verbose)
  414. @click.command()
  415. @click.pass_context
  416. def upgrade(ctx):
  417. oo_cfg = ctx.obj['oo_cfg']
  418. verbose = ctx.obj['verbose']
  419. if len(oo_cfg.hosts) == 0:
  420. click.echo("No hosts defined in: %s" % oo_cfg['configuration'])
  421. sys.exit(1)
  422. # Update config to reflect the version we're targetting, we'll write
  423. # to disk once ansible completes successfully, not before.
  424. old_variant = oo_cfg.settings['variant']
  425. old_version = oo_cfg.settings['variant_version']
  426. if oo_cfg.settings['variant'] == 'enterprise':
  427. oo_cfg.settings['variant'] = 'openshift-enterprise'
  428. version = find_variant(oo_cfg.settings['variant'])[1]
  429. oo_cfg.settings['variant_version'] = version.name
  430. click.echo("Openshift will be upgraded from %s %s to %s %s on the following hosts:\n" % (
  431. old_variant, old_version, oo_cfg.settings['variant'],
  432. oo_cfg.settings['variant_version']))
  433. for host in oo_cfg.hosts:
  434. click.echo(" * %s" % host.name)
  435. if not ctx.obj['unattended']:
  436. # Prompt interactively to confirm:
  437. proceed = click.confirm("\nDo you wish to proceed?")
  438. if not proceed:
  439. click.echo("Upgrade cancelled.")
  440. sys.exit(0)
  441. retcode = openshift_ansible.run_upgrade_playbook(verbose)
  442. if retcode > 0:
  443. click.echo("Errors encountered during upgrade, please check %s." %
  444. oo_cfg.settings['ansible_log_path'])
  445. else:
  446. click.echo("Upgrade completed! Rebooting all hosts is recommended.")
  447. @click.command()
  448. @click.option('--force', '-f', is_flag=True, default=False)
  449. @click.pass_context
  450. def install(ctx, force):
  451. oo_cfg = ctx.obj['oo_cfg']
  452. verbose = ctx.obj['verbose']
  453. if ctx.obj['unattended']:
  454. error_if_missing_info(oo_cfg)
  455. else:
  456. oo_cfg = get_missing_info_from_user(oo_cfg)
  457. click.echo('Gathering information from hosts...')
  458. callback_facts, error = openshift_ansible.default_facts(oo_cfg.hosts,
  459. verbose)
  460. if error:
  461. click.echo("There was a problem fetching the required information. " \
  462. "Please see {} for details.".format(oo_cfg.settings['ansible_log_path']))
  463. sys.exit(1)
  464. hosts_to_run_on, callback_facts = get_hosts_to_run_on(
  465. oo_cfg, callback_facts, ctx.obj['unattended'], force, verbose)
  466. click.echo('Writing config to: %s' % oo_cfg.config_path)
  467. # We already verified this is not the case for unattended installs, so this can
  468. # only trigger for live CLI users:
  469. # TODO: if there are *new* nodes and this is a live install, we may need the user
  470. # to confirm the settings for new nodes. Look into this once we're distinguishing
  471. # between new and pre-existing nodes.
  472. if len(oo_cfg.calc_missing_facts()) > 0:
  473. confirm_hosts_facts(oo_cfg, callback_facts)
  474. oo_cfg.save_to_disk()
  475. click.echo('Ready to run installation process.')
  476. message = """
  477. If changes are needed to the values recorded by the installer please update {}.
  478. """.format(oo_cfg.config_path)
  479. if not ctx.obj['unattended']:
  480. confirm_continue(message)
  481. error = openshift_ansible.run_main_playbook(oo_cfg.hosts,
  482. hosts_to_run_on, verbose)
  483. if error:
  484. # The bootstrap script will print out the log location.
  485. message = """
  486. An error was detected. After resolving the problem please relaunch the
  487. installation process.
  488. """
  489. click.echo(message)
  490. sys.exit(1)
  491. else:
  492. message = """
  493. The installation was successful!
  494. If this is your first time installing please take a look at the Administrator
  495. Guide for advanced options related to routing, storage, authentication and much
  496. more:
  497. http://docs.openshift.com/enterprise/latest/admin_guide/overview.html
  498. """
  499. click.echo(message)
  500. click.pause()
  501. cli.add_command(install)
  502. cli.add_command(upgrade)
  503. cli.add_command(uninstall)
  504. if __name__ == '__main__':
  505. # This is expected behaviour for context passing with click library:
  506. # pylint: disable=unexpected-keyword-arg
  507. cli(obj={})