openshift_facts.py 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456
  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. # pylint: disable=too-many-statements
  728. def set_version_facts_if_unset(facts):
  729. """ Set version facts. This currently includes common.version and
  730. common.version_gte_3_1_or_1_1.
  731. Args:
  732. facts (dict): existing facts
  733. Returns:
  734. dict: the facts dict updated with version facts.
  735. """
  736. if 'common' in facts:
  737. deployment_type = facts['common']['deployment_type']
  738. openshift_version = get_openshift_version(facts)
  739. if openshift_version:
  740. version = LooseVersion(openshift_version)
  741. facts['common']['version'] = openshift_version
  742. facts['common']['short_version'] = '.'.join([str(x) for x in version.version[0:2]])
  743. if deployment_type == 'origin':
  744. version_gte_3_1_or_1_1 = version >= LooseVersion('1.1.0')
  745. version_gte_3_1_1_or_1_1_1 = version >= LooseVersion('1.1.1')
  746. version_gte_3_2_or_1_2 = version >= LooseVersion('1.2.0')
  747. version_gte_3_3_or_1_3 = version >= LooseVersion('1.3.0')
  748. version_gte_3_4_or_1_4 = version >= LooseVersion('1.4.0')
  749. version_gte_3_5_or_1_5 = version >= LooseVersion('1.5.0')
  750. version_gte_3_6_or_1_6 = version >= LooseVersion('1.6.0')
  751. else:
  752. version_gte_3_1_or_1_1 = version >= LooseVersion('3.0.2.905')
  753. version_gte_3_1_1_or_1_1_1 = version >= LooseVersion('3.1.1')
  754. version_gte_3_2_or_1_2 = version >= LooseVersion('3.1.1.901')
  755. version_gte_3_3_or_1_3 = version >= LooseVersion('3.3.0')
  756. version_gte_3_4_or_1_4 = version >= LooseVersion('3.4.0')
  757. version_gte_3_5_or_1_5 = version >= LooseVersion('3.5.0')
  758. version_gte_3_6_or_1_6 = version >= LooseVersion('3.6.0')
  759. else:
  760. version_gte_3_1_or_1_1 = True
  761. version_gte_3_1_1_or_1_1_1 = True
  762. version_gte_3_2_or_1_2 = True
  763. version_gte_3_3_or_1_3 = True
  764. version_gte_3_4_or_1_4 = True
  765. version_gte_3_5_or_1_5 = True
  766. version_gte_3_6_or_1_6 = False
  767. facts['common']['version_gte_3_1_or_1_1'] = version_gte_3_1_or_1_1
  768. facts['common']['version_gte_3_1_1_or_1_1_1'] = version_gte_3_1_1_or_1_1_1
  769. facts['common']['version_gte_3_2_or_1_2'] = version_gte_3_2_or_1_2
  770. facts['common']['version_gte_3_3_or_1_3'] = version_gte_3_3_or_1_3
  771. facts['common']['version_gte_3_4_or_1_4'] = version_gte_3_4_or_1_4
  772. facts['common']['version_gte_3_5_or_1_5'] = version_gte_3_5_or_1_5
  773. facts['common']['version_gte_3_6_or_1_6'] = version_gte_3_6_or_1_6
  774. if version_gte_3_5_or_1_5:
  775. examples_content_version = 'v1.5'
  776. elif version_gte_3_4_or_1_4:
  777. examples_content_version = 'v1.4'
  778. elif version_gte_3_3_or_1_3:
  779. examples_content_version = 'v1.3'
  780. elif version_gte_3_2_or_1_2:
  781. examples_content_version = 'v1.2'
  782. elif version_gte_3_1_or_1_1:
  783. examples_content_version = 'v1.1'
  784. else:
  785. examples_content_version = 'v1.0'
  786. facts['common']['examples_content_version'] = examples_content_version
  787. return facts
  788. def set_manageiq_facts_if_unset(facts):
  789. """ Set manageiq facts. This currently includes common.use_manageiq.
  790. Args:
  791. facts (dict): existing facts
  792. Returns:
  793. dict: the facts dict updated with version facts.
  794. Raises:
  795. OpenShiftFactsInternalError:
  796. """
  797. if 'common' not in facts:
  798. if 'version_gte_3_1_or_1_1' not in facts['common']:
  799. raise OpenShiftFactsInternalError(
  800. "Invalid invocation: The required facts are not set"
  801. )
  802. if 'use_manageiq' not in facts['common']:
  803. facts['common']['use_manageiq'] = facts['common']['version_gte_3_1_or_1_1']
  804. return facts
  805. def set_sdn_facts_if_unset(facts, system_facts):
  806. """ Set sdn facts if not already present in facts dict
  807. Args:
  808. facts (dict): existing facts
  809. system_facts (dict): ansible_facts
  810. Returns:
  811. dict: the facts dict updated with the generated sdn facts if they
  812. were not already present
  813. """
  814. # pylint: disable=too-many-branches
  815. if 'common' in facts:
  816. use_sdn = facts['common']['use_openshift_sdn']
  817. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  818. use_sdn = safe_get_bool(use_sdn)
  819. facts['common']['use_openshift_sdn'] = use_sdn
  820. if 'sdn_network_plugin_name' not in facts['common']:
  821. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  822. facts['common']['sdn_network_plugin_name'] = plugin
  823. if 'master' in facts:
  824. # set defaults for sdn_cluster_network_cidr and sdn_host_subnet_length
  825. # these might be overridden if they exist in the master config file
  826. sdn_cluster_network_cidr = '10.128.0.0/14'
  827. sdn_host_subnet_length = '9'
  828. master_cfg_path = os.path.join(facts['common']['config_base'],
  829. 'master/master-config.yaml')
  830. if os.path.isfile(master_cfg_path):
  831. with open(master_cfg_path, 'r') as master_cfg_f:
  832. config = yaml.safe_load(master_cfg_f.read())
  833. if 'networkConfig' in config:
  834. if 'clusterNetworkCIDR' in config['networkConfig']:
  835. sdn_cluster_network_cidr = \
  836. config['networkConfig']['clusterNetworkCIDR']
  837. if 'hostSubnetLength' in config['networkConfig']:
  838. sdn_host_subnet_length = \
  839. config['networkConfig']['hostSubnetLength']
  840. if 'sdn_cluster_network_cidr' not in facts['master']:
  841. facts['master']['sdn_cluster_network_cidr'] = sdn_cluster_network_cidr
  842. if 'sdn_host_subnet_length' not in facts['master']:
  843. facts['master']['sdn_host_subnet_length'] = sdn_host_subnet_length
  844. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  845. node_ip = facts['common']['ip']
  846. # default MTU if interface MTU cannot be detected
  847. facts['node']['sdn_mtu'] = '1450'
  848. for val in itervalues(system_facts):
  849. if isinstance(val, dict) and 'mtu' in val:
  850. mtu = val['mtu']
  851. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  852. facts['node']['sdn_mtu'] = str(mtu - 50)
  853. return facts
  854. def set_nodename(facts):
  855. """ set nodename """
  856. if 'node' in facts and 'common' in facts:
  857. if 'cloudprovider' in facts and facts['cloudprovider']['kind'] == 'openstack':
  858. facts['node']['nodename'] = facts['provider']['metadata']['hostname'].replace('.novalocal', '')
  859. elif 'cloudprovider' in facts and facts['cloudprovider']['kind'] == 'gce':
  860. facts['node']['nodename'] = '.'.split(facts['provider']['metadata']['hostname'])[0]
  861. else:
  862. facts['node']['nodename'] = facts['common']['hostname'].lower()
  863. return facts
  864. def migrate_oauth_template_facts(facts):
  865. """
  866. Migrate an old oauth template fact to a newer format if it's present.
  867. The legacy 'oauth_template' fact was just a filename, and assumed you were
  868. setting the 'login' template.
  869. The new pluralized 'oauth_templates' fact is a dict mapping the template
  870. name to a filename.
  871. Simplify the code after this by merging the old fact into the new.
  872. """
  873. if 'master' in facts and 'oauth_template' in facts['master']:
  874. if 'oauth_templates' not in facts['master']:
  875. facts['master']['oauth_templates'] = {"login": facts['master']['oauth_template']}
  876. elif 'login' not in facts['master']['oauth_templates']:
  877. facts['master']['oauth_templates']['login'] = facts['master']['oauth_template']
  878. return facts
  879. def format_url(use_ssl, hostname, port, path=''):
  880. """ Format url based on ssl flag, hostname, port and path
  881. Args:
  882. use_ssl (bool): is ssl enabled
  883. hostname (str): hostname
  884. port (str): port
  885. path (str): url path
  886. Returns:
  887. str: The generated url string
  888. """
  889. scheme = 'https' if use_ssl else 'http'
  890. netloc = hostname
  891. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  892. netloc += ":%s" % port
  893. try:
  894. url = urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  895. except AttributeError:
  896. # pylint: disable=undefined-variable
  897. url = urlunparse((scheme, netloc, path, '', '', ''))
  898. return url
  899. def get_current_config(facts):
  900. """ Get current openshift config
  901. Args:
  902. facts (dict): existing facts
  903. Returns:
  904. dict: the facts dict updated with the current openshift config
  905. """
  906. current_config = dict()
  907. roles = [role for role in facts if role not in ['common', 'provider']]
  908. for role in roles:
  909. if 'roles' in current_config:
  910. current_config['roles'].append(role)
  911. else:
  912. current_config['roles'] = [role]
  913. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  914. # determine the location of files.
  915. # TODO: I suspect this isn't working right now, but it doesn't prevent
  916. # anything from working properly as far as I can tell, perhaps because
  917. # we override the kubeconfig path everywhere we use it?
  918. # Query kubeconfig settings
  919. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  920. if role == 'node':
  921. kubeconfig_dir = os.path.join(
  922. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  923. )
  924. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  925. if os.path.isfile('/usr/bin/openshift') and os.path.isfile(kubeconfig_path):
  926. try:
  927. _, output, _ = module.run_command( # noqa: F405
  928. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  929. "json", "--kubeconfig=%s" % kubeconfig_path],
  930. check_rc=False
  931. )
  932. config = json.loads(output)
  933. cad = 'certificate-authority-data'
  934. try:
  935. for cluster in config['clusters']:
  936. config['clusters'][cluster][cad] = 'masked'
  937. except KeyError:
  938. pass
  939. try:
  940. for user in config['users']:
  941. config['users'][user][cad] = 'masked'
  942. config['users'][user]['client-key-data'] = 'masked'
  943. except KeyError:
  944. pass
  945. current_config['kubeconfig'] = config
  946. # override pylint broad-except warning, since we do not want
  947. # to bubble up any exceptions if oc config view
  948. # fails
  949. # pylint: disable=broad-except
  950. except Exception:
  951. pass
  952. return current_config
  953. def build_kubelet_args(facts):
  954. """Build node kubelet_args
  955. In the node-config.yaml file, kubeletArgument sub-keys have their
  956. values provided as a list. Hence the gratuitous use of ['foo'] below.
  957. """
  958. cloud_cfg_path = os.path.join(
  959. facts['common']['config_base'],
  960. 'cloudprovider')
  961. # We only have to do this stuff on hosts that are nodes
  962. if 'node' in facts:
  963. # Any changes to the kubeletArguments parameter are stored
  964. # here first.
  965. kubelet_args = {}
  966. if 'cloudprovider' in facts:
  967. # EVERY cloud is special <3
  968. if 'kind' in facts['cloudprovider']:
  969. if facts['cloudprovider']['kind'] == 'aws':
  970. kubelet_args['cloud-provider'] = ['aws']
  971. kubelet_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  972. if facts['cloudprovider']['kind'] == 'openstack':
  973. kubelet_args['cloud-provider'] = ['openstack']
  974. kubelet_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  975. if facts['cloudprovider']['kind'] == 'gce':
  976. kubelet_args['cloud-provider'] = ['gce']
  977. kubelet_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  978. # Automatically add node-labels to the kubeletArguments
  979. # parameter. See BZ1359848 for additional details.
  980. #
  981. # Ref: https://bugzilla.redhat.com/show_bug.cgi?id=1359848
  982. if 'labels' in facts['node'] and isinstance(facts['node']['labels'], dict):
  983. # tl;dr: os_node_labels="{'foo': 'bar', 'a': 'b'}" turns
  984. # into ['foo=bar', 'a=b']
  985. #
  986. # On the openshift_node_labels inventory variable we loop
  987. # over each key-value tuple (from .items()) and join the
  988. # key to the value with an '=' character, this produces a
  989. # list.
  990. #
  991. # map() seems to be returning an itertools.imap object
  992. # instead of a list. We cast it to a list ourselves.
  993. # pylint: disable=unnecessary-lambda
  994. labels_str = list(map(lambda x: '='.join(x), facts['node']['labels'].items()))
  995. if labels_str != '':
  996. kubelet_args['node-labels'] = labels_str
  997. # If we've added items to the kubelet_args dict then we need
  998. # to merge the new items back into the main facts object.
  999. if kubelet_args != {}:
  1000. facts = merge_facts({'node': {'kubelet_args': kubelet_args}}, facts, [], [])
  1001. return facts
  1002. def build_controller_args(facts):
  1003. """ Build master controller_args """
  1004. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  1005. 'cloudprovider')
  1006. if 'master' in facts:
  1007. controller_args = {}
  1008. if 'cloudprovider' in facts:
  1009. if 'kind' in facts['cloudprovider']:
  1010. if facts['cloudprovider']['kind'] == 'aws':
  1011. controller_args['cloud-provider'] = ['aws']
  1012. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  1013. if facts['cloudprovider']['kind'] == 'openstack':
  1014. controller_args['cloud-provider'] = ['openstack']
  1015. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  1016. if facts['cloudprovider']['kind'] == 'gce':
  1017. controller_args['cloud-provider'] = ['gce']
  1018. controller_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  1019. if controller_args != {}:
  1020. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [], [])
  1021. return facts
  1022. def build_api_server_args(facts):
  1023. """ Build master api_server_args """
  1024. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  1025. 'cloudprovider')
  1026. if 'master' in facts:
  1027. api_server_args = {}
  1028. if 'cloudprovider' in facts:
  1029. if 'kind' in facts['cloudprovider']:
  1030. if facts['cloudprovider']['kind'] == 'aws':
  1031. api_server_args['cloud-provider'] = ['aws']
  1032. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  1033. if facts['cloudprovider']['kind'] == 'openstack':
  1034. api_server_args['cloud-provider'] = ['openstack']
  1035. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  1036. if facts['cloudprovider']['kind'] == 'gce':
  1037. api_server_args['cloud-provider'] = ['gce']
  1038. api_server_args['cloud-config'] = [cloud_cfg_path + '/gce.conf']
  1039. if api_server_args != {}:
  1040. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [], [])
  1041. return facts
  1042. def is_service_running(service):
  1043. """ Queries systemd through dbus to see if the service is running """
  1044. service_running = False
  1045. try:
  1046. bus = SystemBus()
  1047. systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
  1048. manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
  1049. service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
  1050. service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
  1051. service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
  1052. service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
  1053. service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
  1054. if service_load_state == 'loaded' and service_active_state == 'active':
  1055. service_running = True
  1056. except DBusException:
  1057. # TODO: do not swallow exception, as it may be hiding useful debugging
  1058. # information.
  1059. pass
  1060. return service_running
  1061. def rpm_rebuilddb():
  1062. """
  1063. Runs rpm --rebuilddb to ensure the db is in good shape.
  1064. """
  1065. module.run_command(['/usr/bin/rpm', '--rebuilddb']) # noqa: F405
  1066. def get_version_output(binary, version_cmd):
  1067. """ runs and returns the version output for a command """
  1068. cmd = []
  1069. for item in (binary, version_cmd):
  1070. if isinstance(item, list):
  1071. cmd.extend(item)
  1072. else:
  1073. cmd.append(item)
  1074. if os.path.isfile(cmd[0]):
  1075. _, output, _ = module.run_command(cmd) # noqa: F405
  1076. return output
  1077. def get_docker_version_info():
  1078. """ Parses and returns the docker version info """
  1079. result = None
  1080. if is_service_running('docker'):
  1081. version_info = yaml.safe_load(get_version_output('/usr/bin/docker', 'version'))
  1082. if 'Server' in version_info:
  1083. result = {
  1084. 'api_version': version_info['Server']['API version'],
  1085. 'version': version_info['Server']['Version']
  1086. }
  1087. return result
  1088. def get_hosted_registry_insecure():
  1089. """ Parses OPTIONS from /etc/sysconfig/docker to determine if the
  1090. registry is currently insecure.
  1091. """
  1092. hosted_registry_insecure = None
  1093. if os.path.exists('/etc/sysconfig/docker'):
  1094. try:
  1095. ini_str = text_type('[root]\n' + open('/etc/sysconfig/docker', 'r').read(), 'utf-8')
  1096. ini_fp = io.StringIO(ini_str)
  1097. config = configparser.RawConfigParser()
  1098. config.readfp(ini_fp)
  1099. options = config.get('root', 'OPTIONS')
  1100. if 'insecure-registry' in options:
  1101. hosted_registry_insecure = True
  1102. except Exception: # pylint: disable=broad-except
  1103. pass
  1104. return hosted_registry_insecure
  1105. def get_openshift_version(facts):
  1106. """ Get current version of openshift on the host.
  1107. Checks a variety of ways ranging from fastest to slowest.
  1108. Args:
  1109. facts (dict): existing facts
  1110. optional cli_image for pulling the version number
  1111. Returns:
  1112. version: the current openshift version
  1113. """
  1114. version = None
  1115. # No need to run this method repeatedly on a system if we already know the
  1116. # version
  1117. # TODO: We need a way to force reload this after upgrading bits.
  1118. if 'common' in facts:
  1119. if 'version' in facts['common'] and facts['common']['version'] is not None:
  1120. return chomp_commit_offset(facts['common']['version'])
  1121. if os.path.isfile('/usr/bin/openshift'):
  1122. _, output, _ = module.run_command(['/usr/bin/openshift', 'version']) # noqa: F405
  1123. version = parse_openshift_version(output)
  1124. elif 'common' in facts and 'is_containerized' in facts['common']:
  1125. version = get_container_openshift_version(facts)
  1126. # Handle containerized masters that have not yet been configured as a node.
  1127. # This can be very slow and may get re-run multiple times, so we only use this
  1128. # if other methods failed to find a version.
  1129. if not version and os.path.isfile('/usr/local/bin/openshift'):
  1130. _, output, _ = module.run_command(['/usr/local/bin/openshift', 'version']) # noqa: F405
  1131. version = parse_openshift_version(output)
  1132. return chomp_commit_offset(version)
  1133. def chomp_commit_offset(version):
  1134. """Chomp any "+git.foo" commit offset string from the given `version`
  1135. and return the modified version string.
  1136. Ex:
  1137. - chomp_commit_offset(None) => None
  1138. - chomp_commit_offset(1337) => "1337"
  1139. - chomp_commit_offset("v3.4.0.15+git.derp") => "v3.4.0.15"
  1140. - chomp_commit_offset("v3.4.0.15") => "v3.4.0.15"
  1141. - chomp_commit_offset("v1.3.0+52492b4") => "v1.3.0"
  1142. """
  1143. if version is None:
  1144. return version
  1145. else:
  1146. # Stringify, just in case it's a Number type. Split by '+' and
  1147. # return the first split. No concerns about strings without a
  1148. # '+', .split() returns an array of the original string.
  1149. return str(version).split('+')[0]
  1150. def get_container_openshift_version(facts):
  1151. """
  1152. If containerized, see if we can determine the installed version via the
  1153. systemd environment files.
  1154. """
  1155. for filename in ['/etc/sysconfig/%s-master', '/etc/sysconfig/%s-node']:
  1156. env_path = filename % facts['common']['service_type']
  1157. if not os.path.exists(env_path):
  1158. continue
  1159. with open(env_path) as env_file:
  1160. for line in env_file:
  1161. if line.startswith("IMAGE_VERSION="):
  1162. tag = line[len("IMAGE_VERSION="):].strip()
  1163. # Remove leading "v" and any trailing release info, we just want
  1164. # a version number here:
  1165. version = tag[1:].split("-")[0]
  1166. return version
  1167. return None
  1168. def parse_openshift_version(output):
  1169. """ Apply provider facts to supplied facts dict
  1170. Args:
  1171. string: output of 'openshift version'
  1172. Returns:
  1173. string: the version number
  1174. """
  1175. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  1176. ver = versions.get('openshift', '')
  1177. # Remove trailing build number and commit hash from older versions, we need to return a straight
  1178. # w.x.y.z version here for use as openshift_version throughout the playbooks/roles. (i.e. 3.1.1.6-64-g80b61da)
  1179. ver = ver.split('-')[0]
  1180. return ver
  1181. def apply_provider_facts(facts, provider_facts):
  1182. """ Apply provider facts to supplied facts dict
  1183. Args:
  1184. facts (dict): facts dict to update
  1185. provider_facts (dict): provider facts to apply
  1186. roles: host roles
  1187. Returns:
  1188. dict: the merged facts
  1189. """
  1190. if not provider_facts:
  1191. return facts
  1192. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  1193. for h_var, ip_var in common_vars:
  1194. ip_value = provider_facts['network'].get(ip_var)
  1195. if ip_value:
  1196. facts['common'][ip_var] = ip_value
  1197. facts['common'][h_var] = choose_hostname(
  1198. [provider_facts['network'].get(h_var)],
  1199. facts['common'][h_var]
  1200. )
  1201. facts['provider'] = provider_facts
  1202. return facts
  1203. # Disabling pylint too many branches. This function needs refactored
  1204. # but is a very core part of openshift_facts.
  1205. # pylint: disable=too-many-branches, too-many-nested-blocks
  1206. def merge_facts(orig, new, additive_facts_to_overwrite, protected_facts_to_overwrite):
  1207. """ Recursively merge facts dicts
  1208. Args:
  1209. orig (dict): existing facts
  1210. new (dict): facts to update
  1211. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1212. '.' notation ex: ['master.named_certificates']
  1213. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1214. '.' notation ex: ['master.master_count']
  1215. Returns:
  1216. dict: the merged facts
  1217. """
  1218. additive_facts = ['named_certificates']
  1219. protected_facts = ['ha']
  1220. # Facts we do not ever want to merge. These originate in inventory variables
  1221. # and contain JSON dicts. We don't ever want to trigger a merge
  1222. # here, just completely overwrite with the new if they are present there.
  1223. inventory_json_facts = ['admission_plugin_config',
  1224. 'kube_admission_plugin_config',
  1225. 'image_policy_config',
  1226. "builddefaults",
  1227. "buildoverrides"]
  1228. facts = dict()
  1229. for key, value in iteritems(orig):
  1230. # Key exists in both old and new facts.
  1231. if key in new:
  1232. if key in inventory_json_facts:
  1233. # Watchout for JSON facts that sometimes load as strings.
  1234. # (can happen if the JSON contains a boolean)
  1235. if isinstance(new[key], string_types):
  1236. facts[key] = yaml.safe_load(new[key])
  1237. else:
  1238. facts[key] = copy.deepcopy(new[key])
  1239. # Continue to recurse if old and new fact is a dictionary.
  1240. elif isinstance(value, dict) and isinstance(new[key], dict):
  1241. # Collect the subset of additive facts to overwrite if
  1242. # key matches. These will be passed to the subsequent
  1243. # merge_facts call.
  1244. relevant_additive_facts = []
  1245. for item in additive_facts_to_overwrite:
  1246. if '.' in item and item.startswith(key + '.'):
  1247. relevant_additive_facts.append(item)
  1248. # Collect the subset of protected facts to overwrite
  1249. # if key matches. These will be passed to the
  1250. # subsequent merge_facts call.
  1251. relevant_protected_facts = []
  1252. for item in protected_facts_to_overwrite:
  1253. if '.' in item and item.startswith(key + '.'):
  1254. relevant_protected_facts.append(item)
  1255. facts[key] = merge_facts(value, new[key], relevant_additive_facts, relevant_protected_facts)
  1256. # Key matches an additive fact and we are not overwriting
  1257. # it so we will append the new value to the existing value.
  1258. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  1259. if isinstance(value, list) and isinstance(new[key], list):
  1260. new_fact = []
  1261. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  1262. if item not in new_fact:
  1263. new_fact.append(item)
  1264. facts[key] = new_fact
  1265. # Key matches a protected fact and we are not overwriting
  1266. # it so we will determine if it is okay to change this
  1267. # fact.
  1268. elif key in protected_facts and key not in [x.split('.')[-1] for x in protected_facts_to_overwrite]:
  1269. # ha (bool) can not change unless it has been passed
  1270. # as a protected fact to overwrite.
  1271. if key == 'ha':
  1272. if safe_get_bool(value) != safe_get_bool(new[key]):
  1273. # pylint: disable=line-too-long
  1274. module.fail_json(msg='openshift_facts received a different value for openshift.master.ha') # noqa: F405
  1275. else:
  1276. facts[key] = value
  1277. # No other condition has been met. Overwrite the old fact
  1278. # with the new value.
  1279. else:
  1280. facts[key] = copy.deepcopy(new[key])
  1281. # Key isn't in new so add it to facts to keep it.
  1282. else:
  1283. facts[key] = copy.deepcopy(value)
  1284. new_keys = set(new.keys()) - set(orig.keys())
  1285. for key in new_keys:
  1286. # Watchout for JSON facts that sometimes load as strings.
  1287. # (can happen if the JSON contains a boolean)
  1288. if key in inventory_json_facts and isinstance(new[key], string_types):
  1289. facts[key] = yaml.safe_load(new[key])
  1290. else:
  1291. facts[key] = copy.deepcopy(new[key])
  1292. return facts
  1293. def save_local_facts(filename, facts):
  1294. """ Save local facts
  1295. Args:
  1296. filename (str): local facts file
  1297. facts (dict): facts to set
  1298. """
  1299. try:
  1300. fact_dir = os.path.dirname(filename)
  1301. try:
  1302. os.makedirs(fact_dir) # try to make the directory
  1303. except OSError as exception:
  1304. if exception.errno != errno.EEXIST: # but it is okay if it is already there
  1305. raise # pass any other exceptions up the chain
  1306. with open(filename, 'w') as fact_file:
  1307. fact_file.write(module.jsonify(facts)) # noqa: F405
  1308. os.chmod(filename, 0o600)
  1309. except (IOError, OSError) as ex:
  1310. raise OpenShiftFactsFileWriteError(
  1311. "Could not create fact file: %s, error: %s" % (filename, ex)
  1312. )
  1313. def get_local_facts_from_file(filename):
  1314. """ Retrieve local facts from fact file
  1315. Args:
  1316. filename (str): local facts file
  1317. Returns:
  1318. dict: the retrieved facts
  1319. """
  1320. local_facts = dict()
  1321. try:
  1322. # Handle conversion of INI style facts file to json style
  1323. ini_facts = configparser.SafeConfigParser()
  1324. ini_facts.read(filename)
  1325. for section in ini_facts.sections():
  1326. local_facts[section] = dict()
  1327. for key, value in ini_facts.items(section):
  1328. local_facts[section][key] = value
  1329. except (configparser.MissingSectionHeaderError,
  1330. configparser.ParsingError):
  1331. try:
  1332. with open(filename, 'r') as facts_file:
  1333. local_facts = json.load(facts_file)
  1334. except (ValueError, IOError):
  1335. pass
  1336. return local_facts
  1337. def sort_unique(alist):
  1338. """ Sorts and de-dupes a list
  1339. Args:
  1340. list: a list
  1341. Returns:
  1342. list: a sorted de-duped list
  1343. """
  1344. alist.sort()
  1345. out = list()
  1346. for i in alist:
  1347. if i not in out:
  1348. out.append(i)
  1349. return out
  1350. def safe_get_bool(fact):
  1351. """ Get a boolean fact safely.
  1352. Args:
  1353. facts: fact to convert
  1354. Returns:
  1355. bool: given fact as a bool
  1356. """
  1357. return bool(strtobool(str(fact)))
  1358. def set_proxy_facts(facts):
  1359. """ Set global proxy facts
  1360. Args:
  1361. facts(dict): existing facts
  1362. Returns:
  1363. facts(dict): Updated facts with missing values
  1364. """
  1365. if 'common' in facts:
  1366. common = facts['common']
  1367. if 'http_proxy' in common or 'https_proxy' in common:
  1368. if 'no_proxy' in common and isinstance(common['no_proxy'], string_types):
  1369. common['no_proxy'] = common['no_proxy'].split(",")
  1370. elif 'no_proxy' not in common:
  1371. common['no_proxy'] = []
  1372. if 'generate_no_proxy_hosts' in common and safe_get_bool(common['generate_no_proxy_hosts']):
  1373. if 'no_proxy_internal_hostnames' in common:
  1374. common['no_proxy'].extend(common['no_proxy_internal_hostnames'].split(','))
  1375. # We always add local dns domain and ourselves no matter what
  1376. common['no_proxy'].append('.' + common['dns_domain'])
  1377. common['no_proxy'].append(common['hostname'])
  1378. common['no_proxy'] = ','.join(sort_unique(common['no_proxy']))
  1379. facts['common'] = common
  1380. return facts
  1381. def set_builddefaults_facts(facts):
  1382. """ Set build defaults including setting proxy values from http_proxy, https_proxy,
  1383. no_proxy to the more specific builddefaults and builddefaults_git vars.
  1384. 1. http_proxy, https_proxy, no_proxy
  1385. 2. builddefaults_*
  1386. 3. builddefaults_git_*
  1387. Args:
  1388. facts(dict): existing facts
  1389. Returns:
  1390. facts(dict): Updated facts with missing values
  1391. """
  1392. if 'builddefaults' in facts:
  1393. builddefaults = facts['builddefaults']
  1394. common = facts['common']
  1395. # Copy values from common to builddefaults
  1396. if 'http_proxy' not in builddefaults and 'http_proxy' in common:
  1397. builddefaults['http_proxy'] = common['http_proxy']
  1398. if 'https_proxy' not in builddefaults and 'https_proxy' in common:
  1399. builddefaults['https_proxy'] = common['https_proxy']
  1400. if 'no_proxy' not in builddefaults and 'no_proxy' in common:
  1401. builddefaults['no_proxy'] = common['no_proxy']
  1402. # Create git specific facts from generic values, if git specific values are
  1403. # not defined.
  1404. if 'git_http_proxy' not in builddefaults and 'http_proxy' in builddefaults:
  1405. builddefaults['git_http_proxy'] = builddefaults['http_proxy']
  1406. if 'git_https_proxy' not in builddefaults and 'https_proxy' in builddefaults:
  1407. builddefaults['git_https_proxy'] = builddefaults['https_proxy']
  1408. if 'git_no_proxy' not in builddefaults and 'no_proxy' in builddefaults:
  1409. builddefaults['git_no_proxy'] = builddefaults['no_proxy']
  1410. # If we're actually defining a builddefaults config then create admission_plugin_config
  1411. # then merge builddefaults[config] structure into admission_plugin_config
  1412. if 'config' in builddefaults:
  1413. if 'admission_plugin_config' not in facts['master']:
  1414. facts['master']['admission_plugin_config'] = dict()
  1415. facts['master']['admission_plugin_config'].update(builddefaults['config'])
  1416. # if the user didn't actually provide proxy values, delete the proxy env variable defaults.
  1417. delete_empty_keys(facts['master']['admission_plugin_config']['BuildDefaults']['configuration']['env'])
  1418. return facts
  1419. def delete_empty_keys(keylist):
  1420. """ Delete dictionary elements from keylist where "value" is empty.
  1421. Args:
  1422. keylist(list): A list of builddefault configuration envs.
  1423. Returns:
  1424. none
  1425. Example:
  1426. keylist = [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  1427. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  1428. {'name': 'NO_PROXY', 'value': ''}]
  1429. After calling delete_empty_keys the provided list is modified to become:
  1430. [{'name': 'HTTP_PROXY', 'value': 'http://file.rdu.redhat.com:3128'},
  1431. {'name': 'HTTPS_PROXY', 'value': 'http://file.rdu.redhat.com:3128'}]
  1432. """
  1433. count = 0
  1434. for i in range(0, len(keylist)):
  1435. if len(keylist[i - count]['value']) == 0:
  1436. del keylist[i - count]
  1437. count += 1
  1438. def set_buildoverrides_facts(facts):
  1439. """ Set build overrides
  1440. Args:
  1441. facts(dict): existing facts
  1442. Returns:
  1443. facts(dict): Updated facts with missing values
  1444. """
  1445. if 'buildoverrides' in facts:
  1446. buildoverrides = facts['buildoverrides']
  1447. # If we're actually defining a buildoverrides config then create admission_plugin_config
  1448. # then merge buildoverrides[config] structure into admission_plugin_config
  1449. if 'config' in buildoverrides:
  1450. if 'admission_plugin_config' not in facts['master']:
  1451. facts['master']['admission_plugin_config'] = dict()
  1452. facts['master']['admission_plugin_config'].update(buildoverrides['config'])
  1453. return facts
  1454. # pylint: disable=too-many-statements
  1455. def set_container_facts_if_unset(facts):
  1456. """ Set containerized facts.
  1457. Args:
  1458. facts (dict): existing facts
  1459. Returns:
  1460. dict: the facts dict updated with the generated containerization
  1461. facts
  1462. """
  1463. deployment_type = facts['common']['deployment_type']
  1464. if deployment_type in ['enterprise', 'openshift-enterprise']:
  1465. master_image = 'openshift3/ose'
  1466. cli_image = master_image
  1467. node_image = 'openshift3/node'
  1468. ovs_image = 'openshift3/openvswitch'
  1469. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1470. pod_image = 'openshift3/ose-pod'
  1471. router_image = 'openshift3/ose-haproxy-router'
  1472. registry_image = 'openshift3/ose-docker-registry'
  1473. deployer_image = 'openshift3/ose-deployer'
  1474. elif deployment_type == 'atomic-enterprise':
  1475. master_image = 'aep3_beta/aep'
  1476. cli_image = master_image
  1477. node_image = 'aep3_beta/node'
  1478. ovs_image = 'aep3_beta/openvswitch'
  1479. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1480. pod_image = 'aep3_beta/aep-pod'
  1481. router_image = 'aep3_beta/aep-haproxy-router'
  1482. registry_image = 'aep3_beta/aep-docker-registry'
  1483. deployer_image = 'aep3_beta/aep-deployer'
  1484. else:
  1485. master_image = 'openshift/origin'
  1486. cli_image = master_image
  1487. node_image = 'openshift/node'
  1488. ovs_image = 'openshift/openvswitch'
  1489. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1490. pod_image = 'openshift/origin-pod'
  1491. router_image = 'openshift/origin-haproxy-router'
  1492. registry_image = 'openshift/origin-docker-registry'
  1493. deployer_image = 'openshift/origin-deployer'
  1494. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1495. if 'is_containerized' not in facts['common']:
  1496. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1497. if 'cli_image' not in facts['common']:
  1498. facts['common']['cli_image'] = cli_image
  1499. if 'pod_image' not in facts['common']:
  1500. facts['common']['pod_image'] = pod_image
  1501. if 'router_image' not in facts['common']:
  1502. facts['common']['router_image'] = router_image
  1503. if 'registry_image' not in facts['common']:
  1504. facts['common']['registry_image'] = registry_image
  1505. if 'deployer_image' not in facts['common']:
  1506. facts['common']['deployer_image'] = deployer_image
  1507. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  1508. facts['etcd']['etcd_image'] = etcd_image
  1509. if 'master' in facts and 'master_image' not in facts['master']:
  1510. facts['master']['master_image'] = master_image
  1511. if 'node' in facts:
  1512. if 'node_image' not in facts['node']:
  1513. facts['node']['node_image'] = node_image
  1514. if 'ovs_image' not in facts['node']:
  1515. facts['node']['ovs_image'] = ovs_image
  1516. if safe_get_bool(facts['common']['is_containerized']):
  1517. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1518. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1519. return facts
  1520. def set_installed_variant_rpm_facts(facts):
  1521. """ Set RPM facts of installed variant
  1522. Args:
  1523. facts (dict): existing facts
  1524. Returns:
  1525. dict: the facts dict updated with installed_variant_rpms
  1526. """
  1527. installed_rpms = []
  1528. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1529. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1530. variant_rpms = [base_rpm] + \
  1531. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1532. ['tuned-profiles-%s-node' % base_rpm]
  1533. for rpm in variant_rpms:
  1534. exit_code, _, _ = module.run_command(['rpm', '-q', rpm]) # noqa: F405
  1535. if exit_code == 0:
  1536. installed_rpms.append(rpm)
  1537. facts['common']['installed_variant_rpms'] = installed_rpms
  1538. return facts
  1539. class OpenShiftFactsInternalError(Exception):
  1540. """Origin Facts Error"""
  1541. pass
  1542. class OpenShiftFactsUnsupportedRoleError(Exception):
  1543. """Origin Facts Unsupported Role Error"""
  1544. pass
  1545. class OpenShiftFactsFileWriteError(Exception):
  1546. """Origin Facts File Write Error"""
  1547. pass
  1548. class OpenShiftFactsMetadataUnavailableError(Exception):
  1549. """Origin Facts Metadata Unavailable Error"""
  1550. pass
  1551. class OpenShiftFacts(object):
  1552. """ Origin Facts
  1553. Attributes:
  1554. facts (dict): facts for the host
  1555. Args:
  1556. module (AnsibleModule): an AnsibleModule object
  1557. role (str): role for setting local facts
  1558. filename (str): local facts file to use
  1559. local_facts (dict): local facts to set
  1560. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1561. '.' notation ex: ['master.named_certificates']
  1562. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1563. '.' notation ex: ['master.master_count']
  1564. Raises:
  1565. OpenShiftFactsUnsupportedRoleError:
  1566. """
  1567. known_roles = ['builddefaults',
  1568. 'buildoverrides',
  1569. 'clock',
  1570. 'cloudprovider',
  1571. 'common',
  1572. 'docker',
  1573. 'etcd',
  1574. 'hosted',
  1575. 'master',
  1576. 'node']
  1577. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1578. # pylint: disable=too-many-arguments,no-value-for-parameter
  1579. def __init__(self, role, filename, local_facts,
  1580. additive_facts_to_overwrite=None,
  1581. openshift_env=None,
  1582. openshift_env_structures=None,
  1583. protected_facts_to_overwrite=None):
  1584. self.changed = False
  1585. self.filename = filename
  1586. if role not in self.known_roles:
  1587. raise OpenShiftFactsUnsupportedRoleError(
  1588. "Role %s is not supported by this module" % role
  1589. )
  1590. self.role = role
  1591. try:
  1592. # ansible-2.1
  1593. # pylint: disable=too-many-function-args,invalid-name
  1594. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter']) # noqa: F405
  1595. for (k, v) in self.system_facts.items():
  1596. self.system_facts["ansible_%s" % k.replace('-', '_')] = v
  1597. except UnboundLocalError:
  1598. # ansible-2.2
  1599. self.system_facts = get_all_facts(module)['ansible_facts'] # noqa: F405
  1600. self.facts = self.generate_facts(local_facts,
  1601. additive_facts_to_overwrite,
  1602. openshift_env,
  1603. openshift_env_structures,
  1604. protected_facts_to_overwrite)
  1605. def generate_facts(self,
  1606. local_facts,
  1607. additive_facts_to_overwrite,
  1608. openshift_env,
  1609. openshift_env_structures,
  1610. protected_facts_to_overwrite):
  1611. """ Generate facts
  1612. Args:
  1613. local_facts (dict): local_facts for overriding generated defaults
  1614. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1615. '.' notation ex: ['master.named_certificates']
  1616. openshift_env (dict): openshift_env facts for overriding generated defaults
  1617. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1618. '.' notation ex: ['master.master_count']
  1619. Returns:
  1620. dict: The generated facts
  1621. """
  1622. local_facts = self.init_local_facts(local_facts,
  1623. additive_facts_to_overwrite,
  1624. openshift_env,
  1625. openshift_env_structures,
  1626. protected_facts_to_overwrite)
  1627. roles = local_facts.keys()
  1628. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1629. deployment_type = local_facts['common']['deployment_type']
  1630. else:
  1631. deployment_type = 'origin'
  1632. if 'common' in local_facts and 'deployment_subtype' in local_facts['common']:
  1633. deployment_subtype = local_facts['common']['deployment_subtype']
  1634. else:
  1635. deployment_subtype = 'basic'
  1636. defaults = self.get_defaults(roles, deployment_type, deployment_subtype)
  1637. provider_facts = self.init_provider_facts()
  1638. facts = apply_provider_facts(defaults, provider_facts)
  1639. facts = merge_facts(facts,
  1640. local_facts,
  1641. additive_facts_to_overwrite,
  1642. protected_facts_to_overwrite)
  1643. facts = migrate_oauth_template_facts(facts)
  1644. facts['current_config'] = get_current_config(facts)
  1645. facts = set_url_facts_if_unset(facts)
  1646. facts = set_project_cfg_facts_if_unset(facts)
  1647. facts = set_flannel_facts_if_unset(facts)
  1648. facts = set_nuage_facts_if_unset(facts)
  1649. facts = set_node_schedulability(facts)
  1650. facts = set_selectors(facts)
  1651. facts = set_identity_providers_if_unset(facts)
  1652. facts = set_deployment_facts_if_unset(facts)
  1653. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1654. facts = set_container_facts_if_unset(facts)
  1655. facts = build_kubelet_args(facts)
  1656. facts = build_controller_args(facts)
  1657. facts = build_api_server_args(facts)
  1658. facts = set_version_facts_if_unset(facts)
  1659. facts = set_dnsmasq_facts_if_unset(facts)
  1660. facts = set_manageiq_facts_if_unset(facts)
  1661. facts = set_aggregate_facts(facts)
  1662. facts = set_etcd_facts_if_unset(facts)
  1663. facts = set_proxy_facts(facts)
  1664. facts = set_builddefaults_facts(facts)
  1665. facts = set_buildoverrides_facts(facts)
  1666. if not safe_get_bool(facts['common']['is_containerized']):
  1667. facts = set_installed_variant_rpm_facts(facts)
  1668. facts = set_nodename(facts)
  1669. return dict(openshift=facts)
  1670. def get_defaults(self, roles, deployment_type, deployment_subtype):
  1671. """ Get default fact values
  1672. Args:
  1673. roles (list): list of roles for this host
  1674. Returns:
  1675. dict: The generated default facts
  1676. """
  1677. defaults = {}
  1678. ip_addr = self.system_facts['ansible_default_ipv4']['address']
  1679. exit_code, output, _ = module.run_command(['hostname', '-f']) # noqa: F405
  1680. hostname_f = output.strip() if exit_code == 0 else ''
  1681. hostname_values = [hostname_f, self.system_facts['ansible_nodename'],
  1682. self.system_facts['ansible_fqdn']]
  1683. hostname = choose_hostname(hostname_values, ip_addr)
  1684. defaults['common'] = dict(use_openshift_sdn=True, ip=ip_addr,
  1685. public_ip=ip_addr,
  1686. deployment_type=deployment_type,
  1687. deployment_subtype=deployment_subtype,
  1688. hostname=hostname,
  1689. public_hostname=hostname,
  1690. portal_net='172.30.0.0/16',
  1691. client_binary='oc', admin_binary='oadm',
  1692. dns_domain='cluster.local',
  1693. install_examples=True,
  1694. debug_level=2)
  1695. if 'master' in roles:
  1696. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1697. controllers_port='8444',
  1698. console_use_ssl=True,
  1699. console_path='/console',
  1700. console_port='8443', etcd_use_ssl=True,
  1701. etcd_hosts='', etcd_port='4001',
  1702. portal_net='172.30.0.0/16',
  1703. embedded_etcd=True, embedded_kube=True,
  1704. embedded_dns=True,
  1705. bind_addr='0.0.0.0',
  1706. session_max_seconds=3600,
  1707. session_name='ssn',
  1708. session_secrets_file='',
  1709. access_token_max_seconds=86400,
  1710. auth_token_max_seconds=500,
  1711. oauth_grant_method='auto',
  1712. dynamic_provisioning_enabled=True,
  1713. max_requests_inflight=500)
  1714. if 'node' in roles:
  1715. defaults['node'] = dict(labels={}, annotations={},
  1716. iptables_sync_period='30s',
  1717. local_quota_per_fsgroup="",
  1718. set_node_ip=False)
  1719. if 'docker' in roles:
  1720. docker = dict(disable_push_dockerhub=False,
  1721. options='--log-driver=json-file --log-opt max-size=50m')
  1722. # NOTE: This is a workaround for a dnf output racecondition that can occur in
  1723. # some situations. See https://bugzilla.redhat.com/show_bug.cgi?id=918184
  1724. if self.system_facts['ansible_pkg_mgr'] == 'dnf':
  1725. rpm_rebuilddb()
  1726. version_info = get_docker_version_info()
  1727. if version_info is not None:
  1728. docker['api_version'] = version_info['api_version']
  1729. docker['version'] = version_info['version']
  1730. docker['gte_1_10'] = LooseVersion(version_info['version']) >= LooseVersion('1.10')
  1731. hosted_registry_insecure = get_hosted_registry_insecure()
  1732. if hosted_registry_insecure is not None:
  1733. docker['hosted_registry_insecure'] = hosted_registry_insecure
  1734. defaults['docker'] = docker
  1735. if 'clock' in roles:
  1736. exit_code, _, _ = module.run_command(['rpm', '-q', 'chrony']) # noqa: F405
  1737. chrony_installed = bool(exit_code == 0)
  1738. defaults['clock'] = dict(
  1739. enabled=True,
  1740. chrony_installed=chrony_installed)
  1741. if 'cloudprovider' in roles:
  1742. defaults['cloudprovider'] = dict(kind=None)
  1743. if 'hosted' in roles or self.role == 'hosted':
  1744. defaults['hosted'] = dict(
  1745. metrics=dict(
  1746. deploy=False,
  1747. duration=7,
  1748. resolution='10s',
  1749. storage=dict(
  1750. kind=None,
  1751. volume=dict(
  1752. name='metrics',
  1753. size='10Gi'
  1754. ),
  1755. nfs=dict(
  1756. directory='/exports',
  1757. options='*(rw,root_squash)'
  1758. ),
  1759. host=None,
  1760. access=dict(
  1761. modes=['ReadWriteOnce']
  1762. ),
  1763. create_pv=True,
  1764. create_pvc=False
  1765. )
  1766. ),
  1767. logging=dict(
  1768. storage=dict(
  1769. kind=None,
  1770. volume=dict(
  1771. name='logging-es',
  1772. size='10Gi'
  1773. ),
  1774. nfs=dict(
  1775. directory='/exports',
  1776. options='*(rw,root_squash)'
  1777. ),
  1778. host=None,
  1779. access=dict(
  1780. modes=['ReadWriteOnce']
  1781. ),
  1782. create_pv=True,
  1783. create_pvc=False
  1784. )
  1785. ),
  1786. registry=dict(
  1787. storage=dict(
  1788. kind=None,
  1789. volume=dict(
  1790. name='registry',
  1791. size='5Gi'
  1792. ),
  1793. nfs=dict(
  1794. directory='/exports',
  1795. options='*(rw,root_squash)'),
  1796. host=None,
  1797. access=dict(
  1798. modes=['ReadWriteMany']
  1799. ),
  1800. create_pv=True,
  1801. create_pvc=True
  1802. )
  1803. ),
  1804. router=dict()
  1805. )
  1806. return defaults
  1807. def guess_host_provider(self):
  1808. """ Guess the host provider
  1809. Returns:
  1810. dict: The generated default facts for the detected provider
  1811. """
  1812. # TODO: cloud provider facts should probably be submitted upstream
  1813. product_name = self.system_facts['ansible_product_name']
  1814. product_version = self.system_facts['ansible_product_version']
  1815. virt_type = self.system_facts['ansible_virtualization_type']
  1816. virt_role = self.system_facts['ansible_virtualization_role']
  1817. provider = None
  1818. metadata = None
  1819. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1820. # need to create PR for ansible to expose it
  1821. bios_vendor = get_file_content( # noqa: F405
  1822. '/sys/devices/virtual/dmi/id/bios_vendor'
  1823. )
  1824. if bios_vendor == 'Google':
  1825. provider = 'gce'
  1826. metadata_url = ('http://metadata.google.internal/'
  1827. 'computeMetadata/v1/?recursive=true')
  1828. headers = {'Metadata-Flavor': 'Google'}
  1829. metadata = get_provider_metadata(metadata_url, True, headers,
  1830. True)
  1831. # Filter sshKeys and serviceAccounts from gce metadata
  1832. if metadata:
  1833. metadata['project']['attributes'].pop('sshKeys', None)
  1834. metadata['instance'].pop('serviceAccounts', None)
  1835. elif virt_type == 'xen' and virt_role == 'guest' and re.match(r'.*\.amazon$', product_version):
  1836. provider = 'aws'
  1837. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1838. metadata = get_provider_metadata(metadata_url)
  1839. elif re.search(r'OpenStack', product_name):
  1840. provider = 'openstack'
  1841. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1842. 'meta_data.json')
  1843. metadata = get_provider_metadata(metadata_url, True, None,
  1844. True)
  1845. if metadata:
  1846. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1847. metadata['ec2_compat'] = get_provider_metadata(
  1848. ec2_compat_url
  1849. )
  1850. # disable pylint maybe-no-member because overloaded use of
  1851. # the module name causes pylint to not detect that results
  1852. # is an array or hash
  1853. # pylint: disable=maybe-no-member
  1854. # Filter public_keys and random_seed from openstack metadata
  1855. metadata.pop('public_keys', None)
  1856. metadata.pop('random_seed', None)
  1857. if not metadata['ec2_compat']:
  1858. metadata = None
  1859. return dict(name=provider, metadata=metadata)
  1860. def init_provider_facts(self):
  1861. """ Initialize the provider facts
  1862. Returns:
  1863. dict: The normalized provider facts
  1864. """
  1865. provider_info = self.guess_host_provider()
  1866. provider_facts = normalize_provider_facts(
  1867. provider_info.get('name'),
  1868. provider_info.get('metadata')
  1869. )
  1870. return provider_facts
  1871. @staticmethod
  1872. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1873. """ Split openshift_env facts based on openshift_env structures.
  1874. Args:
  1875. openshift_env_fact (string): the openshift_env fact to split
  1876. ex: 'openshift_cloudprovider_openstack_auth_url'
  1877. openshift_env_structures (list): a list of structures to determine fact keys
  1878. ex: ['openshift.cloudprovider.openstack.*']
  1879. Returns:
  1880. list: a list of keys that represent the fact
  1881. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1882. """
  1883. # By default, we'll split an openshift_env fact by underscores.
  1884. fact_keys = openshift_env_fact.split('_')
  1885. # Determine if any of the provided variable structures match the fact.
  1886. matching_structure = None
  1887. if openshift_env_structures is not None:
  1888. for structure in openshift_env_structures:
  1889. if re.match(structure, openshift_env_fact):
  1890. matching_structure = structure
  1891. # Fact didn't match any variable structures so return the default fact keys.
  1892. if matching_structure is None:
  1893. return fact_keys
  1894. final_keys = []
  1895. structure_keys = matching_structure.split('.')
  1896. for structure_key in structure_keys:
  1897. # Matched current key. Add to final keys.
  1898. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1899. final_keys.append(structure_key)
  1900. # Wildcard means we will be taking everything from here to the end of the fact.
  1901. elif structure_key == '*':
  1902. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1903. # Shouldn't have gotten here, return the fact keys.
  1904. else:
  1905. return fact_keys
  1906. return final_keys
  1907. # Disabling too-many-branches and too-many-locals.
  1908. # This should be cleaned up as a TODO item.
  1909. # pylint: disable=too-many-branches, too-many-locals
  1910. def init_local_facts(self, facts=None,
  1911. additive_facts_to_overwrite=None,
  1912. openshift_env=None,
  1913. openshift_env_structures=None,
  1914. protected_facts_to_overwrite=None):
  1915. """ Initialize the local facts
  1916. Args:
  1917. facts (dict): local facts to set
  1918. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1919. '.' notation ex: ['master.named_certificates']
  1920. openshift_env (dict): openshift env facts to set
  1921. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1922. '.' notation ex: ['master.master_count']
  1923. Returns:
  1924. dict: The result of merging the provided facts with existing
  1925. local facts
  1926. """
  1927. changed = False
  1928. facts_to_set = dict()
  1929. if facts is not None:
  1930. facts_to_set[self.role] = facts
  1931. if openshift_env != {} and openshift_env is not None:
  1932. for fact, value in iteritems(openshift_env):
  1933. oo_env_facts = dict()
  1934. current_level = oo_env_facts
  1935. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1936. if len(keys) > 0 and keys[0] != self.role:
  1937. continue
  1938. for key in keys:
  1939. if key == keys[-1]:
  1940. current_level[key] = value
  1941. elif key not in current_level:
  1942. current_level[key] = dict()
  1943. current_level = current_level[key]
  1944. facts_to_set = merge_facts(orig=facts_to_set,
  1945. new=oo_env_facts,
  1946. additive_facts_to_overwrite=[],
  1947. protected_facts_to_overwrite=[])
  1948. local_facts = get_local_facts_from_file(self.filename)
  1949. migrated_facts = migrate_local_facts(local_facts)
  1950. new_local_facts = merge_facts(migrated_facts,
  1951. facts_to_set,
  1952. additive_facts_to_overwrite,
  1953. protected_facts_to_overwrite)
  1954. if 'docker' in new_local_facts:
  1955. # remove duplicate and empty strings from registry lists
  1956. for cat in ['additional', 'blocked', 'insecure']:
  1957. key = '{0}_registries'.format(cat)
  1958. if key in new_local_facts['docker']:
  1959. val = new_local_facts['docker'][key]
  1960. if isinstance(val, string_types):
  1961. val = [x.strip() for x in val.split(',')]
  1962. new_local_facts['docker'][key] = list(set(val) - set(['']))
  1963. # Convert legacy log_options comma sep string to a list if present:
  1964. if 'log_options' in new_local_facts['docker'] and \
  1965. isinstance(new_local_facts['docker']['log_options'], string_types):
  1966. new_local_facts['docker']['log_options'] = new_local_facts['docker']['log_options'].split(',')
  1967. new_local_facts = self.remove_empty_facts(new_local_facts)
  1968. if new_local_facts != local_facts:
  1969. self.validate_local_facts(new_local_facts)
  1970. changed = True
  1971. if not module.check_mode: # noqa: F405
  1972. save_local_facts(self.filename, new_local_facts)
  1973. self.changed = changed
  1974. return new_local_facts
  1975. def remove_empty_facts(self, facts=None):
  1976. """ Remove empty facts
  1977. Args:
  1978. facts (dict): facts to clean
  1979. """
  1980. facts_to_remove = []
  1981. for fact, value in iteritems(facts):
  1982. if isinstance(facts[fact], dict):
  1983. facts[fact] = self.remove_empty_facts(facts[fact])
  1984. else:
  1985. if value == "" or value == [""] or value is None:
  1986. facts_to_remove.append(fact)
  1987. for fact in facts_to_remove:
  1988. del facts[fact]
  1989. return facts
  1990. def validate_local_facts(self, facts=None):
  1991. """ Validate local facts
  1992. Args:
  1993. facts (dict): local facts to validate
  1994. """
  1995. invalid_facts = dict()
  1996. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1997. if invalid_facts:
  1998. msg = 'Invalid facts detected:\n'
  1999. # pylint: disable=consider-iterating-dictionary
  2000. for key in invalid_facts.keys():
  2001. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  2002. module.fail_json(msg=msg, changed=self.changed) # noqa: F405
  2003. # disabling pylint errors for line-too-long since we're dealing
  2004. # with best effort reduction of error messages here.
  2005. # disabling errors for too-many-branches since we require checking
  2006. # many conditions.
  2007. # pylint: disable=line-too-long, too-many-branches
  2008. @staticmethod
  2009. def validate_master_facts(facts, invalid_facts):
  2010. """ Validate master facts
  2011. Args:
  2012. facts (dict): local facts to validate
  2013. invalid_facts (dict): collected invalid_facts
  2014. Returns:
  2015. dict: Invalid facts
  2016. """
  2017. if 'master' in facts:
  2018. # openshift.master.session_auth_secrets
  2019. if 'session_auth_secrets' in facts['master']:
  2020. session_auth_secrets = facts['master']['session_auth_secrets']
  2021. if not issubclass(type(session_auth_secrets), list):
  2022. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  2023. elif 'session_encryption_secrets' not in facts['master']:
  2024. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  2025. 'if openshift_master_session_auth_secrets is provided.')
  2026. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  2027. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  2028. 'openshift_master_session_encryption_secrets must be '
  2029. 'equal length.')
  2030. else:
  2031. for secret in session_auth_secrets:
  2032. if len(secret) < 32:
  2033. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  2034. 'Secrets must be at least 32 characters in length.')
  2035. # openshift.master.session_encryption_secrets
  2036. if 'session_encryption_secrets' in facts['master']:
  2037. session_encryption_secrets = facts['master']['session_encryption_secrets']
  2038. if not issubclass(type(session_encryption_secrets), list):
  2039. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  2040. elif 'session_auth_secrets' not in facts['master']:
  2041. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  2042. 'set if openshift_master_session_encryption_secrets '
  2043. 'is provided.')
  2044. else:
  2045. for secret in session_encryption_secrets:
  2046. if len(secret) not in [16, 24, 32]:
  2047. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  2048. 'Secrets must be 16, 24, or 32 characters in length.')
  2049. return invalid_facts
  2050. def main():
  2051. """ main """
  2052. # disabling pylint errors for global-variable-undefined and invalid-name
  2053. # for 'global module' usage, since it is required to use ansible_facts
  2054. # pylint: disable=global-variable-undefined, invalid-name
  2055. global module
  2056. module = AnsibleModule( # noqa: F405
  2057. argument_spec=dict(
  2058. role=dict(default='common', required=False,
  2059. choices=OpenShiftFacts.known_roles),
  2060. local_facts=dict(default=None, type='dict', required=False),
  2061. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  2062. openshift_env=dict(default={}, type='dict', required=False),
  2063. openshift_env_structures=dict(default=[], type='list', required=False),
  2064. protected_facts_to_overwrite=dict(default=[], type='list', required=False)
  2065. ),
  2066. supports_check_mode=True,
  2067. add_file_common_args=True,
  2068. )
  2069. if not HAVE_DBUS:
  2070. module.fail_json(msg="This module requires dbus python bindings") # noqa: F405
  2071. module.params['gather_subset'] = ['hardware', 'network', 'virtual', 'facter'] # noqa: F405
  2072. module.params['gather_timeout'] = 10 # noqa: F405
  2073. module.params['filter'] = '*' # noqa: F405
  2074. role = module.params['role'] # noqa: F405
  2075. local_facts = module.params['local_facts'] # noqa: F405
  2076. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite'] # noqa: F405
  2077. openshift_env = module.params['openshift_env'] # noqa: F405
  2078. openshift_env_structures = module.params['openshift_env_structures'] # noqa: F405
  2079. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite'] # noqa: F405
  2080. fact_file = '/etc/ansible/facts.d/openshift.fact'
  2081. openshift_facts = OpenShiftFacts(role,
  2082. fact_file,
  2083. local_facts,
  2084. additive_facts_to_overwrite,
  2085. openshift_env,
  2086. openshift_env_structures,
  2087. protected_facts_to_overwrite)
  2088. file_params = module.params.copy() # noqa: F405
  2089. file_params['path'] = fact_file
  2090. file_args = module.load_file_common_arguments(file_params) # noqa: F405
  2091. changed = module.set_fs_attributes_if_different(file_args, # noqa: F405
  2092. openshift_facts.changed)
  2093. return module.exit_json(changed=changed, # noqa: F405
  2094. ansible_facts=openshift_facts.facts)
  2095. if __name__ == '__main__':
  2096. main()