openshift_facts.py 95 KB

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