openshift_facts.py 54 KB

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