openshift_facts.py 57 KB

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