openshift_facts.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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. def first_ip(network):
  27. """ Return the first IPv4 address in network
  28. Args:
  29. network (str): network in CIDR format
  30. Returns:
  31. str: first IPv4 address
  32. """
  33. atoi = lambda addr: struct.unpack("!I", socket.inet_aton(addr))[0]
  34. itoa = lambda addr: socket.inet_ntoa(struct.pack("!I", addr))
  35. (address, netmask) = network.split('/')
  36. netmask_i = (0xffffffff << (32 - atoi(netmask))) & 0xffffffff
  37. return itoa((atoi(address) & netmask_i) + 1)
  38. def hostname_valid(hostname):
  39. """ Test if specified hostname should be considered valid
  40. Args:
  41. hostname (str): hostname to test
  42. Returns:
  43. bool: True if valid, otherwise False
  44. """
  45. if (not hostname or
  46. hostname.startswith('localhost') or
  47. hostname.endswith('localdomain') or
  48. len(hostname.split('.')) < 2):
  49. return False
  50. return True
  51. def choose_hostname(hostnames=None, fallback=''):
  52. """ Choose a hostname from the provided hostnames
  53. Given a list of hostnames and a fallback value, choose a hostname to
  54. use. This function will prefer fqdns if they exist (excluding any that
  55. begin with localhost or end with localdomain) over ip addresses.
  56. Args:
  57. hostnames (list): list of hostnames
  58. fallback (str): default value to set if hostnames does not contain
  59. a valid hostname
  60. Returns:
  61. str: chosen hostname
  62. """
  63. hostname = fallback
  64. if hostnames is None:
  65. return hostname
  66. ip_regex = r'\A\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z'
  67. ips = [i for i in hostnames
  68. if (i is not None and isinstance(i, basestring)
  69. and re.match(ip_regex, i))]
  70. hosts = [i for i in hostnames
  71. if i is not None and i != '' and i not in ips]
  72. for host_list in (hosts, ips):
  73. for host in host_list:
  74. if hostname_valid(host):
  75. return host
  76. return hostname
  77. def query_metadata(metadata_url, headers=None, expect_json=False):
  78. """ Return metadata from the provided metadata_url
  79. Args:
  80. metadata_url (str): metadata url
  81. headers (dict): headers to set for metadata request
  82. expect_json (bool): does the metadata_url return json
  83. Returns:
  84. dict or list: metadata request result
  85. """
  86. result, info = fetch_url(module, metadata_url, headers=headers)
  87. if info['status'] != 200:
  88. raise OpenShiftFactsMetadataUnavailableError("Metadata unavailable")
  89. if expect_json:
  90. return module.from_json(result.read())
  91. else:
  92. return [line.strip() for line in result.readlines()]
  93. def walk_metadata(metadata_url, headers=None, expect_json=False):
  94. """ Walk the metadata tree and return a dictionary of the entire tree
  95. Args:
  96. metadata_url (str): metadata url
  97. headers (dict): headers to set for metadata request
  98. expect_json (bool): does the metadata_url return json
  99. Returns:
  100. dict: the result of walking the metadata tree
  101. """
  102. metadata = dict()
  103. for line in query_metadata(metadata_url, headers, expect_json):
  104. if line.endswith('/') and not line == 'public-keys/':
  105. key = line[:-1]
  106. metadata[key] = walk_metadata(metadata_url + line,
  107. headers, expect_json)
  108. else:
  109. results = query_metadata(metadata_url + line, headers,
  110. expect_json)
  111. if len(results) == 1:
  112. # disable pylint maybe-no-member because overloaded use of
  113. # the module name causes pylint to not detect that results
  114. # is an array or hash
  115. # pylint: disable=maybe-no-member
  116. metadata[line] = results.pop()
  117. else:
  118. metadata[line] = results
  119. return metadata
  120. def get_provider_metadata(metadata_url, supports_recursive=False,
  121. headers=None, expect_json=False):
  122. """ Retrieve the provider metadata
  123. Args:
  124. metadata_url (str): metadata url
  125. supports_recursive (bool): does the provider metadata api support
  126. recursion
  127. headers (dict): headers to set for metadata request
  128. expect_json (bool): does the metadata_url return json
  129. Returns:
  130. dict: the provider metadata
  131. """
  132. try:
  133. if supports_recursive:
  134. metadata = query_metadata(metadata_url, headers,
  135. expect_json)
  136. else:
  137. metadata = walk_metadata(metadata_url, headers,
  138. expect_json)
  139. except OpenShiftFactsMetadataUnavailableError:
  140. metadata = None
  141. return metadata
  142. def normalize_gce_facts(metadata, facts):
  143. """ Normalize gce facts
  144. Args:
  145. metadata (dict): provider metadata
  146. facts (dict): facts to update
  147. Returns:
  148. dict: the result of adding the normalized metadata to the provided
  149. facts dict
  150. """
  151. for interface in metadata['instance']['networkInterfaces']:
  152. int_info = dict(ips=[interface['ip']], network_type='gce')
  153. int_info['public_ips'] = [ac['externalIp'] for ac
  154. in interface['accessConfigs']]
  155. int_info['public_ips'].extend(interface['forwardedIps'])
  156. _, _, network_id = interface['network'].rpartition('/')
  157. int_info['network_id'] = network_id
  158. facts['network']['interfaces'].append(int_info)
  159. _, _, zone = metadata['instance']['zone'].rpartition('/')
  160. facts['zone'] = zone
  161. # Default to no sdn for GCE deployments
  162. facts['use_openshift_sdn'] = False
  163. # GCE currently only supports a single interface
  164. facts['network']['ip'] = facts['network']['interfaces'][0]['ips'][0]
  165. pub_ip = facts['network']['interfaces'][0]['public_ips'][0]
  166. facts['network']['public_ip'] = pub_ip
  167. facts['network']['hostname'] = metadata['instance']['hostname']
  168. # TODO: attempt to resolve public_hostname
  169. facts['network']['public_hostname'] = facts['network']['public_ip']
  170. return facts
  171. def normalize_aws_facts(metadata, facts):
  172. """ Normalize aws facts
  173. Args:
  174. metadata (dict): provider metadata
  175. facts (dict): facts to update
  176. Returns:
  177. dict: the result of adding the normalized metadata to the provided
  178. facts dict
  179. """
  180. for interface in sorted(
  181. metadata['network']['interfaces']['macs'].values(),
  182. key=lambda x: x['device-number']
  183. ):
  184. int_info = dict()
  185. var_map = {'ips': 'local-ipv4s', 'public_ips': 'public-ipv4s'}
  186. for ips_var, int_var in var_map.iteritems():
  187. ips = interface.get(int_var)
  188. if isinstance(ips, basestring):
  189. int_info[ips_var] = [ips]
  190. else:
  191. int_info[ips_var] = ips
  192. if 'vpc-id' in interface:
  193. int_info['network_type'] = 'vpc'
  194. else:
  195. int_info['network_type'] = 'classic'
  196. if int_info['network_type'] == 'vpc':
  197. int_info['network_id'] = interface['subnet-id']
  198. else:
  199. int_info['network_id'] = None
  200. facts['network']['interfaces'].append(int_info)
  201. facts['zone'] = metadata['placement']['availability-zone']
  202. # TODO: actually attempt to determine default local and public ips
  203. # by using the ansible default ip fact and the ipv4-associations
  204. # from the ec2 metadata
  205. facts['network']['ip'] = metadata.get('local-ipv4')
  206. facts['network']['public_ip'] = metadata.get('public-ipv4')
  207. # TODO: verify that local hostname makes sense and is resolvable
  208. facts['network']['hostname'] = metadata.get('local-hostname')
  209. # TODO: verify that public hostname makes sense and is resolvable
  210. facts['network']['public_hostname'] = metadata.get('public-hostname')
  211. return facts
  212. def normalize_openstack_facts(metadata, facts):
  213. """ Normalize openstack facts
  214. Args:
  215. metadata (dict): provider metadata
  216. facts (dict): facts to update
  217. Returns:
  218. dict: the result of adding the normalized metadata to the provided
  219. facts dict
  220. """
  221. # openstack ec2 compat api does not support network interfaces and
  222. # the version tested on did not include the info in the openstack
  223. # metadata api, should be updated if neutron exposes this.
  224. facts['zone'] = metadata['availability_zone']
  225. local_ipv4 = metadata['ec2_compat']['local-ipv4'].split(',')[0]
  226. facts['network']['ip'] = local_ipv4
  227. facts['network']['public_ip'] = metadata['ec2_compat']['public-ipv4']
  228. # TODO: verify local hostname makes sense and is resolvable
  229. facts['network']['hostname'] = metadata['hostname']
  230. # TODO: verify that public hostname makes sense and is resolvable
  231. pub_h = metadata['ec2_compat']['public-hostname']
  232. facts['network']['public_hostname'] = pub_h
  233. return facts
  234. def normalize_provider_facts(provider, metadata):
  235. """ Normalize provider facts
  236. Args:
  237. provider (str): host provider
  238. metadata (dict): provider metadata
  239. Returns:
  240. dict: the normalized provider facts
  241. """
  242. if provider is None or metadata is None:
  243. return {}
  244. # TODO: test for ipv6_enabled where possible (gce, aws do not support)
  245. # and configure ipv6 facts if available
  246. # TODO: add support for setting user_data if available
  247. facts = dict(name=provider, metadata=metadata,
  248. network=dict(interfaces=[], ipv6_enabled=False))
  249. if provider == 'gce':
  250. facts = normalize_gce_facts(metadata, facts)
  251. elif provider == 'ec2':
  252. facts = normalize_aws_facts(metadata, facts)
  253. elif provider == 'openstack':
  254. facts = normalize_openstack_facts(metadata, facts)
  255. return facts
  256. def set_fluentd_facts_if_unset(facts):
  257. """ Set fluentd facts if not already present in facts dict
  258. dict: the facts dict updated with the generated fluentd facts if
  259. missing
  260. Args:
  261. facts (dict): existing facts
  262. Returns:
  263. dict: the facts dict updated with the generated fluentd
  264. facts if they were not already present
  265. """
  266. if 'common' in facts:
  267. if 'use_fluentd' not in facts['common']:
  268. use_fluentd = False
  269. facts['common']['use_fluentd'] = use_fluentd
  270. return facts
  271. def set_flannel_facts_if_unset(facts):
  272. """ Set flannel facts if not already present in facts dict
  273. dict: the facts dict updated with the flannel facts if
  274. missing
  275. Args:
  276. facts (dict): existing facts
  277. Returns:
  278. dict: the facts dict updated with the flannel
  279. facts if they were not already present
  280. """
  281. if 'common' in facts:
  282. if 'use_flannel' not in facts['common']:
  283. use_flannel = False
  284. facts['common']['use_flannel'] = use_flannel
  285. return facts
  286. def set_node_schedulability(facts):
  287. """ Set schedulable facts if not already present in facts dict
  288. Args:
  289. facts (dict): existing facts
  290. Returns:
  291. dict: the facts dict updated with the generated schedulable
  292. facts if they were not already present
  293. """
  294. if 'node' in facts:
  295. if 'schedulable' not in facts['node']:
  296. if 'master' in facts:
  297. facts['node']['schedulable'] = False
  298. else:
  299. facts['node']['schedulable'] = True
  300. return facts
  301. def set_master_selectors(facts):
  302. """ Set selectors facts if not already present in facts dict
  303. Args:
  304. facts (dict): existing facts
  305. Returns:
  306. dict: the facts dict updated with the generated selectors
  307. facts if they were not already present
  308. """
  309. if 'master' in facts:
  310. if 'infra_nodes' in facts['master']:
  311. deployment_type = facts['common']['deployment_type']
  312. if deployment_type == 'online':
  313. selector = "type=infra"
  314. else:
  315. selector = "region=infra"
  316. if 'router_selector' not in facts['master']:
  317. facts['master']['router_selector'] = selector
  318. if 'registry_selector' not in facts['master']:
  319. facts['master']['registry_selector'] = selector
  320. return facts
  321. def set_metrics_facts_if_unset(facts):
  322. """ Set cluster metrics facts if not already present in facts dict
  323. dict: the facts dict updated with the generated cluster metrics facts if
  324. missing
  325. Args:
  326. facts (dict): existing facts
  327. Returns:
  328. dict: the facts dict updated with the generated cluster metrics
  329. facts if they were not already present
  330. """
  331. if 'common' in facts:
  332. if 'use_cluster_metrics' not in facts['common']:
  333. use_cluster_metrics = False
  334. facts['common']['use_cluster_metrics'] = use_cluster_metrics
  335. return facts
  336. def set_project_cfg_facts_if_unset(facts):
  337. """ Set Project Configuration facts if not already present in facts dict
  338. dict:
  339. Args:
  340. facts (dict): existing facts
  341. Returns:
  342. dict: the facts dict updated with the generated Project Configuration
  343. facts if they were not already present
  344. """
  345. config = {
  346. 'default_node_selector': '',
  347. 'project_request_message': '',
  348. 'project_request_template': '',
  349. 'mcs_allocator_range': 's0:/2',
  350. 'mcs_labels_per_project': 5,
  351. 'uid_allocator_range': '1000000000-1999999999/10000'
  352. }
  353. if 'master' in facts:
  354. for key, value in config.items():
  355. if key not in facts['master']:
  356. facts['master'][key] = value
  357. return facts
  358. def set_identity_providers_if_unset(facts):
  359. """ Set identity_providers fact if not already present in facts dict
  360. Args:
  361. facts (dict): existing facts
  362. Returns:
  363. dict: the facts dict updated with the generated identity providers
  364. facts if they were not already present
  365. """
  366. if 'master' in facts:
  367. deployment_type = facts['common']['deployment_type']
  368. if 'identity_providers' not in facts['master']:
  369. identity_provider = dict(
  370. name='allow_all', challenge=True, login=True,
  371. kind='AllowAllPasswordIdentityProvider'
  372. )
  373. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  374. identity_provider = dict(
  375. name='deny_all', challenge=True, login=True,
  376. kind='DenyAllPasswordIdentityProvider'
  377. )
  378. facts['master']['identity_providers'] = [identity_provider]
  379. return facts
  380. def set_url_facts_if_unset(facts):
  381. """ Set url facts if not already present in facts dict
  382. Args:
  383. facts (dict): existing facts
  384. Returns:
  385. dict: the facts dict updated with the generated url facts if they
  386. were not already present
  387. """
  388. if 'master' in facts:
  389. api_use_ssl = facts['master']['api_use_ssl']
  390. api_port = facts['master']['api_port']
  391. console_use_ssl = facts['master']['console_use_ssl']
  392. console_port = facts['master']['console_port']
  393. console_path = facts['master']['console_path']
  394. etcd_use_ssl = facts['master']['etcd_use_ssl']
  395. etcd_hosts = facts['master']['etcd_hosts']
  396. etcd_port = facts['master']['etcd_port']
  397. hostname = facts['common']['hostname']
  398. public_hostname = facts['common']['public_hostname']
  399. cluster_hostname = facts['master'].get('cluster_hostname')
  400. cluster_public_hostname = facts['master'].get('cluster_public_hostname')
  401. if 'etcd_urls' not in facts['master']:
  402. etcd_urls = []
  403. if etcd_hosts != '':
  404. facts['master']['etcd_port'] = etcd_port
  405. facts['master']['embedded_etcd'] = False
  406. for host in etcd_hosts:
  407. etcd_urls.append(format_url(etcd_use_ssl, host,
  408. etcd_port))
  409. else:
  410. etcd_urls = [format_url(etcd_use_ssl, hostname,
  411. etcd_port)]
  412. facts['master']['etcd_urls'] = etcd_urls
  413. if 'api_url' not in facts['master']:
  414. api_hostname = cluster_hostname if cluster_hostname else hostname
  415. facts['master']['api_url'] = format_url(api_use_ssl, api_hostname,
  416. api_port)
  417. if 'public_api_url' not in facts['master']:
  418. api_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  419. facts['master']['public_api_url'] = format_url(api_use_ssl,
  420. api_public_hostname,
  421. api_port)
  422. if 'console_url' not in facts['master']:
  423. console_hostname = cluster_hostname if cluster_hostname else hostname
  424. facts['master']['console_url'] = format_url(console_use_ssl,
  425. console_hostname,
  426. console_port,
  427. console_path)
  428. if 'public_console_url' not in facts['master']:
  429. console_public_hostname = cluster_public_hostname if cluster_public_hostname else public_hostname
  430. facts['master']['public_console_url'] = format_url(console_use_ssl,
  431. console_public_hostname,
  432. console_port,
  433. console_path)
  434. return facts
  435. def set_aggregate_facts(facts):
  436. """ Set aggregate facts
  437. Args:
  438. facts (dict): existing facts
  439. Returns:
  440. dict: the facts dict updated with aggregated facts
  441. """
  442. all_hostnames = set()
  443. internal_hostnames = set()
  444. if 'common' in facts:
  445. all_hostnames.add(facts['common']['hostname'])
  446. all_hostnames.add(facts['common']['public_hostname'])
  447. all_hostnames.add(facts['common']['ip'])
  448. all_hostnames.add(facts['common']['public_ip'])
  449. internal_hostnames.add(facts['common']['hostname'])
  450. internal_hostnames.add(facts['common']['ip'])
  451. cluster_domain = facts['common']['dns_domain']
  452. if 'master' in facts:
  453. if 'cluster_hostname' in facts['master']:
  454. all_hostnames.add(facts['master']['cluster_hostname'])
  455. if 'cluster_public_hostname' in facts['master']:
  456. all_hostnames.add(facts['master']['cluster_public_hostname'])
  457. svc_names = ['openshift', 'openshift.default', 'openshift.default.svc',
  458. 'openshift.default.svc.' + cluster_domain, 'kubernetes', 'kubernetes.default',
  459. 'kubernetes.default.svc', 'kubernetes.default.svc.' + cluster_domain]
  460. all_hostnames.update(svc_names)
  461. internal_hostnames.update(svc_names)
  462. first_svc_ip = first_ip(facts['master']['portal_net'])
  463. all_hostnames.add(first_svc_ip)
  464. internal_hostnames.add(first_svc_ip)
  465. facts['common']['all_hostnames'] = list(all_hostnames)
  466. facts['common']['internal_hostnames'] = list(internal_hostnames)
  467. return facts
  468. def set_etcd_facts_if_unset(facts):
  469. """
  470. If using embedded etcd, loads the data directory from master-config.yaml.
  471. If using standalone etcd, loads ETCD_DATA_DIR from etcd.conf.
  472. If anything goes wrong parsing these, the fact will not be set.
  473. """
  474. if 'master' in facts and facts['master']['embedded_etcd']:
  475. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  476. if 'etcd_data_dir' not in etcd_facts:
  477. try:
  478. # Parse master config to find actual etcd data dir:
  479. master_cfg_path = os.path.join(facts['common']['config_base'],
  480. 'master/master-config.yaml')
  481. master_cfg_f = open(master_cfg_path, 'r')
  482. config = yaml.safe_load(master_cfg_f.read())
  483. master_cfg_f.close()
  484. etcd_facts['etcd_data_dir'] = \
  485. config['etcdConfig']['storageDirectory']
  486. facts['etcd'] = etcd_facts
  487. # We don't want exceptions bubbling up here:
  488. # pylint: disable=broad-except
  489. except Exception:
  490. pass
  491. else:
  492. etcd_facts = facts['etcd'] if 'etcd' in facts else dict()
  493. # Read ETCD_DATA_DIR from /etc/etcd/etcd.conf:
  494. try:
  495. # Add a fake section for parsing:
  496. ini_str = '[root]\n' + open('/etc/etcd/etcd.conf', 'r').read()
  497. ini_fp = StringIO.StringIO(ini_str)
  498. config = ConfigParser.RawConfigParser()
  499. config.readfp(ini_fp)
  500. etcd_data_dir = config.get('root', 'ETCD_DATA_DIR')
  501. if etcd_data_dir.startswith('"') and etcd_data_dir.endswith('"'):
  502. etcd_data_dir = etcd_data_dir[1:-1]
  503. etcd_facts['etcd_data_dir'] = etcd_data_dir
  504. facts['etcd'] = etcd_facts
  505. # We don't want exceptions bubbling up here:
  506. # pylint: disable=broad-except
  507. except Exception:
  508. pass
  509. return facts
  510. def set_deployment_facts_if_unset(facts):
  511. """ Set Facts that vary based on deployment_type. This currently
  512. includes common.service_type, common.config_base, master.registry_url,
  513. node.registry_url, node.storage_plugin_deps
  514. Args:
  515. facts (dict): existing facts
  516. Returns:
  517. dict: the facts dict updated with the generated deployment_type
  518. facts
  519. """
  520. # disabled to avoid breaking up facts related to deployment type into
  521. # multiple methods for now.
  522. # pylint: disable=too-many-statements, too-many-branches
  523. if 'common' in facts:
  524. deployment_type = facts['common']['deployment_type']
  525. if 'service_type' not in facts['common']:
  526. service_type = 'atomic-openshift'
  527. if deployment_type == 'origin':
  528. service_type = 'origin'
  529. elif deployment_type in ['enterprise']:
  530. service_type = 'openshift'
  531. facts['common']['service_type'] = service_type
  532. if 'config_base' not in facts['common']:
  533. config_base = '/etc/origin'
  534. if deployment_type in ['enterprise']:
  535. config_base = '/etc/openshift'
  536. # Handle upgrade scenarios when symlinks don't yet exist:
  537. if not os.path.exists(config_base) and os.path.exists('/etc/openshift'):
  538. config_base = '/etc/openshift'
  539. facts['common']['config_base'] = config_base
  540. if 'data_dir' not in facts['common']:
  541. data_dir = '/var/lib/origin'
  542. if deployment_type in ['enterprise']:
  543. data_dir = '/var/lib/openshift'
  544. # Handle upgrade scenarios when symlinks don't yet exist:
  545. if not os.path.exists(data_dir) and os.path.exists('/var/lib/openshift'):
  546. data_dir = '/var/lib/openshift'
  547. facts['common']['data_dir'] = data_dir
  548. # remove duplicate and empty strings from registry lists
  549. for cat in ['additional', 'blocked', 'insecure']:
  550. key = 'docker_{0}_registries'.format(cat)
  551. if key in facts['common']:
  552. facts['common'][key] = list(set(facts['common'][key]) - set(['']))
  553. if deployment_type in ['enterprise', 'atomic-enterprise', 'openshift-enterprise']:
  554. addtl_regs = facts['common'].get('docker_additional_registries', [])
  555. ent_reg = 'registry.access.redhat.com'
  556. if ent_reg not in addtl_regs:
  557. facts['common']['docker_additional_registries'] = addtl_regs + [ent_reg]
  558. for role in ('master', 'node'):
  559. if role in facts:
  560. deployment_type = facts['common']['deployment_type']
  561. if 'registry_url' not in facts[role]:
  562. registry_url = 'openshift/origin-${component}:${version}'
  563. if deployment_type in ['enterprise', 'online', 'openshift-enterprise']:
  564. registry_url = 'openshift3/ose-${component}:${version}'
  565. elif deployment_type == 'atomic-enterprise':
  566. registry_url = 'aep3_beta/aep-${component}:${version}'
  567. facts[role]['registry_url'] = registry_url
  568. if 'master' in facts:
  569. deployment_type = facts['common']['deployment_type']
  570. openshift_features = ['Builder', 'S2IBuilder', 'WebConsole']
  571. if 'disabled_features' in facts['master']:
  572. if deployment_type == 'atomic-enterprise':
  573. curr_disabled_features = set(facts['master']['disabled_features'])
  574. facts['master']['disabled_features'] = list(curr_disabled_features.union(openshift_features))
  575. else:
  576. if deployment_type == 'atomic-enterprise':
  577. facts['master']['disabled_features'] = openshift_features
  578. if 'node' in facts:
  579. deployment_type = facts['common']['deployment_type']
  580. if 'storage_plugin_deps' not in facts['node']:
  581. if deployment_type in ['openshift-enterprise', 'atomic-enterprise']:
  582. facts['node']['storage_plugin_deps'] = ['ceph', 'glusterfs']
  583. else:
  584. facts['node']['storage_plugin_deps'] = []
  585. return facts
  586. def set_version_facts_if_unset(facts):
  587. """ Set version facts. This currently includes common.version and
  588. common.version_greater_than_3_1_or_1_1.
  589. Args:
  590. facts (dict): existing facts
  591. Returns:
  592. dict: the facts dict updated with version facts.
  593. """
  594. if 'common' in facts:
  595. deployment_type = facts['common']['deployment_type']
  596. facts['common']['version'] = version = get_openshift_version()
  597. if version is not None:
  598. if deployment_type == 'origin':
  599. version_gt_3_1_or_1_1 = LooseVersion(version) > LooseVersion('1.0.6')
  600. version_gt_3_1_1_or_1_1_1 = LooseVersion(version) > LooseVersion('1.1.1')
  601. else:
  602. version_gt_3_1_or_1_1 = LooseVersion(version) > LooseVersion('3.0.2.900')
  603. version_gt_3_1_1_or_1_1_1 = LooseVersion(version) > LooseVersion('3.1.1')
  604. else:
  605. version_gt_3_1_or_1_1 = True
  606. version_gt_3_1_1_or_1_1_1 = True
  607. facts['common']['version_greater_than_3_1_or_1_1'] = version_gt_3_1_or_1_1
  608. facts['common']['version_greater_than_3_1_1_or_1_1_1'] = version_gt_3_1_1_or_1_1_1
  609. return facts
  610. def set_manageiq_facts_if_unset(facts):
  611. """ Set manageiq facts. This currently includes common.use_manageiq.
  612. Args:
  613. facts (dict): existing facts
  614. Returns:
  615. dict: the facts dict updated with version facts.
  616. Raises:
  617. OpenShiftFactsInternalError:
  618. """
  619. if 'common' not in facts:
  620. if 'version_greater_than_3_1_or_1_1' not in facts['common']:
  621. raise OpenShiftFactsInternalError(
  622. "Invalid invocation: The required facts are not set"
  623. )
  624. if 'use_mangeiq' not in facts['common']:
  625. facts['common']['use_manageiq'] = facts['common']['version_greater_than_3_1_or_1_1']
  626. return facts
  627. def set_sdn_facts_if_unset(facts, system_facts):
  628. """ Set sdn facts if not already present in facts dict
  629. Args:
  630. facts (dict): existing facts
  631. system_facts (dict): ansible_facts
  632. Returns:
  633. dict: the facts dict updated with the generated sdn facts if they
  634. were not already present
  635. """
  636. if 'common' in facts:
  637. use_sdn = facts['common']['use_openshift_sdn']
  638. if not (use_sdn == '' or isinstance(use_sdn, bool)):
  639. use_sdn = bool(strtobool(str(use_sdn)))
  640. facts['common']['use_openshift_sdn'] = use_sdn
  641. if 'sdn_network_plugin_name' not in facts['common']:
  642. plugin = 'redhat/openshift-ovs-subnet' if use_sdn else ''
  643. facts['common']['sdn_network_plugin_name'] = plugin
  644. if 'master' in facts:
  645. if 'sdn_cluster_network_cidr' not in facts['master']:
  646. facts['master']['sdn_cluster_network_cidr'] = '10.1.0.0/16'
  647. if 'sdn_host_subnet_length' not in facts['master']:
  648. facts['master']['sdn_host_subnet_length'] = '8'
  649. if 'node' in facts and 'sdn_mtu' not in facts['node']:
  650. node_ip = facts['common']['ip']
  651. # default MTU if interface MTU cannot be detected
  652. facts['node']['sdn_mtu'] = '1450'
  653. for val in system_facts.itervalues():
  654. if isinstance(val, dict) and 'mtu' in val:
  655. mtu = val['mtu']
  656. if 'ipv4' in val and val['ipv4'].get('address') == node_ip:
  657. facts['node']['sdn_mtu'] = str(mtu - 50)
  658. return facts
  659. def format_url(use_ssl, hostname, port, path=''):
  660. """ Format url based on ssl flag, hostname, port and path
  661. Args:
  662. use_ssl (bool): is ssl enabled
  663. hostname (str): hostname
  664. port (str): port
  665. path (str): url path
  666. Returns:
  667. str: The generated url string
  668. """
  669. scheme = 'https' if use_ssl else 'http'
  670. netloc = hostname
  671. if (use_ssl and port != '443') or (not use_ssl and port != '80'):
  672. netloc += ":%s" % port
  673. return urlparse.urlunparse((scheme, netloc, path, '', '', ''))
  674. def get_current_config(facts):
  675. """ Get current openshift config
  676. Args:
  677. facts (dict): existing facts
  678. Returns:
  679. dict: the facts dict updated with the current openshift config
  680. """
  681. current_config = dict()
  682. roles = [role for role in facts if role not in ['common', 'provider']]
  683. for role in roles:
  684. if 'roles' in current_config:
  685. current_config['roles'].append(role)
  686. else:
  687. current_config['roles'] = [role]
  688. # TODO: parse the /etc/sysconfig/openshift-{master,node} config to
  689. # determine the location of files.
  690. # TODO: I suspect this isn't working right now, but it doesn't prevent
  691. # anything from working properly as far as I can tell, perhaps because
  692. # we override the kubeconfig path everywhere we use it?
  693. # Query kubeconfig settings
  694. kubeconfig_dir = '/var/lib/origin/openshift.local.certificates'
  695. if role == 'node':
  696. kubeconfig_dir = os.path.join(
  697. kubeconfig_dir, "node-%s" % facts['common']['hostname']
  698. )
  699. kubeconfig_path = os.path.join(kubeconfig_dir, '.kubeconfig')
  700. if (os.path.isfile('/usr/bin/openshift')
  701. and os.path.isfile(kubeconfig_path)):
  702. try:
  703. _, output, _ = module.run_command(
  704. ["/usr/bin/openshift", "ex", "config", "view", "-o",
  705. "json", "--kubeconfig=%s" % kubeconfig_path],
  706. check_rc=False
  707. )
  708. config = json.loads(output)
  709. cad = 'certificate-authority-data'
  710. try:
  711. for cluster in config['clusters']:
  712. config['clusters'][cluster][cad] = 'masked'
  713. except KeyError:
  714. pass
  715. try:
  716. for user in config['users']:
  717. config['users'][user][cad] = 'masked'
  718. config['users'][user]['client-key-data'] = 'masked'
  719. except KeyError:
  720. pass
  721. current_config['kubeconfig'] = config
  722. # override pylint broad-except warning, since we do not want
  723. # to bubble up any exceptions if oc config view
  724. # fails
  725. # pylint: disable=broad-except
  726. except Exception:
  727. pass
  728. return current_config
  729. def get_openshift_version():
  730. """ Get current version of openshift on the host
  731. Returns:
  732. version: the current openshift version
  733. """
  734. version = None
  735. if os.path.isfile('/usr/bin/openshift'):
  736. _, output, _ = module.run_command(['/usr/bin/openshift', 'version'])
  737. versions = dict(e.split(' v') for e in output.splitlines() if ' v' in e)
  738. version = versions.get('openshift', '')
  739. #TODO: acknowledge the possility of a containerized install
  740. return version
  741. def apply_provider_facts(facts, provider_facts):
  742. """ Apply provider facts to supplied facts dict
  743. Args:
  744. facts (dict): facts dict to update
  745. provider_facts (dict): provider facts to apply
  746. roles: host roles
  747. Returns:
  748. dict: the merged facts
  749. """
  750. if not provider_facts:
  751. return facts
  752. use_openshift_sdn = provider_facts.get('use_openshift_sdn')
  753. if isinstance(use_openshift_sdn, bool):
  754. facts['common']['use_openshift_sdn'] = use_openshift_sdn
  755. common_vars = [('hostname', 'ip'), ('public_hostname', 'public_ip')]
  756. for h_var, ip_var in common_vars:
  757. ip_value = provider_facts['network'].get(ip_var)
  758. if ip_value:
  759. facts['common'][ip_var] = ip_value
  760. facts['common'][h_var] = choose_hostname(
  761. [provider_facts['network'].get(h_var)],
  762. facts['common'][ip_var]
  763. )
  764. facts['provider'] = provider_facts
  765. return facts
  766. def merge_facts(orig, new, additive_facts_to_overwrite):
  767. """ Recursively merge facts dicts
  768. Args:
  769. orig (dict): existing facts
  770. new (dict): facts to update
  771. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  772. '.' notation ex: ['master.named_certificates']
  773. Returns:
  774. dict: the merged facts
  775. """
  776. additive_facts = ['named_certificates']
  777. facts = dict()
  778. for key, value in orig.iteritems():
  779. if key in new:
  780. if isinstance(value, dict) and isinstance(new[key], dict):
  781. relevant_additive_facts = []
  782. # Keep additive_facts_to_overwrite if key matches
  783. for item in additive_facts_to_overwrite:
  784. if '.' in item and item.startswith(key + '.'):
  785. relevant_additive_facts.append(item)
  786. facts[key] = merge_facts(value, new[key], relevant_additive_facts)
  787. elif key in additive_facts and key not in [x.split('.')[-1] for x in additive_facts_to_overwrite]:
  788. # Fact is additive so we'll combine orig and new.
  789. if isinstance(value, list) and isinstance(new[key], list):
  790. new_fact = []
  791. for item in copy.deepcopy(value) + copy.copy(new[key]):
  792. if item not in new_fact:
  793. new_fact.append(item)
  794. facts[key] = new_fact
  795. else:
  796. facts[key] = copy.copy(new[key])
  797. else:
  798. facts[key] = copy.deepcopy(value)
  799. new_keys = set(new.keys()) - set(orig.keys())
  800. for key in new_keys:
  801. facts[key] = copy.deepcopy(new[key])
  802. return facts
  803. def save_local_facts(filename, facts):
  804. """ Save local facts
  805. Args:
  806. filename (str): local facts file
  807. facts (dict): facts to set
  808. """
  809. try:
  810. fact_dir = os.path.dirname(filename)
  811. if not os.path.exists(fact_dir):
  812. os.makedirs(fact_dir)
  813. with open(filename, 'w') as fact_file:
  814. fact_file.write(module.jsonify(facts))
  815. os.chmod(filename, 0o600)
  816. except (IOError, OSError) as ex:
  817. raise OpenShiftFactsFileWriteError(
  818. "Could not create fact file: %s, error: %s" % (filename, ex)
  819. )
  820. def get_local_facts_from_file(filename):
  821. """ Retrieve local facts from fact file
  822. Args:
  823. filename (str): local facts file
  824. Returns:
  825. dict: the retrieved facts
  826. """
  827. local_facts = dict()
  828. try:
  829. # Handle conversion of INI style facts file to json style
  830. ini_facts = ConfigParser.SafeConfigParser()
  831. ini_facts.read(filename)
  832. for section in ini_facts.sections():
  833. local_facts[section] = dict()
  834. for key, value in ini_facts.items(section):
  835. local_facts[section][key] = value
  836. except (ConfigParser.MissingSectionHeaderError,
  837. ConfigParser.ParsingError):
  838. try:
  839. with open(filename, 'r') as facts_file:
  840. local_facts = json.load(facts_file)
  841. except (ValueError, IOError):
  842. pass
  843. return local_facts
  844. def set_container_facts_if_unset(facts):
  845. """ Set containerized facts.
  846. Args:
  847. facts (dict): existing facts
  848. Returns:
  849. dict: the facts dict updated with the generated containerization
  850. facts
  851. """
  852. deployment_type = facts['common']['deployment_type']
  853. if deployment_type in ['enterprise', 'openshift-enterprise']:
  854. master_image = 'openshift3/ose'
  855. cli_image = master_image
  856. node_image = 'openshift3/node'
  857. ovs_image = 'openshift3/openvswitch'
  858. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  859. elif deployment_type == 'atomic-enterprise':
  860. master_image = 'aep3_beta/aep'
  861. cli_image = master_image
  862. node_image = 'aep3_beta/node'
  863. ovs_image = 'aep3_beta/openvswitch'
  864. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  865. else:
  866. master_image = 'openshift/origin'
  867. cli_image = master_image
  868. node_image = 'openshift/node'
  869. ovs_image = 'openshift/openvswitch'
  870. etcd_image = 'registry.access.redhat.com/rhel7/etcd'
  871. facts['common']['is_atomic'] = os.path.isfile('/run/ostree-booted')
  872. if 'is_containerized' not in facts['common']:
  873. facts['common']['is_containerized'] = facts['common']['is_atomic']
  874. if 'cli_image' not in facts['common']:
  875. facts['common']['cli_image'] = cli_image
  876. if 'etcd' in facts and 'etcd_image' not in facts['etcd']:
  877. facts['etcd']['etcd_image'] = etcd_image
  878. if 'master' in facts and 'master_image' not in facts['master']:
  879. facts['master']['master_image'] = master_image
  880. if 'node' in facts:
  881. if 'node_image' not in facts['node']:
  882. facts['node']['node_image'] = node_image
  883. if 'ovs_image' not in facts['node']:
  884. facts['node']['ovs_image'] = ovs_image
  885. return facts
  886. class OpenShiftFactsInternalError(Exception):
  887. """Origin Facts Error"""
  888. pass
  889. class OpenShiftFactsUnsupportedRoleError(Exception):
  890. """Origin Facts Unsupported Role Error"""
  891. pass
  892. class OpenShiftFactsFileWriteError(Exception):
  893. """Origin Facts File Write Error"""
  894. pass
  895. class OpenShiftFactsMetadataUnavailableError(Exception):
  896. """Origin Facts Metadata Unavailable Error"""
  897. pass
  898. class OpenShiftFacts(object):
  899. """ Origin Facts
  900. Attributes:
  901. facts (dict): facts for the host
  902. Args:
  903. module (AnsibleModule): an AnsibleModule object
  904. role (str): role for setting local facts
  905. filename (str): local facts file to use
  906. local_facts (dict): local facts to set
  907. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  908. '.' notation ex: ['master.named_certificates']
  909. Raises:
  910. OpenShiftFactsUnsupportedRoleError:
  911. """
  912. known_roles = ['common', 'master', 'node', 'master_sdn', 'node_sdn', 'etcd', 'nfs']
  913. def __init__(self, role, filename, local_facts, additive_facts_to_overwrite=False):
  914. self.changed = False
  915. self.filename = filename
  916. if role not in self.known_roles:
  917. raise OpenShiftFactsUnsupportedRoleError(
  918. "Role %s is not supported by this module" % role
  919. )
  920. self.role = role
  921. self.system_facts = ansible_facts(module)
  922. self.facts = self.generate_facts(local_facts, additive_facts_to_overwrite)
  923. def generate_facts(self, local_facts, additive_facts_to_overwrite):
  924. """ Generate facts
  925. Args:
  926. local_facts (dict): local_facts for overriding generated
  927. defaults
  928. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  929. '.' notation ex: ['master.named_certificates']
  930. Returns:
  931. dict: The generated facts
  932. """
  933. local_facts = self.init_local_facts(local_facts, additive_facts_to_overwrite)
  934. roles = local_facts.keys()
  935. defaults = self.get_defaults(roles)
  936. provider_facts = self.init_provider_facts()
  937. facts = apply_provider_facts(defaults, provider_facts)
  938. facts = merge_facts(facts, local_facts, additive_facts_to_overwrite)
  939. facts['current_config'] = get_current_config(facts)
  940. facts = set_url_facts_if_unset(facts)
  941. facts = set_project_cfg_facts_if_unset(facts)
  942. facts = set_fluentd_facts_if_unset(facts)
  943. facts = set_flannel_facts_if_unset(facts)
  944. facts = set_node_schedulability(facts)
  945. facts = set_master_selectors(facts)
  946. facts = set_metrics_facts_if_unset(facts)
  947. facts = set_identity_providers_if_unset(facts)
  948. facts = set_sdn_facts_if_unset(facts, self.system_facts)
  949. facts = set_deployment_facts_if_unset(facts)
  950. facts = set_version_facts_if_unset(facts)
  951. facts = set_manageiq_facts_if_unset(facts)
  952. facts = set_aggregate_facts(facts)
  953. facts = set_etcd_facts_if_unset(facts)
  954. facts = set_container_facts_if_unset(facts)
  955. return dict(openshift=facts)
  956. def get_defaults(self, roles):
  957. """ Get default fact values
  958. Args:
  959. roles (list): list of roles for this host
  960. Returns:
  961. dict: The generated default facts
  962. """
  963. defaults = dict()
  964. ip_addr = self.system_facts['default_ipv4']['address']
  965. exit_code, output, _ = module.run_command(['hostname', '-f'])
  966. hostname_f = output.strip() if exit_code == 0 else ''
  967. hostname_values = [hostname_f, self.system_facts['nodename'],
  968. self.system_facts['fqdn']]
  969. hostname = choose_hostname(hostname_values, ip_addr)
  970. common = dict(use_openshift_sdn=True, ip=ip_addr, public_ip=ip_addr,
  971. deployment_type='origin', hostname=hostname,
  972. public_hostname=hostname)
  973. common['client_binary'] = 'oc'
  974. common['admin_binary'] = 'oadm'
  975. common['dns_domain'] = 'cluster.local'
  976. common['install_examples'] = True
  977. defaults['common'] = common
  978. if 'master' in roles:
  979. master = dict(api_use_ssl=True, api_port='8443',
  980. console_use_ssl=True, console_path='/console',
  981. console_port='8443', etcd_use_ssl=True, etcd_hosts='',
  982. etcd_port='4001', portal_net='172.30.0.0/16',
  983. embedded_etcd=True, embedded_kube=True,
  984. embedded_dns=True, dns_port='53',
  985. bind_addr='0.0.0.0', session_max_seconds=3600,
  986. session_name='ssn', session_secrets_file='',
  987. access_token_max_seconds=86400,
  988. auth_token_max_seconds=500,
  989. oauth_grant_method='auto')
  990. defaults['master'] = master
  991. if 'node' in roles:
  992. node = dict(labels={}, annotations={}, portal_net='172.30.0.0/16',
  993. iptables_sync_period='5s', set_node_ip=False)
  994. defaults['node'] = node
  995. if 'nfs' in roles:
  996. nfs = dict(exports_dir='/var/export', registry_volume='regvol',
  997. export_options='*(rw,sync,all_squash)')
  998. defaults['nfs'] = nfs
  999. return defaults
  1000. def guess_host_provider(self):
  1001. """ Guess the host provider
  1002. Returns:
  1003. dict: The generated default facts for the detected provider
  1004. """
  1005. # TODO: cloud provider facts should probably be submitted upstream
  1006. product_name = self.system_facts['product_name']
  1007. product_version = self.system_facts['product_version']
  1008. virt_type = self.system_facts['virtualization_type']
  1009. virt_role = self.system_facts['virtualization_role']
  1010. provider = None
  1011. metadata = None
  1012. # TODO: this is not exposed through module_utils/facts.py in ansible,
  1013. # need to create PR for ansible to expose it
  1014. bios_vendor = get_file_content(
  1015. '/sys/devices/virtual/dmi/id/bios_vendor'
  1016. )
  1017. if bios_vendor == 'Google':
  1018. provider = 'gce'
  1019. metadata_url = ('http://metadata.google.internal/'
  1020. 'computeMetadata/v1/?recursive=true')
  1021. headers = {'Metadata-Flavor': 'Google'}
  1022. metadata = get_provider_metadata(metadata_url, True, headers,
  1023. True)
  1024. # Filter sshKeys and serviceAccounts from gce metadata
  1025. if metadata:
  1026. metadata['project']['attributes'].pop('sshKeys', None)
  1027. metadata['instance'].pop('serviceAccounts', None)
  1028. elif (virt_type == 'xen' and virt_role == 'guest'
  1029. and re.match(r'.*\.amazon$', product_version)):
  1030. provider = 'ec2'
  1031. metadata_url = 'http://169.254.169.254/latest/meta-data/'
  1032. metadata = get_provider_metadata(metadata_url)
  1033. elif re.search(r'OpenStack', product_name):
  1034. provider = 'openstack'
  1035. metadata_url = ('http://169.254.169.254/openstack/latest/'
  1036. 'meta_data.json')
  1037. metadata = get_provider_metadata(metadata_url, True, None,
  1038. True)
  1039. if metadata:
  1040. ec2_compat_url = 'http://169.254.169.254/latest/meta-data/'
  1041. metadata['ec2_compat'] = get_provider_metadata(
  1042. ec2_compat_url
  1043. )
  1044. # disable pylint maybe-no-member because overloaded use of
  1045. # the module name causes pylint to not detect that results
  1046. # is an array or hash
  1047. # pylint: disable=maybe-no-member
  1048. # Filter public_keys and random_seed from openstack metadata
  1049. metadata.pop('public_keys', None)
  1050. metadata.pop('random_seed', None)
  1051. if not metadata['ec2_compat']:
  1052. metadata = None
  1053. return dict(name=provider, metadata=metadata)
  1054. def init_provider_facts(self):
  1055. """ Initialize the provider facts
  1056. Returns:
  1057. dict: The normalized provider facts
  1058. """
  1059. provider_info = self.guess_host_provider()
  1060. provider_facts = normalize_provider_facts(
  1061. provider_info.get('name'),
  1062. provider_info.get('metadata')
  1063. )
  1064. return provider_facts
  1065. def init_local_facts(self, facts=None, additive_facts_to_overwrite=False):
  1066. """ Initialize the provider facts
  1067. Args:
  1068. facts (dict): local facts to set
  1069. additive_facts_to_overwrite (list): additive facts to overwrite in jinja
  1070. '.' notation ex: ['master.named_certificates']
  1071. Returns:
  1072. dict: The result of merging the provided facts with existing
  1073. local facts
  1074. """
  1075. changed = False
  1076. facts_to_set = {self.role: dict()}
  1077. if facts is not None:
  1078. facts_to_set[self.role] = facts
  1079. local_facts = get_local_facts_from_file(self.filename)
  1080. for arg in ['labels', 'annotations']:
  1081. if arg in facts_to_set and isinstance(facts_to_set[arg],
  1082. basestring):
  1083. facts_to_set[arg] = module.from_json(facts_to_set[arg])
  1084. new_local_facts = merge_facts(local_facts, facts_to_set, additive_facts_to_overwrite)
  1085. for facts in new_local_facts.values():
  1086. keys_to_delete = []
  1087. for fact, value in facts.iteritems():
  1088. if value == "" or value is None:
  1089. keys_to_delete.append(fact)
  1090. for key in keys_to_delete:
  1091. del facts[key]
  1092. if new_local_facts != local_facts:
  1093. self.validate_local_facts(new_local_facts)
  1094. changed = True
  1095. if not module.check_mode:
  1096. save_local_facts(self.filename, new_local_facts)
  1097. self.changed = changed
  1098. return new_local_facts
  1099. def validate_local_facts(self, facts=None):
  1100. """ Validate local facts
  1101. Args:
  1102. facts (dict): local facts to validate
  1103. """
  1104. invalid_facts = dict()
  1105. invalid_facts = self.validate_master_facts(facts, invalid_facts)
  1106. if invalid_facts:
  1107. msg = 'Invalid facts detected:\n'
  1108. for key in invalid_facts.keys():
  1109. msg += '{0}: {1}\n'.format(key, invalid_facts[key])
  1110. module.fail_json(msg=msg,
  1111. changed=self.changed)
  1112. # disabling pylint errors for line-too-long since we're dealing
  1113. # with best effort reduction of error messages here.
  1114. # disabling errors for too-many-branches since we require checking
  1115. # many conditions.
  1116. # pylint: disable=line-too-long, too-many-branches
  1117. @staticmethod
  1118. def validate_master_facts(facts, invalid_facts):
  1119. """ Validate master facts
  1120. Args:
  1121. facts (dict): local facts to validate
  1122. invalid_facts (dict): collected invalid_facts
  1123. Returns:
  1124. dict: Invalid facts
  1125. """
  1126. if 'master' in facts:
  1127. # openshift.master.session_auth_secrets
  1128. if 'session_auth_secrets' in facts['master']:
  1129. session_auth_secrets = facts['master']['session_auth_secrets']
  1130. if not issubclass(type(session_auth_secrets), list):
  1131. invalid_facts['session_auth_secrets'] = 'Expects session_auth_secrets is a list.'
  1132. elif 'session_encryption_secrets' not in facts['master']:
  1133. invalid_facts['session_auth_secrets'] = ('openshift_master_session_encryption secrets must be set '
  1134. 'if openshift_master_session_auth_secrets is provided.')
  1135. elif len(session_auth_secrets) != len(facts['master']['session_encryption_secrets']):
  1136. invalid_facts['session_auth_secrets'] = ('openshift_master_session_auth_secrets and '
  1137. 'openshift_master_session_encryption_secrets must be '
  1138. 'equal length.')
  1139. else:
  1140. for secret in session_auth_secrets:
  1141. if len(secret) < 32:
  1142. invalid_facts['session_auth_secrets'] = ('Invalid secret in session_auth_secrets. '
  1143. 'Secrets must be at least 32 characters in length.')
  1144. # openshift.master.session_encryption_secrets
  1145. if 'session_encryption_secrets' in facts['master']:
  1146. session_encryption_secrets = facts['master']['session_encryption_secrets']
  1147. if not issubclass(type(session_encryption_secrets), list):
  1148. invalid_facts['session_encryption_secrets'] = 'Expects session_encryption_secrets is a list.'
  1149. elif 'session_auth_secrets' not in facts['master']:
  1150. invalid_facts['session_encryption_secrets'] = ('openshift_master_session_auth_secrets must be '
  1151. 'set if openshift_master_session_encryption_secrets '
  1152. 'is provided.')
  1153. else:
  1154. for secret in session_encryption_secrets:
  1155. if len(secret) not in [16, 24, 32]:
  1156. invalid_facts['session_encryption_secrets'] = ('Invalid secret in session_encryption_secrets. '
  1157. 'Secrets must be 16, 24, or 32 characters in length.')
  1158. return invalid_facts
  1159. def main():
  1160. """ main """
  1161. # disabling pylint errors for global-variable-undefined and invalid-name
  1162. # for 'global module' usage, since it is required to use ansible_facts
  1163. # pylint: disable=global-variable-undefined, invalid-name
  1164. global module
  1165. module = AnsibleModule(
  1166. argument_spec=dict(
  1167. role=dict(default='common', required=False,
  1168. choices=OpenShiftFacts.known_roles),
  1169. local_facts=dict(default=None, type='dict', required=False),
  1170. additive_facts_to_overwrite=dict(default=[], type='list', required=False),
  1171. ),
  1172. supports_check_mode=True,
  1173. add_file_common_args=True,
  1174. )
  1175. role = module.params['role']
  1176. local_facts = module.params['local_facts']
  1177. additive_facts_to_overwrite = module.params['additive_facts_to_overwrite']
  1178. fact_file = '/etc/ansible/facts.d/openshift.fact'
  1179. openshift_facts = OpenShiftFacts(role, fact_file, local_facts, additive_facts_to_overwrite)
  1180. file_params = module.params.copy()
  1181. file_params['path'] = fact_file
  1182. file_args = module.load_file_common_arguments(file_params)
  1183. changed = module.set_fs_attributes_if_different(file_args,
  1184. openshift_facts.changed)
  1185. return module.exit_json(changed=changed,
  1186. ansible_facts=openshift_facts.facts)
  1187. # ignore pylint errors related to the module_utils import
  1188. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import
  1189. # import module snippets
  1190. from ansible.module_utils.basic import *
  1191. from ansible.module_utils.facts import *
  1192. from ansible.module_utils.urls import *
  1193. if __name__ == '__main__':
  1194. main()