openshift_facts.py 78 KB

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