cli_installer.py 41 KB

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