openshift_facts.py 102 KB

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