openshift_facts.py 96 KB

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