openshift_facts.py 96 KB

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