openshift_facts.py 39 KB

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