cli_installer.py 28 KB

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