openshift_facts.py 93 KB

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