cli_installer.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. def get_hosts_to_run_on(oo_cfg, callback_facts, unattended, force):
  270. # Copy the list of existing hosts so we can remove any already installed nodes.
  271. hosts_to_run_on = list(oo_cfg.hosts)
  272. # Check if master or nodes already have something installed
  273. installed_hosts = get_installed_hosts(oo_cfg.hosts, callback_facts)
  274. if len(installed_hosts) > 0:
  275. # present a message listing already installed hosts
  276. for host in installed_hosts:
  277. if host.master:
  278. click.echo("{} is already an OpenShift Master".format(host))
  279. # Masters stay in the list, we need to run against them when adding
  280. # new nodes.
  281. elif host.node:
  282. click.echo("{} is already an OpenShift Node".format(host))
  283. hosts_to_run_on.remove(host)
  284. # for unattended either continue if they force install or exit if they didn't
  285. if unattended:
  286. if not force:
  287. click.echo('Installed environment detected and no additional nodes specified: ' \
  288. 'aborting. If you want a fresh install, use --force')
  289. sys.exit(1)
  290. # for attended ask the user what to do
  291. else:
  292. click.echo('Installed environment detected and no additional nodes specified. ')
  293. response = click.prompt('Do you want to (1) add more nodes or ' \
  294. '(2) perform a clean install?', type=int)
  295. if response == 1: # add more nodes
  296. new_nodes = collect_new_nodes()
  297. hosts_to_run_on.extend(new_nodes)
  298. oo_cfg.hosts.extend(new_nodes)
  299. openshift_ansible.set_config(oo_cfg)
  300. callback_facts, error = openshift_ansible.default_facts(oo_cfg.hosts)
  301. if error:
  302. click.echo("There was a problem fetching the required information. " \
  303. "See {} for details.".format(oo_cfg.settings['ansible_log_path']))
  304. sys.exit(1)
  305. else:
  306. pass # proceeding as normal should do a clean install
  307. return hosts_to_run_on, callback_facts
  308. @click.group()
  309. @click.pass_context
  310. @click.option('--unattended', '-u', is_flag=True, default=False)
  311. @click.option('--configuration', '-c',
  312. type=click.Path(file_okay=True,
  313. dir_okay=False,
  314. writable=True,
  315. readable=True),
  316. default=None)
  317. @click.option('--ansible-playbook-directory',
  318. '-a',
  319. type=click.Path(exists=True,
  320. file_okay=False,
  321. dir_okay=True,
  322. readable=True),
  323. # callback=validate_ansible_dir,
  324. default='/usr/share/openshift-ansible/',
  325. envvar='OO_ANSIBLE_PLAYBOOK_DIRECTORY')
  326. @click.option('--ansible-config',
  327. type=click.Path(file_okay=True,
  328. dir_okay=False,
  329. writable=True,
  330. readable=True),
  331. default=None)
  332. @click.option('--ansible-log-path',
  333. type=click.Path(file_okay=True,
  334. dir_okay=False,
  335. writable=True,
  336. readable=True),
  337. default="/tmp/ansible.log")
  338. #pylint: disable=too-many-arguments
  339. # Main CLI entrypoint, not much we can do about too many arguments.
  340. def cli(ctx, unattended, configuration, ansible_playbook_directory, ansible_config, ansible_log_path):
  341. """
  342. The main click CLI module. Responsible for handling most common CLI options,
  343. assigning any defaults and adding to the context for the sub-commands.
  344. """
  345. ctx.obj = {}
  346. ctx.obj['unattended'] = unattended
  347. ctx.obj['configuration'] = configuration
  348. ctx.obj['ansible_config'] = ansible_config
  349. ctx.obj['ansible_log_path'] = ansible_log_path
  350. oo_cfg = OOConfig(ctx.obj['configuration'])
  351. # If no playbook dir on the CLI, check the config:
  352. if not ansible_playbook_directory:
  353. ansible_playbook_directory = oo_cfg.settings.get('ansible_playbook_directory', '')
  354. # If still no playbook dir, check for the default location:
  355. if not ansible_playbook_directory and os.path.exists(DEFAULT_PLAYBOOK_DIR):
  356. ansible_playbook_directory = DEFAULT_PLAYBOOK_DIR
  357. validate_ansible_dir(ansible_playbook_directory)
  358. oo_cfg.settings['ansible_playbook_directory'] = ansible_playbook_directory
  359. oo_cfg.ansible_playbook_directory = ansible_playbook_directory
  360. ctx.obj['ansible_playbook_directory'] = ansible_playbook_directory
  361. if ctx.obj['ansible_config']:
  362. oo_cfg.settings['ansible_config'] = ctx.obj['ansible_config']
  363. elif os.path.exists(DEFAULT_ANSIBLE_CONFIG):
  364. # If we're installed by RPM this file should exist and we can use it as our default:
  365. oo_cfg.settings['ansible_config'] = DEFAULT_ANSIBLE_CONFIG
  366. oo_cfg.settings['ansible_log_path'] = ctx.obj['ansible_log_path']
  367. ctx.obj['oo_cfg'] = oo_cfg
  368. openshift_ansible.set_config(oo_cfg)
  369. @click.command()
  370. @click.pass_context
  371. def uninstall(ctx):
  372. oo_cfg = ctx.obj['oo_cfg']
  373. if len(oo_cfg.hosts) == 0:
  374. click.echo("No hosts defined in: %s" % oo_cfg['configuration'])
  375. sys.exit(1)
  376. click.echo("OpenShift will be uninstalled from the following hosts:\n")
  377. if not ctx.obj['unattended']:
  378. # Prompt interactively to confirm:
  379. for host in oo_cfg.hosts:
  380. click.echo(" * %s" % host.name)
  381. proceed = click.confirm("\nDo you wish to proceed?")
  382. if not proceed:
  383. click.echo("Uninstall cancelled.")
  384. sys.exit(0)
  385. openshift_ansible.run_uninstall_playbook()
  386. @click.command()
  387. @click.pass_context
  388. def upgrade(ctx):
  389. oo_cfg = ctx.obj['oo_cfg']
  390. if len(oo_cfg.hosts) == 0:
  391. click.echo("No hosts defined in: %s" % oo_cfg['configuration'])
  392. sys.exit(1)
  393. # Update config to reflect the version we're targetting, we'll write
  394. # to disk once ansible completes successfully, not before.
  395. old_variant = oo_cfg.settings['variant']
  396. old_version = oo_cfg.settings['variant_version']
  397. if oo_cfg.settings['variant'] == 'enterprise':
  398. oo_cfg.settings['variant'] = 'openshift-enterprise'
  399. version = find_variant(oo_cfg.settings['variant'])[1]
  400. oo_cfg.settings['variant_version'] = version.name
  401. click.echo("Openshift will be upgraded from %s %s to %s %s on the following hosts:\n" % (
  402. old_variant, old_version, oo_cfg.settings['variant'],
  403. oo_cfg.settings['variant_version']))
  404. for host in oo_cfg.hosts:
  405. click.echo(" * %s" % host.name)
  406. if not ctx.obj['unattended']:
  407. # Prompt interactively to confirm:
  408. proceed = click.confirm("\nDo you wish to proceed?")
  409. if not proceed:
  410. click.echo("Upgrade cancelled.")
  411. sys.exit(0)
  412. retcode = install_transactions.run_upgrade_playbook()
  413. if retcode > 0:
  414. click.echo("Errors encountered during upgrade, please check %s." %
  415. oo_cfg.settings['ansible_log_path'])
  416. else:
  417. click.echo("Upgrade completed! Rebooting all hosts is recommended.")
  418. @click.command()
  419. @click.option('--force', '-f', is_flag=True, default=False)
  420. @click.pass_context
  421. def install(ctx, force):
  422. oo_cfg = ctx.obj['oo_cfg']
  423. if ctx.obj['unattended']:
  424. error_if_missing_info(oo_cfg)
  425. else:
  426. oo_cfg = get_missing_info_from_user(oo_cfg)
  427. click.echo('Gathering information from hosts...')
  428. callback_facts, error = openshift_ansible.default_facts(oo_cfg.hosts)
  429. if error:
  430. click.echo("There was a problem fetching the required information. " \
  431. "Please see {} for details.".format(oo_cfg.settings['ansible_log_path']))
  432. sys.exit(1)
  433. hosts_to_run_on, callback_facts = get_hosts_to_run_on(oo_cfg, callback_facts, ctx.obj['unattended'], force)
  434. click.echo('Writing config to: %s' % oo_cfg.config_path)
  435. # We already verified this is not the case for unattended installs, so this can
  436. # only trigger for live CLI users:
  437. # TODO: if there are *new* nodes and this is a live install, we may need the user
  438. # to confirm the settings for new nodes. Look into this once we're distinguishing
  439. # between new and pre-existing nodes.
  440. if len(oo_cfg.calc_missing_facts()) > 0:
  441. confirm_hosts_facts(oo_cfg, callback_facts)
  442. oo_cfg.save_to_disk()
  443. click.echo('Ready to run installation process.')
  444. message = """
  445. If changes are needed to the values recorded by the installer please update {}.
  446. """.format(oo_cfg.config_path)
  447. if not ctx.obj['unattended']:
  448. confirm_continue(message)
  449. error = openshift_ansible.run_main_playbook(oo_cfg.hosts,
  450. hosts_to_run_on)
  451. if error:
  452. # The bootstrap script will print out the log location.
  453. message = """
  454. An error was detected. After resolving the problem please relaunch the
  455. installation process.
  456. """
  457. click.echo(message)
  458. sys.exit(1)
  459. else:
  460. message = """
  461. The installation was successful!
  462. If this is your first time installing please take a look at the Administrator
  463. Guide for advanced options related to routing, storage, authentication and much
  464. more:
  465. http://docs.openshift.com/enterprise/latest/admin_guide/overview.html
  466. """
  467. click.echo(message)
  468. click.pause()
  469. cli.add_command(install)
  470. cli.add_command(upgrade)
  471. cli.add_command(uninstall)
  472. if __name__ == '__main__':
  473. # This is expected behaviour for context passing with click library:
  474. # pylint: disable=unexpected-keyword-arg
  475. cli(obj={})