openshift_facts.py 34 KB

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