openshift_facts.py 94 KB

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