openshift_facts.py 99 KB

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