Add keystone client

This client will be used by novaclient and heatclient to create a bay.
The original sources are come from Ironic.

Change-Id: Ib075148afb0ddf503e71b333cef85523561a2732
This commit is contained in:
OTSUKA, Yuanying 2014-12-12 16:34:05 +09:00
parent bb5615495a
commit 6919cad773
4 changed files with 270 additions and 1 deletions

View File

@ -415,3 +415,16 @@ class ServiceLocked(Conflict):
class ServiceNotLocked(Invalid):
message = _("Service %(service)s found not to be locked on release")
class KeystoneUnauthorized(MagnumException):
message = _("Not authorized in Keystone.")
class KeystoneFailure(MagnumException):
message = _("Keystone failed.")
class CatalogNotFound(MagnumException):
message = _("Service type %(service_type)s with endpoint type "
"%(endpoint_type)s not found in keystone service catalog.")

127
magnum/common/keystone.py Normal file
View File

@ -0,0 +1,127 @@
# coding=utf-8
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneclient import exceptions as ksexception
# NOTE(deva): import auth_token so oslo.config pulls in keystone_authtoken
from keystonemiddleware import auth_token # noqa
from oslo.config import cfg
from six.moves.urllib import parse
from magnum.common import exception
from magnum.openstack.common._i18n import _
CONF = cfg.CONF
def _is_apiv3(auth_url, auth_version):
"""Checks if V3 version of API is being used or not.
This method inspects auth_url and auth_version, and checks whether V3
version of the API is being used or not.
:param auth_url: a http or https url to be inspected (like
'http://127.0.0.1:9898/').
:param auth_version: a string containing the version (like 'v2', 'v3.0')
:returns: True if V3 of the API is being used.
"""
return auth_version == 'v3.0' or '/v3' in parse.urlparse(auth_url).path
def _get_ksclient(token=None):
auth_url = CONF.keystone_authtoken.auth_uri
if not auth_url:
raise exception.KeystoneFailure(_('Keystone API endpoint is missing'))
auth_version = CONF.keystone_authtoken.auth_version
api_v3 = _is_apiv3(auth_url, auth_version)
if api_v3:
from keystoneclient.v3 import client
else:
from keystoneclient.v2_0 import client
auth_url = get_keystone_url(auth_url, auth_version)
try:
if token:
return client.Client(token=token, auth_url=auth_url)
else:
return client.Client(username=CONF.keystone_authtoken.admin_user,
password=CONF.keystone_authtoken.admin_password,
tenant_name=CONF.keystone_authtoken.admin_tenant_name,
auth_url=auth_url)
except ksexception.Unauthorized:
raise exception.KeystoneUnauthorized()
except ksexception.AuthorizationFailure as err:
raise exception.KeystoneFailure(_('Could not authorize in Keystone:'
' %s') % err)
def get_keystone_url(auth_url, auth_version):
"""Gives an http/https url to contact keystone.
Given an auth_url and auth_version, this method generates the url in
which keystone can be reached.
:param auth_url: a http or https url to be inspected (like
'http://127.0.0.1:9898/').
:param auth_version: a string containing the version (like v2, v3.0, etc)
:returns: a string containing the keystone url
"""
api_v3 = _is_apiv3(auth_url, auth_version)
api_version = 'v3' if api_v3 else 'v2.0'
# NOTE(lucasagomes): Get rid of the trailing '/' otherwise urljoin()
# fails to override the version in the URL
return parse.urljoin(auth_url.rstrip('/'), api_version)
def get_service_url(service_type='container', endpoint_type='internal'):
"""Wrapper for get service url from keystone service catalog.
Given a service_type and an endpoint_type, this method queries keystone
service catalog and provides the url for the desired endpoint.
:param service_type: the keystone service for which url is required.
:param endpoint_type: the type of endpoint for the service.
:returns: an http/https url for the desired endpoint.
"""
ksclient = _get_ksclient()
if not ksclient.has_service_catalog():
raise exception.KeystoneFailure(_('No Keystone service catalog '
'loaded'))
try:
endpoint = ksclient.service_catalog.url_for(service_type=service_type,
endpoint_type=endpoint_type)
except ksexception.EndpointNotFound:
raise exception.CatalogNotFound(service_type=service_type,
endpoint_type=endpoint_type)
return endpoint
def get_admin_auth_token():
"""Get an admin auth_token from the Keystone."""
ksclient = _get_ksclient()
return ksclient.auth_token
def token_expires_soon(token, duration=None):
"""Determines if token expiration is about to occur.
:param duration: time interval in seconds
:returns: boolean : true if expiration is within the given duration
"""
ksclient = _get_ksclient(token=token)
return ksclient.auth_ref.will_expire_soon(stale_duration=duration)

View File

