openshift_facts.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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. console_use_ssl = facts['master']['console_use_ssl']
  392. console_port = facts['master']['console_port']
  393. console_path = facts['master']['console_path']
  394. etcd_use_ssl = facts['master']['etcd_use_ssl']
  395. etcd_hosts = facts['master']['etcd_hosts']
  396. etcd_port = facts['master']['etcd_port']
  397. hostname = facts['common']['hostname']
  398. public_hostname = facts['common']['public_hostname']
  399. cluster_hostname = facts['master'].get('cluster_hostname')
  400. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  401. if 'etcd_urls' not in facts['master']:
  402. etcd_urls = []
  403. if etcd_hosts != '':
  404. facts['master']['etcd_port'] = etcd_port
  405. facts['master']['embedded_etcd'] = False
  406. for host in etcd_hosts:
  407. etcd_urls.append(format_url(etcd_use_ssl, host,
  408. etcd_port))
  409. else:
  410. etcd_urls = [format_url(etcd_use_ssl, hostname,
  411. etcd_port)]
  412. facts['master']['etcd_urls'] = etcd_urls
  413. if 'api_url' not in facts['master']:
  414. api_hostname = cluster_hostname if cluster_hostname else hostname
  415. facts['master']['api_url'] = format_url(api_use_ssl, api_hostname,
  416. api_port)
  417. if 'public_api_url' not in facts['master']:
  418. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  419. facts['master']['public_api_url'] = format_url(api_use_ssl,
  420. api_public_hostname,
  421. api_port)
  422. if 'console_url' not in facts['master']:
  423. console_hostname = cluster_hostname if cluster_hostname else hostname
  424. facts['master']['console_url'] = format_url(console_use_ssl,
  425. console_hostname,
  426. console_port,
  427. console_path)
  428. if 'public_console_url' not in facts['master']:
  429. console_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  430. facts['master']['public_console_url'] = format_url(console_use_ssl,
  431. console_public_hostname,
  432. console_port,
  433. console_path)
  434. return facts
  435. def set_aggregate_facts(facts):
  436. """ Set aggregate facts
  437. Args:
  438. facts (dict): existing facts
  439. Returns:
  440. dict: the facts dict updated with aggregated facts
  441. """
  442. all_hostnames = set()
  443. internal_hostnames = set()
  444. if 'common' in facts:
  445. all_hostnames.add(facts['common']['hostname'])
  446. all_hostnames.add(facts['common']['public_hostname'])
  447. all_hostnames.add(facts['common']['ip'])
  448. all_hostnames.add(facts['common']['public_ip'])
  449. internal_hostnames.add(facts['common']['hostname'])
  450. internal_hostnames.add(facts['common']['ip'])
  451. cluster_domain = facts['common']['dns_domain']
  452. if 'master' in facts:
  453. if 'cluster_hostname' in facts['master']:
  454. all_hostnames.add(facts['master']['cluster_hostname'])
  455. if 'cluster_public_hostname' in facts['master']:
  456. all_hostnames.add(facts['master']['cluster_public_hostname'])
  457. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  458. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  459. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  460. all_hostnames.update(svc_names)
  461. internal_hostnames.update(svc_names)
  462. first_svc_ip = first_ip(facts['master']['portal_net'])
  463. all_hostnames.add(first_svc_ip)
  464. internal_hostnames.add(first_svc_ip)
  465. facts['common']['all_hostnames'] = list(all_hostnames)
  466. facts['common']['internal_hostnames'] = list(internal_hostnames)
  467. return facts
  468. def set_etcd_facts_if_unset(facts):
  469. """
  470. If using embedded etcd, loads the data directory from master-config.yaml.
  471. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  472. If anything goes wrong parsing these, the fact will not be set.
  473. """
  474. if 'master' in facts and facts['master']['embedded_etcd']:
  475. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  476. if 'etcd_data_dir' not in etcd_facts:
  477. try:
  478. # Parse master config to find actual etcd data dir:
  479. master_cfg_path = os.path.join(facts['common']['config_base'],
  480. 'master/master-config.yaml')
  481. master_cfg_f = open(master_cfg_path, 'r')
  482. config = yaml.safe_load(master_cfg_f.read())
  483. master_cfg_f.close()
  484. etcd_facts['etcd_data_dir'] = \
  485. config['etcdConfig']['storageDirectory']
  486. facts['etcd'] = etcd_facts
  487. # We don't want exceptions bubbling up here:
  488. # pylint: disable=broad-except
  489. except Exception:
  490. pass
  491. else:
  492. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  493. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  494. try:
  495. # Add a fake section for parsing:
  496. ini_str = '[root]\n' + open('/etc/etcd/etcd.conf', 'r').read()
  497. ini_fp = StringIO.StringIO(ini_str)
  498. config = ConfigParser.RawConfigParser()
  499. config.readfp(ini_fp)
  500. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  501. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  502. etcd_data_dir = etcd_data_dir[1:-1]
  503. etcd_facts['etcd_data_dir'] = etcd_data_dir
  504. facts['etcd'] = etcd_facts
  505. # We don't want exceptions bubbling up here:
  506. # pylint: disable=broad-except
  507. except Exception:
  508. pass
  509. return facts
  510. def set_deployment_facts_if_unset(facts):
  511. """ Set Facts that vary based on deployment_type. This currently
  512. includes common.service_type, common.config_base, master.registry_url,
  513. node.registry_url, node.storage_plugin_deps
  514. Args:
  515. facts (dict): existing facts
  516. Returns:
  517. dict: the facts dict updated with the generated deployment_type
  518. facts
  519. """
  520. # disabled to avoid breaking up facts related to deployment type into
  521. # multiple methods for now.
  522. # pylint: disable=too-many-statements, too-many-branches
  523. if 'common' in facts:
  524. deployment_type = facts['common']['deployment_type']
  525. if 'service_type' not in facts['common']:
  526. service_type = 'atomic-openshift'
  527. if deployment_type == 'origin':
  528. service_type = 'origin'
  529. elif deployment_type in ['enterprise']:
  530. service_type = 'openshift'
  531. facts['common']['service_type'] = service_type
  532. if 'config_base' not in facts['common']:
  533. config_base = '/etc/origin'
  534. if deployment_type in ['enterprise', 'online']:
  535. config_base = '/etc/openshift'
  536. # Handle upgrade scenarios when symlinks don't yet exist:
  537. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  538. config_base = '/etc/openshift'
  539. facts['common']['config_base'] = config_base
  540. if 'data_dir' not in facts['common']:
  541. data_dir = '/var/lib/origin'
  542. if deployment_type in ['enterprise', 'online']:
  543. data_dir = '/var/lib/openshift'
  544. # Handle upgrade scenarios when symlinks don't yet exist:
  545. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  546. data_dir = '/var/lib/openshift'
  547. facts['common']['data_dir'] = data_dir
  548. # remove duplicate and empty strings from registry lists
  549. for cat in ['additional', 'blocked', 'insecure']:
  550. key = 'docker_{0}_registries'.format(cat)
  551. if key in facts['common']:
  552. facts['common'][key] = list(set(facts['common'][key]) - set(['']))
  553. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  554. addtl_regs = facts['common'].get('docker_additional_registries', [])
  555. ent_reg = 'registry.access.redhat.com'
  556. if ent_reg not in addtl_regs:
  557. facts['common']['docker_additional_registries'] = addtl_regs + [ent_reg]
  558. for role in ('master', 'node'):
  559. if role in facts:
  560. deployment_type = facts['common']['deployment_type']
  561. if 'registry_url' not in facts[role]:
  562. registry_url = 'openshift/origin-${component}:${version}'
  563. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  564. registry_url = 'openshift3/ose-${component}:${version}'
  565. elif deployment_type == 'atomic-enterprise':
  566. registry_url = 'aep3_beta/aep-${component}:${version}'
  567. facts[role]['registry_url'] = registry_url
  568. if 'master' in facts:
  569. deployment_type = facts['common']['deployment_type']
  570. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  571. if 'disabled_features' in facts['master']:
  572. if deployment_type == 'atomic-enterprise':
  573. curr_disabled_features = set(facts['master']['disabled_features'])
  574. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  575. else:
  576. if deployment_type == 'atomic-enterprise':
  577. facts['master']['disabled_features'] = openshift_features
  578. if 'node' in facts:
  579. deployment_type = facts['common']['deployment_type']
  580. if 'storage_plugin_deps' not in facts['node']:
  581. if deployment_type in ['openshift-enterprise', 'atomic-enterprise']:
  582. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs']
  583. else:
  584. facts['node']['storage_plugin_deps'] = []
  585. return facts
  586. def set_version_facts_if_unset(facts):
  587. """ Set version facts. This currently includes common.version and
  588. common.version_greater_than_3_1_or_1_1.
  589. Args:
  590. facts (dict): existing facts
  591. Returns:
  592. dict: the facts dict updated with version facts.
  593. """
  594. if 'common' in facts:
  595. deployment_type = facts['common']['deployment_type']
  596. facts['common']['version'] = version = get_openshift_version()
  597. if version is not None:
  598. if deployment_type == 'origin':
  599. version_gt_3_1_or_1_1 = LooseVersion(version) > LooseVersion('1.0.6')
  600. version_gt_3_1_1_or_1_1_1 = LooseVersion(version) > LooseVersion('1.1.1')
  601. else:
  602. version_gt_3_1_or_1_1 = LooseVersion(version) > LooseVersion('3.0.2.900')
  603. version_gt_3_1_1_or_1_1_1 = LooseVersion(version) > LooseVersion('3.1.1')
  604. else:
  605. version_gt_3_1_or_1_1 = True
  606. version_gt_3_1_1_or_1_1_1 = True
  607. facts['common']['version_greater_than_3_1_or_1_1'] = version_gt_3_1_or_1_1
  608. facts['common']['version_greater_than_3_1_1_or_1_1_1'] = version_gt_3_1_1_or_1_1_1
  609. return facts
  610. def set_sdn_facts_if_unset(facts, system_facts):
  611. """ Set sdn facts if not already present in facts dict
  612. Args:
  613. facts (dict): existing facts
  614. system_facts (dict): ansible_facts
  615. Returns:
  616. dict: the facts dict updated with the generated sdn facts if they
  617. were not already present
  618. """
  619. if 'common' in facts:
  620. use_sdn = facts['common']['use_openshift_sdn']
  621. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  622. use_sdn = bool(strtobool(str(use_sdn)))
  623. facts['common']['use_openshift_sdn'] = use_sdn
  624. if 'sdn_network_plugin_name' not in facts['common']:
  625. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  626. facts['common']['sdn_network_plugin_name'] = plugin
  627. if 'master' in facts:
  628. if 'sdn_cluster_network_cidr' not in facts['master']:
  629. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  630. if 'sdn_host_subnet_length' not in facts['master']:
  631. facts['master']['sdn_host_subnet_length'] = '8'
  632. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  633. node_ip = facts['common']['ip']
  634. # default MTU if interface MTU cannot be detected
  635. facts['node']['sdn_mtu'] = '1450'
  636. for val in system_facts.itervalues():
  637. if isinstance(val, dict) and 'mtu' in val:
  638. mtu = val['mtu']
  639. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  640. facts['node']['sdn_mtu'] = str(mtu - 50)
  641. return facts
  642. def format_url(use_ssl, hostname, port, path=''):
  643. """ Format url based on ssl flag, hostname, port and path
  644. Args:
  645. use_ssl (bool): is ssl enabled
  646. hostname (str): hostname
  647. port (str): port
  648. path (str): url path
  649. Returns:
  650. str: The generated url string
  651. """
  652. scheme = 'https' if use_ssl else 'http'
  653. netloc = hostname
  654. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  655. netloc += ":%s" % port
  656. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  657. def get_current_config(facts):
  658. """ Get current openshift config
  659. Args:
  660. facts (dict): existing facts
  661. Returns:
  662. dict: the facts dict updated with the current openshift config
  663. """
  664. current_config = dict()
  665. roles = [role for role in facts if role not in ['common', 'provider']]
  666. for role in roles:
  667. if 'roles' in current_config:
  668. current_config['roles'].append(role)
  669. else:
  670. current_config['roles'] = [role]
  671. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  672. # determine the location of files.
  673. # TODO: I suspect this isn't working right now, but it doesn't prevent
  674. # anything from working properly as far as I can tell, perhaps because
  675. # we override the kubeconfig path everywhere we use it?
  676. # Query kubeconfig settings
  677. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  678. if role == 'node':
  679. kubeconfig_dir = os.path.join(
  680. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  681. )
  682. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  683. if (os.path.isfile('/usr/bin/openshift')
  684. and os.path.isfile(kubeconfig_path)):
  685. try:
  686. _, output, _ = module.run_command(
  687. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  688. "json", "--kubeconfig=%s" % kubeconfig_path],
  689. check_rc=False
  690. )
  691. config = json.loads(output)
  692. cad = 'certificate-authority-data'
  693. try:
  694. for cluster in config['clusters']:
  695. config['clusters'][cluster][cad] = 'masked'
  696. except KeyError:
  697. pass
  698. try:
  699. for user in config['users']:
  700. config['users'][user][cad] = 'masked'
  701. config['users'][user]['client-key-data'] = 'masked'
  702. except KeyError:
  703. pass
  704. current_config['kubeconfig'] = config
  705. # override pylint broad-except warning, since we do not want
  706. # to bubble up any exceptions if oc config view
  707. # fails
  708. # pylint: disable=broad-except
  709. except Exception:
  710. pass
  711. return current_config
  712. def get_openshift_version():
  713. """ Get current version of openshift on the host
  714. Returns:
  715. version: the current openshift version
  716. """
  717. version = None
  718. if os.path.isfile('/usr/bin/openshift'):
  719. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  720. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  721. version = versions.get('openshift', '')
  722. #TODO: acknowledge the possility of a containerized install
  723. return version
  724. def apply_provider_facts(facts, provider_facts):
  725. """ Apply provider facts to supplied facts dict
  726. Args:
  727. facts (dict): facts dict to update
  728. provider_facts (dict): provider facts to apply
  729. roles: host roles
  730. Returns:
  731. dict: the merged facts
  732. """
  733. if not provider_facts:
  734. return facts
  735. use_openshift_sdn = provider_facts.get('use_openshift_sdn')
  736. if isinstance(use_openshift_sdn, bool):
  737. facts['common']['use_openshift_sdn'] = use_openshift_sdn
  738. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  739. for h_var, ip_var in common_vars:
  740. ip_value = provider_facts['network'].get(ip_var)
  741. if ip_value:
  742. facts['common'][ip_var] = ip_value
  743. facts['common'][h_var] = choose_hostname(
  744. [provider_facts['network'].get(h_var)],
  745. facts['common'][ip_var]
  746. )
  747. facts['provider'] = provider_facts
  748. return facts
  749. def merge_facts(orig, new, additive_facts_to_overwrite):
  750. """ Recursively merge facts dicts
  751. Args:
  752. orig (dict): existing facts
  753. new (dict): facts to update
  754. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  755. '.' notation ex: ['master.named_certificates']
  756. Returns:
  757. dict: the merged facts
  758. """
  759. additive_facts = ['named_certificates']
  760. facts = dict()
  761. for key, value in orig.iteritems():
  762. if key in new:
  763. if isinstance(value, dict) and isinstance(new[key], dict):
  764. relevant_additive_facts = []
  765. # Keep additive_facts_to_overwrite if key matches
  766. for item in additive_facts_to_overwrite:
  767. if '.' in item and item.startswith(key + '.'):
  768. relevant_additive_facts.append(item)
  769. facts[key] = merge_facts(value, new[key], relevant_additive_facts)
  770. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  771. # Fact is additive so we'll combine orig and new.
  772. if isinstance(value, list) and isinstance(new[key], list):
  773. new_fact = []
  774. for item in copy.deepcopy(value) + copy.copy(new[key]):
  775. if item not in new_fact:
  776. new_fact.append(item)
  777. facts[key] = new_fact
  778. else:
  779. facts[key] = copy.copy(new[key])
  780. else:
  781. facts[key] = copy.deepcopy(value)
  782. new_keys = set(new.keys()) - set(orig.keys())
  783. for key in new_keys:
  784. facts[key] = copy.deepcopy(new[key])
  785. return facts
  786. def save_local_facts(filename, facts):
  787. """ Save local facts
  788. Args:
  789. filename (str): local facts file
  790. facts (dict): facts to set
  791. """
  792. try:
  793. fact_dir = os.path.dirname(filename)
  794. if not os.path.exists(fact_dir):
  795. os.makedirs(fact_dir)
  796. with open(filename, 'w') as fact_file:
  797. fact_file.write(module.jsonify(facts))
  798. os.chmod(filename, 0o600)
  799. except (IOError, OSError) as ex:
  800. raise OpenShiftFactsFileWriteError(
  801. "Could not create fact file: %s, error: %s" % (filename, ex)
  802. )
  803. def get_local_facts_from_file(filename):
  804. """ Retrieve local facts from fact file
  805. Args:
  806. filename (str): local facts file
  807. Returns:
  808. dict: the retrieved facts
  809. """
  810. local_facts = dict()
  811. try:
  812. # Handle conversion of INI style facts file to json style
  813. ini_facts = ConfigParser.SafeConfigParser()
  814. ini_facts.read(filename)
  815. for section in ini_facts.sections():
  816. local_facts[section] = dict()
  817. for key, value in ini_facts.items(section):
  818. local_facts[section][key] = value
  819. except (ConfigParser.MissingSectionHeaderError,
  820. ConfigParser.ParsingError):
  821. try:
  822. with open(filename, 'r') as facts_file:
  823. local_facts = json.load(facts_file)
  824. except (ValueError, IOError):
  825. pass
  826. return local_facts
  827. def set_container_facts_if_unset(facts):
  828. """ Set containerized facts.
  829. Args:
  830. facts (dict): existing facts
  831. Returns:
  832. dict: the facts dict updated with the generated containerization
  833. facts
  834. """
  835. deployment_type = facts['common']['deployment_type']
  836. if deployment_type in ['enterprise', 'openshift-enterprise']:
  837. master_image = 'openshift3/ose'
  838. cli_image = master_image
  839. node_image = 'openshift3/node'
  840. ovs_image = 'openshift3/openvswitch'
  841. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  842. elif deployment_type == 'atomic-enterprise':
  843. master_image = 'aep3_beta/aep'
  844. cli_image = master_image
  845. node_image = 'aep3_beta/node'
  846. ovs_image = 'aep3_beta/openvswitch'
  847. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  848. else:
  849. master_image = 'openshift/origin'
  850. cli_image = master_image
  851. node_image = 'openshift/node'
  852. ovs_image = 'openshift/openvswitch'
  853. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  854. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  855. if 'is_containerized' not in facts['common']:
  856. facts['common']['is_containerized'] = facts['common']['is_atomic']
  857. if 'cli_image' not in facts['common']:
  858. facts['common']['cli_image'] = cli_image
  859. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  860. facts['etcd']['etcd_image'] = etcd_image
  861. if 'master' in facts and 'master_image' not in facts['master']:
  862. facts['master']['master_image'] = master_image
  863. if 'node' in facts:
  864. if 'node_image' not in facts['node']:
  865. facts['node']['node_image'] = node_image
  866. if 'ovs_image' not in facts['node']:
  867. facts['node']['ovs_image'] = ovs_image
  868. return facts
  869. class OpenShiftFactsUnsupportedRoleError(Exception):
  870. """Origin Facts Unsupported Role Error"""
  871. pass
  872. class OpenShiftFactsFileWriteError(Exception):
  873. """Origin Facts File Write Error"""
  874. pass
  875. class OpenShiftFactsMetadataUnavailableError(Exception):
  876. """Origin Facts Metadata Unavailable Error"""
  877. pass
  878. class OpenShiftFacts(object):
  879. """ Origin Facts
  880. Attributes:
  881. facts (dict): facts for the host
  882. Args:
  883. role (str): role for setting local facts
  884. filename (str): local facts file to use
  885. local_facts (dict): local facts to set
  886. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  887. '.' notation ex: ['master.named_certificates']
  888. Raises:
  889. OpenShiftFactsUnsupportedRoleError:
  890. """
  891. known_roles = ['common', 'master', 'node', 'master_sdn', 'node_sdn', 'etcd', 'nfs']
  892. def __init__(self, role, filename, local_facts, additive_facts_to_overwrite=False):
  893. self.changed = False
  894. self.filename = filename
  895. if role not in self.known_roles:
  896. raise OpenShiftFactsUnsupportedRoleError(
  897. "Role %s is not supported by this module" % role
  898. )
  899. self.role = role
  900. self.system_facts = ansible_facts(module)
  901. self.facts = self.generate_facts(local_facts, additive_facts_to_overwrite)
  902. def generate_facts(self, local_facts, additive_facts_to_overwrite):
  903. """ Generate facts
  904. Args:
  905. local_facts (dict): local_facts for overriding generated
  906. defaults
  907. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  908. '.' notation ex: ['master.named_certificates']
  909. Returns:
  910. dict: The generated facts
  911. """
  912. local_facts = self.init_local_facts(local_facts, additive_facts_to_overwrite)
  913. roles = local_facts.keys()
  914. defaults = self.get_defaults(roles)
  915. provider_facts = self.init_provider_facts()
  916. facts = apply_provider_facts(defaults, provider_facts)
  917. facts = merge_facts(facts, local_facts, additive_facts_to_overwrite)
  918. facts['current_config'] = get_current_config(facts)
  919. facts = set_url_facts_if_unset(facts)
  920. facts = set_project_cfg_facts_if_unset(facts)
  921. facts = set_fluentd_facts_if_unset(facts)
  922. facts = set_flannel_facts_if_unset(facts)
  923. facts = set_node_schedulability(facts)
  924. facts = set_master_selectors(facts)
  925. facts = set_metrics_facts_if_unset(facts)
  926. facts = set_identity_providers_if_unset(facts)
  927. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  928. facts = set_deployment_facts_if_unset(facts)
  929. facts = set_version_facts_if_unset(facts)
  930. facts = set_aggregate_facts(facts)
  931. facts = set_etcd_facts_if_unset(facts)
  932. facts = set_container_facts_if_unset(facts)
  933. return dict(openshift=facts)
  934. def get_defaults(self, roles):
  935. """ Get default fact values
  936. Args:
  937. roles (list): list of roles for this host
  938. Returns:
  939. dict: The generated default facts
  940. """
  941. defaults = dict()
  942. ip_addr = self.system_facts['default_ipv4']['address']
  943. exit_code, output, _ = module.run_command(['hostname', '-f'])
  944. hostname_f = output.strip() if exit_code == 0 else ''
  945. hostname_values = [hostname_f, self.system_facts['nodename'],
  946. self.system_facts['fqdn']]
  947. hostname = choose_hostname(hostname_values, ip_addr)
  948. common = dict(use_openshift_sdn=True, ip=ip_addr, public_ip=ip_addr,
  949. deployment_type='origin', hostname=hostname,
  950. public_hostname=hostname, use_manageiq=False)
  951. common['client_binary'] = 'oc'
  952. common['admin_binary'] = 'oadm'
  953. common['dns_domain'] = 'cluster.local'
  954. common['install_examples'] = True
  955. defaults['common'] = common
  956. if 'master' in roles:
  957. master = dict(api_use_ssl=True, api_port='8443',
  958. console_use_ssl=True, console_path='/console',
  959. console_port='8443', etcd_use_ssl=True, etcd_hosts='',
  960. etcd_port='4001', portal_net='172.30.0.0/16',
  961. embedded_etcd=True, embedded_kube=True,
  962. embedded_dns=True, dns_port='53',
  963. bind_addr='0.0.0.0', session_max_seconds=3600,
  964. session_name='ssn', session_secrets_file='',
  965. access_token_max_seconds=86400,
  966. auth_token_max_seconds=500,
  967. oauth_grant_method='auto')
  968. defaults['master'] = master
  969. if 'node' in roles:
  970. node = dict(labels={}, annotations={}, portal_net='172.30.0.0/16',
  971. iptables_sync_period='5s', set_node_ip=False)
  972. defaults['node'] = node
  973. if 'nfs' in roles:
  974. nfs = dict(exports_dir='/var/export', registry_volume='regvol',
  975. export_options='*(rw,sync,all_squash)')
  976. defaults['nfs'] = nfs
  977. return defaults
  978. def guess_host_provider(self):
  979. """ Guess the host provider
  980. Returns:
  981. dict: The generated default facts for the detected provider
  982. """
  983. # TODO: cloud provider facts should probably be submitted upstream
  984. product_name = self.system_facts['product_name']
  985. product_version = self.system_facts['product_version']
  986. virt_type = self.system_facts['virtualization_type']
  987. virt_role = self.system_facts['virtualization_role']
  988. provider = None
  989. metadata = None
  990. # TODO: this is not exposed through module_utils/facts.py in ansible,
  991. # need to create PR for ansible to expose it
  992. bios_vendor = get_file_content(
  993. '/sys/devices/virtual/dmi/id/bios_vendor'
  994. )
  995. if bios_vendor == 'Google':
  996. provider = 'gce'
  997. metadata_url = ('http://metadata.google.internal/'
  998. 'computeMetadata/v1/?recursive=true')
  999. headers = {'Metadata-Flavor': 'Google'}
  1000. metadata = get_provider_metadata(metadata_url, True, headers,
  1001. True)
  1002. # Filter sshKeys and serviceAccounts from gce metadata
  1003. if metadata:
  1004. metadata['project']['attributes'].pop('sshKeys', None)
  1005. metadata['instance'].pop('serviceAccounts', None)
  1006. elif (virt_type == 'xen' and virt_role == 'guest'
  1007. and re.match(r'.*\.amazon$', product_version)):
  1008. provider = 'ec2'
  1009. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1010. metadata = get_provider_metadata(metadata_url)
  1011. elif re.search(r'OpenStack', product_name):
  1012. provider = 'openstack'
  1013. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1014. 'meta_data.json')
  1015. metadata = get_provider_metadata(metadata_url, True, None,
  1016. True)
  1017. if metadata:
  1018. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1019. metadata['ec2_compat'] = get_provider_metadata(
  1020. ec2_compat_url
  1021. )
  1022. # disable pylint maybe-no-member because overloaded use of
  1023. # the module name causes pylint to not detect that results
  1024. # is an array or hash
  1025. # pylint: disable=maybe-no-member
  1026. # Filter public_keys and random_seed from openstack metadata
  1027. metadata.pop('public_keys', None)
  1028. metadata.pop('random_seed', None)
  1029. if not metadata['ec2_compat']:
  1030. metadata = None
  1031. return dict(name=provider, metadata=metadata)
  1032. def init_provider_facts(self):
  1033. """ Initialize the provider facts
  1034. Returns:
  1035. dict: The normalized provider facts
  1036. """
  1037. provider_info = self.guess_host_provider()
  1038. provider_facts = normalize_provider_facts(
  1039. provider_info.get('name'),
  1040. provider_info.get('metadata')
  1041. )
  1042. return provider_facts
  1043. def init_local_facts(self, facts=None, additive_facts_to_overwrite=False):
  1044. """ Initialize the provider facts
  1045. Args:
  1046. facts (dict): local facts to set
  1047. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1048. '.' notation ex: ['master.named_certificates']
  1049. Returns:
  1050. dict: The result of merging the provided facts with existing
  1051. local facts
  1052. """
  1053. changed = False
  1054. facts_to_set = {self.role: dict()}
  1055. if facts is not None:
  1056. facts_to_set[self.role] = facts
  1057. local_facts = get_local_facts_from_file(self.filename)
  1058. for arg in ['labels', 'annotations']:
  1059. if arg in facts_to_set and isinstance(facts_to_set[arg],
  1060. basestring):
  1061. facts_to_set[arg] = module.from_json(facts_to_set[arg])
  1062. new_local_facts = merge_facts(local_facts, facts_to_set, additive_facts_to_overwrite)
  1063. for facts in new_local_facts.values():
  1064. keys_to_delete = []
  1065. for fact, value in facts.iteritems():
  1066. if value == "" or value is None:
  1067. keys_to_delete.append(fact)
  1068. for key in keys_to_delete:
  1069. del facts[key]
  1070. if new_local_facts != local_facts:
  1071. changed = True
  1072. if not module.check_mode:
  1073. save_local_facts(self.filename, new_local_facts)
  1074. self.changed = changed
  1075. return new_local_facts
  1076. def main():
  1077. """ main """
  1078. # disabling pylint errors for global-variable-undefined and invalid-name
  1079. # for 'global module' usage, since it is required to use ansible_facts
  1080. # pylint: disable=global-variable-undefined, invalid-name
  1081. global module
  1082. module = AnsibleModule(
  1083. argument_spec=dict(
  1084. role=dict(default='common', required=False,
  1085. choices=OpenShiftFacts.known_roles),
  1086. local_facts=dict(default=None, type='dict', required=False),
  1087. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1088. ),
  1089. supports_check_mode=True,
  1090. add_file_common_args=True,
  1091. )
  1092. role = module.params['role']
  1093. local_facts = module.params['local_facts']
  1094. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1095. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1096. openshift_facts = OpenShiftFacts(role, fact_file, local_facts, additive_facts_to_overwrite)
  1097. file_params = module.params.copy()
  1098. file_params['path'] = fact_file
  1099. file_args = module.load_file_common_arguments(file_params)
  1100. changed = module.set_fs_attributes_if_different(file_args,
  1101. openshift_facts.changed)
  1102. return module.exit_json(changed=changed,
  1103. ansible_facts=openshift_facts.facts)
  1104. # ignore pylint errors related to the module_utils import
  1105. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1106. # import module snippets
  1107. from ansible.module_utils.basic import *
  1108. from ansible.module_utils.facts import *
  1109. from ansible.module_utils.urls import *
  1110. if __name__ == '__main__':
  1111. main()