openshift_facts.py 101 KB

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