openshift_facts.py 79 KB

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