openshift_facts.py 71 KB

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