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.

adapter.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. import os
  13. import warnings
  14. from keystoneauth1 import session
  15. class Adapter(object):
  16. """An instance of a session with local variables.
  17. A session is a global object that is shared around amongst many clients. It
  18. therefore contains state that is relevant to everyone. There is a lot of
  19. state such as the service type and region_name that are only relevant to a
  20. particular client that is using the session. An adapter provides a wrapper
  21. of client local data around the global session object.
  22. version, min_version, max_version and default_microversion can all be
  23. given either as a string or a tuple.
  24. :param session: The session object to wrap.
  25. :type session: keystoneauth1.session.Session
  26. :param str service_type: The default service_type for URL discovery.
  27. :param str service_name: The default service_name for URL discovery.
  28. :param str interface: The default interface for URL discovery.
  29. :param str region_name: The default region_name for URL discovery.
  30. :param str endpoint_override: Always use this endpoint URL for requests
  31. for this client.
  32. :param version: The minimum version restricted to a given Major API.
  33. Mutually exclusive with min_version and max_version.
  34. (optional)
  35. :param auth: An auth plugin to use instead of the session one.
  36. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  37. :param str user_agent: The User-Agent string to set.
  38. :param int connect_retries: the maximum number of retries that should
  39. be attempted for connection errors.
  40. Default None - use session default which
  41. is don't retry.
  42. :param logger: A logging object to use for requests that pass through this
  43. adapter.
  44. :type logger: logging.Logger
  45. :param dict allow: Extra filters to pass when discovering API versions.
  46. (optional)
  47. :param dict additional_headers: Additional headers that should be attached
  48. to every request passing through the
  49. adapter. Headers of the same name specified
  50. per request will take priority.
  51. :param str client_name: The name of the client that created the adapter.
  52. This will be used to create the user_agent.
  53. :param str client_version: The version of the client that created the
  54. adapter. This will be used to create the
  55. user_agent.
  56. :param bool allow_version_hack: Allow keystoneauth to hack up catalog
  57. URLS to support older schemes.
  58. (optional, default True)
  59. :param str global_request_id: A global_request_id (in the form of
  60. ``req-$uuid``) that will be passed on all
  61. requests. Enables cross project request id
  62. tracking.
  63. :param min_version: The minimum major version of a given API, intended to
  64. be used as the lower bound of a range with
  65. max_version. Mutually exclusive with version.
  66. If min_version is given with no max_version it is as
  67. if max version is 'latest'. (optional)
  68. :param max_version: The maximum major version of a given API, intended to
  69. be used as the upper bound of a range with min_version.
  70. Mutually exclusive with version. (optional)
  71. :param default_microversion: The default microversion value to send
  72. with API requests. While microversions are
  73. a per-request feature, a user may know they
  74. want to default to sending a specific value.
  75. (optional)
  76. :param int status_code_retries: the maximum number of retries that
  77. should be attempted for retriable
  78. HTTP status codes (optional, defaults
  79. to 0 - never retry).
  80. :param list retriable_status_codes: list of HTTP status codes that
  81. should be retried (optional,
  82. defaults to HTTP 503, has no effect
  83. when status_code_retries is 0).
  84. """
  85. client_name = None
  86. client_version = None
  87. def __init__(self, session, service_type=None, service_name=None,
  88. interface=None, region_name=None, endpoint_override=None,
  89. version=None, auth=None, user_agent=None,
  90. connect_retries=None, logger=None, allow=None,
  91. additional_headers=None, client_name=None,
  92. client_version=None, allow_version_hack=None,
  93. global_request_id=None,
  94. min_version=None, max_version=None,
  95. default_microversion=None, status_code_retries=None,
  96. retriable_status_codes=None):
  97. if version and (min_version or max_version):
  98. raise TypeError(
  99. "version is mutually exclusive with min_version and"
  100. " max_version")
  101. # NOTE(jamielennox): when adding new parameters to adapter please also
  102. # add them to the adapter call in httpclient.HTTPClient.__init__ as
  103. # well as to load_adapter_from_argparse below if the argument is
  104. # intended to be something a user would reasonably expect to set on
  105. # a command line
  106. self.session = session
  107. self.service_type = service_type
  108. self.service_name = service_name
  109. self.interface = interface
  110. self.region_name = region_name
  111. self.endpoint_override = endpoint_override
  112. self.version = version
  113. self.user_agent = user_agent
  114. self.auth = auth
  115. self.connect_retries = connect_retries
  116. self.logger = logger
  117. self.allow = allow or {}
  118. self.additional_headers = additional_headers or {}
  119. self.allow_version_hack = allow_version_hack
  120. self.min_version = min_version
  121. self.max_version = max_version
  122. self.default_microversion = default_microversion
  123. self.status_code_retries = status_code_retries
  124. self.retriable_status_codes = retriable_status_codes
  125. self.global_request_id = global_request_id
  126. if client_name:
  127. self.client_name = client_name
  128. if client_version:
  129. self.client_version = client_version
  130. def _set_endpoint_filter_kwargs(self, kwargs):
  131. if self.service_type:
  132. kwargs.setdefault('service_type', self.service_type)
  133. if self.service_name:
  134. kwargs.setdefault('service_name', self.service_name)
  135. if self.interface:
  136. kwargs.setdefault('interface', self.interface)
  137. if self.region_name:
  138. kwargs.setdefault('region_name', self.region_name)
  139. if self.version:
  140. kwargs.setdefault('version', self.version)
  141. if self.min_version:
  142. kwargs.setdefault('min_version', self.min_version)
  143. if self.max_version:
  144. kwargs.setdefault('max_version', self.max_version)
  145. if self.allow_version_hack is not None:
  146. kwargs.setdefault('allow_version_hack', self.allow_version_hack)
  147. def request(self, url, method, **kwargs):
  148. endpoint_filter = kwargs.setdefault('endpoint_filter', {})
  149. self._set_endpoint_filter_kwargs(endpoint_filter)
  150. if self.endpoint_override:
  151. kwargs.setdefault('endpoint_override', self.endpoint_override)
  152. if self.auth:
  153. kwargs.setdefault('auth', self.auth)
  154. if self.user_agent:
  155. kwargs.setdefault('user_agent', self.user_agent)
  156. if self.connect_retries is not None:
  157. kwargs.setdefault('connect_retries', self.connect_retries)
  158. if self.status_code_retries is not None:
  159. kwargs.setdefault('status_code_retries', self.status_code_retries)
  160. if self.retriable_status_codes:
  161. kwargs.setdefault('retriable_status_codes',
  162. self.retriable_status_codes)
  163. if self.logger:
  164. kwargs.setdefault('logger', self.logger)
  165. if self.allow:
  166. kwargs.setdefault('allow', self.allow)
  167. if self.default_microversion is not None:
  168. kwargs.setdefault('microversion', self.default_microversion)
  169. if isinstance(self.session, (session.Session, Adapter)):
  170. # these things are unsupported by keystoneclient's session so be
  171. # careful with them until everyone has transitioned to ksa.
  172. # Allowing adapter allows adapter nesting that auth_token does.
  173. if self.client_name:
  174. kwargs.setdefault('client_name', self.client_name)
  175. if self.client_version:
  176. kwargs.setdefault('client_version', self.client_version)
  177. else:
  178. warnings.warn('Using keystoneclient sessions has been deprecated. '
  179. 'Please update your software to use keystoneauth1.')
  180. for k, v in self.additional_headers.items():
  181. kwargs.setdefault('headers', {}).setdefault(k, v)
  182. if self.global_request_id is not None:
  183. kwargs.setdefault('headers', {}).setdefault(
  184. "X-OpenStack-Request-ID", self.global_request_id)
  185. return self.session.request(url, method, **kwargs)
  186. def get_token(self, auth=None):
  187. """Return a token as provided by the auth plugin.
  188. :param auth: The auth plugin to use for token. Overrides the plugin
  189. on the session. (optional)
  190. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  191. :raises keystoneauth1.exceptions.auth.AuthorizationFailure: if a new
  192. token fetch fails.
  193. :returns: A valid token.
  194. :rtype: :class:`str`
  195. """
  196. return self.session.get_token(auth or self.auth)
  197. def get_endpoint(self, auth=None, **kwargs):
  198. """Get an endpoint as provided by the auth plugin.
  199. :param auth: The auth plugin to use for token. Overrides the plugin on
  200. the session. (optional)
  201. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  202. :raises keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin: if a
  203. plugin is not available.
  204. :returns: An endpoint if available or None.
  205. :rtype: :class:`str`
  206. """
  207. if self.endpoint_override:
  208. return self.endpoint_override
  209. self._set_endpoint_filter_kwargs(kwargs)
  210. return self.session.get_endpoint(auth or self.auth, **kwargs)
  211. def get_endpoint_data(self, auth=None):
  212. """Get the endpoint data for this Adapter's endpoint.
  213. :param auth: The auth plugin to use for token. Overrides the plugin on
  214. the session. (optional)
  215. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  216. :raises keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin: if a
  217. plugin is not available.
  218. :raises TypeError: If arguments are invalid
  219. :returns: Endpoint data if available or None.
  220. :rtype: keystoneauth1.discover.EndpointData
  221. """
  222. kwargs = {}
  223. self._set_endpoint_filter_kwargs(kwargs)
  224. if self.endpoint_override:
  225. kwargs['endpoint_override'] = self.endpoint_override
  226. return self.session.get_endpoint_data(auth or self.auth, **kwargs)
  227. def get_api_major_version(self, auth=None, **kwargs):
  228. """Get the major API version as provided by the auth plugin.
  229. :param auth: The auth plugin to use for token. Overrides the plugin on
  230. the session. (optional)
  231. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  232. :raises keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin: if a
  233. plugin is not available.
  234. :return: The major version of the API of the service discovered.
  235. :rtype: tuple or None
  236. """
  237. self._set_endpoint_filter_kwargs(kwargs)
  238. if self.endpoint_override:
  239. kwargs['endpoint_override'] = self.endpoint_override
  240. return self.session.get_api_major_version(auth or self.auth, **kwargs)
  241. def invalidate(self, auth=None):
  242. """Invalidate an authentication plugin."""
  243. return self.session.invalidate(auth or self.auth)
  244. def get_user_id(self, auth=None):
  245. """Return the authenticated user_id as provided by the auth plugin.
  246. :param auth: The auth plugin to use for token. Overrides the plugin
  247. on the session. (optional)
  248. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  249. :raises keystoneauth1.exceptions.auth.AuthorizationFailure:
  250. if a new token fetch fails.
  251. :raises keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin:
  252. if a plugin is not available.
  253. :returns: Current `user_id` or None if not supported by plugin.
  254. :rtype: :class:`str`
  255. """
  256. return self.session.get_user_id(auth or self.auth)
  257. def get_project_id(self, auth=None):
  258. """Return the authenticated project_id as provided by the auth plugin.
  259. :param auth: The auth plugin to use for token. Overrides the plugin
  260. on the session. (optional)
  261. :type auth: keystoneauth1.plugin.BaseAuthPlugin
  262. :raises keystoneauth1.exceptions.auth.AuthorizationFailure:
  263. if a new token fetch fails.
  264. :raises keystoneauth1.exceptions.auth_plugins.MissingAuthPlugin:
  265. if a plugin is not available.
  266. :returns: Current `project_id` or None if not supported by plugin.
  267. :rtype: :class:`str`
  268. """
  269. return self.session.get_project_id(auth or self.auth)
  270. def get(self, url, **kwargs):
  271. return self.request(url, 'GET', **kwargs)
  272. def head(self, url, **kwargs):
  273. return self.request(url, 'HEAD', **kwargs)
  274. def post(self, url, **kwargs):
  275. return self.request(url, 'POST', **kwargs)
  276. def put(self, url, **kwargs):
  277. return self.request(url, 'PUT', **kwargs)
  278. def patch(self, url, **kwargs):
  279. return self.request(url, 'PATCH', **kwargs)
  280. def delete(self, url, **kwargs):
  281. return self.request(url, 'DELETE', **kwargs)
  282. # TODO(efried): Move this to loading.adapter.Adapter
  283. @classmethod
  284. def register_argparse_arguments(cls, parser, service_type=None):
  285. """Attach arguments to a given argparse Parser for Adapters.
  286. :param parser: The argparse parser to attach options to.
  287. :type parser: argparse.ArgumentParser
  288. :param str service_type: Default service_type value. (optional)
  289. """
  290. adapter_group = parser.add_argument_group(
  291. 'Service Options',
  292. 'Options controlling the specialization of the API'
  293. ' Connection from information found in the catalog')
  294. adapter_group.add_argument(
  295. '--os-service-type',
  296. metavar='<name>',
  297. default=os.environ.get('OS_SERVICE_TYPE', service_type),
  298. help='Service type to request from the catalog')
  299. adapter_group.add_argument(
  300. '--os-service-name',
  301. metavar='<name>',
  302. default=os.environ.get('OS_SERVICE_NAME', None),
  303. help='Service name to request from the catalog')
  304. adapter_group.add_argument(
  305. '--os-interface',
  306. metavar='<name>',
  307. default=os.environ.get('OS_INTERFACE', 'public'),
  308. help='API Interface to use [public, internal, admin]')
  309. adapter_group.add_argument(
  310. '--os-region-name',
  311. metavar='<name>',
  312. default=os.environ.get('OS_REGION_NAME', None),
  313. help='Region of the cloud to use')
  314. adapter_group.add_argument(
  315. '--os-endpoint-override',
  316. metavar='<name>',
  317. default=os.environ.get('OS_ENDPOINT_OVERRIDE', None),
  318. help='Endpoint to use instead of the endpoint in the catalog')
  319. adapter_group.add_argument(
  320. '--os-api-version',
  321. metavar='<name>',
  322. default=os.environ.get('OS_API_VERSION', None),
  323. help='Which version of the service API to use')
  324. # TODO(efried): Move this to loading.adapter.Adapter
  325. @classmethod
  326. def register_service_argparse_arguments(cls, parser, service_type):
  327. """Attach arguments to a given argparse Parser for Adapters.
  328. :param parser: The argparse parser to attach options to.
  329. :type parser: argparse.ArgumentParser
  330. :param str service_type: Name of a service to generate additional
  331. arguments for.
  332. """
  333. service_env = service_type.upper().replace('-', '_')
  334. adapter_group = parser.add_argument_group(
  335. '{service_type} Service Options'.format(
  336. service_type=service_type.title()),
  337. 'Options controlling the specialization of the {service_type}'
  338. ' API Connection from information found in the catalog'.format(
  339. service_type=service_type.title()))
  340. adapter_group.add_argument(
  341. '--os-{service_type}-service-type'.format(
  342. service_type=service_type),
  343. metavar='<name>',
  344. default=os.environ.get(
  345. 'OS_{service_type}_SERVICE_TYPE'.format(
  346. service_type=service_env), None),
  347. help=('Service type to request from the catalog for the'
  348. ' {service_type} service'.format(
  349. service_type=service_type)))
  350. adapter_group.add_argument(
  351. '--os-{service_type}-service-name'.format(
  352. service_type=service_type),
  353. metavar='<name>',
  354. default=os.environ.get(
  355. 'OS_{service_type}_SERVICE_NAME'.format(
  356. service_type=service_env), None),
  357. help=('Service name to request from the catalog for the'
  358. ' {service_type} service'.format(
  359. service_type=service_type)))
  360. adapter_group.add_argument(
  361. '--os-{service_type}-interface'.format(
  362. service_type=service_type),
  363. metavar='<name>',
  364. default=os.environ.get(
  365. 'OS_{service_type}_INTERFACE'.format(
  366. service_type=service_env), None),
  367. help=('API Interface to use for the {service_type} service'
  368. ' [public, internal, admin]'.format(
  369. service_type=service_type)))
  370. adapter_group.add_argument(
  371. '--os-{service_type}-api-version'.format(
  372. service_type=service_type),
  373. metavar='<name>',
  374. default=os.environ.get(
  375. 'OS_{service_type}_API_VERSION'.format(
  376. service_type=service_env), None),
  377. help=('Which version of the service API to use for'
  378. ' the {service_type} service'.format(
  379. service_type=service_type)))
  380. adapter_group.add_argument(
  381. '--os-{service_type}-endpoint-override'.format(
  382. service_type=service_type),
  383. metavar='<name>',
  384. default=os.environ.get(
  385. 'OS_{service_type}_ENDPOINT_OVERRIDE'.format(
  386. service_type=service_env), None),
  387. help=('Endpoint to use for the {service_type} service'
  388. ' instead of the endpoint in the catalog'.format(
  389. service_type=service_type)))
  390. class LegacyJsonAdapter(Adapter):
  391. """Make something that looks like an old HTTPClient.
  392. A common case when using an adapter is that we want an interface similar to
  393. the HTTPClients of old which returned the body as JSON as well.
  394. You probably don't want this if you are starting from scratch.
  395. """
  396. def request(self, *args, **kwargs):
  397. headers = kwargs.setdefault('headers', {})
  398. headers.setdefault('Accept', 'application/json')
  399. try:
  400. kwargs['json'] = kwargs.pop('body')
  401. except KeyError:
  402. pass
  403. resp = super(LegacyJsonAdapter, self).request(*args, **kwargs)
  404. try:
  405. body = resp.json()
  406. except ValueError:
  407. body = None
  408. return resp, body
  409. # TODO(efried): Deprecate this in favor of
  410. # loading.adapter.register_argparse_arguments
  411. def register_adapter_argparse_arguments(*args, **kwargs):
  412. return Adapter.register_argparse_arguments(*args, **kwargs)
  413. # TODO(efried): Deprecate this in favor of
  414. # loading.adapter.register_service_argparse_arguments
  415. def register_service_adapter_argparse_arguments(*args, **kwargs):
  416. return Adapter.register_service_argparse_arguments(*args, **kwargs)