openshift_facts.py 103 KB

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