openshift_facts.py 86 KB

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