openshift_facts.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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_identity_providers_if_unset(facts):
  305. """ Set identity_providers fact if not already present in facts dict
  306. Args:
  307. facts (dict): existing facts
  308. Returns:
  309. dict: the facts dict updated with the generated identity providers
  310. facts if they were not already present
  311. """
  312. if 'master' in facts:
  313. deployment_type = facts['common']['deployment_type']
  314. if 'identity_providers' not in facts['master']:
  315. identity_provider = dict(
  316. name='allow_all', challenge=True, login=True,
  317. kind='AllowAllPasswordIdentityProvider'
  318. )
  319. if deployment_type == 'enterprise':
  320. identity_provider = dict(
  321. name='deny_all', challenge=True, login=True,
  322. kind='DenyAllPasswordIdentityProvider'
  323. )
  324. facts['master']['identity_providers'] = [identity_provider]
  325. return facts
  326. def set_url_facts_if_unset(facts):
  327. """ Set url facts 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 url facts if they
  332. were not already present
  333. """
  334. if 'master' in facts:
  335. api_use_ssl = facts['master']['api_use_ssl']
  336. api_port = facts['master']['api_port']
  337. console_use_ssl = facts['master']['console_use_ssl']
  338. console_port = facts['master']['console_port']
  339. console_path = facts['master']['console_path']
  340. etcd_use_ssl = facts['master']['etcd_use_ssl']
  341. etcd_hosts = facts['master']['etcd_hosts']
  342. etcd_port = facts['master']['etcd_port']
  343. hostname = facts['common']['hostname']
  344. public_hostname = facts['common']['public_hostname']
  345. cluster_hostname = facts['master'].get('cluster_hostname')
  346. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  347. if 'etcd_urls' not in facts['master']:
  348. etcd_urls = []
  349. if etcd_hosts != '':
  350. facts['master']['etcd_port'] = etcd_port
  351. facts['master']['embedded_etcd'] = False
  352. for host in etcd_hosts:
  353. etcd_urls.append(format_url(etcd_use_ssl, host,
  354. etcd_port))
  355. else:
  356. etcd_urls = [format_url(etcd_use_ssl, hostname,
  357. etcd_port)]
  358. facts['master']['etcd_urls'] = etcd_urls
  359. if 'api_url' not in facts['master']:
  360. api_hostname = cluster_hostname if cluster_hostname else hostname
  361. facts['master']['api_url'] = format_url(api_use_ssl, api_hostname,
  362. api_port)
  363. if 'public_api_url' not in facts['master']:
  364. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  365. facts['master']['public_api_url'] = format_url(api_use_ssl,
  366. api_public_hostname,
  367. api_port)
  368. if 'console_url' not in facts['master']:
  369. console_hostname = cluster_hostname if cluster_hostname else hostname
  370. facts['master']['console_url'] = format_url(console_use_ssl,
  371. console_hostname,
  372. console_port,
  373. console_path)
  374. if 'public_console_url' not in facts['master']:
  375. console_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  376. facts['master']['public_console_url'] = format_url(console_use_ssl,
  377. console_public_hostname,
  378. console_port,
  379. console_path)
  380. return facts
  381. def set_aggregate_facts(facts):
  382. """ Set aggregate facts
  383. Args:
  384. facts (dict): existing facts
  385. Returns:
  386. dict: the facts dict updated with aggregated facts
  387. """
  388. all_hostnames = set()
  389. if 'common' in facts:
  390. all_hostnames.add(facts['common']['hostname'])
  391. all_hostnames.add(facts['common']['public_hostname'])
  392. if 'master' in facts:
  393. if 'cluster_hostname' in facts['master']:
  394. all_hostnames.add(facts['master']['cluster_hostname'])
  395. if 'cluster_public_hostname' in facts['master']:
  396. all_hostnames.add(facts['master']['cluster_public_hostname'])
  397. facts['common']['all_hostnames'] = list(all_hostnames)
  398. return facts
  399. def set_node_plugin_facts_if_unset(facts):
  400. """ Set Facts for node storage plugin dependencies if not set.
  401. Args:
  402. facts (dict): existing facts
  403. Returns:
  404. dict: the facts dict updated with the generated storage plugin
  405. dependency facts
  406. """
  407. if 'node' in facts:
  408. if 'storage_plugin_deps' not in facts['node']:
  409. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs']
  410. return facts
  411. def set_deployment_facts_if_unset(facts):
  412. """ Set Facts that vary based on deployment_type. This currently
  413. includes common.service_type, common.config_base, master.registry_url,
  414. node.registry_url
  415. Args:
  416. facts (dict): existing facts
  417. Returns:
  418. dict: the facts dict updated with the generated deployment_type
  419. facts
  420. """
  421. # Perhaps re-factor this as a map?
  422. # pylint: disable=too-many-branches
  423. if 'common' in facts:
  424. deployment_type = facts['common']['deployment_type']
  425. if 'service_type' not in facts['common']:
  426. service_type = 'atomic-openshift'
  427. if deployment_type == 'origin':
  428. service_type = 'origin'
  429. elif deployment_type in ['enterprise', 'online']:
  430. service_type = 'openshift'
  431. facts['common']['service_type'] = service_type
  432. if 'config_base' not in facts['common']:
  433. config_base = '/etc/origin'
  434. if deployment_type in ['enterprise', 'online']:
  435. config_base = '/etc/openshift'
  436. facts['common']['config_base'] = config_base
  437. if 'data_dir' not in facts['common']:
  438. data_dir = '/var/lib/origin'
  439. if deployment_type in ['enterprise', 'online']:
  440. data_dir = '/var/lib/openshift'
  441. facts['common']['data_dir'] = data_dir
  442. facts['common']['version'] = get_openshift_version()
  443. for role in ('master', 'node'):
  444. if role in facts:
  445. deployment_type = facts['common']['deployment_type']
  446. if 'registry_url' not in facts[role]:
  447. registry_url = 'openshift/origin-${component}:${version}'
  448. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  449. registry_url = 'openshift3/ose-${component}:${version}'
  450. elif deployment_type == 'atomic-enterprise':
  451. registry_url = 'aep3/aep-${component}:${version}'
  452. facts[role]['registry_url'] = registry_url
  453. return facts
  454. def set_sdn_facts_if_unset(facts):
  455. """ Set sdn facts if not already present in facts dict
  456. Args:
  457. facts (dict): existing facts
  458. Returns:
  459. dict: the facts dict updated with the generated sdn facts if they
  460. were not already present
  461. """
  462. if 'common' in facts:
  463. use_sdn = facts['common']['use_openshift_sdn']
  464. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  465. facts['common']['use_openshift_sdn'] = bool(strtobool(str(use_sdn)))
  466. if 'sdn_network_plugin_name' not in facts['common']:
  467. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  468. facts['common']['sdn_network_plugin_name'] = plugin
  469. if 'master' in facts:
  470. if 'sdn_cluster_network_cidr' not in facts['master']:
  471. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  472. if 'sdn_host_subnet_length' not in facts['master']:
  473. facts['master']['sdn_host_subnet_length'] = '8'
  474. if 'node' in facts:
  475. if 'sdn_mtu' not in facts['node']:
  476. facts['node']['sdn_mtu'] = '1450'
  477. return facts
  478. def format_url(use_ssl, hostname, port, path=''):
  479. """ Format url based on ssl flag, hostname, port and path
  480. Args:
  481. use_ssl (bool): is ssl enabled
  482. hostname (str): hostname
  483. port (str): port
  484. path (str): url path
  485. Returns:
  486. str: The generated url string
  487. """
  488. scheme = 'https' if use_ssl else 'http'
  489. netloc = hostname
  490. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  491. netloc += ":%s" % port
  492. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  493. def get_current_config(facts):
  494. """ Get current openshift config
  495. Args:
  496. facts (dict): existing facts
  497. Returns:
  498. dict: the facts dict updated with the current openshift config
  499. """
  500. current_config = dict()
  501. roles = [role for role in facts if role not in ['common', 'provider']]
  502. for role in roles:
  503. if 'roles' in current_config:
  504. current_config['roles'].append(role)
  505. else:
  506. current_config['roles'] = [role]
  507. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  508. # determine the location of files.
  509. # TODO: I suspect this isn't working right now, but it doesn't prevent
  510. # anything from working properly as far as I can tell, perhaps because
  511. # we override the kubeconfig path everywhere we use it?
  512. # Query kubeconfig settings
  513. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  514. if role == 'node':
  515. kubeconfig_dir = os.path.join(
  516. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  517. )
  518. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  519. if (os.path.isfile('/usr/bin/openshift')
  520. and os.path.isfile(kubeconfig_path)):
  521. try:
  522. _, output, _ = module.run_command(
  523. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  524. "json", "--kubeconfig=%s" % kubeconfig_path],
  525. check_rc=False
  526. )
  527. config = json.loads(output)
  528. cad = 'certificate-authority-data'
  529. try:
  530. for cluster in config['clusters']:
  531. config['clusters'][cluster][cad] = 'masked'
  532. except KeyError:
  533. pass
  534. try:
  535. for user in config['users']:
  536. config['users'][user][cad] = 'masked'
  537. config['users'][user]['client-key-data'] = 'masked'
  538. except KeyError:
  539. pass
  540. current_config['kubeconfig'] = config
  541. # override pylint broad-except warning, since we do not want
  542. # to bubble up any exceptions if oc config view
  543. # fails
  544. # pylint: disable=broad-except
  545. except Exception:
  546. pass
  547. return current_config
  548. def get_openshift_version():
  549. """ Get current version of openshift on the host
  550. Returns:
  551. version: the current openshift version
  552. """
  553. version = ''
  554. if os.path.isfile('/usr/bin/openshift'):
  555. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  556. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  557. version = versions.get('openshift', '')
  558. #TODO: acknowledge the possility of a containerized install
  559. return version
  560. def apply_provider_facts(facts, provider_facts):
  561. """ Apply provider facts to supplied facts dict
  562. Args:
  563. facts (dict): facts dict to update
  564. provider_facts (dict): provider facts to apply
  565. roles: host roles
  566. Returns:
  567. dict: the merged facts
  568. """
  569. if not provider_facts:
  570. return facts
  571. use_openshift_sdn = provider_facts.get('use_openshift_sdn')
  572. if isinstance(use_openshift_sdn, bool):
  573. facts['common']['use_openshift_sdn'] = use_openshift_sdn
  574. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  575. for h_var, ip_var in common_vars:
  576. ip_value = provider_facts['network'].get(ip_var)
  577. if ip_value:
  578. facts['common'][ip_var] = ip_value
  579. facts['common'][h_var] = choose_hostname(
  580. [provider_facts['network'].get(h_var)],
  581. facts['common'][ip_var]
  582. )
  583. facts['provider'] = provider_facts
  584. return facts
  585. def merge_facts(orig, new):
  586. """ Recursively merge facts dicts
  587. Args:
  588. orig (dict): existing facts
  589. new (dict): facts to update
  590. Returns:
  591. dict: the merged facts
  592. """
  593. facts = dict()
  594. for key, value in orig.iteritems():
  595. if key in new:
  596. if isinstance(value, dict) and isinstance(new[key], dict):
  597. facts[key] = merge_facts(value, new[key])
  598. else:
  599. facts[key] = copy.copy(new[key])
  600. else:
  601. facts[key] = copy.deepcopy(value)
  602. new_keys = set(new.keys()) - set(orig.keys())
  603. for key in new_keys:
  604. facts[key] = copy.deepcopy(new[key])
  605. return facts
  606. def save_local_facts(filename, facts):
  607. """ Save local facts
  608. Args:
  609. filename (str): local facts file
  610. facts (dict): facts to set
  611. """
  612. try:
  613. fact_dir = os.path.dirname(filename)
  614. if not os.path.exists(fact_dir):
  615. os.makedirs(fact_dir)
  616. with open(filename, 'w') as fact_file:
  617. fact_file.write(module.jsonify(facts))
  618. except (IOError, OSError) as ex:
  619. raise OpenShiftFactsFileWriteError(
  620. "Could not create fact file: %s, error: %s" % (filename, ex)
  621. )
  622. def get_local_facts_from_file(filename):
  623. """ Retrieve local facts from fact file
  624. Args:
  625. filename (str): local facts file
  626. Returns:
  627. dict: the retrieved facts
  628. """
  629. local_facts = dict()
  630. try:
  631. # Handle conversion of INI style facts file to json style
  632. ini_facts = ConfigParser.SafeConfigParser()
  633. ini_facts.read(filename)
  634. for section in ini_facts.sections():
  635. local_facts[section] = dict()
  636. for key, value in ini_facts.items(section):
  637. local_facts[section][key] = value
  638. except (ConfigParser.MissingSectionHeaderError,
  639. ConfigParser.ParsingError):
  640. try:
  641. with open(filename, 'r') as facts_file:
  642. local_facts = json.load(facts_file)
  643. except (ValueError, IOError):
  644. pass
  645. return local_facts
  646. class OpenShiftFactsUnsupportedRoleError(Exception):
  647. """Origin Facts Unsupported Role Error"""
  648. pass
  649. class OpenShiftFactsFileWriteError(Exception):
  650. """Origin Facts File Write Error"""
  651. pass
  652. class OpenShiftFactsMetadataUnavailableError(Exception):
  653. """Origin Facts Metadata Unavailable Error"""
  654. pass
  655. class OpenShiftFacts(object):
  656. """ Origin Facts
  657. Attributes:
  658. facts (dict): facts for the host
  659. Args:
  660. role (str): role for setting local facts
  661. filename (str): local facts file to use
  662. local_facts (dict): local facts to set
  663. Raises:
  664. OpenShiftFactsUnsupportedRoleError:
  665. """
  666. known_roles = ['common', 'master', 'node', 'master_sdn', 'node_sdn', 'dns']
  667. def __init__(self, role, filename, local_facts):
  668. self.changed = False
  669. self.filename = filename
  670. if role not in self.known_roles:
  671. raise OpenShiftFactsUnsupportedRoleError(
  672. "Role %s is not supported by this module" % role
  673. )
  674. self.role = role
  675. self.system_facts = ansible_facts(module)
  676. self.facts = self.generate_facts(local_facts)
  677. def generate_facts(self, local_facts):
  678. """ Generate facts
  679. Args:
  680. local_facts (dict): local_facts for overriding generated
  681. defaults
  682. Returns:
  683. dict: The generated facts
  684. """
  685. local_facts = self.init_local_facts(local_facts)
  686. roles = local_facts.keys()
  687. defaults = self.get_defaults(roles)
  688. provider_facts = self.init_provider_facts()
  689. facts = apply_provider_facts(defaults, provider_facts)
  690. facts = merge_facts(facts, local_facts)
  691. facts['current_config'] = get_current_config(facts)
  692. facts = set_url_facts_if_unset(facts)
  693. facts = set_fluentd_facts_if_unset(facts)
  694. facts = set_node_schedulability(facts)
  695. facts = set_master_selectors(facts)
  696. facts = set_metrics_facts_if_unset(facts)
  697. facts = set_identity_providers_if_unset(facts)
  698. facts = set_sdn_facts_if_unset(facts)
  699. facts = set_deployment_facts_if_unset(facts)
  700. facts = set_node_plugin_facts_if_unset(facts)
  701. facts = set_aggregate_facts(facts)
  702. return dict(openshift=facts)
  703. def get_defaults(self, roles):
  704. """ Get default fact values
  705. Args:
  706. roles (list): list of roles for this host
  707. Returns:
  708. dict: The generated default facts
  709. """
  710. defaults = dict()
  711. ip_addr = self.system_facts['default_ipv4']['address']
  712. exit_code, output, _ = module.run_command(['hostname', '-f'])
  713. hostname_f = output.strip() if exit_code == 0 else ''
  714. hostname_values = [hostname_f, self.system_facts['nodename'],
  715. self.system_facts['fqdn']]
  716. hostname = choose_hostname(hostname_values, ip_addr)
  717. common = dict(use_openshift_sdn=True, ip=ip_addr, public_ip=ip_addr,
  718. deployment_type='origin', hostname=hostname,
  719. public_hostname=hostname)
  720. common['client_binary'] = 'oc' if os.path.isfile('/usr/bin/oc') else 'osc'
  721. common['admin_binary'] = 'oadm' if os.path.isfile('/usr/bin/oadm') else 'osadm'
  722. defaults['common'] = common
  723. if 'master' in roles:
  724. master = dict(api_use_ssl=True, api_port='8443',
  725. console_use_ssl=True, console_path='/console',
  726. console_port='8443', etcd_use_ssl=True, etcd_hosts='',
  727. etcd_port='4001', portal_net='172.30.0.0/16',
  728. embedded_etcd=True, embedded_kube=True,
  729. embedded_dns=True, dns_port='53',
  730. bind_addr='0.0.0.0', session_max_seconds=3600,
  731. session_name='ssn', session_secrets_file='',
  732. access_token_max_seconds=86400,
  733. auth_token_max_seconds=500,
  734. oauth_grant_method='auto', cluster_defer_ha=False)
  735. defaults['master'] = master
  736. if 'node' in roles:
  737. node = dict(labels={}, annotations={}, portal_net='172.30.0.0/16')
  738. defaults['node'] = node
  739. return defaults
  740. def guess_host_provider(self):
  741. """ Guess the host provider
  742. Returns:
  743. dict: The generated default facts for the detected provider
  744. """
  745. # TODO: cloud provider facts should probably be submitted upstream
  746. product_name = self.system_facts['product_name']
  747. product_version = self.system_facts['product_version']
  748. virt_type = self.system_facts['virtualization_type']
  749. virt_role = self.system_facts['virtualization_role']
  750. provider = None
  751. metadata = None
  752. # TODO: this is not exposed through module_utils/facts.py in ansible,
  753. # need to create PR for ansible to expose it
  754. bios_vendor = get_file_content(
  755. '/sys/devices/virtual/dmi/id/bios_vendor'
  756. )
  757. if bios_vendor == 'Google':
  758. provider = 'gce'
  759. metadata_url = ('http://metadata.google.internal/'
  760. 'computeMetadata/v1/?recursive=true')
  761. headers = {'Metadata-Flavor': 'Google'}
  762. metadata = get_provider_metadata(metadata_url, True, headers,
  763. True)
  764. # Filter sshKeys and serviceAccounts from gce metadata
  765. if metadata:
  766. metadata['project']['attributes'].pop('sshKeys', None)
  767. metadata['instance'].pop('serviceAccounts', None)
  768. elif (virt_type == 'xen' and virt_role == 'guest'
  769. and re.match(r'.*\.amazon$', product_version)):
  770. provider = 'ec2'
  771. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  772. metadata = get_provider_metadata(metadata_url)
  773. elif re.search(r'OpenStack', product_name):
  774. provider = 'openstack'
  775. metadata_url = ('http://169.254.169.254/openstack/latest/'
  776. 'meta_data.json')
  777. metadata = get_provider_metadata(metadata_url, True, None,
  778. True)
  779. if metadata:
  780. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  781. metadata['ec2_compat'] = get_provider_metadata(
  782. ec2_compat_url
  783. )
  784. # disable pylint maybe-no-member because overloaded use of
  785. # the module name causes pylint to not detect that results
  786. # is an array or hash
  787. # pylint: disable=maybe-no-member
  788. # Filter public_keys and random_seed from openstack metadata
  789. metadata.pop('public_keys', None)
  790. metadata.pop('random_seed', None)
  791. if not metadata['ec2_compat']:
  792. metadata = None
  793. return dict(name=provider, metadata=metadata)
  794. def init_provider_facts(self):
  795. """ Initialize the provider facts
  796. Returns:
  797. dict: The normalized provider facts
  798. """
  799. provider_info = self.guess_host_provider()
  800. provider_facts = normalize_provider_facts(
  801. provider_info.get('name'),
  802. provider_info.get('metadata')
  803. )
  804. return provider_facts
  805. def init_local_facts(self, facts=None):
  806. """ Initialize the provider facts
  807. Args:
  808. facts (dict): local facts to set
  809. Returns:
  810. dict: The result of merging the provided facts with existing
  811. local facts
  812. """
  813. changed = False
  814. facts_to_set = {self.role: dict()}
  815. if facts is not None:
  816. facts_to_set[self.role] = facts
  817. local_facts = get_local_facts_from_file(self.filename)
  818. for arg in ['labels', 'annotations']:
  819. if arg in facts_to_set and isinstance(facts_to_set[arg],
  820. basestring):
  821. facts_to_set[arg] = module.from_json(facts_to_set[arg])
  822. new_local_facts = merge_facts(local_facts, facts_to_set)
  823. for facts in new_local_facts.values():
  824. keys_to_delete = []
  825. for fact, value in facts.iteritems():
  826. if value == "" or value is None:
  827. keys_to_delete.append(fact)
  828. for key in keys_to_delete:
  829. del facts[key]
  830. if new_local_facts != local_facts:
  831. changed = True
  832. if not module.check_mode:
  833. save_local_facts(self.filename, new_local_facts)
  834. self.changed = changed
  835. return new_local_facts
  836. def main():
  837. """ main """
  838. # disabling pylint errors for global-variable-undefined and invalid-name
  839. # for 'global module' usage, since it is required to use ansible_facts
  840. # pylint: disable=global-variable-undefined, invalid-name
  841. global module
  842. module = AnsibleModule(
  843. argument_spec=dict(
  844. role=dict(default='common', required=False,
  845. choices=OpenShiftFacts.known_roles),
  846. local_facts=dict(default=None, type='dict', required=False),
  847. ),
  848. supports_check_mode=True,
  849. add_file_common_args=True,
  850. )
  851. role = module.params['role']
  852. local_facts = module.params['local_facts']
  853. fact_file = '/etc/ansible/facts.d/openshift.fact'
  854. openshift_facts = OpenShiftFacts(role, fact_file, local_facts)
  855. file_params = module.params.copy()
  856. file_params['path'] = fact_file
  857. file_args = module.load_file_common_arguments(file_params)
  858. changed = module.set_fs_attributes_if_different(file_args,
  859. openshift_facts.changed)
  860. return module.exit_json(changed=changed,
  861. ansible_facts=openshift_facts.facts)
  862. # ignore pylint errors related to the module_utils import
  863. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  864. # import module snippets
  865. from ansible.module_utils.basic import *
  866. from ansible.module_utils.facts import *
  867. from ansible.module_utils.urls import *
  868. if __name__ == '__main__':
  869. main()