openshift_facts.py 87 KB

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