cli_installer.py 40 KB

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