openshift_facts.py 99 KB

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