openshift_facts.py 38 KB

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