openshift_facts.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. #!/usr/bin/python
  2. # pylint: disable=too-many-lines
  3. # -*- coding: utf-8 -*-
  4. # vim: expandtab:tabstop=4:shiftwidth=4
  5. # Reason: Disable pylint too-many-lines because we don't want to split up this file.
  6. # Status: Permanently disabled to keep this module as self-contained as possible.
  7. """Ansible module for retrieving and setting openshift related facts"""
  8. DOCUMENTATION = '''
  9. ---
  10. module: openshift_facts
  11. short_description: Cluster Facts
  12. author: Jason DeTiberus
  13. requirements: [ ]
  14. '''
  15. EXAMPLES = '''
  16. '''
  17. import ConfigParser
  18. import copy
  19. import os
  20. import StringIO
  21. import yaml
  22. from distutils.util import strtobool
  23. from distutils.version import LooseVersion
  24. import struct
  25. import socket
  26. def first_ip(network):
  27. """ Return the first IPv4 address in network
  28. Args:
  29. network (str): network in CIDR format
  30. Returns:
  31. str: first IPv4 address
  32. """
  33. atoi = lambda addr: struct.unpack("!I", socket.inet_aton(addr))[0]
  34. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr))
  35. (address, netmask) = network.split('/')
  36. netmask_i = (0xffffffff << (32 - atoi(netmask))) & 0xffffffff
  37. return itoa((atoi(address) & netmask_i) + 1)
  38. def hostname_valid(hostname):
  39. """ Test if specified hostname should be considered valid
  40. Args:
  41. hostname (str): hostname to test
  42. Returns:
  43. bool: True if valid, otherwise False
  44. """
  45. if (not hostname or
  46. hostname.startswith('localhost') or
  47. hostname.endswith('localdomain') or
  48. len(hostname.split('.')) < 2):
  49. return False
  50. return True
  51. def choose_hostname(hostnames=None, fallback=''):
  52. """ Choose a hostname from the provided hostnames
  53. Given a list of hostnames and a fallback value, choose a hostname to
  54. use. This function will prefer fqdns if they exist (excluding any that
  55. begin with localhost or end with localdomain) over ip addresses.
  56. Args:
  57. hostnames (list): list of hostnames
  58. fallback (str): default value to set if hostnames does not contain
  59. a valid hostname
  60. Returns:
  61. str: chosen hostname
  62. """
  63. hostname = fallback
  64. if hostnames is None:
  65. return hostname
  66. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  67. ips = [i for i in hostnames
  68. if (i is not None and isinstance(i, basestring)
  69. and re.match(ip_regex, i))]
  70. hosts = [i for i in hostnames
  71. if i is not None and i != '' and i not in ips]
  72. for host_list in (hosts, ips):
  73. for host in host_list:
  74. if hostname_valid(host):
  75. return host
  76. return hostname
  77. def query_metadata(metadata_url, headers=None, expect_json=False):
  78. """ Return metadata from the provided metadata_url
  79. Args:
  80. metadata_url (str): metadata url
  81. headers (dict): headers to set for metadata request
  82. expect_json (bool): does the metadata_url return json
  83. Returns:
  84. dict or list: metadata request result
  85. """
  86. result, info = fetch_url(module, metadata_url, headers=headers)
  87. if info['status'] != 200:
  88. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  89. if expect_json:
  90. return module.from_json(result.read())
  91. else:
  92. return [line.strip() for line in result.readlines()]
  93. def walk_metadata(metadata_url, headers=None, expect_json=False):
  94. """ Walk the metadata tree and return a dictionary of the entire tree
  95. Args:
  96. metadata_url (str): metadata url
  97. headers (dict): headers to set for metadata request
  98. expect_json (bool): does the metadata_url return json
  99. Returns:
  100. dict: the result of walking the metadata tree
  101. """
  102. metadata = dict()
  103. for line in query_metadata(metadata_url, headers, expect_json):
  104. if line.endswith('/') and not line == 'public-keys/':
  105. key = line[:-1]
  106. metadata[key] = walk_metadata(metadata_url + line,
  107. headers, expect_json)
  108. else:
  109. results = query_metadata(metadata_url + line, headers,
  110. expect_json)
  111. if len(results) == 1:
  112. # disable pylint maybe-no-member because overloaded use of
  113. # the module name causes pylint to not detect that results
  114. # is an array or hash
  115. # pylint: disable=maybe-no-member
  116. metadata[line] = results.pop()
  117. else:
  118. metadata[line] = results
  119. return metadata
  120. def get_provider_metadata(metadata_url, supports_recursive=False,
  121. headers=None, expect_json=False):
  122. """ Retrieve the provider metadata
  123. Args:
  124. metadata_url (str): metadata url
  125. supports_recursive (bool): does the provider metadata api support
  126. recursion
  127. headers (dict): headers to set for metadata request
  128. expect_json (bool): does the metadata_url return json
  129. Returns:
  130. dict: the provider metadata
  131. """
  132. try:
  133. if supports_recursive:
  134. metadata = query_metadata(metadata_url, headers,
  135. expect_json)
  136. else:
  137. metadata = walk_metadata(metadata_url, headers,
  138. expect_json)
  139. except OpenShiftFactsMetadataUnavailableError:
  140. metadata = None
  141. return metadata
  142. def normalize_gce_facts(metadata, facts):
  143. """ Normalize gce facts
  144. Args:
  145. metadata (dict): provider metadata
  146. facts (dict): facts to update
  147. Returns:
  148. dict: the result of adding the normalized metadata to the provided
  149. facts dict
  150. """
  151. for interface in metadata['instance']['networkInterfaces']:
  152. int_info = dict(ips=[interface['ip']], network_type='gce')
  153. int_info['public_ips'] = [ac['externalIp'] for ac
  154. in interface['accessConfigs']]
  155. int_info['public_ips'].extend(interface['forwardedIps'])
  156. _, _, network_id = interface['network'].rpartition('/')
  157. int_info['network_id'] = network_id
  158. facts['network']['interfaces'].append(int_info)
  159. _, _, zone = metadata['instance']['zone'].rpartition('/')
  160. facts['zone'] = zone
  161. # GCE currently only supports a single interface
  162. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  163. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  164. facts['network']['public_ip'] = pub_ip
  165. facts['network']['hostname'] = metadata['instance']['hostname']
  166. # TODO: attempt to resolve public_hostname
  167. facts['network']['public_hostname'] = facts['network']['public_ip']
  168. return facts
  169. def normalize_aws_facts(metadata, facts):
  170. """ Normalize aws facts
  171. Args:
  172. metadata (dict): provider metadata
  173. facts (dict): facts to update
  174. Returns:
  175. dict: the result of adding the normalized metadata to the provided
  176. facts dict
  177. """
  178. for interface in sorted(
  179. metadata['network']['interfaces']['macs'].values(),
  180. key=lambda x: x['device-number']
  181. ):
  182. int_info = dict()
  183. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  184. for ips_var, int_var in var_map.iteritems():
  185. ips = interface.get(int_var)
  186. if isinstance(ips, basestring):
  187. int_info[ips_var] = [ips]
  188. else:
  189. int_info[ips_var] = ips
  190. if 'vpc-id' in interface:
  191. int_info['network_type'] = 'vpc'
  192. else:
  193. int_info['network_type'] = 'classic'
  194. if int_info['network_type'] == 'vpc':
  195. int_info['network_id'] = interface['subnet-id']
  196. else:
  197. int_info['network_id'] = None
  198. facts['network']['interfaces'].append(int_info)
  199. facts['zone'] = metadata['placement']['availability-zone']
  200. # TODO: actually attempt to determine default local and public ips
  201. # by using the ansible default ip fact and the ipv4-associations
  202. # from the ec2 metadata
  203. facts['network']['ip'] = metadata.get('local-ipv4')
  204. facts['network']['public_ip'] = metadata.get('public-ipv4')
  205. # TODO: verify that local hostname makes sense and is resolvable
  206. facts['network']['hostname'] = metadata.get('local-hostname')
  207. # TODO: verify that public hostname makes sense and is resolvable
  208. facts['network']['public_hostname'] = metadata.get('public-hostname')
  209. return facts
  210. def normalize_openstack_facts(metadata, facts):
  211. """ Normalize openstack 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. # openstack ec2 compat api does not support network interfaces and
  220. # the version tested on did not include the info in the openstack
  221. # metadata api, should be updated if neutron exposes this.
  222. facts['zone'] = metadata['availability_zone']
  223. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  224. facts['network']['ip'] = local_ipv4
  225. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  226. # TODO: verify local hostname makes sense and is resolvable
  227. facts['network']['hostname'] = metadata['hostname']
  228. # TODO: verify that public hostname makes sense and is resolvable
  229. pub_h = metadata['ec2_compat']['public-hostname']
  230. facts['network']['public_hostname'] = pub_h
  231. return facts
  232. def normalize_provider_facts(provider, metadata):
  233. """ Normalize provider facts
  234. Args:
  235. provider (str): host provider
  236. metadata (dict): provider metadata
  237. Returns:
  238. dict: the normalized provider facts
  239. """
  240. if provider is None or metadata is None:
  241. return {}
  242. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  243. # and configure ipv6 facts if available
  244. # TODO: add support for setting user_data if available
  245. facts = dict(name=provider, metadata=metadata,
  246. network=dict(interfaces=[], ipv6_enabled=False))
  247. if provider == 'gce':
  248. facts = normalize_gce_facts(metadata, facts)
  249. elif provider == 'ec2':
  250. facts = normalize_aws_facts(metadata, facts)
  251. elif provider == 'openstack':
  252. facts = normalize_openstack_facts(metadata, facts)
  253. return facts
  254. def set_fluentd_facts_if_unset(facts):
  255. """ Set fluentd facts if not already present in facts dict
  256. dict: the facts dict updated with the generated fluentd facts if
  257. missing
  258. Args:
  259. facts (dict): existing facts
  260. Returns:
  261. dict: the facts dict updated with the generated fluentd
  262. facts if they were not already present
  263. """
  264. if 'common' in facts:
  265. if 'use_fluentd' not in facts['common']:
  266. use_fluentd = False
  267. facts['common']['use_fluentd'] = use_fluentd
  268. return facts
  269. def set_flannel_facts_if_unset(facts):
  270. """ Set flannel facts if not already present in facts dict
  271. dict: the facts dict updated with the flannel facts if
  272. missing
  273. Args:
  274. facts (dict): existing facts
  275. Returns:
  276. dict: the facts dict updated with the flannel
  277. facts if they were not already present
  278. """
  279. if 'common' in facts:
  280. if 'use_flannel' not in facts['common']:
  281. use_flannel = False
  282. facts['common']['use_flannel'] = use_flannel
  283. return facts
  284. def set_node_schedulability(facts):
  285. """ Set schedulable facts if not already present in facts dict
  286. Args:
  287. facts (dict): existing facts
  288. Returns:
  289. dict: the facts dict updated with the generated schedulable
  290. facts if they were not already present
  291. """
  292. if 'node' in facts:
  293. if 'schedulable' not in facts['node']:
  294. if 'master' in facts:
  295. facts['node']['schedulable'] = False
  296. else:
  297. facts['node']['schedulable'] = True
  298. return facts
  299. def set_master_selectors(facts):
  300. """ Set selectors facts if not already present in facts dict
  301. Args:
  302. facts (dict): existing facts
  303. Returns:
  304. dict: the facts dict updated with the generated selectors
  305. facts if they were not already present
  306. """
  307. if 'master' in facts:
  308. if 'infra_nodes' in facts['master']:
  309. deployment_type = facts['common']['deployment_type']
  310. if deployment_type == 'online':
  311. selector = "type=infra"
  312. else:
  313. selector = "region=infra"
  314. if 'router_selector' not in facts['master']:
  315. facts['master']['router_selector'] = selector
  316. if 'registry_selector' not in facts['master']:
  317. facts['master']['registry_selector'] = selector
  318. return facts
  319. def set_metrics_facts_if_unset(facts):
  320. """ Set cluster metrics facts if not already present in facts dict
  321. dict: the facts dict updated with the generated cluster metrics facts if
  322. missing
  323. Args:
  324. facts (dict): existing facts
  325. Returns:
  326. dict: the facts dict updated with the generated cluster metrics
  327. facts if they were not already present
  328. """
  329. if 'common' in facts:
  330. if 'use_cluster_metrics' not in facts['common']:
  331. use_cluster_metrics = False
  332. facts['common']['use_cluster_metrics'] = use_cluster_metrics
  333. return facts
  334. def set_project_cfg_facts_if_unset(facts):
  335. """ Set Project Configuration facts if not already present in facts dict
  336. dict:
  337. Args:
  338. facts (dict): existing facts
  339. Returns:
  340. dict: the facts dict updated with the generated Project Configuration
  341. facts if they were not already present
  342. """
  343. config = {
  344. 'default_node_selector': '',
  345. 'project_request_message': '',
  346. 'project_request_template': '',
  347. 'mcs_allocator_range': 's0:/2',
  348. 'mcs_labels_per_project': 5,
  349. 'uid_allocator_range': '1000000000-1999999999/10000'
  350. }
  351. if 'master' in facts:
  352. for key, value in config.items():
  353. if key not in facts['master']:
  354. facts['master'][key] = value
  355. return facts
  356. def set_identity_providers_if_unset(facts):
  357. """ Set identity_providers fact if not already present in facts dict
  358. Args:
  359. facts (dict): existing facts
  360. Returns:
  361. dict: the facts dict updated with the generated identity providers
  362. facts if they were not already present
  363. """
  364. if 'master' in facts:
  365. deployment_type = facts['common']['deployment_type']
  366. if 'identity_providers' not in facts['master']:
  367. identity_provider = dict(
  368. name='allow_all', challenge=True, login=True,
  369. kind='AllowAllPasswordIdentityProvider'
  370. )
  371. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  372. identity_provider = dict(
  373. name='deny_all', challenge=True, login=True,
  374. kind='DenyAllPasswordIdentityProvider'
  375. )
  376. facts['master']['identity_providers'] = [identity_provider]
  377. return facts
  378. def set_url_facts_if_unset(facts):
  379. """ Set url facts if not already present in facts dict
  380. Args:
  381. facts (dict): existing facts
  382. Returns:
  383. dict: the facts dict updated with the generated url facts if they
  384. were not already present
  385. """
  386. if 'master' in facts:
  387. api_use_ssl = facts['master']['api_use_ssl']
  388. api_port = facts['master']['api_port']
  389. console_use_ssl = facts['master']['console_use_ssl']
  390. console_port = facts['master']['console_port']
  391. console_path = facts['master']['console_path']
  392. etcd_use_ssl = facts['master']['etcd_use_ssl']
  393. etcd_hosts = facts['master']['etcd_hosts']
  394. etcd_port = facts['master']['etcd_port']
  395. hostname = facts['common']['hostname']
  396. public_hostname = facts['common']['public_hostname']
  397. cluster_hostname = facts['master'].get('cluster_hostname')
  398. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  399. if 'etcd_urls' not in facts['master']:
  400. etcd_urls = []
  401. if etcd_hosts != '':
  402. facts['master']['etcd_port'] = etcd_port
  403. facts['master']['embedded_etcd'] = False
  404. for host in etcd_hosts:
  405. etcd_urls.append(format_url(etcd_use_ssl, host,
  406. etcd_port))
  407. else:
  408. etcd_urls = [format_url(etcd_use_ssl, hostname,
  409. etcd_port)]
  410. facts['master']['etcd_urls'] = etcd_urls
  411. if 'api_url' not in facts['master']:
  412. api_hostname = cluster_hostname if cluster_hostname else hostname
  413. facts['master']['api_url'] = format_url(api_use_ssl, api_hostname,
  414. api_port)
  415. if 'public_api_url' not in facts['master']:
  416. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  417. facts['master']['public_api_url'] = format_url(api_use_ssl,
  418. api_public_hostname,
  419. api_port)
  420. if 'console_url' not in facts['master']:
  421. console_hostname = cluster_hostname if cluster_hostname else hostname
  422. facts['master']['console_url'] = format_url(console_use_ssl,
  423. console_hostname,
  424. console_port,
  425. console_path)
  426. if 'public_console_url' not in facts['master']:
  427. console_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  428. facts['master']['public_console_url'] = format_url(console_use_ssl,
  429. console_public_hostname,
  430. console_port,
  431. console_path)
  432. return facts
  433. def set_aggregate_facts(facts):
  434. """ Set aggregate facts
  435. Args:
  436. facts (dict): existing facts
  437. Returns:
  438. dict: the facts dict updated with aggregated facts
  439. """
  440. all_hostnames = set()
  441. internal_hostnames = set()
  442. if 'common' in facts:
  443. all_hostnames.add(facts['common']['hostname'])
  444. all_hostnames.add(facts['common']['public_hostname'])
  445. all_hostnames.add(facts['common']['ip'])
  446. all_hostnames.add(facts['common']['public_ip'])
  447. internal_hostnames.add(facts['common']['hostname'])
  448. internal_hostnames.add(facts['common']['ip'])
  449. cluster_domain = facts['common']['dns_domain']
  450. if 'master' in facts:
  451. if 'cluster_hostname' in facts['master']:
  452. all_hostnames.add(facts['master']['cluster_hostname'])
  453. if 'cluster_public_hostname' in facts['master']:
  454. all_hostnames.add(facts['master']['cluster_public_hostname'])
  455. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  456. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  457. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  458. all_hostnames.update(svc_names)
  459. internal_hostnames.update(svc_names)
  460. first_svc_ip = first_ip(facts['master']['portal_net'])
  461. all_hostnames.add(first_svc_ip)
  462. internal_hostnames.add(first_svc_ip)
  463. facts['common']['all_hostnames'] = list(all_hostnames)
  464. facts['common']['internal_hostnames'] = list(internal_hostnames)
  465. return facts
  466. def set_etcd_facts_if_unset(facts):
  467. """
  468. If using embedded etcd, loads the data directory from master-config.yaml.
  469. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  470. If anything goes wrong parsing these, the fact will not be set.
  471. """
  472. if 'master' in facts and facts['master']['embedded_etcd']:
  473. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  474. if 'etcd_data_dir' not in etcd_facts:
  475. try:
  476. # Parse master config to find actual etcd data dir:
  477. master_cfg_path = os.path.join(facts['common']['config_base'],
  478. 'master/master-config.yaml')
  479. master_cfg_f = open(master_cfg_path, 'r')
  480. config = yaml.safe_load(master_cfg_f.read())
  481. master_cfg_f.close()
  482. etcd_facts['etcd_data_dir'] = \
  483. config['etcdConfig']['storageDirectory']
  484. facts['etcd'] = etcd_facts
  485. # We don't want exceptions bubbling up here:
  486. # pylint: disable=broad-except
  487. except Exception:
  488. pass
  489. else:
  490. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  491. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  492. try:
  493. # Add a fake section for parsing:
  494. ini_str = '[root]\n' + open('/etc/etcd/etcd.conf', 'r').read()
  495. ini_fp = StringIO.StringIO(ini_str)
  496. config = ConfigParser.RawConfigParser()
  497. config.readfp(ini_fp)
  498. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  499. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  500. etcd_data_dir = etcd_data_dir[1:-1]
  501. etcd_facts['etcd_data_dir'] = etcd_data_dir
  502. facts['etcd'] = etcd_facts
  503. # We don't want exceptions bubbling up here:
  504. # pylint: disable=broad-except
  505. except Exception:
  506. pass
  507. return facts
  508. def set_deployment_facts_if_unset(facts):
  509. """ Set Facts that vary based on deployment_type. This currently
  510. includes common.service_type, common.config_base, master.registry_url,
  511. node.registry_url, node.storage_plugin_deps
  512. Args:
  513. facts (dict): existing facts
  514. Returns:
  515. dict: the facts dict updated with the generated deployment_type
  516. facts
  517. """
  518. # disabled to avoid breaking up facts related to deployment type into
  519. # multiple methods for now.
  520. # pylint: disable=too-many-statements, too-many-branches
  521. if 'common' in facts:
  522. deployment_type = facts['common']['deployment_type']
  523. if 'service_type' not in facts['common']:
  524. service_type = 'atomic-openshift'
  525. if deployment_type == 'origin':
  526. service_type = 'origin'
  527. elif deployment_type in ['enterprise']:
  528. service_type = 'openshift'
  529. facts['common']['service_type'] = service_type
  530. if 'config_base' not in facts['common']:
  531. config_base = '/etc/origin'
  532. if deployment_type in ['enterprise']:
  533. config_base = '/etc/openshift'
  534. # Handle upgrade scenarios when symlinks don't yet exist:
  535. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  536. config_base = '/etc/openshift'
  537. facts['common']['config_base'] = config_base
  538. if 'data_dir' not in facts['common']:
  539. data_dir = '/var/lib/origin'
  540. if deployment_type in ['enterprise']:
  541. data_dir = '/var/lib/openshift'
  542. # Handle upgrade scenarios when symlinks don't yet exist:
  543. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  544. data_dir = '/var/lib/openshift'
  545. facts['common']['data_dir'] = data_dir
  546. # remove duplicate and empty strings from registry lists
  547. for cat in ['additional', 'blocked', 'insecure']:
  548. key = 'docker_{0}_registries'.format(cat)
  549. if key in facts['common']:
  550. facts['common'][key] = list(set(facts['common'][key]) - set(['']))
  551. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  552. addtl_regs = facts['common'].get('docker_additional_registries', [])
  553. ent_reg = 'registry.access.redhat.com'
  554. if ent_reg not in addtl_regs:
  555. facts['common']['docker_additional_registries'] = addtl_regs + [ent_reg]
  556. for role in ('master', 'node'):
  557. if role in facts:
  558. deployment_type = facts['common']['deployment_type']
  559. if 'registry_url' not in facts[role]:
  560. registry_url = 'openshift/origin-${component}:${version}'
  561. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  562. registry_url = 'openshift3/ose-${component}:${version}'
  563. elif deployment_type == 'atomic-enterprise':
  564. registry_url = 'aep3_beta/aep-${component}:${version}'
  565. facts[role]['registry_url'] = registry_url
  566. if 'master' in facts:
  567. deployment_type = facts['common']['deployment_type']
  568. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  569. if 'disabled_features' in facts['master']:
  570. if deployment_type == 'atomic-enterprise':
  571. curr_disabled_features = set(facts['master']['disabled_features'])
  572. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  573. else:
  574. if deployment_type == 'atomic-enterprise':
  575. facts['master']['disabled_features'] = openshift_features
  576. if 'node' in facts:
  577. deployment_type = facts['common']['deployment_type']
  578. if 'storage_plugin_deps' not in facts['node']:
  579. if deployment_type in ['openshift-enterprise', 'atomic-enterprise']:
  580. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs']
  581. else:
  582. facts['node']['storage_plugin_deps'] = []
  583. return facts
  584. def set_version_facts_if_unset(facts):
  585. """ Set version facts. This currently includes common.version and
  586. common.version_greater_than_3_1_or_1_1.
  587. Args:
  588. facts (dict): existing facts
  589. Returns:
  590. dict: the facts dict updated with version facts.
  591. """
  592. if 'common' in facts:
  593. deployment_type = facts['common']['deployment_type']
  594. facts['common']['version'] = version = get_openshift_version()
  595. if version is not None:
  596. if deployment_type == 'origin':
  597. version_gt_3_1_or_1_1 = LooseVersion(version) > LooseVersion('1.0.6')
  598. version_gt_3_1_1_or_1_1_1 = LooseVersion(version) > LooseVersion('1.1.1')
  599. else:
  600. version_gt_3_1_or_1_1 = LooseVersion(version) > LooseVersion('3.0.2.900')
  601. version_gt_3_1_1_or_1_1_1 = LooseVersion(version) > LooseVersion('3.1.1')
  602. else:
  603. version_gt_3_1_or_1_1 = True
  604. version_gt_3_1_1_or_1_1_1 = True
  605. facts['common']['version_greater_than_3_1_or_1_1'] = version_gt_3_1_or_1_1
  606. facts['common']['version_greater_than_3_1_1_or_1_1_1'] = version_gt_3_1_1_or_1_1_1
  607. return facts
  608. def set_manageiq_facts_if_unset(facts):
  609. """ Set manageiq facts. This currently includes common.use_manageiq.
  610. Args:
  611. facts (dict): existing facts
  612. Returns:
  613. dict: the facts dict updated with version facts.
  614. Raises:
  615. OpenShiftFactsInternalError:
  616. """
  617. if 'common' not in facts:
  618. if 'version_greater_than_3_1_or_1_1' not in facts['common']:
  619. raise OpenShiftFactsInternalError(
  620. "Invalid invocation: The required facts are not set"
  621. )
  622. if 'use_manageiq' not in facts['common']:
  623. facts['common']['use_manageiq'] = facts['common']['version_greater_than_3_1_or_1_1']
  624. return facts
  625. def set_sdn_facts_if_unset(facts, system_facts):
  626. """ Set sdn facts if not already present in facts dict
  627. Args:
  628. facts (dict): existing facts
  629. system_facts (dict): ansible_facts
  630. Returns:
  631. dict: the facts dict updated with the generated sdn facts if they
  632. were not already present
  633. """
  634. if 'common' in facts:
  635. use_sdn = facts['common']['use_openshift_sdn']
  636. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  637. use_sdn = bool(strtobool(str(use_sdn)))
  638. facts['common']['use_openshift_sdn'] = use_sdn
  639. if 'sdn_network_plugin_name' not in facts['common']:
  640. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  641. facts['common']['sdn_network_plugin_name'] = plugin
  642. if 'master' in facts:
  643. if 'sdn_cluster_network_cidr' not in facts['master']:
  644. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  645. if 'sdn_host_subnet_length' not in facts['master']:
  646. facts['master']['sdn_host_subnet_length'] = '8'
  647. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  648. node_ip = facts['common']['ip']
  649. # default MTU if interface MTU cannot be detected
  650. facts['node']['sdn_mtu'] = '1450'
  651. for val in system_facts.itervalues():
  652. if isinstance(val, dict) and 'mtu' in val:
  653. mtu = val['mtu']
  654. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  655. facts['node']['sdn_mtu'] = str(mtu - 50)
  656. return facts
  657. def format_url(use_ssl, hostname, port, path=''):
  658. """ Format url based on ssl flag, hostname, port and path
  659. Args:
  660. use_ssl (bool): is ssl enabled
  661. hostname (str): hostname
  662. port (str): port
  663. path (str): url path
  664. Returns:
  665. str: The generated url string
  666. """
  667. scheme = 'https' if use_ssl else 'http'
  668. netloc = hostname
  669. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  670. netloc += ":%s" % port
  671. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  672. def get_current_config(facts):
  673. """ Get current openshift config
  674. Args:
  675. facts (dict): existing facts
  676. Returns:
  677. dict: the facts dict updated with the current openshift config
  678. """
  679. current_config = dict()
  680. roles = [role for role in facts if role not in ['common', 'provider']]
  681. for role in roles:
  682. if 'roles' in current_config:
  683. current_config['roles'].append(role)
  684. else:
  685. current_config['roles'] = [role]
  686. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  687. # determine the location of files.
  688. # TODO: I suspect this isn't working right now, but it doesn't prevent
  689. # anything from working properly as far as I can tell, perhaps because
  690. # we override the kubeconfig path everywhere we use it?
  691. # Query kubeconfig settings
  692. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  693. if role == 'node':
  694. kubeconfig_dir = os.path.join(
  695. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  696. )
  697. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  698. if (os.path.isfile('/usr/bin/openshift')
  699. and os.path.isfile(kubeconfig_path)):
  700. try:
  701. _, output, _ = module.run_command(
  702. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  703. "json", "--kubeconfig=%s" % kubeconfig_path],
  704. check_rc=False
  705. )
  706. config = json.loads(output)
  707. cad = 'certificate-authority-data'
  708. try:
  709. for cluster in config['clusters']:
  710. config['clusters'][cluster][cad] = 'masked'
  711. except KeyError:
  712. pass
  713. try:
  714. for user in config['users']:
  715. config['users'][user][cad] = 'masked'
  716. config['users'][user]['client-key-data'] = 'masked'
  717. except KeyError:
  718. pass
  719. current_config['kubeconfig'] = config
  720. # override pylint broad-except warning, since we do not want
  721. # to bubble up any exceptions if oc config view
  722. # fails
  723. # pylint: disable=broad-except
  724. except Exception:
  725. pass
  726. return current_config
  727. def get_openshift_version():
  728. """ Get current version of openshift on the host
  729. Returns:
  730. version: the current openshift version
  731. """
  732. version = None
  733. if os.path.isfile('/usr/bin/openshift'):
  734. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  735. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  736. version = versions.get('openshift', '')
  737. #TODO: acknowledge the possility of a containerized install
  738. return version
  739. def apply_provider_facts(facts, provider_facts):
  740. """ Apply provider facts to supplied facts dict
  741. Args:
  742. facts (dict): facts dict to update
  743. provider_facts (dict): provider facts to apply
  744. roles: host roles
  745. Returns:
  746. dict: the merged facts
  747. """
  748. if not provider_facts:
  749. return facts
  750. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  751. for h_var, ip_var in common_vars:
  752. ip_value = provider_facts['network'].get(ip_var)
  753. if ip_value:
  754. facts['common'][ip_var] = ip_value
  755. facts['common'][h_var] = choose_hostname(
  756. [provider_facts['network'].get(h_var)],
  757. facts['common'][ip_var]
  758. )
  759. facts['provider'] = provider_facts
  760. return facts
  761. def merge_facts(orig, new, additive_facts_to_overwrite):
  762. """ Recursively merge facts dicts
  763. Args:
  764. orig (dict): existing facts
  765. new (dict): facts to update
  766. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  767. '.' notation ex: ['master.named_certificates']
  768. Returns:
  769. dict: the merged facts
  770. """
  771. additive_facts = ['named_certificates']
  772. facts = dict()
  773. for key, value in orig.iteritems():
  774. if key in new:
  775. if isinstance(value, dict) and isinstance(new[key], dict):
  776. relevant_additive_facts = []
  777. # Keep additive_facts_to_overwrite if key matches
  778. for item in additive_facts_to_overwrite:
  779. if '.' in item and item.startswith(key + '.'):
  780. relevant_additive_facts.append(item)
  781. facts[key] = merge_facts(value, new[key], relevant_additive_facts)
  782. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  783. # Fact is additive so we'll combine orig and new.
  784. if isinstance(value, list) and isinstance(new[key], list):
  785. new_fact = []
  786. for item in copy.deepcopy(value) + copy.copy(new[key]):
  787. if item not in new_fact:
  788. new_fact.append(item)
  789. facts[key] = new_fact
  790. else:
  791. facts[key] = copy.copy(new[key])
  792. else:
  793. facts[key] = copy.deepcopy(value)
  794. new_keys = set(new.keys()) - set(orig.keys())
  795. for key in new_keys:
  796. facts[key] = copy.deepcopy(new[key])
  797. return facts
  798. def save_local_facts(filename, facts):
  799. """ Save local facts
  800. Args:
  801. filename (str): local facts file
  802. facts (dict): facts to set
  803. """
  804. try:
  805. fact_dir = os.path.dirname(filename)
  806. if not os.path.exists(fact_dir):
  807. os.makedirs(fact_dir)
  808. with open(filename, 'w') as fact_file:
  809. fact_file.write(module.jsonify(facts))
  810. os.chmod(filename, 0o600)
  811. except (IOError, OSError) as ex:
  812. raise OpenShiftFactsFileWriteError(
  813. "Could not create fact file: %s, error: %s" % (filename, ex)
  814. )
  815. def get_local_facts_from_file(filename):
  816. """ Retrieve local facts from fact file
  817. Args:
  818. filename (str): local facts file
  819. Returns:
  820. dict: the retrieved facts
  821. """
  822. local_facts = dict()
  823. try:
  824. # Handle conversion of INI style facts file to json style
  825. ini_facts = ConfigParser.SafeConfigParser()
  826. ini_facts.read(filename)
  827. for section in ini_facts.sections():
  828. local_facts[section] = dict()
  829. for key, value in ini_facts.items(section):
  830. local_facts[section][key] = value
  831. except (ConfigParser.MissingSectionHeaderError,
  832. ConfigParser.ParsingError):
  833. try:
  834. with open(filename, 'r') as facts_file:
  835. local_facts = json.load(facts_file)
  836. except (ValueError, IOError):
  837. pass
  838. return local_facts
  839. def set_container_facts_if_unset(facts):
  840. """ Set containerized facts.
  841. Args:
  842. facts (dict): existing facts
  843. Returns:
  844. dict: the facts dict updated with the generated containerization
  845. facts
  846. """
  847. deployment_type = facts['common']['deployment_type']
  848. if deployment_type in ['enterprise', 'openshift-enterprise']:
  849. master_image = 'openshift3/ose'
  850. cli_image = master_image
  851. node_image = 'openshift3/node'
  852. ovs_image = 'openshift3/openvswitch'
  853. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  854. elif deployment_type == 'atomic-enterprise':
  855. master_image = 'aep3_beta/aep'
  856. cli_image = master_image
  857. node_image = 'aep3_beta/node'
  858. ovs_image = 'aep3_beta/openvswitch'
  859. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  860. else:
  861. master_image = 'openshift/origin'
  862. cli_image = master_image
  863. node_image = 'openshift/node'
  864. ovs_image = 'openshift/openvswitch'
  865. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  866. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  867. if 'is_containerized' not in facts['common']:
  868. facts['common']['is_containerized'] = facts['common']['is_atomic']
  869. if 'cli_image' not in facts['common']:
  870. facts['common']['cli_image'] = cli_image
  871. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  872. facts['etcd']['etcd_image'] = etcd_image
  873. if 'master' in facts and 'master_image' not in facts['master']:
  874. facts['master']['master_image'] = master_image
  875. if 'node' in facts:
  876. if 'node_image' not in facts['node']:
  877. facts['node']['node_image'] = node_image
  878. if 'ovs_image' not in facts['node']:
  879. facts['node']['ovs_image'] = ovs_image
  880. return facts
  881. class OpenShiftFactsInternalError(Exception):
  882. """Origin Facts Error"""
  883. pass
  884. class OpenShiftFactsUnsupportedRoleError(Exception):
  885. """Origin Facts Unsupported Role Error"""
  886. pass
  887. class OpenShiftFactsFileWriteError(Exception):
  888. """Origin Facts File Write Error"""
  889. pass
  890. class OpenShiftFactsMetadataUnavailableError(Exception):
  891. """Origin Facts Metadata Unavailable Error"""
  892. pass
  893. class OpenShiftFacts(object):
  894. """ Origin Facts
  895. Attributes:
  896. facts (dict): facts for the host
  897. Args:
  898. module (AnsibleModule): an AnsibleModule object
  899. role (str): role for setting local facts
  900. filename (str): local facts file to use
  901. local_facts (dict): local facts to set
  902. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  903. '.' notation ex: ['master.named_certificates']
  904. Raises:
  905. OpenShiftFactsUnsupportedRoleError:
  906. """
  907. known_roles = ['common', 'master', 'node', 'etcd', 'nfs']
  908. def __init__(self, role, filename, local_facts, additive_facts_to_overwrite=False):
  909. self.changed = False
  910. self.filename = filename
  911. if role not in self.known_roles:
  912. raise OpenShiftFactsUnsupportedRoleError(
  913. "Role %s is not supported by this module" % role
  914. )
  915. self.role = role
  916. self.system_facts = ansible_facts(module)
  917. self.facts = self.generate_facts(local_facts, additive_facts_to_overwrite)
  918. def generate_facts(self, local_facts, additive_facts_to_overwrite):
  919. """ Generate facts
  920. Args:
  921. local_facts (dict): local_facts for overriding generated
  922. defaults
  923. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  924. '.' notation ex: ['master.named_certificates']
  925. Returns:
  926. dict: The generated facts
  927. """
  928. local_facts = self.init_local_facts(local_facts, additive_facts_to_overwrite)
  929. roles = local_facts.keys()
  930. defaults = self.get_defaults(roles)
  931. provider_facts = self.init_provider_facts()
  932. facts = apply_provider_facts(defaults, provider_facts)
  933. facts = merge_facts(facts, local_facts, additive_facts_to_overwrite)
  934. facts['current_config'] = get_current_config(facts)
  935. facts = set_url_facts_if_unset(facts)
  936. facts = set_project_cfg_facts_if_unset(facts)
  937. facts = set_fluentd_facts_if_unset(facts)
  938. facts = set_flannel_facts_if_unset(facts)
  939. facts = set_node_schedulability(facts)
  940. facts = set_master_selectors(facts)
  941. facts = set_metrics_facts_if_unset(facts)
  942. facts = set_identity_providers_if_unset(facts)
  943. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  944. facts = set_deployment_facts_if_unset(facts)
  945. facts = set_version_facts_if_unset(facts)
  946. facts = set_manageiq_facts_if_unset(facts)
  947. facts = set_aggregate_facts(facts)
  948. facts = set_etcd_facts_if_unset(facts)
  949. facts = set_container_facts_if_unset(facts)
  950. return dict(openshift=facts)
  951. def get_defaults(self, roles):
  952. """ Get default fact values
  953. Args:
  954. roles (list): list of roles for this host
  955. Returns:
  956. dict: The generated default facts
  957. """
  958. defaults = dict()
  959. ip_addr = self.system_facts['default_ipv4']['address']
  960. exit_code, output, _ = module.run_command(['hostname', '-f'])
  961. hostname_f = output.strip() if exit_code == 0 else ''
  962. hostname_values = [hostname_f, self.system_facts['nodename'],
  963. self.system_facts['fqdn']]
  964. hostname = choose_hostname(hostname_values, ip_addr)
  965. common = dict(use_openshift_sdn=True, ip=ip_addr, public_ip=ip_addr,
  966. deployment_type='origin', hostname=hostname,
  967. public_hostname=hostname)
  968. common['client_binary'] = 'oc'
  969. common['admin_binary'] = 'oadm'
  970. common['dns_domain'] = 'cluster.local'
  971. common['install_examples'] = True
  972. defaults['common'] = common
  973. if 'master' in roles:
  974. master = dict(api_use_ssl=True, api_port='8443',
  975. console_use_ssl=True, console_path='/console',
  976. console_port='8443', etcd_use_ssl=True, etcd_hosts='',
  977. etcd_port='4001', portal_net='172.30.0.0/16',
  978. embedded_etcd=True, embedded_kube=True,
  979. embedded_dns=True, dns_port='53',
  980. bind_addr='0.0.0.0', session_max_seconds=3600,
  981. session_name='ssn', session_secrets_file='',
  982. access_token_max_seconds=86400,
  983. auth_token_max_seconds=500,
  984. oauth_grant_method='auto')
  985. defaults['master'] = master
  986. if 'node' in roles:
  987. node = dict(labels={}, annotations={}, portal_net='172.30.0.0/16',
  988. iptables_sync_period='5s', set_node_ip=False)
  989. defaults['node'] = node
  990. if 'nfs' in roles:
  991. nfs = dict(exports_dir='/var/export', registry_volume='regvol',
  992. export_options='*(rw,sync,all_squash)')
  993. defaults['nfs'] = nfs
  994. return defaults
  995. def guess_host_provider(self):
  996. """ Guess the host provider
  997. Returns:
  998. dict: The generated default facts for the detected provider
  999. """
  1000. # TODO: cloud provider facts should probably be submitted upstream
  1001. product_name = self.system_facts['product_name']
  1002. product_version = self.system_facts['product_version']
  1003. virt_type = self.system_facts['virtualization_type']
  1004. virt_role = self.system_facts['virtualization_role']
  1005. provider = None
  1006. metadata = None
  1007. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1008. # need to create PR for ansible to expose it
  1009. bios_vendor = get_file_content(
  1010. '/sys/devices/virtual/dmi/id/bios_vendor'
  1011. )
  1012. if bios_vendor == 'Google':
  1013. provider = 'gce'
  1014. metadata_url = ('http://metadata.google.internal/'
  1015. 'computeMetadata/v1/?recursive=true')
  1016. headers = {'Metadata-Flavor': 'Google'}
  1017. metadata = get_provider_metadata(metadata_url, True, headers,
  1018. True)
  1019. # Filter sshKeys and serviceAccounts from gce metadata
  1020. if metadata:
  1021. metadata['project']['attributes'].pop('sshKeys', None)
  1022. metadata['instance'].pop('serviceAccounts', None)
  1023. elif (virt_type == 'xen' and virt_role == 'guest'
  1024. and re.match(r'.*\.amazon$', product_version)):
  1025. provider = 'ec2'
  1026. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1027. metadata = get_provider_metadata(metadata_url)
  1028. elif re.search(r'OpenStack', product_name):
  1029. provider = 'openstack'
  1030. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1031. 'meta_data.json')
  1032. metadata = get_provider_metadata(metadata_url, True, None,
  1033. True)
  1034. if metadata:
  1035. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1036. metadata['ec2_compat'] = get_provider_metadata(
  1037. ec2_compat_url
  1038. )
  1039. # disable pylint maybe-no-member because overloaded use of
  1040. # the module name causes pylint to not detect that results
  1041. # is an array or hash
  1042. # pylint: disable=maybe-no-member
  1043. # Filter public_keys and random_seed from openstack metadata
  1044. metadata.pop('public_keys', None)
  1045. metadata.pop('random_seed', None)
  1046. if not metadata['ec2_compat']:
  1047. metadata = None
  1048. return dict(name=provider, metadata=metadata)
  1049. def init_provider_facts(self):
  1050. """ Initialize the provider facts
  1051. Returns:
  1052. dict: The normalized provider facts
  1053. """
  1054. provider_info = self.guess_host_provider()
  1055. provider_facts = normalize_provider_facts(
  1056. provider_info.get('name'),
  1057. provider_info.get('metadata')
  1058. )
  1059. return provider_facts
  1060. def init_local_facts(self, facts=None, additive_facts_to_overwrite=False):
  1061. """ Initialize the provider facts
  1062. Args:
  1063. facts (dict): local facts to set
  1064. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1065. '.' notation ex: ['master.named_certificates']
  1066. Returns:
  1067. dict: The result of merging the provided facts with existing
  1068. local facts
  1069. """
  1070. changed = False
  1071. facts_to_set = {self.role: dict()}
  1072. if facts is not None:
  1073. facts_to_set[self.role] = facts
  1074. local_facts = get_local_facts_from_file(self.filename)
  1075. for arg in ['labels', 'annotations']:
  1076. if arg in facts_to_set and isinstance(facts_to_set[arg],
  1077. basestring):
  1078. facts_to_set[arg] = module.from_json(facts_to_set[arg])
  1079. new_local_facts = merge_facts(local_facts, facts_to_set, additive_facts_to_overwrite)
  1080. for facts in new_local_facts.values():
  1081. keys_to_delete = []
  1082. for fact, value in facts.iteritems():
  1083. if value == "" or value is None:
  1084. keys_to_delete.append(fact)
  1085. for key in keys_to_delete:
  1086. del facts[key]
  1087. if new_local_facts != local_facts:
  1088. self.validate_local_facts(new_local_facts)
  1089. changed = True
  1090. if not module.check_mode:
  1091. save_local_facts(self.filename, new_local_facts)
  1092. self.changed = changed
  1093. return new_local_facts
  1094. def validate_local_facts(self, facts=None):
  1095. """ Validate local facts
  1096. Args:
  1097. facts (dict): local facts to validate
  1098. """
  1099. invalid_facts = dict()
  1100. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1101. if invalid_facts:
  1102. msg = 'Invalid facts detected:\n'
  1103. for key in invalid_facts.keys():
  1104. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1105. module.fail_json(msg=msg,
  1106. changed=self.changed)
  1107. # disabling pylint errors for line-too-long since we're dealing
  1108. # with best effort reduction of error messages here.
  1109. # disabling errors for too-many-branches since we require checking
  1110. # many conditions.
  1111. # pylint: disable=line-too-long, too-many-branches
  1112. @staticmethod
  1113. def validate_master_facts(facts, invalid_facts):
  1114. """ Validate master facts
  1115. Args:
  1116. facts (dict): local facts to validate
  1117. invalid_facts (dict): collected invalid_facts
  1118. Returns:
  1119. dict: Invalid facts
  1120. """
  1121. if 'master' in facts:
  1122. # openshift.master.session_auth_secrets
  1123. if 'session_auth_secrets' in facts['master']:
  1124. session_auth_secrets = facts['master']['session_auth_secrets']
  1125. if not issubclass(type(session_auth_secrets), list):
  1126. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1127. elif 'session_encryption_secrets' not in facts['master']:
  1128. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1129. 'if openshift_master_session_auth_secrets is provided.')
  1130. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1131. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1132. 'openshift_master_session_encryption_secrets must be '
  1133. 'equal length.')
  1134. else:
  1135. for secret in session_auth_secrets:
  1136. if len(secret) < 32:
  1137. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1138. 'Secrets must be at least 32 characters in length.')
  1139. # openshift.master.session_encryption_secrets
  1140. if 'session_encryption_secrets' in facts['master']:
  1141. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1142. if not issubclass(type(session_encryption_secrets), list):
  1143. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1144. elif 'session_auth_secrets' not in facts['master']:
  1145. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1146. 'set if openshift_master_session_encryption_secrets '
  1147. 'is provided.')
  1148. else:
  1149. for secret in session_encryption_secrets:
  1150. if len(secret) not in [16, 24, 32]:
  1151. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1152. 'Secrets must be 16, 24, or 32 characters in length.')
  1153. return invalid_facts
  1154. def main():
  1155. """ main """
  1156. # disabling pylint errors for global-variable-undefined and invalid-name
  1157. # for 'global module' usage, since it is required to use ansible_facts
  1158. # pylint: disable=global-variable-undefined, invalid-name
  1159. global module
  1160. module = AnsibleModule(
  1161. argument_spec=dict(
  1162. role=dict(default='common', required=False,
  1163. choices=OpenShiftFacts.known_roles),
  1164. local_facts=dict(default=None, type='dict', required=False),
  1165. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1166. ),
  1167. supports_check_mode=True,
  1168. add_file_common_args=True,
  1169. )
  1170. role = module.params['role']
  1171. local_facts = module.params['local_facts']
  1172. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1173. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1174. openshift_facts = OpenShiftFacts(role, fact_file, local_facts, additive_facts_to_overwrite)
  1175. file_params = module.params.copy()
  1176. file_params['path'] = fact_file
  1177. file_args = module.load_file_common_arguments(file_params)
  1178. changed = module.set_fs_attributes_if_different(file_args,
  1179. openshift_facts.changed)
  1180. return module.exit_json(changed=changed,
  1181. ansible_facts=openshift_facts.facts)
  1182. # ignore pylint errors related to the module_utils import
  1183. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1184. # import module snippets
  1185. from ansible.module_utils.basic import *
  1186. from ansible.module_utils.facts import *
  1187. from ansible.module_utils.urls import *
  1188. if __name__ == '__main__':
  1189. main()