openshift_facts.py 40 KB

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