openshift_facts.py 99 KB

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