openshift_facts.py 37 KB

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