openshift_facts.py 99 KB

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