openshift_facts.py 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  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. node_image = 'openshift3/node'
  1350. ovs_image = 'openshift3/openvswitch'
  1351. pod_image = 'openshift3/ose-pod'
  1352. router_image = 'openshift3/ose-haproxy-router'
  1353. registry_image = 'openshift3/ose-docker-registry'
  1354. deployer_image = 'openshift3/ose-deployer'
  1355. else:
  1356. master_image = 'openshift/origin'
  1357. node_image = 'openshift/node'
  1358. ovs_image = 'openshift/openvswitch'
  1359. pod_image = 'openshift/origin-pod'
  1360. router_image = 'openshift/origin-haproxy-router'
  1361. registry_image = 'openshift/origin-docker-registry'
  1362. deployer_image = 'openshift/origin-deployer'
  1363. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1364. # If openshift_docker_use_system_container is set and is True ....
  1365. if 'use_system_container' in list(facts['docker'].keys()):
  1366. # use safe_get_bool as the inventory variable may not be a
  1367. # valid boolean on it's own.
  1368. if safe_get_bool(facts['docker']['use_system_container']):
  1369. # ... set the service name to container-engine
  1370. facts['docker']['service_name'] = 'container-engine'
  1371. if 'is_containerized' not in facts['common']:
  1372. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1373. if 'pod_image' not in facts['common']:
  1374. facts['common']['pod_image'] = pod_image
  1375. if 'router_image' not in facts['common']:
  1376. facts['common']['router_image'] = router_image
  1377. if 'registry_image' not in facts['common']:
  1378. facts['common']['registry_image'] = registry_image
  1379. if 'deployer_image' not in facts['common']:
  1380. facts['common']['deployer_image'] = deployer_image
  1381. if 'master' in facts and 'master_image' not in facts['master']:
  1382. facts['master']['master_image'] = master_image
  1383. facts['master']['master_system_image'] = master_image
  1384. if 'node' in facts:
  1385. if 'node_image' not in facts['node']:
  1386. facts['node']['node_image'] = node_image
  1387. facts['node']['node_system_image'] = node_image
  1388. if 'ovs_image' not in facts['node']:
  1389. facts['node']['ovs_image'] = ovs_image
  1390. facts['node']['ovs_system_image'] = ovs_image
  1391. if safe_get_bool(facts['common']['is_containerized']):
  1392. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1393. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1394. return facts
  1395. def set_installed_variant_rpm_facts(facts):
  1396. """ Set RPM facts of installed variant
  1397. Args:
  1398. facts (dict): existing facts
  1399. Returns:
  1400. dict: the facts dict updated with installed_variant_rpms
  1401. """
  1402. installed_rpms = []
  1403. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1404. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1405. variant_rpms = [base_rpm] + \
  1406. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1407. ['tuned-profiles-%s-node' % base_rpm]
  1408. for rpm in variant_rpms:
  1409. exit_code, _, _ = module.run_command(['rpm', '-q', rpm]) # noqa: F405
  1410. if exit_code == 0:
  1411. installed_rpms.append(rpm)
  1412. facts['common']['installed_variant_rpms'] = installed_rpms
  1413. return facts
  1414. class OpenShiftFactsInternalError(Exception):
  1415. """Origin Facts Error"""
  1416. pass
  1417. class OpenShiftFactsUnsupportedRoleError(Exception):
  1418. """Origin Facts Unsupported Role Error"""
  1419. pass
  1420. class OpenShiftFactsFileWriteError(Exception):
  1421. """Origin Facts File Write Error"""
  1422. pass
  1423. class OpenShiftFactsMetadataUnavailableError(Exception):
  1424. """Origin Facts Metadata Unavailable Error"""
  1425. pass
  1426. class OpenShiftFacts(object):
  1427. """ Origin Facts
  1428. Attributes:
  1429. facts (dict): facts for the host
  1430. Args:
  1431. module (AnsibleModule): an AnsibleModule object
  1432. role (str): role for setting local facts
  1433. filename (str): local facts file to use
  1434. local_facts (dict): local facts to set
  1435. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1436. '.' notation ex: ['master.named_certificates']
  1437. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1438. '.' notation ex: ['master.master_count']
  1439. Raises:
  1440. OpenShiftFactsUnsupportedRoleError:
  1441. """
  1442. known_roles = ['builddefaults',
  1443. 'buildoverrides',
  1444. 'cloudprovider',
  1445. 'common',
  1446. 'docker',
  1447. 'etcd',
  1448. 'hosted',
  1449. 'master',
  1450. 'node',
  1451. 'logging',
  1452. 'loggingops',
  1453. 'metrics',
  1454. 'prometheus']
  1455. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1456. # pylint: disable=too-many-arguments,no-value-for-parameter
  1457. def __init__(self, role, filename, local_facts,
  1458. additive_facts_to_overwrite=None,
  1459. openshift_env=None,
  1460. openshift_env_structures=None,
  1461. protected_facts_to_overwrite=None):
  1462. self.changed = False
  1463. self.filename = filename
  1464. if role not in self.known_roles:
  1465. raise OpenShiftFactsUnsupportedRoleError(
  1466. "Role %s is not supported by this module" % role
  1467. )
  1468. self.role = role
  1469. # Collect system facts and preface each fact with 'ansible_'.
  1470. try:
  1471. # pylint: disable=too-many-function-args,invalid-name
  1472. self.system_facts = ansible_facts(module, ['hardware', 'network', 'virtual', 'facter']) # noqa: F405
  1473. additional_facts = {}
  1474. for (k, v) in self.system_facts.items():
  1475. additional_facts["ansible_%s" % k.replace('-', '_')] = v
  1476. self.system_facts.update(additional_facts)
  1477. except UnboundLocalError:
  1478. # ansible-2.2,2.3
  1479. self.system_facts = get_all_facts(module)['ansible_facts'] # noqa: F405
  1480. self.facts = self.generate_facts(local_facts,
  1481. additive_facts_to_overwrite,
  1482. openshift_env,
  1483. openshift_env_structures,
  1484. protected_facts_to_overwrite)
  1485. def generate_facts(self,
  1486. local_facts,
  1487. additive_facts_to_overwrite,
  1488. openshift_env,
  1489. openshift_env_structures,
  1490. protected_facts_to_overwrite):
  1491. """ Generate facts
  1492. Args:
  1493. local_facts (dict): local_facts for overriding generated defaults
  1494. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1495. '.' notation ex: ['master.named_certificates']
  1496. openshift_env (dict): openshift_env facts for overriding generated defaults
  1497. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1498. '.' notation ex: ['master.master_count']
  1499. Returns:
  1500. dict: The generated facts
  1501. """
  1502. local_facts = self.init_local_facts(local_facts,
  1503. additive_facts_to_overwrite,
  1504. openshift_env,
  1505. openshift_env_structures,
  1506. protected_facts_to_overwrite)
  1507. roles = local_facts.keys()
  1508. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1509. deployment_type = local_facts['common']['deployment_type']
  1510. else:
  1511. deployment_type = 'origin'
  1512. if 'common' in local_facts and 'deployment_subtype' in local_facts['common']:
  1513. deployment_subtype = local_facts['common']['deployment_subtype']
  1514. else:
  1515. deployment_subtype = 'basic'
  1516. defaults = self.get_defaults(roles, deployment_type, deployment_subtype)
  1517. provider_facts = self.init_provider_facts()
  1518. facts = apply_provider_facts(defaults, provider_facts)
  1519. facts = merge_facts(facts,
  1520. local_facts,
  1521. additive_facts_to_overwrite,
  1522. protected_facts_to_overwrite)
  1523. facts = migrate_oauth_template_facts(facts)
  1524. facts['current_config'] = get_current_config(facts)
  1525. facts = set_url_facts_if_unset(facts)
  1526. facts = set_project_cfg_facts_if_unset(facts)
  1527. facts = set_selectors(facts)
  1528. facts = set_identity_providers_if_unset(facts)
  1529. facts = set_deployment_facts_if_unset(facts)
  1530. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1531. facts = set_container_facts_if_unset(facts)
  1532. facts = build_kubelet_args(facts)
  1533. facts = build_controller_args(facts)
  1534. facts = build_api_server_args(facts)
  1535. facts = set_version_facts_if_unset(facts)
  1536. facts = set_dnsmasq_facts_if_unset(facts)
  1537. facts = set_aggregate_facts(facts)
  1538. facts = set_etcd_facts_if_unset(facts)
  1539. facts = set_proxy_facts(facts)
  1540. facts = set_builddefaults_facts(facts)
  1541. facts = set_buildoverrides_facts(facts)
  1542. if not safe_get_bool(facts['common']['is_containerized']):
  1543. facts = set_installed_variant_rpm_facts(facts)
  1544. facts = set_nodename(facts)
  1545. return dict(openshift=facts)
  1546. def get_defaults(self, roles, deployment_type, deployment_subtype):
  1547. """ Get default fact values
  1548. Args:
  1549. roles (list): list of roles for this host
  1550. Returns:
  1551. dict: The generated default facts
  1552. """
  1553. defaults = {}
  1554. ip_addr = self.system_facts['ansible_default_ipv4']['address']
  1555. exit_code, output, _ = module.run_command(['hostname', '-f']) # noqa: F405
  1556. hostname_f = output.strip() if exit_code == 0 else ''
  1557. hostname_values = [hostname_f, self.system_facts['ansible_nodename'],
  1558. self.system_facts['ansible_fqdn']]
  1559. hostname = choose_hostname(hostname_values, ip_addr).lower()
  1560. defaults['common'] = dict(ip=ip_addr,
  1561. public_ip=ip_addr,
  1562. deployment_type=deployment_type,
  1563. deployment_subtype=deployment_subtype,
  1564. hostname=hostname,
  1565. public_hostname=hostname,
  1566. portal_net='172.30.0.0/16',
  1567. client_binary='oc', admin_binary='oadm',
  1568. dns_domain='cluster.local',
  1569. config_base='/etc/origin')
  1570. if 'master' in roles:
  1571. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1572. controllers_port='8444',
  1573. console_use_ssl=True,
  1574. console_path='/console',
  1575. console_port='8443', etcd_use_ssl=True,
  1576. etcd_hosts='', etcd_port='4001',
  1577. portal_net='172.30.0.0/16',
  1578. embedded_etcd=True, embedded_kube=True,
  1579. embedded_dns=True,
  1580. bind_addr='0.0.0.0',
  1581. session_max_seconds=3600,
  1582. session_name='ssn',
  1583. session_secrets_file='',
  1584. access_token_max_seconds=86400,
  1585. auth_token_max_seconds=500,
  1586. oauth_grant_method='auto',
  1587. dynamic_provisioning_enabled=True,
  1588. max_requests_inflight=500)
  1589. if 'node' in roles:
  1590. defaults['node'] = dict(labels={}, annotations={},
  1591. iptables_sync_period='30s',
  1592. local_quota_per_fsgroup="",
  1593. set_node_ip=False)
  1594. if 'docker' in roles:
  1595. docker = dict(disable_push_dockerhub=False,
  1596. options='--log-driver=journald')
  1597. # NOTE: This is a workaround for a dnf output racecondition that can occur in
  1598. # some situations. See https://bugzilla.redhat.com/show_bug.cgi?id=918184
  1599. if self.system_facts['ansible_pkg_mgr'] == 'dnf':
  1600. rpm_rebuilddb()
  1601. version_info = get_docker_version_info()
  1602. if version_info is not None:
  1603. docker['api_version'] = version_info['api_version']
  1604. docker['version'] = version_info['version']
  1605. docker['gte_1_10'] = LooseVersion(version_info['version']) >= LooseVersion('1.10')
  1606. hosted_registry_insecure = get_hosted_registry_insecure()
  1607. if hosted_registry_insecure is not None:
  1608. docker['hosted_registry_insecure'] = hosted_registry_insecure
  1609. docker['service_name'] = 'docker'
  1610. defaults['docker'] = docker
  1611. if 'cloudprovider' in roles:
  1612. defaults['cloudprovider'] = dict(kind=None)
  1613. if 'hosted' in roles or self.role == 'hosted':
  1614. defaults['hosted'] = dict(
  1615. etcd=dict(
  1616. storage=dict(
  1617. kind=None,
  1618. volume=dict(
  1619. name='etcd',
  1620. size='1Gi'
  1621. ),
  1622. nfs=dict(
  1623. directory='/exports',
  1624. options='*(rw,root_squash)'
  1625. ),
  1626. host=None,
  1627. access=dict(
  1628. modes=['ReadWriteOnce']
  1629. ),
  1630. create_pv=True,
  1631. create_pvc=False
  1632. )
  1633. ),
  1634. registry=dict(
  1635. storage=dict(
  1636. kind=None,
  1637. volume=dict(
  1638. name='registry',
  1639. size='5Gi'
  1640. ),
  1641. nfs=dict(
  1642. directory='/exports',
  1643. options='*(rw,root_squash)'),
  1644. glusterfs=dict(
  1645. endpoints='glusterfs-registry-endpoints',
  1646. path='glusterfs-registry-volume',
  1647. readOnly=False,
  1648. swap=False,
  1649. swapcopy=True),
  1650. host=None,
  1651. access=dict(
  1652. modes=['ReadWriteMany']
  1653. ),
  1654. create_pv=True,
  1655. create_pvc=True
  1656. )
  1657. ),
  1658. router=dict()
  1659. )
  1660. defaults['logging'] = dict(
  1661. storage=dict(
  1662. kind=None,
  1663. volume=dict(
  1664. name='logging-es',
  1665. size='10Gi'
  1666. ),
  1667. nfs=dict(
  1668. directory='/exports',
  1669. options='*(rw,root_squash)'
  1670. ),
  1671. host=None,
  1672. access=dict(
  1673. modes=['ReadWriteOnce']
  1674. ),
  1675. create_pv=True,
  1676. create_pvc=False
  1677. )
  1678. )
  1679. defaults['loggingops'] = dict(
  1680. storage=dict(
  1681. kind=None,
  1682. volume=dict(
  1683. name='logging-es-ops',
  1684. size='10Gi'
  1685. ),
  1686. nfs=dict(
  1687. directory='/exports',
  1688. options='*(rw,root_squash)'
  1689. ),
  1690. host=None,
  1691. access=dict(
  1692. modes=['ReadWriteOnce']
  1693. ),
  1694. create_pv=True,
  1695. create_pvc=False
  1696. )
  1697. )
  1698. defaults['metrics'] = dict(
  1699. deploy=False,
  1700. duration=7,
  1701. resolution='10s',
  1702. storage=dict(
  1703. kind=None,
  1704. volume=dict(
  1705. name='metrics',
  1706. size='10Gi'
  1707. ),
  1708. nfs=dict(
  1709. directory='/exports',
  1710. options='*(rw,root_squash)'
  1711. ),
  1712. host=None,
  1713. access=dict(
  1714. modes=['ReadWriteOnce']
  1715. ),
  1716. create_pv=True,
  1717. create_pvc=False
  1718. )
  1719. )
  1720. defaults['prometheus'] = dict(
  1721. storage=dict(
  1722. kind=None,
  1723. volume=dict(
  1724. name='prometheus',
  1725. size='10Gi'
  1726. ),
  1727. nfs=dict(
  1728. directory='/exports',
  1729. options='*(rw,root_squash)'
  1730. ),
  1731. host=None,
  1732. access=dict(
  1733. modes=['ReadWriteOnce']
  1734. ),
  1735. create_pv=True,
  1736. create_pvc=False
  1737. )
  1738. )
  1739. defaults['prometheus']['alertmanager'] = dict(
  1740. storage=dict(
  1741. kind=None,
  1742. volume=dict(
  1743. name='prometheus-alertmanager',
  1744. size='10Gi'
  1745. ),
  1746. nfs=dict(
  1747. directory='/exports',
  1748. options='*(rw,root_squash)'
  1749. ),
  1750. host=None,
  1751. access=dict(
  1752. modes=['ReadWriteOnce']
  1753. ),
  1754. create_pv=True,
  1755. create_pvc=False
  1756. )
  1757. )
  1758. defaults['prometheus']['alertbuffer'] = dict(
  1759. storage=dict(
  1760. kind=None,
  1761. volume=dict(
  1762. name='prometheus-alertbuffer',
  1763. size='10Gi'
  1764. ),
  1765. nfs=dict(
  1766. directory='/exports',
  1767. options='*(rw,root_squash)'
  1768. ),
  1769. host=None,
  1770. access=dict(
  1771. modes=['ReadWriteOnce']
  1772. ),
  1773. create_pv=True,
  1774. create_pvc=False
  1775. )
  1776. )
  1777. return defaults
  1778. def guess_host_provider(self):
  1779. """ Guess the host provider
  1780. Returns:
  1781. dict: The generated default facts for the detected provider
  1782. """
  1783. # TODO: cloud provider facts should probably be submitted upstream
  1784. product_name = self.system_facts['ansible_product_name']
  1785. product_version = self.system_facts['ansible_product_version']
  1786. virt_type = self.system_facts['ansible_virtualization_type']
  1787. virt_role = self.system_facts['ansible_virtualization_role']
  1788. bios_vendor = self.system_facts['ansible_system_vendor']
  1789. provider = None
  1790. metadata = None
  1791. if bios_vendor == 'Google':
  1792. provider = 'gce'
  1793. metadata_url = ('http://metadata.google.internal/'
  1794. 'computeMetadata/v1/?recursive=true')
  1795. headers = {'Metadata-Flavor': 'Google'}
  1796. metadata = get_provider_metadata(metadata_url, True, headers,
  1797. True)
  1798. # Filter sshKeys and serviceAccounts from gce metadata
  1799. if metadata:
  1800. metadata['project']['attributes'].pop('sshKeys', None)
  1801. metadata['instance'].pop('serviceAccounts', None)
  1802. elif virt_type == 'xen' and virt_role == 'guest' and re.match(r'.*\.amazon$', product_version):
  1803. provider = 'aws'
  1804. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1805. metadata = get_provider_metadata(metadata_url)
  1806. elif re.search(r'OpenStack', product_name):
  1807. provider = 'openstack'
  1808. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1809. 'meta_data.json')
  1810. metadata = get_provider_metadata(metadata_url, True, None,
  1811. True)
  1812. if metadata:
  1813. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1814. metadata['ec2_compat'] = get_provider_metadata(
  1815. ec2_compat_url
  1816. )
  1817. # disable pylint maybe-no-member because overloaded use of
  1818. # the module name causes pylint to not detect that results
  1819. # is an array or hash
  1820. # pylint: disable=maybe-no-member
  1821. # Filter public_keys and random_seed from openstack metadata
  1822. metadata.pop('public_keys', None)
  1823. metadata.pop('random_seed', None)
  1824. if not metadata['ec2_compat']:
  1825. metadata = None
  1826. return dict(name=provider, metadata=metadata)
  1827. def init_provider_facts(self):
  1828. """ Initialize the provider facts
  1829. Returns:
  1830. dict: The normalized provider facts
  1831. """
  1832. provider_info = self.guess_host_provider()
  1833. provider_facts = normalize_provider_facts(
  1834. provider_info.get('name'),
  1835. provider_info.get('metadata')
  1836. )
  1837. return provider_facts
  1838. @staticmethod
  1839. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1840. """ Split openshift_env facts based on openshift_env structures.
  1841. Args:
  1842. openshift_env_fact (string): the openshift_env fact to split
  1843. ex: 'openshift_cloudprovider_openstack_auth_url'
  1844. openshift_env_structures (list): a list of structures to determine fact keys
  1845. ex: ['openshift.cloudprovider.openstack.*']
  1846. Returns:
  1847. list: a list of keys that represent the fact
  1848. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1849. """
  1850. # By default, we'll split an openshift_env fact by underscores.
  1851. fact_keys = openshift_env_fact.split('_')
  1852. # Determine if any of the provided variable structures match the fact.
  1853. matching_structure = None
  1854. if openshift_env_structures is not None:
  1855. for structure in openshift_env_structures:
  1856. if re.match(structure, openshift_env_fact):
  1857. matching_structure = structure
  1858. # Fact didn't match any variable structures so return the default fact keys.
  1859. if matching_structure is None:
  1860. return fact_keys
  1861. final_keys = []
  1862. structure_keys = matching_structure.split('.')
  1863. for structure_key in structure_keys:
  1864. # Matched current key. Add to final keys.
  1865. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1866. final_keys.append(structure_key)
  1867. # Wildcard means we will be taking everything from here to the end of the fact.
  1868. elif structure_key == '*':
  1869. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1870. # Shouldn't have gotten here, return the fact keys.
  1871. else:
  1872. return fact_keys
  1873. return final_keys
  1874. # Disabling too-many-branches and too-many-locals.
  1875. # This should be cleaned up as a TODO item.
  1876. # pylint: disable=too-many-branches, too-many-locals
  1877. def init_local_facts(self, facts=None,
  1878. additive_facts_to_overwrite=None,
  1879. openshift_env=None,
  1880. openshift_env_structures=None,
  1881. protected_facts_to_overwrite=None):
  1882. """ Initialize the local facts
  1883. Args:
  1884. facts (dict): local facts to set
  1885. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1886. '.' notation ex: ['master.named_certificates']
  1887. openshift_env (dict): openshift env facts to set
  1888. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1889. '.' notation ex: ['master.master_count']
  1890. Returns:
  1891. dict: The result of merging the provided facts with existing
  1892. local facts
  1893. """
  1894. changed = False
  1895. facts_to_set = dict()
  1896. if facts is not None:
  1897. facts_to_set[self.role] = facts
  1898. if openshift_env != {} and openshift_env is not None:
  1899. for fact, value in iteritems(openshift_env):
  1900. oo_env_facts = dict()
  1901. current_level = oo_env_facts
  1902. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1903. if len(keys) > 0 and keys[0] != self.role:
  1904. continue
  1905. # Build a dictionary from the split fact keys.
  1906. # After this loop oo_env_facts is the resultant dictionary.
  1907. # For example:
  1908. # fact = "openshift_metrics_install_metrics"
  1909. # value = 'true'
  1910. # keys = ['metrics', 'install', 'metrics']
  1911. # result = {'metrics': {'install': {'metrics': 'true'}}}
  1912. for i, _ in enumerate(keys):
  1913. # This is the last key. Set the value.
  1914. if i == (len(keys) - 1):
  1915. current_level[keys[i]] = value
  1916. # This is a key other than the last key. Set as
  1917. # dictionary and continue.
  1918. else:
  1919. current_level[keys[i]] = dict()
  1920. current_level = current_level[keys[i]]
  1921. facts_to_set = merge_facts(orig=facts_to_set,
  1922. new=oo_env_facts,
  1923. additive_facts_to_overwrite=[],
  1924. protected_facts_to_overwrite=[])
  1925. local_facts = get_local_facts_from_file(self.filename)
  1926. migrated_facts = migrate_local_facts(local_facts)
  1927. new_local_facts = merge_facts(migrated_facts,
  1928. facts_to_set,
  1929. additive_facts_to_overwrite,
  1930. protected_facts_to_overwrite)
  1931. if 'docker' in new_local_facts:
  1932. # Convert legacy log_options comma sep string to a list if present:
  1933. if 'log_options' in new_local_facts['docker'] and \
  1934. isinstance(new_local_facts['docker']['log_options'], string_types):
  1935. new_local_facts['docker']['log_options'] = new_local_facts['docker']['log_options'].split(',')
  1936. new_local_facts = self.remove_empty_facts(new_local_facts)
  1937. if new_local_facts != local_facts:
  1938. self.validate_local_facts(new_local_facts)
  1939. changed = True
  1940. if not module.check_mode: # noqa: F405
  1941. save_local_facts(self.filename, new_local_facts)
  1942. self.changed = changed
  1943. return new_local_facts
  1944. def remove_empty_facts(self, facts=None):
  1945. """ Remove empty facts
  1946. Args:
  1947. facts (dict): facts to clean
  1948. """
  1949. facts_to_remove = []
  1950. for fact, value in iteritems(facts):
  1951. if isinstance(facts[fact], dict):
  1952. facts[fact] = self.remove_empty_facts(facts[fact])
  1953. else:
  1954. if value == "" or value == [""] or value is None:
  1955. facts_to_remove.append(fact)
  1956. for fact in facts_to_remove:
  1957. del facts[fact]
  1958. return facts
  1959. def validate_local_facts(self, facts=None):
  1960. """ Validate local facts
  1961. Args:
  1962. facts (dict): local facts to validate
  1963. """
  1964. invalid_facts = dict()
  1965. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1966. if invalid_facts:
  1967. msg = 'Invalid facts detected:\n'
  1968. # pylint: disable=consider-iterating-dictionary
  1969. for key in invalid_facts.keys():
  1970. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1971. module.fail_json(msg=msg, changed=self.changed) # noqa: F405
  1972. # disabling pylint errors for line-too-long since we're dealing
  1973. # with best effort reduction of error messages here.
  1974. # disabling errors for too-many-branches since we require checking
  1975. # many conditions.
  1976. # pylint: disable=line-too-long, too-many-branches
  1977. @staticmethod
  1978. def validate_master_facts(facts, invalid_facts):
  1979. """ Validate master facts
  1980. Args:
  1981. facts (dict): local facts to validate
  1982. invalid_facts (dict): collected invalid_facts
  1983. Returns:
  1984. dict: Invalid facts
  1985. """
  1986. if 'master' in facts:
  1987. # openshift.master.session_auth_secrets
  1988. if 'session_auth_secrets' in facts['master']:
  1989. session_auth_secrets = facts['master']['session_auth_secrets']
  1990. if not issubclass(type(session_auth_secrets), list):
  1991. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1992. elif 'session_encryption_secrets' not in facts['master']:
  1993. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1994. 'if openshift_master_session_auth_secrets is provided.')
  1995. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1996. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1997. 'openshift_master_session_encryption_secrets must be '
  1998. 'equal length.')
  1999. else:
  2000. for secret in session_auth_secrets:
  2001. if len(secret) < 32:
  2002. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  2003. 'Secrets must be at least 32 characters in length.')
  2004. # openshift.master.session_encryption_secrets
  2005. if 'session_encryption_secrets' in facts['master']:
  2006. session_encryption_secrets = facts['master']['session_encryption_secrets']
  2007. if not issubclass(type(session_encryption_secrets), list):
  2008. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  2009. elif 'session_auth_secrets' not in facts['master']:
  2010. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  2011. 'set if openshift_master_session_encryption_secrets '
  2012. 'is provided.')
  2013. else:
  2014. for secret in session_encryption_secrets:
  2015. if len(secret) not in [16, 24, 32]:
  2016. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  2017. 'Secrets must be 16, 24, or 32 characters in length.')
  2018. return invalid_facts
  2019. def main():
  2020. """ main """
  2021. # disabling pylint errors for global-variable-undefined and invalid-name
  2022. # for 'global module' usage, since it is required to use ansible_facts
  2023. # pylint: disable=global-variable-undefined, invalid-name
  2024. global module
  2025. module = AnsibleModule( # noqa: F405
  2026. argument_spec=dict(
  2027. role=dict(default='common', required=False,
  2028. choices=OpenShiftFacts.known_roles),
  2029. local_facts=dict(default=None, type='dict', required=False),
  2030. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  2031. openshift_env=dict(default={}, type='dict', required=False),
  2032. openshift_env_structures=dict(default=[], type='list', required=False),
  2033. protected_facts_to_overwrite=dict(default=[], type='list', required=False)
  2034. ),
  2035. supports_check_mode=True,
  2036. add_file_common_args=True,
  2037. )
  2038. if not HAVE_DBUS:
  2039. module.fail_json(msg="This module requires dbus python bindings") # noqa: F405
  2040. module.params['gather_subset'] = ['hardware', 'network', 'virtual', 'facter'] # noqa: F405
  2041. module.params['gather_timeout'] = 10 # noqa: F405
  2042. module.params['filter'] = '*' # noqa: F405
  2043. role = module.params['role'] # noqa: F405
  2044. local_facts = module.params['local_facts'] # noqa: F405
  2045. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite'] # noqa: F405
  2046. openshift_env = module.params['openshift_env'] # noqa: F405
  2047. openshift_env_structures = module.params['openshift_env_structures'] # noqa: F405
  2048. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite'] # noqa: F405
  2049. fact_file = '/etc/ansible/facts.d/openshift.fact'
  2050. openshift_facts = OpenShiftFacts(role,
  2051. fact_file,
  2052. local_facts,
  2053. additive_facts_to_overwrite,
  2054. openshift_env,
  2055. openshift_env_structures,
  2056. protected_facts_to_overwrite)
  2057. file_params = module.params.copy() # noqa: F405
  2058. file_params['path'] = fact_file
  2059. file_args = module.load_file_common_arguments(file_params) # noqa: F405
  2060. changed = module.set_fs_attributes_if_different(file_args, # noqa: F405
  2061. openshift_facts.changed)
  2062. return module.exit_json(changed=changed, # noqa: F405
  2063. ansible_facts=openshift_facts.facts)
  2064. if __name__ == '__main__':
  2065. main()