cli_installer.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. # pylint: disable=missing-docstring,no-self-use,no-value-for-parameter,too-many-lines
  2. import logging
  3. import os
  4. import sys
  5. import click
  6. from pkg_resources import parse_version
  7. from ooinstall import openshift_ansible, utils
  8. from ooinstall.oo_config import Host, OOConfig, OOConfigInvalidHostError, Role
  9. from ooinstall.variants import find_variant, get_variant_version_combos
  10. INSTALLER_LOG = logging.getLogger('installer')
  11. INSTALLER_LOG.setLevel(logging.CRITICAL)
  12. INSTALLER_FILE_HANDLER = logging.FileHandler('/tmp/installer.txt')
  13. INSTALLER_FILE_HANDLER.setFormatter(
  14. logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
  15. # Example output:
  16. # 2016-08-23 07:34:58,480 - installer - DEBUG - Going to 'load_system_facts'
  17. INSTALLER_FILE_HANDLER.setLevel(logging.DEBUG)
  18. INSTALLER_LOG.addHandler(INSTALLER_FILE_HANDLER)
  19. DEFAULT_ANSIBLE_CONFIG = '/usr/share/atomic-openshift-utils/ansible.cfg'
  20. QUIET_ANSIBLE_CONFIG = '/usr/share/atomic-openshift-utils/ansible-quiet.cfg'
  21. DEFAULT_PLAYBOOK_DIR = '/usr/share/ansible/openshift-ansible/'
  22. UPGRADE_MAPPINGS = {
  23. '3.0': {
  24. 'minor_version': '3.0',
  25. 'minor_playbook': 'v3_0_minor/upgrade.yml',
  26. 'major_version': '3.1',
  27. 'major_playbook': 'v3_0_to_v3_1/upgrade.yml',
  28. },
  29. '3.1': {
  30. 'minor_version': '3.1',
  31. 'minor_playbook': 'v3_1_minor/upgrade.yml',
  32. 'major_playbook': 'v3_1_to_v3_2/upgrade.yml',
  33. 'major_version': '3.2',
  34. },
  35. '3.2': {
  36. 'minor_version': '3.2',
  37. 'minor_playbook': 'v3_2/upgrade.yml',
  38. 'major_playbook': 'v3_3/upgrade.yml',
  39. 'major_version': '3.3',
  40. },
  41. }
  42. def validate_ansible_dir(path):
  43. if not path:
  44. raise click.BadParameter('An Ansible path must be provided')
  45. return path
  46. # if not os.path.exists(path)):
  47. # raise click.BadParameter("Path \"{}\" doesn't exist".format(path))
  48. def validate_prompt_hostname(hostname):
  49. if hostname == '' or utils.is_valid_hostname(hostname):
  50. return hostname
  51. raise click.BadParameter('Invalid hostname. Please double-check this value and re-enter it.')
  52. def get_ansible_ssh_user():
  53. click.clear()
  54. message = """
  55. This installation process involves connecting to remote hosts via ssh. Any
  56. account may be used. However, if a non-root account is used, then it must have
  57. passwordless sudo access.
  58. """
  59. click.echo(message)
  60. return click.prompt('User for ssh access', default='root')
  61. def get_routingconfig_subdomain():
  62. click.clear()
  63. message = """
  64. You might want to override the default subdomain used for exposed routes. If you don't know what this is, use the default value.
  65. """
  66. click.echo(message)
  67. return click.prompt('New default subdomain (ENTER for none)', default='')
  68. def list_hosts(hosts):
  69. hosts_idx = range(len(hosts))
  70. for idx in hosts_idx:
  71. click.echo(' {}: {}'.format(idx, hosts[idx]))
  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 address or hostname to connect to for each system in the
  83. cluster. You will then be prompted to identify what role you want 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. Optionally, you can specify multiple master systems for
  87. a high-availability (HA) deployment. If you choose an HA deployment, then you
  88. are prompted to identify a *separate* system to act as the load balancer for
  89. your cluster once you define all masters and nodes.
  90. Any masters configured as part of this installation process are also
  91. configured as nodes. This enables the master to proxy to pods
  92. from the API. By default, this node is unschedulable, but this can be changed
  93. after installation with the 'oadm manage-node' command.
  94. OpenShift nodes provide the runtime environments for containers. They host the
  95. required services to be managed by the master.
  96. http://docs.openshift.com/enterprise/latest/architecture/infrastructure_components/kubernetes_infrastructure.html#master
  97. http://docs.openshift.com/enterprise/latest/architecture/infrastructure_components/kubernetes_infrastructure.html#node
  98. """
  99. click.echo(message)
  100. hosts = []
  101. roles = set(['master', 'node', 'storage', 'etcd'])
  102. more_hosts = True
  103. num_masters = 0
  104. while more_hosts:
  105. host_props = {}
  106. host_props['roles'] = []
  107. host_props['connect_to'] = click.prompt('Enter hostname or IP address',
  108. value_proc=validate_prompt_hostname)
  109. if not masters_set:
  110. if click.confirm('Will this host be an OpenShift master?'):
  111. host_props['roles'].append('master')
  112. host_props['roles'].append('etcd')
  113. num_masters += 1
  114. if oo_cfg.settings['variant_version'] == '3.0':
  115. masters_set = True
  116. host_props['roles'].append('node')
  117. host_props['containerized'] = False
  118. if oo_cfg.settings['variant_version'] != '3.0':
  119. rpm_or_container = \
  120. 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. host_props['new_host'] = existing_env
  126. host = Host(**host_props)
  127. hosts.append(host)
  128. if print_summary:
  129. print_installation_summary(hosts, oo_cfg.settings['variant_version'])
  130. # If we have one master, this is enough for an all-in-one deployment,
  131. # thus we can start asking if you want to proceed. Otherwise we assume
  132. # you must.
  133. if masters_set or num_masters != 2:
  134. more_hosts = click.confirm('Do you want to add additional hosts?')
  135. master_lb = collect_master_lb(hosts)
  136. if master_lb:
  137. hosts.append(master_lb)
  138. roles.add('master_lb')
  139. if not existing_env:
  140. collect_storage_host(hosts)
  141. return hosts, roles
  142. # pylint: disable=too-many-branches
  143. def print_installation_summary(hosts, version=None, verbose=True):
  144. """
  145. Displays a summary of all hosts configured thus far, and what role each
  146. will play.
  147. Shows total nodes/masters, hints for performing/modifying the deployment
  148. with additional setup, warnings for invalid or sub-optimal configurations.
  149. """
  150. click.clear()
  151. click.echo('*** Installation Summary ***\n')
  152. click.echo('Hosts:')
  153. for host in hosts:
  154. print_host_summary(hosts, host)
  155. masters = [host for host in hosts if host.is_master()]
  156. nodes = [host for host in hosts if host.is_node()]
  157. dedicated_nodes = [host for host in hosts if host.is_node() and not host.is_master()]
  158. click.echo('')
  159. click.echo('Total OpenShift masters: %s' % len(masters))
  160. click.echo('Total OpenShift nodes: %s' % len(nodes))
  161. if verbose:
  162. if len(masters) == 1 and version != '3.0':
  163. ha_hint_message = """
  164. NOTE: Add a total of 3 or more masters to perform an HA installation."""
  165. click.echo(ha_hint_message)
  166. elif len(masters) == 2:
  167. min_masters_message = """
  168. WARNING: A minimum of 3 masters are required to perform an HA installation.
  169. Please add one more to proceed."""
  170. click.echo(min_masters_message)
  171. elif len(masters) >= 3:
  172. ha_message = """
  173. NOTE: Multiple masters specified, this will be an HA deployment with a separate
  174. etcd cluster. You will be prompted to provide the FQDN of a load balancer and
  175. a host for storage once finished entering hosts.
  176. """
  177. click.echo(ha_message)
  178. dedicated_nodes_message = """
  179. WARNING: Dedicated nodes are recommended for an HA deployment. If no dedicated
  180. nodes are specified, each configured master will be marked as a schedulable
  181. node."""
  182. min_ha_nodes_message = """
  183. WARNING: A minimum of 3 dedicated nodes are recommended for an HA
  184. deployment."""
  185. if len(dedicated_nodes) == 0:
  186. click.echo(dedicated_nodes_message)
  187. elif len(dedicated_nodes) < 3:
  188. click.echo(min_ha_nodes_message)
  189. click.echo('')
  190. def print_host_summary(all_hosts, host):
  191. click.echo("- %s" % host.connect_to)
  192. if host.is_master():
  193. click.echo(" - OpenShift master")
  194. if host.is_node():
  195. if host.is_dedicated_node():
  196. click.echo(" - OpenShift node (Dedicated)")
  197. elif host.is_schedulable_node(all_hosts):
  198. click.echo(" - OpenShift node")
  199. else:
  200. click.echo(" - OpenShift node (Unscheduled)")
  201. if host.is_master_lb():
  202. if host.preconfigured:
  203. click.echo(" - Load Balancer (Preconfigured)")
  204. else:
  205. click.echo(" - Load Balancer (HAProxy)")
  206. if host.is_etcd():
  207. click.echo(" - Etcd")
  208. if host.is_storage():
  209. click.echo(" - Storage")
  210. if host.new_host:
  211. click.echo(" - NEW")
  212. def collect_master_lb(hosts):
  213. """
  214. Get a valid load balancer from the user and append it to the list of
  215. hosts.
  216. Ensure user does not specify a system already used as a master/node as
  217. this is an invalid configuration.
  218. """
  219. message = """
  220. Setting up high-availability masters requires a load balancing solution.
  221. Please provide the FQDN of a host that will be configured as a proxy. This
  222. can be either an existing load balancer configured to balance all masters on
  223. port 8443 or a new host that will have HAProxy installed on it.
  224. If the host provided is not yet configured, a reference HAProxy load
  225. balancer will be installed. It's important to note that while the rest of the
  226. environment will be fault-tolerant, this reference load balancer will not be.
  227. It can be replaced post-installation with a load balancer with the same
  228. hostname.
  229. """
  230. click.echo(message)
  231. host_props = {}
  232. # Using an embedded function here so we have access to the hosts list:
  233. def validate_prompt_lb(hostname):
  234. # Run the standard hostname check first:
  235. hostname = validate_prompt_hostname(hostname)
  236. # Make sure this host wasn't already specified:
  237. for host in hosts:
  238. if host.connect_to == hostname and (host.is_master() or host.is_node()):
  239. raise click.BadParameter('Cannot re-use "%s" as a load balancer, '
  240. 'please specify a separate host' % hostname)
  241. return hostname
  242. lb_hostname = click.prompt('Enter hostname or IP address',
  243. value_proc=validate_prompt_lb,
  244. default='')
  245. if lb_hostname:
  246. host_props['connect_to'] = lb_hostname
  247. install_haproxy = \
  248. click.confirm('Should the reference HAProxy load balancer be installed on this host?')
  249. host_props['preconfigured'] = not install_haproxy
  250. host_props['roles'] = ['master_lb']
  251. return Host(**host_props)
  252. else:
  253. return None
  254. def collect_storage_host(hosts):
  255. """
  256. Get a valid host for storage from the user and append it to the list of
  257. hosts.
  258. """
  259. message = """
  260. Setting up high-availability masters requires a storage host. Please provide a
  261. host that will be configured as a Registry Storage.
  262. Note: Containerized storage hosts are not currently supported.
  263. """
  264. click.echo(message)
  265. host_props = {}
  266. first_master = next(host for host in hosts if host.is_master())
  267. hostname_or_ip = click.prompt('Enter hostname or IP address',
  268. value_proc=validate_prompt_hostname,
  269. default=first_master.connect_to)
  270. existing, existing_host = is_host_already_node_or_master(hostname_or_ip, hosts)
  271. if existing and existing_host.is_node():
  272. existing_host.roles.append('storage')
  273. else:
  274. host_props['connect_to'] = hostname_or_ip
  275. host_props['preconfigured'] = False
  276. host_props['roles'] = ['storage']
  277. storage = Host(**host_props)
  278. hosts.append(storage)
  279. def is_host_already_node_or_master(hostname, hosts):
  280. is_existing = False
  281. existing_host = None
  282. for host in hosts:
  283. if host.connect_to == hostname and (host.is_master() or host.is_node()):
  284. is_existing = True
  285. existing_host = host
  286. return is_existing, existing_host
  287. def confirm_hosts_facts(oo_cfg, callback_facts):
  288. hosts = oo_cfg.deployment.hosts
  289. click.clear()
  290. message = """
  291. The following is a list of the facts gathered from the provided hosts. The
  292. hostname for a system inside the cluster is often different from the hostname
  293. that is resolveable from command-line or web clients, therefore these settings
  294. cannot be validated automatically.
  295. For some cloud providers, the installer is able to gather metadata exposed in
  296. the instance, so reasonable defaults will be provided.
  297. Please confirm that they are correct before moving forward.
  298. """
  299. notes = """
  300. Format:
  301. connect_to,IP,public IP,hostname,public hostname
  302. Notes:
  303. * The installation host is the hostname from the installer's perspective.
  304. * The IP of the host should be the internal IP of the instance.
  305. * The public IP should be the externally accessible IP associated with the instance
  306. * The hostname should resolve to the internal IP from the instances
  307. themselves.
  308. * The public hostname should resolve to the external IP from hosts outside of
  309. the cloud.
  310. """
  311. # For testing purposes we need to click.echo only once, so build up
  312. # the message:
  313. output = message
  314. default_facts_lines = []
  315. default_facts = {}
  316. for host in hosts:
  317. if host.preconfigured:
  318. continue
  319. try:
  320. default_facts[host.connect_to] = {}
  321. host.ip = callback_facts[host.connect_to]["common"]["ip"]
  322. host.public_ip = callback_facts[host.connect_to]["common"]["public_ip"]
  323. host.hostname = callback_facts[host.connect_to]["common"]["hostname"]
  324. host.public_hostname = callback_facts[host.connect_to]["common"]["public_hostname"]
  325. except KeyError:
  326. click.echo("Problem fetching facts from {}".format(host.connect_to))
  327. continue
  328. default_facts_lines.append(",".join([host.connect_to,
  329. host.ip,
  330. host.public_ip,
  331. host.hostname,
  332. host.public_hostname]))
  333. output = "%s\n%s" % (output, ",".join([host.connect_to,
  334. host.ip,
  335. host.public_ip,
  336. host.hostname,
  337. host.public_hostname]))
  338. output = "%s\n%s" % (output, notes)
  339. click.echo(output)
  340. facts_confirmed = click.confirm("Do the above facts look correct?")
  341. if not facts_confirmed:
  342. message = """
  343. Edit %s with the desired values and run `atomic-openshift-installer --unattended install` to restart the install.
  344. """ % oo_cfg.config_path
  345. click.echo(message)
  346. # Make sure we actually write out the config file.
  347. oo_cfg.save_to_disk()
  348. sys.exit(0)
  349. return default_facts
  350. def check_hosts_config(oo_cfg, unattended):
  351. click.clear()
  352. masters = [host for host in oo_cfg.deployment.hosts if host.is_master()]
  353. if len(masters) == 2:
  354. click.echo("A minimum of 3 masters are required for HA deployments.")
  355. sys.exit(1)
  356. if len(masters) > 1:
  357. master_lb = [host for host in oo_cfg.deployment.hosts if host.is_master_lb()]
  358. if len(master_lb) > 1:
  359. click.echo('ERROR: More than one master load balancer specified. Only one is allowed.')
  360. sys.exit(1)
  361. elif len(master_lb) == 1:
  362. if master_lb[0].is_master() or master_lb[0].is_node():
  363. click.echo('ERROR: The master load balancer is configured as a master or node. '
  364. 'Please correct this.')
  365. sys.exit(1)
  366. else:
  367. message = """
  368. ERROR: No master load balancer specified in config. You must provide the FQDN
  369. of a load balancer to balance the API (port 8443) on all master hosts.
  370. https://docs.openshift.org/latest/install_config/install/advanced_install.html#multiple-masters
  371. """
  372. click.echo(message)
  373. sys.exit(1)
  374. dedicated_nodes = [host for host in oo_cfg.deployment.hosts
  375. if host.is_node() and not host.is_master()]
  376. if len(dedicated_nodes) == 0:
  377. message = """
  378. WARNING: No dedicated nodes specified. By default, colocated masters have
  379. their nodes set to unschedulable. If you proceed all nodes will be labelled
  380. as schedulable.
  381. """
  382. if unattended:
  383. click.echo(message)
  384. else:
  385. confirm_continue(message)
  386. return
  387. def get_variant_and_version(multi_master=False):
  388. message = "\nWhich variant would you like to install?\n\n"
  389. i = 1
  390. combos = get_variant_version_combos()
  391. for (variant, version) in combos:
  392. message = "%s\n(%s) %s" % (message, i, variant.description)
  393. i = i + 1
  394. message = "%s\n" % message
  395. click.echo(message)
  396. if multi_master:
  397. click.echo('NOTE: 3.0 installations are not')
  398. response = click.prompt("Choose a variant from above: ", default=1)
  399. product, version = combos[response - 1]
  400. return product, version
  401. def confirm_continue(message):
  402. if message:
  403. click.echo(message)
  404. click.confirm("Are you ready to continue?", default=False, abort=True)
  405. return
  406. def error_if_missing_info(oo_cfg):
  407. missing_info = False
  408. if not oo_cfg.deployment.hosts:
  409. missing_info = True
  410. click.echo('For unattended installs, hosts must be specified on the '
  411. 'command line or in the config file: %s' % oo_cfg.config_path)
  412. sys.exit(1)
  413. if 'ansible_ssh_user' not in oo_cfg.deployment.variables:
  414. click.echo("Must specify ansible_ssh_user in configuration file.")
  415. sys.exit(1)
  416. # Lookup a variant based on the key we were given:
  417. if not oo_cfg.settings['variant']:
  418. click.echo("No variant specified in configuration file.")
  419. sys.exit(1)
  420. ver = None
  421. if 'variant_version' in oo_cfg.settings:
  422. ver = oo_cfg.settings['variant_version']
  423. variant, version = find_variant(oo_cfg.settings['variant'], version=ver)
  424. if variant is None or version is None:
  425. err_variant_name = oo_cfg.settings['variant']
  426. if ver:
  427. err_variant_name = "%s %s" % (err_variant_name, ver)
  428. click.echo("%s is not an installable variant." % err_variant_name)
  429. sys.exit(1)
  430. oo_cfg.settings['variant_version'] = version.name
  431. # check that all listed host roles are included
  432. listed_roles = oo_cfg.get_host_roles_set()
  433. configured_roles = set([role for role in oo_cfg.deployment.roles])
  434. if listed_roles != configured_roles:
  435. missing_info = True
  436. click.echo('Any roles assigned to hosts must be defined.')
  437. if missing_info:
  438. sys.exit(1)
  439. def get_proxy_hosts_excludes():
  440. message = """
  441. If a proxy is needed to reach HTTP and HTTPS traffic, please enter the
  442. name below. This proxy will be configured by default for all processes
  443. that need to reach systems outside the cluster. An example proxy value
  444. would be:
  445. http://proxy.example.com:8080/
  446. More advanced configuration is possible if using Ansible directly:
  447. https://docs.openshift.com/enterprise/latest/install_config/http_proxies.html
  448. """
  449. click.echo(message)
  450. message = "Specify your http proxy ? (ENTER for none)"
  451. http_proxy_hostname = click.prompt(message, default='')
  452. # TODO: Fix this prompt message and behavior. 'ENTER' will default
  453. # to the http_proxy_hostname if one was provided
  454. message = "Specify your https proxy ? (ENTER for none)"
  455. https_proxy_hostname = click.prompt(message, default=http_proxy_hostname)
  456. if http_proxy_hostname or https_proxy_hostname:
  457. message = """
  458. All hosts in your OpenShift inventory will automatically be added to the NO_PROXY value.
  459. Please provide any additional hosts to be added to NO_PROXY. (ENTER for none)
  460. """
  461. proxy_excludes = click.prompt(message, default='')
  462. else:
  463. proxy_excludes = ''
  464. return http_proxy_hostname, https_proxy_hostname, proxy_excludes
  465. def get_missing_info_from_user(oo_cfg):
  466. """ Prompts the user for any information missing from the given configuration. """
  467. click.clear()
  468. message = """
  469. Welcome to the OpenShift Enterprise 3 installation.
  470. Please confirm that following prerequisites have been met:
  471. * All systems where OpenShift will be installed are running Red Hat Enterprise
  472. Linux 7.
  473. * All systems are properly subscribed to the required OpenShift Enterprise 3
  474. repositories.
  475. * All systems have run docker-storage-setup (part of the Red Hat docker RPM).
  476. * All systems have working DNS that resolves not only from the perspective of
  477. the installer, but also from within the cluster.
  478. When the process completes you will have a default configuration for masters
  479. and nodes. For ongoing environment maintenance it's recommended that the
  480. official Ansible playbooks be used.
  481. For more information on installation prerequisites please see:
  482. https://docs.openshift.com/enterprise/latest/admin_guide/install/prerequisites.html
  483. """
  484. confirm_continue(message)
  485. click.clear()
  486. if not oo_cfg.deployment.variables.get('ansible_ssh_user', False):
  487. oo_cfg.deployment.variables['ansible_ssh_user'] = get_ansible_ssh_user()
  488. click.clear()
  489. if not oo_cfg.settings.get('variant', ''):
  490. variant, version = get_variant_and_version()
  491. oo_cfg.settings['variant'] = variant.name
  492. oo_cfg.settings['variant_version'] = version.name
  493. oo_cfg.settings['variant_subtype'] = version.subtype
  494. click.clear()
  495. if not oo_cfg.deployment.hosts:
  496. oo_cfg.deployment.hosts, roles = collect_hosts(oo_cfg)
  497. set_infra_nodes(oo_cfg.deployment.hosts)
  498. for role in roles:
  499. oo_cfg.deployment.roles[role] = Role(name=role, variables={})
  500. click.clear()
  501. if 'master_routingconfig_subdomain' not in oo_cfg.deployment.variables:
  502. oo_cfg.deployment.variables['master_routingconfig_subdomain'] = \
  503. get_routingconfig_subdomain()
  504. click.clear()
  505. # Are any proxy vars already presisted?
  506. proxy_vars = ['proxy_exclude_hosts', 'proxy_https', 'proxy_http']
  507. # Empty list if NO proxy vars were presisted
  508. saved_proxy_vars = [pv for pv in proxy_vars
  509. if oo_cfg.deployment.variables.get(pv, 'UNSET') is not 'UNSET']
  510. INSTALLER_LOG.debug("Evaluated proxy settings, found %s presisted values",
  511. len(saved_proxy_vars))
  512. current_version = parse_version(
  513. oo_cfg.settings.get('variant_version', '0.0'))
  514. min_version = parse_version('3.2')
  515. # No proxy vars were saved and we are running a version which
  516. # recognizes proxy parameters. We must prompt the user for values
  517. # if this conditional is true.
  518. if not saved_proxy_vars and current_version >= min_version:
  519. INSTALLER_LOG.debug("Prompting user to enter proxy values")
  520. http_proxy, https_proxy, proxy_excludes = get_proxy_hosts_excludes()
  521. oo_cfg.deployment.variables['proxy_http'] = http_proxy
  522. oo_cfg.deployment.variables['proxy_https'] = https_proxy
  523. oo_cfg.deployment.variables['proxy_exclude_hosts'] = proxy_excludes
  524. click.clear()
  525. return oo_cfg
  526. def get_role_variable(oo_cfg, role_name, variable_name):
  527. try:
  528. target_role = next(role for role in oo_cfg.deployment.roles if role.name is role_name)
  529. target_variable = target_role.variables[variable_name]
  530. return target_variable
  531. except (StopIteration, KeyError):
  532. return None
  533. def set_role_variable(oo_cfg, role_name, variable_name, variable_value):
  534. target_role = next(role for role in oo_cfg.deployment.roles if role.name is role_name)
  535. target_role[variable_name] = variable_value
  536. def collect_new_nodes(oo_cfg):
  537. click.clear()
  538. click.echo('*** New Node Configuration ***')
  539. message = """
  540. Add new nodes here
  541. """
  542. click.echo(message)
  543. new_nodes, _ = collect_hosts(oo_cfg, existing_env=True, masters_set=True, print_summary=False)
  544. return new_nodes
  545. def get_installed_hosts(hosts, callback_facts):
  546. installed_hosts = []
  547. uninstalled_hosts = []
  548. for host in [h for h in hosts if h.is_master() or h.is_node()]:
  549. if host.connect_to in callback_facts.keys():
  550. if is_installed_host(host, callback_facts):
  551. INSTALLER_LOG.debug("%s is already installed", str(host))
  552. installed_hosts.append(host)
  553. else:
  554. INSTALLER_LOG.debug("%s is not installed", str(host))
  555. uninstalled_hosts.append(host)
  556. return installed_hosts, uninstalled_hosts
  557. def is_installed_host(host, callback_facts):
  558. version_found = 'common' in callback_facts[host.connect_to].keys() and \
  559. callback_facts[host.connect_to]['common'].get('version', '') and \
  560. callback_facts[host.connect_to]['common'].get('version', '') != 'None'
  561. return version_found
  562. def get_hosts_to_run_on(oo_cfg, callback_facts, unattended, force):
  563. """
  564. We get here once there are hosts in oo_cfg and we need to find out what
  565. state they are in. There are several different cases that might occur:
  566. 1. All hosts in oo_cfg are uninstalled. In this case, we should proceed
  567. with a normal installation.
  568. 2. All hosts in oo_cfg are installed. In this case, ask the user if they
  569. want to force reinstall or exit. We can also hint in this case about
  570. the scaleup workflow.
  571. 3. Some hosts are installed and some are uninstalled. In this case, prompt
  572. the user if they want to force (re)install all hosts specified or direct
  573. them to the scaleup workflow and exit.
  574. """
  575. hosts_to_run_on = []
  576. # Check if master or nodes already have something installed
  577. installed_hosts, uninstalled_hosts = get_installed_hosts(oo_cfg.deployment.hosts,
  578. callback_facts)
  579. nodes = [host for host in oo_cfg.deployment.hosts if host.is_node()]
  580. not_balancers = [host for host in oo_cfg.deployment.hosts if not host.is_master_lb()]
  581. in_hosts = [str(h) for h in installed_hosts]
  582. un_hosts = [str(h) for h in uninstalled_hosts]
  583. all_hosts = [str(h) for h in oo_cfg.deployment.hosts]
  584. no_bals = [str(h) for h in not_balancers]
  585. INSTALLER_LOG.debug("installed hosts: %s", ", ".join(in_hosts))
  586. INSTALLER_LOG.debug("uninstalled hosts: %s", ", ".join(un_hosts))
  587. INSTALLER_LOG.debug("deployment hosts: %s", ", ".join(all_hosts))
  588. INSTALLER_LOG.debug("not balancers: %s", ", ".join(no_bals))
  589. # Case (1): All uninstalled hosts
  590. if len(uninstalled_hosts) == len(nodes):
  591. click.echo('All hosts in config are uninstalled. Proceeding with installation...')
  592. hosts_to_run_on = list(oo_cfg.deployment.hosts)
  593. else:
  594. # Case (2): All installed hosts
  595. if len(installed_hosts) == len(not_balancers):
  596. message = """
  597. All specified hosts in specified environment are installed.
  598. """
  599. # Case (3): Some installed, some uninstalled
  600. else:
  601. message = """
  602. A mix of installed and uninstalled hosts have been detected in your environment.
  603. Please make sure your environment was installed successfully before adding new nodes.
  604. """
  605. # Still inside the case 2/3 else condition
  606. mixed_msg = """
  607. \tInstalled hosts:
  608. \t\t{inst_hosts}
  609. \tUninstalled hosts:
  610. \t\t{uninst_hosts}""".format(inst_hosts=", ".join(in_hosts), uninst_hosts=", ".join(un_hosts))
  611. click.echo(mixed_msg)
  612. # Out of the case 2/3 if/else
  613. click.echo(message)
  614. if not unattended:
  615. response = click.confirm('Do you want to (re)install the environment?\n\n'
  616. 'Note: This will potentially erase any custom changes.')
  617. if response:
  618. hosts_to_run_on = list(oo_cfg.deployment.hosts)
  619. force = True
  620. elif unattended and force:
  621. hosts_to_run_on = list(oo_cfg.deployment.hosts)
  622. if not force:
  623. message = """
  624. If you want to force reinstall of your environment, run:
  625. `atomic-openshift-installer install --force`
  626. If you want to add new nodes to this environment, run:
  627. `atomic-openshift-installer scaleup`
  628. """
  629. click.echo(message)
  630. sys.exit(1)
  631. return hosts_to_run_on, callback_facts
  632. def set_infra_nodes(hosts):
  633. if all(host.is_master() for host in hosts):
  634. infra_list = hosts
  635. else:
  636. nodes_list = [host for host in hosts if host.is_schedulable_node(hosts)]
  637. infra_list = nodes_list[:2]
  638. for host in infra_list:
  639. host.node_labels = "{'region': 'infra'}"
  640. def run_config_playbook(oo_cfg, hosts_to_run_on, unattended, verbose, gen_inventory):
  641. # Write Ansible inventory file to disk:
  642. inventory_file = openshift_ansible.generate_inventory(hosts_to_run_on)
  643. click.echo()
  644. click.echo('Wrote atomic-openshift-installer config: %s' % oo_cfg.config_path)
  645. click.echo("Wrote Ansible inventory: %s" % inventory_file)
  646. click.echo()
  647. if gen_inventory:
  648. sys.exit(0)
  649. click.echo('Ready to run installation process.')
  650. message = """
  651. If changes are needed please edit the config file above and re-run.
  652. """
  653. if not unattended:
  654. confirm_continue(message)
  655. error = openshift_ansible.run_main_playbook(inventory_file, oo_cfg.deployment.hosts,
  656. hosts_to_run_on, verbose)
  657. if error:
  658. # The bootstrap script will print out the log location.
  659. message = """
  660. An error was detected. After resolving the problem please relaunch the
  661. installation process.
  662. """
  663. click.echo(message)
  664. sys.exit(1)
  665. else:
  666. message = """
  667. The installation was successful!
  668. If this is your first time installing please take a look at the Administrator
  669. Guide for advanced options related to routing, storage, authentication, and
  670. more:
  671. http://docs.openshift.com/enterprise/latest/admin_guide/overview.html
  672. """
  673. click.echo(message)
  674. @click.group()
  675. @click.pass_context
  676. @click.option('--unattended', '-u', is_flag=True, default=False)
  677. @click.option('--configuration', '-c',
  678. type=click.Path(file_okay=True,
  679. dir_okay=False,
  680. writable=True,
  681. readable=True),
  682. default=None)
  683. @click.option('--ansible-playbook-directory',
  684. '-a',
  685. type=click.Path(exists=True,
  686. file_okay=False,
  687. dir_okay=True,
  688. readable=True),
  689. # callback=validate_ansible_dir,
  690. default=DEFAULT_PLAYBOOK_DIR,
  691. envvar='OO_ANSIBLE_PLAYBOOK_DIRECTORY')
  692. @click.option('--ansible-log-path',
  693. type=click.Path(file_okay=True,
  694. dir_okay=False,
  695. writable=True,
  696. readable=True),
  697. default="/tmp/ansible.log")
  698. @click.option('-v', '--verbose',
  699. is_flag=True, default=False)
  700. @click.option('-d', '--debug',
  701. help="Enable installer debugging (/tmp/installer.log)",
  702. is_flag=True, default=False)
  703. @click.help_option('--help', '-h')
  704. # pylint: disable=too-many-arguments
  705. # pylint: disable=line-too-long
  706. # Main CLI entrypoint, not much we can do about too many arguments.
  707. def cli(ctx, unattended, configuration, ansible_playbook_directory, ansible_log_path, verbose, debug):
  708. """
  709. atomic-openshift-installer makes the process for installing OSE or AEP
  710. easier by interactively gathering the data needed to run on each host.
  711. It can also be run in unattended mode if provided with a configuration file.
  712. Further reading: https://docs.openshift.com/enterprise/latest/install_config/install/quick_install.html
  713. """
  714. if debug:
  715. # DEFAULT log level threshold is set to CRITICAL (the
  716. # highest), anything below that (we only use debug/warning
  717. # presently) is not logged. If '-d' is given though, we'll
  718. # lower the threshold to debug (almost everything gets through)
  719. INSTALLER_LOG.setLevel(logging.DEBUG)
  720. INSTALLER_LOG.debug("Quick Installer debugging initialized")
  721. ctx.obj = {}
  722. ctx.obj['unattended'] = unattended
  723. ctx.obj['configuration'] = configuration
  724. ctx.obj['ansible_log_path'] = ansible_log_path
  725. ctx.obj['verbose'] = verbose
  726. try:
  727. oo_cfg = OOConfig(ctx.obj['configuration'])
  728. except OOConfigInvalidHostError as err:
  729. click.echo(err)
  730. sys.exit(1)
  731. # If no playbook dir on the CLI, check the config:
  732. if not ansible_playbook_directory:
  733. ansible_playbook_directory = oo_cfg.settings.get('ansible_playbook_directory', '')
  734. # If still no playbook dir, check for the default location:
  735. if not ansible_playbook_directory and os.path.exists(DEFAULT_PLAYBOOK_DIR):
  736. ansible_playbook_directory = DEFAULT_PLAYBOOK_DIR
  737. validate_ansible_dir(ansible_playbook_directory)
  738. oo_cfg.settings['ansible_playbook_directory'] = ansible_playbook_directory
  739. oo_cfg.ansible_playbook_directory = ansible_playbook_directory
  740. ctx.obj['ansible_playbook_directory'] = ansible_playbook_directory
  741. if os.path.exists(DEFAULT_ANSIBLE_CONFIG):
  742. # If we're installed by RPM this file should exist and we can use it as our default:
  743. oo_cfg.settings['ansible_config'] = DEFAULT_ANSIBLE_CONFIG
  744. if not verbose and os.path.exists(QUIET_ANSIBLE_CONFIG):
  745. oo_cfg.settings['ansible_quiet_config'] = QUIET_ANSIBLE_CONFIG
  746. oo_cfg.settings['ansible_log_path'] = ctx.obj['ansible_log_path']
  747. ctx.obj['oo_cfg'] = oo_cfg
  748. openshift_ansible.set_config(oo_cfg)
  749. @click.command()
  750. @click.pass_context
  751. def uninstall(ctx):
  752. oo_cfg = ctx.obj['oo_cfg']
  753. verbose = ctx.obj['verbose']
  754. if hasattr(oo_cfg, 'deployment'):
  755. hosts = oo_cfg.deployment.hosts
  756. elif hasattr(oo_cfg, 'hosts'):
  757. hosts = oo_cfg.hosts
  758. else:
  759. click.echo("No hosts defined in: %s" % oo_cfg.config_path)
  760. sys.exit(1)
  761. click.echo("OpenShift will be uninstalled from the following hosts:\n")
  762. if not ctx.obj['unattended']:
  763. # Prompt interactively to confirm:
  764. for host in hosts:
  765. click.echo(" * %s" % host.connect_to)
  766. proceed = click.confirm("\nDo you want to proceed?")
  767. if not proceed:
  768. click.echo("Uninstall cancelled.")
  769. sys.exit(0)
  770. openshift_ansible.run_uninstall_playbook(hosts, verbose)
  771. @click.command()
  772. @click.option('--latest-minor', '-l', is_flag=True, default=False)
  773. @click.option('--next-major', '-n', is_flag=True, default=False)
  774. @click.pass_context
  775. # pylint: disable=too-many-statements,too-many-branches
  776. def upgrade(ctx, latest_minor, next_major):
  777. oo_cfg = ctx.obj['oo_cfg']
  778. if len(oo_cfg.deployment.hosts) == 0:
  779. click.echo("No hosts defined in: %s" % oo_cfg.config_path)
  780. sys.exit(1)
  781. variant = oo_cfg.settings['variant']
  782. if find_variant(variant)[0] is None:
  783. click.echo("%s is not a supported variant for upgrade." % variant)
  784. sys.exit(0)
  785. old_version = oo_cfg.settings['variant_version']
  786. try:
  787. mapping = UPGRADE_MAPPINGS[old_version]
  788. except KeyError:
  789. click.echo('No upgrades available for %s %s' % (variant, old_version))
  790. sys.exit(0)
  791. message = """
  792. This tool will help you upgrade your existing OpenShift installation.
  793. Currently running: %s %s
  794. """
  795. click.echo(message % (variant, old_version))
  796. # Map the dynamic upgrade options to the playbook to run for each.
  797. # Index offset by 1.
  798. # List contains tuples of booleans for (latest_minor, next_major)
  799. selections = []
  800. if not (latest_minor or next_major):
  801. i = 0
  802. if 'minor_playbook' in mapping:
  803. click.echo("(%s) Update to latest %s" % (i + 1, old_version))
  804. selections.append((True, False))
  805. i += 1
  806. if 'major_playbook' in mapping:
  807. click.echo("(%s) Upgrade to next release: %s" % (i + 1, mapping['major_version']))
  808. selections.append((False, True))
  809. i += 1
  810. response = click.prompt("\nChoose an option from above",
  811. type=click.Choice(list(map(str, range(1, len(selections) + 1)))))
  812. latest_minor, next_major = selections[int(response) - 1]
  813. if next_major:
  814. if 'major_playbook' not in mapping:
  815. click.echo("No major upgrade supported for %s %s with this version "
  816. "of atomic-openshift-utils." % (variant, old_version))
  817. sys.exit(0)
  818. playbook = mapping['major_playbook']
  819. new_version = mapping['major_version']
  820. # Update config to reflect the version we're targeting, we'll write
  821. # to disk once Ansible completes successfully, not before.
  822. oo_cfg.settings['variant_version'] = new_version
  823. if oo_cfg.settings['variant'] == 'enterprise':
  824. oo_cfg.settings['variant'] = 'openshift-enterprise'
  825. if latest_minor:
  826. if 'minor_playbook' not in mapping:
  827. click.echo("No minor upgrade supported for %s %s with this version "
  828. "of atomic-openshift-utils." % (variant, old_version))
  829. sys.exit(0)
  830. playbook = mapping['minor_playbook']
  831. new_version = old_version
  832. click.echo("OpenShift will be upgraded from %s %s to latest %s %s on the following hosts:\n" % (
  833. variant, old_version, oo_cfg.settings['variant'], new_version))
  834. for host in oo_cfg.deployment.hosts:
  835. click.echo(" * %s" % host.connect_to)
  836. if not ctx.obj['unattended']:
  837. # Prompt interactively to confirm:
  838. if not click.confirm("\nDo you want to proceed?"):
  839. click.echo("Upgrade cancelled.")
  840. sys.exit(0)
  841. retcode = openshift_ansible.run_upgrade_playbook(oo_cfg.deployment.hosts,
  842. playbook,
  843. ctx.obj['verbose'])
  844. if retcode > 0:
  845. click.echo("Errors encountered during upgrade, please check %s." %
  846. oo_cfg.settings['ansible_log_path'])
  847. else:
  848. oo_cfg.save_to_disk()
  849. click.echo("Upgrade completed! Rebooting all hosts is recommended.")
  850. @click.command()
  851. @click.option('--force', '-f', is_flag=True, default=False)
  852. @click.option('--gen-inventory', is_flag=True, default=False,
  853. help="Generate an Ansible inventory file and exit.")
  854. @click.pass_context
  855. def install(ctx, force, gen_inventory):
  856. oo_cfg = ctx.obj['oo_cfg']
  857. verbose = ctx.obj['verbose']
  858. unattended = ctx.obj['unattended']
  859. if unattended:
  860. error_if_missing_info(oo_cfg)
  861. else:
  862. oo_cfg = get_missing_info_from_user(oo_cfg)
  863. check_hosts_config(oo_cfg, unattended)
  864. print_installation_summary(oo_cfg.deployment.hosts,
  865. oo_cfg.settings.get('variant_version', None))
  866. click.echo('Gathering information from hosts...')
  867. callback_facts, error = openshift_ansible.default_facts(oo_cfg.deployment.hosts,
  868. verbose)
  869. if error or callback_facts is None:
  870. click.echo("There was a problem fetching the required information. "
  871. "Please see {} for details.".format(oo_cfg.settings['ansible_log_path']))
  872. sys.exit(1)
  873. hosts_to_run_on, callback_facts = get_hosts_to_run_on(oo_cfg,
  874. callback_facts,
  875. unattended,
  876. force)
  877. # We already verified this is not the case for unattended installs, so this can
  878. # only trigger for live CLI users:
  879. if not ctx.obj['unattended'] and len(oo_cfg.calc_missing_facts()) > 0:
  880. confirm_hosts_facts(oo_cfg, callback_facts)
  881. # Write quick installer config file to disk:
  882. oo_cfg.save_to_disk()
  883. run_config_playbook(oo_cfg, hosts_to_run_on, unattended, verbose, gen_inventory)
  884. @click.command()
  885. @click.option('--gen-inventory', is_flag=True, default=False,
  886. help="Generate an Ansible inventory file and exit.")
  887. @click.pass_context
  888. def scaleup(ctx, gen_inventory):
  889. oo_cfg = ctx.obj['oo_cfg']
  890. verbose = ctx.obj['verbose']
  891. unattended = ctx.obj['unattended']
  892. installed_hosts = list(oo_cfg.deployment.hosts)
  893. if len(installed_hosts) == 0:
  894. click.echo('No hosts specified.')
  895. sys.exit(1)
  896. click.echo('Welcome to the OpenShift Enterprise 3 Scaleup utility.')
  897. print_installation_summary(installed_hosts,
  898. oo_cfg.settings['variant_version'],
  899. verbose=False,)
  900. message = """
  901. ---
  902. We have detected this previously installed OpenShift environment.
  903. This tool will guide you through the process of adding additional
  904. nodes to your cluster.
  905. """
  906. confirm_continue(message)
  907. error_if_missing_info(oo_cfg)
  908. check_hosts_config(oo_cfg, True)
  909. installed_masters = [host for host in installed_hosts if host.is_master()]
  910. new_nodes = collect_new_nodes(oo_cfg)
  911. oo_cfg.deployment.hosts.extend(new_nodes)
  912. hosts_to_run_on = installed_masters + new_nodes
  913. openshift_ansible.set_config(oo_cfg)
  914. click.echo('Gathering information from hosts...')
  915. callback_facts, error = openshift_ansible.default_facts(oo_cfg.deployment.hosts, verbose)
  916. if error or callback_facts is None:
  917. click.echo("There was a problem fetching the required information. See "
  918. "{} for details.".format(oo_cfg.settings['ansible_log_path']))
  919. sys.exit(1)
  920. print_installation_summary(oo_cfg.deployment.hosts,
  921. oo_cfg.settings.get('variant_version', None))
  922. click.echo('Gathering information from hosts...')
  923. callback_facts, error = openshift_ansible.default_facts(oo_cfg.deployment.hosts,
  924. verbose)
  925. if error or callback_facts is None:
  926. click.echo("There was a problem fetching the required information. "
  927. "Please see {} for details.".format(oo_cfg.settings['ansible_log_path']))
  928. sys.exit(1)
  929. # We already verified this is not the case for unattended installs, so this can
  930. # only trigger for live CLI users:
  931. if not ctx.obj['unattended'] and len(oo_cfg.calc_missing_facts()) > 0:
  932. confirm_hosts_facts(oo_cfg, callback_facts)
  933. # Write quick installer config file to disk:
  934. oo_cfg.save_to_disk()
  935. run_config_playbook(oo_cfg, hosts_to_run_on, unattended, verbose, gen_inventory)
  936. cli.add_command(install)
  937. cli.add_command(scaleup)
  938. cli.add_command(upgrade)
  939. cli.add_command(uninstall)
  940. if __name__ == '__main__':
  941. # This is expected behaviour for context passing with click library:
  942. # pylint: disable=unexpected-keyword-arg
  943. cli(obj={})