openshift_facts.py 79 KB

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