cli_installer.py 41 KB

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