openshift_facts.py 37 KB

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