openshift_facts.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. #!/usr/bin/python
  2. # pylint: disable=too-many-lines
  3. # -*- coding: utf-8 -*-
  4. # Reason: Disable pylint too-many-lines because we don't want to split up this file.
  5. # Status: Permanently disabled to keep this module as self-contained as possible.
  6. """Ansible module for retrieving and setting openshift related facts"""
  7. # pylint: disable=no-name-in-module, import-error, wrong-import-order
  8. import copy
  9. import errno
  10. import json
  11. import re
  12. import os
  13. import yaml
  14. import struct
  15. import socket
  16. import ipaddress
  17. from distutils.util import strtobool
  18. from distutils.version import LooseVersion
  19. from ansible.module_utils.six import u
  20. from ansible.module_utils.six import string_types
  21. from ansible.module_utils.six.moves import configparser
  22. # ignore pylint errors related to the module_utils import
  23. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  24. # import module snippets
  25. from ansible.module_utils.basic import * # noqa: F403
  26. from ansible.module_utils.facts import * # noqa: F403
  27. from ansible.module_utils.urls import * # noqa: F403
  28. from ansible.module_utils.six import iteritems, itervalues
  29. from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse
  30. from ansible.module_utils._text import to_native
  31. HAVE_DBUS = False
  32. try:
  33. from dbus import SystemBus, Interface
  34. from dbus.exceptions import DBusException
  35. HAVE_DBUS = True
  36. except ImportError:
  37. pass
  38. DOCUMENTATION = '''
  39. ---
  40. module: openshift_facts
  41. short_description: Cluster Facts
  42. author: Jason DeTiberus
  43. requirements: [ ]
  44. '''
  45. EXAMPLES = '''
  46. '''
  47. # TODO: We should add a generic migration function that takes source and destination
  48. # paths and does the right thing rather than one function for common, one for node, etc.
  49. def migrate_common_facts(facts):
  50. """ Migrate facts from various roles into common """
  51. params = {
  52. 'node': ('portal_net'),
  53. 'master': ('portal_net')
  54. }
  55. if 'common' not in facts:
  56. facts['common'] = {}
  57. # pylint: disable=consider-iterating-dictionary
  58. for role in params.keys():
  59. if role in facts:
  60. for param in params[role]:
  61. if param in facts[role]:
  62. facts['common'][param] = facts[role].pop(param)
  63. return facts
  64. def migrate_admission_plugin_facts(facts):
  65. """ Apply migrations for admission plugin facts """
  66. if 'master' in facts:
  67. if 'kube_admission_plugin_config' in facts['master']:
  68. if 'admission_plugin_config' not in facts['master']:
  69. facts['master']['admission_plugin_config'] = dict()
  70. # Merge existing kube_admission_plugin_config with admission_plugin_config.
  71. facts['master']['admission_plugin_config'] = merge_facts(facts['master']['admission_plugin_config'],
  72. facts['master']['kube_admission_plugin_config'],
  73. additive_facts_to_overwrite=[])
  74. # Remove kube_admission_plugin_config fact
  75. facts['master'].pop('kube_admission_plugin_config', None)
  76. return facts
  77. def migrate_local_facts(facts):
  78. """ Apply migrations of local facts """
  79. migrated_facts = copy.deepcopy(facts)
  80. migrated_facts = migrate_common_facts(migrated_facts)
  81. migrated_facts = migrate_admission_plugin_facts(migrated_facts)
  82. return migrated_facts
  83. def first_ip(network):
  84. """ Return the first IPv4 address in network
  85. Args:
  86. network (str): network in CIDR format
  87. Returns:
  88. str: first IPv4 address
  89. """
  90. atoi = lambda addr: struct.unpack("!I", socket.inet_aton(addr))[0] # noqa: E731
  91. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr)) # noqa: E731
  92. (address, netmask) = network.split('/')
  93. netmask_i = (0xffffffff << (32 - atoi(netmask))) & 0xffffffff
  94. return itoa((atoi(address) & netmask_i) + 1)
  95. def hostname_valid(hostname):
  96. """ Test if specified hostname should be considered valid
  97. Args:
  98. hostname (str): hostname to test
  99. Returns:
  100. bool: True if valid, otherwise False
  101. """
  102. if (not hostname or
  103. hostname.startswith('localhost') or
  104. hostname.endswith('localdomain') or
  105. # OpenShift will not allow a node with more than 63 chars in name.
  106. len(hostname) > 63):
  107. return False
  108. return True
  109. def choose_hostname(hostnames=None, fallback=''):
  110. """ Choose a hostname from the provided hostnames
  111. Given a list of hostnames and a fallback value, choose a hostname to
  112. use. This function will prefer fqdns if they exist (excluding any that
  113. begin with localhost or end with localdomain) over ip addresses.
  114. Args:
  115. hostnames (list): list of hostnames
  116. fallback (str): default value to set if hostnames does not contain
  117. a valid hostname
  118. Returns:
  119. str: chosen hostname
  120. """
  121. hostname = fallback
  122. if hostnames is None:
  123. return hostname
  124. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  125. ips = [i for i in hostnames if i is not None and isinstance(i, string_types) and re.match(ip_regex, i)]
  126. hosts = [i for i in hostnames if i is not None and i != '' and i not in ips]
  127. for host_list in (hosts, ips):
  128. for host in host_list:
  129. if hostname_valid(host):
  130. return host
  131. return hostname
  132. def query_metadata(metadata_url, headers=None, expect_json=False):
  133. """ Return metadata from the provided metadata_url
  134. Args:
  135. metadata_url (str): metadata url
  136. headers (dict): headers to set for metadata request
  137. expect_json (bool): does the metadata_url return json
  138. Returns:
  139. dict or list: metadata request result
  140. """
  141. result, info = fetch_url(module, metadata_url, headers=headers) # noqa: F405
  142. if info['status'] != 200:
  143. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  144. if expect_json:
  145. return module.from_json(to_native(result.read())) # noqa: F405
  146. else:
  147. return [to_native(line.strip()) for line in result.readlines()]
  148. def walk_metadata(metadata_url, headers=None, expect_json=False):
  149. """ Walk the metadata tree and return a dictionary of the entire tree
  150. Args:
  151. metadata_url (str): metadata url
  152. headers (dict): headers to set for metadata request
  153. expect_json (bool): does the metadata_url return json
  154. Returns:
  155. dict: the result of walking the metadata tree
  156. """
  157. metadata = dict()
  158. for line in query_metadata(metadata_url, headers, expect_json):
  159. if line.endswith('/') and not line == 'public-keys/':
  160. key = line[:-1]
  161. metadata[key] = walk_metadata(metadata_url + line,
  162. headers, expect_json)
  163. else:
  164. results = query_metadata(metadata_url + line, headers,
  165. expect_json)
  166. if len(results) == 1:
  167. # disable pylint maybe-no-member because overloaded use of
  168. # the module name causes pylint to not detect that results
  169. # is an array or hash
  170. # pylint: disable=maybe-no-member
  171. metadata[line] = results.pop()
  172. else:
  173. metadata[line] = results
  174. return metadata
  175. def get_provider_metadata(metadata_url, supports_recursive=False,
  176. headers=None, expect_json=False):
  177. """ Retrieve the provider metadata
  178. Args:
  179. metadata_url (str): metadata url
  180. supports_recursive (bool): does the provider metadata api support
  181. recursion
  182. headers (dict): headers to set for metadata request
  183. expect_json (bool): does the metadata_url return json
  184. Returns:
  185. dict: the provider metadata
  186. """
  187. try:
  188. if supports_recursive:
  189. metadata = query_metadata(metadata_url, headers,
  190. expect_json)
  191. else:
  192. metadata = walk_metadata(metadata_url, headers,
  193. expect_json)
  194. except OpenShiftFactsMetadataUnavailableError:
  195. metadata = None
  196. return metadata
  197. def normalize_gce_facts(metadata, facts):
  198. """ Normalize gce facts
  199. Args:
  200. metadata (dict): provider metadata
  201. facts (dict): facts to update
  202. Returns:
  203. dict: the result of adding the normalized metadata to the provided
  204. facts dict
  205. """
  206. for interface in metadata['instance']['networkInterfaces']:
  207. int_info = dict(ips=[interface['ip']], network_type='gce')
  208. int_info['public_ips'] = [ac['externalIp'] for ac
  209. in interface['accessConfigs']]
  210. int_info['public_ips'].extend(interface['forwardedIps'])
  211. _, _, network_id = interface['network'].rpartition('/')
  212. int_info['network_id'] = network_id
  213. facts['network']['interfaces'].append(int_info)
  214. _, _, zone = metadata['instance']['zone'].rpartition('/')
  215. facts['zone'] = zone
  216. # GCE currently only supports a single interface
  217. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  218. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  219. facts['network']['public_ip'] = pub_ip
  220. # Split instance hostname from GCE metadata to use the short instance name
  221. facts['network']['hostname'] = metadata['instance']['hostname'].split('.')[0]
  222. # TODO: attempt to resolve public_hostname
  223. facts['network']['public_hostname'] = facts['network']['public_ip']
  224. return facts
  225. def normalize_aws_facts(metadata, facts):
  226. """ Normalize aws facts
  227. Args:
  228. metadata (dict): provider metadata
  229. facts (dict): facts to update
  230. Returns:
  231. dict: the result of adding the normalized metadata to the provided
  232. facts dict
  233. """
  234. for interface in sorted(
  235. metadata['network']['interfaces']['macs'].values(),
  236. key=lambda x: x['device-number']
  237. ):
  238. int_info = dict()
  239. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  240. for ips_var, int_var in iteritems(var_map):
  241. ips = interface.get(int_var)
  242. if isinstance(ips, string_types):
  243. int_info[ips_var] = [ips]
  244. else:
  245. int_info[ips_var] = ips
  246. if 'vpc-id' in interface:
  247. int_info['network_type'] = 'vpc'
  248. else:
  249. int_info['network_type'] = 'classic'
  250. if int_info['network_type'] == 'vpc':
  251. int_info['network_id'] = interface['subnet-id']
  252. else:
  253. int_info['network_id'] = None
  254. facts['network']['interfaces'].append(int_info)
  255. facts['zone'] = metadata['placement']['availability-zone']
  256. # TODO: actually attempt to determine default local and public ips
  257. # by using the ansible default ip fact and the ipv4-associations
  258. # from the ec2 metadata
  259. facts['network']['ip'] = metadata.get('local-ipv4')
  260. facts['network']['public_ip'] = metadata.get('public-ipv4')
  261. # TODO: verify that local hostname makes sense and is resolvable
  262. facts['network']['hostname'] = metadata.get('local-hostname')
  263. # TODO: verify that public hostname makes sense and is resolvable
  264. facts['network']['public_hostname'] = metadata.get('public-hostname')
  265. return facts
  266. def normalize_openstack_facts(metadata, facts):
  267. """ Normalize openstack facts
  268. Args:
  269. metadata (dict): provider metadata
  270. facts (dict): facts to update
  271. Returns:
  272. dict: the result of adding the normalized metadata to the provided
  273. facts dict
  274. """
  275. # openstack ec2 compat api does not support network interfaces and
  276. # the version tested on did not include the info in the openstack
  277. # metadata api, should be updated if neutron exposes this.
  278. facts['zone'] = metadata['availability_zone']
  279. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  280. facts['network']['ip'] = local_ipv4
  281. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  282. for f_var, h_var, ip_var in [('hostname', 'hostname', 'local-ipv4'),
  283. ('public_hostname', 'public-hostname', 'public-ipv4')]:
  284. try:
  285. if socket.gethostbyname(metadata['ec2_compat'][h_var]) == metadata['ec2_compat'][ip_var]:
  286. facts['network'][f_var] = metadata['ec2_compat'][h_var]
  287. else:
  288. facts['network'][f_var] = metadata['ec2_compat'][ip_var]
  289. except socket.gaierror:
  290. facts['network'][f_var] = metadata['ec2_compat'][ip_var]
  291. return facts
  292. def normalize_provider_facts(provider, metadata):
  293. """ Normalize provider facts
  294. Args:
  295. provider (str): host provider
  296. metadata (dict): provider metadata
  297. Returns:
  298. dict: the normalized provider facts
  299. """
  300. if provider is None or metadata is None:
  301. return {}
  302. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  303. # and configure ipv6 facts if available
  304. # TODO: add support for setting user_data if available
  305. facts = dict(name=provider, metadata=metadata,
  306. network=dict(interfaces=[], ipv6_enabled=False))
  307. if provider == 'gce':
  308. facts = normalize_gce_facts(metadata, facts)
  309. elif provider == 'aws':
  310. facts = normalize_aws_facts(metadata, facts)
  311. elif provider == 'openstack':
  312. facts = normalize_openstack_facts(metadata, facts)
  313. return facts
  314. def set_identity_providers_if_unset(facts):
  315. """ Set identity_providers fact if not already present in facts dict
  316. Args:
  317. facts (dict): existing facts
  318. Returns:
  319. dict: the facts dict updated with the generated identity providers
  320. facts if they were not already present
  321. """
  322. if 'master' in facts:
  323. deployment_type = facts['common']['deployment_type']
  324. if 'identity_providers' not in facts['master']:
  325. identity_provider = dict(
  326. name='allow_all', challenge=True, login=True,
  327. kind='AllowAllPasswordIdentityProvider'
  328. )
  329. if deployment_type == 'openshift-enterprise':
  330. identity_provider = dict(
  331. name='deny_all', challenge=True, login=True,
  332. kind='DenyAllPasswordIdentityProvider'
  333. )
  334. facts['master']['identity_providers'] = [identity_provider]
  335. return facts
  336. def set_url_facts_if_unset(facts):
  337. """ Set url facts if not already present in facts dict
  338. Args:
  339. facts (dict): existing facts
  340. Returns:
  341. dict: the facts dict updated with the generated url facts if they
  342. were not already present
  343. """
  344. if 'master' in facts:
  345. hostname = facts['common']['hostname']
  346. cluster_hostname = facts['master'].get('cluster_hostname')
  347. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  348. public_hostname = facts['common']['public_hostname']
  349. api_hostname = cluster_hostname if cluster_hostname else hostname
  350. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  351. console_path = facts['master']['console_path']
  352. etcd_hosts = facts['master']['etcd_hosts']
  353. use_ssl = dict(
  354. api=facts['master']['api_use_ssl'],
  355. public_api=facts['master']['api_use_ssl'],
  356. loopback_api=facts['master']['api_use_ssl'],
  357. console=facts['master']['console_use_ssl'],
  358. public_console=facts['master']['console_use_ssl'],
  359. etcd=facts['master']['etcd_use_ssl']
  360. )
  361. ports = dict(
  362. api=facts['master']['api_port'],
  363. public_api=facts['master']['api_port'],
  364. loopback_api=facts['master']['api_port'],
  365. console=facts['master']['console_port'],
  366. public_console=facts['master']['console_port'],
  367. etcd=facts['master']['etcd_port'],
  368. )
  369. etcd_urls = []
  370. if etcd_hosts != '':
  371. facts['master']['etcd_port'] = ports['etcd']
  372. for host in etcd_hosts:
  373. etcd_urls.append(format_url(use_ssl['etcd'], host,
  374. ports['etcd']))
  375. else:
  376. etcd_urls = [format_url(use_ssl['etcd'], hostname,
  377. ports['etcd'])]
  378. facts['master'].setdefault('etcd_urls', etcd_urls)
  379. prefix_hosts = [('api', api_hostname),
  380. ('public_api', api_public_hostname),
  381. ('loopback_api', hostname)]
  382. for prefix, host in prefix_hosts:
  383. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  384. host,
  385. ports[prefix]))
  386. r_lhn = "{0}:{1}".format(hostname, ports['api']).replace('.', '-')
  387. r_lhu = "system:openshift-master/{0}:{1}".format(api_hostname, ports['api']).replace('.', '-')
  388. facts['master'].setdefault('loopback_cluster_name', r_lhn)
  389. facts['master'].setdefault('loopback_context_name', "default/{0}/system:openshift-master".format(r_lhn))
  390. facts['master'].setdefault('loopback_user', r_lhu)
  391. prefix_hosts = [('console', api_hostname), ('public_console', api_public_hostname)]
  392. for prefix, host in prefix_hosts:
  393. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  394. host,
  395. ports[prefix],
  396. console_path))
  397. return facts
  398. def set_aggregate_facts(facts):
  399. """ Set aggregate facts
  400. Args:
  401. facts (dict): existing facts
  402. Returns:
  403. dict: the facts dict updated with aggregated facts
  404. """
  405. all_hostnames = set()
  406. internal_hostnames = set()
  407. kube_svc_ip = first_ip(facts['common']['portal_net'])
  408. if 'common' in facts:
  409. all_hostnames.add(facts['common']['hostname'])
  410. all_hostnames.add(facts['common']['public_hostname'])
  411. all_hostnames.add(facts['common']['ip'])
  412. all_hostnames.add(facts['common']['public_ip'])
  413. facts['common']['kube_svc_ip'] = kube_svc_ip
  414. internal_hostnames.add(facts['common']['hostname'])
  415. internal_hostnames.add(facts['common']['ip'])
  416. cluster_domain = facts['common']['dns_domain']
  417. if 'master' in facts:
  418. if 'cluster_hostname' in facts['master']:
  419. all_hostnames.add(facts['master']['cluster_hostname'])
  420. if 'cluster_public_hostname' in facts['master']:
  421. all_hostnames.add(facts['master']['cluster_public_hostname'])
  422. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  423. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  424. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  425. all_hostnames.update(svc_names)
  426. internal_hostnames.update(svc_names)
  427. all_hostnames.add(kube_svc_ip)
  428. internal_hostnames.add(kube_svc_ip)
  429. facts['common']['all_hostnames'] = list(all_hostnames)
  430. facts['common']['internal_hostnames'] = list(internal_hostnames)
  431. return facts
  432. def set_deployment_facts_if_unset(facts):
  433. """ Set Facts that vary based on deployment_type. This currently
  434. includes master.registry_url
  435. Args:
  436. facts (dict): existing facts
  437. Returns:
  438. dict: the facts dict updated with the generated deployment_type
  439. facts
  440. """
  441. if 'master' in facts:
  442. deployment_type = facts['common']['deployment_type']
  443. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  444. if 'disabled_features' not in facts['master']:
  445. if facts['common']['deployment_subtype'] == 'registry':
  446. facts['master']['disabled_features'] = openshift_features
  447. if 'registry_url' not in facts['master']:
  448. registry_url = 'openshift/origin-${component}:${version}'
  449. if deployment_type == 'openshift-enterprise':
  450. registry_url = 'openshift3/ose-${component}:${version}'
  451. facts['master']['registry_url'] = registry_url
  452. return facts
  453. # pylint: disable=too-many-statements
  454. def set_version_facts_if_unset(facts):
  455. """ Set version facts. This currently includes common.version and
  456. common.version_gte_3_x
  457. Args:
  458. facts (dict): existing facts
  459. Returns:
  460. dict: the facts dict updated with version facts.
  461. """
  462. if 'common' in facts:
  463. openshift_version = get_openshift_version(facts)
  464. if openshift_version and openshift_version != "latest":
  465. version = LooseVersion(openshift_version)
  466. facts['common']['version'] = openshift_version
  467. facts['common']['short_version'] = '.'.join([str(x) for x in version.version[0:2]])
  468. version_gte_3_6 = version >= LooseVersion('3.6')
  469. version_gte_3_7 = version >= LooseVersion('3.7')
  470. version_gte_3_8 = version >= LooseVersion('3.8')
  471. version_gte_3_9 = version >= LooseVersion('3.9')
  472. else:
  473. # 'Latest' version is set to True, 'Next' versions set to False
  474. version_gte_3_6 = True
  475. version_gte_3_7 = True
  476. version_gte_3_8 = False
  477. version_gte_3_9 = False
  478. facts['common']['version_gte_3_6'] = version_gte_3_6
  479. facts['common']['version_gte_3_7'] = version_gte_3_7
  480. facts['common']['version_gte_3_8'] = version_gte_3_8
  481. facts['common']['version_gte_3_9'] = version_gte_3_9
  482. if version_gte_3_9:
  483. examples_content_version = 'v3.9'
  484. elif version_gte_3_8:
  485. examples_content_version = 'v3.8'
  486. elif version_gte_3_7:
  487. examples_content_version = 'v3.7'
  488. elif version_gte_3_6:
  489. examples_content_version = 'v3.6'
  490. else:
  491. examples_content_version = 'v1.5'
  492. facts['common']['examples_content_version'] = examples_content_version
  493. return facts
  494. def set_sdn_facts_if_unset(facts, system_facts):
  495. """ Set sdn facts if not already present in facts dict
  496. Args:
  497. facts (dict): existing facts
  498. system_facts (dict): ansible_facts
  499. Returns:
  500. dict: the facts dict updated with the generated sdn facts if they
  501. were not already present
  502. """
  503. if 'master' in facts:
  504. # set defaults for sdn_cluster_network_cidr and sdn_host_subnet_length
  505. # these might be overridden if they exist in the master config file
  506. sdn_cluster_network_cidr = '10.128.0.0/14'
  507. sdn_host_subnet_length = '9'
  508. master_cfg_path = os.path.join(facts['common']['config_base'],
  509. 'master/master-config.yaml')
  510. if os.path.isfile(master_cfg_path):
  511. with open(master_cfg_path, 'r') as master_cfg_f:
  512. config = yaml.safe_load(master_cfg_f.read())
  513. if 'networkConfig' in config:
  514. if 'clusterNetworkCIDR' in config['networkConfig']:
  515. sdn_cluster_network_cidr = \
  516. config['networkConfig']['clusterNetworkCIDR']
  517. if 'hostSubnetLength' in config['networkConfig']:
  518. sdn_host_subnet_length = \
  519. config['networkConfig']['hostSubnetLength']
  520. if 'sdn_cluster_network_cidr' not in facts['master']:
  521. facts['master']['sdn_cluster_network_cidr'] = sdn_cluster_network_cidr
  522. if 'sdn_host_subnet_length' not in facts['master']:
  523. facts['master']['sdn_host_subnet_length'] = sdn_host_subnet_length
  524. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  525. node_ip = facts['common']['ip']
  526. # default MTU if interface MTU cannot be detected
  527. facts['node']['sdn_mtu'] = '1450'
  528. for val in itervalues(system_facts):
  529. if isinstance(val, dict) and 'mtu' in val:
  530. mtu = val['mtu']
  531. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  532. facts['node']['sdn_mtu'] = str(mtu - 50)
  533. return facts
  534. def set_nodename(facts):
  535. """ set nodename """
  536. if 'node' in facts and 'common' in facts:
  537. if 'cloudprovider' in facts and facts['cloudprovider']['kind'] == 'gce':
  538. facts['node']['nodename'] = facts['provider']['metadata']['instance']['hostname'].split('.')[0]
  539. # TODO: The openstack cloudprovider nodename setting was too opinionaed.
  540. # It needs to be generalized before it can be enabled again.
  541. # elif 'cloudprovider' in facts and facts['cloudprovider']['kind'] == 'openstack':
  542. # facts['node']['nodename'] = facts['provider']['metadata']['hostname'].replace('.novalocal', '')
  543. else:
  544. facts['node']['nodename'] = facts['common']['hostname'].lower()
  545. return facts
  546. def format_url(use_ssl, hostname, port, path=''):
  547. """ Format url based on ssl flag, hostname, port and path
  548. Args:
  549. use_ssl (bool): is ssl enabled
  550. hostname (str): hostname
  551. port (str): port
  552. path (str): url path
  553. Returns:
  554. str: The generated url string
  555. """
  556. scheme = 'https' if use_ssl else 'http'
  557. netloc = hostname
  558. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  559. netloc += ":%s" % port
  560. try:
  561. url = urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  562. except AttributeError:
  563. # pylint: disable=undefined-variable
  564. url = urlunparse((scheme, netloc, path, '', '', ''))
  565. return url
  566. def get_current_config(facts):
  567. """ Get current openshift config
  568. Args:
  569. facts (dict): existing facts
  570. Returns:
  571. dict: the facts dict updated with the current openshift config
  572. """
  573. current_config = dict()
  574. roles = [role for role in facts if role not in ['common', 'provider']]
  575. for role in roles:
  576. if 'roles' in current_config:
  577. current_config['roles'].append(role)
  578. else:
  579. current_config['roles'] = [role]
  580. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  581. # determine the location of files.
  582. # TODO: I suspect this isn't working right now, but it doesn't prevent
  583. # anything from working properly as far as I can tell, perhaps because
  584. # we override the kubeconfig path everywhere we use it?
  585. # Query kubeconfig settings
  586. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  587. if role == 'node':
  588. kubeconfig_dir = os.path.join(
  589. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  590. )
  591. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  592. if os.path.isfile('/usr/bin/openshift') and os.path.isfile(kubeconfig_path):
  593. try:
  594. _, output, _ = module.run_command( # noqa: F405
  595. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  596. "json", "--kubeconfig=%s" % kubeconfig_path],
  597. check_rc=False
  598. )
  599. config = json.loads(output)
  600. cad = 'certificate-authority-data'
  601. try:
  602. for cluster in config['clusters']:
  603. config['clusters'][cluster][cad] = 'masked'
  604. except KeyError:
  605. pass
  606. try:
  607. for user in config['users']:
  608. config['users'][user][cad] = 'masked'
  609. config['users'][user]['client-key-data'] = 'masked'
  610. except KeyError:
  611. pass
  612. current_config['kubeconfig'] = config
  613. # override pylint broad-except warning, since we do not want
  614. # to bubble up any exceptions if oc config view
  615. # fails
  616. # pylint: disable=broad-except
  617. except Exception:
  618. pass
  619. return current_config
  620. def build_controller_args(facts):
  621. """ Build master controller_args """
  622. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  623. 'cloudprovider')
  624. if 'master' in facts:
  625. controller_args = {}
  626. if 'cloudprovider' in facts:
  627. if 'kind' in facts['cloudprovider']:
  628. if facts['cloudprovider']['kind'] == 'aws':
  629. controller_args['cloud-provider'] = ['aws']
  630. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  631. if facts['cloudprovider']['kind'] == 'openstack':
  632. controller_args['cloud-provider'] = ['openstack']
  633. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  634. if facts['cloudprovider']['kind'] == 'gce':
  635. controller_args['cloud-provider'] = ['gce']
  636. controller_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  637. if controller_args != {}:
  638. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [])
  639. return facts
  640. def build_api_server_args(facts):
  641. """ Build master api_server_args """
  642. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  643. 'cloudprovider')
  644. if 'master' in facts:
  645. api_server_args = {}
  646. if 'cloudprovider' in facts:
  647. if 'kind' in facts['cloudprovider']:
  648. if facts['cloudprovider']['kind'] == 'aws':
  649. api_server_args['cloud-provider'] = ['aws']
  650. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  651. if facts['cloudprovider']['kind'] == 'openstack':
  652. api_server_args['cloud-provider'] = ['openstack']
  653. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  654. if facts['cloudprovider']['kind'] == 'gce':
  655. api_server_args['cloud-provider'] = ['gce']
  656. api_server_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  657. if api_server_args != {}:
  658. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [])
  659. return facts
  660. def is_service_running(service):
  661. """ Queries systemd through dbus to see if the service is running """
  662. service_running = False
  663. try:
  664. bus = SystemBus()
  665. systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
  666. manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
  667. service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
  668. service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
  669. service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
  670. service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
  671. service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
  672. if service_load_state == 'loaded' and service_active_state == 'active':
  673. service_running = True
  674. except DBusException:
  675. # TODO: do not swallow exception, as it may be hiding useful debugging
  676. # information.
  677. pass
  678. return service_running
  679. def rpm_rebuilddb():
  680. """
  681. Runs rpm --rebuilddb to ensure the db is in good shape.
  682. """
  683. module.run_command(['/usr/bin/rpm', '--rebuilddb']) # noqa: F405
  684. def get_version_output(binary, version_cmd):
  685. """ runs and returns the version output for a command """
  686. cmd = []
  687. for item in (binary, version_cmd):
  688. if isinstance(item, list):
  689. cmd.extend(item)
  690. else:
  691. cmd.append(item)
  692. if os.path.isfile(cmd[0]):
  693. _, output, _ = module.run_command(cmd) # noqa: F405
  694. return output
  695. # We may need this in the future.
  696. def get_docker_version_info():
  697. """ Parses and returns the docker version info """
  698. result = None
  699. if is_service_running('docker') or is_service_running('container-engine'):
  700. version_info = yaml.safe_load(get_version_output('/usr/bin/docker', 'version'))
  701. if 'Server' in version_info:
  702. result = {
  703. 'api_version': version_info['Server']['API version'],
  704. 'version': version_info['Server']['Version']
  705. }
  706. return result
  707. def get_openshift_version(facts):
  708. """ Get current version of openshift on the host.
  709. Checks a variety of ways ranging from fastest to slowest.
  710. Args:
  711. facts (dict): existing facts
  712. optional cli_image for pulling the version number
  713. Returns:
  714. version: the current openshift version
  715. """
  716. version = None
  717. # No need to run this method repeatedly on a system if we already know the
  718. # version
  719. # TODO: We need a way to force reload this after upgrading bits.
  720. if 'common' in facts:
  721. if 'version' in facts['common'] and facts['common']['version'] is not None:
  722. return chomp_commit_offset(facts['common']['version'])
  723. if os.path.isfile('/usr/bin/openshift'):
  724. _, output, _ = module.run_command(['/usr/bin/openshift', 'version']) # noqa: F405
  725. version = parse_openshift_version(output)
  726. else:
  727. version = get_container_openshift_version(facts)
  728. # Handle containerized masters that have not yet been configured as a node.
  729. # This can be very slow and may get re-run multiple times, so we only use this
  730. # if other methods failed to find a version.
  731. if not version and os.path.isfile('/usr/local/bin/openshift'):
  732. _, output, _ = module.run_command(['/usr/local/bin/openshift', 'version']) # noqa: F405
  733. version = parse_openshift_version(output)
  734. return chomp_commit_offset(version)
  735. def chomp_commit_offset(version):
  736. """Chomp any "+git.foo" commit offset string from the given `version`
  737. and return the modified version string.
  738. Ex:
  739. - chomp_commit_offset(None) => None
  740. - chomp_commit_offset(1337) => "1337"
  741. - chomp_commit_offset("v3.4.0.15+git.derp") => "v3.4.0.15"
  742. - chomp_commit_offset("v3.4.0.15") => "v3.4.0.15"
  743. - chomp_commit_offset("v1.3.0+52492b4") => "v1.3.0"
  744. """
  745. if version is None:
  746. return version
  747. else:
  748. # Stringify, just in case it's a Number type. Split by '+' and
  749. # return the first split. No concerns about strings without a
  750. # '+', .split() returns an array of the original string.
  751. return str(version).split('+')[0]
  752. def get_container_openshift_version(facts):
  753. """
  754. If containerized, see if we can determine the installed version via the
  755. systemd environment files.
  756. """
  757. deployment_type = facts['common']['deployment_type']
  758. service_type_dict = {'origin': 'origin',
  759. 'openshift-enterprise': 'atomic-openshift'}
  760. service_type = service_type_dict[deployment_type]
  761. for filename in ['/etc/sysconfig/%s-master-controllers', '/etc/sysconfig/%s-node']:
  762. env_path = filename % service_type
  763. if not os.path.exists(env_path):
  764. continue
  765. with open(env_path) as env_file:
  766. for line in env_file:
  767. if line.startswith("IMAGE_VERSION="):
  768. tag = line[len("IMAGE_VERSION="):].strip()
  769. # Remove leading "v" and any trailing release info, we just want
  770. # a version number here:
  771. no_v_version = tag[1:] if tag[0] == 'v' else tag
  772. version = no_v_version.split("-")[0]
  773. return version
  774. return None
  775. def parse_openshift_version(output):
  776. """ Apply provider facts to supplied facts dict
  777. Args:
  778. string: output of 'openshift version'
  779. Returns:
  780. string: the version number
  781. """
  782. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  783. ver = versions.get('openshift', '')
  784. # Remove trailing build number and commit hash from older versions, we need to return a straight
  785. # w.x.y.z version here for use as openshift_version throughout the playbooks/roles. (i.e. 3.1.1.6-64-g80b61da)
  786. ver = ver.split('-')[0]
  787. return ver
  788. def apply_provider_facts(facts, provider_facts):
  789. """ Apply provider facts to supplied facts dict
  790. Args:
  791. facts (dict): facts dict to update
  792. provider_facts (dict): provider facts to apply
  793. roles: host roles
  794. Returns:
  795. dict: the merged facts
  796. """
  797. if not provider_facts:
  798. return facts
  799. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  800. for h_var, ip_var in common_vars:
  801. ip_value = provider_facts['network'].get(ip_var)
  802. if ip_value:
  803. facts['common'][ip_var] = ip_value
  804. facts['common'][h_var] = choose_hostname(
  805. [provider_facts['network'].get(h_var)],
  806. facts['common'][h_var]
  807. )
  808. facts['provider'] = provider_facts
  809. return facts
  810. # Disabling pylint too many branches. This function needs refactored
  811. # but is a very core part of openshift_facts.
  812. # pylint: disable=too-many-branches, too-many-nested-blocks
  813. def merge_facts(orig, new, additive_facts_to_overwrite):
  814. """ Recursively merge facts dicts
  815. Args:
  816. orig (dict): existing facts
  817. new (dict): facts to update
  818. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  819. '.' notation ex: ['master.named_certificates']
  820. Returns:
  821. dict: the merged facts
  822. """
  823. additive_facts = ['named_certificates']
  824. # Facts we do not ever want to merge. These originate in inventory variables
  825. # and contain JSON dicts. We don't ever want to trigger a merge
  826. # here, just completely overwrite with the new if they are present there.
  827. inventory_json_facts = ['admission_plugin_config',
  828. 'kube_admission_plugin_config',
  829. 'image_policy_config',
  830. "builddefaults",
  831. "buildoverrides"]
  832. facts = dict()
  833. for key, value in iteritems(orig):
  834. # Key exists in both old and new facts.
  835. if key in new:
  836. if key in inventory_json_facts:
  837. # Watchout for JSON facts that sometimes load as strings.
  838. # (can happen if the JSON contains a boolean)
  839. if isinstance(new[key], string_types):
  840. facts[key] = yaml.safe_load(new[key])
  841. else:
  842. facts[key] = copy.deepcopy(new[key])
  843. # Continue to recurse if old and new fact is a dictionary.
  844. elif isinstance(value, dict) and isinstance(new[key], dict):
  845. # Collect the subset of additive facts to overwrite if
  846. # key matches. These will be passed to the subsequent
  847. # merge_facts call.
  848. relevant_additive_facts = []
  849. for item in additive_facts_to_overwrite:
  850. if '.' in item and item.startswith(key + '.'):
  851. relevant_additive_facts.append(item)
  852. facts[key] = merge_facts(value, new[key], relevant_additive_facts)
  853. # Key matches an additive fact and we are not overwriting
  854. # it so we will append the new value to the existing value.
  855. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  856. if isinstance(value, list) and isinstance(new[key], list):
  857. new_fact = []
  858. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  859. if item not in new_fact:
  860. new_fact.append(item)
  861. facts[key] = new_fact
  862. # No other condition has been met. Overwrite the old fact
  863. # with the new value.
  864. else:
  865. facts[key] = copy.deepcopy(new[key])
  866. # Key isn't in new so add it to facts to keep it.
  867. else:
  868. facts[key] = copy.deepcopy(value)
  869. new_keys = set(new.keys()) - set(orig.keys())
  870. for key in new_keys:
  871. # Watchout for JSON facts that sometimes load as strings.
  872. # (can happen if the JSON contains a boolean)
  873. if key in inventory_json_facts and isinstance(new[key], string_types):
  874. facts[key] = yaml.safe_load(new[key])
  875. else:
  876. facts[key] = copy.deepcopy(new[key])
  877. return facts
  878. def save_local_facts(filename, facts):
  879. """ Save local facts
  880. Args:
  881. filename (str): local facts file
  882. facts (dict): facts to set
  883. """
  884. try:
  885. fact_dir = os.path.dirname(filename)
  886. try:
  887. os.makedirs(fact_dir) # try to make the directory
  888. except OSError as exception:
  889. if exception.errno != errno.EEXIST: # but it is okay if it is already there
  890. raise # pass any other exceptions up the chain
  891. with open(filename, 'w') as fact_file:
  892. fact_file.write(module.jsonify(facts)) # noqa: F405
  893. os.chmod(filename, 0o600)
  894. except (IOError, OSError) as ex:
  895. raise OpenShiftFactsFileWriteError(
  896. "Could not create fact file: %s, error: %s" % (filename, ex)
  897. )
  898. def get_local_facts_from_file(filename):
  899. """ Retrieve local facts from fact file
  900. Args:
  901. filename (str): local facts file
  902. Returns:
  903. dict: the retrieved facts
  904. """
  905. local_facts = dict()
  906. try:
  907. # Handle conversion of INI style facts file to json style
  908. ini_facts = configparser.SafeConfigParser()
  909. ini_facts.read(filename)
  910. for section in ini_facts.sections():
  911. local_facts[section] = dict()
  912. for key, value in ini_facts.items(section):
  913. local_facts[section][key] = value
  914. except (configparser.MissingSectionHeaderError,
  915. configparser.ParsingError):
  916. try:
  917. with open(filename, 'r') as facts_file:
  918. local_facts = json.load(facts_file)
  919. except (ValueError, IOError):
  920. pass
  921. return local_facts
  922. def sort_unique(alist):
  923. """ Sorts and de-dupes a list
  924. Args:
  925. list: a list
  926. Returns:
  927. list: a sorted de-duped list
  928. """
  929. return sorted(list(set(alist)))
  930. def safe_get_bool(fact):
  931. """ Get a boolean fact safely.
  932. Args:
  933. facts: fact to convert
  934. Returns:
  935. bool: given fact as a bool
  936. """
  937. return bool(strtobool(str(fact)))
  938. def set_proxy_facts(facts):
  939. """ Set global proxy facts
  940. Args:
  941. facts(dict): existing facts
  942. Returns:
  943. facts(dict): Updated facts with missing values
  944. """
  945. if 'common' in facts:
  946. common = facts['common']
  947. if 'http_proxy' in common or 'https_proxy' in common or 'no_proxy' in common:
  948. if 'no_proxy' in common and isinstance(common['no_proxy'], string_types):
  949. common['no_proxy'] = common['no_proxy'].split(",")
  950. elif 'no_proxy' not in common:
  951. common['no_proxy'] = []
  952. # See https://bugzilla.redhat.com/show_bug.cgi?id=1466783
  953. # masters behind a proxy need to connect to etcd via IP
  954. if 'no_proxy_etcd_host_ips' in common:
  955. if isinstance(common['no_proxy_etcd_host_ips'], string_types):
  956. common['no_proxy'].extend(common['no_proxy_etcd_host_ips'].split(','))
  957. if 'generate_no_proxy_hosts' in common and safe_get_bool(common['generate_no_proxy_hosts']):
  958. if 'no_proxy_internal_hostnames' in common:
  959. common['no_proxy'].extend(common['no_proxy_internal_hostnames'].split(','))
  960. # We always add local dns domain and ourselves no matter what
  961. kube_svc_ip = str(ipaddress.ip_network(u(common['portal_net']))[1])
  962. common['no_proxy'].append(kube_svc_ip)
  963. common['no_proxy'].append('.' + common['dns_domain'])
  964. common['no_proxy'].append('.svc')
  965. common['no_proxy'].append(common['hostname'])
  966. common['no_proxy'] = ','.join(sort_unique(common['no_proxy']))
  967. facts['common'] = common
  968. return facts
  969. def set_builddefaults_facts(facts):
  970. """ Set build defaults including setting proxy values from http_proxy, https_proxy,
  971. no_proxy to the more specific builddefaults and builddefaults_git vars.
  972. 1. http_proxy, https_proxy, no_proxy
  973. 2. builddefaults_*
  974. 3. builddefaults_git_*
  975. Args:
  976. facts(dict): existing facts
  977. Returns:
  978. facts(dict): Updated facts with missing values
  979. """
  980. if 'builddefaults' in facts:
  981. builddefaults = facts['builddefaults']
  982. common = facts['common']
  983. # Copy values from common to builddefaults
  984. if 'http_proxy' not in builddefaults and 'http_proxy' in common:
  985. builddefaults['http_proxy'] = common['http_proxy']
  986. if 'https_proxy' not in builddefaults and 'https_proxy' in common:
  987. builddefaults['https_proxy'] = common['https_proxy']
  988. if 'no_proxy' not in builddefaults and 'no_proxy' in common:
  989. builddefaults['no_proxy'] = common['no_proxy']
  990. # Create git specific facts from generic values, if git specific values are
  991. # not defined.
  992. if 'git_http_proxy' not in builddefaults and 'http_proxy' in builddefaults:
  993. builddefaults['git_http_proxy'] = builddefaults['http_proxy']
  994. if 'git_https_proxy' not in builddefaults and 'https_proxy' in builddefaults:
  995. builddefaults['git_https_proxy'] = builddefaults['https_proxy']
  996. if 'git_no_proxy' not in builddefaults and 'no_proxy' in builddefaults:
  997. builddefaults['git_no_proxy'] = builddefaults['no_proxy']
  998. # If we're actually defining a builddefaults config then create admission_plugin_config
  999. # then merge builddefaults[config] structure into admission_plugin_config
  1000. # 'config' is the 'openshift_builddefaults_json' inventory variable
  1001. if 'config' in builddefaults:
  1002. if 'admission_plugin_config' not in facts['master']:
  1003. # Scaffold out the full expected datastructure
  1004. facts['master']['admission_plugin_config'] = {'BuildDefaults': {'configuration': {'env': {}}}}
  1005. facts['master']['admission_plugin_config'].update(builddefaults['config'])
  1006. if 'env' in facts['master']['admission_plugin_config']['BuildDefaults']['configuration']:
  1007. delete_empty_keys(facts['master']['admission_plugin_config']['BuildDefaults']['configuration']['env'])
  1008. return facts
  1009. def delete_empty_keys(keylist):
  1010. """ Delete dictionary elements from keylist where "value" is empty.
  1011. Args:
  1012. keylist(list): A list of builddefault configuration envs.
  1013. Returns:
  1014. none
  1015. Example:
  1016. keylist = [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  1017. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  1018. {'name': 'NO_PROXY', 'value': ''}]
  1019. After calling delete_empty_keys the provided list is modified to become:
  1020. [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  1021. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'}]
  1022. """
  1023. count = 0
  1024. for i in range(0, len(keylist)):
  1025. if len(keylist[i - count]['value']) == 0:
  1026. del keylist[i - count]
  1027. count += 1
  1028. def set_buildoverrides_facts(facts):
  1029. """ Set build overrides
  1030. Args:
  1031. facts(dict): existing facts
  1032. Returns:
  1033. facts(dict): Updated facts with missing values
  1034. """
  1035. if 'buildoverrides' in facts:
  1036. buildoverrides = facts['buildoverrides']
  1037. # If we're actually defining a buildoverrides config then create admission_plugin_config
  1038. # then merge buildoverrides[config] structure into admission_plugin_config
  1039. if 'config' in buildoverrides:
  1040. if 'admission_plugin_config' not in facts['master']:
  1041. facts['master']['admission_plugin_config'] = dict()
  1042. facts['master']['admission_plugin_config'].update(buildoverrides['config'])
  1043. return facts
  1044. # pylint: disable=too-many-statements
  1045. def set_container_facts_if_unset(facts):
  1046. """ Set containerized facts.
  1047. Args:
  1048. facts (dict): existing facts
  1049. Returns:
  1050. dict: the facts dict updated with the generated containerization
  1051. facts
  1052. """
  1053. return facts
  1054. class OpenShiftFactsInternalError(Exception):
  1055. """Origin Facts Error"""
  1056. pass
  1057. class OpenShiftFactsUnsupportedRoleError(Exception):
  1058. """Origin Facts Unsupported Role Error"""
  1059. pass
  1060. class OpenShiftFactsFileWriteError(Exception):
  1061. """Origin Facts File Write Error"""
  1062. pass
  1063. class OpenShiftFactsMetadataUnavailableError(Exception):
  1064. """Origin Facts Metadata Unavailable Error"""
  1065. pass
  1066. class OpenShiftFacts(object):
  1067. """ Origin Facts
  1068. Attributes:
  1069. facts (dict): facts for the host
  1070. Args:
  1071. module (AnsibleModule): an AnsibleModule object
  1072. role (str): role for setting local facts
  1073. filename (str): local facts file to use
  1074. local_facts (dict): local facts to set
  1075. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1076. '.' notation ex: ['master.named_certificates']
  1077. Raises:
  1078. OpenShiftFactsUnsupportedRoleError:
  1079. """
  1080. known_roles = ['builddefaults',
  1081. 'buildoverrides',
  1082. 'cloudprovider',
  1083. 'common',
  1084. 'etcd',
  1085. 'master',
  1086. 'node']
  1087. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1088. # pylint: disable=too-many-arguments,no-value-for-parameter
  1089. def __init__(self, role, filename, local_facts,
  1090. additive_facts_to_overwrite=None):
  1091. self.changed = False
  1092. self.filename = filename
  1093. if role not in self.known_roles:
  1094. raise OpenShiftFactsUnsupportedRoleError(
  1095. "Role %s is not supported by this module" % role
  1096. )
  1097. self.role = role
  1098. # Collect system facts and preface each fact with 'ansible_'.
  1099. try:
  1100. # pylint: disable=too-many-function-args,invalid-name
  1101. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter']) # noqa: F405
  1102. additional_facts = {}
  1103. for (k, v) in self.system_facts.items():
  1104. additional_facts["ansible_%s" % k.replace('-', '_')] = v
  1105. self.system_facts.update(additional_facts)
  1106. except UnboundLocalError:
  1107. # ansible-2.2,2.3
  1108. self.system_facts = get_all_facts(module)['ansible_facts'] # noqa: F405
  1109. self.facts = self.generate_facts(local_facts,
  1110. additive_facts_to_overwrite)
  1111. def generate_facts(self,
  1112. local_facts,
  1113. additive_facts_to_overwrite):
  1114. """ Generate facts
  1115. Args:
  1116. local_facts (dict): local_facts for overriding generated defaults
  1117. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1118. '.' notation ex: ['master.named_certificates']
  1119. Returns:
  1120. dict: The generated facts
  1121. """
  1122. local_facts = self.init_local_facts(local_facts,
  1123. additive_facts_to_overwrite)
  1124. roles = local_facts.keys()
  1125. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1126. deployment_type = local_facts['common']['deployment_type']
  1127. else:
  1128. deployment_type = 'origin'
  1129. if 'common' in local_facts and 'deployment_subtype' in local_facts['common']:
  1130. deployment_subtype = local_facts['common']['deployment_subtype']
  1131. else:
  1132. deployment_subtype = 'basic'
  1133. defaults = self.get_defaults(roles, deployment_type, deployment_subtype)
  1134. provider_facts = self.init_provider_facts()
  1135. facts = apply_provider_facts(defaults, provider_facts)
  1136. facts = merge_facts(facts,
  1137. local_facts,
  1138. additive_facts_to_overwrite)
  1139. facts['current_config'] = get_current_config(facts)
  1140. facts = set_url_facts_if_unset(facts)
  1141. facts = set_identity_providers_if_unset(facts)
  1142. facts = set_deployment_facts_if_unset(facts)
  1143. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1144. facts = set_container_facts_if_unset(facts)
  1145. facts = build_controller_args(facts)
  1146. facts = build_api_server_args(facts)
  1147. facts = set_version_facts_if_unset(facts)
  1148. facts = set_aggregate_facts(facts)
  1149. facts = set_proxy_facts(facts)
  1150. facts = set_builddefaults_facts(facts)
  1151. facts = set_buildoverrides_facts(facts)
  1152. facts = set_nodename(facts)
  1153. return dict(openshift=facts)
  1154. def get_defaults(self, roles, deployment_type, deployment_subtype):
  1155. """ Get default fact values
  1156. Args:
  1157. roles (list): list of roles for this host
  1158. Returns:
  1159. dict: The generated default facts
  1160. """
  1161. defaults = {}
  1162. ip_addr = self.system_facts['ansible_default_ipv4']['address']
  1163. exit_code, output, _ = module.run_command(['hostname', '-f']) # noqa: F405
  1164. hostname_f = output.strip() if exit_code == 0 else ''
  1165. hostname_values = [hostname_f, self.system_facts['ansible_nodename'],
  1166. self.system_facts['ansible_fqdn']]
  1167. hostname = choose_hostname(hostname_values, ip_addr).lower()
  1168. defaults['common'] = dict(ip=ip_addr,
  1169. public_ip=ip_addr,
  1170. deployment_type=deployment_type,
  1171. deployment_subtype=deployment_subtype,
  1172. hostname=hostname,
  1173. public_hostname=hostname,
  1174. portal_net='172.30.0.0/16',
  1175. dns_domain='cluster.local',
  1176. config_base='/etc/origin')
  1177. if 'master' in roles:
  1178. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1179. controllers_port='8444',
  1180. console_use_ssl=True,
  1181. console_path='/console',
  1182. console_port='8443', etcd_use_ssl=True,
  1183. etcd_hosts='', etcd_port='4001',
  1184. portal_net='172.30.0.0/16',
  1185. embedded_kube=True,
  1186. embedded_dns=True,
  1187. bind_addr='0.0.0.0',
  1188. session_max_seconds=3600,
  1189. session_name='ssn',
  1190. session_secrets_file='',
  1191. access_token_max_seconds=86400,
  1192. auth_token_max_seconds=500,
  1193. oauth_grant_method='auto',
  1194. dynamic_provisioning_enabled=True,
  1195. max_requests_inflight=500)
  1196. if 'cloudprovider' in roles:
  1197. defaults['cloudprovider'] = dict(kind=None)
  1198. return defaults
  1199. def guess_host_provider(self):
  1200. """ Guess the host provider
  1201. Returns:
  1202. dict: The generated default facts for the detected provider
  1203. """
  1204. # TODO: cloud provider facts should probably be submitted upstream
  1205. product_name = self.system_facts['ansible_product_name']
  1206. product_version = self.system_facts['ansible_product_version']
  1207. virt_type = self.system_facts['ansible_virtualization_type']
  1208. virt_role = self.system_facts['ansible_virtualization_role']
  1209. bios_vendor = self.system_facts['ansible_system_vendor']
  1210. provider = None
  1211. metadata = None
  1212. if bios_vendor == 'Google':
  1213. provider = 'gce'
  1214. metadata_url = ('http://metadata.google.internal/'
  1215. 'computeMetadata/v1/?recursive=true')
  1216. headers = {'Metadata-Flavor': 'Google'}
  1217. metadata = get_provider_metadata(metadata_url, True, headers,
  1218. True)
  1219. # Filter sshKeys and serviceAccounts from gce metadata
  1220. if metadata:
  1221. metadata['project']['attributes'].pop('sshKeys', None)
  1222. metadata['instance'].pop('serviceAccounts', None)
  1223. elif bios_vendor == 'Amazon EC2':
  1224. # Adds support for Amazon EC2 C5 instance types
  1225. provider = 'aws'
  1226. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1227. metadata = get_provider_metadata(metadata_url)
  1228. elif virt_type == 'xen' and virt_role == 'guest' and re.match(r'.*\.amazon$', product_version):
  1229. provider = 'aws'
  1230. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1231. metadata = get_provider_metadata(metadata_url)
  1232. elif re.search(r'OpenStack', product_name):
  1233. provider = 'openstack'
  1234. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1235. 'meta_data.json')
  1236. metadata = get_provider_metadata(metadata_url, True, None,
  1237. True)
  1238. if metadata:
  1239. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1240. metadata['ec2_compat'] = get_provider_metadata(
  1241. ec2_compat_url
  1242. )
  1243. # disable pylint maybe-no-member because overloaded use of
  1244. # the module name causes pylint to not detect that results
  1245. # is an array or hash
  1246. # pylint: disable=maybe-no-member
  1247. # Filter public_keys and random_seed from openstack metadata
  1248. metadata.pop('public_keys', None)
  1249. metadata.pop('random_seed', None)
  1250. if not metadata['ec2_compat']:
  1251. metadata = None
  1252. return dict(name=provider, metadata=metadata)
  1253. def init_provider_facts(self):
  1254. """ Initialize the provider facts
  1255. Returns:
  1256. dict: The normalized provider facts
  1257. """
  1258. provider_info = self.guess_host_provider()
  1259. provider_facts = normalize_provider_facts(
  1260. provider_info.get('name'),
  1261. provider_info.get('metadata')
  1262. )
  1263. return provider_facts
  1264. # Disabling too-many-branches and too-many-locals.
  1265. # This should be cleaned up as a TODO item.
  1266. # pylint: disable=too-many-branches, too-many-locals
  1267. def init_local_facts(self, facts=None,
  1268. additive_facts_to_overwrite=None):
  1269. """ Initialize the local facts
  1270. Args:
  1271. facts (dict): local facts to set
  1272. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1273. '.' notation ex: ['master.named_certificates']
  1274. Returns:
  1275. dict: The result of merging the provided facts with existing
  1276. local facts
  1277. """
  1278. changed = False
  1279. facts_to_set = dict()
  1280. if facts is not None:
  1281. facts_to_set[self.role] = facts
  1282. local_facts = get_local_facts_from_file(self.filename)
  1283. migrated_facts = migrate_local_facts(local_facts)
  1284. new_local_facts = merge_facts(migrated_facts,
  1285. facts_to_set,
  1286. additive_facts_to_overwrite)
  1287. new_local_facts = self.remove_empty_facts(new_local_facts)
  1288. if new_local_facts != local_facts:
  1289. self.validate_local_facts(new_local_facts)
  1290. changed = True
  1291. if not module.check_mode: # noqa: F405
  1292. save_local_facts(self.filename, new_local_facts)
  1293. self.changed = changed
  1294. return new_local_facts
  1295. def remove_empty_facts(self, facts=None):
  1296. """ Remove empty facts
  1297. Args:
  1298. facts (dict): facts to clean
  1299. """
  1300. facts_to_remove = []
  1301. for fact, value in iteritems(facts):
  1302. if isinstance(facts[fact], dict):
  1303. facts[fact] = self.remove_empty_facts(facts[fact])
  1304. else:
  1305. if value == "" or value == [""] or value is None:
  1306. facts_to_remove.append(fact)
  1307. for fact in facts_to_remove:
  1308. del facts[fact]
  1309. return facts
  1310. def validate_local_facts(self, facts=None):
  1311. """ Validate local facts
  1312. Args:
  1313. facts (dict): local facts to validate
  1314. """
  1315. invalid_facts = dict()
  1316. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1317. if invalid_facts:
  1318. msg = 'Invalid facts detected:\n'
  1319. # pylint: disable=consider-iterating-dictionary
  1320. for key in invalid_facts.keys():
  1321. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1322. module.fail_json(msg=msg, changed=self.changed) # noqa: F405
  1323. # disabling pylint errors for line-too-long since we're dealing
  1324. # with best effort reduction of error messages here.
  1325. # disabling errors for too-many-branches since we require checking
  1326. # many conditions.
  1327. # pylint: disable=line-too-long, too-many-branches
  1328. @staticmethod
  1329. def validate_master_facts(facts, invalid_facts):
  1330. """ Validate master facts
  1331. Args:
  1332. facts (dict): local facts to validate
  1333. invalid_facts (dict): collected invalid_facts
  1334. Returns:
  1335. dict: Invalid facts
  1336. """
  1337. if 'master' in facts:
  1338. # openshift.master.session_auth_secrets
  1339. if 'session_auth_secrets' in facts['master']:
  1340. session_auth_secrets = facts['master']['session_auth_secrets']
  1341. if not issubclass(type(session_auth_secrets), list):
  1342. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1343. elif 'session_encryption_secrets' not in facts['master']:
  1344. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1345. 'if openshift_master_session_auth_secrets is provided.')
  1346. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1347. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1348. 'openshift_master_session_encryption_secrets must be '
  1349. 'equal length.')
  1350. else:
  1351. for secret in session_auth_secrets:
  1352. if len(secret) < 32:
  1353. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1354. 'Secrets must be at least 32 characters in length.')
  1355. # openshift.master.session_encryption_secrets
  1356. if 'session_encryption_secrets' in facts['master']:
  1357. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1358. if not issubclass(type(session_encryption_secrets), list):
  1359. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1360. elif 'session_auth_secrets' not in facts['master']:
  1361. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1362. 'set if openshift_master_session_encryption_secrets '
  1363. 'is provided.')
  1364. else:
  1365. for secret in session_encryption_secrets:
  1366. if len(secret) not in [16, 24, 32]:
  1367. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1368. 'Secrets must be 16, 24, or 32 characters in length.')
  1369. return invalid_facts
  1370. def main():
  1371. """ main """
  1372. # disabling pylint errors for global-variable-undefined and invalid-name
  1373. # for 'global module' usage, since it is required to use ansible_facts
  1374. # pylint: disable=global-variable-undefined, invalid-name
  1375. global module
  1376. module = AnsibleModule( # noqa: F405
  1377. argument_spec=dict(
  1378. role=dict(default='common', required=False,
  1379. choices=OpenShiftFacts.known_roles),
  1380. local_facts=dict(default=None, type='dict', required=False),
  1381. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1382. ),
  1383. supports_check_mode=True,
  1384. add_file_common_args=True,
  1385. )
  1386. if not HAVE_DBUS:
  1387. module.fail_json(msg="This module requires dbus python bindings") # noqa: F405
  1388. module.params['gather_subset'] = ['hardware', 'network', 'virtual', 'facter'] # noqa: F405
  1389. module.params['gather_timeout'] = 10 # noqa: F405
  1390. module.params['filter'] = '*' # noqa: F405
  1391. role = module.params['role'] # noqa: F405
  1392. local_facts = module.params['local_facts'] # noqa: F405
  1393. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite'] # noqa: F405
  1394. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1395. openshift_facts = OpenShiftFacts(role,
  1396. fact_file,
  1397. local_facts,
  1398. additive_facts_to_overwrite)
  1399. file_params = module.params.copy() # noqa: F405
  1400. file_params['path'] = fact_file
  1401. file_args = module.load_file_common_arguments(file_params) # noqa: F405
  1402. changed = module.set_fs_attributes_if_different(file_args, # noqa: F405
  1403. openshift_facts.changed)
  1404. return module.exit_json(changed=changed, # noqa: F405
  1405. ansible_facts=openshift_facts.facts)
  1406. if __name__ == '__main__':
  1407. main()