openshift_facts.py 77 KB

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