openshift_facts.py 102 KB

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