openshift_facts.py 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  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 migrate_oauth_template_facts(facts):
  707. """
  708. Migrate an old oauth template fact to a newer format if it's present.
  709. The legacy 'oauth_template' fact was just a filename, and assumed you were
  710. setting the 'login' template.
  711. The new pluralized 'oauth_templates' fact is a dict mapping the template
  712. name to a filename.
  713. Simplify the code after this by merging the old fact into the new.
  714. """
  715. if 'master' in facts and 'oauth_template' in facts['master']:
  716. if 'oauth_templates' not in facts['master']:
  717. facts['master']['oauth_templates'] = {"login": facts['master']['oauth_template']}
  718. elif 'login' not in facts['master']['oauth_templates']:
  719. facts['master']['oauth_templates']['login'] = facts['master']['oauth_template']
  720. return facts
  721. def format_url(use_ssl, hostname, port, path=''):
  722. """ Format url based on ssl flag, hostname, port and path
  723. Args:
  724. use_ssl (bool): is ssl enabled
  725. hostname (str): hostname
  726. port (str): port
  727. path (str): url path
  728. Returns:
  729. str: The generated url string
  730. """
  731. scheme = 'https' if use_ssl else 'http'
  732. netloc = hostname
  733. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  734. netloc += ":%s" % port
  735. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  736. def get_current_config(facts):
  737. """ Get current openshift config
  738. Args:
  739. facts (dict): existing facts
  740. Returns:
  741. dict: the facts dict updated with the current openshift config
  742. """
  743. current_config = dict()
  744. roles = [role for role in facts if role not in ['common', 'provider']]
  745. for role in roles:
  746. if 'roles' in current_config:
  747. current_config['roles'].append(role)
  748. else:
  749. current_config['roles'] = [role]
  750. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  751. # determine the location of files.
  752. # TODO: I suspect this isn't working right now, but it doesn't prevent
  753. # anything from working properly as far as I can tell, perhaps because
  754. # we override the kubeconfig path everywhere we use it?
  755. # Query kubeconfig settings
  756. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  757. if role == 'node':
  758. kubeconfig_dir = os.path.join(
  759. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  760. )
  761. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  762. if (os.path.isfile('/usr/bin/openshift')
  763. and os.path.isfile(kubeconfig_path)):
  764. try:
  765. _, output, _ = module.run_command(
  766. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  767. "json", "--kubeconfig=%s" % kubeconfig_path],
  768. check_rc=False
  769. )
  770. config = json.loads(output)
  771. cad = 'certificate-authority-data'
  772. try:
  773. for cluster in config['clusters']:
  774. config['clusters'][cluster][cad] = 'masked'
  775. except KeyError:
  776. pass
  777. try:
  778. for user in config['users']:
  779. config['users'][user][cad] = 'masked'
  780. config['users'][user]['client-key-data'] = 'masked'
  781. except KeyError:
  782. pass
  783. current_config['kubeconfig'] = config
  784. # override pylint broad-except warning, since we do not want
  785. # to bubble up any exceptions if oc config view
  786. # fails
  787. # pylint: disable=broad-except
  788. except Exception:
  789. pass
  790. return current_config
  791. def build_kubelet_args(facts):
  792. """ Build node kubelet_args """
  793. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  794. 'cloudprovider')
  795. if 'node' in facts:
  796. kubelet_args = {}
  797. if 'cloudprovider' in facts:
  798. if 'kind' in facts['cloudprovider']:
  799. if facts['cloudprovider']['kind'] == 'aws':
  800. kubelet_args['cloud-provider'] = ['aws']
  801. kubelet_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  802. if facts['cloudprovider']['kind'] == 'openstack':
  803. kubelet_args['cloud-provider'] = ['openstack']
  804. kubelet_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  805. if kubelet_args != {}:
  806. facts = merge_facts({'node': {'kubelet_args': kubelet_args}}, facts, [], [])
  807. return facts
  808. def build_controller_args(facts):
  809. """ Build master controller_args """
  810. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  811. 'cloudprovider')
  812. if 'master' in facts:
  813. controller_args = {}
  814. if 'cloudprovider' in facts:
  815. if 'kind' in facts['cloudprovider']:
  816. if facts['cloudprovider']['kind'] == 'aws':
  817. controller_args['cloud-provider'] = ['aws']
  818. controller_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  819. if facts['cloudprovider']['kind'] == 'openstack':
  820. controller_args['cloud-provider'] = ['openstack']
  821. controller_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  822. if controller_args != {}:
  823. facts = merge_facts({'master': {'controller_args': controller_args}}, facts, [], [])
  824. return facts
  825. def build_api_server_args(facts):
  826. """ Build master api_server_args """
  827. cloud_cfg_path = os.path.join(facts['common']['config_base'],
  828. 'cloudprovider')
  829. if 'master' in facts:
  830. api_server_args = {}
  831. if 'cloudprovider' in facts:
  832. if 'kind' in facts['cloudprovider']:
  833. if facts['cloudprovider']['kind'] == 'aws':
  834. api_server_args['cloud-provider'] = ['aws']
  835. api_server_args['cloud-config'] = [cloud_cfg_path + '/aws.conf']
  836. if facts['cloudprovider']['kind'] == 'openstack':
  837. api_server_args['cloud-provider'] = ['openstack']
  838. api_server_args['cloud-config'] = [cloud_cfg_path + '/openstack.conf']
  839. if api_server_args != {}:
  840. facts = merge_facts({'master': {'api_server_args': api_server_args}}, facts, [], [])
  841. return facts
  842. def is_service_running(service):
  843. """ Queries systemd through dbus to see if the service is running """
  844. service_running = False
  845. bus = SystemBus()
  846. systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
  847. manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
  848. try:
  849. service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
  850. service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
  851. service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
  852. service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
  853. service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
  854. if service_load_state == 'loaded' and service_active_state == 'active':
  855. service_running = True
  856. except DBusException:
  857. pass
  858. return service_running
  859. def get_version_output(binary, version_cmd):
  860. """ runs and returns the version output for a command """
  861. cmd = []
  862. for item in (binary, version_cmd):
  863. if isinstance(item, list):
  864. cmd.extend(item)
  865. else:
  866. cmd.append(item)
  867. if os.path.isfile(cmd[0]):
  868. _, output, _ = module.run_command(cmd)
  869. return output
  870. def get_docker_version_info():
  871. """ Parses and returns the docker version info """
  872. result = None
  873. if is_service_running('docker'):
  874. version_info = yaml.safe_load(get_version_output('/usr/bin/docker', 'version'))
  875. if 'Server' in version_info:
  876. result = {
  877. 'api_version': version_info['Server']['API version'],
  878. 'version': version_info['Server']['Version']
  879. }
  880. return result
  881. def get_openshift_version(facts, cli_image=None):
  882. """ Get current version of openshift on the host
  883. Args:
  884. facts (dict): existing facts
  885. optional cli_image for pulling the version number
  886. Returns:
  887. version: the current openshift version
  888. """
  889. version = None
  890. # No need to run this method repeatedly on a system if we already know the
  891. # version
  892. if 'common' in facts:
  893. if 'version' in facts['common'] and facts['common']['version'] is not None:
  894. return facts['common']['version']
  895. if os.path.isfile('/usr/bin/openshift'):
  896. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  897. version = parse_openshift_version(output)
  898. if 'is_containerized' in facts['common'] and safe_get_bool(facts['common']['is_containerized']):
  899. container = None
  900. if 'master' in facts:
  901. if 'cluster_method' in facts['master']:
  902. container = facts['common']['service_type'] + '-master-api'
  903. else:
  904. container = facts['common']['service_type'] + '-master'
  905. elif 'node' in facts:
  906. container = facts['common']['service_type'] + '-node'
  907. if container is not None:
  908. exit_code, output, _ = module.run_command(['docker', 'exec', container, 'openshift', 'version'])
  909. # if for some reason the container is installed but not running
  910. # we'll fall back to using docker run later in this method.
  911. if exit_code == 0:
  912. version = parse_openshift_version(output)
  913. if version is None and cli_image is not None:
  914. # Assume we haven't installed the environment yet and we need
  915. # to query the latest image, but only if docker is installed
  916. if 'docker' in facts and 'version' in facts['docker']:
  917. exit_code, output, _ = module.run_command(['docker', 'run', '--rm', cli_image, 'version'])
  918. version = parse_openshift_version(output)
  919. return version
  920. def parse_openshift_version(output):
  921. """ Apply provider facts to supplied facts dict
  922. Args:
  923. string: output of 'openshift version'
  924. Returns:
  925. string: the version number
  926. """
  927. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  928. return versions.get('openshift', '')
  929. def apply_provider_facts(facts, provider_facts):
  930. """ Apply provider facts to supplied facts dict
  931. Args:
  932. facts (dict): facts dict to update
  933. provider_facts (dict): provider facts to apply
  934. roles: host roles
  935. Returns:
  936. dict: the merged facts
  937. """
  938. if not provider_facts:
  939. return facts
  940. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  941. for h_var, ip_var in common_vars:
  942. ip_value = provider_facts['network'].get(ip_var)
  943. if ip_value:
  944. facts['common'][ip_var] = ip_value
  945. facts['common'][h_var] = choose_hostname(
  946. [provider_facts['network'].get(h_var)],
  947. facts['common'][ip_var]
  948. )
  949. facts['provider'] = provider_facts
  950. return facts
  951. # Disabling pylint too many branches. This function needs refactored
  952. # but is a very core part of openshift_facts.
  953. # pylint: disable=too-many-branches
  954. def merge_facts(orig, new, additive_facts_to_overwrite, protected_facts_to_overwrite):
  955. """ Recursively merge facts dicts
  956. Args:
  957. orig (dict): existing facts
  958. new (dict): facts to update
  959. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  960. '.' notation ex: ['master.named_certificates']
  961. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  962. '.' notation ex: ['master.master_count']
  963. Returns:
  964. dict: the merged facts
  965. """
  966. additive_facts = ['named_certificates']
  967. protected_facts = ['ha', 'master_count']
  968. # Facts we do not ever want to merge. These originate in inventory variables
  969. # and contain JSON dicts. We don't ever want to trigger a merge
  970. # here, just completely overwrite with the new if they are present there.
  971. inventory_json_facts = ['admission_plugin_config',
  972. 'kube_admission_plugin_config',
  973. 'image_policy_config']
  974. facts = dict()
  975. for key, value in orig.iteritems():
  976. # Key exists in both old and new facts.
  977. if key in new:
  978. if key in inventory_json_facts:
  979. # Watchout for JSON facts that sometimes load as strings.
  980. # (can happen if the JSON contains a boolean)
  981. if isinstance(new[key], str):
  982. facts[key] = yaml.safe_load(new[key])
  983. else:
  984. facts[key] = copy.deepcopy(new[key])
  985. # Continue to recurse if old and new fact is a dictionary.
  986. elif isinstance(value, dict) and isinstance(new[key], dict):
  987. # Collect the subset of additive facts to overwrite if
  988. # key matches. These will be passed to the subsequent
  989. # merge_facts call.
  990. relevant_additive_facts = []
  991. for item in additive_facts_to_overwrite:
  992. if '.' in item and item.startswith(key + '.'):
  993. relevant_additive_facts.append(item)
  994. # Collect the subset of protected facts to overwrite
  995. # if key matches. These will be passed to the
  996. # subsequent merge_facts call.
  997. relevant_protected_facts = []
  998. for item in protected_facts_to_overwrite:
  999. if '.' in item and item.startswith(key + '.'):
  1000. relevant_protected_facts.append(item)
  1001. facts[key] = merge_facts(value, new[key], relevant_additive_facts, relevant_protected_facts)
  1002. # Key matches an additive fact and we are not overwriting
  1003. # it so we will append the new value to the existing value.
  1004. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  1005. if isinstance(value, list) and isinstance(new[key], list):
  1006. new_fact = []
  1007. for item in copy.deepcopy(value) + copy.deepcopy(new[key]):
  1008. if item not in new_fact:
  1009. new_fact.append(item)
  1010. facts[key] = new_fact
  1011. # Key matches a protected fact and we are not overwriting
  1012. # it so we will determine if it is okay to change this
  1013. # fact.
  1014. elif key in protected_facts and key not in [x.split('.')[-1] for x in protected_facts_to_overwrite]:
  1015. # The master count (int) can only increase unless it
  1016. # has been passed as a protected fact to overwrite.
  1017. if key == 'master_count':
  1018. if int(value) <= int(new[key]):
  1019. facts[key] = copy.deepcopy(new[key])
  1020. else:
  1021. module.fail_json(msg='openshift_facts received a lower value for openshift.master.master_count')
  1022. # ha (bool) can not change unless it has been passed
  1023. # as a protected fact to overwrite.
  1024. if key == 'ha':
  1025. if safe_get_bool(value) != safe_get_bool(new[key]):
  1026. module.fail_json(msg='openshift_facts received a different value for openshift.master.ha')
  1027. else:
  1028. facts[key] = value
  1029. # No other condition has been met. Overwrite the old fact
  1030. # with the new value.
  1031. else:
  1032. facts[key] = copy.deepcopy(new[key])
  1033. # Key isn't in new so add it to facts to keep it.
  1034. else:
  1035. facts[key] = copy.deepcopy(value)
  1036. new_keys = set(new.keys()) - set(orig.keys())
  1037. for key in new_keys:
  1038. facts[key] = copy.deepcopy(new[key])
  1039. return facts
  1040. def save_local_facts(filename, facts):
  1041. """ Save local facts
  1042. Args:
  1043. filename (str): local facts file
  1044. facts (dict): facts to set
  1045. """
  1046. try:
  1047. fact_dir = os.path.dirname(filename)
  1048. if not os.path.exists(fact_dir):
  1049. os.makedirs(fact_dir)
  1050. with open(filename, 'w') as fact_file:
  1051. fact_file.write(module.jsonify(facts))
  1052. os.chmod(filename, 0o600)
  1053. except (IOError, OSError) as ex:
  1054. raise OpenShiftFactsFileWriteError(
  1055. "Could not create fact file: %s, error: %s" % (filename, ex)
  1056. )
  1057. def get_local_facts_from_file(filename):
  1058. """ Retrieve local facts from fact file
  1059. Args:
  1060. filename (str): local facts file
  1061. Returns:
  1062. dict: the retrieved facts
  1063. """
  1064. local_facts = dict()
  1065. try:
  1066. # Handle conversion of INI style facts file to json style
  1067. ini_facts = ConfigParser.SafeConfigParser()
  1068. ini_facts.read(filename)
  1069. for section in ini_facts.sections():
  1070. local_facts[section] = dict()
  1071. for key, value in ini_facts.items(section):
  1072. local_facts[section][key] = value
  1073. except (ConfigParser.MissingSectionHeaderError,
  1074. ConfigParser.ParsingError):
  1075. try:
  1076. with open(filename, 'r') as facts_file:
  1077. local_facts = json.load(facts_file)
  1078. except (ValueError, IOError):
  1079. pass
  1080. return local_facts
  1081. def safe_get_bool(fact):
  1082. """ Get a boolean fact safely.
  1083. Args:
  1084. facts: fact to convert
  1085. Returns:
  1086. bool: given fact as a bool
  1087. """
  1088. return bool(strtobool(str(fact)))
  1089. # pylint: disable=too-many-statements
  1090. def set_container_facts_if_unset(facts):
  1091. """ Set containerized facts.
  1092. Args:
  1093. facts (dict): existing facts
  1094. Returns:
  1095. dict: the facts dict updated with the generated containerization
  1096. facts
  1097. """
  1098. deployment_type = facts['common']['deployment_type']
  1099. if deployment_type in ['enterprise', 'openshift-enterprise']:
  1100. master_image = 'openshift3/ose'
  1101. cli_image = master_image
  1102. node_image = 'openshift3/node'
  1103. ovs_image = 'openshift3/openvswitch'
  1104. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1105. pod_image = 'openshift3/ose-pod'
  1106. router_image = 'openshift3/ose-haproxy-router'
  1107. registry_image = 'openshift3/ose-docker-registry'
  1108. deployer_image = 'openshift3/ose-deployer'
  1109. elif deployment_type == 'atomic-enterprise':
  1110. master_image = 'aep3_beta/aep'
  1111. cli_image = master_image
  1112. node_image = 'aep3_beta/node'
  1113. ovs_image = 'aep3_beta/openvswitch'
  1114. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1115. pod_image = 'aep3_beta/aep-pod'
  1116. router_image = 'aep3_beta/aep-haproxy-router'
  1117. registry_image = 'aep3_beta/aep-docker-registry'
  1118. deployer_image = 'aep3_beta/aep-deployer'
  1119. else:
  1120. master_image = 'openshift/origin'
  1121. cli_image = master_image
  1122. node_image = 'openshift/node'
  1123. ovs_image = 'openshift/openvswitch'
  1124. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  1125. pod_image = 'openshift/origin-pod'
  1126. router_image = 'openshift/origin-haproxy-router'
  1127. registry_image = 'openshift/origin-docker-registry'
  1128. deployer_image = 'openshift/origin-deployer'
  1129. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  1130. if 'is_containerized' not in facts['common']:
  1131. facts['common']['is_containerized'] = facts['common']['is_atomic']
  1132. if 'cli_image' not in facts['common']:
  1133. facts['common']['cli_image'] = cli_image
  1134. if 'pod_image' not in facts['common']:
  1135. facts['common']['pod_image'] = pod_image
  1136. if 'router_image' not in facts['common']:
  1137. facts['common']['router_image'] = router_image
  1138. if 'registry_image' not in facts['common']:
  1139. facts['common']['registry_image'] = registry_image
  1140. if 'deployer_image' not in facts['common']:
  1141. facts['common']['deployer_image'] = deployer_image
  1142. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  1143. facts['etcd']['etcd_image'] = etcd_image
  1144. if 'master' in facts and 'master_image' not in facts['master']:
  1145. facts['master']['master_image'] = master_image
  1146. if 'node' in facts:
  1147. if 'node_image' not in facts['node']:
  1148. facts['node']['node_image'] = node_image
  1149. if 'ovs_image' not in facts['node']:
  1150. facts['node']['ovs_image'] = ovs_image
  1151. if safe_get_bool(facts['common']['is_containerized']):
  1152. facts['common']['admin_binary'] = '/usr/local/bin/oadm'
  1153. facts['common']['client_binary'] = '/usr/local/bin/oc'
  1154. openshift_version = get_openshift_version(facts, cli_image)
  1155. if openshift_version is not None:
  1156. base_version = openshift_version.split('-')[0]
  1157. facts['common']['image_tag'] = "v" + base_version
  1158. return facts
  1159. def set_installed_variant_rpm_facts(facts):
  1160. """ Set RPM facts of installed variant
  1161. Args:
  1162. facts (dict): existing facts
  1163. Returns:
  1164. dict: the facts dict updated with installed_variant_rpms
  1165. """
  1166. installed_rpms = []
  1167. for base_rpm in ['openshift', 'atomic-openshift', 'origin']:
  1168. optional_rpms = ['master', 'node', 'clients', 'sdn-ovs']
  1169. variant_rpms = [base_rpm] + \
  1170. ['{0}-{1}'.format(base_rpm, r) for r in optional_rpms] + \
  1171. ['tuned-profiles-%s-node' % base_rpm]
  1172. for rpm in variant_rpms:
  1173. exit_code, _, _ = module.run_command(['rpm', '-q', rpm])
  1174. if exit_code == 0:
  1175. installed_rpms.append(rpm)
  1176. facts['common']['installed_variant_rpms'] = installed_rpms
  1177. return facts
  1178. class OpenShiftFactsInternalError(Exception):
  1179. """Origin Facts Error"""
  1180. pass
  1181. class OpenShiftFactsUnsupportedRoleError(Exception):
  1182. """Origin Facts Unsupported Role Error"""
  1183. pass
  1184. class OpenShiftFactsFileWriteError(Exception):
  1185. """Origin Facts File Write Error"""
  1186. pass
  1187. class OpenShiftFactsMetadataUnavailableError(Exception):
  1188. """Origin Facts Metadata Unavailable Error"""
  1189. pass
  1190. class OpenShiftFacts(object):
  1191. """ Origin Facts
  1192. Attributes:
  1193. facts (dict): facts for the host
  1194. Args:
  1195. module (AnsibleModule): an AnsibleModule object
  1196. role (str): role for setting local facts
  1197. filename (str): local facts file to use
  1198. local_facts (dict): local facts to set
  1199. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1200. '.' notation ex: ['master.named_certificates']
  1201. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1202. '.' notation ex: ['master.master_count']
  1203. Raises:
  1204. OpenShiftFactsUnsupportedRoleError:
  1205. """
  1206. known_roles = ['cloudprovider',
  1207. 'common',
  1208. 'docker',
  1209. 'etcd',
  1210. 'hosted',
  1211. 'master',
  1212. 'node']
  1213. # Disabling too-many-arguments, this should be cleaned up as a TODO item.
  1214. # pylint: disable=too-many-arguments
  1215. def __init__(self, role, filename, local_facts,
  1216. additive_facts_to_overwrite=None,
  1217. openshift_env=None,
  1218. openshift_env_structures=None,
  1219. protected_facts_to_overwrite=None):
  1220. self.changed = False
  1221. self.filename = filename
  1222. if role not in self.known_roles:
  1223. raise OpenShiftFactsUnsupportedRoleError(
  1224. "Role %s is not supported by this module" % role
  1225. )
  1226. self.role = role
  1227. self.system_facts = ansible_facts(module)
  1228. self.facts = self.generate_facts(local_facts,
  1229. additive_facts_to_overwrite,
  1230. openshift_env,
  1231. openshift_env_structures,
  1232. protected_facts_to_overwrite)
  1233. def generate_facts(self,
  1234. local_facts,
  1235. additive_facts_to_overwrite,
  1236. openshift_env,
  1237. openshift_env_structures,
  1238. protected_facts_to_overwrite):
  1239. """ Generate facts
  1240. Args:
  1241. local_facts (dict): local_facts for overriding generated defaults
  1242. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1243. '.' notation ex: ['master.named_certificates']
  1244. openshift_env (dict): openshift_env facts for overriding generated defaults
  1245. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1246. '.' notation ex: ['master.master_count']
  1247. Returns:
  1248. dict: The generated facts
  1249. """
  1250. local_facts = self.init_local_facts(local_facts,
  1251. additive_facts_to_overwrite,
  1252. openshift_env,
  1253. openshift_env_structures,
  1254. protected_facts_to_overwrite)
  1255. roles = local_facts.keys()
  1256. if 'common' in local_facts and 'deployment_type' in local_facts['common']:
  1257. deployment_type = local_facts['common']['deployment_type']
  1258. else:
  1259. deployment_type = 'origin'
  1260. defaults = self.get_defaults(roles, deployment_type)
  1261. provider_facts = self.init_provider_facts()
  1262. facts = apply_provider_facts(defaults, provider_facts)
  1263. facts = merge_facts(facts,
  1264. local_facts,
  1265. additive_facts_to_overwrite,
  1266. protected_facts_to_overwrite)
  1267. facts = migrate_oauth_template_facts(facts)
  1268. facts['current_config'] = get_current_config(facts)
  1269. facts = set_url_facts_if_unset(facts)
  1270. facts = set_project_cfg_facts_if_unset(facts)
  1271. facts = set_flannel_facts_if_unset(facts)
  1272. facts = set_nuage_facts_if_unset(facts)
  1273. facts = set_node_schedulability(facts)
  1274. facts = set_master_selectors(facts)
  1275. facts = set_metrics_facts_if_unset(facts)
  1276. facts = set_identity_providers_if_unset(facts)
  1277. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  1278. facts = set_deployment_facts_if_unset(facts)
  1279. facts = set_container_facts_if_unset(facts)
  1280. facts = build_kubelet_args(facts)
  1281. facts = build_controller_args(facts)
  1282. facts = build_api_server_args(facts)
  1283. facts = set_version_facts_if_unset(facts)
  1284. facts = set_manageiq_facts_if_unset(facts)
  1285. facts = set_aggregate_facts(facts)
  1286. facts = set_etcd_facts_if_unset(facts)
  1287. if not safe_get_bool(facts['common']['is_containerized']):
  1288. facts = set_installed_variant_rpm_facts(facts)
  1289. return dict(openshift=facts)
  1290. def get_defaults(self, roles, deployment_type):
  1291. """ Get default fact values
  1292. Args:
  1293. roles (list): list of roles for this host
  1294. Returns:
  1295. dict: The generated default facts
  1296. """
  1297. defaults = {}
  1298. ip_addr = self.system_facts['default_ipv4']['address']
  1299. exit_code, output, _ = module.run_command(['hostname', '-f'])
  1300. hostname_f = output.strip() if exit_code == 0 else ''
  1301. hostname_values = [hostname_f, self.system_facts['nodename'],
  1302. self.system_facts['fqdn']]
  1303. hostname = choose_hostname(hostname_values, ip_addr)
  1304. defaults['common'] = dict(use_openshift_sdn=True, ip=ip_addr,
  1305. public_ip=ip_addr,
  1306. deployment_type=deployment_type,
  1307. hostname=hostname,
  1308. public_hostname=hostname,
  1309. client_binary='oc', admin_binary='oadm',
  1310. dns_domain='cluster.local',
  1311. install_examples=True,
  1312. debug_level=2)
  1313. if 'master' in roles:
  1314. scheduler_predicates = [
  1315. {"name": "MatchNodeSelector"},
  1316. {"name": "PodFitsResources"},
  1317. {"name": "PodFitsPorts"},
  1318. {"name": "NoDiskConflict"},
  1319. {"name": "Region", "argument": {"serviceAffinity" : {"labels" : ["region"]}}}
  1320. ]
  1321. scheduler_priorities = [
  1322. {"name": "LeastRequestedPriority", "weight": 1},
  1323. {"name": "SelectorSpreadPriority", "weight": 1},
  1324. {"name": "Zone", "weight" : 2, "argument": {"serviceAntiAffinity" : {"label": "zone"}}}
  1325. ]
  1326. defaults['master'] = dict(api_use_ssl=True, api_port='8443',
  1327. controllers_port='8444',
  1328. console_use_ssl=True,
  1329. console_path='/console',
  1330. console_port='8443', etcd_use_ssl=True,
  1331. etcd_hosts='', etcd_port='4001',
  1332. portal_net='172.30.0.0/16',
  1333. embedded_etcd=True, embedded_kube=True,
  1334. embedded_dns=True, dns_port='53',
  1335. bind_addr='0.0.0.0',
  1336. session_max_seconds=3600,
  1337. session_name='ssn',
  1338. session_secrets_file='',
  1339. access_token_max_seconds=86400,
  1340. auth_token_max_seconds=500,
  1341. oauth_grant_method='auto',
  1342. scheduler_predicates=scheduler_predicates,
  1343. scheduler_priorities=scheduler_priorities)
  1344. if 'node' in roles:
  1345. defaults['node'] = dict(labels={}, annotations={},
  1346. iptables_sync_period='5s',
  1347. local_quota_per_fsgroup="",
  1348. set_node_ip=False)
  1349. if 'docker' in roles:
  1350. docker = dict(disable_push_dockerhub=False)
  1351. version_info = get_docker_version_info()
  1352. if version_info is not None:
  1353. docker['api_version'] = version_info['api_version']
  1354. docker['version'] = version_info['version']
  1355. defaults['docker'] = docker
  1356. if 'cloudprovider' in roles:
  1357. defaults['cloudprovider'] = dict(kind=None)
  1358. defaults['hosted'] = dict(
  1359. registry=dict(
  1360. storage=dict(
  1361. kind=None,
  1362. volume=dict(
  1363. name='registry',
  1364. size='5Gi'
  1365. ),
  1366. nfs=dict(
  1367. directory='/exports',
  1368. options='*(rw,root_squash)'),
  1369. host=None,
  1370. access_modes=['ReadWriteMany'],
  1371. create_pv=True
  1372. )
  1373. )
  1374. )
  1375. return defaults
  1376. def guess_host_provider(self):
  1377. """ Guess the host provider
  1378. Returns:
  1379. dict: The generated default facts for the detected provider
  1380. """
  1381. # TODO: cloud provider facts should probably be submitted upstream
  1382. product_name = self.system_facts['product_name']
  1383. product_version = self.system_facts['product_version']
  1384. virt_type = self.system_facts['virtualization_type']
  1385. virt_role = self.system_facts['virtualization_role']
  1386. provider = None
  1387. metadata = None
  1388. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1389. # need to create PR for ansible to expose it
  1390. bios_vendor = get_file_content(
  1391. '/sys/devices/virtual/dmi/id/bios_vendor'
  1392. )
  1393. if bios_vendor == 'Google':
  1394. provider = 'gce'
  1395. metadata_url = ('http://metadata.google.internal/'
  1396. 'computeMetadata/v1/?recursive=true')
  1397. headers = {'Metadata-Flavor': 'Google'}
  1398. metadata = get_provider_metadata(metadata_url, True, headers,
  1399. True)
  1400. # Filter sshKeys and serviceAccounts from gce metadata
  1401. if metadata:
  1402. metadata['project']['attributes'].pop('sshKeys', None)
  1403. metadata['instance'].pop('serviceAccounts', None)
  1404. elif (virt_type == 'xen' and virt_role == 'guest'
  1405. and re.match(r'.*\.amazon$', product_version)):
  1406. provider = 'aws'
  1407. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1408. metadata = get_provider_metadata(metadata_url)
  1409. elif re.search(r'OpenStack', product_name):
  1410. provider = 'openstack'
  1411. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1412. 'meta_data.json')
  1413. metadata = get_provider_metadata(metadata_url, True, None,
  1414. True)
  1415. if metadata:
  1416. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1417. metadata['ec2_compat'] = get_provider_metadata(
  1418. ec2_compat_url
  1419. )
  1420. # disable pylint maybe-no-member because overloaded use of
  1421. # the module name causes pylint to not detect that results
  1422. # is an array or hash
  1423. # pylint: disable=maybe-no-member
  1424. # Filter public_keys and random_seed from openstack metadata
  1425. metadata.pop('public_keys', None)
  1426. metadata.pop('random_seed', None)
  1427. if not metadata['ec2_compat']:
  1428. metadata = None
  1429. return dict(name=provider, metadata=metadata)
  1430. def init_provider_facts(self):
  1431. """ Initialize the provider facts
  1432. Returns:
  1433. dict: The normalized provider facts
  1434. """
  1435. provider_info = self.guess_host_provider()
  1436. provider_facts = normalize_provider_facts(
  1437. provider_info.get('name'),
  1438. provider_info.get('metadata')
  1439. )
  1440. return provider_facts
  1441. @staticmethod
  1442. def split_openshift_env_fact_keys(openshift_env_fact, openshift_env_structures):
  1443. """ Split openshift_env facts based on openshift_env structures.
  1444. Args:
  1445. openshift_env_fact (string): the openshift_env fact to split
  1446. ex: 'openshift_cloudprovider_openstack_auth_url'
  1447. openshift_env_structures (list): a list of structures to determine fact keys
  1448. ex: ['openshift.cloudprovider.openstack.*']
  1449. Returns:
  1450. list: a list of keys that represent the fact
  1451. ex: ['openshift', 'cloudprovider', 'openstack', 'auth_url']
  1452. """
  1453. # By default, we'll split an openshift_env fact by underscores.
  1454. fact_keys = openshift_env_fact.split('_')
  1455. # Determine if any of the provided variable structures match the fact.
  1456. matching_structure = None
  1457. if openshift_env_structures != None:
  1458. for structure in openshift_env_structures:
  1459. if re.match(structure, openshift_env_fact):
  1460. matching_structure = structure
  1461. # Fact didn't match any variable structures so return the default fact keys.
  1462. if matching_structure is None:
  1463. return fact_keys
  1464. final_keys = []
  1465. structure_keys = matching_structure.split('.')
  1466. for structure_key in structure_keys:
  1467. # Matched current key. Add to final keys.
  1468. if structure_key == fact_keys[structure_keys.index(structure_key)]:
  1469. final_keys.append(structure_key)
  1470. # Wildcard means we will be taking everything from here to the end of the fact.
  1471. elif structure_key == '*':
  1472. final_keys.append('_'.join(fact_keys[structure_keys.index(structure_key):]))
  1473. # Shouldn't have gotten here, return the fact keys.
  1474. else:
  1475. return fact_keys
  1476. return final_keys
  1477. # Disabling too-many-branches and too-many-locals.
  1478. # This should be cleaned up as a TODO item.
  1479. #pylint: disable=too-many-branches, too-many-locals
  1480. def init_local_facts(self, facts=None,
  1481. additive_facts_to_overwrite=None,
  1482. openshift_env=None,
  1483. openshift_env_structures=None,
  1484. protected_facts_to_overwrite=None):
  1485. """ Initialize the local facts
  1486. Args:
  1487. facts (dict): local facts to set
  1488. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1489. '.' notation ex: ['master.named_certificates']
  1490. openshift_env (dict): openshift env facts to set
  1491. protected_facts_to_overwrite (list): protected facts to overwrite in jinja
  1492. '.' notation ex: ['master.master_count']
  1493. Returns:
  1494. dict: The result of merging the provided facts with existing
  1495. local facts
  1496. """
  1497. changed = False
  1498. facts_to_set = dict()
  1499. if facts is not None:
  1500. facts_to_set[self.role] = facts
  1501. if openshift_env != {} and openshift_env != None:
  1502. for fact, value in openshift_env.iteritems():
  1503. oo_env_facts = dict()
  1504. current_level = oo_env_facts
  1505. keys = self.split_openshift_env_fact_keys(fact, openshift_env_structures)[1:]
  1506. if len(keys) > 0 and keys[0] != self.role:
  1507. continue
  1508. for key in keys:
  1509. if key == keys[-1]:
  1510. current_level[key] = value
  1511. elif key not in current_level:
  1512. current_level[key] = dict()
  1513. current_level = current_level[key]
  1514. facts_to_set = merge_facts(orig=facts_to_set,
  1515. new=oo_env_facts,
  1516. additive_facts_to_overwrite=[],
  1517. protected_facts_to_overwrite=[])
  1518. local_facts = get_local_facts_from_file(self.filename)
  1519. migrated_facts = migrate_local_facts(local_facts)
  1520. new_local_facts = merge_facts(migrated_facts,
  1521. facts_to_set,
  1522. additive_facts_to_overwrite,
  1523. protected_facts_to_overwrite)
  1524. if 'docker' in new_local_facts:
  1525. # remove duplicate and empty strings from registry lists
  1526. for cat in ['additional', 'blocked', 'insecure']:
  1527. key = '{0}_registries'.format(cat)
  1528. if key in new_local_facts['docker']:
  1529. val = new_local_facts['docker'][key]
  1530. if isinstance(val, basestring):
  1531. val = [x.strip() for x in val.split(',')]
  1532. new_local_facts['docker'][key] = list(set(val) - set(['']))
  1533. for facts in new_local_facts.values():
  1534. keys_to_delete = []
  1535. if isinstance(facts, dict):
  1536. for fact, value in facts.iteritems():
  1537. if value == "" or value is None:
  1538. keys_to_delete.append(fact)
  1539. for key in keys_to_delete:
  1540. del facts[key]
  1541. if new_local_facts != local_facts:
  1542. self.validate_local_facts(new_local_facts)
  1543. changed = True
  1544. if not module.check_mode:
  1545. save_local_facts(self.filename, new_local_facts)
  1546. self.changed = changed
  1547. return new_local_facts
  1548. def validate_local_facts(self, facts=None):
  1549. """ Validate local facts
  1550. Args:
  1551. facts (dict): local facts to validate
  1552. """
  1553. invalid_facts = dict()
  1554. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1555. if invalid_facts:
  1556. msg = 'Invalid facts detected:\n'
  1557. for key in invalid_facts.keys():
  1558. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1559. module.fail_json(msg=msg,
  1560. changed=self.changed)
  1561. # disabling pylint errors for line-too-long since we're dealing
  1562. # with best effort reduction of error messages here.
  1563. # disabling errors for too-many-branches since we require checking
  1564. # many conditions.
  1565. # pylint: disable=line-too-long, too-many-branches
  1566. @staticmethod
  1567. def validate_master_facts(facts, invalid_facts):
  1568. """ Validate master facts
  1569. Args:
  1570. facts (dict): local facts to validate
  1571. invalid_facts (dict): collected invalid_facts
  1572. Returns:
  1573. dict: Invalid facts
  1574. """
  1575. if 'master' in facts:
  1576. # openshift.master.session_auth_secrets
  1577. if 'session_auth_secrets' in facts['master']:
  1578. session_auth_secrets = facts['master']['session_auth_secrets']
  1579. if not issubclass(type(session_auth_secrets), list):
  1580. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1581. elif 'session_encryption_secrets' not in facts['master']:
  1582. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1583. 'if openshift_master_session_auth_secrets is provided.')
  1584. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1585. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1586. 'openshift_master_session_encryption_secrets must be '
  1587. 'equal length.')
  1588. else:
  1589. for secret in session_auth_secrets:
  1590. if len(secret) < 32:
  1591. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1592. 'Secrets must be at least 32 characters in length.')
  1593. # openshift.master.session_encryption_secrets
  1594. if 'session_encryption_secrets' in facts['master']:
  1595. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1596. if not issubclass(type(session_encryption_secrets), list):
  1597. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1598. elif 'session_auth_secrets' not in facts['master']:
  1599. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1600. 'set if openshift_master_session_encryption_secrets '
  1601. 'is provided.')
  1602. else:
  1603. for secret in session_encryption_secrets:
  1604. if len(secret) not in [16, 24, 32]:
  1605. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1606. 'Secrets must be 16, 24, or 32 characters in length.')
  1607. return invalid_facts
  1608. def main():
  1609. """ main """
  1610. # disabling pylint errors for global-variable-undefined and invalid-name
  1611. # for 'global module' usage, since it is required to use ansible_facts
  1612. # pylint: disable=global-variable-undefined, invalid-name
  1613. global module
  1614. module = AnsibleModule(
  1615. argument_spec=dict(
  1616. role=dict(default='common', required=False,
  1617. choices=OpenShiftFacts.known_roles),
  1618. local_facts=dict(default=None, type='dict', required=False),
  1619. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1620. openshift_env=dict(default={}, type='dict', required=False),
  1621. openshift_env_structures=dict(default=[], type='list', required=False),
  1622. protected_facts_to_overwrite=dict(default=[], type='list', required=False),
  1623. ),
  1624. supports_check_mode=True,
  1625. add_file_common_args=True,
  1626. )
  1627. role = module.params['role']
  1628. local_facts = module.params['local_facts']
  1629. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1630. openshift_env = module.params['openshift_env']
  1631. openshift_env_structures = module.params['openshift_env_structures']
  1632. protected_facts_to_overwrite = module.params['protected_facts_to_overwrite']
  1633. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1634. openshift_facts = OpenShiftFacts(role,
  1635. fact_file,
  1636. local_facts,
  1637. additive_facts_to_overwrite,
  1638. openshift_env,
  1639. openshift_env_structures,
  1640. protected_facts_to_overwrite)
  1641. file_params = module.params.copy()
  1642. file_params['path'] = fact_file
  1643. file_args = module.load_file_common_arguments(file_params)
  1644. changed = module.set_fs_attributes_if_different(file_args,
  1645. openshift_facts.changed)
  1646. return module.exit_json(changed=changed,
  1647. ansible_facts=openshift_facts.facts)
  1648. # ignore pylint errors related to the module_utils import
  1649. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1650. # import module snippets
  1651. from ansible.module_utils.basic import *
  1652. from ansible.module_utils.facts import *
  1653. from ansible.module_utils.urls import *
  1654. if __name__ == '__main__':
  1655. main()