diff --git a/cinder/keymgr/barbican.py b/cinder/keymgr/barbican.py index 3af2d6f469a..60631cfe538 100644 --- a/cinder/keymgr/barbican.py +++ b/cinder/keymgr/barbican.py @@ -47,6 +47,7 @@ class BarbicanKeyManager(key_mgr.KeyManager): # the barbican endpoint can't have the '/v1' on the end self._barbican_endpoint = self._base_url.rpartition('/')[0] self._barbican_client = None + self._current_context = None def _get_barbican_client(self, ctxt): """Creates a client to connect to the Barbican service. @@ -58,30 +59,34 @@ class BarbicanKeyManager(key_mgr.KeyManager): or project_id is None """ - if not self._barbican_client: - # Confirm context is provided, if not raise not authorized - if not ctxt: - msg = _("User is not authorized to use key manager.") - LOG.error(msg) - raise exception.NotAuthorized(msg) + # Confirm context is provided, if not raise not authorized + if not ctxt: + msg = _("User is not authorized to use key manager.") + LOG.error(msg) + raise exception.NotAuthorized(msg) - if not hasattr(ctxt, 'project_id') or ctxt.project_id is None: - msg = _("Unable to create Barbican Client without project_id.") - LOG.error(msg) - raise exception.KeyManagerError(msg) + if not hasattr(ctxt, 'project_id') or ctxt.project_id is None: + msg = _("Unable to create Barbican Client without project_id.") + LOG.error(msg) + raise exception.KeyManagerError(msg) - try: - auth = identity.v3.Token( - auth_url=CONF.keymgr.encryption_auth_url, - token=ctxt.auth_token, - project_id=ctxt.project_id) - sess = session.Session(auth=auth) - self._barbican_client = barbican_client.Client( - session=sess, - endpoint=self._barbican_endpoint) - except Exception: - with excutils.save_and_reraise_exception(): - LOG.exception(_LE("Error creating Barbican client.")) + # If same context, return cached barbican client + if self._barbican_client and self._current_context == ctxt: + return self._barbican_client + + try: + auth = identity.v3.Token( + auth_url=CONF.keymgr.encryption_auth_url, + token=ctxt.auth_token, + project_id=ctxt.project_id) + sess = session.Session(auth=auth) + self._barbican_client = barbican_client.Client( + session=sess, + endpoint=self._barbican_endpoint) + self._current_context = ctxt + except Exception: + with excutils.save_and_reraise_exception(): + LOG.exception(_LE("Error creating Barbican client.")) return self._barbican_client diff --git a/cinder/tests/unit/keymgr/test_barbican.py b/cinder/tests/unit/keymgr/test_barbican.py index a15b312e417..21ce94c00fc 100644 --- a/cinder/tests/unit/keymgr/test_barbican.py +++ b/cinder/tests/unit/keymgr/test_barbican.py @@ -75,6 +75,7 @@ class BarbicanKeyManagerTestCase(test_key_mgr.KeyManagerTestCase): self.create = self.mock_barbican.secrets.create self.key_mgr._barbican_client = self.mock_barbican + self.key_mgr._current_context = self.ctxt def _build_mock_symKey(self): self.mock_symKey = mock.Mock()