@ -26,6 +26,10 @@ import testscenarios
from magnum.tests import conf_fixture
CONF = cfg.CONF
CONF.set_override('use_stderr', False)
class BaseTestCase(testscenarios.WithScenarios, base.BaseTestCase):
"""Test base class."""
@ -35,6 +39,8 @@ class BaseTestCase(testscenarios.WithScenarios, base.BaseTestCase):
class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests."""
def setUp(self):
super(TestCase, self).setUp()
self.app = testing.load_test_app(os.path.join(
@ -47,4 +53,8 @@ class TestCase(base.BaseTestCase):
super(TestCase, self).tearDown()
pecan.set_config({}, overwrite=True)
"""Test case base class for all unit tests."""
def config(self, **kw):
"""Override config options for a test."""
group = kw.pop('group', None)
for k, v in kw.iteritems():
CONF.set_override(k, v, group)

View File

@ -0,0 +1,119 @@
# -*- encoding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystoneclient import exceptions as ksexception
import mock
from magnum.common import exception
from magnum.common import keystone
from magnum.tests import base
class FakeCatalog:
def url_for(self, **kwargs):
return 'fake-url'
class FakeClient:
def __init__(self, **kwargs):
self.service_catalog = FakeCatalog()
def has_service_catalog(self):
return True
class KeystoneTestCase(base.TestCase):
def setUp(self):
super(KeystoneTestCase, self).setUp()
self.config(group='keystone_authtoken',
auth_uri='http://127.0.0.1:9898/',
admin_user='fake', admin_password='fake',
admin_tenant_name='fake')
def test_failure_authorization(self):
self.assertRaises(exception.KeystoneFailure, keystone.get_service_url)
@mock.patch.object(FakeCatalog, 'url_for')
@mock.patch('keystoneclient.v2_0.client.Client')
def test_get_url(self, mock_ks, mock_uf):
fake_url = 'http://127.0.0.1:6385'
mock_uf.return_value = fake_url
mock_ks.return_value = FakeClient()
res = keystone.get_service_url()
self.assertEqual(fake_url, res)
@mock.patch.object(FakeCatalog, 'url_for')
@mock.patch('keystoneclient.v2_0.client.Client')
def test_url_not_found(self, mock_ks, mock_uf):
mock_uf.side_effect = ksexception.EndpointNotFound
mock_ks.return_value = FakeClient()
self.assertRaises(exception.CatalogNotFound, keystone.get_service_url)
@mock.patch.object(FakeClient, 'has_service_catalog')
@mock.patch('keystoneclient.v2_0.client.Client')
def test_no_catalog(self, mock_ks, mock_hsc):
mock_hsc.return_value = False
mock_ks.return_value = FakeClient()
self.assertRaises(exception.KeystoneFailure, keystone.get_service_url)
@mock.patch('keystoneclient.v2_0.client.Client')
def test_unauthorized(self, mock_ks):
mock_ks.side_effect = ksexception.Unauthorized
self.assertRaises(exception.KeystoneUnauthorized,
keystone.get_service_url)
def test_get_service_url_fail_missing_auth_uri(self):
self.config(group='keystone_authtoken', auth_uri=None)
self.assertRaises(exception.KeystoneFailure,
keystone.get_service_url)
@mock.patch('keystoneclient.v2_0.client.Client')
def test_get_service_url_versionless_v2(self, mock_ks):
mock_ks.return_value = FakeClient()
self.config(group='keystone_authtoken', auth_uri='http://127.0.0.1')
expected_url = 'http://127.0.0.1/v2.0'
keystone.get_service_url()
mock_ks.assert_called_once_with(username='fake', password='fake',
tenant_name='fake',
auth_url=expected_url)
@mock.patch('keystoneclient.v3.client.Client')
def test_get_service_url_versionless_v3(self, mock_ks):
mock_ks.return_value = FakeClient()
self.config(group='keystone_authtoken', auth_version='v3.0',
auth_uri='http://127.0.0.1')
expected_url = 'http://127.0.0.1/v3'
keystone.get_service_url()
mock_ks.assert_called_once_with(username='fake', password='fake',
tenant_name='fake',
auth_url=expected_url)
@mock.patch('keystoneclient.v2_0.client.Client')
def test_get_service_url_version_override(self, mock_ks):
mock_ks.return_value = FakeClient()
self.config(group='keystone_authtoken',
auth_uri='http://127.0.0.1/v2.0/')
expected_url = 'http://127.0.0.1/v2.0'
keystone.get_service_url()
mock_ks.assert_called_once_with(username='fake', password='fake',
tenant_name='fake',
auth_url=expected_url)
@mock.patch('keystoneclient.v2_0.client.Client')
def test_get_admin_auth_token(self, mock_ks):
fake_client = FakeClient()
fake_client.auth_token = '123456'
mock_ks.return_value = fake_client
self.assertEqual('123456', keystone.get_admin_auth_token())