openshift_facts.py 101 KB

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