openshift_facts.py 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  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. import ConfigParser
  9. import copy
  10. import io
  11. import os
  12. import yaml
  13. from distutils.util import strtobool
  14. from distutils.version import LooseVersion
  15. import struct
  16. import socket
  17. from dbus import SystemBus, Interface
  18. from dbus.exceptions import DBusException
  19. DOCUMENTATION = '''
  20. ---
  21. module: openshift_facts
  22. short_description: Cluster Facts
  23. author: Jason DeTiberus
  24. requirements: [ ]
  25. '''
  26. EXAMPLES = '''
  27. '''
  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. if 'metrics' not in facts['hosted']:
  409. facts['hosted']['metrics'] = {}
  410. if 'selector' not in facts['hosted']['metrics'] or facts['hosted']['metrics']['selector'] in [None, 'None']:
  411. facts['hosted']['metrics']['selector'] = None
  412. if 'logging' not in facts['hosted']:
  413. facts['hosted']['logging'] = {}
  414. if 'selector' not in facts['hosted']['logging'] or facts['hosted']['logging']['selector'] in [None, 'None']:
  415. facts['hosted']['logging']['selector'] = None
  416. return facts
  417. def set_dnsmasq_facts_if_unset(facts):
  418. """ Set dnsmasq facts if not already present in facts
  419. Args:
  420. facts (dict) existing facts
  421. Returns:
  422. facts (dict) updated facts with values set if not previously set
  423. """
  424. if 'common' in facts:
  425. facts['common']['use_dnsmasq'] = bool('use_dnsmasq' not in facts['common'] and
  426. safe_get_bool(facts['common']['version_gte_3_2_or_1_2']))
  427. if 'master' in facts and 'dns_port' not in facts['master']:
  428. if safe_get_bool(facts['common']['use_dnsmasq']):
  429. facts['master']['dns_port'] = 8053
  430. else:
  431. facts['master']['dns_port'] = 53
  432. return facts
  433. def set_project_cfg_facts_if_unset(facts):
  434. """ Set Project Configuration facts if not already present in facts dict
  435. dict:
  436. Args:
  437. facts (dict): existing facts
  438. Returns:
  439. dict: the facts dict updated with the generated Project Configuration
  440. facts if they were not already present
  441. """
  442. config = {
  443. 'default_node_selector': '',
  444. 'project_request_message': '',
  445. 'project_request_template': '',
  446. 'mcs_allocator_range': 's0:/2',
  447. 'mcs_labels_per_project': 5,
  448. 'uid_allocator_range': '1000000000-1999999999/10000'
  449. }
  450. if 'master' in facts:
  451. for key, value in config.items():
  452. if key not in facts['master']:
  453. facts['master'][key] = value
  454. return facts
  455. def set_identity_providers_if_unset(facts):
  456. """ Set identity_providers fact if not already present in facts dict
  457. Args:
  458. facts (dict): existing facts
  459. Returns:
  460. dict: the facts dict updated with the generated identity providers
  461. facts if they were not already present
  462. """
  463. if 'master' in facts:
  464. deployment_type = facts['common']['deployment_type']
  465. if 'identity_providers' not in facts['master']:
  466. identity_provider = dict(
  467. name='allow_all', challenge=True, login=True,
  468. kind='AllowAllPasswordIdentityProvider'
  469. )
  470. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  471. identity_provider = dict(
  472. name='deny_all', challenge=True, login=True,
  473. kind='DenyAllPasswordIdentityProvider'
  474. )
  475. facts['master']['identity_providers'] = [identity_provider]
  476. return facts
  477. def set_url_facts_if_unset(facts):
  478. """ Set url facts if not already present in facts dict
  479. Args:
  480. facts (dict): existing facts
  481. Returns:
  482. dict: the facts dict updated with the generated url facts if they
  483. were not already present
  484. """
  485. if 'master' in facts:
  486. hostname = facts['common']['hostname']
  487. cluster_hostname = facts['master'].get('cluster_hostname')
  488. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  489. public_hostname = facts['common']['public_hostname']
  490. api_hostname = cluster_hostname if cluster_hostname else hostname
  491. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  492. console_path = facts['master']['console_path']
  493. etcd_hosts = facts['master']['etcd_hosts']
  494. use_ssl = dict(
  495. api=facts['master']['api_use_ssl'],
  496. public_api=facts['master']['api_use_ssl'],
  497. loopback_api=facts['master']['api_use_ssl'],
  498. console=facts['master']['console_use_ssl'],
  499. public_console=facts['master']['console_use_ssl'],
  500. etcd=facts['master']['etcd_use_ssl']
  501. )
  502. ports = dict(
  503. api=facts['master']['api_port'],
  504. public_api=facts['master']['api_port'],
  505. loopback_api=facts['master']['api_port'],
  506. console=facts['master']['console_port'],
  507. public_console=facts['master']['console_port'],
  508. etcd=facts['master']['etcd_port'],
  509. )
  510. etcd_urls = []
  511. if etcd_hosts != '':
  512. facts['master']['etcd_port'] = ports['etcd']
  513. facts['master']['embedded_etcd'] = False
  514. for host in etcd_hosts:
  515. etcd_urls.append(format_url(use_ssl['etcd'], host,
  516. ports['etcd']))
  517. else:
  518. etcd_urls = [format_url(use_ssl['etcd'], hostname,
  519. ports['etcd'])]
  520. facts['master'].setdefault('etcd_urls', etcd_urls)
  521. prefix_hosts = [('api', api_hostname),
  522. ('public_api', api_public_hostname),
  523. ('loopback_api', hostname)]
  524. for prefix, host in prefix_hosts:
  525. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  526. host,
  527. ports[prefix]))
  528. r_lhn = "{0}:{1}".format(hostname, ports['api']).replace('.', '-')
  529. r_lhu = "system:openshift-master/{0}:{1}".format(api_hostname, ports['api']).replace('.', '-')
  530. facts['master'].setdefault('loopback_cluster_name', r_lhn)
  531. facts['master'].setdefault('loopback_context_name', "default/{0}/system:openshift-master".format(r_lhn))
  532. facts['master'].setdefault('loopback_user', r_lhu)
  533. prefix_hosts = [('console', api_hostname), ('public_console', api_public_hostname)]
  534. for prefix, host in prefix_hosts:
  535. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  536. host,
  537. ports[prefix],
  538. console_path))
  539. return facts
  540. def set_aggregate_facts(facts):
  541. """ Set aggregate facts
  542. Args:
  543. facts (dict): existing facts
  544. Returns:
  545. dict: the facts dict updated with aggregated facts
  546. """
  547. all_hostnames = set()
  548. internal_hostnames = set()
  549. kube_svc_ip = first_ip(facts['common']['portal_net'])
  550. if 'common' in facts:
  551. all_hostnames.add(facts['common']['hostname'])
  552. all_hostnames.add(facts['common']['public_hostname'])
  553. all_hostnames.add(facts['common']['ip'])
  554. all_hostnames.add(facts['common']['public_ip'])
  555. facts['common']['kube_svc_ip'] = kube_svc_ip
  556. internal_hostnames.add(facts['common']['hostname'])
  557. internal_hostnames.add(facts['common']['ip'])
  558. cluster_domain = facts['common']['dns_domain']
  559. if 'master' in facts:
  560. if 'cluster_hostname' in facts['master']:
  561. all_hostnames.add(facts['master']['cluster_hostname'])
  562. if 'cluster_public_hostname' in facts['master']:
  563. all_hostnames.add(facts['master']['cluster_public_hostname'])
  564. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  565. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  566. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  567. all_hostnames.update(svc_names)
  568. internal_hostnames.update(svc_names)
  569. all_hostnames.add(kube_svc_ip)
  570. internal_hostnames.add(kube_svc_ip)
  571. facts['common']['all_hostnames'] = list(all_hostnames)
  572. facts['common']['internal_hostnames'] = list(internal_hostnames)
  573. return facts
  574. def set_etcd_facts_if_unset(facts):
  575. """
  576. If using embedded etcd, loads the data directory from master-config.yaml.
  577. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  578. If anything goes wrong parsing these, the fact will not be set.
  579. """
  580. if 'master' in facts and safe_get_bool(facts['master']['embedded_etcd']):
  581. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  582. if 'etcd_data_dir' not in etcd_facts:
  583. try:
  584. # Parse master config to find actual etcd data dir:
  585. master_cfg_path = os.path.join(facts['common']['config_base'],
  586. 'master/master-config.yaml')
  587. master_cfg_f = open(master_cfg_path, 'r')
  588. config = yaml.safe_load(master_cfg_f.read())
  589. master_cfg_f.close()
  590. etcd_facts['etcd_data_dir'] = \
  591. config['etcdConfig']['storageDirectory']
  592. facts['etcd'] = etcd_facts
  593. # We don't want exceptions bubbling up here:
  594. # pylint: disable=broad-except
  595. except Exception:
  596. pass
  597. else:
  598. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  599. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  600. try:
  601. # Add a fake section for parsing:
  602. ini_str = unicode('[root]\n' + open('/etc/etcd/etcd.conf', 'r').read(), 'utf-8')
  603. ini_fp = io.StringIO(ini_str)
  604. config = ConfigParser.RawConfigParser()
  605. config.readfp(ini_fp)
  606. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  607. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  608. etcd_data_dir = etcd_data_dir[1:-1]
  609. etcd_facts['etcd_data_dir'] = etcd_data_dir
  610. facts['etcd'] = etcd_facts
  611. # We don't want exceptions bubbling up here:
  612. # pylint: disable=broad-except
  613. except Exception:
  614. pass
  615. return facts
  616. def set_deployment_facts_if_unset(facts):
  617. """ Set Facts that vary based on deployment_type. This currently
  618. includes common.service_type, common.config_base, master.registry_url,
  619. node.registry_url, node.storage_plugin_deps
  620. Args:
  621. facts (dict): existing facts
  622. Returns:
  623. dict: the facts dict updated with the generated deployment_type
  624. facts
  625. """
  626. # disabled to avoid breaking up facts related to deployment type into
  627. # multiple methods for now.
  628. # pylint: disable=too-many-statements, too-many-branches
  629. if 'common' in facts:
  630. deployment_type = facts['common']['deployment_type']
  631. if 'service_type' not in facts['common']:
  632. service_type = 'atomic-openshift'
  633. if deployment_type == 'origin':
  634. service_type = 'origin'
  635. elif deployment_type in ['enterprise']:
  636. service_type = 'openshift'
  637. facts['common']['service_type'] = service_type
  638. if 'config_base' not in facts['common']:
  639. config_base = '/etc/origin'
  640. if deployment_type in ['enterprise']:
  641. config_base = '/etc/openshift'
  642. # Handle upgrade scenarios when symlinks don't yet exist:
  643. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  644. config_base = '/etc/openshift'
  645. facts['common']['config_base'] = config_base
  646. if 'data_dir' not in facts['common']:
  647. data_dir = '/var/lib/origin'
  648. if deployment_type in ['enterprise']:
  649. data_dir = '/var/lib/openshift'
  650. # Handle upgrade scenarios when symlinks don't yet exist:
  651. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  652. data_dir = '/var/lib/openshift'
  653. facts['common']['data_dir'] = data_dir
  654. if 'docker' in facts:
  655. deployment_type = facts['common']['deployment_type']
  656. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  657. addtl_regs = facts['docker'].get('additional_registries', [])
  658. ent_reg = 'registry.access.redhat.com'
  659. if ent_reg not in addtl_regs:
  660. facts['docker']['additional_registries'] = addtl_regs + [ent_reg]
  661. for role in ('master', 'node'):
  662. if role in facts:
  663. deployment_type = facts['common']['deployment_type']
  664. if 'registry_url' not in facts[role]:
  665. registry_url = 'openshift/origin-${component}:${version}'
  666. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  667. registry_url = 'openshift3/ose-${component}:${version}'
  668. elif deployment_type == 'atomic-enterprise':
  669. registry_url = 'aep3_beta/aep-${component}:${version}'
  670. facts[role]['registry_url'] = registry_url
  671. if 'master' in facts:
  672. deployment_type = facts['common']['deployment_type']
  673. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  674. if 'disabled_features' in facts['master']:
  675. if deployment_type == 'atomic-enterprise':
  676. curr_disabled_features = set(facts['master']['disabled_features'])
  677. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  678. else:
  679. if facts['common']['deployment_subtype'] == 'registry':
  680. facts['master']['disabled_features'] = openshift_features
  681. if 'node' in facts:
  682. deployment_type = facts['common']['deployment_type']
  683. if 'storage_plugin_deps' not in facts['node']:
  684. if deployment_type in ['openshift-enterprise', 'atomic-enterprise', 'origin']:
  685. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs', 'iscsi']
  686. else:
  687. facts['node']['storage_plugin_deps'] = []
  688. return facts
  689. def set_version_facts_if_unset(facts):
  690. """ Set version facts. This currently includes common.version and
  691. common.version_gte_3_1_or_1_1.
  692. Args:
  693. facts (dict): existing facts
  694. Returns:
  695. dict: the facts dict updated with version facts.
  696. """
  697. if 'common' in facts:
  698. deployment_type = facts['common']['deployment_type']
  699. version = get_openshift_version(facts)
  700. if version:
  701. facts['common']['version'] = version
  702. if deployment_type == 'origin':
  703. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('1.1.0')
  704. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('1.1.1')
  705. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('1.2.0')
  706. version_gte_3_3_or_1_3 = LooseVersion(version) >= LooseVersion('1.3.0')
  707. else:
  708. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('3.0.2.905')
  709. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('3.1.1')
  710. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('3.1.1.901')
  711. version_gte_3_3_or_1_3 = LooseVersion(version) >= LooseVersion('3.3.0')
  712. else:
  713. version_gte_3_1_or_1_1 = True
  714. version_gte_3_1_1_or_1_1_1 = True
  715. version_gte_3_2_or_1_2 = True
  716. version_gte_3_3_or_1_3 = False
  717. facts['common']['version_gte_3_1_or_1_1'] = version_gte_3_1_or_1_1
  718. facts['common']['version_gte_3_1_1_or_1_1_1'] = version_gte_3_1_1_or_1_1_1
  719. facts['common']['version_gte_3_2_or_1_2'] = version_gte_3_2_or_1_2
  720. facts['common']['version_gte_3_3_or_1_3'] = version_gte_3_3_or_1_3
  721. if version_gte_3_3_or_1_3:
  722. examples_content_version = 'v1.3'
  723. elif version_gte_3_2_or_1_2:
  724. examples_content_version = 'v1.2'
  725. elif version_gte_3_1_or_1_1:
  726. examples_content_version = 'v1.1'
  727. else:
  728. examples_content_version = 'v1.0'
  729. facts['common']['examples_content_version'] = examples_content_version
  730. return facts
  731. def set_manageiq_facts_if_unset(facts):
  732. """ Set manageiq facts. This currently includes common.use_manageiq.
  733. Args:
  734. facts (dict): existing facts
  735. Returns:
  736. dict: the facts dict updated with version facts.
  737. Raises:
  738. OpenShiftFactsInternalError:
  739. """
  740. if 'common' not in facts:
  741. if 'version_gte_3_1_or_1_1' not in facts['common']:
  742. raise OpenShiftFactsInternalError(
  743. "Invalid invocation: The required facts are not set"
  744. )
  745. if 'use_manageiq' not in facts['common']:
  746. facts['common']['use_manageiq'] = facts['common']['version_gte_3_1_or_1_1']
  747. return facts
  748. def set_sdn_facts_if_unset(facts, system_facts):
  749. """ Set sdn facts if not already present in facts dict
  750. Args:
  751. facts (dict): existing facts
  752. system_facts (dict): ansible_facts
  753. Returns:
  754. dict: the facts dict updated with the generated sdn facts if they
  755. were not already present
  756. """
  757. if 'common' in facts:
  758. use_sdn = facts['common']['use_openshift_sdn']
  759. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  760. use_sdn = safe_get_bool(use_sdn)
  761. facts['common']['use_openshift_sdn'] = use_sdn
  762. if 'sdn_network_plugin_name' not in facts['common']:
  763. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  764. facts['common']['sdn_network_plugin_name'] = plugin
  765. if 'master' in facts:
  766. if 'sdn_cluster_network_cidr' not in facts['master']:
  767. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  768. if 'sdn_host_subnet_length' not in facts['master']:
  769. facts['master']['sdn_host_subnet_length'] = '8'
  770. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  771. node_ip = facts['common']['ip']
  772. # default MTU if interface MTU cannot be detected
  773. facts['node']['sdn_mtu'] = '1450'
  774. for val in system_facts.itervalues():
  775. if isinstance(val, dict) and 'mtu' in val:
  776. mtu = val['mtu']
  777. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  778. facts['node']['sdn_mtu'] = str(mtu - 50)
  779. return facts
  780. def migrate_oauth_template_facts(facts):
  781. """
  782. Migrate an old oauth template fact to a newer format if it's present.
  783. The legacy 'oauth_template' fact was just a filename, and assumed you were
  784. setting the 'login' template.
  785. The new pluralized 'oauth_templates' fact is a dict mapping the template
  786. name to a filename.
  787. Simplify the code after this by merging the old fact into the new.
  788. """
  789. if 'master' in facts and 'oauth_template' in facts['master']:
  790. if 'oauth_templates' not in facts['master']:
  791. facts['master']['oauth_templates'] = {"login": facts['master']['oauth_template']}
  792. elif 'login' not in facts['master']['oauth_templates']:
  793. facts['master']['oauth_templates']['login'] = facts['master']['oauth_template']
  794. return facts
  795. def format_url(use_ssl, hostname, port, path=''):
  796. """ Format url based on ssl flag, hostname, port and path
  797. Args:
  798. use_ssl (bool): is ssl enabled
  799. hostname (str): hostname
  800. port (str): port
  801. path (str): url path
  802. Returns:
  803. str: The generated url string
  804. """
  805. scheme = 'https' if use_ssl else 'http'
  806. netloc = hostname
  807. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  808. netloc += ":%s" % port
  809. try:
  810. url = urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  811. except AttributeError:
  812. # pylint: disable=undefined-variable
  813. url = urlunparse((scheme, netloc, path, '', '', ''))
  814. return url
  815. def get_current_config(facts):
  816. """ Get current openshift config
  817. Args:
  818. facts (dict): existing facts
  819. Returns:
  820. dict: the facts dict updated with the current openshift config
  821. """
  822. current_config = dict()
  823. roles = [role for role in facts if role not in ['common', 'provider']]
  824. for role in roles:
  825. if 'roles' in current_config:
  826. current_config['roles'].append(role)
  827. else:
  828. current_config['roles'] = [role]
  829. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  830. # determine the location of files.
  831. # TODO: I suspect this isn't working right now, but it doesn't prevent
  832. # anything from working properly as far as I can tell, perhaps because
  833. # we override the kubeconfig path everywhere we use it?
  834. # Query kubeconfig settings
  835. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  836. if role == 'node':
  837. kubeconfig_dir = os.path.join(
  838. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  839. )
  840. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  841. if (os.path.isfile('/usr/bin/openshift')
  842. and os.path.isfile(kubeconfig_path)):
  843. try:
  844. _, output, _ = module.run_command(
  845. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  846. "json", "--kubeconfig=%s" % kubeconfig_path],
  847. check_rc=False
  848. )
  849. config = json.loads(output)
  850. cad = 'certificate-authority-data'
  851. try:
  852. for cluster in config['clusters']:
  853. config['clusters'][cluster][cad] = 'masked'
  854. except KeyError:
  855. pass
  856. try:
  857. for user in config['users']:
  858. config['users'][user][cad] = 'masked'
  859. config['users'][user]['client-key-data'] = 'masked'
  860. except KeyError:
  861. pass
  862. current_config['kubeconfig'] = config
  863. # override pylint broad-except warning, since we do not want
  864. # to bubble up any exceptions if oc config view
  865. # fails
  866. # pylint: disable=broad-except
  867. except Exception:
  868. pass
  869. return current_config
  870. def build_kubelet_args(facts):
  871. """ Build node kubelet_args """
  872. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  873. 'cloudprovider')
  874. if 'node' in facts:
  875. kubelet_args = {}
  876. if 'cloudprovider' in facts:
  877. if 'kind' in facts['cloudprovider']:
  878. if facts['cloudprovider']['kind'] == 'aws':
  879. kubelet_args['cloud-provider'] = ['aws']
  880. kubelet_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  881. if facts['cloudprovider']['kind'] == 'openstack':
  882. kubelet_args['cloud-provider'] = ['openstack']
  883. kubelet_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  884. if facts['cloudprovider']['kind'] == 'gce':
  885. kubelet_args['cloud-provider'] = ['gce']
  886. if kubelet_args != {}:
  887. facts = merge_facts({'node': {'kubelet_args': kubelet_args}}, facts, [], [])
  888. return facts
  889. def build_controller_args(facts):
  890. """ Build master controller_args """
  891. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  892. 'cloudprovider')
  893. if 'master' in facts:
  894. controller_args = {}
  895. if 'cloudprovider' in facts:
  896. if 'kind' in facts['cloudprovider']:
  897. if facts['cloudprovider']['kind'] == 'aws':
  898. controller_args['cloud-provider'] = ['aws']
  899. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  900. if facts['cloudprovider']['kind'] == 'openstack':
  901. controller_args['cloud-provider'] = ['openstack']
  902. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  903. if facts['cloudprovider']['kind'] == 'gce':
  904. controller_args['cloud-provider'] = ['gce']
  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 facts['cloudprovider']['kind'] == 'gce':
  923. api_server_args['cloud-provider'] = ['gce']
  924. if api_server_args != {}:
  925. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [], [])
  926. return facts
  927. def is_service_running(service):
  928. """ Queries systemd through dbus to see if the service is running """
  929. service_running = False
  930. bus = SystemBus()
  931. systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
  932. manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
  933. try:
  934. service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
  935. service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
  936. service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
  937. service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
  938. service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
  939. if service_load_state == 'loaded' and service_active_state == 'active':
  940. service_running = True
  941. except DBusException:
  942. pass
  943. return service_running
  944. def get_version_output(binary, version_cmd):
  945. """ runs and returns the version output for a command """
  946. cmd = []
  947. for item in (binary, version_cmd):
  948. if isinstance(item, list):
  949. cmd.extend(item)
  950. else:
  951. cmd.append(item)
  952. if os.path.isfile(cmd[0]):
  953. _, output, _ = module.run_command(cmd)
  954. return output
  955. def get_docker_version_info():
  956. """ Parses and returns the docker version info """
  957. result = None
  958. if is_service_running('docker'):
  959. version_info = yaml.safe_load(get_version_output('/usr/bin/docker', 'version'))
  960. if 'Server' in version_info:
  961. result = {
  962. 'api_version': version_info['Server']['API version'],
  963. 'version': version_info['Server']['Version']
  964. }
  965. return result
  966. def get_openshift_version(facts):
  967. """ Get current version of openshift on the host.
  968. Checks a variety of ways ranging from fastest to slowest.
  969. Args:
  970. facts (dict): existing facts
  971. optional cli_image for pulling the version number
  972. Returns:
  973. version: the current openshift version
  974. """
  975. version = None
  976. # No need to run this method repeatedly on a system if we already know the
  977. # version
  978. if 'common' in facts:
  979. if 'version' in facts['common'] and facts['common']['version'] is not None:
  980. return facts['common']['version']
  981. if os.path.isfile('/usr/bin/openshift'):
  982. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  983. version = parse_openshift_version(output)
  984. elif 'common' in facts and 'is_containerized' in facts['common']:
  985. version = get_container_openshift_version(facts)
  986. # Handle containerized masters that have not yet been configured as a node.
  987. # This can be very slow and may get re-run multiple times, so we only use this
  988. # if other methods failed to find a version.
  989. if not version and os.path.isfile('/usr/local/bin/openshift'):
  990. _, output, _ = module.run_command(['/usr/local/bin/openshift', 'version'])
  991. version = parse_openshift_version(output)
  992. return version
  993. def get_container_openshift_version(facts):
  994. """
  995. If containerized, see if we can determine the installed version via the
  996. systemd environment files.
  997. """
  998. for filename in ['/etc/sysconfig/%s-master', '/etc/sysconfig/%s-node']:
  999. env_path = filename % facts['common']['service_type']
  1000. if not os.path.exists(env_path):
  1001. continue
  1002. with open(env_path) as env_file:
  1003. for line in env_file:
  1004. if line.startswith("IMAGE_VERSION="):
  1005. tag = line[len("IMAGE_VERSION="):].strip()
  1006. # Remove leading "v" and any trailing release info, we just want
  1007. # a version number here:
  1008. version = tag[1:].split("-")[0]
  1009. return version
  1010. return None
  1011. def parse_openshift_version(output):
  1012. """ Apply provider facts to supplied facts dict
  1013. Args:
  1014. string: output of 'openshift version'
  1015. Returns:
  1016. string: the version number
  1017. """
  1018. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  1019. ver = versions.get('openshift', '')
  1020. # Remove trailing build number and commit hash from older versions, we need to return a straight
  1021. # w.x.y.z version here for use as openshift_version throughout the playbooks/roles. (i.e. 3.1.1.6-64-g80b61da)
  1022. ver = ver.split('-')[0]
  1023. return ver
  1024. def apply_provider_facts(facts, provider_facts):
  1025. """ Apply provider facts to supplied facts dict
  1026. Args:
  1027. facts (dict): facts dict to update
  1028. provider_facts (dict): provider facts to apply
  1029. roles: host roles
  1030. Returns:
  1031. dict: the merged facts
  1032. """
  1033. if not provider_facts:
  1034. return facts
  1035. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  1036. for h_var, ip_var in common_vars:
  1037. ip_value = provider_facts['network'].get(ip_var)
  1038. if ip_value:
  1039. facts['common'][ip_var] = ip_value
  1040. facts['common'][h_var] = choose_hostname(
  1041. [provider_facts['network'].get(h_var)],
  1042. facts['common'][ip_var]
  1043. )
  1044. facts['provider'] = provider_facts
  1045. return facts
  1046. # Disabling pylint too many branches. This function needs refactored
  1047. # but is a very core part of openshift_facts.
  1048. # pylint: disable=too-many-branches
  1049. def merge_facts(orig, new, additive_facts_to_overwrite, protected_facts_to_overwrite):
  1050. """ Recursively merge facts dicts
  1051. Args:
  1052. orig (dict): existing facts
  1053. new (dict): facts to update
  1054. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1055. '.' notation ex: ['master.named_certificates']
  1056. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1057. '.' notation ex: ['master.master_count']
  1058. Returns:
  1059. dict: the merged facts
  1060. """
  1061. additive_facts = ['named_certificates']
  1062. protected_facts = ['ha', 'master_count']
  1063. # Facts we do not ever want to merge. These originate in inventory variables
  1064. # and contain JSON dicts. We don't ever want to trigger a merge
  1065. # here, just completely overwrite with the new if they are present there.
  1066. inventory_json_facts = ['admission_plugin_config',
  1067. 'kube_admission_plugin_config',
  1068. 'image_policy_config']
  1069. facts = dict()
  1070. for key, value in orig.iteritems():
  1071. # Key exists in both old and new facts.
  1072. if key in new:
  1073. if key in inventory_json_facts:
  1074. # Watchout for JSON facts that sometimes load as strings.
  1075. # (can happen if the JSON contains a boolean)
  1076. if isinstance(new[key], basestring):
  1077. facts[key] = yaml.safe_load(new[key])
  1078. else:
  1079. facts[key] = copy.deepcopy(new[key])
  1080. # Continue to recurse if old and new fact is a dictionary.
  1081. elif isinstance(value, dict) and isinstance(new[key], dict):
  1082. # Collect the subset of additive facts to overwrite if
  1083. # key matches. These will be passed to the subsequent
  1084. # merge_facts call.
  1085. relevant_additive_facts = []
  1086. for item in additive_facts_to_overwrite:
  1087. if '.' in item and item.startswith(key + '.'):
  1088. relevant_additive_facts.append(item)
  1089. # Collect the subset of protected facts to overwrite
  1090. # if key matches. These will be passed to the
  1091. # subsequent merge_facts call.
  1092. relevant_protected_facts = []
  1093. for item in protected_facts_to_overwrite:
  1094. if '.' in item and item.startswith(key + '.'):
  1095. relevant_protected_facts.append(item)
  1096. facts[key] = merge_facts(value, new[key], relevant_additive_facts, relevant_protected_facts)
  1097. # Key matches an additive fact and we are not overwriting
  1098. # it so we will append the new value to the existing value.
  1099. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  1100. if isinstance(value, list) and isinstance(new[key], list):
  1101. new_fact = []
  1102. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  1103. if item not in new_fact:
  1104. new_fact.append(item)
  1105. facts[key] = new_fact
  1106. # Key matches a protected fact and we are not overwriting
  1107. # it so we will determine if it is okay to change this
  1108. # fact.
  1109. elif key in protected_facts and key not in [x.split('.')[-1] for x in protected_facts_to_overwrite]:
  1110. # The master count (int) can only increase unless it
  1111. # has been passed as a protected fact to overwrite.
  1112. if key == 'master_count':
  1113. if int(value) <= int(new[key]):
  1114. facts[key] = copy.deepcopy(new[key])
  1115. else:
  1116. module.fail_json(msg='openshift_facts received a lower value for openshift.master.master_count')
  1117. # ha (bool) can not change unless it has been passed
  1118. # as a protected fact to overwrite.
  1119. if key == 'ha':
  1120. if safe_get_bool(value) != safe_get_bool(new[key]):
  1121. module.fail_json(msg='openshift_facts received a different value for openshift.master.ha')
  1122. else:
  1123. facts[key] = value
  1124. # No other condition has been met. Overwrite the old fact
  1125. # with the new value.
  1126. else:
  1127. facts[key] = copy.deepcopy(new[key])
  1128. # Key isn't in new so add it to facts to keep it.
  1129. else:
  1130. facts[key] = copy.deepcopy(value)
  1131. new_keys = set(new.keys()) - set(orig.keys())
  1132. for key in new_keys:
  1133. # Watchout for JSON facts that sometimes load as strings.
  1134. # (can happen if the JSON contains a boolean)
  1135. if key in inventory_json_facts and isinstance(new[key], basestring):
  1136. facts[key] = yaml.safe_load(new[key])
  1137. else:
  1138. facts[key] = copy.deepcopy(new[key])
  1139. return facts
  1140. def save_local_facts(filename, facts):
  1141. """ Save local facts
  1142. Args:
  1143. filename (str): local facts file
  1144. facts (dict): facts to set
  1145. """
  1146. try:
  1147. fact_dir = os.path.dirname(filename)
  1148. if not os.path.exists(fact_dir):
  1149. os.makedirs(fact_dir)
  1150. with open(filename, 'w') as fact_file:
  1151. fact_file.write(module.jsonify(facts))
  1152. os.chmod(filename, 0o600)
  1153. except (IOError, OSError) as ex:
  1154. raise OpenShiftFactsFileWriteError(
  1155. "Could not create fact file: %s, error: %s" % (filename, ex)
  1156. )
  1157. def get_local_facts_from_file(filename):
  1158. """ Retrieve local facts from fact file
  1159. Args:
  1160. filename (str): local facts file
  1161. Returns:
  1162. dict: the retrieved facts
  1163. """
  1164. local_facts = dict()
  1165. try:
  1166. # Handle conversion of INI style facts file to json style
  1167. ini_facts = ConfigParser.SafeConfigParser()
  1168. ini_facts.read(filename)
  1169. for section in ini_facts.sections():
  1170. local_facts[section] = dict()
  1171. for key, value in ini_facts.items(section):
  1172. local_facts[section][key] = value
  1173. except (ConfigParser.MissingSectionHeaderError,
  1174. ConfigParser.ParsingError):
  1175. try:
  1176. with open(filename, 'r') as facts_file:
  1177. local_facts = json.load(facts_file)
  1178. except (ValueError, IOError):
  1179. pass
  1180. return local_facts
  1181. def sort_unique(alist):
  1182. """ Sorts and de-dupes a list
  1183. Args:
  1184. list: a list
  1185. Returns:
  1186. list: a sorted de-duped list
  1187. """
  1188. alist.sort()
  1189. out = list()
  1190. for i in alist:
  1191. if i not in out:
  1192. out.append(i)
  1193. return out
  1194. def safe_get_bool(fact):
  1195. """ Get a boolean fact safely.
  1196. Args:
  1197. facts: fact to convert
  1198. Returns:
  1199. bool: given fact as a bool
  1200. """
  1201. return bool(strtobool(str(fact)))
  1202. def set_proxy_facts(facts):
  1203. """ Set global proxy facts and promote defaults from http_proxy, https_proxy,
  1204. no_proxy to the more specific builddefaults and builddefaults_git vars.
  1205. 1. http_proxy, https_proxy, no_proxy
  1206. 2. builddefaults_*
  1207. 3. builddefaults_git_*
  1208. Args:
  1209. facts(dict): existing facts
  1210. Returns:
  1211. facts(dict): Updated facts with missing values
  1212. """
  1213. if 'common' in facts:
  1214. common = facts['common']
  1215. if 'http_proxy' in common or 'https_proxy' in common:
  1216. if 'no_proxy' in common and \
  1217. isinstance(common['no_proxy'], basestring):
  1218. common['no_proxy'] = common['no_proxy'].split(",")
  1219. elif 'no_proxy' not in common:
  1220. common['no_proxy'] = []
  1221. if 'generate_no_proxy_hosts' in common and \
  1222. safe_get_bool(common['generate_no_proxy_hosts']):
  1223. if 'no_proxy_internal_hostnames' in common:
  1224. common['no_proxy'].extend(common['no_proxy_internal_hostnames'].split(','))
  1225. common['no_proxy'].append('.' + common['dns_domain'])
  1226. # We always add ourselves no matter what
  1227. common['no_proxy'].append(common['hostname'])
  1228. common['no_proxy'] = sort_unique(common['no_proxy'])
  1229. facts['common'] = common
  1230. if 'builddefaults' in facts:
  1231. builddefaults = facts['builddefaults']
  1232. common = facts['common']
  1233. # Copy values from common to builddefaults
  1234. if 'http_proxy' not in builddefaults and 'http_proxy' in common:
  1235. builddefaults['http_proxy'] = common['http_proxy']
  1236. if 'https_proxy' not in builddefaults and 'https_proxy' in common:
  1237. builddefaults['https_proxy'] = common['https_proxy']
  1238. # make no_proxy into a list if it's not
  1239. if 'no_proxy' in builddefaults and isinstance(builddefaults['no_proxy'], basestring):
  1240. builddefaults['no_proxy'] = builddefaults['no_proxy'].split(",")
  1241. if 'no_proxy' not in builddefaults and 'no_proxy' in common:
  1242. builddefaults['no_proxy'] = common['no_proxy']
  1243. if 'git_http_proxy' not in builddefaults and 'http_proxy' in builddefaults:
  1244. builddefaults['git_http_proxy'] = builddefaults['http_proxy']
  1245. if 'git_https_proxy' not in builddefaults and 'https_proxy' in builddefaults:
  1246. builddefaults['git_https_proxy'] = builddefaults['https_proxy']
  1247. # If we're actually defining a proxy config then create kube_admission_plugin_config
  1248. # if it doesn't exist, then merge builddefaults[config] structure
  1249. # into kube_admission_plugin_config
  1250. if 'kube_admission_plugin_config' not in facts['master']:
  1251. facts['master']['kube_admission_plugin_config'] = dict()
  1252. if 'config' in builddefaults and ('http_proxy' in builddefaults or \
  1253. 'https_proxy' in builddefaults):
  1254. facts['master']['kube_admission_plugin_config'].update(builddefaults['config'])
  1255. facts['builddefaults'] = builddefaults
  1256. return facts
  1257. # pylint: disable=too-many-statements
  1258. def set_container_facts_if_unset(facts):
  1259. """ Set containerized facts.
  1260. Args:
  1261. facts (dict): existing facts
  1262. Returns:
  1263. dict: the facts dict updated with the generated containerization
  1264. facts
  1265. """
  1266. deployment_type = facts['common']['deployment_type']
  1267. if deployment_type in ['enterprise', 'openshift-enterprise']:
  1268. master_image = 'openshift3/ose'
  1269. cli_image = master_image
  1270. node_image = 'openshift3/node'
  1271. ovs_image = 'openshift3/openvswitch'
  1272. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1273. pod_image = 'openshift3/ose-pod'
  1274. router_image = 'openshift3/ose-haproxy-router'
  1275. registry_image = 'openshift3/ose-docker-registry'
  1276. deployer_image = 'openshift3/ose-deployer'
  1277. elif deployment_type == 'atomic-enterprise':
  1278. master_image = 'aep3_beta/aep'
  1279. cli_image = master_image
  1280. node_image = 'aep3_beta/node'
  1281. ovs_image = 'aep3_beta/openvswitch'
  1282. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1283. pod_image = 'aep3_beta/aep-pod'
  1284. router_image = 'aep3_beta/aep-haproxy-router'
  1285. registry_image = 'aep3_beta/aep-docker-registry'
  1286. deployer_image = 'aep3_beta/aep-deployer'
  1287. else:
  1288. master_image = 'openshift/origin'
  1289. cli_image = master_image
  1290. node_image = 'openshift/node'
  1291. ovs_image = 'openshift/openvswitch'
  1292. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1293. pod_image = 'openshift/origin-pod'
  1294. router_image = 'openshift/origin-haproxy-router'
  1295. registry_image = 'openshift/origin-docker-registry'
  1296. deployer_image = 'openshift/origin-deployer'
  1297. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1298. if 'is_containerized' not in facts['common']:
  1299. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1300. if 'cli_image' not in facts['common']:
  1301. facts['common']['cli_image'] = cli_image
  1302. if 'pod_image' not in facts['common']:
  1303. facts['common']['pod_image'] = pod_image
  1304. if 'router_image' not in facts['common']:
  1305. facts['common']['router_image'] = router_image
  1306. if 'registry_image' not in facts['common']:
  1307. facts['common']['registry_image'] = registry_image
  1308. if 'deployer_image' not in facts['common']:
  1309. facts['common']['deployer_image'] = deployer_image
  1310. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  1311. facts['etcd']['etcd_image'] = etcd_image
  1312. if 'master' in facts and 'master_image' not in facts['master']:
  1313. facts['master']['master_image'] = master_image
  1314. if 'node' in facts:
  1315. if 'node_image' not in facts['node']:
  1316. facts['node']['node_image'] = node_image
  1317. if 'ovs_image' not in facts['node']:
  1318. facts['node']['ovs_image'] = ovs_image
  1319. if safe_get_bool(facts['common']['is_containerized']):
  1320. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1321. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1322. return facts
  1323. def set_installed_variant_rpm_facts(facts):
  1324. """ Set RPM facts of installed variant
  1325. Args:
  1326. facts (dict): existing facts
  1327. Returns:
  1328. dict: the facts dict updated with installed_variant_rpms
  1329. """
  1330. installed_rpms = []
  1331. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1332. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1333. variant_rpms = [base_rpm] + \
  1334. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1335. ['tuned-profiles-%s-node' % base_rpm]
  1336. for rpm in variant_rpms:
  1337. exit_code, _, _ = module.run_command(['rpm', '-q', rpm])
  1338. if exit_code == 0:
  1339. installed_rpms.append(rpm)
  1340. facts['common']['installed_variant_rpms'] = installed_rpms
  1341. return facts
  1342. class OpenShiftFactsInternalError(Exception):
  1343. """Origin Facts Error"""
  1344. pass
  1345. class OpenShiftFactsUnsupportedRoleError(Exception):
  1346. """Origin Facts Unsupported Role Error"""
  1347. pass
  1348. class OpenShiftFactsFileWriteError(Exception):
  1349. """Origin Facts File Write Error"""
  1350. pass
  1351. class OpenShiftFactsMetadataUnavailableError(Exception):
  1352. """Origin Facts Metadata Unavailable Error"""
  1353. pass
  1354. class OpenShiftFacts(object):
  1355. """ Origin Facts
  1356. Attributes:
  1357. facts (dict): facts for the host
  1358. Args:
  1359. module (AnsibleModule): an AnsibleModule object
  1360. role (str): role for setting local facts
  1361. filename (str): local facts file to use
  1362. local_facts (dict): local facts to set
  1363. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1364. '.' notation ex: ['master.named_certificates']
  1365. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1366. '.' notation ex: ['master.master_count']
  1367. Raises:
  1368. OpenShiftFactsUnsupportedRoleError:
  1369. """
  1370. known_roles = ['builddefaults',
  1371. 'clock',
  1372. 'cloudprovider',
  1373. 'common',
  1374. 'docker',
  1375. 'etcd',
  1376. 'hosted',
  1377. 'loadbalancer',
  1378. 'master',
  1379. 'node']
  1380. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1381. # pylint: disable=too-many-arguments,no-value-for-parameter
  1382. def __init__(self, role, filename, local_facts,
  1383. additive_facts_to_overwrite=None,
  1384. openshift_env=None,
  1385. openshift_env_structures=None,
  1386. protected_facts_to_overwrite=None):
  1387. self.changed = False
  1388. self.filename = filename
  1389. if role not in self.known_roles:
  1390. raise OpenShiftFactsUnsupportedRoleError(
  1391. "Role %s is not supported by this module" % role
  1392. )
  1393. self.role = role
  1394. try:
  1395. # ansible-2.1
  1396. # pylint: disable=too-many-function-args,invalid-name
  1397. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter'])
  1398. for (k, v) in self.system_facts.items():
  1399. self.system_facts["ansible_%s" % k.replace('-', '_')] = v
  1400. except UnboundLocalError:
  1401. # ansible-2.2
  1402. self.system_facts = get_all_facts(module)['ansible_facts']
  1403. self.facts = self.generate_facts(local_facts,
  1404. additive_facts_to_overwrite,
  1405. openshift_env,
  1406. openshift_env_structures,
  1407. protected_facts_to_overwrite)
  1408. def generate_facts(self,
  1409. local_facts,
  1410. additive_facts_to_overwrite,
  1411. openshift_env,
  1412. openshift_env_structures,
  1413. protected_facts_to_overwrite):
  1414. """ Generate facts
  1415. Args:
  1416. local_facts (dict): local_facts for overriding generated defaults
  1417. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1418. '.' notation ex: ['master.named_certificates']
  1419. openshift_env (dict): openshift_env facts for overriding generated defaults
  1420. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1421. '.' notation ex: ['master.master_count']
  1422. Returns:
  1423. dict: The generated facts
  1424. """
  1425. local_facts = self.init_local_facts(local_facts,
  1426. additive_facts_to_overwrite,
  1427. openshift_env,
  1428. openshift_env_structures,
  1429. protected_facts_to_overwrite)
  1430. roles = local_facts.keys()
  1431. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1432. deployment_type = local_facts['common']['deployment_type']
  1433. else:
  1434. deployment_type = 'origin'
  1435. if 'common' in local_facts and 'deployment_subtype' in local_facts['common']:
  1436. deployment_subtype = local_facts['common']['deployment_subtype']
  1437. else:
  1438. deployment_subtype = 'basic'
  1439. defaults = self.get_defaults(roles, deployment_type, deployment_subtype)
  1440. provider_facts = self.init_provider_facts()
  1441. facts = apply_provider_facts(defaults, provider_facts)
  1442. facts = merge_facts(facts,
  1443. local_facts,
  1444. additive_facts_to_overwrite,
  1445. protected_facts_to_overwrite)
  1446. facts = migrate_oauth_template_facts(facts)
  1447. facts['current_config'] = get_current_config(facts)
  1448. facts = set_url_facts_if_unset(facts)
  1449. facts = set_project_cfg_facts_if_unset(facts)
  1450. facts = set_flannel_facts_if_unset(facts)
  1451. facts = set_nuage_facts_if_unset(facts)
  1452. facts = set_node_schedulability(facts)
  1453. facts = set_selectors(facts)
  1454. facts = set_identity_providers_if_unset(facts)
  1455. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1456. facts = set_deployment_facts_if_unset(facts)
  1457. facts = set_container_facts_if_unset(facts)
  1458. facts = build_kubelet_args(facts)
  1459. facts = build_controller_args(facts)
  1460. facts = build_api_server_args(facts)
  1461. facts = set_version_facts_if_unset(facts)
  1462. facts = set_dnsmasq_facts_if_unset(facts)
  1463. facts = set_manageiq_facts_if_unset(facts)
  1464. facts = set_aggregate_facts(facts)
  1465. facts = set_etcd_facts_if_unset(facts)
  1466. facts = set_proxy_facts(facts)
  1467. if not safe_get_bool(facts['common']['is_containerized']):
  1468. facts = set_installed_variant_rpm_facts(facts)
  1469. return dict(openshift=facts)
  1470. def get_defaults(self, roles, deployment_type, deployment_subtype):
  1471. """ Get default fact values
  1472. Args:
  1473. roles (list): list of roles for this host
  1474. Returns:
  1475. dict: The generated default facts
  1476. """
  1477. defaults = {}
  1478. ip_addr = self.system_facts['ansible_default_ipv4']['address']
  1479. exit_code, output, _ = module.run_command(['hostname', '-f'])
  1480. hostname_f = output.strip() if exit_code == 0 else ''
  1481. hostname_values = [hostname_f, self.system_facts['ansible_nodename'],
  1482. self.system_facts['ansible_fqdn']]
  1483. hostname = choose_hostname(hostname_values, ip_addr)
  1484. defaults['common'] = dict(use_openshift_sdn=True, ip=ip_addr,
  1485. public_ip=ip_addr,
  1486. deployment_type=deployment_type,
  1487. deployment_subtype=deployment_subtype,
  1488. hostname=hostname,
  1489. public_hostname=hostname,
  1490. portal_net='172.30.0.0/16',
  1491. client_binary='oc', admin_binary='oadm',
  1492. dns_domain='cluster.local',
  1493. install_examples=True,
  1494. debug_level=2)
  1495. if 'master' in roles:
  1496. scheduler_predicates = [
  1497. {"name": "MatchNodeSelector"},
  1498. {"name": "PodFitsResources"},
  1499. {"name": "PodFitsPorts"},
  1500. {"name": "NoDiskConflict"},
  1501. {"name": "NoVolumeZoneConflict"},
  1502. {"name": "MaxEBSVolumeCount"},
  1503. {"name": "MaxGCEPDVolumeCount"},
  1504. {"name": "Region", "argument": {"serviceAffinity" : {"labels" : ["region"]}}}
  1505. ]
  1506. scheduler_priorities = [
  1507. {"name": "LeastRequestedPriority", "weight": 1},
  1508. {"name": "SelectorSpreadPriority", "weight": 1},
  1509. {"name": "Zone", "weight" : 2, "argument": {"serviceAntiAffinity" : {"label": "zone"}}}
  1510. ]
  1511. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1512. controllers_port='8444',
  1513. console_use_ssl=True,
  1514. console_path='/console',
  1515. console_port='8443', etcd_use_ssl=True,
  1516. etcd_hosts='', etcd_port='4001',
  1517. portal_net='172.30.0.0/16',
  1518. embedded_etcd=True, embedded_kube=True,
  1519. embedded_dns=True,
  1520. bind_addr='0.0.0.0',
  1521. session_max_seconds=3600,
  1522. session_name='ssn',
  1523. session_secrets_file='',
  1524. access_token_max_seconds=86400,
  1525. auth_token_max_seconds=500,
  1526. oauth_grant_method='auto',
  1527. scheduler_predicates=scheduler_predicates,
  1528. scheduler_priorities=scheduler_priorities,
  1529. dynamic_provisioning_enabled=True,
  1530. max_requests_inflight=500)
  1531. if 'node' in roles:
  1532. defaults['node'] = dict(labels={}, annotations={},
  1533. iptables_sync_period='30s',
  1534. local_quota_per_fsgroup="",
  1535. set_node_ip=False)
  1536. if 'docker' in roles:
  1537. docker = dict(disable_push_dockerhub=False,
  1538. hosted_registry_insecure=True,
  1539. options='--log-driver=json-file --log-opt max-size=50m')
  1540. version_info = get_docker_version_info()
  1541. if version_info is not None:
  1542. docker['api_version'] = version_info['api_version']
  1543. docker['version'] = version_info['version']
  1544. docker['gte_1_10'] = LooseVersion(version_info['version']) >= LooseVersion('1.10')
  1545. defaults['docker'] = docker
  1546. if 'clock' in roles:
  1547. exit_code, _, _ = module.run_command(['rpm', '-q', 'chrony'])
  1548. chrony_installed = bool(exit_code == 0)
  1549. defaults['clock'] = dict(
  1550. enabled=True,
  1551. chrony_installed=chrony_installed)
  1552. if 'cloudprovider' in roles:
  1553. defaults['cloudprovider'] = dict(kind=None)
  1554. if 'hosted' in roles or self.role == 'hosted':
  1555. defaults['hosted'] = dict(
  1556. metrics=dict(
  1557. deploy=False,
  1558. duration=7,
  1559. resolution='10s',
  1560. storage=dict(
  1561. kind=None,
  1562. volume=dict(
  1563. name='metrics',
  1564. size='10Gi'
  1565. ),
  1566. nfs=dict(
  1567. directory='/exports',
  1568. options='*(rw,root_squash)'
  1569. ),
  1570. host=None,
  1571. access_modes=['ReadWriteOnce'],
  1572. create_pv=True,
  1573. create_pvc=False
  1574. )
  1575. ),
  1576. logging=dict(
  1577. storage=dict(
  1578. kind=None,
  1579. volume=dict(
  1580. name='logging-es',
  1581. size='10Gi'
  1582. ),
  1583. nfs=dict(
  1584. directory='/exports',
  1585. options='*(rw,root_squash)'
  1586. ),
  1587. host=None,
  1588. access_modes=['ReadWriteOnce'],
  1589. create_pv=True,
  1590. create_pvc=False
  1591. )
  1592. ),
  1593. registry=dict(
  1594. storage=dict(
  1595. kind=None,
  1596. volume=dict(
  1597. name='registry',
  1598. size='5Gi'
  1599. ),
  1600. nfs=dict(
  1601. directory='/exports',
  1602. options='*(rw,root_squash)'),
  1603. host=None,
  1604. access_modes=['ReadWriteMany'],
  1605. create_pv=True,
  1606. create_pvc=True
  1607. )
  1608. ),
  1609. router=dict()
  1610. )
  1611. if 'loadbalancer' in roles:
  1612. loadbalancer = dict(frontend_port='8443',
  1613. default_maxconn='20000',
  1614. global_maxconn='20000',
  1615. limit_nofile='100000')
  1616. defaults['loadbalancer'] = loadbalancer
  1617. return defaults
  1618. def guess_host_provider(self):
  1619. """ Guess the host provider
  1620. Returns:
  1621. dict: The generated default facts for the detected provider
  1622. """
  1623. # TODO: cloud provider facts should probably be submitted upstream
  1624. product_name = self.system_facts['ansible_product_name']
  1625. product_version = self.system_facts['ansible_product_version']
  1626. virt_type = self.system_facts['ansible_virtualization_type']
  1627. virt_role = self.system_facts['ansible_virtualization_role']
  1628. provider = None
  1629. metadata = None
  1630. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1631. # need to create PR for ansible to expose it
  1632. bios_vendor = get_file_content(
  1633. '/sys/devices/virtual/dmi/id/bios_vendor'
  1634. )
  1635. if bios_vendor == 'Google':
  1636. provider = 'gce'
  1637. metadata_url = ('http://metadata.google.internal/'
  1638. 'computeMetadata/v1/?recursive=true')
  1639. headers = {'Metadata-Flavor': 'Google'}
  1640. metadata = get_provider_metadata(metadata_url, True, headers,
  1641. True)
  1642. # Filter sshKeys and serviceAccounts from gce metadata
  1643. if metadata:
  1644. metadata['project']['attributes'].pop('sshKeys', None)
  1645. metadata['instance'].pop('serviceAccounts', None)
  1646. elif (virt_type == 'xen' and virt_role == 'guest'
  1647. and re.match(r'.*\.amazon$', product_version)):
  1648. provider = 'aws'
  1649. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1650. metadata = get_provider_metadata(metadata_url)
  1651. elif re.search(r'OpenStack', product_name):
  1652. provider = 'openstack'
  1653. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1654. 'meta_data.json')
  1655. metadata = get_provider_metadata(metadata_url, True, None,
  1656. True)
  1657. if metadata:
  1658. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1659. metadata['ec2_compat'] = get_provider_metadata(
  1660. ec2_compat_url
  1661. )
  1662. # disable pylint maybe-no-member because overloaded use of
  1663. # the module name causes pylint to not detect that results
  1664. # is an array or hash
  1665. # pylint: disable=maybe-no-member
  1666. # Filter public_keys and random_seed from openstack metadata
  1667. metadata.pop('public_keys', None)
  1668. metadata.pop('random_seed', None)
  1669. if not metadata['ec2_compat']:
  1670. metadata = None
  1671. return dict(name=provider, metadata=metadata)
  1672. def init_provider_facts(self):
  1673. """ Initialize the provider facts
  1674. Returns:
  1675. dict: The normalized provider facts
  1676. """
  1677. provider_info = self.guess_host_provider()
  1678. provider_facts = normalize_provider_facts(
  1679. provider_info.get('name'),
  1680. provider_info.get('metadata')
  1681. )
  1682. return provider_facts
  1683. @staticmethod
  1684. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1685. """ Split openshift_env facts based on openshift_env structures.
  1686. Args:
  1687. openshift_env_fact (string): the openshift_env fact to split
  1688. ex: 'openshift_cloudprovider_openstack_auth_url'
  1689. openshift_env_structures (list): a list of structures to determine fact keys
  1690. ex: ['openshift.cloudprovider.openstack.*']
  1691. Returns:
  1692. list: a list of keys that represent the fact
  1693. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1694. """
  1695. # By default, we'll split an openshift_env fact by underscores.
  1696. fact_keys = openshift_env_fact.split('_')
  1697. # Determine if any of the provided variable structures match the fact.
  1698. matching_structure = None
  1699. if openshift_env_structures != None:
  1700. for structure in openshift_env_structures:
  1701. if re.match(structure, openshift_env_fact):
  1702. matching_structure = structure
  1703. # Fact didn't match any variable structures so return the default fact keys.
  1704. if matching_structure is None:
  1705. return fact_keys
  1706. final_keys = []
  1707. structure_keys = matching_structure.split('.')
  1708. for structure_key in structure_keys:
  1709. # Matched current key. Add to final keys.
  1710. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1711. final_keys.append(structure_key)
  1712. # Wildcard means we will be taking everything from here to the end of the fact.
  1713. elif structure_key == '*':
  1714. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1715. # Shouldn't have gotten here, return the fact keys.
  1716. else:
  1717. return fact_keys
  1718. return final_keys
  1719. # Disabling too-many-branches and too-many-locals.
  1720. # This should be cleaned up as a TODO item.
  1721. #pylint: disable=too-many-branches, too-many-locals
  1722. def init_local_facts(self, facts=None,
  1723. additive_facts_to_overwrite=None,
  1724. openshift_env=None,
  1725. openshift_env_structures=None,
  1726. protected_facts_to_overwrite=None):
  1727. """ Initialize the local facts
  1728. Args:
  1729. facts (dict): local facts to set
  1730. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1731. '.' notation ex: ['master.named_certificates']
  1732. openshift_env (dict): openshift env facts to set
  1733. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1734. '.' notation ex: ['master.master_count']
  1735. Returns:
  1736. dict: The result of merging the provided facts with existing
  1737. local facts
  1738. """
  1739. changed = False
  1740. facts_to_set = dict()
  1741. if facts is not None:
  1742. facts_to_set[self.role] = facts
  1743. if openshift_env != {} and openshift_env != None:
  1744. for fact, value in openshift_env.iteritems():
  1745. oo_env_facts = dict()
  1746. current_level = oo_env_facts
  1747. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1748. if len(keys) > 0 and keys[0] != self.role:
  1749. continue
  1750. for key in keys:
  1751. if key == keys[-1]:
  1752. current_level[key] = value
  1753. elif key not in current_level:
  1754. current_level[key] = dict()
  1755. current_level = current_level[key]
  1756. facts_to_set = merge_facts(orig=facts_to_set,
  1757. new=oo_env_facts,
  1758. additive_facts_to_overwrite=[],
  1759. protected_facts_to_overwrite=[])
  1760. local_facts = get_local_facts_from_file(self.filename)
  1761. migrated_facts = migrate_local_facts(local_facts)
  1762. new_local_facts = merge_facts(migrated_facts,
  1763. facts_to_set,
  1764. additive_facts_to_overwrite,
  1765. protected_facts_to_overwrite)
  1766. if 'docker' in new_local_facts:
  1767. # remove duplicate and empty strings from registry lists
  1768. for cat in ['additional', 'blocked', 'insecure']:
  1769. key = '{0}_registries'.format(cat)
  1770. if key in new_local_facts['docker']:
  1771. val = new_local_facts['docker'][key]
  1772. if isinstance(val, basestring):
  1773. val = [x.strip() for x in val.split(',')]
  1774. new_local_facts['docker'][key] = list(set(val) - set(['']))
  1775. # Convert legacy log_options comma sep string to a list if present:
  1776. if 'log_options' in new_local_facts['docker'] and \
  1777. isinstance(new_local_facts['docker']['log_options'], basestring):
  1778. new_local_facts['docker']['log_options'] = new_local_facts['docker']['log_options'].split(',')
  1779. new_local_facts = self.remove_empty_facts(new_local_facts)
  1780. if new_local_facts != local_facts:
  1781. self.validate_local_facts(new_local_facts)
  1782. changed = True
  1783. if not module.check_mode:
  1784. save_local_facts(self.filename, new_local_facts)
  1785. self.changed = changed
  1786. return new_local_facts
  1787. def remove_empty_facts(self, facts=None):
  1788. """ Remove empty facts
  1789. Args:
  1790. facts (dict): facts to clean
  1791. """
  1792. facts_to_remove = []
  1793. for fact, value in facts.iteritems():
  1794. if isinstance(facts[fact], dict):
  1795. facts[fact] = self.remove_empty_facts(facts[fact])
  1796. else:
  1797. if value == "" or value == [""] or value is None:
  1798. facts_to_remove.append(fact)
  1799. for fact in facts_to_remove:
  1800. del facts[fact]
  1801. return facts
  1802. def validate_local_facts(self, facts=None):
  1803. """ Validate local facts
  1804. Args:
  1805. facts (dict): local facts to validate
  1806. """
  1807. invalid_facts = dict()
  1808. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1809. if invalid_facts:
  1810. msg = 'Invalid facts detected:\n'
  1811. for key in invalid_facts.keys():
  1812. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1813. module.fail_json(msg=msg,
  1814. changed=self.changed)
  1815. # disabling pylint errors for line-too-long since we're dealing
  1816. # with best effort reduction of error messages here.
  1817. # disabling errors for too-many-branches since we require checking
  1818. # many conditions.
  1819. # pylint: disable=line-too-long, too-many-branches
  1820. @staticmethod
  1821. def validate_master_facts(facts, invalid_facts):
  1822. """ Validate master facts
  1823. Args:
  1824. facts (dict): local facts to validate
  1825. invalid_facts (dict): collected invalid_facts
  1826. Returns:
  1827. dict: Invalid facts
  1828. """
  1829. if 'master' in facts:
  1830. # openshift.master.session_auth_secrets
  1831. if 'session_auth_secrets' in facts['master']:
  1832. session_auth_secrets = facts['master']['session_auth_secrets']
  1833. if not issubclass(type(session_auth_secrets), list):
  1834. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1835. elif 'session_encryption_secrets' not in facts['master']:
  1836. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1837. 'if openshift_master_session_auth_secrets is provided.')
  1838. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1839. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1840. 'openshift_master_session_encryption_secrets must be '
  1841. 'equal length.')
  1842. else:
  1843. for secret in session_auth_secrets:
  1844. if len(secret) < 32:
  1845. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1846. 'Secrets must be at least 32 characters in length.')
  1847. # openshift.master.session_encryption_secrets
  1848. if 'session_encryption_secrets' in facts['master']:
  1849. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1850. if not issubclass(type(session_encryption_secrets), list):
  1851. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1852. elif 'session_auth_secrets' not in facts['master']:
  1853. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1854. 'set if openshift_master_session_encryption_secrets '
  1855. 'is provided.')
  1856. else:
  1857. for secret in session_encryption_secrets:
  1858. if len(secret) not in [16, 24, 32]:
  1859. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1860. 'Secrets must be 16, 24, or 32 characters in length.')
  1861. return invalid_facts
  1862. def main():
  1863. """ main """
  1864. # disabling pylint errors for global-variable-undefined and invalid-name
  1865. # for 'global module' usage, since it is required to use ansible_facts
  1866. # pylint: disable=global-variable-undefined, invalid-name
  1867. global module
  1868. module = AnsibleModule(
  1869. argument_spec=dict(
  1870. role=dict(default='common', required=False,
  1871. choices=OpenShiftFacts.known_roles),
  1872. local_facts=dict(default=None, type='dict', required=False),
  1873. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1874. openshift_env=dict(default={}, type='dict', required=False),
  1875. openshift_env_structures=dict(default=[], type='list', required=False),
  1876. protected_facts_to_overwrite=dict(default=[], type='list', required=False)
  1877. ),
  1878. supports_check_mode=True,
  1879. add_file_common_args=True,
  1880. )
  1881. module.params['gather_subset'] = ['hardware', 'network', 'virtual', 'facter']
  1882. module.params['gather_timeout'] = 10
  1883. module.params['filter'] = '*'
  1884. role = module.params['role']
  1885. local_facts = module.params['local_facts']
  1886. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1887. openshift_env = module.params['openshift_env']
  1888. openshift_env_structures = module.params['openshift_env_structures']
  1889. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite']
  1890. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1891. openshift_facts = OpenShiftFacts(role,
  1892. fact_file,
  1893. local_facts,
  1894. additive_facts_to_overwrite,
  1895. openshift_env,
  1896. openshift_env_structures,
  1897. protected_facts_to_overwrite)
  1898. file_params = module.params.copy()
  1899. file_params['path'] = fact_file
  1900. file_args = module.load_file_common_arguments(file_params)
  1901. changed = module.set_fs_attributes_if_different(file_args,
  1902. openshift_facts.changed)
  1903. return module.exit_json(changed=changed,
  1904. ansible_facts=openshift_facts.facts)
  1905. # ignore pylint errors related to the module_utils import
  1906. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1907. # import module snippets
  1908. from ansible.module_utils.basic import *
  1909. from ansible.module_utils.facts import *
  1910. from ansible.module_utils.urls import *
  1911. if __name__ == '__main__':
  1912. main()