cli_installer.py 31 KB

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