openshift_facts.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  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. from dbus import SystemBus, Interface
  27. from dbus.exceptions import DBusException
  28. def migrate_docker_facts(facts):
  29. """ Apply migrations for docker facts """
  30. params = {
  31. 'common': (
  32. 'additional_registries',
  33. 'insecure_registries',
  34. 'blocked_registries',
  35. 'options'
  36. ),
  37. 'node': (
  38. 'log_driver',
  39. 'log_options'
  40. )
  41. }
  42. if 'docker' not in facts:
  43. facts['docker'] = {}
  44. for role in params.keys():
  45. if role in facts:
  46. for param in params[role]:
  47. old_param = 'docker_' + param
  48. if old_param in facts[role]:
  49. facts['docker'][param] = facts[role].pop(old_param)
  50. if 'node' in facts and 'portal_net' in facts['node']:
  51. facts['docker']['hosted_registry_insecure'] = True
  52. facts['docker']['hosted_registry_network'] = facts['node'].pop('portal_net')
  53. return facts
  54. def migrate_local_facts(facts):
  55. """ Apply migrations of local facts """
  56. migrated_facts = copy.deepcopy(facts)
  57. return migrate_docker_facts(migrated_facts)
  58. def first_ip(network):
  59. """ Return the first IPv4 address in network
  60. Args:
  61. network (str): network in CIDR format
  62. Returns:
  63. str: first IPv4 address
  64. """
  65. atoi = lambda addr: struct.unpack("!I", socket.inet_aton(addr))[0]
  66. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr))
  67. (address, netmask) = network.split('/')
  68. netmask_i = (0xffffffff << (32 - atoi(netmask))) & 0xffffffff
  69. return itoa((atoi(address) & netmask_i) + 1)
  70. def hostname_valid(hostname):
  71. """ Test if specified hostname should be considered valid
  72. Args:
  73. hostname (str): hostname to test
  74. Returns:
  75. bool: True if valid, otherwise False
  76. """
  77. if (not hostname or
  78. hostname.startswith('localhost') or
  79. hostname.endswith('localdomain') or
  80. len(hostname.split('.')) < 2):
  81. return False
  82. return True
  83. def choose_hostname(hostnames=None, fallback=''):
  84. """ Choose a hostname from the provided hostnames
  85. Given a list of hostnames and a fallback value, choose a hostname to
  86. use. This function will prefer fqdns if they exist (excluding any that
  87. begin with localhost or end with localdomain) over ip addresses.
  88. Args:
  89. hostnames (list): list of hostnames
  90. fallback (str): default value to set if hostnames does not contain
  91. a valid hostname
  92. Returns:
  93. str: chosen hostname
  94. """
  95. hostname = fallback
  96. if hostnames is None:
  97. return hostname
  98. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  99. ips = [i for i in hostnames
  100. if (i is not None and isinstance(i, basestring)
  101. and re.match(ip_regex, i))]
  102. hosts = [i for i in hostnames
  103. if i is not None and i != '' and i not in ips]
  104. for host_list in (hosts, ips):
  105. for host in host_list:
  106. if hostname_valid(host):
  107. return host
  108. return hostname
  109. def query_metadata(metadata_url, headers=None, expect_json=False):
  110. """ Return metadata from the provided metadata_url
  111. Args:
  112. metadata_url (str): metadata url
  113. headers (dict): headers to set for metadata request
  114. expect_json (bool): does the metadata_url return json
  115. Returns:
  116. dict or list: metadata request result
  117. """
  118. result, info = fetch_url(module, metadata_url, headers=headers)
  119. if info['status'] != 200:
  120. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  121. if expect_json:
  122. return module.from_json(result.read())
  123. else:
  124. return [line.strip() for line in result.readlines()]
  125. def walk_metadata(metadata_url, headers=None, expect_json=False):
  126. """ Walk the metadata tree and return a dictionary of the entire tree
  127. Args:
  128. metadata_url (str): metadata url
  129. headers (dict): headers to set for metadata request
  130. expect_json (bool): does the metadata_url return json
  131. Returns:
  132. dict: the result of walking the metadata tree
  133. """
  134. metadata = dict()
  135. for line in query_metadata(metadata_url, headers, expect_json):
  136. if line.endswith('/') and not line == 'public-keys/':
  137. key = line[:-1]
  138. metadata[key] = walk_metadata(metadata_url + line,
  139. headers, expect_json)
  140. else:
  141. results = query_metadata(metadata_url + line, headers,
  142. expect_json)
  143. if len(results) == 1:
  144. # disable pylint maybe-no-member because overloaded use of
  145. # the module name causes pylint to not detect that results
  146. # is an array or hash
  147. # pylint: disable=maybe-no-member
  148. metadata[line] = results.pop()
  149. else:
  150. metadata[line] = results
  151. return metadata
  152. def get_provider_metadata(metadata_url, supports_recursive=False,
  153. headers=None, expect_json=False):
  154. """ Retrieve the provider metadata
  155. Args:
  156. metadata_url (str): metadata url
  157. supports_recursive (bool): does the provider metadata api support
  158. recursion
  159. headers (dict): headers to set for metadata request
  160. expect_json (bool): does the metadata_url return json
  161. Returns:
  162. dict: the provider metadata
  163. """
  164. try:
  165. if supports_recursive:
  166. metadata = query_metadata(metadata_url, headers,
  167. expect_json)
  168. else:
  169. metadata = walk_metadata(metadata_url, headers,
  170. expect_json)
  171. except OpenShiftFactsMetadataUnavailableError:
  172. metadata = None
  173. return metadata
  174. def normalize_gce_facts(metadata, facts):
  175. """ Normalize gce facts
  176. Args:
  177. metadata (dict): provider metadata
  178. facts (dict): facts to update
  179. Returns:
  180. dict: the result of adding the normalized metadata to the provided
  181. facts dict
  182. """
  183. for interface in metadata['instance']['networkInterfaces']:
  184. int_info = dict(ips=[interface['ip']], network_type='gce')
  185. int_info['public_ips'] = [ac['externalIp'] for ac
  186. in interface['accessConfigs']]
  187. int_info['public_ips'].extend(interface['forwardedIps'])
  188. _, _, network_id = interface['network'].rpartition('/')
  189. int_info['network_id'] = network_id
  190. facts['network']['interfaces'].append(int_info)
  191. _, _, zone = metadata['instance']['zone'].rpartition('/')
  192. facts['zone'] = zone
  193. # GCE currently only supports a single interface
  194. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  195. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  196. facts['network']['public_ip'] = pub_ip
  197. facts['network']['hostname'] = metadata['instance']['hostname']
  198. # TODO: attempt to resolve public_hostname
  199. facts['network']['public_hostname'] = facts['network']['public_ip']
  200. return facts
  201. def normalize_aws_facts(metadata, facts):
  202. """ Normalize aws facts
  203. Args:
  204. metadata (dict): provider metadata
  205. facts (dict): facts to update
  206. Returns:
  207. dict: the result of adding the normalized metadata to the provided
  208. facts dict
  209. """
  210. for interface in sorted(
  211. metadata['network']['interfaces']['macs'].values(),
  212. key=lambda x: x['device-number']
  213. ):
  214. int_info = dict()
  215. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  216. for ips_var, int_var in var_map.iteritems():
  217. ips = interface.get(int_var)
  218. if isinstance(ips, basestring):
  219. int_info[ips_var] = [ips]
  220. else:
  221. int_info[ips_var] = ips
  222. if 'vpc-id' in interface:
  223. int_info['network_type'] = 'vpc'
  224. else:
  225. int_info['network_type'] = 'classic'
  226. if int_info['network_type'] == 'vpc':
  227. int_info['network_id'] = interface['subnet-id']
  228. else:
  229. int_info['network_id'] = None
  230. facts['network']['interfaces'].append(int_info)
  231. facts['zone'] = metadata['placement']['availability-zone']
  232. # TODO: actually attempt to determine default local and public ips
  233. # by using the ansible default ip fact and the ipv4-associations
  234. # from the ec2 metadata
  235. facts['network']['ip'] = metadata.get('local-ipv4')
  236. facts['network']['public_ip'] = metadata.get('public-ipv4')
  237. # TODO: verify that local hostname makes sense and is resolvable
  238. facts['network']['hostname'] = metadata.get('local-hostname')
  239. # TODO: verify that public hostname makes sense and is resolvable
  240. facts['network']['public_hostname'] = metadata.get('public-hostname')
  241. return facts
  242. def normalize_openstack_facts(metadata, facts):
  243. """ Normalize openstack facts
  244. Args:
  245. metadata (dict): provider metadata
  246. facts (dict): facts to update
  247. Returns:
  248. dict: the result of adding the normalized metadata to the provided
  249. facts dict
  250. """
  251. # openstack ec2 compat api does not support network interfaces and
  252. # the version tested on did not include the info in the openstack
  253. # metadata api, should be updated if neutron exposes this.
  254. facts['zone'] = metadata['availability_zone']
  255. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  256. facts['network']['ip'] = local_ipv4
  257. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  258. # TODO: verify local hostname makes sense and is resolvable
  259. facts['network']['hostname'] = metadata['hostname']
  260. # TODO: verify that public hostname makes sense and is resolvable
  261. pub_h = metadata['ec2_compat']['public-hostname']
  262. facts['network']['public_hostname'] = pub_h
  263. return facts
  264. def normalize_provider_facts(provider, metadata):
  265. """ Normalize provider facts
  266. Args:
  267. provider (str): host provider
  268. metadata (dict): provider metadata
  269. Returns:
  270. dict: the normalized provider facts
  271. """
  272. if provider is None or metadata is None:
  273. return {}
  274. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  275. # and configure ipv6 facts if available
  276. # TODO: add support for setting user_data if available
  277. facts = dict(name=provider, metadata=metadata,
  278. network=dict(interfaces=[], ipv6_enabled=False))
  279. if provider == 'gce':
  280. facts = normalize_gce_facts(metadata, facts)
  281. elif provider == 'aws':
  282. facts = normalize_aws_facts(metadata, facts)
  283. elif provider == 'openstack':
  284. facts = normalize_openstack_facts(metadata, facts)
  285. return facts
  286. def set_flannel_facts_if_unset(facts):
  287. """ Set flannel facts if not already present in facts dict
  288. dict: the facts dict updated with the flannel facts if
  289. missing
  290. Args:
  291. facts (dict): existing facts
  292. Returns:
  293. dict: the facts dict updated with the flannel
  294. facts if they were not already present
  295. """
  296. if 'common' in facts:
  297. if 'use_flannel' not in facts['common']:
  298. use_flannel = False
  299. facts['common']['use_flannel'] = use_flannel
  300. return facts
  301. def set_nuage_facts_if_unset(facts):
  302. """ Set nuage facts if not already present in facts dict
  303. dict: the facts dict updated with the nuage facts if
  304. missing
  305. Args:
  306. facts (dict): existing facts
  307. Returns:
  308. dict: the facts dict updated with the nuage
  309. facts if they were not already present
  310. """
  311. if 'common' in facts:
  312. if 'use_nuage' not in facts['common']:
  313. use_nuage = False
  314. facts['common']['use_nuage'] = use_nuage
  315. return facts
  316. def set_node_schedulability(facts):
  317. """ Set schedulable facts if not already present in facts dict
  318. Args:
  319. facts (dict): existing facts
  320. Returns:
  321. dict: the facts dict updated with the generated schedulable
  322. facts if they were not already present
  323. """
  324. if 'node' in facts:
  325. if 'schedulable' not in facts['node']:
  326. if 'master' in facts:
  327. facts['node']['schedulable'] = False
  328. else:
  329. facts['node']['schedulable'] = True
  330. return facts
  331. def set_master_selectors(facts):
  332. """ Set selectors facts if not already present in facts dict
  333. Args:
  334. facts (dict): existing facts
  335. Returns:
  336. dict: the facts dict updated with the generated selectors
  337. facts if they were not already present
  338. """
  339. if 'master' in facts:
  340. if 'infra_nodes' in facts['master']:
  341. deployment_type = facts['common']['deployment_type']
  342. if deployment_type == 'online':
  343. selector = "type=infra"
  344. else:
  345. selector = "region=infra"
  346. if 'router_selector' not in facts['master']:
  347. facts['master']['router_selector'] = selector
  348. if 'registry_selector' not in facts['master']:
  349. facts['master']['registry_selector'] = selector
  350. return facts
  351. def set_metrics_facts_if_unset(facts):
  352. """ Set cluster metrics facts if not already present in facts dict
  353. dict: the facts dict updated with the generated cluster metrics facts if
  354. missing
  355. Args:
  356. facts (dict): existing facts
  357. Returns:
  358. dict: the facts dict updated with the generated cluster metrics
  359. facts if they were not already present
  360. """
  361. if 'common' in facts:
  362. if 'use_cluster_metrics' not in facts['common']:
  363. use_cluster_metrics = False
  364. facts['common']['use_cluster_metrics'] = use_cluster_metrics
  365. return facts
  366. def set_project_cfg_facts_if_unset(facts):
  367. """ Set Project Configuration facts if not already present in facts dict
  368. dict:
  369. Args:
  370. facts (dict): existing facts
  371. Returns:
  372. dict: the facts dict updated with the generated Project Configuration
  373. facts if they were not already present
  374. """
  375. config = {
  376. 'default_node_selector': '',
  377. 'project_request_message': '',
  378. 'project_request_template': '',
  379. 'mcs_allocator_range': 's0:/2',
  380. 'mcs_labels_per_project': 5,
  381. 'uid_allocator_range': '1000000000-1999999999/10000'
  382. }
  383. if 'master' in facts:
  384. for key, value in config.items():
  385. if key not in facts['master']:
  386. facts['master'][key] = value
  387. return facts
  388. def set_identity_providers_if_unset(facts):
  389. """ Set identity_providers fact if not already present in facts dict
  390. Args:
  391. facts (dict): existing facts
  392. Returns:
  393. dict: the facts dict updated with the generated identity providers
  394. facts if they were not already present
  395. """
  396. if 'master' in facts:
  397. deployment_type = facts['common']['deployment_type']
  398. if 'identity_providers' not in facts['master']:
  399. identity_provider = dict(
  400. name='allow_all', challenge=True, login=True,
  401. kind='AllowAllPasswordIdentityProvider'
  402. )
  403. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  404. identity_provider = dict(
  405. name='deny_all', challenge=True, login=True,
  406. kind='DenyAllPasswordIdentityProvider'
  407. )
  408. facts['master']['identity_providers'] = [identity_provider]
  409. return facts
  410. def set_url_facts_if_unset(facts):
  411. """ Set url facts if not already present in facts dict
  412. Args:
  413. facts (dict): existing facts
  414. Returns:
  415. dict: the facts dict updated with the generated url facts if they
  416. were not already present
  417. """
  418. if 'master' in facts:
  419. hostname = facts['common']['hostname']
  420. cluster_hostname = facts['master'].get('cluster_hostname')
  421. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  422. public_hostname = facts['common']['public_hostname']
  423. api_hostname = cluster_hostname if cluster_hostname else hostname
  424. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  425. console_path = facts['master']['console_path']
  426. etcd_hosts = facts['master']['etcd_hosts']
  427. use_ssl = dict(
  428. api=facts['master']['api_use_ssl'],
  429. public_api=facts['master']['api_use_ssl'],
  430. loopback_api=facts['master']['api_use_ssl'],
  431. console=facts['master']['console_use_ssl'],
  432. public_console=facts['master']['console_use_ssl'],
  433. etcd=facts['master']['etcd_use_ssl']
  434. )
  435. ports = dict(
  436. api=facts['master']['api_port'],
  437. public_api=facts['master']['api_port'],
  438. loopback_api=facts['master']['api_port'],
  439. console=facts['master']['console_port'],
  440. public_console=facts['master']['console_port'],
  441. etcd=facts['master']['etcd_port'],
  442. )
  443. etcd_urls = []
  444. if etcd_hosts != '':
  445. facts['master']['etcd_port'] = ports['etcd']
  446. facts['master']['embedded_etcd'] = False
  447. for host in etcd_hosts:
  448. etcd_urls.append(format_url(use_ssl['etcd'], host,
  449. ports['etcd']))
  450. else:
  451. etcd_urls = [format_url(use_ssl['etcd'], hostname,
  452. ports['etcd'])]
  453. facts['master'].setdefault('etcd_urls', etcd_urls)
  454. prefix_hosts = [('api', api_hostname),
  455. ('public_api', api_public_hostname),
  456. ('loopback_api', hostname)]
  457. for prefix, host in prefix_hosts:
  458. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  459. host,
  460. ports[prefix]))
  461. r_lhn = "{0}:{1}".format(hostname, ports['api']).replace('.', '-')
  462. r_lhu = "system:openshift-master/{0}:{1}".format(api_hostname, ports['api']).replace('.', '-')
  463. facts['master'].setdefault('loopback_cluster_name', r_lhn)
  464. facts['master'].setdefault('loopback_context_name', "default/{0}/system:openshift-master".format(r_lhn))
  465. facts['master'].setdefault('loopback_user', r_lhu)
  466. prefix_hosts = [('console', api_hostname), ('public_console', api_public_hostname)]
  467. for prefix, host in prefix_hosts:
  468. facts['master'].setdefault(prefix + '_url', format_url(use_ssl[prefix],
  469. host,
  470. ports[prefix],
  471. console_path))
  472. return facts
  473. def set_aggregate_facts(facts):
  474. """ Set aggregate facts
  475. Args:
  476. facts (dict): existing facts
  477. Returns:
  478. dict: the facts dict updated with aggregated facts
  479. """
  480. all_hostnames = set()
  481. internal_hostnames = set()
  482. if 'common' in facts:
  483. all_hostnames.add(facts['common']['hostname'])
  484. all_hostnames.add(facts['common']['public_hostname'])
  485. all_hostnames.add(facts['common']['ip'])
  486. all_hostnames.add(facts['common']['public_ip'])
  487. internal_hostnames.add(facts['common']['hostname'])
  488. internal_hostnames.add(facts['common']['ip'])
  489. cluster_domain = facts['common']['dns_domain']
  490. if 'master' in facts:
  491. if 'cluster_hostname' in facts['master']:
  492. all_hostnames.add(facts['master']['cluster_hostname'])
  493. if 'cluster_public_hostname' in facts['master']:
  494. all_hostnames.add(facts['master']['cluster_public_hostname'])
  495. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  496. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  497. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  498. all_hostnames.update(svc_names)
  499. internal_hostnames.update(svc_names)
  500. first_svc_ip = first_ip(facts['master']['portal_net'])
  501. all_hostnames.add(first_svc_ip)
  502. internal_hostnames.add(first_svc_ip)
  503. facts['common']['all_hostnames'] = list(all_hostnames)
  504. facts['common']['internal_hostnames'] = list(internal_hostnames)
  505. return facts
  506. def set_etcd_facts_if_unset(facts):
  507. """
  508. If using embedded etcd, loads the data directory from master-config.yaml.
  509. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  510. If anything goes wrong parsing these, the fact will not be set.
  511. """
  512. if 'master' in facts and facts['master']['embedded_etcd']:
  513. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  514. if 'etcd_data_dir' not in etcd_facts:
  515. try:
  516. # Parse master config to find actual etcd data dir:
  517. master_cfg_path = os.path.join(facts['common']['config_base'],
  518. 'master/master-config.yaml')
  519. master_cfg_f = open(master_cfg_path, 'r')
  520. config = yaml.safe_load(master_cfg_f.read())
  521. master_cfg_f.close()
  522. etcd_facts['etcd_data_dir'] = \
  523. config['etcdConfig']['storageDirectory']
  524. facts['etcd'] = etcd_facts
  525. # We don't want exceptions bubbling up here:
  526. # pylint: disable=broad-except
  527. except Exception:
  528. pass
  529. else:
  530. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  531. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  532. try:
  533. # Add a fake section for parsing:
  534. ini_str = '[root]\n' + open('/etc/etcd/etcd.conf', 'r').read()
  535. ini_fp = StringIO.StringIO(ini_str)
  536. config = ConfigParser.RawConfigParser()
  537. config.readfp(ini_fp)
  538. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  539. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  540. etcd_data_dir = etcd_data_dir[1:-1]
  541. etcd_facts['etcd_data_dir'] = etcd_data_dir
  542. facts['etcd'] = etcd_facts
  543. # We don't want exceptions bubbling up here:
  544. # pylint: disable=broad-except
  545. except Exception:
  546. pass
  547. return facts
  548. def set_deployment_facts_if_unset(facts):
  549. """ Set Facts that vary based on deployment_type. This currently
  550. includes common.service_type, common.config_base, master.registry_url,
  551. node.registry_url, node.storage_plugin_deps
  552. Args:
  553. facts (dict): existing facts
  554. Returns:
  555. dict: the facts dict updated with the generated deployment_type
  556. facts
  557. """
  558. # disabled to avoid breaking up facts related to deployment type into
  559. # multiple methods for now.
  560. # pylint: disable=too-many-statements, too-many-branches
  561. if 'common' in facts:
  562. deployment_type = facts['common']['deployment_type']
  563. if 'service_type' not in facts['common']:
  564. service_type = 'atomic-openshift'
  565. if deployment_type == 'origin':
  566. service_type = 'origin'
  567. elif deployment_type in ['enterprise']:
  568. service_type = 'openshift'
  569. facts['common']['service_type'] = service_type
  570. if 'config_base' not in facts['common']:
  571. config_base = '/etc/origin'
  572. if deployment_type in ['enterprise']:
  573. config_base = '/etc/openshift'
  574. # Handle upgrade scenarios when symlinks don't yet exist:
  575. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  576. config_base = '/etc/openshift'
  577. facts['common']['config_base'] = config_base
  578. if 'data_dir' not in facts['common']:
  579. data_dir = '/var/lib/origin'
  580. if deployment_type in ['enterprise']:
  581. data_dir = '/var/lib/openshift'
  582. # Handle upgrade scenarios when symlinks don't yet exist:
  583. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  584. data_dir = '/var/lib/openshift'
  585. facts['common']['data_dir'] = data_dir
  586. if 'docker' in facts:
  587. deployment_type = facts['common']['deployment_type']
  588. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  589. addtl_regs = facts['docker'].get('additional_registries', [])
  590. ent_reg = 'registry.access.redhat.com'
  591. if ent_reg not in addtl_regs:
  592. facts['docker']['additional_registries'] = addtl_regs + [ent_reg]
  593. for role in ('master', 'node'):
  594. if role in facts:
  595. deployment_type = facts['common']['deployment_type']
  596. if 'registry_url' not in facts[role]:
  597. registry_url = 'openshift/origin-${component}:${version}'
  598. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  599. registry_url = 'openshift3/ose-${component}:${version}'
  600. elif deployment_type == 'atomic-enterprise':
  601. registry_url = 'aep3_beta/aep-${component}:${version}'
  602. facts[role]['registry_url'] = registry_url
  603. if 'master' in facts:
  604. deployment_type = facts['common']['deployment_type']
  605. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  606. if 'disabled_features' in facts['master']:
  607. if deployment_type == 'atomic-enterprise':
  608. curr_disabled_features = set(facts['master']['disabled_features'])
  609. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  610. else:
  611. if deployment_type == 'atomic-enterprise':
  612. facts['master']['disabled_features'] = openshift_features
  613. if 'node' in facts:
  614. deployment_type = facts['common']['deployment_type']
  615. if 'storage_plugin_deps' not in facts['node']:
  616. if deployment_type in ['openshift-enterprise', 'atomic-enterprise', 'origin']:
  617. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs', 'iscsi']
  618. else:
  619. facts['node']['storage_plugin_deps'] = []
  620. return facts
  621. def set_version_facts_if_unset(facts):
  622. """ Set version facts. This currently includes common.version and
  623. common.version_gte_3_1_or_1_1.
  624. Args:
  625. facts (dict): existing facts
  626. Returns:
  627. dict: the facts dict updated with version facts.
  628. """
  629. if 'common' in facts:
  630. deployment_type = facts['common']['deployment_type']
  631. version = get_openshift_version(facts)
  632. if version is not None:
  633. facts['common']['version'] = version
  634. if deployment_type == 'origin':
  635. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('1.1.0')
  636. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('1.1.1')
  637. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('1.2.0')
  638. else:
  639. version_gte_3_1_or_1_1 = LooseVersion(version) >= LooseVersion('3.0.2.905')
  640. version_gte_3_1_1_or_1_1_1 = LooseVersion(version) >= LooseVersion('3.1.1')
  641. version_gte_3_2_or_1_2 = LooseVersion(version) >= LooseVersion('3.1.1.901')
  642. else:
  643. version_gte_3_1_or_1_1 = True
  644. version_gte_3_1_1_or_1_1_1 = True
  645. version_gte_3_2_or_1_2 = True
  646. facts['common']['version_gte_3_1_or_1_1'] = version_gte_3_1_or_1_1
  647. facts['common']['version_gte_3_1_1_or_1_1_1'] = version_gte_3_1_1_or_1_1_1
  648. facts['common']['version_gte_3_2_or_1_2'] = version_gte_3_2_or_1_2
  649. if version_gte_3_2_or_1_2:
  650. examples_content_version = 'v1.2'
  651. elif version_gte_3_1_or_1_1:
  652. examples_content_version = 'v1.1'
  653. else:
  654. examples_content_version = 'v1.0'
  655. facts['common']['examples_content_version'] = examples_content_version
  656. return facts
  657. def set_manageiq_facts_if_unset(facts):
  658. """ Set manageiq facts. This currently includes common.use_manageiq.
  659. Args:
  660. facts (dict): existing facts
  661. Returns:
  662. dict: the facts dict updated with version facts.
  663. Raises:
  664. OpenShiftFactsInternalError:
  665. """
  666. if 'common' not in facts:
  667. if 'version_gte_3_1_or_1_1' not in facts['common']:
  668. raise OpenShiftFactsInternalError(
  669. "Invalid invocation: The required facts are not set"
  670. )
  671. if 'use_manageiq' not in facts['common']:
  672. facts['common']['use_manageiq'] = facts['common']['version_gte_3_1_or_1_1']
  673. return facts
  674. def set_sdn_facts_if_unset(facts, system_facts):
  675. """ Set sdn facts if not already present in facts dict
  676. Args:
  677. facts (dict): existing facts
  678. system_facts (dict): ansible_facts
  679. Returns:
  680. dict: the facts dict updated with the generated sdn facts if they
  681. were not already present
  682. """
  683. if 'common' in facts:
  684. use_sdn = facts['common']['use_openshift_sdn']
  685. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  686. use_sdn = safe_get_bool(use_sdn)
  687. facts['common']['use_openshift_sdn'] = use_sdn
  688. if 'sdn_network_plugin_name' not in facts['common']:
  689. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  690. facts['common']['sdn_network_plugin_name'] = plugin
  691. if 'master' in facts:
  692. if 'sdn_cluster_network_cidr' not in facts['master']:
  693. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  694. if 'sdn_host_subnet_length' not in facts['master']:
  695. facts['master']['sdn_host_subnet_length'] = '8'
  696. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  697. node_ip = facts['common']['ip']
  698. # default MTU if interface MTU cannot be detected
  699. facts['node']['sdn_mtu'] = '1450'
  700. for val in system_facts.itervalues():
  701. if isinstance(val, dict) and 'mtu' in val:
  702. mtu = val['mtu']
  703. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  704. facts['node']['sdn_mtu'] = str(mtu - 50)
  705. return facts
  706. def format_url(use_ssl, hostname, port, path=''):
  707. """ Format url based on ssl flag, hostname, port and path
  708. Args:
  709. use_ssl (bool): is ssl enabled
  710. hostname (str): hostname
  711. port (str): port
  712. path (str): url path
  713. Returns:
  714. str: The generated url string
  715. """
  716. scheme = 'https' if use_ssl else 'http'
  717. netloc = hostname
  718. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  719. netloc += ":%s" % port
  720. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  721. def get_current_config(facts):
  722. """ Get current openshift config
  723. Args:
  724. facts (dict): existing facts
  725. Returns:
  726. dict: the facts dict updated with the current openshift config
  727. """
  728. current_config = dict()
  729. roles = [role for role in facts if role not in ['common', 'provider']]
  730. for role in roles:
  731. if 'roles' in current_config:
  732. current_config['roles'].append(role)
  733. else:
  734. current_config['roles'] = [role]
  735. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  736. # determine the location of files.
  737. # TODO: I suspect this isn't working right now, but it doesn't prevent
  738. # anything from working properly as far as I can tell, perhaps because
  739. # we override the kubeconfig path everywhere we use it?
  740. # Query kubeconfig settings
  741. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  742. if role == 'node':
  743. kubeconfig_dir = os.path.join(
  744. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  745. )
  746. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  747. if (os.path.isfile('/usr/bin/openshift')
  748. and os.path.isfile(kubeconfig_path)):
  749. try:
  750. _, output, _ = module.run_command(
  751. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  752. "json", "--kubeconfig=%s" % kubeconfig_path],
  753. check_rc=False
  754. )
  755. config = json.loads(output)
  756. cad = 'certificate-authority-data'
  757. try:
  758. for cluster in config['clusters']:
  759. config['clusters'][cluster][cad] = 'masked'
  760. except KeyError:
  761. pass
  762. try:
  763. for user in config['users']:
  764. config['users'][user][cad] = 'masked'
  765. config['users'][user]['client-key-data'] = 'masked'
  766. except KeyError:
  767. pass
  768. current_config['kubeconfig'] = config
  769. # override pylint broad-except warning, since we do not want
  770. # to bubble up any exceptions if oc config view
  771. # fails
  772. # pylint: disable=broad-except
  773. except Exception:
  774. pass
  775. return current_config
  776. def build_kubelet_args(facts):
  777. """ Build node kubelet_args """
  778. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  779. 'cloudprovider')
  780. if 'node' in facts:
  781. kubelet_args = {}
  782. if 'cloudprovider' in facts:
  783. if facts['cloudprovider']['kind'] == 'aws':
  784. kubelet_args['cloud-provider'] = ['aws']
  785. kubelet_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  786. if facts['cloudprovider']['kind'] == 'openstack':
  787. kubelet_args['cloud-provider'] = ['openstack']
  788. kubelet_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  789. if kubelet_args != {}:
  790. facts = merge_facts({'node': {'kubelet_args': kubelet_args}}, facts, [], [])
  791. return facts
  792. def build_controller_args(facts):
  793. """ Build master controller_args """
  794. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  795. 'cloudprovider')
  796. if 'master' in facts:
  797. controller_args = {}
  798. if 'cloudprovider' in facts:
  799. if facts['cloudprovider']['kind'] == 'aws':
  800. controller_args['cloud-provider'] = ['aws']
  801. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  802. if facts['cloudprovider']['kind'] == 'openstack':
  803. controller_args['cloud-provider'] = ['openstack']
  804. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  805. if controller_args != {}:
  806. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [], [])
  807. return facts
  808. def build_api_server_args(facts):
  809. """ Build master api_server_args """
  810. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  811. 'cloudprovider')
  812. if 'master' in facts:
  813. api_server_args = {}
  814. if 'cloudprovider' in facts:
  815. if facts['cloudprovider']['kind'] == 'aws':
  816. api_server_args['cloud-provider'] = ['aws']
  817. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  818. if facts['cloudprovider']['kind'] == 'openstack':
  819. api_server_args['cloud-provider'] = ['openstack']
  820. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  821. if api_server_args != {}:
  822. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [], [])
  823. return facts
  824. def is_service_running(service):
  825. """ Queries systemd through dbus to see if the service is running """
  826. service_running = False
  827. bus = SystemBus()
  828. systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
  829. manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
  830. try:
  831. service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
  832. service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
  833. service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
  834. service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
  835. service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
  836. if service_load_state == 'loaded' and service_active_state == 'active':
  837. service_running = True
  838. except DBusException:
  839. pass
  840. return service_running
  841. def get_version_output(binary, version_cmd):
  842. """ runs and returns the version output for a command """
  843. cmd = []
  844. for item in (binary, version_cmd):
  845. if isinstance(item, list):
  846. cmd.extend(item)
  847. else:
  848. cmd.append(item)
  849. if os.path.isfile(cmd[0]):
  850. _, output, _ = module.run_command(cmd)
  851. return output
  852. def get_docker_version_info():
  853. """ Parses and returns the docker version info """
  854. result = None
  855. if is_service_running('docker'):
  856. version_info = yaml.safe_load(get_version_output('/usr/bin/docker', 'version'))
  857. if 'Server' in version_info:
  858. result = {
  859. 'api_version': version_info['Server']['API version'],
  860. 'version': version_info['Server']['Version']
  861. }
  862. return result
  863. def get_openshift_version(facts, cli_image=None):
  864. """ Get current version of openshift on the host
  865. Args:
  866. facts (dict): existing facts
  867. optional cli_image for pulling the version number
  868. Returns:
  869. version: the current openshift version
  870. """
  871. version = None
  872. # No need to run this method repeatedly on a system if we already know the
  873. # version
  874. if 'common' in facts:
  875. if 'version' in facts['common'] and facts['common']['version'] is not None:
  876. return facts['common']['version']
  877. if os.path.isfile('/usr/bin/openshift'):
  878. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  879. version = parse_openshift_version(output)
  880. if 'is_containerized' in facts['common'] and safe_get_bool(facts['common']['is_containerized']):
  881. container = None
  882. if 'master' in facts:
  883. if 'cluster_method' in facts['master']:
  884. container = facts['common']['service_type'] + '-master-api'
  885. else:
  886. container = facts['common']['service_type'] + '-master'
  887. elif 'node' in facts:
  888. container = facts['common']['service_type'] + '-node'
  889. if container is not None:
  890. exit_code, output, _ = module.run_command(['docker', 'exec', container, 'openshift', 'version'])
  891. # if for some reason the container is installed but not running
  892. # we'll fall back to using docker run later in this method.
  893. if exit_code == 0:
  894. version = parse_openshift_version(output)
  895. if version is None and cli_image is not None:
  896. # Assume we haven't installed the environment yet and we need
  897. # to query the latest image, but only if docker is installed
  898. if 'docker' in facts and 'version' in facts['docker']:
  899. exit_code, output, _ = module.run_command(['docker', 'run', '--rm', cli_image, 'version'])
  900. version = parse_openshift_version(output)
  901. return version
  902. def parse_openshift_version(output):
  903. """ Apply provider facts to supplied facts dict
  904. Args:
  905. string: output of 'openshift version'
  906. Returns:
  907. string: the version number
  908. """
  909. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  910. return versions.get('openshift', '')
  911. def apply_provider_facts(facts, provider_facts):
  912. """ Apply provider facts to supplied facts dict
  913. Args:
  914. facts (dict): facts dict to update
  915. provider_facts (dict): provider facts to apply
  916. roles: host roles
  917. Returns:
  918. dict: the merged facts
  919. """
  920. if not provider_facts:
  921. return facts
  922. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  923. for h_var, ip_var in common_vars:
  924. ip_value = provider_facts['network'].get(ip_var)
  925. if ip_value:
  926. facts['common'][ip_var] = ip_value
  927. facts['common'][h_var] = choose_hostname(
  928. [provider_facts['network'].get(h_var)],
  929. facts['common'][ip_var]
  930. )
  931. facts['provider'] = provider_facts
  932. return facts
  933. # Disabling pylint too many branches. This function needs refactored
  934. # but is a very core part of openshift_facts.
  935. # pylint: disable=too-many-branches
  936. def merge_facts(orig, new, additive_facts_to_overwrite, protected_facts_to_overwrite):
  937. """ Recursively merge facts dicts
  938. Args:
  939. orig (dict): existing facts
  940. new (dict): facts to update
  941. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  942. '.' notation ex: ['master.named_certificates']
  943. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  944. '.' notation ex: ['master.master_count']
  945. Returns:
  946. dict: the merged facts
  947. """
  948. additive_facts = ['named_certificates']
  949. protected_facts = ['ha', 'master_count']
  950. facts = dict()
  951. for key, value in orig.iteritems():
  952. # Key exists in both old and new facts.
  953. if key in new:
  954. # Continue to recurse if old and new fact is a dictionary.
  955. if isinstance(value, dict) and isinstance(new[key], dict):
  956. # Collect the subset of additive facts to overwrite if
  957. # key matches. These will be passed to the subsequent
  958. # merge_facts call.
  959. relevant_additive_facts = []
  960. for item in additive_facts_to_overwrite:
  961. if '.' in item and item.startswith(key + '.'):
  962. relevant_additive_facts.append(item)
  963. # Collect the subset of protected facts to overwrite
  964. # if key matches. These will be passed to the
  965. # subsequent merge_facts call.
  966. relevant_protected_facts = []
  967. for item in protected_facts_to_overwrite:
  968. if '.' in item and item.startswith(key + '.'):
  969. relevant_protected_facts.append(item)
  970. facts[key] = merge_facts(value, new[key], relevant_additive_facts, relevant_protected_facts)
  971. # Key matches an additive fact and we are not overwriting
  972. # it so we will append the new value to the existing value.
  973. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  974. if isinstance(value, list) and isinstance(new[key], list):
  975. new_fact = []
  976. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  977. if item not in new_fact:
  978. new_fact.append(item)
  979. facts[key] = new_fact
  980. # Key matches a protected fact and we are not overwriting
  981. # it so we will determine if it is okay to change this
  982. # fact.
  983. elif key in protected_facts and key not in [x.split('.')[-1] for x in protected_facts_to_overwrite]:
  984. # The master count (int) can only increase unless it
  985. # has been passed as a protected fact to overwrite.
  986. if key == 'master_count':
  987. if int(value) <= int(new[key]):
  988. facts[key] = copy.deepcopy(new[key])
  989. else:
  990. module.fail_json(msg='openshift_facts received a lower value for openshift.master.master_count')
  991. # ha (bool) can not change unless it has been passed
  992. # as a protected fact to overwrite.
  993. if key == 'ha':
  994. if safe_get_bool(value) != safe_get_bool(new[key]):
  995. module.fail_json(msg='openshift_facts received a different value for openshift.master.ha')
  996. else:
  997. facts[key] = value
  998. # No other condition has been met. Overwrite the old fact
  999. # with the new value.
  1000. else:
  1001. facts[key] = copy.deepcopy(new[key])
  1002. # Key isn't in new so add it to facts to keep it.
  1003. else:
  1004. facts[key] = copy.deepcopy(value)
  1005. new_keys = set(new.keys()) - set(orig.keys())
  1006. for key in new_keys:
  1007. facts[key] = copy.deepcopy(new[key])
  1008. return facts
  1009. def save_local_facts(filename, facts):
  1010. """ Save local facts
  1011. Args:
  1012. filename (str): local facts file
  1013. facts (dict): facts to set
  1014. """
  1015. try:
  1016. fact_dir = os.path.dirname(filename)
  1017. if not os.path.exists(fact_dir):
  1018. os.makedirs(fact_dir)
  1019. with open(filename, 'w') as fact_file:
  1020. fact_file.write(module.jsonify(facts))
  1021. os.chmod(filename, 0o600)
  1022. except (IOError, OSError) as ex:
  1023. raise OpenShiftFactsFileWriteError(
  1024. "Could not create fact file: %s, error: %s" % (filename, ex)
  1025. )
  1026. def get_local_facts_from_file(filename):
  1027. """ Retrieve local facts from fact file
  1028. Args:
  1029. filename (str): local facts file
  1030. Returns:
  1031. dict: the retrieved facts
  1032. """
  1033. local_facts = dict()
  1034. try:
  1035. # Handle conversion of INI style facts file to json style
  1036. ini_facts = ConfigParser.SafeConfigParser()
  1037. ini_facts.read(filename)
  1038. for section in ini_facts.sections():
  1039. local_facts[section] = dict()
  1040. for key, value in ini_facts.items(section):
  1041. local_facts[section][key] = value
  1042. except (ConfigParser.MissingSectionHeaderError,
  1043. ConfigParser.ParsingError):
  1044. try:
  1045. with open(filename, 'r') as facts_file:
  1046. local_facts = json.load(facts_file)
  1047. except (ValueError, IOError):
  1048. pass
  1049. return local_facts
  1050. def safe_get_bool(fact):
  1051. """ Get a boolean fact safely.
  1052. Args:
  1053. facts: fact to convert
  1054. Returns:
  1055. bool: given fact as a bool
  1056. """
  1057. return bool(strtobool(str(fact)))
  1058. # pylint: disable=too-many-statements
  1059. def set_container_facts_if_unset(facts):
  1060. """ Set containerized facts.
  1061. Args:
  1062. facts (dict): existing facts
  1063. Returns:
  1064. dict: the facts dict updated with the generated containerization
  1065. facts
  1066. """
  1067. deployment_type = facts['common']['deployment_type']
  1068. if deployment_type in ['enterprise', 'openshift-enterprise']:
  1069. master_image = 'openshift3/ose'
  1070. cli_image = master_image
  1071. node_image = 'openshift3/node'
  1072. ovs_image = 'openshift3/openvswitch'
  1073. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1074. pod_image = 'openshift3/ose-pod'
  1075. router_image = 'openshift3/ose-haproxy-router'
  1076. registry_image = 'openshift3/ose-docker-registry'
  1077. deployer_image = 'openshift3/ose-deployer'
  1078. elif deployment_type == 'atomic-enterprise':
  1079. master_image = 'aep3_beta/aep'
  1080. cli_image = master_image
  1081. node_image = 'aep3_beta/node'
  1082. ovs_image = 'aep3_beta/openvswitch'
  1083. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1084. pod_image = 'aep3_beta/aep-pod'
  1085. router_image = 'aep3_beta/aep-haproxy-router'
  1086. registry_image = 'aep3_beta/aep-docker-registry'
  1087. deployer_image = 'aep3_beta/aep-deployer'
  1088. else:
  1089. master_image = 'openshift/origin'
  1090. cli_image = master_image
  1091. node_image = 'openshift/node'
  1092. ovs_image = 'openshift/openvswitch'
  1093. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1094. pod_image = 'openshift/origin-pod'
  1095. router_image = 'openshift/origin-haproxy-router'
  1096. registry_image = 'openshift/origin-docker-registry'
  1097. deployer_image = 'openshift/origin-deployer'
  1098. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1099. if 'is_containerized' not in facts['common']:
  1100. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1101. if 'cli_image' not in facts['common']:
  1102. facts['common']['cli_image'] = cli_image
  1103. if 'pod_image' not in facts['common']:
  1104. facts['common']['pod_image'] = pod_image
  1105. if 'router_image' not in facts['common']:
  1106. facts['common']['router_image'] = router_image
  1107. if 'registry_image' not in facts['common']:
  1108. facts['common']['registry_image'] = registry_image
  1109. if 'deployer_image' not in facts['common']:
  1110. facts['common']['deployer_image'] = deployer_image
  1111. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  1112. facts['etcd']['etcd_image'] = etcd_image
  1113. if 'master' in facts and 'master_image' not in facts['master']:
  1114. facts['master']['master_image'] = master_image
  1115. if 'node' in facts:
  1116. if 'node_image' not in facts['node']:
  1117. facts['node']['node_image'] = node_image
  1118. if 'ovs_image' not in facts['node']:
  1119. facts['node']['ovs_image'] = ovs_image
  1120. if safe_get_bool(facts['common']['is_containerized']):
  1121. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1122. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1123. openshift_version = get_openshift_version(facts, cli_image)
  1124. if openshift_version is not None:
  1125. base_version = openshift_version.split('-')[0]
  1126. facts['common']['image_tag'] = "v" + base_version
  1127. return facts
  1128. def set_installed_variant_rpm_facts(facts):
  1129. """ Set RPM facts of installed variant
  1130. Args:
  1131. facts (dict): existing facts
  1132. Returns:
  1133. dict: the facts dict updated with installed_variant_rpms
  1134. """
  1135. installed_rpms = []
  1136. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1137. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1138. variant_rpms = [base_rpm] + \
  1139. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1140. ['tuned-profiles-%s-node' % base_rpm]
  1141. for rpm in variant_rpms:
  1142. exit_code, _, _ = module.run_command(['rpm', '-q', rpm])
  1143. if exit_code == 0:
  1144. installed_rpms.append(rpm)
  1145. facts['common']['installed_variant_rpms'] = installed_rpms
  1146. return facts
  1147. class OpenShiftFactsInternalError(Exception):
  1148. """Origin Facts Error"""
  1149. pass
  1150. class OpenShiftFactsUnsupportedRoleError(Exception):
  1151. """Origin Facts Unsupported Role Error"""
  1152. pass
  1153. class OpenShiftFactsFileWriteError(Exception):
  1154. """Origin Facts File Write Error"""
  1155. pass
  1156. class OpenShiftFactsMetadataUnavailableError(Exception):
  1157. """Origin Facts Metadata Unavailable Error"""
  1158. pass
  1159. class OpenShiftFacts(object):
  1160. """ Origin Facts
  1161. Attributes:
  1162. facts (dict): facts for the host
  1163. Args:
  1164. module (AnsibleModule): an AnsibleModule object
  1165. role (str): role for setting local facts
  1166. filename (str): local facts file to use
  1167. local_facts (dict): local facts to set
  1168. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1169. '.' notation ex: ['master.named_certificates']
  1170. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1171. '.' notation ex: ['master.master_count']
  1172. Raises:
  1173. OpenShiftFactsUnsupportedRoleError:
  1174. """
  1175. known_roles = ['cloudprovider',
  1176. 'common',
  1177. 'docker',
  1178. 'etcd',
  1179. 'hosted',
  1180. 'master',
  1181. 'node']
  1182. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1183. # pylint: disable=too-many-arguments
  1184. def __init__(self, role, filename, local_facts,
  1185. additive_facts_to_overwrite=None,
  1186. openshift_env=None,
  1187. openshift_env_structures=None,
  1188. protected_facts_to_overwrite=None):
  1189. self.changed = False
  1190. self.filename = filename
  1191. if role not in self.known_roles:
  1192. raise OpenShiftFactsUnsupportedRoleError(
  1193. "Role %s is not supported by this module" % role
  1194. )
  1195. self.role = role
  1196. self.system_facts = ansible_facts(module)
  1197. self.facts = self.generate_facts(local_facts,
  1198. additive_facts_to_overwrite,
  1199. openshift_env,
  1200. openshift_env_structures,
  1201. protected_facts_to_overwrite)
  1202. def generate_facts(self,
  1203. local_facts,
  1204. additive_facts_to_overwrite,
  1205. openshift_env,
  1206. openshift_env_structures,
  1207. protected_facts_to_overwrite):
  1208. """ Generate facts
  1209. Args:
  1210. local_facts (dict): local_facts for overriding generated defaults
  1211. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1212. '.' notation ex: ['master.named_certificates']
  1213. openshift_env (dict): openshift_env facts for overriding generated defaults
  1214. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1215. '.' notation ex: ['master.master_count']
  1216. Returns:
  1217. dict: The generated facts
  1218. """
  1219. local_facts = self.init_local_facts(local_facts,
  1220. additive_facts_to_overwrite,
  1221. openshift_env,
  1222. openshift_env_structures,
  1223. protected_facts_to_overwrite)
  1224. roles = local_facts.keys()
  1225. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1226. deployment_type = local_facts['common']['deployment_type']
  1227. else:
  1228. deployment_type = 'origin'
  1229. defaults = self.get_defaults(roles, deployment_type)
  1230. provider_facts = self.init_provider_facts()
  1231. facts = apply_provider_facts(defaults, provider_facts)
  1232. facts = merge_facts(facts,
  1233. local_facts,
  1234. additive_facts_to_overwrite,
  1235. protected_facts_to_overwrite)
  1236. facts['current_config'] = get_current_config(facts)
  1237. facts = set_url_facts_if_unset(facts)
  1238. facts = set_project_cfg_facts_if_unset(facts)
  1239. facts = set_flannel_facts_if_unset(facts)
  1240. facts = set_nuage_facts_if_unset(facts)
  1241. facts = set_node_schedulability(facts)
  1242. facts = set_master_selectors(facts)
  1243. facts = set_metrics_facts_if_unset(facts)
  1244. facts = set_identity_providers_if_unset(facts)
  1245. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1246. facts = set_deployment_facts_if_unset(facts)
  1247. facts = set_container_facts_if_unset(facts)
  1248. facts = build_kubelet_args(facts)
  1249. facts = build_controller_args(facts)
  1250. facts = build_api_server_args(facts)
  1251. facts = set_version_facts_if_unset(facts)
  1252. facts = set_manageiq_facts_if_unset(facts)
  1253. facts = set_aggregate_facts(facts)
  1254. facts = set_etcd_facts_if_unset(facts)
  1255. if not safe_get_bool(facts['common']['is_containerized']):
  1256. facts = set_installed_variant_rpm_facts(facts)
  1257. return dict(openshift=facts)
  1258. def get_defaults(self, roles, deployment_type):
  1259. """ Get default fact values
  1260. Args:
  1261. roles (list): list of roles for this host
  1262. Returns:
  1263. dict: The generated default facts
  1264. """
  1265. defaults = {}
  1266. ip_addr = self.system_facts['default_ipv4']['address']
  1267. exit_code, output, _ = module.run_command(['hostname', '-f'])
  1268. hostname_f = output.strip() if exit_code == 0 else ''
  1269. hostname_values = [hostname_f, self.system_facts['nodename'],
  1270. self.system_facts['fqdn']]
  1271. hostname = choose_hostname(hostname_values, ip_addr)
  1272. defaults['common'] = dict(use_openshift_sdn=True, ip=ip_addr,
  1273. public_ip=ip_addr,
  1274. deployment_type=deployment_type,
  1275. hostname=hostname,
  1276. public_hostname=hostname,
  1277. client_binary='oc', admin_binary='oadm',
  1278. dns_domain='cluster.local',
  1279. install_examples=True,
  1280. debug_level=2)
  1281. if 'master' in roles:
  1282. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1283. controllers_port='8444',
  1284. console_use_ssl=True,
  1285. console_path='/console',
  1286. console_port='8443', etcd_use_ssl=True,
  1287. etcd_hosts='', etcd_port='4001',
  1288. portal_net='172.30.0.0/16',
  1289. embedded_etcd=True, embedded_kube=True,
  1290. embedded_dns=True, dns_port='53',
  1291. bind_addr='0.0.0.0',
  1292. session_max_seconds=3600,
  1293. session_name='ssn',
  1294. session_secrets_file='',
  1295. access_token_max_seconds=86400,
  1296. auth_token_max_seconds=500,
  1297. oauth_grant_method='auto')
  1298. if 'node' in roles:
  1299. defaults['node'] = dict(labels={}, annotations={},
  1300. iptables_sync_period='5s',
  1301. local_quota_per_fsgroup="",
  1302. set_node_ip=False)
  1303. if 'docker' in roles:
  1304. docker = dict(disable_push_dockerhub=False)
  1305. version_info = get_docker_version_info()
  1306. if version_info is not None:
  1307. docker['api_version'] = version_info['api_version']
  1308. docker['version'] = version_info['version']
  1309. defaults['docker'] = docker
  1310. if 'cloudprovider' in roles:
  1311. defaults['cloudprovider'] = dict(kind=None)
  1312. defaults['hosted'] = dict(
  1313. registry=dict(
  1314. storage=dict(
  1315. kind=None,
  1316. volume=dict(
  1317. name='registry',
  1318. size='5Gi'
  1319. ),
  1320. nfs=dict(
  1321. directory='/exports',
  1322. options='*(rw,root_squash)'),
  1323. host=None,
  1324. access_modes=['ReadWriteMany'],
  1325. create_pv=True
  1326. )
  1327. )
  1328. )
  1329. return defaults
  1330. def guess_host_provider(self):
  1331. """ Guess the host provider
  1332. Returns:
  1333. dict: The generated default facts for the detected provider
  1334. """
  1335. # TODO: cloud provider facts should probably be submitted upstream
  1336. product_name = self.system_facts['product_name']
  1337. product_version = self.system_facts['product_version']
  1338. virt_type = self.system_facts['virtualization_type']
  1339. virt_role = self.system_facts['virtualization_role']
  1340. provider = None
  1341. metadata = None
  1342. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1343. # need to create PR for ansible to expose it
  1344. bios_vendor = get_file_content(
  1345. '/sys/devices/virtual/dmi/id/bios_vendor'
  1346. )
  1347. if bios_vendor == 'Google':
  1348. provider = 'gce'
  1349. metadata_url = ('http://metadata.google.internal/'
  1350. 'computeMetadata/v1/?recursive=true')
  1351. headers = {'Metadata-Flavor': 'Google'}
  1352. metadata = get_provider_metadata(metadata_url, True, headers,
  1353. True)
  1354. # Filter sshKeys and serviceAccounts from gce metadata
  1355. if metadata:
  1356. metadata['project']['attributes'].pop('sshKeys', None)
  1357. metadata['instance'].pop('serviceAccounts', None)
  1358. elif (virt_type == 'xen' and virt_role == 'guest'
  1359. and re.match(r'.*\.amazon$', product_version)):
  1360. provider = 'aws'
  1361. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1362. metadata = get_provider_metadata(metadata_url)
  1363. elif re.search(r'OpenStack', product_name):
  1364. provider = 'openstack'
  1365. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1366. 'meta_data.json')
  1367. metadata = get_provider_metadata(metadata_url, True, None,
  1368. True)
  1369. if metadata:
  1370. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1371. metadata['ec2_compat'] = get_provider_metadata(
  1372. ec2_compat_url
  1373. )
  1374. # disable pylint maybe-no-member because overloaded use of
  1375. # the module name causes pylint to not detect that results
  1376. # is an array or hash
  1377. # pylint: disable=maybe-no-member
  1378. # Filter public_keys and random_seed from openstack metadata
  1379. metadata.pop('public_keys', None)
  1380. metadata.pop('random_seed', None)
  1381. if not metadata['ec2_compat']:
  1382. metadata = None
  1383. return dict(name=provider, metadata=metadata)
  1384. def init_provider_facts(self):
  1385. """ Initialize the provider facts
  1386. Returns:
  1387. dict: The normalized provider facts
  1388. """
  1389. provider_info = self.guess_host_provider()
  1390. provider_facts = normalize_provider_facts(
  1391. provider_info.get('name'),
  1392. provider_info.get('metadata')
  1393. )
  1394. return provider_facts
  1395. @staticmethod
  1396. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1397. """ Split openshift_env facts based on openshift_env structures.
  1398. Args:
  1399. openshift_env_fact (string): the openshift_env fact to split
  1400. ex: 'openshift_cloudprovider_openstack_auth_url'
  1401. openshift_env_structures (list): a list of structures to determine fact keys
  1402. ex: ['openshift.cloudprovider.openstack.*']
  1403. Returns:
  1404. list: a list of keys that represent the fact
  1405. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1406. """
  1407. # By default, we'll split an openshift_env fact by underscores.
  1408. fact_keys = openshift_env_fact.split('_')
  1409. # Determine if any of the provided variable structures match the fact.
  1410. matching_structure = None
  1411. if openshift_env_structures != None:
  1412. for structure in openshift_env_structures:
  1413. if re.match(structure, openshift_env_fact):
  1414. matching_structure = structure
  1415. # Fact didn't match any variable structures so return the default fact keys.
  1416. if matching_structure is None:
  1417. return fact_keys
  1418. final_keys = []
  1419. structure_keys = matching_structure.split('.')
  1420. for structure_key in structure_keys:
  1421. # Matched current key. Add to final keys.
  1422. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1423. final_keys.append(structure_key)
  1424. # Wildcard means we will be taking everything from here to the end of the fact.
  1425. elif structure_key == '*':
  1426. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1427. # Shouldn't have gotten here, return the fact keys.
  1428. else:
  1429. return fact_keys
  1430. return final_keys
  1431. # Disabling too-many-branches and too-many-locals.
  1432. # This should be cleaned up as a TODO item.
  1433. #pylint: disable=too-many-branches, too-many-locals
  1434. def init_local_facts(self, facts=None,
  1435. additive_facts_to_overwrite=None,
  1436. openshift_env=None,
  1437. openshift_env_structures=None,
  1438. protected_facts_to_overwrite=None):
  1439. """ Initialize the local facts
  1440. Args:
  1441. facts (dict): local facts to set
  1442. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1443. '.' notation ex: ['master.named_certificates']
  1444. openshift_env (dict): openshift env facts to set
  1445. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1446. '.' notation ex: ['master.master_count']
  1447. Returns:
  1448. dict: The result of merging the provided facts with existing
  1449. local facts
  1450. """
  1451. changed = False
  1452. facts_to_set = dict()
  1453. if facts is not None:
  1454. facts_to_set[self.role] = facts
  1455. if openshift_env != {} and openshift_env != None:
  1456. for fact, value in openshift_env.iteritems():
  1457. oo_env_facts = dict()
  1458. current_level = oo_env_facts
  1459. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1460. if len(keys) > 0 and keys[0] != self.role:
  1461. continue
  1462. for key in keys:
  1463. if key == keys[-1]:
  1464. current_level[key] = value
  1465. elif key not in current_level:
  1466. current_level[key] = dict()
  1467. current_level = current_level[key]
  1468. facts_to_set = merge_facts(orig=facts_to_set,
  1469. new=oo_env_facts,
  1470. additive_facts_to_overwrite=[],
  1471. protected_facts_to_overwrite=[])
  1472. local_facts = get_local_facts_from_file(self.filename)
  1473. migrated_facts = migrate_local_facts(local_facts)
  1474. new_local_facts = merge_facts(migrated_facts,
  1475. facts_to_set,
  1476. additive_facts_to_overwrite,
  1477. protected_facts_to_overwrite)
  1478. if 'docker' in new_local_facts:
  1479. # remove duplicate and empty strings from registry lists
  1480. for cat in ['additional', 'blocked', 'insecure']:
  1481. key = '{0}_registries'.format(cat)
  1482. if key in new_local_facts['docker']:
  1483. val = new_local_facts['docker'][key]
  1484. if isinstance(val, basestring):
  1485. val = [x.strip() for x in val.split(',')]
  1486. new_local_facts['docker'][key] = list(set(val) - set(['']))
  1487. for facts in new_local_facts.values():
  1488. keys_to_delete = []
  1489. if isinstance(facts, dict):
  1490. for fact, value in facts.iteritems():
  1491. if value == "" or value is None:
  1492. keys_to_delete.append(fact)
  1493. for key in keys_to_delete:
  1494. del facts[key]
  1495. if new_local_facts != local_facts:
  1496. self.validate_local_facts(new_local_facts)
  1497. changed = True
  1498. if not module.check_mode:
  1499. save_local_facts(self.filename, new_local_facts)
  1500. self.changed = changed
  1501. return new_local_facts
  1502. def validate_local_facts(self, facts=None):
  1503. """ Validate local facts
  1504. Args:
  1505. facts (dict): local facts to validate
  1506. """
  1507. invalid_facts = dict()
  1508. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1509. if invalid_facts:
  1510. msg = 'Invalid facts detected:\n'
  1511. for key in invalid_facts.keys():
  1512. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1513. module.fail_json(msg=msg,
  1514. changed=self.changed)
  1515. # disabling pylint errors for line-too-long since we're dealing
  1516. # with best effort reduction of error messages here.
  1517. # disabling errors for too-many-branches since we require checking
  1518. # many conditions.
  1519. # pylint: disable=line-too-long, too-many-branches
  1520. @staticmethod
  1521. def validate_master_facts(facts, invalid_facts):
  1522. """ Validate master facts
  1523. Args:
  1524. facts (dict): local facts to validate
  1525. invalid_facts (dict): collected invalid_facts
  1526. Returns:
  1527. dict: Invalid facts
  1528. """
  1529. if 'master' in facts:
  1530. # openshift.master.session_auth_secrets
  1531. if 'session_auth_secrets' in facts['master']:
  1532. session_auth_secrets = facts['master']['session_auth_secrets']
  1533. if not issubclass(type(session_auth_secrets), list):
  1534. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1535. elif 'session_encryption_secrets' not in facts['master']:
  1536. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1537. 'if openshift_master_session_auth_secrets is provided.')
  1538. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1539. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1540. 'openshift_master_session_encryption_secrets must be '
  1541. 'equal length.')
  1542. else:
  1543. for secret in session_auth_secrets:
  1544. if len(secret) < 32:
  1545. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1546. 'Secrets must be at least 32 characters in length.')
  1547. # openshift.master.session_encryption_secrets
  1548. if 'session_encryption_secrets' in facts['master']:
  1549. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1550. if not issubclass(type(session_encryption_secrets), list):
  1551. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1552. elif 'session_auth_secrets' not in facts['master']:
  1553. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1554. 'set if openshift_master_session_encryption_secrets '
  1555. 'is provided.')
  1556. else:
  1557. for secret in session_encryption_secrets:
  1558. if len(secret) not in [16, 24, 32]:
  1559. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1560. 'Secrets must be 16, 24, or 32 characters in length.')
  1561. return invalid_facts
  1562. def main():
  1563. """ main """
  1564. # disabling pylint errors for global-variable-undefined and invalid-name
  1565. # for 'global module' usage, since it is required to use ansible_facts
  1566. # pylint: disable=global-variable-undefined, invalid-name
  1567. global module
  1568. module = AnsibleModule(
  1569. argument_spec=dict(
  1570. role=dict(default='common', required=False,
  1571. choices=OpenShiftFacts.known_roles),
  1572. local_facts=dict(default=None, type='dict', required=False),
  1573. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1574. openshift_env=dict(default={}, type='dict', required=False),
  1575. openshift_env_structures=dict(default=[], type='list', required=False),
  1576. protected_facts_to_overwrite=dict(default=[], type='list', required=False),
  1577. ),
  1578. supports_check_mode=True,
  1579. add_file_common_args=True,
  1580. )
  1581. role = module.params['role']
  1582. local_facts = module.params['local_facts']
  1583. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1584. openshift_env = module.params['openshift_env']
  1585. openshift_env_structures = module.params['openshift_env_structures']
  1586. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite']
  1587. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1588. openshift_facts = OpenShiftFacts(role,
  1589. fact_file,
  1590. local_facts,
  1591. additive_facts_to_overwrite,
  1592. openshift_env,
  1593. openshift_env_structures,
  1594. protected_facts_to_overwrite)
  1595. file_params = module.params.copy()
  1596. file_params['path'] = fact_file
  1597. file_args = module.load_file_common_arguments(file_params)
  1598. changed = module.set_fs_attributes_if_different(file_args,
  1599. openshift_facts.changed)
  1600. return module.exit_json(changed=changed,
  1601. ansible_facts=openshift_facts.facts)
  1602. # ignore pylint errors related to the module_utils import
  1603. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1604. # import module snippets
  1605. from ansible.module_utils.basic import *
  1606. from ansible.module_utils.facts import *
  1607. from ansible.module_utils.urls import *
  1608. if __name__ == '__main__':
  1609. main()