openshift_facts.py 97 KB

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