openshift_facts.py 93 KB

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