openshift_facts.py 93 KB

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