cli_installer.py 41 KB

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