openshift_facts.py 44 KB

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