openshift_facts.py 78 KB

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