openshift_facts.py 81 KB

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