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