cli_installer.py 44 KB

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