openshift_facts.py 92 KB

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