openshift_facts.py 54 KB

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