cli_installer.py 29 KB

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