openshift_facts.py 97 KB

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