OpenStack Identity Authentication Library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

discover.py 58KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  1. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  2. # not use this file except in compliance with the License. You may obtain
  3. # a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  9. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  10. # License for the specific language governing permissions and limitations
  11. # under the License.
  12. """The passive components to version discovery.
  13. The Discover object in discover.py contains functions that can create objects
  14. on your behalf. These functions are not usable from within the keystoneauth1
  15. library because you will get dependency resolution issues.
  16. The Discover object in this file provides the querying components of Discovery.
  17. This includes functions like url_for which allow you to retrieve URLs and the
  18. raw data specified in version discovery responses.
  19. """
  20. import copy
  21. import re
  22. import os_service_types
  23. import six
  24. from six.moves import urllib
  25. from keystoneauth1 import _utils as utils
  26. from keystoneauth1 import exceptions
  27. _LOGGER = utils.get_logger(__name__)
  28. LATEST = float('inf')
  29. _SERVICE_TYPES = os_service_types.ServiceTypes()
  30. def _str_or_latest(val):
  31. """Convert val to a string, handling LATEST => 'latest'.
  32. :param val: An int or the special value LATEST.
  33. :return: A string representation of val. If val was LATEST, the return is
  34. 'latest'.
  35. """
  36. return 'latest' if val == LATEST else str(val)
  37. def _int_or_latest(val):
  38. """Convert val to an int or the special value LATEST.
  39. :param val: An int()-able, or the string 'latest', or the special value
  40. LATEST.
  41. :return: An int, or the special value LATEST
  42. """
  43. return LATEST if val == 'latest' or val == LATEST else int(val)
  44. def get_version_data(session, url, authenticated=None):
  45. """Retrieve raw version data from a url.
  46. The return is a list of dicts of the form::
  47. [{
  48. 'status': 'STABLE',
  49. 'id': 'v2.3',
  50. 'links': [
  51. {
  52. 'href': 'http://network.example.com/v2.3',
  53. 'rel': 'self',
  54. },
  55. {
  56. 'href': 'http://network.example.com/',
  57. 'rel': 'collection',
  58. },
  59. ],
  60. 'min_version': '2.0',
  61. 'max_version': '2.7',
  62. },
  63. ...,
  64. ]
  65. Note:
  66. The maximum microversion may be specified by `max_version` or `version`,
  67. the former superseding the latter.
  68. All `*version` keys are optional.
  69. Other keys and 'links' entries are permitted, but ignored.
  70. :param session: A Session object that can be used for communication.
  71. :type session: keystoneauth1.session.Session
  72. :param string url: Endpoint or discovery URL from which to retrieve data.
  73. :param bool authenticated: Include a token in the discovery call.
  74. (optional) Defaults to None.
  75. :return: A list of dicts containing version information.
  76. :rtype: list(dict)
  77. """
  78. headers = {'Accept': 'application/json'}
  79. resp = session.get(url, headers=headers, authenticated=authenticated)
  80. try:
  81. body_resp = resp.json()
  82. except ValueError:
  83. pass
  84. else:
  85. # In the event of querying a root URL we will get back a list of
  86. # available versions.
  87. try:
  88. return body_resp['versions']['values']
  89. except (KeyError, TypeError):
  90. pass
  91. # Most servers don't have a 'values' element so accept a simple
  92. # versions dict if available.
  93. try:
  94. return body_resp['versions']
  95. except KeyError:
  96. pass
  97. # Otherwise if we query an endpoint like /v2.0 then we will get back
  98. # just the one available version.
  99. try:
  100. return [body_resp['version']]
  101. except KeyError:
  102. pass
  103. err_text = resp.text[:50] + '...' if len(resp.text) > 50 else resp.text
  104. raise exceptions.DiscoveryFailure('Invalid Response - Bad version data '
  105. 'returned: %s' % err_text)
  106. def normalize_version_number(version):
  107. """Turn a version representation into a tuple.
  108. Examples:
  109. The following all produce a return value of (1, 0)::
  110. 1, '1', 'v1', [1], (1,), ['1'], 1.0, '1.0', 'v1.0', (1, 0)
  111. The following all produce a return value of (1, 20, 3)::
  112. 'v1.20.3', '1.20.3', (1, 20, 3), ['1', '20', '3']
  113. The following all produce a return value of (LATEST, LATEST)::
  114. 'latest', 'vlatest', ('latest', 'latest'), (LATEST, LATEST)
  115. The following all produce a return value of (2, LATEST)::
  116. '2.latest', 'v2.latest', (2, LATEST), ('2', 'latest')
  117. :param version: A version specifier in any of the following forms:
  118. String, possibly prefixed with 'v', containing one or more numbers
  119. *or* the string 'latest', separated by periods. Examples: 'v1',
  120. 'v1.2', '1.2.3', '123', 'latest', '1.latest', 'v1.latest'.
  121. Integer. This will be assumed to be the major version, with a minor
  122. version of 0.
  123. Float. The integer part is assumed to be the major version; the
  124. decimal part the minor version.
  125. Non-string iterable comprising integers, integer strings, the string
  126. 'latest', or the special value LATEST.
  127. Examples: (1,), [1, 2], ('12', '34', '56'), (LATEST,), (2, 'latest')
  128. :return: A tuple of len >= 2 comprising integers and/or LATEST.
  129. :raises TypeError: If the input version cannot be interpreted.
  130. """
  131. # Copy the input var so the error presents the original value
  132. ver = version
  133. # If it's a non-string iterable, turn it into a string for subsequent
  134. # processing. This ensures at least 1 decimal point if e.g. [1] is given.
  135. if not isinstance(ver, six.string_types):
  136. try:
  137. ver = '.'.join(map(_str_or_latest, ver))
  138. except TypeError:
  139. # Not an iterable
  140. pass
  141. # If it's a numeric or an integer as a string then normalize it to a
  142. # float string. This ensures 1 decimal point.
  143. # If it's a float as a string, don't do that, the split/map below will do
  144. # what we want. (Otherwise, we wind up with 3.20 -> (3, 2))
  145. if isinstance(ver, six.string_types):
  146. # trim the v from a 'v2.0' or similar
  147. ver = ver.lstrip('v')
  148. try:
  149. # If version is a pure int, like '1' or '200' this will produce
  150. # a stringified version with a .0 added. If it's any other number,
  151. # such as '1.1' - int(version) raises an Exception
  152. ver = str(float(int(ver)))
  153. except ValueError:
  154. pass
  155. # If it's an int or float, turn it into a float string
  156. elif isinstance(ver, (int, float)):
  157. ver = _str_or_latest(float(ver))
  158. # At this point, we should either have a string that contains numbers with
  159. # at least one decimal point, or something decidedly else.
  160. # if it's a string from above break it on .
  161. try:
  162. ver = ver.split('.')
  163. except AttributeError:
  164. # Not a string
  165. pass
  166. # Handle special case variants of just 'latest'
  167. if ver == 'latest' or tuple(ver) == ('latest',):
  168. return LATEST, LATEST
  169. # It's either an interable, or something else that makes us sad.
  170. try:
  171. return tuple(map(_int_or_latest, ver))
  172. except (TypeError, ValueError):
  173. pass
  174. raise TypeError('Invalid version specified: %s' % version)
  175. def _normalize_version_args(
  176. version, min_version, max_version, service_type=None):
  177. # The sins of our fathers become the blood on our hands.
  178. # If a user requests an old-style service type such as volumev2, then they
  179. # are inherently requesting the major API version 2. It's not a good
  180. # interface, but it's the one that was imposed on the world years ago
  181. # because the client libraries all hid the version discovery document.
  182. # In order to be able to ensure that a user who requests volumev2 does not
  183. # get a block-storage endpoint that only provides v3 of the block-storage
  184. # service, we need to pull the version out of the service_type. The
  185. # service-types-authority will prevent the growth of new monstrosities such
  186. # as this, but in order to move forward without breaking people, we have
  187. # to just cry in the corner while striking ourselves with thorned branches.
  188. # That said, for sure only do this hack for officially known service_types.
  189. if (service_type and
  190. _SERVICE_TYPES.is_known(service_type) and
  191. service_type[-1].isdigit() and
  192. service_type[-2] == 'v'):
  193. implied_version = normalize_version_number(service_type[-1])
  194. else:
  195. implied_version = None
  196. if version and (min_version or max_version):
  197. raise ValueError(
  198. "version is mutually exclusive with min_version and max_version")
  199. if version:
  200. # Explode this into min_version and max_version
  201. min_version = normalize_version_number(version)
  202. max_version = (min_version[0], LATEST)
  203. if implied_version:
  204. if min_version[0] != implied_version[0]:
  205. raise exceptions.ImpliedVersionMismatch(
  206. service_type=service_type,
  207. implied=implied_version,
  208. given=version_to_string(version))
  209. return min_version, max_version
  210. if min_version == 'latest':
  211. if max_version not in (None, 'latest'):
  212. raise ValueError(
  213. "min_version is 'latest' and max_version is {max_version}"
  214. " but is only allowed to be 'latest' or None".format(
  215. max_version=max_version))
  216. max_version = 'latest'
  217. # Normalize e.g. empty string to None
  218. min_version = min_version or None
  219. max_version = max_version or None
  220. if min_version:
  221. min_version = normalize_version_number(min_version)
  222. # If min_version was specified but max_version was not, max is latest.
  223. max_version = normalize_version_number(max_version or 'latest')
  224. # NOTE(efried): We should be doing this instead:
  225. # max_version = normalize_version_number(max_version or 'latest')
  226. # However, see first NOTE(jamielennox) in EndpointData._set_version_info.
  227. if max_version:
  228. max_version = normalize_version_number(max_version)
  229. if None not in (min_version, max_version) and max_version < min_version:
  230. raise ValueError("min_version cannot be greater than max_version")
  231. if implied_version:
  232. if min_version:
  233. if min_version[0] != implied_version[0]:
  234. raise exceptions.ImpliedMinVersionMismatch(
  235. service_type=service_type,
  236. implied=implied_version,
  237. given=version_to_string(min_version))
  238. else:
  239. min_version = implied_version
  240. # If 'latest' is provided with a versioned service-type like
  241. # volumev2 - the user wants the latest of volumev2, not the latest
  242. # of block-storage.
  243. if max_version and max_version[0] != LATEST:
  244. if max_version[0] != implied_version[0]:
  245. raise exceptions.ImpliedMaxVersionMismatch(
  246. service_type=service_type,
  247. implied=implied_version,
  248. given=version_to_string(max_version))
  249. else:
  250. max_version = (implied_version[0], LATEST)
  251. return min_version, max_version
  252. def version_to_string(version):
  253. """Turn a version tuple into a string.
  254. :param tuple version: A version represented as a tuple of ints. As a
  255. special case, a tuple member may be LATEST, which
  256. translates to 'latest'.
  257. :return: A version represented as a period-delimited string.
  258. """
  259. # Special case
  260. if all(ver == LATEST for ver in version):
  261. return 'latest'
  262. return ".".join(map(_str_or_latest, version))
  263. def _version_between(min_version, max_version, candidate):
  264. """Determine whether a candidate version is within a specified range.
  265. :param min_version: The minimum version that is acceptable.
  266. None/empty indicates no lower bound.
  267. :param max_version: The maximum version that is acceptable.
  268. None/empty indicates no upper bound.
  269. :param candidate: Candidate version to test. May not be None/empty.
  270. :return: True if candidate is between min_version and max_version; False
  271. otherwise.
  272. :raises ValueError: If candidate is None.
  273. :raises TypeError: If any input cannot be normalized.
  274. """
  275. if not candidate:
  276. raise ValueError("candidate is required.")
  277. candidate = normalize_version_number(candidate)
  278. # Normalize up front to validate any malformed inputs
  279. if min_version:
  280. min_version = normalize_version_number(min_version)
  281. if max_version:
  282. max_version = normalize_version_number(max_version)
  283. # If the candidate is less than the min_version, it's not a match.
  284. # No min_version means no lower bound.
  285. if min_version and candidate < min_version:
  286. return False
  287. # If the candidate is higher than the max_version, it's not a match.
  288. # No max_version means no upper bound.
  289. if max_version and candidate > max_version:
  290. return False
  291. return True
  292. def version_match(required, candidate):
  293. """Test that an available version satisfies the required version.
  294. To be suitable a version must be of the same major version as required
  295. and be at least a match in minor/patch level.
  296. eg. 3.3 is a match for a required 3.1 but 4.1 is not.
  297. :param tuple required: the version that must be met.
  298. :param tuple candidate: the version to test against required.
  299. :returns: True if candidate is suitable False otherwise.
  300. :rtype: bool
  301. """
  302. # major versions must be the same (e.g. even though v2 is a lower
  303. # version than v3 we can't use it if v2 was requested)
  304. if candidate[0] != required[0]:
  305. return False
  306. # prevent selecting a minor version less than what is required
  307. if candidate < required:
  308. return False
  309. return True
  310. def _latest_soft_match(required, candidate):
  311. if not required:
  312. return False
  313. if LATEST not in required:
  314. return False
  315. if all(part == LATEST for part in required):
  316. return True
  317. if required[0] == candidate[0] and required[1] == LATEST:
  318. return True
  319. # TODO(efried): Do we need to handle >2-part version numbers here?
  320. return False
  321. def _combine_relative_url(discovery_url, version_url):
  322. # NOTE(jamielennox): urllib.parse.urljoin allows the url to be relative
  323. # or even protocol-less. The additional trailing '/' makes urljoin respect
  324. # the current path as canonical even if the url doesn't include it. for
  325. # example a "v2" path from http://host/admin should resolve as
  326. # http://host/admin/v2 where it would otherwise be host/v2. This has no
  327. # effect on absolute urls.
  328. url = urllib.parse.urljoin(discovery_url.rstrip('/') + '/', version_url)
  329. # Sadly version discovery documents are common with the scheme
  330. # and netloc broken.
  331. parsed_version_url = urllib.parse.urlparse(url)
  332. parsed_discovery_url = urllib.parse.urlparse(discovery_url)
  333. return urllib.parse.ParseResult(
  334. parsed_discovery_url.scheme,
  335. parsed_discovery_url.netloc,
  336. parsed_version_url.path,
  337. parsed_version_url.params,
  338. parsed_version_url.query,
  339. parsed_version_url.fragment).geturl()
  340. def _version_from_url(url):
  341. if not url:
  342. return url
  343. url = urllib.parse.urlparse(url)
  344. for part in reversed(url.path.split('/')):
  345. try:
  346. return normalize_version_number(part)
  347. except Exception:
  348. pass
  349. return None
  350. class Status(object):
  351. CURRENT = 'CURRENT'
  352. SUPPORTED = 'SUPPORTED'
  353. DEPRECATED = 'DEPRECATED'
  354. EXPERIMENTAL = 'EXPERIMENTAL'
  355. UNKNOWN = 'UNKNOWN'
  356. KNOWN = (CURRENT, SUPPORTED, DEPRECATED, EXPERIMENTAL)
  357. @classmethod
  358. def normalize(cls, raw_status):
  359. """Turn a status into a canonical status value.
  360. If the status from the version discovery document does not match one
  361. of the known values, it will be set to 'UNKNOWN'.
  362. :param str raw_status: Status value from a discovery document.
  363. :returns: A canonicalized version of the status. Valid values
  364. are CURRENT, SUPPORTED, DEPRECATED, EXPERIMENTAL and UNKNOWN
  365. :rtype: str
  366. """
  367. status = raw_status.upper()
  368. if status == 'STABLE':
  369. status = 'CURRENT'
  370. if status not in cls.KNOWN:
  371. status = cls.UNKNOWN
  372. return status
  373. class Discover(object):
  374. CURRENT_STATUSES = ('stable', 'current', 'supported')
  375. DEPRECATED_STATUSES = ('deprecated',)
  376. EXPERIMENTAL_STATUSES = ('experimental',)
  377. def __init__(self, session, url, authenticated=None):
  378. self._url = url
  379. self._data = get_version_data(session, url,
  380. authenticated=authenticated)
  381. def raw_version_data(self, allow_experimental=False,
  382. allow_deprecated=True, allow_unknown=False):
  383. """Get raw version information from URL.
  384. Raw data indicates that only minimal validation processing is performed
  385. on the data, so what is returned here will be the data in the same
  386. format it was received from the endpoint.
  387. :param bool allow_experimental: Allow experimental version endpoints.
  388. :param bool allow_deprecated: Allow deprecated version endpoints.
  389. :param bool allow_unknown: Allow endpoints with an unrecognised status.
  390. :returns: The endpoints returned from the server that match the
  391. criteria.
  392. :rtype: list
  393. """
  394. versions = []
  395. for v in self._data:
  396. try:
  397. status = v['status']
  398. except KeyError:
  399. _LOGGER.warning('Skipping over invalid version data. '
  400. 'No stability status in version.')
  401. continue
  402. status = status.lower()
  403. if status in self.CURRENT_STATUSES:
  404. versions.append(v)
  405. elif status in self.DEPRECATED_STATUSES:
  406. if allow_deprecated:
  407. versions.append(v)
  408. elif status in self.EXPERIMENTAL_STATUSES:
  409. if allow_experimental:
  410. versions.append(v)
  411. elif allow_unknown:
  412. versions.append(v)
  413. return versions
  414. def version_data(self, reverse=False, **kwargs):
  415. """Get normalized version data.
  416. Return version data in a structured way.
  417. :param bool reverse: Reverse the list. reverse=true will mean the
  418. returned list is sorted from newest to oldest
  419. version.
  420. :returns: A list of :class:`VersionData` sorted by version number.
  421. :rtype: list(VersionData)
  422. """
  423. data = self.raw_version_data(**kwargs)
  424. versions = []
  425. for v in data:
  426. try:
  427. version_str = v['id']
  428. except KeyError:
  429. _LOGGER.info('Skipping invalid version data. Missing ID.')
  430. continue
  431. try:
  432. links = v['links']
  433. except KeyError:
  434. _LOGGER.info('Skipping invalid version data. Missing links')
  435. continue
  436. version_number = normalize_version_number(version_str)
  437. # collect microversion information
  438. # NOTE(efried): Some existing discovery documents (e.g. from nova
  439. # v2.0 in the pike release) include *version keys with "" (empty
  440. # string) values, expecting them to be treated the same as if the
  441. # keys were absent.
  442. min_microversion = v.get('min_version') or None
  443. if min_microversion:
  444. min_microversion = normalize_version_number(min_microversion)
  445. max_microversion = v.get('max_version')
  446. if not max_microversion:
  447. max_microversion = v.get('version') or None
  448. if max_microversion:
  449. max_microversion = normalize_version_number(max_microversion)
  450. next_min_version = v.get('next_min_version') or None
  451. if next_min_version:
  452. next_min_version = normalize_version_number(next_min_version)
  453. not_before = v.get('not_before') or None
  454. self_url = None
  455. collection_url = None
  456. for link in links:
  457. try:
  458. rel = link['rel']
  459. url = _combine_relative_url(self._url, link['href'])
  460. except (KeyError, TypeError):
  461. _LOGGER.info('Skipping invalid version link. '
  462. 'Missing link URL or relationship.')
  463. continue
  464. if rel.lower() == 'self':
  465. self_url = url
  466. elif rel.lower() == 'collection':
  467. collection_url = url
  468. if not self_url:
  469. _LOGGER.info('Skipping invalid version data. '
  470. 'Missing link to endpoint.')
  471. continue
  472. versions.append(
  473. VersionData(version=version_number,
  474. url=self_url,
  475. collection=collection_url,
  476. min_microversion=min_microversion,
  477. max_microversion=max_microversion,
  478. next_min_version=next_min_version,
  479. not_before=not_before,
  480. status=Status.normalize(v['status']),
  481. raw_status=v['status']))
  482. versions.sort(key=lambda v: v['version'], reverse=reverse)
  483. return versions
  484. def version_string_data(self, reverse=False, **kwargs):
  485. """Get normalized version data with versions as strings.
  486. Return version data in a structured way.
  487. :param bool reverse: Reverse the list. reverse=true will mean the
  488. returned list is sorted from newest to oldest
  489. version.
  490. :returns: A list of :class:`VersionData` sorted by version number.
  491. :rtype: list(VersionData)
  492. """
  493. version_data = self.version_data(reverse=reverse, **kwargs)
  494. for version in version_data:
  495. for key in ('version', 'min_microversion', 'max_microversion'):
  496. if version[key]:
  497. version[key] = version_to_string(version[key])
  498. return version_data
  499. def data_for(self, version, **kwargs):
  500. """Return endpoint data for a version.
  501. NOTE: This method raises a TypeError if version is None. It is
  502. kept for backwards compatability. New code should use
  503. versioned_data_for instead.
  504. :param tuple version: The version is always a minimum version in the
  505. same major release as there should be no compatibility issues with
  506. using a version newer than the one asked for.
  507. :returns: the endpoint data for a URL that matches the required version
  508. (the format is described in version_data) or None if no
  509. match.
  510. :rtype: dict
  511. """
  512. version = normalize_version_number(version)
  513. for data in self.version_data(reverse=True, **kwargs):
  514. # Since the data is reversed, the latest version is first. If
  515. # latest was requested, return it.
  516. if _latest_soft_match(version, data['version']):
  517. return data
  518. if version_match(version, data['version']):
  519. return data
  520. return None
  521. def url_for(self, version, **kwargs):
  522. """Get the endpoint url for a version.
  523. NOTE: This method raises a TypeError if version is None. It is
  524. kept for backwards compatability. New code should use
  525. versioned_url_for instead.
  526. :param tuple version: The version is always a minimum version in the
  527. same major release as there should be no compatibility issues with
  528. using a version newer than the one asked for.
  529. :returns: The url for the specified version or None if no match.
  530. :rtype: str
  531. """
  532. data = self.data_for(version, **kwargs)
  533. return data['url'] if data else None
  534. def versioned_data_for(self, url=None,
  535. min_version=None, max_version=None,
  536. **kwargs):
  537. """Return endpoint data for the service at a url.
  538. min_version and max_version can be given either as strings or tuples.
  539. :param string url: If url is given, the data will be returned for the
  540. endpoint data that has a self link matching the url.
  541. :param min_version: The minimum endpoint version that is acceptable. If
  542. min_version is given with no max_version it is as if max version is
  543. 'latest'. If min_version is 'latest', max_version may only be
  544. 'latest' or None.
  545. :param max_version: The maximum endpoint version that is acceptable. If
  546. min_version is given with no max_version it is as if max version is
  547. 'latest'. If min_version is 'latest', max_version may only be
  548. 'latest' or None.
  549. :returns: the endpoint data for a URL that matches the required version
  550. (the format is described in version_data) or None if no
  551. match.
  552. :rtype: dict
  553. """
  554. min_version, max_version = _normalize_version_args(
  555. None, min_version, max_version)
  556. no_version = not max_version and not min_version
  557. version_data = self.version_data(reverse=True, **kwargs)
  558. # If we don't have to check a min_version, we can short
  559. # circuit anything else
  560. if (max_version == (LATEST, LATEST) and
  561. (not min_version or min_version == (LATEST, LATEST))):
  562. # because we reverse we can just take the first entry
  563. return version_data[0]
  564. if url:
  565. url = url.rstrip('/') + '/'
  566. if no_version and not url:
  567. # because we reverse we can just take the first entry
  568. return version_data[0]
  569. # Version data is in order from highest to lowest, so we return
  570. # the first matching entry
  571. for data in version_data:
  572. if url and data['url'] and data['url'].rstrip('/') + '/' == url:
  573. return data
  574. if _latest_soft_match(min_version, data['version']):
  575. return data
  576. # Only validate version bounds if versions were specified
  577. if min_version and max_version and _version_between(
  578. min_version, max_version, data['version']):
  579. return data
  580. # If there is no version requested and we could not find a matching
  581. # url in the discovery doc, that means we've got an unversioned
  582. # endpoint in the catalog and the user is requesting version data
  583. # so that they know what version they got. We can return the first
  584. # entry from version_data, because the user hasn't requested anything
  585. # different.
  586. if no_version and url:
  587. return version_data[0]
  588. # We couldn't find a match.
  589. return None
  590. def versioned_url_for(self, min_version=None, max_version=None, **kwargs):
  591. """Get the endpoint url for a version.
  592. min_version and max_version can be given either as strings or tuples.
  593. :param min_version: The minimum version that is acceptable. If
  594. min_version is given with no max_version it is as if max version
  595. is 'latest'.
  596. :param max_version: The maximum version that is acceptable. If
  597. min_version is given with no max_version it is as if max version is
  598. 'latest'.
  599. :returns: The url for the specified version or None if no match.
  600. :rtype: str
  601. """
  602. data = self.versioned_data_for(min_version=min_version,
  603. max_version=max_version, **kwargs)
  604. return data['url'] if data else None
  605. class VersionData(dict):
  606. """Normalized Version Data about an endpoint."""
  607. def __init__(
  608. self,
  609. version,
  610. url,
  611. collection=None,
  612. max_microversion=None,
  613. min_microversion=None,
  614. next_min_version=None,
  615. not_before=None,
  616. status='CURRENT',
  617. raw_status=None):
  618. super(VersionData, self).__init__()
  619. self['version'] = version
  620. self['url'] = url
  621. self['collection'] = collection
  622. self['max_microversion'] = max_microversion
  623. self['min_microversion'] = min_microversion
  624. self['next_min_version'] = next_min_version
  625. self['not_before'] = not_before
  626. self['status'] = status
  627. self['raw_status'] = raw_status
  628. @property
  629. def version(self):
  630. """The normalized version of the endpoint."""
  631. return self.get('version')
  632. @property
  633. def url(self):
  634. """The url for the endpoint."""
  635. return self.get('url')
  636. @property
  637. def collection(self):
  638. """The URL for the discovery document.
  639. May be None.
  640. """
  641. return self.get('collection')
  642. @property
  643. def min_microversion(self):
  644. """The minimum microversion supported by the endpoint.
  645. May be None.
  646. """
  647. return self.get('min_microversion')
  648. @property
  649. def max_microversion(self):
  650. """The maximum microversion supported by the endpoint.
  651. May be None.
  652. """
  653. return self.get('max_microversion')
  654. @property
  655. def status(self):
  656. """A canonicalized version of the status.
  657. Valid values are CURRENT, SUPPORTED, DEPRECATED and EXPERIMENTAL.
  658. """
  659. return self.get('status')
  660. @property
  661. def raw_status(self):
  662. """The status as provided by the server."""
  663. return self.get('raw_status')
  664. class EndpointData(object):
  665. """Normalized information about a discovered endpoint.
  666. Contains url, version, microversion, interface and region information.
  667. This is essentially the data contained in the catalog and the version
  668. discovery documents about an endpoint that is used to select the endpoint
  669. desired by the user. It is returned so that a user can know which qualities
  670. a discovered endpoint had, in case their request allowed for a range of
  671. possibilities.
  672. """
  673. def __init__(self,
  674. catalog_url=None,
  675. service_url=None,
  676. service_type=None,
  677. service_name=None,
  678. service_id=None,
  679. region_name=None,
  680. interface=None,
  681. endpoint_id=None,
  682. raw_endpoint=None,
  683. api_version=None,
  684. major_version=None,
  685. min_microversion=None,
  686. max_microversion=None,
  687. next_min_version=None,
  688. not_before=None,
  689. status=None):
  690. self.catalog_url = catalog_url
  691. self.service_url = service_url
  692. self.service_type = service_type
  693. self.service_name = service_name
  694. self.service_id = service_id
  695. self.interface = interface
  696. self.region_name = region_name
  697. self.endpoint_id = endpoint_id
  698. self.raw_endpoint = raw_endpoint
  699. self.major_version = major_version
  700. self.min_microversion = min_microversion
  701. self.max_microversion = max_microversion
  702. self.next_min_version = next_min_version
  703. self.not_before = not_before
  704. self.status = status
  705. self._saved_project_id = None
  706. self._catalog_matches_version = False
  707. self._catalog_matches_exactly = False
  708. self._disc = None
  709. self.api_version = api_version or _version_from_url(self.url)
  710. def __copy__(self):
  711. """Return a new EndpointData based on this one."""
  712. new_data = EndpointData(
  713. catalog_url=self.catalog_url,
  714. service_url=self.service_url,
  715. service_type=self.service_type,
  716. service_name=self.service_name,
  717. service_id=self.service_id,
  718. region_name=self.region_name,
  719. interface=self.interface,
  720. endpoint_id=self.endpoint_id,
  721. raw_endpoint=self.raw_endpoint,
  722. api_version=self.api_version,
  723. major_version=self.major_version,
  724. min_microversion=self.min_microversion,
  725. max_microversion=self.max_microversion,
  726. next_min_version=self.next_min_version,
  727. not_before=self.not_before,
  728. status=self.status,
  729. )
  730. # Save cached discovery object - but we don't want to
  731. # actually provide a constructor argument
  732. new_data._disc = self._disc
  733. new_data._saved_project_id = self._saved_project_id
  734. return new_data
  735. def __str__(self):
  736. """Produce a string like EndpointData{key=val, ...}, for debugging."""
  737. str_attrs = (
  738. 'api_version', 'catalog_url', 'endpoint_id', 'interface',
  739. 'major_version', 'max_microversion', 'min_microversion',
  740. 'next_min_version', 'not_before', 'raw_endpoint', 'region_name',
  741. 'service_id', 'service_name', 'service_type', 'service_url', 'url')
  742. return "%s{%s}" % (self.__class__.__name__, ', '.join(
  743. ["%s=%s" % (attr, getattr(self, attr)) for attr in str_attrs]))
  744. @property
  745. def url(self):
  746. return self.service_url or self.catalog_url
  747. def get_current_versioned_data(self, session, allow=None, cache=None,
  748. project_id=None):
  749. """Run version discovery on the current endpoint.
  750. A simplified version of get_versioned_data, get_current_versioned_data
  751. runs discovery but only on the endpoint that has been found already.
  752. It can be useful in some workflows where the user wants version
  753. information about the endpoint they have.
  754. :param session: A session object that can be used for communication.
  755. :type session: keystoneauth1.session.Session
  756. :param dict allow: Extra filters to pass when discovering API
  757. versions. (optional)
  758. :param dict cache: A dict to be used for caching results in
  759. addition to caching them on the Session.
  760. (optional)
  761. :param string project_id: ID of the currently scoped project. Used for
  762. removing project_id components of URLs from
  763. the catalog. (optional)
  764. :returns: A new EndpointData with the requested versioned data.
  765. :rtype: :py:class:`keystoneauth1.discover.EndpointData`
  766. :raises keystoneauth1.exceptions.discovery.DiscoveryFailure: If the
  767. appropriate versioned data
  768. could not be discovered.
  769. """
  770. min_version, max_version = _normalize_version_args(
  771. self.api_version, None, None)
  772. return self.get_versioned_data(
  773. session=session, allow=allow, cache=cache, allow_version_hack=True,
  774. discover_versions=True,
  775. min_version=min_version, max_version=max_version)
  776. def get_versioned_data(self, session, allow=None, cache=None,
  777. allow_version_hack=True, project_id=None,
  778. discover_versions=True,
  779. min_version=None, max_version=None):
  780. """Run version discovery for the service described.
  781. Performs Version Discovery and returns a new EndpointData object with
  782. information found.
  783. min_version and max_version can be given either as strings or tuples.
  784. :param session: A session object that can be used for communication.
  785. :type session: keystoneauth1.session.Session
  786. :param dict allow: Extra filters to pass when discovering API
  787. versions. (optional)
  788. :param dict cache: A dict to be used for caching results in
  789. addition to caching them on the Session.
  790. (optional)
  791. :param bool allow_version_hack: Allow keystoneauth to hack up catalog
  792. URLS to support older schemes.
  793. (optional, default True)
  794. :param string project_id: ID of the currently scoped project. Used for
  795. removing project_id components of URLs from
  796. the catalog. (optional)
  797. :param bool discover_versions: Whether to get version metadata from
  798. the version discovery document even
  799. if it's not neccessary to fulfill the
  800. major version request. (optional,
  801. defaults to True)
  802. :param min_version: The minimum version that is acceptable. If
  803. min_version is given with no max_version it is as
  804. if max version is 'latest'.
  805. :param max_version: The maximum version that is acceptable. If
  806. min_version is given with no max_version it is as
  807. if max version is 'latest'.
  808. :returns: A new EndpointData with the requested versioned data.
  809. :rtype: :py:class:`keystoneauth1.discover.EndpointData`
  810. :raises keystoneauth1.exceptions.discovery.DiscoveryFailure: If the
  811. appropriate versioned data
  812. could not be discovered.
  813. """
  814. min_version, max_version = _normalize_version_args(
  815. None, min_version, max_version)
  816. if not allow:
  817. allow = {}
  818. # This method should always return a new EndpointData
  819. new_data = copy.copy(self)
  820. new_data._set_version_info(
  821. session=session, allow=allow, cache=cache,
  822. allow_version_hack=allow_version_hack, project_id=project_id,
  823. discover_versions=discover_versions, min_version=min_version,
  824. max_version=max_version)
  825. return new_data
  826. def get_all_version_string_data(self, session, project_id=None):
  827. """Return version data for all versions discovery can find.
  828. :param string project_id: ID of the currently scoped project. Used for
  829. removing project_id components of URLs from
  830. the catalog. (optional)
  831. :returns: A list of :class:`VersionData` sorted by version number.
  832. :rtype: list(VersionData)
  833. """
  834. versions = []
  835. for vers_url in self._get_discovery_url_choices(project_id=project_id):
  836. try:
  837. d = get_discovery(session, vers_url)
  838. except Exception as e:
  839. # Ignore errors here - we're just searching for one of the
  840. # URLs that will give us data.
  841. _LOGGER.debug(
  842. "Failed attempt at discovery on %s: %s", vers_url, str(e))
  843. continue
  844. for version in d.version_string_data():
  845. versions.append(version)
  846. break
  847. return versions or self._infer_version_data(project_id)
  848. def _infer_version_data(self, project_id=None):
  849. """Return version data dict for when discovery fails.
  850. :param string project_id: ID of the currently scoped project. Used for
  851. removing project_id components of URLs from
  852. the catalog. (optional)
  853. :returns: A list of :class:`VersionData` sorted by version number.
  854. :rtype: list(VersionData)
  855. """
  856. version = self.api_version
  857. if version:
  858. version = version_to_string(self.api_version)
  859. url = self.url.rstrip("/")
  860. if project_id and url.endswith(project_id):
  861. url, _ = self.url.rsplit('/', 1)
  862. url += "/"
  863. return [VersionData(url=url, version=version)]
  864. def _set_version_info(self, session, allow=None, cache=None,
  865. allow_version_hack=True, project_id=None,
  866. discover_versions=False,
  867. min_version=None, max_version=None):
  868. match_url = None
  869. no_version = not max_version and not min_version
  870. if no_version and not discover_versions:
  871. # NOTE(jamielennox): This may not be the best thing to default to
  872. # but is here for backwards compatibility. It may be worth
  873. # defaulting to the most recent version.
  874. return
  875. elif no_version and discover_versions:
  876. # We want to run discovery, but we don't want to find different
  877. # endpoints than what's in the catalog
  878. allow_version_hack = False
  879. match_url = self.url
  880. if project_id:
  881. self.project_id = project_id
  882. discovered_data = None
  883. # Maybe we've run discovery in the past and have a document that can
  884. # satisfy the request without further work
  885. if self._disc:
  886. discovered_data = self._disc.versioned_data_for(
  887. min_version=min_version, max_version=max_version,
  888. url=match_url, **allow)
  889. if not discovered_data:
  890. self._run_discovery(
  891. session=session, cache=cache,
  892. min_version=min_version, max_version=max_version,
  893. project_id=project_id, allow_version_hack=allow_version_hack,
  894. discover_versions=discover_versions)
  895. if not self._disc:
  896. return
  897. discovered_data = self._disc.versioned_data_for(
  898. min_version=min_version, max_version=max_version,
  899. url=match_url, **allow)
  900. if not discovered_data:
  901. if min_version and not max_version:
  902. raise exceptions.DiscoveryFailure(
  903. "Minimum version {min_version} was not found".format(
  904. min_version=version_to_string(min_version)))
  905. elif max_version and not min_version:
  906. raise exceptions.DiscoveryFailure(
  907. "Maximum version {max_version} was not found".format(
  908. max_version=version_to_string(max_version)))
  909. elif min_version and max_version:
  910. raise exceptions.DiscoveryFailure(
  911. "No version found between {min_version}"
  912. " and {max_version}".format(
  913. min_version=version_to_string(min_version),
  914. max_version=version_to_string(max_version)))
  915. self.min_microversion = discovered_data['min_microversion']
  916. self.max_microversion = discovered_data['max_microversion']
  917. self.next_min_version = discovered_data['next_min_version']
  918. self.not_before = discovered_data['not_before']
  919. self.api_version = discovered_data['version']
  920. self.status = discovered_data['status']
  921. # TODO(mordred): these next two things should be done by Discover
  922. # in versioned_data_for.
  923. discovered_url = discovered_data['url']
  924. # NOTE(jamielennox): urljoin allows the url to be relative or even
  925. # protocol-less. The additional trailing '/' make urljoin respect
  926. # the current path as canonical even if the url doesn't include it.
  927. # for example a "v2" path from http://host/admin should resolve as
  928. # http://host/admin/v2 where it would otherwise be host/v2.
  929. # This has no effect on absolute urls returned from url_for.
  930. url = urllib.parse.urljoin(self._disc._url.rstrip('/') + '/',
  931. discovered_url)
  932. # If we had to pop a project_id from the catalog_url, put it back on
  933. if self._saved_project_id:
  934. url = urllib.parse.urljoin(url.rstrip('/') + '/',
  935. self._saved_project_id)
  936. self.service_url = url
  937. def _run_discovery(self, session, cache, min_version, max_version,
  938. project_id, allow_version_hack, discover_versions):
  939. tried = set()
  940. for vers_url in self._get_discovery_url_choices(
  941. project_id=project_id,
  942. allow_version_hack=allow_version_hack,
  943. min_version=min_version,
  944. max_version=max_version):
  945. if self._catalog_matches_exactly and not discover_versions:
  946. # The version we started with is correct, and we don't want
  947. # new data
  948. return
  949. if vers_url in tried:
  950. continue
  951. tried.add(vers_url)
  952. try:
  953. self._disc = get_discovery(
  954. session, vers_url,
  955. cache=cache,
  956. authenticated=False)
  957. break
  958. except (exceptions.DiscoveryFailure,
  959. exceptions.HttpError,
  960. exceptions.ConnectionError):
  961. continue
  962. if not self._disc:
  963. # We couldn't find a version discovery document anywhere.
  964. if self._catalog_matches_version:
  965. # But - the version in the catalog is fine.
  966. self.service_url = self.catalog_url
  967. return
  968. # NOTE(jamielennox): The logic here is required for backwards
  969. # compatibility. By itself it is not ideal.
  970. if allow_version_hack:
  971. # NOTE(jamielennox): If we can't contact the server we
  972. # fall back to just returning the URL from the catalog. This
  973. # is backwards compatible behaviour and used when there is no
  974. # other choice. Realistically if you have provided a version
  975. # you should be able to rely on that version being returned or
  976. # the request failing.
  977. _LOGGER.warning(
  978. 'Failed to contact the endpoint at %s for '
  979. 'discovery. Fallback to using that endpoint as '
  980. 'the base url.', self.url)
  981. return
  982. else:
  983. # NOTE(jamielennox): If you've said no to allow_version_hack
  984. # and we can't determine the actual URL this is a failure
  985. # because we are specifying that the deployment must be up to
  986. # date enough to properly specify a version and keystoneauth
  987. # can't deliver.
  988. raise exceptions.DiscoveryFailure(
  989. "Version requested but version discovery document was not"
  990. " found and allow_version_hack was False")
  991. def _get_discovery_url_choices(
  992. self, project_id=None, allow_version_hack=True,
  993. min_version=None, max_version=None):
  994. """Find potential locations for version discovery URLs.
  995. min_version and max_version are already normalized, so will either be
  996. None or a tuple.
  997. """
  998. url = urllib.parse.urlparse(self.url.rstrip('/'))
  999. url_parts = url.path.split('/')
  1000. # First, check to see if the catalog url ends with a project id
  1001. # We need to remove it and save it for later if it does
  1002. if project_id and url_parts[-1].endswith(project_id):
  1003. self._saved_project_id = url_parts.pop()
  1004. elif not project_id:
  1005. # Peek to see if -2 is a version. If so, -1 is a project_id,
  1006. # even if we don't know that at this point in the call stack
  1007. try:
  1008. normalize_version_number(url_parts[-2])
  1009. self._saved_project_id = url_parts.pop()
  1010. except (IndexError, TypeError):
  1011. pass
  1012. catalog_discovery = versioned_discovery = None
  1013. # Next, check to see if the url indicates a version and if that
  1014. # version either matches our version request or is within the
  1015. # range requested. If so, we can start by trying the given url
  1016. # as it has a high potential for success.
  1017. try:
  1018. url_version = normalize_version_number(url_parts[-1])
  1019. versioned_discovery = urllib.parse.ParseResult(
  1020. url.scheme,
  1021. url.netloc,
  1022. '/'.join(url_parts),
  1023. url.params,
  1024. url.query,
  1025. url.fragment).geturl()
  1026. except TypeError:
  1027. pass
  1028. else:
  1029. # `is_between` means version bounds were specified *and* the URL
  1030. # version is between them.
  1031. is_between = min_version and max_version and _version_between(
  1032. min_version, max_version, url_version)
  1033. exact_match = (is_between and max_version and
  1034. max_version[0] == url_version[0])
  1035. high_match = (is_between and max_version and
  1036. max_version[1] != LATEST and
  1037. version_match(max_version, url_version))
  1038. if exact_match or is_between:
  1039. self._catalog_matches_version = True
  1040. self._catalog_matches_exactly = exact_match
  1041. # The endpoint from the catalog matches the version request
  1042. # We construct a URL minus any project_id, but we don't
  1043. # return it just yet. It's a good option, but unless we
  1044. # have an exact match or match the max requested, we want
  1045. # to try for an unversioned endpoint first.
  1046. catalog_discovery = urllib.parse.ParseResult(
  1047. url.scheme,
  1048. url.netloc,
  1049. '/'.join(url_parts),
  1050. url.params,
  1051. url.query,
  1052. url.fragment).geturl().rstrip('/') + '/'
  1053. # If we found a viable catalog endpoint and it's
  1054. # an exact match or matches the max, go ahead and give
  1055. # it a go.
  1056. if catalog_discovery and (high_match or exact_match):
  1057. yield catalog_discovery
  1058. catalog_discovery = None
  1059. url_parts.pop()
  1060. if allow_version_hack:
  1061. # If there were projects or versions in the url they are now gone.
  1062. # That means we're left with what should be the unversioned url.
  1063. hacked_url = urllib.parse.ParseResult(
  1064. url.scheme,
  1065. url.netloc,
  1066. '/'.join(url_parts),
  1067. url.params,
  1068. url.query,
  1069. url.fragment).geturl()
  1070. # Since this is potentially us constructing a base URL from the
  1071. # versioned URL - we need to make sure it has a trailing /. But
  1072. # we only want to do that if we have built a new URL - not if
  1073. # we're using the one from the catalog
  1074. if hacked_url != self.catalog_url:
  1075. hacked_url = hacked_url.strip('/') + '/'
  1076. yield hacked_url
  1077. # If we have a catalog discovery url, it either means we didn't
  1078. # return it earlier because it wasn't an exact enough match, or
  1079. # that we did and it failed. We don't double-request things when
  1080. # consuming this, so it's safe to return it here in case we didn't
  1081. # already return it.
  1082. if catalog_discovery:
  1083. yield catalog_discovery
  1084. # NOTE(mordred): For backwards compatibility people might have
  1085. # added version hacks using the version hack system. The logic
  1086. # above should handle most cases, so by the time we get here it's
  1087. # most likely to be a no-op
  1088. yield self._get_catalog_discover_hack()
  1089. elif versioned_discovery and self._saved_project_id:
  1090. # We popped a project_id but are either avoiding version hacks
  1091. # or we didn't request a version. That means we still want to fetch
  1092. # the document from the "catalog url" - but the catalog url is has
  1093. # a project_id suffix so is likely not going to work for us. Try
  1094. # fetching from the project-less versioned endpoint.
  1095. yield versioned_discovery
  1096. # As a final fallthrough case, return the actual unmodified url from
  1097. # the catalog.
  1098. yield self.catalog_url
  1099. def _get_catalog_discover_hack(self):
  1100. """Apply the catalog hacks and figure out an unversioned endpoint.
  1101. This function is internal to keystoneauth1.
  1102. :returns: A url that has been transformed by the regex hacks that
  1103. match the service_type.
  1104. """
  1105. return _VERSION_HACKS.get_discover_hack(self.service_type, self.url)
  1106. def get_discovery(session, url, cache=None, authenticated=False):
  1107. """Return the discovery object for a URL.
  1108. Check the session and the plugin cache to see if we have already
  1109. performed discovery on the URL and if so return it, otherwise create
  1110. a new discovery object, cache it and return it.
  1111. NOTE: This function is expected to be used by keystoneauth and should not
  1112. be needed by users part of normal usage. A normal user should use
  1113. get_endpoint or get_endpoint_data on `keystoneauth.session.Session` or
  1114. endpoint_filters on `keystoneauth.session.Session` or
  1115. `keystoneauth.session.Session`. However, should the user need to perform
  1116. direct discovery for some reason, this function should be used so that
  1117. the discovery caching is used.
  1118. :param session: A session object to discover with.
  1119. :type session: keystoneauth1.session.Session
  1120. :param str url: The url to lookup.
  1121. :param dict cache:
  1122. A dict to be used for caching results, in addition to caching them
  1123. on the Session. (optional) Defaults to None.
  1124. :param bool authenticated:
  1125. Include a token in the discovery call. (optional) Defaults to None,
  1126. which will use a token if an auth plugin is installed.
  1127. :raises keystoneauth1.exceptions.discovery.DiscoveryFailure:
  1128. if for some reason the lookup fails.
  1129. :raises keystoneauth1.exceptions.http.HttpError:
  1130. An error from an invalid HTTP response.
  1131. :returns: A discovery object with the results of looking up that URL.
  1132. :rtype: :py:class:`keystoneauth1.discover.Discovery`
  1133. """
  1134. # There are between one and three different caches. The user may have
  1135. # passed one in. There is definitely one on the session, and there is
  1136. # one on the auth plugin if the Session has an auth plugin.
  1137. caches = []
  1138. # If a cache was passed in, check it first.
  1139. if cache is not None:
  1140. caches.append(cache)
  1141. # If the session has a cache, check it second, since it could have been
  1142. # provided by the user at Session creation time.
  1143. if hasattr(session, '_discovery_cache'):
  1144. caches.append(session._discovery_cache)
  1145. # Finally check the auth cache associated with the Session.
  1146. if session.auth and hasattr(session.auth, '_discovery_cache'):
  1147. caches.append(session.auth._discovery_cache)
  1148. for cache in caches:
  1149. disc = cache.get(url)
  1150. if disc:
  1151. break
  1152. else:
  1153. disc = Discover(session, url, authenticated=authenticated)
  1154. # Whether we get one from fetching or from cache, set it in the
  1155. # caches. This assures that if we combine sessions and auth plugins
  1156. # that we don't make unnecesary calls.
  1157. if disc:
  1158. for cache in caches:
  1159. cache[url] = disc
  1160. return disc
  1161. class _VersionHacks(object):
  1162. """A container to abstract the list of version hacks.
  1163. This could be done as simply a dictionary but is abstracted like this to
  1164. make for easier testing.
  1165. """
  1166. def __init__(self):
  1167. self._discovery_data = {}
  1168. def add_discover_hack(self, service_type, old, new=''):
  1169. """Add a new hack for a service type.
  1170. :param str service_type: The service_type in the catalog.
  1171. :param re.RegexObject old: The pattern to use.
  1172. :param str new: What to replace the pattern with.
  1173. """
  1174. hacks = self._discovery_data.setdefault(service_type, [])
  1175. hacks.append((old, new))
  1176. def get_discover_hack(self, service_type, url):
  1177. """Apply the catalog hacks and figure out an unversioned endpoint.
  1178. :param str service_type: the service_type to look up.
  1179. :param str url: The original url that came from a service_catalog.
  1180. :returns: Either the unversioned url or the one from the catalog
  1181. to try.
  1182. """
  1183. for old, new in self._discovery_data.get(service_type, []):
  1184. new_string, number_of_subs_made = old.subn(new, url)
  1185. if number_of_subs_made > 0:
  1186. return new_string
  1187. return url
  1188. _VERSION_HACKS = _VersionHacks()
  1189. _VERSION_HACKS.add_discover_hack('identity', re.compile('/v2.0/?$'), '/')
  1190. def add_catalog_discover_hack(service_type, old, new):
  1191. """Add a version removal rule for a particular service.
  1192. Originally deployments of OpenStack would contain a versioned endpoint in
  1193. the catalog for different services. E.g. an identity service might look
  1194. like ``http://localhost:5000/v2.0``. This is a problem when we want to use
  1195. a different version like v3.0 as there is no way to tell where it is
  1196. located. We cannot simply change all service catalogs either so there must
  1197. be a way to handle the older style of catalog.
  1198. This function adds a rule for a given service type that if part of the URL
  1199. matches a given regular expression in *old* then it will be replaced with
  1200. the *new* value. This will replace all instances of old with new. It should
  1201. therefore contain a regex anchor.
  1202. For example the included rule states::
  1203. add_catalog_version_hack('identity', re.compile('/v2.0/?$'), '/')
  1204. so if the catalog retrieves an *identity* URL that ends with /v2.0 or
  1205. /v2.0/ then it should replace it simply with / to fix the user's catalog.
  1206. :param str service_type: The service type as defined in the catalog that
  1207. the rule will apply to.
  1208. :param re.RegexObject old: The regular expression to search for and replace
  1209. if found.
  1210. :param str new: The new string to replace the pattern with.
  1211. """
  1212. _VERSION_HACKS.add_discover_hack(service_type, old, new)