cli_installer.py 32 KB

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