openshift_facts.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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. from distutils.util import strtobool
  21. def hostname_valid(hostname):
  22. """ Test if specified hostname should be considered valid
  23. Args:
  24. hostname (str): hostname to test
  25. Returns:
  26. bool: True if valid, otherwise False
  27. """
  28. if (not hostname or
  29. hostname.startswith('localhost') or
  30. hostname.endswith('localdomain') or
  31. len(hostname.split('.')) < 2):
  32. return False
  33. return True
  34. def choose_hostname(hostnames=None, fallback=''):
  35. """ Choose a hostname from the provided hostnames
  36. Given a list of hostnames and a fallback value, choose a hostname to
  37. use. This function will prefer fqdns if they exist (excluding any that
  38. begin with localhost or end with localdomain) over ip addresses.
  39. Args:
  40. hostnames (list): list of hostnames
  41. fallback (str): default value to set if hostnames does not contain
  42. a valid hostname
  43. Returns:
  44. str: chosen hostname
  45. """
  46. hostname = fallback
  47. if hostnames is None:
  48. return hostname
  49. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  50. ips = [i for i in hostnames
  51. if (i is not None and isinstance(i, basestring)
  52. and re.match(ip_regex, i))]
  53. hosts = [i for i in hostnames
  54. if i is not None and i != '' and i not in ips]
  55. for host_list in (hosts, ips):
  56. for host in host_list:
  57. if hostname_valid(host):
  58. return host
  59. return hostname
  60. def query_metadata(metadata_url, headers=None, expect_json=False):
  61. """ Return metadata from the provided metadata_url
  62. Args:
  63. metadata_url (str): metadata url
  64. headers (dict): headers to set for metadata request
  65. expect_json (bool): does the metadata_url return json
  66. Returns:
  67. dict or list: metadata request result
  68. """
  69. result, info = fetch_url(module, metadata_url, headers=headers)
  70. if info['status'] != 200:
  71. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  72. if expect_json:
  73. return module.from_json(result.read())
  74. else:
  75. return [line.strip() for line in result.readlines()]
  76. def walk_metadata(metadata_url, headers=None, expect_json=False):
  77. """ Walk the metadata tree and return a dictionary of the entire tree
  78. Args:
  79. metadata_url (str): metadata url
  80. headers (dict): headers to set for metadata request
  81. expect_json (bool): does the metadata_url return json
  82. Returns:
  83. dict: the result of walking the metadata tree
  84. """
  85. metadata = dict()
  86. for line in query_metadata(metadata_url, headers, expect_json):
  87. if line.endswith('/') and not line == 'public-keys/':
  88. key = line[:-1]
  89. metadata[key] = walk_metadata(metadata_url + line,
  90. headers, expect_json)
  91. else:
  92. results = query_metadata(metadata_url + line, headers,
  93. expect_json)
  94. if len(results) == 1:
  95. # disable pylint maybe-no-member because overloaded use of
  96. # the module name causes pylint to not detect that results
  97. # is an array or hash
  98. # pylint: disable=maybe-no-member
  99. metadata[line] = results.pop()
  100. else:
  101. metadata[line] = results
  102. return metadata
  103. def get_provider_metadata(metadata_url, supports_recursive=False,
  104. headers=None, expect_json=False):
  105. """ Retrieve the provider metadata
  106. Args:
  107. metadata_url (str): metadata url
  108. supports_recursive (bool): does the provider metadata api support
  109. recursion
  110. headers (dict): headers to set for metadata request
  111. expect_json (bool): does the metadata_url return json
  112. Returns:
  113. dict: the provider metadata
  114. """
  115. try:
  116. if supports_recursive:
  117. metadata = query_metadata(metadata_url, headers,
  118. expect_json)
  119. else:
  120. metadata = walk_metadata(metadata_url, headers,
  121. expect_json)
  122. except OpenShiftFactsMetadataUnavailableError:
  123. metadata = None
  124. return metadata
  125. def normalize_gce_facts(metadata, facts):
  126. """ Normalize gce facts
  127. Args:
  128. metadata (dict): provider metadata
  129. facts (dict): facts to update
  130. Returns:
  131. dict: the result of adding the normalized metadata to the provided
  132. facts dict
  133. """
  134. for interface in metadata['instance']['networkInterfaces']:
  135. int_info = dict(ips=[interface['ip']], network_type='gce')
  136. int_info['public_ips'] = [ac['externalIp'] for ac
  137. in interface['accessConfigs']]
  138. int_info['public_ips'].extend(interface['forwardedIps'])
  139. _, _, network_id = interface['network'].rpartition('/')
  140. int_info['network_id'] = network_id
  141. facts['network']['interfaces'].append(int_info)
  142. _, _, zone = metadata['instance']['zone'].rpartition('/')
  143. facts['zone'] = zone
  144. # Default to no sdn for GCE deployments
  145. facts['use_openshift_sdn'] = False
  146. # GCE currently only supports a single interface
  147. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  148. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  149. facts['network']['public_ip'] = pub_ip
  150. facts['network']['hostname'] = metadata['instance']['hostname']
  151. # TODO: attempt to resolve public_hostname
  152. facts['network']['public_hostname'] = facts['network']['public_ip']
  153. return facts
  154. def normalize_aws_facts(metadata, facts):
  155. """ Normalize aws facts
  156. Args:
  157. metadata (dict): provider metadata
  158. facts (dict): facts to update
  159. Returns:
  160. dict: the result of adding the normalized metadata to the provided
  161. facts dict
  162. """
  163. for interface in sorted(
  164. metadata['network']['interfaces']['macs'].values(),
  165. key=lambda x: x['device-number']
  166. ):
  167. int_info = dict()
  168. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  169. for ips_var, int_var in var_map.iteritems():
  170. ips = interface.get(int_var)
  171. if isinstance(ips, basestring):
  172. int_info[ips_var] = [ips]
  173. else:
  174. int_info[ips_var] = ips
  175. if 'vpc-id' in interface:
  176. int_info['network_type'] = 'vpc'
  177. else:
  178. int_info['network_type'] = 'classic'
  179. if int_info['network_type'] == 'vpc':
  180. int_info['network_id'] = interface['subnet-id']
  181. else:
  182. int_info['network_id'] = None
  183. facts['network']['interfaces'].append(int_info)
  184. facts['zone'] = metadata['placement']['availability-zone']
  185. # TODO: actually attempt to determine default local and public ips
  186. # by using the ansible default ip fact and the ipv4-associations
  187. # from the ec2 metadata
  188. facts['network']['ip'] = metadata.get('local-ipv4')
  189. facts['network']['public_ip'] = metadata.get('public-ipv4')
  190. # TODO: verify that local hostname makes sense and is resolvable
  191. facts['network']['hostname'] = metadata.get('local-hostname')
  192. # TODO: verify that public hostname makes sense and is resolvable
  193. facts['network']['public_hostname'] = metadata.get('public-hostname')
  194. return facts
  195. def normalize_openstack_facts(metadata, facts):
  196. """ Normalize openstack facts
  197. Args:
  198. metadata (dict): provider metadata
  199. facts (dict): facts to update
  200. Returns:
  201. dict: the result of adding the normalized metadata to the provided
  202. facts dict
  203. """
  204. # openstack ec2 compat api does not support network interfaces and
  205. # the version tested on did not include the info in the openstack
  206. # metadata api, should be updated if neutron exposes this.
  207. facts['zone'] = metadata['availability_zone']
  208. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  209. facts['network']['ip'] = local_ipv4
  210. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  211. # TODO: verify local hostname makes sense and is resolvable
  212. facts['network']['hostname'] = metadata['hostname']
  213. # TODO: verify that public hostname makes sense and is resolvable
  214. pub_h = metadata['ec2_compat']['public-hostname']
  215. facts['network']['public_hostname'] = pub_h
  216. return facts
  217. def normalize_provider_facts(provider, metadata):
  218. """ Normalize provider facts
  219. Args:
  220. provider (str): host provider
  221. metadata (dict): provider metadata
  222. Returns:
  223. dict: the normalized provider facts
  224. """
  225. if provider is None or metadata is None:
  226. return {}
  227. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  228. # and configure ipv6 facts if available
  229. # TODO: add support for setting user_data if available
  230. facts = dict(name=provider, metadata=metadata,
  231. network=dict(interfaces=[], ipv6_enabled=False))
  232. if provider == 'gce':
  233. facts = normalize_gce_facts(metadata, facts)
  234. elif provider == 'ec2':
  235. facts = normalize_aws_facts(metadata, facts)
  236. elif provider == 'openstack':
  237. facts = normalize_openstack_facts(metadata, facts)
  238. return facts
  239. def set_fluentd_facts_if_unset(facts):
  240. """ Set fluentd facts if not already present in facts dict
  241. dict: the facts dict updated with the generated fluentd facts if
  242. missing
  243. Args:
  244. facts (dict): existing facts
  245. Returns:
  246. dict: the facts dict updated with the generated fluentd
  247. facts if they were not already present
  248. """
  249. if 'common' in facts:
  250. if 'use_fluentd' not in facts['common']:
  251. use_fluentd = False
  252. facts['common']['use_fluentd'] = use_fluentd
  253. return facts
  254. def set_node_schedulability(facts):
  255. """ Set schedulable facts if not already present in facts dict
  256. Args:
  257. facts (dict): existing facts
  258. Returns:
  259. dict: the facts dict updated with the generated schedulable
  260. facts if they were not already present
  261. """
  262. if 'node' in facts:
  263. if 'schedulable' not in facts['node']:
  264. if 'master' in facts:
  265. facts['node']['schedulable'] = False
  266. else:
  267. facts['node']['schedulable'] = True
  268. return facts
  269. def set_master_selectors(facts):
  270. """ Set selectors facts if not already present in facts dict
  271. Args:
  272. facts (dict): existing facts
  273. Returns:
  274. dict: the facts dict updated with the generated selectors
  275. facts if they were not already present
  276. """
  277. if 'master' in facts:
  278. if 'infra_nodes' in facts['master']:
  279. deployment_type = facts['common']['deployment_type']
  280. if deployment_type == 'online':
  281. selector = "type=infra"
  282. else:
  283. selector = "region=infra"
  284. if 'router_selector' not in facts['master']:
  285. facts['master']['router_selector'] = selector
  286. if 'registry_selector' not in facts['master']:
  287. facts['master']['registry_selector'] = selector
  288. return facts
  289. def set_metrics_facts_if_unset(facts):
  290. """ Set cluster metrics facts if not already present in facts dict
  291. dict: the facts dict updated with the generated cluster metrics facts if
  292. missing
  293. Args:
  294. facts (dict): existing facts
  295. Returns:
  296. dict: the facts dict updated with the generated cluster metrics
  297. facts if they were not already present
  298. """
  299. if 'common' in facts:
  300. if 'use_cluster_metrics' not in facts['common']:
  301. use_cluster_metrics = False
  302. facts['common']['use_cluster_metrics'] = use_cluster_metrics
  303. return facts
  304. def set_project_cfg_facts_if_unset(facts):
  305. """ Set Project Configuration facts if not already present in facts dict
  306. dict:
  307. Args:
  308. facts (dict): existing facts
  309. Returns:
  310. dict: the facts dict updated with the generated Project Configuration
  311. facts if they were not already present
  312. """
  313. config = {
  314. 'default_node_selector': '',
  315. 'project_request_message': '',
  316. 'project_request_template': '',
  317. 'mcs_allocator_range': 's0:/2',
  318. 'mcs_labels_per_project': 5,
  319. 'uid_allocator_range': '1000000000-1999999999/10000'
  320. }
  321. if 'master' in facts:
  322. for key, value in config.items():
  323. if key not in facts['master']:
  324. facts['master'][key] = value
  325. return facts
  326. def set_identity_providers_if_unset(facts):
  327. """ Set identity_providers fact if not already present in facts dict
  328. Args:
  329. facts (dict): existing facts
  330. Returns:
  331. dict: the facts dict updated with the generated identity providers
  332. facts if they were not already present
  333. """
  334. if 'master' in facts:
  335. deployment_type = facts['common']['deployment_type']
  336. if 'identity_providers' not in facts['master']:
  337. identity_provider = dict(
  338. name='allow_all', challenge=True, login=True,
  339. kind='AllowAllPasswordIdentityProvider'
  340. )
  341. if deployment_type == 'enterprise':
  342. identity_provider = dict(
  343. name='deny_all', challenge=True, login=True,
  344. kind='DenyAllPasswordIdentityProvider'
  345. )
  346. facts['master']['identity_providers'] = [identity_provider]
  347. return facts
  348. def set_url_facts_if_unset(facts):
  349. """ Set url facts if not already present in facts dict
  350. Args:
  351. facts (dict): existing facts
  352. Returns:
  353. dict: the facts dict updated with the generated url facts if they
  354. were not already present
  355. """
  356. if 'master' in facts:
  357. api_use_ssl = facts['master']['api_use_ssl']
  358. api_port = facts['master']['api_port']
  359. console_use_ssl = facts['master']['console_use_ssl']
  360. console_port = facts['master']['console_port']
  361. console_path = facts['master']['console_path']
  362. etcd_use_ssl = facts['master']['etcd_use_ssl']
  363. etcd_hosts = facts['master']['etcd_hosts']
  364. etcd_port = facts['master']['etcd_port']
  365. hostname = facts['common']['hostname']
  366. public_hostname = facts['common']['public_hostname']
  367. cluster_hostname = facts['master'].get('cluster_hostname')
  368. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  369. if 'etcd_urls' not in facts['master']:
  370. etcd_urls = []
  371. if etcd_hosts != '':
  372. facts['master']['etcd_port'] = etcd_port
  373. facts['master']['embedded_etcd'] = False
  374. for host in etcd_hosts:
  375. etcd_urls.append(format_url(etcd_use_ssl, host,
  376. etcd_port))
  377. else:
  378. etcd_urls = [format_url(etcd_use_ssl, hostname,
  379. etcd_port)]
  380. facts['master']['etcd_urls'] = etcd_urls
  381. if 'api_url' not in facts['master']:
  382. api_hostname = cluster_hostname if cluster_hostname else hostname
  383. facts['master']['api_url'] = format_url(api_use_ssl, api_hostname,
  384. api_port)
  385. if 'public_api_url' not in facts['master']:
  386. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  387. facts['master']['public_api_url'] = format_url(api_use_ssl,
  388. api_public_hostname,
  389. api_port)
  390. if 'console_url' not in facts['master']:
  391. console_hostname = cluster_hostname if cluster_hostname else hostname
  392. facts['master']['console_url'] = format_url(console_use_ssl,
  393. console_hostname,
  394. console_port,
  395. console_path)
  396. if 'public_console_url' not in facts['master']:
  397. console_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  398. facts['master']['public_console_url'] = format_url(console_use_ssl,
  399. console_public_hostname,
  400. console_port,
  401. console_path)
  402. return facts
  403. def set_aggregate_facts(facts):
  404. """ Set aggregate facts
  405. Args:
  406. facts (dict): existing facts
  407. Returns:
  408. dict: the facts dict updated with aggregated facts
  409. """
  410. all_hostnames = set()
  411. if 'common' in facts:
  412. all_hostnames.add(facts['common']['hostname'])
  413. all_hostnames.add(facts['common']['public_hostname'])
  414. if 'master' in facts:
  415. if 'cluster_hostname' in facts['master']:
  416. all_hostnames.add(facts['master']['cluster_hostname'])
  417. if 'cluster_public_hostname' in facts['master']:
  418. all_hostnames.add(facts['master']['cluster_public_hostname'])
  419. facts['common']['all_hostnames'] = list(all_hostnames)
  420. return facts
  421. def set_deployment_facts_if_unset(facts):
  422. """ Set Facts that vary based on deployment_type. This currently
  423. includes common.service_type, common.config_base, master.registry_url,
  424. node.registry_url
  425. Args:
  426. facts (dict): existing facts
  427. Returns:
  428. dict: the facts dict updated with the generated deployment_type
  429. facts
  430. """
  431. # Perhaps re-factor this as a map?
  432. # pylint: disable=too-many-branches
  433. if 'common' in facts:
  434. deployment_type = facts['common']['deployment_type']
  435. if 'service_type' not in facts['common']:
  436. service_type = 'atomic-openshift'
  437. if deployment_type == 'origin':
  438. service_type = 'origin'
  439. elif deployment_type in ['enterprise', 'online']:
  440. service_type = 'openshift'
  441. facts['common']['service_type'] = service_type
  442. if 'config_base' not in facts['common']:
  443. config_base = '/etc/origin'
  444. if deployment_type in ['enterprise', 'online']:
  445. config_base = '/etc/openshift'
  446. facts['common']['config_base'] = config_base
  447. if 'data_dir' not in facts['common']:
  448. data_dir = '/var/lib/origin'
  449. if deployment_type in ['enterprise', 'online']:
  450. data_dir = '/var/lib/openshift'
  451. facts['common']['data_dir'] = data_dir
  452. facts['common']['version'] = get_openshift_version()
  453. for role in ('master', 'node'):
  454. if role in facts:
  455. deployment_type = facts['common']['deployment_type']
  456. if 'registry_url' not in facts[role]:
  457. registry_url = 'openshift/origin-${component}:${version}'
  458. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  459. registry_url = 'openshift3/ose-${component}:${version}'
  460. elif deployment_type == 'atomic-enterprise':
  461. registry_url = 'aep3/aep-${component}:${version}'
  462. facts[role]['registry_url'] = registry_url
  463. return facts
  464. def set_sdn_facts_if_unset(facts):
  465. """ Set sdn facts if not already present in facts dict
  466. Args:
  467. facts (dict): existing facts
  468. Returns:
  469. dict: the facts dict updated with the generated sdn facts if they
  470. were not already present
  471. """
  472. if 'common' in facts:
  473. use_sdn = facts['common']['use_openshift_sdn']
  474. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  475. facts['common']['use_openshift_sdn'] = bool(strtobool(str(use_sdn)))
  476. if 'sdn_network_plugin_name' not in facts['common']:
  477. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  478. facts['common']['sdn_network_plugin_name'] = plugin
  479. if 'master' in facts:
  480. if 'sdn_cluster_network_cidr' not in facts['master']:
  481. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  482. if 'sdn_host_subnet_length' not in facts['master']:
  483. facts['master']['sdn_host_subnet_length'] = '8'
  484. if 'node' in facts:
  485. if 'sdn_mtu' not in facts['node']:
  486. facts['node']['sdn_mtu'] = '1450'
  487. return facts
  488. def format_url(use_ssl, hostname, port, path=''):
  489. """ Format url based on ssl flag, hostname, port and path
  490. Args:
  491. use_ssl (bool): is ssl enabled
  492. hostname (str): hostname
  493. port (str): port
  494. path (str): url path
  495. Returns:
  496. str: The generated url string
  497. """
  498. scheme = 'https' if use_ssl else 'http'
  499. netloc = hostname
  500. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  501. netloc += ":%s" % port
  502. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  503. def get_current_config(facts):
  504. """ Get current openshift config
  505. Args:
  506. facts (dict): existing facts
  507. Returns:
  508. dict: the facts dict updated with the current openshift config
  509. """
  510. current_config = dict()
  511. roles = [role for role in facts if role not in ['common', 'provider']]
  512. for role in roles:
  513. if 'roles' in current_config:
  514. current_config['roles'].append(role)
  515. else:
  516. current_config['roles'] = [role]
  517. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  518. # determine the location of files.
  519. # TODO: I suspect this isn't working right now, but it doesn't prevent
  520. # anything from working properly as far as I can tell, perhaps because
  521. # we override the kubeconfig path everywhere we use it?
  522. # Query kubeconfig settings
  523. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  524. if role == 'node':
  525. kubeconfig_dir = os.path.join(
  526. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  527. )
  528. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  529. if (os.path.isfile('/usr/bin/openshift')
  530. and os.path.isfile(kubeconfig_path)):
  531. try:
  532. _, output, _ = module.run_command(
  533. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  534. "json", "--kubeconfig=%s" % kubeconfig_path],
  535. check_rc=False
  536. )
  537. config = json.loads(output)
  538. cad = 'certificate-authority-data'
  539. try:
  540. for cluster in config['clusters']:
  541. config['clusters'][cluster][cad] = 'masked'
  542. except KeyError:
  543. pass
  544. try:
  545. for user in config['users']:
  546. config['users'][user][cad] = 'masked'
  547. config['users'][user]['client-key-data'] = 'masked'
  548. except KeyError:
  549. pass
  550. current_config['kubeconfig'] = config
  551. # override pylint broad-except warning, since we do not want
  552. # to bubble up any exceptions if oc config view
  553. # fails
  554. # pylint: disable=broad-except
  555. except Exception:
  556. pass
  557. return current_config
  558. def get_openshift_version():
  559. """ Get current version of openshift on the host
  560. Returns:
  561. version: the current openshift version
  562. """
  563. version = ''
  564. if os.path.isfile('/usr/bin/openshift'):
  565. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  566. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  567. version = versions.get('openshift', '')
  568. #TODO: acknowledge the possility of a containerized install
  569. return version
  570. def apply_provider_facts(facts, provider_facts):
  571. """ Apply provider facts to supplied facts dict
  572. Args:
  573. facts (dict): facts dict to update
  574. provider_facts (dict): provider facts to apply
  575. roles: host roles
  576. Returns:
  577. dict: the merged facts
  578. """
  579. if not provider_facts:
  580. return facts
  581. use_openshift_sdn = provider_facts.get('use_openshift_sdn')
  582. if isinstance(use_openshift_sdn, bool):
  583. facts['common']['use_openshift_sdn'] = use_openshift_sdn
  584. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  585. for h_var, ip_var in common_vars:
  586. ip_value = provider_facts['network'].get(ip_var)
  587. if ip_value:
  588. facts['common'][ip_var] = ip_value
  589. facts['common'][h_var] = choose_hostname(
  590. [provider_facts['network'].get(h_var)],
  591. facts['common'][ip_var]
  592. )
  593. facts['provider'] = provider_facts
  594. return facts
  595. def merge_facts(orig, new):
  596. """ Recursively merge facts dicts
  597. Args:
  598. orig (dict): existing facts
  599. new (dict): facts to update
  600. Returns:
  601. dict: the merged facts
  602. """
  603. facts = dict()
  604. for key, value in orig.iteritems():
  605. if key in new:
  606. if isinstance(value, dict) and isinstance(new[key], dict):
  607. facts[key] = merge_facts(value, new[key])
  608. else:
  609. facts[key] = copy.copy(new[key])
  610. else:
  611. facts[key] = copy.deepcopy(value)
  612. new_keys = set(new.keys()) - set(orig.keys())
  613. for key in new_keys:
  614. facts[key] = copy.deepcopy(new[key])
  615. return facts
  616. def save_local_facts(filename, facts):
  617. """ Save local facts
  618. Args:
  619. filename (str): local facts file
  620. facts (dict): facts to set
  621. """
  622. try:
  623. fact_dir = os.path.dirname(filename)
  624. if not os.path.exists(fact_dir):
  625. os.makedirs(fact_dir)
  626. with open(filename, 'w') as fact_file:
  627. fact_file.write(module.jsonify(facts))
  628. except (IOError, OSError) as ex:
  629. raise OpenShiftFactsFileWriteError(
  630. "Could not create fact file: %s, error: %s" % (filename, ex)
  631. )
  632. def get_local_facts_from_file(filename):
  633. """ Retrieve local facts from fact file
  634. Args:
  635. filename (str): local facts file
  636. Returns:
  637. dict: the retrieved facts
  638. """
  639. local_facts = dict()
  640. try:
  641. # Handle conversion of INI style facts file to json style
  642. ini_facts = ConfigParser.SafeConfigParser()
  643. ini_facts.read(filename)
  644. for section in ini_facts.sections():
  645. local_facts[section] = dict()
  646. for key, value in ini_facts.items(section):
  647. local_facts[section][key] = value
  648. except (ConfigParser.MissingSectionHeaderError,
  649. ConfigParser.ParsingError):
  650. try:
  651. with open(filename, 'r') as facts_file:
  652. local_facts = json.load(facts_file)
  653. except (ValueError, IOError):
  654. pass
  655. return local_facts
  656. class OpenShiftFactsUnsupportedRoleError(Exception):
  657. """Origin Facts Unsupported Role Error"""
  658. pass
  659. class OpenShiftFactsFileWriteError(Exception):
  660. """Origin Facts File Write Error"""
  661. pass
  662. class OpenShiftFactsMetadataUnavailableError(Exception):
  663. """Origin Facts Metadata Unavailable Error"""
  664. pass
  665. class OpenShiftFacts(object):
  666. """ Origin Facts
  667. Attributes:
  668. facts (dict): facts for the host
  669. Args:
  670. role (str): role for setting local facts
  671. filename (str): local facts file to use
  672. local_facts (dict): local facts to set
  673. Raises:
  674. OpenShiftFactsUnsupportedRoleError:
  675. """
  676. known_roles = ['common', 'master', 'node', 'master_sdn', 'node_sdn', 'dns']
  677. def __init__(self, role, filename, local_facts):
  678. self.changed = False
  679. self.filename = filename
  680. if role not in self.known_roles:
  681. raise OpenShiftFactsUnsupportedRoleError(
  682. "Role %s is not supported by this module" % role
  683. )
  684. self.role = role
  685. self.system_facts = ansible_facts(module)
  686. self.facts = self.generate_facts(local_facts)
  687. def generate_facts(self, local_facts):
  688. """ Generate facts
  689. Args:
  690. local_facts (dict): local_facts for overriding generated
  691. defaults
  692. Returns:
  693. dict: The generated facts
  694. """
  695. local_facts = self.init_local_facts(local_facts)
  696. roles = local_facts.keys()
  697. defaults = self.get_defaults(roles)
  698. provider_facts = self.init_provider_facts()
  699. facts = apply_provider_facts(defaults, provider_facts)
  700. facts = merge_facts(facts, local_facts)
  701. facts['current_config'] = get_current_config(facts)
  702. facts = set_url_facts_if_unset(facts)
  703. facts = set_project_cfg_facts_if_unset(facts)
  704. facts = set_fluentd_facts_if_unset(facts)
  705. facts = set_node_schedulability(facts)
  706. facts = set_master_selectors(facts)
  707. facts = set_metrics_facts_if_unset(facts)
  708. facts = set_identity_providers_if_unset(facts)
  709. facts = set_sdn_facts_if_unset(facts)
  710. facts = set_deployment_facts_if_unset(facts)
  711. facts = set_aggregate_facts(facts)
  712. return dict(openshift=facts)
  713. def get_defaults(self, roles):
  714. """ Get default fact values
  715. Args:
  716. roles (list): list of roles for this host
  717. Returns:
  718. dict: The generated default facts
  719. """
  720. defaults = dict()
  721. ip_addr = self.system_facts['default_ipv4']['address']
  722. exit_code, output, _ = module.run_command(['hostname', '-f'])
  723. hostname_f = output.strip() if exit_code == 0 else ''
  724. hostname_values = [hostname_f, self.system_facts['nodename'],
  725. self.system_facts['fqdn']]
  726. hostname = choose_hostname(hostname_values, ip_addr)
  727. common = dict(use_openshift_sdn=True, ip=ip_addr, public_ip=ip_addr,
  728. deployment_type='origin', hostname=hostname,
  729. public_hostname=hostname)
  730. common['client_binary'] = 'oc' if os.path.isfile('/usr/bin/oc') else 'osc'
  731. common['admin_binary'] = 'oadm' if os.path.isfile('/usr/bin/oadm') else 'osadm'
  732. defaults['common'] = common
  733. if 'master' in roles:
  734. master = dict(api_use_ssl=True, api_port='8443',
  735. console_use_ssl=True, console_path='/console',
  736. console_port='8443', etcd_use_ssl=True, etcd_hosts='',
  737. etcd_port='4001', portal_net='172.30.0.0/16',
  738. embedded_etcd=True, embedded_kube=True,
  739. embedded_dns=True, dns_port='53',
  740. bind_addr='0.0.0.0', session_max_seconds=3600,
  741. session_name='ssn', session_secrets_file='',
  742. access_token_max_seconds=86400,
  743. auth_token_max_seconds=500,
  744. oauth_grant_method='auto', cluster_defer_ha=False)
  745. defaults['master'] = master
  746. if 'node' in roles:
  747. node = dict(labels={}, annotations={}, portal_net='172.30.0.0/16')
  748. defaults['node'] = node
  749. return defaults
  750. def guess_host_provider(self):
  751. """ Guess the host provider
  752. Returns:
  753. dict: The generated default facts for the detected provider
  754. """
  755. # TODO: cloud provider facts should probably be submitted upstream
  756. product_name = self.system_facts['product_name']
  757. product_version = self.system_facts['product_version']
  758. virt_type = self.system_facts['virtualization_type']
  759. virt_role = self.system_facts['virtualization_role']
  760. provider = None
  761. metadata = None
  762. # TODO: this is not exposed through module_utils/facts.py in ansible,
  763. # need to create PR for ansible to expose it
  764. bios_vendor = get_file_content(
  765. '/sys/devices/virtual/dmi/id/bios_vendor'
  766. )
  767. if bios_vendor == 'Google':
  768. provider = 'gce'
  769. metadata_url = ('http://metadata.google.internal/'
  770. 'computeMetadata/v1/?recursive=true')
  771. headers = {'Metadata-Flavor': 'Google'}
  772. metadata = get_provider_metadata(metadata_url, True, headers,
  773. True)
  774. # Filter sshKeys and serviceAccounts from gce metadata
  775. if metadata:
  776. metadata['project']['attributes'].pop('sshKeys', None)
  777. metadata['instance'].pop('serviceAccounts', None)
  778. elif (virt_type == 'xen' and virt_role == 'guest'
  779. and re.match(r'.*\.amazon$', product_version)):
  780. provider = 'ec2'
  781. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  782. metadata = get_provider_metadata(metadata_url)
  783. elif re.search(r'OpenStack', product_name):
  784. provider = 'openstack'
  785. metadata_url = ('http://169.254.169.254/openstack/latest/'
  786. 'meta_data.json')
  787. metadata = get_provider_metadata(metadata_url, True, None,
  788. True)
  789. if metadata:
  790. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  791. metadata['ec2_compat'] = get_provider_metadata(
  792. ec2_compat_url
  793. )
  794. # disable pylint maybe-no-member because overloaded use of
  795. # the module name causes pylint to not detect that results
  796. # is an array or hash
  797. # pylint: disable=maybe-no-member
  798. # Filter public_keys and random_seed from openstack metadata
  799. metadata.pop('public_keys', None)
  800. metadata.pop('random_seed', None)
  801. if not metadata['ec2_compat']:
  802. metadata = None
  803. return dict(name=provider, metadata=metadata)
  804. def init_provider_facts(self):
  805. """ Initialize the provider facts
  806. Returns:
  807. dict: The normalized provider facts
  808. """
  809. provider_info = self.guess_host_provider()
  810. provider_facts = normalize_provider_facts(
  811. provider_info.get('name'),
  812. provider_info.get('metadata')
  813. )
  814. return provider_facts
  815. def init_local_facts(self, facts=None):
  816. """ Initialize the provider facts
  817. Args:
  818. facts (dict): local facts to set
  819. Returns:
  820. dict: The result of merging the provided facts with existing
  821. local facts
  822. """
  823. changed = False
  824. facts_to_set = {self.role: dict()}
  825. if facts is not None:
  826. facts_to_set[self.role] = facts
  827. local_facts = get_local_facts_from_file(self.filename)
  828. for arg in ['labels', 'annotations']:
  829. if arg in facts_to_set and isinstance(facts_to_set[arg],
  830. basestring):
  831. facts_to_set[arg] = module.from_json(facts_to_set[arg])
  832. new_local_facts = merge_facts(local_facts, facts_to_set)
  833. for facts in new_local_facts.values():
  834. keys_to_delete = []
  835. for fact, value in facts.iteritems():
  836. if value == "" or value is None:
  837. keys_to_delete.append(fact)
  838. for key in keys_to_delete:
  839. del facts[key]
  840. if new_local_facts != local_facts:
  841. changed = True
  842. if not module.check_mode:
  843. save_local_facts(self.filename, new_local_facts)
  844. self.changed = changed
  845. return new_local_facts
  846. def main():
  847. """ main """
  848. # disabling pylint errors for global-variable-undefined and invalid-name
  849. # for 'global module' usage, since it is required to use ansible_facts
  850. # pylint: disable=global-variable-undefined, invalid-name
  851. global module
  852. module = AnsibleModule(
  853. argument_spec=dict(
  854. role=dict(default='common', required=False,
  855. choices=OpenShiftFacts.known_roles),
  856. local_facts=dict(default=None, type='dict', required=False),
  857. ),
  858. supports_check_mode=True,
  859. add_file_common_args=True,
  860. )
  861. role = module.params['role']
  862. local_facts = module.params['local_facts']
  863. fact_file = '/etc/ansible/facts.d/openshift.fact'
  864. openshift_facts = OpenShiftFacts(role, fact_file, local_facts)
  865. file_params = module.params.copy()
  866. file_params['path'] = fact_file
  867. file_args = module.load_file_common_arguments(file_params)
  868. changed = module.set_fs_attributes_if_different(file_args,
  869. openshift_facts.changed)
  870. return module.exit_json(changed=changed,
  871. ansible_facts=openshift_facts.facts)
  872. # ignore pylint errors related to the module_utils import
  873. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  874. # import module snippets
  875. from ansible.module_utils.basic import *
  876. from ansible.module_utils.facts import *
  877. from ansible.module_utils.urls import *
  878. if __name__ == '__main__':
  879. main()