openshift_facts.py 74 KB

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