aboutsummaryrefslogtreecommitdiffstats
path: root/keystone-moon/keystone/catalog
diff options
context:
space:
mode:
authorWuKong <rebirthmonkey@gmail.com>2015-06-30 18:47:29 +0200
committerWuKong <rebirthmonkey@gmail.com>2015-06-30 18:47:29 +0200
commitb8c756ecdd7cced1db4300935484e8c83701c82e (patch)
tree87e51107d82b217ede145de9d9d59e2100725bd7 /keystone-moon/keystone/catalog
parentc304c773bae68fb854ed9eab8fb35c4ef17cf136 (diff)
migrate moon code from github to opnfv
Change-Id: Ice53e368fd1114d56a75271aa9f2e598e3eba604 Signed-off-by: WuKong <rebirthmonkey@gmail.com>
Diffstat (limited to 'keystone-moon/keystone/catalog')
-rw-r--r--keystone-moon/keystone/catalog/__init__.py17
-rw-r--r--keystone-moon/keystone/catalog/backends/__init__.py0
-rw-r--r--keystone-moon/keystone/catalog/backends/kvs.py154
-rw-r--r--keystone-moon/keystone/catalog/backends/sql.py337
-rw-r--r--keystone-moon/keystone/catalog/backends/templated.py127
-rw-r--r--keystone-moon/keystone/catalog/controllers.py336
-rw-r--r--keystone-moon/keystone/catalog/core.py506
-rw-r--r--keystone-moon/keystone/catalog/routers.py40
-rw-r--r--keystone-moon/keystone/catalog/schema.py96
9 files changed, 1613 insertions, 0 deletions
diff --git a/keystone-moon/keystone/catalog/__init__.py b/keystone-moon/keystone/catalog/__init__.py
new file mode 100644
index 00000000..8d4d1567
--- /dev/null
+++ b/keystone-moon/keystone/catalog/__init__.py
@@ -0,0 +1,17 @@
+# Copyright 2012 OpenStack Foundation
+#
+# 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 keystone.catalog import controllers # noqa
+from keystone.catalog.core import * # noqa
+from keystone.catalog import routers # noqa
diff --git a/keystone-moon/keystone/catalog/backends/__init__.py b/keystone-moon/keystone/catalog/backends/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/keystone-moon/keystone/catalog/backends/__init__.py
diff --git a/keystone-moon/keystone/catalog/backends/kvs.py b/keystone-moon/keystone/catalog/backends/kvs.py
new file mode 100644
index 00000000..30a121d8
--- /dev/null
+++ b/keystone-moon/keystone/catalog/backends/kvs.py
@@ -0,0 +1,154 @@
+# Copyright 2012 OpenStack Foundation
+#
+# 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 keystone import catalog
+from keystone.common import driver_hints
+from keystone.common import kvs
+
+
+class Catalog(kvs.Base, catalog.Driver):
+ # Public interface
+ def get_catalog(self, user_id, tenant_id):
+ return self.db.get('catalog-%s-%s' % (tenant_id, user_id))
+
+ # region crud
+
+ def _delete_child_regions(self, region_id, root_region_id):
+ """Delete all child regions.
+
+ Recursively delete any region that has the supplied region
+ as its parent.
+ """
+ children = [r for r in self.list_regions(driver_hints.Hints())
+ if r['parent_region_id'] == region_id]
+ for child in children:
+ if child['id'] == root_region_id:
+ # Hit a circular region hierarchy
+ return
+ self._delete_child_regions(child['id'], root_region_id)
+ self._delete_region(child['id'])
+
+ def _check_parent_region(self, region_ref):
+ """Raise a NotFound if the parent region does not exist.
+
+ If the region_ref has a specified parent_region_id, check that
+ the parent exists, otherwise, raise a NotFound.
+ """
+ parent_region_id = region_ref.get('parent_region_id')
+ if parent_region_id is not None:
+ # This will raise NotFound if the parent doesn't exist,
+ # which is the behavior we want.
+ self.get_region(parent_region_id)
+
+ def create_region(self, region):
+ region_id = region['id']
+ region.setdefault('parent_region_id')
+ self._check_parent_region(region)
+ self.db.set('region-%s' % region_id, region)
+ region_list = set(self.db.get('region_list', []))
+ region_list.add(region_id)
+ self.db.set('region_list', list(region_list))
+ return region
+
+ def list_regions(self, hints):
+ return [self.get_region(x) for x in self.db.get('region_list', [])]
+
+ def get_region(self, region_id):
+ return self.db.get('region-%s' % region_id)
+
+ def update_region(self, region_id, region):
+ self._check_parent_region(region)
+ old_region = self.get_region(region_id)
+ old_region.update(region)
+ self._ensure_no_circle_in_hierarchical_regions(old_region)
+ self.db.set('region-%s' % region_id, old_region)
+ return old_region
+
+ def _delete_region(self, region_id):
+ self.db.delete('region-%s' % region_id)
+ region_list = set(self.db.get('region_list', []))
+ region_list.remove(region_id)
+ self.db.set('region_list', list(region_list))
+
+ def delete_region(self, region_id):
+ self._delete_child_regions(region_id, region_id)
+ self._delete_region(region_id)
+
+ # service crud
+
+ def create_service(self, service_id, service):
+ self.db.set('service-%s' % service_id, service)
+ service_list = set(self.db.get('service_list', []))
+ service_list.add(service_id)
+ self.db.set('service_list', list(service_list))
+ return service
+
+ def list_services(self, hints):
+ return [self.get_service(x) for x in self.db.get('service_list', [])]
+
+ def get_service(self, service_id):
+ return self.db.get('service-%s' % service_id)
+
+ def update_service(self, service_id, service):
+ old_service = self.get_service(service_id)
+ old_service.update(service)
+ self.db.set('service-%s' % service_id, old_service)
+ return old_service
+
+ def delete_service(self, service_id):
+ # delete referencing endpoints
+ for endpoint_id in self.db.get('endpoint_list', []):
+ if self.get_endpoint(endpoint_id)['service_id'] == service_id:
+ self.delete_endpoint(endpoint_id)
+
+ self.db.delete('service-%s' % service_id)
+ service_list = set(self.db.get('service_list', []))
+ service_list.remove(service_id)
+ self.db.set('service_list', list(service_list))
+
+ # endpoint crud
+
+ def create_endpoint(self, endpoint_id, endpoint):
+ self.db.set('endpoint-%s' % endpoint_id, endpoint)
+ endpoint_list = set(self.db.get('endpoint_list', []))
+ endpoint_list.add(endpoint_id)
+ self.db.set('endpoint_list', list(endpoint_list))
+ return endpoint
+
+ def list_endpoints(self, hints):
+ return [self.get_endpoint(x) for x in self.db.get('endpoint_list', [])]
+
+ def get_endpoint(self, endpoint_id):
+ return self.db.get('endpoint-%s' % endpoint_id)
+
+ def update_endpoint(self, endpoint_id, endpoint):
+ if endpoint.get('region_id') is not None:
+ self.get_region(endpoint['region_id'])
+
+ old_endpoint = self.get_endpoint(endpoint_id)
+ old_endpoint.update(endpoint)
+ self.db.set('endpoint-%s' % endpoint_id, old_endpoint)
+ return old_endpoint
+
+ def delete_endpoint(self, endpoint_id):
+ self.db.delete('endpoint-%s' % endpoint_id)
+ endpoint_list = set(self.db.get('endpoint_list', []))
+ endpoint_list.remove(endpoint_id)
+ self.db.set('endpoint_list', list(endpoint_list))
+
+ # Private interface
+ def _create_catalog(self, user_id, tenant_id, data):
+ self.db.set('catalog-%s-%s' % (tenant_id, user_id), data)
+ return data
diff --git a/keystone-moon/keystone/catalog/backends/sql.py b/keystone-moon/keystone/catalog/backends/sql.py
new file mode 100644
index 00000000..8ab82305
--- /dev/null
+++ b/keystone-moon/keystone/catalog/backends/sql.py
@@ -0,0 +1,337 @@
+# Copyright 2012 OpenStack Foundation
+# Copyright 2012 Canonical Ltd.
+#
+# 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.
+
+import itertools
+
+from oslo_config import cfg
+import six
+import sqlalchemy
+from sqlalchemy.sql import true
+
+from keystone import catalog
+from keystone.catalog import core
+from keystone.common import sql
+from keystone import exception
+
+
+CONF = cfg.CONF
+
+
+class Region(sql.ModelBase, sql.DictBase):
+ __tablename__ = 'region'
+ attributes = ['id', 'description', 'parent_region_id']
+ id = sql.Column(sql.String(255), primary_key=True)
+ description = sql.Column(sql.String(255), nullable=False)
+ # NOTE(jaypipes): Right now, using an adjacency list model for
+ # storing the hierarchy of regions is fine, since
+ # the API does not support any kind of querying for
+ # more complex hierarchical queries such as "get me only
+ # the regions that are subchildren of this region", etc.
+ # If, in the future, such queries are needed, then it
+ # would be possible to add in columns to this model for
+ # "left" and "right" and provide support for a nested set
+ # model.
+ parent_region_id = sql.Column(sql.String(255), nullable=True)
+
+ # TODO(jaypipes): I think it's absolutely stupid that every single model
+ # is required to have an "extra" column because of the
+ # DictBase in the keystone.common.sql.core module. Forcing
+ # tables to have pointless columns in the database is just
+ # bad. Remove all of this extra JSON blob stuff.
+ # See: https://bugs.launchpad.net/keystone/+bug/1265071
+ extra = sql.Column(sql.JsonBlob())
+ endpoints = sqlalchemy.orm.relationship("Endpoint", backref="region")
+
+
+class Service(sql.ModelBase, sql.DictBase):
+ __tablename__ = 'service'
+ attributes = ['id', 'type', 'enabled']
+ id = sql.Column(sql.String(64), primary_key=True)
+ type = sql.Column(sql.String(255))
+ enabled = sql.Column(sql.Boolean, nullable=False, default=True,
+ server_default=sqlalchemy.sql.expression.true())
+ extra = sql.Column(sql.JsonBlob())
+ endpoints = sqlalchemy.orm.relationship("Endpoint", backref="service")
+
+
+class Endpoint(sql.ModelBase, sql.DictBase):
+ __tablename__ = 'endpoint'
+ attributes = ['id', 'interface', 'region_id', 'service_id', 'url',
+ 'legacy_endpoint_id', 'enabled']
+ id = sql.Column(sql.String(64), primary_key=True)
+ legacy_endpoint_id = sql.Column(sql.String(64))
+ interface = sql.Column(sql.String(8), nullable=False)
+ region_id = sql.Column(sql.String(255),
+ sql.ForeignKey('region.id',
+ ondelete='RESTRICT'),
+ nullable=True,
+ default=None)
+ service_id = sql.Column(sql.String(64),
+ sql.ForeignKey('service.id'),
+ nullable=False)
+ url = sql.Column(sql.Text(), nullable=False)
+ enabled = sql.Column(sql.Boolean, nullable=False, default=True,
+ server_default=sqlalchemy.sql.expression.true())
+ extra = sql.Column(sql.JsonBlob())
+
+
+class Catalog(catalog.Driver):
+ # Regions
+ def list_regions(self, hints):
+ session = sql.get_session()
+ regions = session.query(Region)
+ regions = sql.filter_limit_query(Region, regions, hints)
+ return [s.to_dict() for s in list(regions)]
+
+ def _get_region(self, session, region_id):
+ ref = session.query(Region).get(region_id)
+ if not ref:
+ raise exception.RegionNotFound(region_id=region_id)
+ return ref
+
+ def _delete_child_regions(self, session, region_id, root_region_id):
+ """Delete all child regions.
+
+ Recursively delete any region that has the supplied region
+ as its parent.
+ """
+ children = session.query(Region).filter_by(parent_region_id=region_id)
+ for child in children:
+ if child.id == root_region_id:
+ # Hit a circular region hierarchy
+ return
+ self._delete_child_regions(session, child.id, root_region_id)
+ session.delete(child)
+
+ def _check_parent_region(self, session, region_ref):
+ """Raise a NotFound if the parent region does not exist.
+
+ If the region_ref has a specified parent_region_id, check that
+ the parent exists, otherwise, raise a NotFound.
+ """
+ parent_region_id = region_ref.get('parent_region_id')
+ if parent_region_id is not None:
+ # This will raise NotFound if the parent doesn't exist,
+ # which is the behavior we want.
+ self._get_region(session, parent_region_id)
+
+ def _has_endpoints(self, session, region, root_region):
+ if region.endpoints is not None and len(region.endpoints) > 0:
+ return True
+
+ q = session.query(Region)
+ q = q.filter_by(parent_region_id=region.id)
+ for child in q.all():
+ if child.id == root_region.id:
+ # Hit a circular region hierarchy
+ return False
+ if self._has_endpoints(session, child, root_region):
+ return True
+ return False
+
+ def get_region(self, region_id):
+ session = sql.get_session()
+ return self._get_region(session, region_id).to_dict()
+
+ def delete_region(self, region_id):
+ session = sql.get_session()
+ with session.begin():
+ ref = self._get_region(session, region_id)
+ if self._has_endpoints(session, ref, ref):
+ raise exception.RegionDeletionError(region_id=region_id)
+ self._delete_child_regions(session, region_id, region_id)
+ session.delete(ref)
+
+ @sql.handle_conflicts(conflict_type='region')
+ def create_region(self, region_ref):
+ session = sql.get_session()
+ with session.begin():
+ self._check_parent_region(session, region_ref)
+ region = Region.from_dict(region_ref)
+ session.add(region)
+ return region.to_dict()
+
+ def update_region(self, region_id, region_ref):
+ session = sql.get_session()
+ with session.begin():
+ self._check_parent_region(session, region_ref)
+ ref = self._get_region(session, region_id)
+ old_dict = ref.to_dict()
+ old_dict.update(region_ref)
+ self._ensure_no_circle_in_hierarchical_regions(old_dict)
+ new_region = Region.from_dict(old_dict)
+ for attr in Region.attributes:
+ if attr != 'id':
+ setattr(ref, attr, getattr(new_region, attr))
+ return ref.to_dict()
+
+ # Services
+ @sql.truncated
+ def list_services(self, hints):
+ session = sql.get_session()
+ services = session.query(Service)
+ services = sql.filter_limit_query(Service, services, hints)
+ return [s.to_dict() for s in list(services)]
+
+ def _get_service(self, session, service_id):
+ ref = session.query(Service).get(service_id)
+ if not ref:
+ raise exception.ServiceNotFound(service_id=service_id)
+ return ref
+
+ def get_service(self, service_id):
+ session = sql.get_session()
+ return self._get_service(session, service_id).to_dict()
+
+ def delete_service(self, service_id):
+ session = sql.get_session()
+ with session.begin():
+ ref = self._get_service(session, service_id)
+ session.query(Endpoint).filter_by(service_id=service_id).delete()
+ session.delete(ref)
+
+ def create_service(self, service_id, service_ref):
+ session = sql.get_session()
+ with session.begin():
+ service = Service.from_dict(service_ref)
+ session.add(service)
+ return service.to_dict()
+
+ def update_service(self, service_id, service_ref):
+ session = sql.get_session()
+ with session.begin():
+ ref = self._get_service(session, service_id)
+ old_dict = ref.to_dict()
+ old_dict.update(service_ref)
+ new_service = Service.from_dict(old_dict)
+ for attr in Service.attributes:
+ if attr != 'id':
+ setattr(ref, attr, getattr(new_service, attr))
+ ref.extra = new_service.extra
+ return ref.to_dict()
+
+ # Endpoints
+ def create_endpoint(self, endpoint_id, endpoint_ref):
+ session = sql.get_session()
+ new_endpoint = Endpoint.from_dict(endpoint_ref)
+
+ with session.begin():
+ session.add(new_endpoint)
+ return new_endpoint.to_dict()
+
+ def delete_endpoint(self, endpoint_id):
+ session = sql.get_session()
+ with session.begin():
+ ref = self._get_endpoint(session, endpoint_id)
+ session.delete(ref)
+
+ def _get_endpoint(self, session, endpoint_id):
+ try:
+ return session.query(Endpoint).filter_by(id=endpoint_id).one()
+ except sql.NotFound:
+ raise exception.EndpointNotFound(endpoint_id=endpoint_id)
+
+ def get_endpoint(self, endpoint_id):
+ session = sql.get_session()
+ return self._get_endpoint(session, endpoint_id).to_dict()
+
+ @sql.truncated
+ def list_endpoints(self, hints):
+ session = sql.get_session()
+ endpoints = session.query(Endpoint)
+ endpoints = sql.filter_limit_query(Endpoint, endpoints, hints)
+ return [e.to_dict() for e in list(endpoints)]
+
+ def update_endpoint(self, endpoint_id, endpoint_ref):
+ session = sql.get_session()
+
+ with session.begin():
+ ref = self._get_endpoint(session, endpoint_id)
+ old_dict = ref.to_dict()
+ old_dict.update(endpoint_ref)
+ new_endpoint = Endpoint.from_dict(old_dict)
+ for attr in Endpoint.attributes:
+ if attr != 'id':
+ setattr(ref, attr, getattr(new_endpoint, attr))
+ ref.extra = new_endpoint.extra
+ return ref.to_dict()
+
+ def get_catalog(self, user_id, tenant_id):
+ substitutions = dict(
+ itertools.chain(six.iteritems(CONF),
+ six.iteritems(CONF.eventlet_server)))
+ substitutions.update({'tenant_id': tenant_id, 'user_id': user_id})
+
+ session = sql.get_session()
+ endpoints = (session.query(Endpoint).
+ options(sql.joinedload(Endpoint.service)).
+ filter(Endpoint.enabled == true()).all())
+
+ catalog = {}
+
+ for endpoint in endpoints:
+ if not endpoint.service['enabled']:
+ continue
+ try:
+ url = core.format_url(endpoint['url'], substitutions)
+ except exception.MalformedEndpoint:
+ continue # this failure is already logged in format_url()
+
+ region = endpoint['region_id']
+ service_type = endpoint.service['type']
+ default_service = {
+ 'id': endpoint['id'],
+ 'name': endpoint.service.extra.get('name', ''),
+ 'publicURL': ''
+ }
+ catalog.setdefault(region, {})
+ catalog[region].setdefault(service_type, default_service)
+ interface_url = '%sURL' % endpoint['interface']
+ catalog[region][service_type][interface_url] = url
+
+ return catalog
+
+ def get_v3_catalog(self, user_id, tenant_id):
+ d = dict(
+ itertools.chain(six.iteritems(CONF),
+ six.iteritems(CONF.eventlet_server)))
+ d.update({'tenant_id': tenant_id,
+ 'user_id': user_id})
+
+ session = sql.get_session()
+ services = (session.query(Service).filter(Service.enabled == true()).
+ options(sql.joinedload(Service.endpoints)).
+ all())
+
+ def make_v3_endpoints(endpoints):
+ for endpoint in (ep.to_dict() for ep in endpoints if ep.enabled):
+ del endpoint['service_id']
+ del endpoint['legacy_endpoint_id']
+ del endpoint['enabled']
+ endpoint['region'] = endpoint['region_id']
+ try:
+ endpoint['url'] = core.format_url(endpoint['url'], d)
+ except exception.MalformedEndpoint:
+ continue # this failure is already logged in format_url()
+
+ yield endpoint
+
+ def make_v3_service(svc):
+ eps = list(make_v3_endpoints(svc.endpoints))
+ service = {'endpoints': eps, 'id': svc.id, 'type': svc.type}
+ service['name'] = svc.extra.get('name', '')
+ return service
+
+ return [make_v3_service(svc) for svc in services]
diff --git a/keystone-moon/keystone/catalog/backends/templated.py b/keystone-moon/keystone/catalog/backends/templated.py
new file mode 100644
index 00000000..d3ee105d
--- /dev/null
+++ b/keystone-moon/keystone/catalog/backends/templated.py
@@ -0,0 +1,127 @@
+# Copyright 2012 OpenStack Foundationc
+#
+# 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.
+
+import itertools
+import os.path
+
+from oslo_config import cfg
+from oslo_log import log
+import six
+
+from keystone.catalog.backends import kvs
+from keystone.catalog import core
+from keystone import exception
+from keystone.i18n import _LC
+
+
+LOG = log.getLogger(__name__)
+
+CONF = cfg.CONF
+
+
+def parse_templates(template_lines):
+ o = {}
+ for line in template_lines:
+ if ' = ' not in line:
+ continue
+
+ k, v = line.strip().split(' = ')
+ if not k.startswith('catalog.'):
+ continue
+
+ parts = k.split('.')
+
+ region = parts[1]
+ # NOTE(termie): object-store insists on having a dash
+ service = parts[2].replace('_', '-')
+ key = parts[3]
+
+ region_ref = o.get(region, {})
+ service_ref = region_ref.get(service, {})
+ service_ref[key] = v
+
+ region_ref[service] = service_ref
+ o[region] = region_ref
+
+ return o
+
+
+class Catalog(kvs.Catalog):
+ """A backend that generates endpoints for the Catalog based on templates.
+
+ It is usually configured via config entries that look like:
+
+ catalog.$REGION.$SERVICE.$key = $value
+
+ and is stored in a similar looking hierarchy. Where a value can contain
+ values to be interpolated by standard python string interpolation that look
+ like (the % is replaced by a $ due to paste attempting to interpolate on
+ its own:
+
+ http://localhost:$(public_port)s/
+
+ When expanding the template it will pass in a dict made up of the conf
+ instance plus a few additional key-values, notably tenant_id and user_id.
+
+ It does not care what the keys and values are but it is worth noting that
+ keystone_compat will expect certain keys to be there so that it can munge
+ them into the output format keystone expects. These keys are:
+
+ name - the name of the service, most likely repeated for all services of
+ the same type, across regions.
+
+ adminURL - the url of the admin endpoint
+
+ publicURL - the url of the public endpoint
+
+ internalURL - the url of the internal endpoint
+
+ """
+
+ def __init__(self, templates=None):
+ super(Catalog, self).__init__()
+ if templates:
+ self.templates = templates
+ else:
+ template_file = CONF.catalog.template_file
+ if not os.path.exists(template_file):
+ template_file = CONF.find_file(template_file)
+ self._load_templates(template_file)
+
+ def _load_templates(self, template_file):
+ try:
+ self.templates = parse_templates(open(template_file))
+ except IOError:
+ LOG.critical(_LC('Unable to open template file %s'), template_file)
+ raise
+
+ def get_catalog(self, user_id, tenant_id):
+ substitutions = dict(
+ itertools.chain(six.iteritems(CONF),
+ six.iteritems(CONF.eventlet_server)))
+ substitutions.update({'tenant_id': tenant_id, 'user_id': user_id})
+
+ catalog = {}
+ for region, region_ref in six.iteritems(self.templates):
+ catalog[region] = {}
+ for service, service_ref in six.iteritems(region_ref):
+ service_data = {}
+ try:
+ for k, v in six.iteritems(service_ref):
+ service_data[k] = core.format_url(v, substitutions)
+ except exception.MalformedEndpoint:
+ continue # this failure is already logged in format_url()
+ catalog[region][service] = service_data
+
+ return catalog
diff --git a/keystone-moon/keystone/catalog/controllers.py b/keystone-moon/keystone/catalog/controllers.py
new file mode 100644
index 00000000..3518c4bf
--- /dev/null
+++ b/keystone-moon/keystone/catalog/controllers.py
@@ -0,0 +1,336 @@
+# Copyright 2012 OpenStack Foundation
+# Copyright 2012 Canonical Ltd.
+#
+# 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.
+
+import uuid
+
+import six
+
+from keystone.catalog import schema
+from keystone.common import controller
+from keystone.common import dependency
+from keystone.common import validation
+from keystone.common import wsgi
+from keystone import exception
+from keystone.i18n import _
+from keystone import notifications
+
+
+INTERFACES = ['public', 'internal', 'admin']
+
+
+@dependency.requires('catalog_api')
+class Service(controller.V2Controller):
+
+ @controller.v2_deprecated
+ def get_services(self, context):
+ self.assert_admin(context)
+ service_list = self.catalog_api.list_services()
+ return {'OS-KSADM:services': service_list}
+
+ @controller.v2_deprecated
+ def get_service(self, context, service_id):
+ self.assert_admin(context)
+ service_ref = self.catalog_api.get_service(service_id)
+ return {'OS-KSADM:service': service_ref}
+
+ @controller.v2_deprecated
+ def delete_service(self, context, service_id):
+ self.assert_admin(context)
+ self.catalog_api.delete_service(service_id)
+
+ @controller.v2_deprecated
+ def create_service(self, context, OS_KSADM_service):
+ self.assert_admin(context)
+ service_id = uuid.uuid4().hex
+ service_ref = OS_KSADM_service.copy()
+ service_ref['id'] = service_id
+ new_service_ref = self.catalog_api.create_service(
+ service_id, service_ref)
+ return {'OS-KSADM:service': new_service_ref}
+
+
+@dependency.requires('catalog_api')
+class Endpoint(controller.V2Controller):
+
+ @controller.v2_deprecated
+ def get_endpoints(self, context):
+ """Merge matching v3 endpoint refs into legacy refs."""
+ self.assert_admin(context)
+ legacy_endpoints = {}
+ for endpoint in self.catalog_api.list_endpoints():
+ if not endpoint.get('legacy_endpoint_id'):
+ # endpoints created in v3 should not appear on the v2 API
+ continue
+
+ # is this is a legacy endpoint we haven't indexed yet?
+ if endpoint['legacy_endpoint_id'] not in legacy_endpoints:
+ legacy_ep = endpoint.copy()
+ legacy_ep['id'] = legacy_ep.pop('legacy_endpoint_id')
+ legacy_ep.pop('interface')
+ legacy_ep.pop('url')
+ legacy_ep['region'] = legacy_ep.pop('region_id')
+
+ legacy_endpoints[endpoint['legacy_endpoint_id']] = legacy_ep
+ else:
+ legacy_ep = legacy_endpoints[endpoint['legacy_endpoint_id']]
+
+ # add the legacy endpoint with an interface url
+ legacy_ep['%surl' % endpoint['interface']] = endpoint['url']
+ return {'endpoints': legacy_endpoints.values()}
+
+ @controller.v2_deprecated
+ def create_endpoint(self, context, endpoint):
+ """Create three v3 endpoint refs based on a legacy ref."""
+ self.assert_admin(context)
+
+ # according to the v2 spec publicurl is mandatory
+ self._require_attribute(endpoint, 'publicurl')
+ # service_id is necessary
+ self._require_attribute(endpoint, 'service_id')
+
+ initiator = notifications._get_request_audit_info(context)
+
+ if endpoint.get('region') is not None:
+ try:
+ self.catalog_api.get_region(endpoint['region'])
+ except exception.RegionNotFound:
+ region = dict(id=endpoint['region'])
+ self.catalog_api.create_region(region, initiator)
+
+ legacy_endpoint_ref = endpoint.copy()
+
+ urls = {}
+ for i in INTERFACES:
+ # remove all urls so they aren't persisted them more than once
+ url = '%surl' % i
+ if endpoint.get(url):
+ # valid urls need to be persisted
+ urls[i] = endpoint.pop(url)
+ elif url in endpoint:
+ # null or empty urls can be discarded
+ endpoint.pop(url)
+ legacy_endpoint_ref.pop(url)
+
+ legacy_endpoint_id = uuid.uuid4().hex
+ for interface, url in six.iteritems(urls):
+ endpoint_ref = endpoint.copy()
+ endpoint_ref['id'] = uuid.uuid4().hex
+ endpoint_ref['legacy_endpoint_id'] = legacy_endpoint_id
+ endpoint_ref['interface'] = interface
+ endpoint_ref['url'] = url
+ endpoint_ref['region_id'] = endpoint_ref.pop('region')
+ self.catalog_api.create_endpoint(endpoint_ref['id'], endpoint_ref,
+ initiator)
+
+ legacy_endpoint_ref['id'] = legacy_endpoint_id
+ return {'endpoint': legacy_endpoint_ref}
+
+ @controller.v2_deprecated
+ def delete_endpoint(self, context, endpoint_id):
+ """Delete up to three v3 endpoint refs based on a legacy ref ID."""
+ self.assert_admin(context)
+
+ deleted_at_least_one = False
+ for endpoint in self.catalog_api.list_endpoints():
+ if endpoint['legacy_endpoint_id'] == endpoint_id:
+ self.catalog_api.delete_endpoint(endpoint['id'])
+ deleted_at_least_one = True
+
+ if not deleted_at_least_one:
+ raise exception.EndpointNotFound(endpoint_id=endpoint_id)
+
+
+@dependency.requires('catalog_api')
+class RegionV3(controller.V3Controller):
+ collection_name = 'regions'
+ member_name = 'region'
+
+ def create_region_with_id(self, context, region_id, region):
+ """Create a region with a user-specified ID.
+
+ This method is unprotected because it depends on ``self.create_region``
+ to enforce policy.
+ """
+ if 'id' in region and region_id != region['id']:
+ raise exception.ValidationError(
+ _('Conflicting region IDs specified: '
+ '"%(url_id)s" != "%(ref_id)s"') % {
+ 'url_id': region_id,
+ 'ref_id': region['id']})
+ region['id'] = region_id
+ return self.create_region(context, region)
+
+ @controller.protected()
+ @validation.validated(schema.region_create, 'region')
+ def create_region(self, context, region):
+ ref = self._normalize_dict(region)
+
+ if not ref.get('id'):
+ ref = self._assign_unique_id(ref)
+
+ initiator = notifications._get_request_audit_info(context)
+ ref = self.catalog_api.create_region(ref, initiator)
+ return wsgi.render_response(
+ RegionV3.wrap_member(context, ref),
+ status=(201, 'Created'))
+
+ @controller.filterprotected('parent_region_id')
+ def list_regions(self, context, filters):
+ hints = RegionV3.build_driver_hints(context, filters)
+ refs = self.catalog_api.list_regions(hints)
+ return RegionV3.wrap_collection(context, refs, hints=hints)
+
+ @controller.protected()
+ def get_region(self, context, region_id):
+ ref = self.catalog_api.get_region(region_id)
+ return RegionV3.wrap_member(context, ref)
+
+ @controller.protected()
+ @validation.validated(schema.region_update, 'region')
+ def update_region(self, context, region_id, region):
+ self._require_matching_id(region_id, region)
+ initiator = notifications._get_request_audit_info(context)
+ ref = self.catalog_api.update_region(region_id, region, initiator)
+ return RegionV3.wrap_member(context, ref)
+
+ @controller.protected()
+ def delete_region(self, context, region_id):
+ initiator = notifications._get_request_audit_info(context)
+ return self.catalog_api.delete_region(region_id, initiator)
+
+
+@dependency.requires('catalog_api')
+class ServiceV3(controller.V3Controller):
+ collection_name = 'services'
+ member_name = 'service'
+
+ def __init__(self):
+ super(ServiceV3, self).__init__()
+ self.get_member_from_driver = self.catalog_api.get_service
+
+ @controller.protected()
+ @validation.validated(schema.service_create, 'service')
+ def create_service(self, context, service):
+ ref = self._assign_unique_id(self._normalize_dict(service))
+ initiator = notifications._get_request_audit_info(context)
+ ref = self.catalog_api.create_service(ref['id'], ref, initiator)
+ return ServiceV3.wrap_member(context, ref)
+
+ @controller.filterprotected('type', 'name')
+ def list_services(self, context, filters):
+ hints = ServiceV3.build_driver_hints(context, filters)
+ refs = self.catalog_api.list_services(hints=hints)
+ return ServiceV3.wrap_collection(context, refs, hints=hints)
+
+ @controller.protected()
+ def get_service(self, context, service_id):
+ ref = self.catalog_api.get_service(service_id)
+ return ServiceV3.wrap_member(context, ref)
+
+ @controller.protected()
+ @validation.validated(schema.service_update, 'service')
+ def update_service(self, context, service_id, service):
+ self._require_matching_id(service_id, service)
+ initiator = notifications._get_request_audit_info(context)
+ ref = self.catalog_api.update_service(service_id, service, initiator)
+ return ServiceV3.wrap_member(context, ref)
+
+ @controller.protected()
+ def delete_service(self, context, service_id):
+ initiator = notifications._get_request_audit_info(context)
+ return self.catalog_api.delete_service(service_id, initiator)
+
+
+@dependency.requires('catalog_api')
+class EndpointV3(controller.V3Controller):
+ collection_name = 'endpoints'
+ member_name = 'endpoint'
+
+ def __init__(self):
+ super(EndpointV3, self).__init__()
+ self.get_member_from_driver = self.catalog_api.get_endpoint
+
+ @classmethod
+ def filter_endpoint(cls, ref):
+ if 'legacy_endpoint_id' in ref:
+ ref.pop('legacy_endpoint_id')
+ ref['region'] = ref['region_id']
+ return ref
+
+ @classmethod
+ def wrap_member(cls, context, ref):
+ ref = cls.filter_endpoint(ref)
+ return super(EndpointV3, cls).wrap_member(context, ref)
+
+ def _validate_endpoint_region(self, endpoint, context=None):
+ """Ensure the region for the endpoint exists.
+
+ If 'region_id' is used to specify the region, then we will let the
+ manager/driver take care of this. If, however, 'region' is used,
+ then for backward compatibility, we will auto-create the region.
+
+ """
+ if (endpoint.get('region_id') is None and
+ endpoint.get('region') is not None):
+ # To maintain backward compatibility with clients that are
+ # using the v3 API in the same way as they used the v2 API,
+ # create the endpoint region, if that region does not exist
+ # in keystone.
+ endpoint['region_id'] = endpoint.pop('region')
+ try:
+ self.catalog_api.get_region(endpoint['region_id'])
+ except exception.RegionNotFound:
+ region = dict(id=endpoint['region_id'])
+ initiator = notifications._get_request_audit_info(context)
+ self.catalog_api.create_region(region, initiator)
+
+ return endpoint
+
+ @controller.protected()
+ @validation.validated(schema.endpoint_create, 'endpoint')
+ def create_endpoint(self, context, endpoint):
+ ref = self._assign_unique_id(self._normalize_dict(endpoint))
+ ref = self._validate_endpoint_region(ref, context)
+ initiator = notifications._get_request_audit_info(context)
+ ref = self.catalog_api.create_endpoint(ref['id'], ref, initiator)
+ return EndpointV3.wrap_member(context, ref)
+
+ @controller.filterprotected('interface', 'service_id')
+ def list_endpoints(self, context, filters):
+ hints = EndpointV3.build_driver_hints(context, filters)
+ refs = self.catalog_api.list_endpoints(hints=hints)
+ return EndpointV3.wrap_collection(context, refs, hints=hints)
+
+ @controller.protected()
+ def get_endpoint(self, context, endpoint_id):
+ ref = self.catalog_api.get_endpoint(endpoint_id)
+ return EndpointV3.wrap_member(context, ref)
+
+ @controller.protected()
+ @validation.validated(schema.endpoint_update, 'endpoint')
+ def update_endpoint(self, context, endpoint_id, endpoint):
+ self._require_matching_id(endpoint_id, endpoint)
+
+ endpoint = self._validate_endpoint_region(endpoint.copy(), context)
+
+ initiator = notifications._get_request_audit_info(context)
+ ref = self.catalog_api.update_endpoint(endpoint_id, endpoint,
+ initiator)
+ return EndpointV3.wrap_member(context, ref)
+
+ @controller.protected()
+ def delete_endpoint(self, context, endpoint_id):
+ initiator = notifications._get_request_audit_info(context)
+ return self.catalog_api.delete_endpoint(endpoint_id, initiator)
diff --git a/keystone-moon/keystone/catalog/core.py b/keystone-moon/keystone/catalog/core.py
new file mode 100644
index 00000000..fba26b89
--- /dev/null
+++ b/keystone-moon/keystone/catalog/core.py
@@ -0,0 +1,506 @@
+# Copyright 2012 OpenStack Foundation
+# Copyright 2012 Canonical Ltd.
+#
+# 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.
+
+"""Main entry point into the Catalog service."""
+
+import abc
+
+from oslo_config import cfg
+from oslo_log import log
+import six
+
+from keystone.common import cache
+from keystone.common import dependency
+from keystone.common import driver_hints
+from keystone.common import manager
+from keystone.common import utils
+from keystone import exception
+from keystone.i18n import _
+from keystone.i18n import _LE
+from keystone import notifications
+
+
+CONF = cfg.CONF
+LOG = log.getLogger(__name__)
+MEMOIZE = cache.get_memoization_decorator(section='catalog')
+
+
+def format_url(url, substitutions):
+ """Formats a user-defined URL with the given substitutions.
+
+ :param string url: the URL to be formatted
+ :param dict substitutions: the dictionary used for substitution
+ :returns: a formatted URL
+
+ """
+
+ WHITELISTED_PROPERTIES = [
+ 'tenant_id', 'user_id', 'public_bind_host', 'admin_bind_host',
+ 'compute_host', 'compute_port', 'admin_port', 'public_port',
+ 'public_endpoint', 'admin_endpoint', ]
+
+ substitutions = utils.WhiteListedItemFilter(
+ WHITELISTED_PROPERTIES,
+ substitutions)
+ try:
+ result = url.replace('$(', '%(') % substitutions
+ except AttributeError:
+ LOG.error(_LE('Malformed endpoint - %(url)r is not a string'),
+ {"url": url})
+ raise exception.MalformedEndpoint(endpoint=url)
+ except KeyError as e:
+ LOG.error(_LE("Malformed endpoint %(url)s - unknown key %(keyerror)s"),
+ {"url": url,
+ "keyerror": e})
+ raise exception.MalformedEndpoint(endpoint=url)
+ except TypeError as e:
+ LOG.error(_LE("Malformed endpoint '%(url)s'. The following type error "
+ "occurred during string substitution: %(typeerror)s"),
+ {"url": url,
+ "typeerror": e})
+ raise exception.MalformedEndpoint(endpoint=url)
+ except ValueError as e:
+ LOG.error(_LE("Malformed endpoint %s - incomplete format "
+ "(are you missing a type notifier ?)"), url)
+ raise exception.MalformedEndpoint(endpoint=url)
+ return result
+
+
+@dependency.provider('catalog_api')
+class Manager(manager.Manager):
+ """Default pivot point for the Catalog backend.
+
+ See :mod:`keystone.common.manager.Manager` for more details on how this
+ dynamically calls the backend.
+
+ """
+ _ENDPOINT = 'endpoint'
+ _SERVICE = 'service'
+ _REGION = 'region'
+
+ def __init__(self):
+ super(Manager, self).__init__(CONF.catalog.driver)
+
+ def create_region(self, region_ref, initiator=None):
+ # Check duplicate ID
+ try:
+ self.get_region(region_ref['id'])
+ except exception.RegionNotFound:
+ pass
+ else:
+ msg = _('Duplicate ID, %s.') % region_ref['id']
+ raise exception.Conflict(type='region', details=msg)
+
+ # NOTE(lbragstad): The description column of the region database
+ # can not be null. So if the user doesn't pass in a description then
+ # set it to an empty string.
+ region_ref.setdefault('description', '')
+ try:
+ ret = self.driver.create_region(region_ref)
+ except exception.NotFound:
+ parent_region_id = region_ref.get('parent_region_id')
+ raise exception.RegionNotFound(region_id=parent_region_id)
+
+ notifications.Audit.created(self._REGION, ret['id'], initiator)
+ return ret
+
+ @MEMOIZE
+ def get_region(self, region_id):
+ try:
+ return self.driver.get_region(region_id)
+ except exception.NotFound:
+ raise exception.RegionNotFound(region_id=region_id)
+
+ def update_region(self, region_id, region_ref, initiator=None):
+ ref = self.driver.update_region(region_id, region_ref)
+ notifications.Audit.updated(self._REGION, region_id, initiator)
+ self.get_region.invalidate(self, region_id)
+ return ref
+
+ def delete_region(self, region_id, initiator=None):
+ try:
+ ret = self.driver.delete_region(region_id)
+ notifications.Audit.deleted(self._REGION, region_id, initiator)
+ self.get_region.invalidate(self, region_id)
+ return ret
+ except exception.NotFound:
+ raise exception.RegionNotFound(region_id=region_id)
+
+ @manager.response_truncated
+ def list_regions(self, hints=None):
+ return self.driver.list_regions(hints or driver_hints.Hints())
+
+ def create_service(self, service_id, service_ref, initiator=None):
+ service_ref.setdefault('enabled', True)
+ service_ref.setdefault('name', '')
+ ref = self.driver.create_service(service_id, service_ref)
+ notifications.Audit.created(self._SERVICE, service_id, initiator)
+ return ref
+
+ @MEMOIZE
+ def get_service(self, service_id):
+ try:
+ return self.driver.get_service(service_id)
+ except exception.NotFound:
+ raise exception.ServiceNotFound(service_id=service_id)
+
+ def update_service(self, service_id, service_ref, initiator=None):
+ ref = self.driver.update_service(service_id, service_ref)
+ notifications.Audit.updated(self._SERVICE, service_id, initiator)
+ self.get_service.invalidate(self, service_id)
+ return ref
+
+ def delete_service(self, service_id, initiator=None):
+ try:
+ endpoints = self.list_endpoints()
+ ret = self.driver.delete_service(service_id)
+ notifications.Audit.deleted(self._SERVICE, service_id, initiator)
+ self.get_service.invalidate(self, service_id)
+ for endpoint in endpoints:
+ if endpoint['service_id'] == service_id:
+ self.get_endpoint.invalidate(self, endpoint['id'])
+ return ret
+ except exception.NotFound:
+ raise exception.ServiceNotFound(service_id=service_id)
+
+ @manager.response_truncated
+ def list_services(self, hints=None):
+ return self.driver.list_services(hints or driver_hints.Hints())
+
+ def _assert_region_exists(self, region_id):
+ try:
+ if region_id is not None:
+ self.get_region(region_id)
+ except exception.RegionNotFound:
+ raise exception.ValidationError(attribute='endpoint region_id',
+ target='region table')
+
+ def _assert_service_exists(self, service_id):
+ try:
+ if service_id is not None:
+ self.get_service(service_id)
+ except exception.ServiceNotFound:
+ raise exception.ValidationError(attribute='endpoint service_id',
+ target='service table')
+
+ def create_endpoint(self, endpoint_id, endpoint_ref, initiator=None):
+ self._assert_region_exists(endpoint_ref.get('region_id'))
+ self._assert_service_exists(endpoint_ref['service_id'])
+ ref = self.driver.create_endpoint(endpoint_id, endpoint_ref)
+
+ notifications.Audit.created(self._ENDPOINT, endpoint_id, initiator)
+ return ref
+
+ def update_endpoint(self, endpoint_id, endpoint_ref, initiator=None):
+ self._assert_region_exists(endpoint_ref.get('region_id'))
+ self._assert_service_exists(endpoint_ref.get('service_id'))
+ ref = self.driver.update_endpoint(endpoint_id, endpoint_ref)
+ notifications.Audit.updated(self._ENDPOINT, endpoint_id, initiator)
+ self.get_endpoint.invalidate(self, endpoint_id)
+ return ref
+
+ def delete_endpoint(self, endpoint_id, initiator=None):
+ try:
+ ret = self.driver.delete_endpoint(endpoint_id)
+ notifications.Audit.deleted(self._ENDPOINT, endpoint_id, initiator)
+ self.get_endpoint.invalidate(self, endpoint_id)
+ return ret
+ except exception.NotFound:
+ raise exception.EndpointNotFound(endpoint_id=endpoint_id)
+
+ @MEMOIZE
+ def get_endpoint(self, endpoint_id):
+ try:
+ return self.driver.get_endpoint(endpoint_id)
+ except exception.NotFound:
+ raise exception.EndpointNotFound(endpoint_id=endpoint_id)
+
+ @manager.response_truncated
+ def list_endpoints(self, hints=None):
+ return self.driver.list_endpoints(hints or driver_hints.Hints())
+
+ def get_catalog(self, user_id, tenant_id):
+ try:
+ return self.driver.get_catalog(user_id, tenant_id)
+ except exception.NotFound:
+ raise exception.NotFound('Catalog not found for user and tenant')
+
+
+@six.add_metaclass(abc.ABCMeta)
+class Driver(object):
+ """Interface description for an Catalog driver."""
+
+ def _get_list_limit(self):
+ return CONF.catalog.list_limit or CONF.list_limit
+
+ def _ensure_no_circle_in_hierarchical_regions(self, region_ref):
+ if region_ref.get('parent_region_id') is None:
+ return
+
+ root_region_id = region_ref['id']
+ parent_region_id = region_ref['parent_region_id']
+
+ while parent_region_id:
+ # NOTE(wanghong): check before getting parent region can ensure no
+ # self circle
+ if parent_region_id == root_region_id:
+ raise exception.CircularRegionHierarchyError(
+ parent_region_id=parent_region_id)
+ parent_region = self.get_region(parent_region_id)
+ parent_region_id = parent_region.get('parent_region_id')
+
+ @abc.abstractmethod
+ def create_region(self, region_ref):
+ """Creates a new region.
+
+ :raises: keystone.exception.Conflict
+ :raises: keystone.exception.RegionNotFound (if parent region invalid)
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def list_regions(self, hints):
+ """List all regions.
+
+ :param hints: contains the list of filters yet to be satisfied.
+ Any filters satisfied here will be removed so that
+ the caller will know if any filters remain.
+
+ :returns: list of region_refs or an empty list.
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def get_region(self, region_id):
+ """Get region by id.
+
+ :returns: region_ref dict
+ :raises: keystone.exception.RegionNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def update_region(self, region_id, region_ref):
+ """Update region by id.
+
+ :returns: region_ref dict
+ :raises: keystone.exception.RegionNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def delete_region(self, region_id):
+ """Deletes an existing region.
+
+ :raises: keystone.exception.RegionNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def create_service(self, service_id, service_ref):
+ """Creates a new service.
+
+ :raises: keystone.exception.Conflict
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def list_services(self, hints):
+ """List all services.
+
+ :param hints: contains the list of filters yet to be satisfied.
+ Any filters satisfied here will be removed so that
+ the caller will know if any filters remain.
+
+ :returns: list of service_refs or an empty list.
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def get_service(self, service_id):
+ """Get service by id.
+
+ :returns: service_ref dict
+ :raises: keystone.exception.ServiceNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def update_service(self, service_id, service_ref):
+ """Update service by id.
+
+ :returns: service_ref dict
+ :raises: keystone.exception.ServiceNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def delete_service(self, service_id):
+ """Deletes an existing service.
+
+ :raises: keystone.exception.ServiceNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def create_endpoint(self, endpoint_id, endpoint_ref):
+ """Creates a new endpoint for a service.
+
+ :raises: keystone.exception.Conflict,
+ keystone.exception.ServiceNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def get_endpoint(self, endpoint_id):
+ """Get endpoint by id.
+
+ :returns: endpoint_ref dict
+ :raises: keystone.exception.EndpointNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def list_endpoints(self, hints):
+ """List all endpoints.
+
+ :param hints: contains the list of filters yet to be satisfied.
+ Any filters satisfied here will be removed so that
+ the caller will know if any filters remain.
+
+ :returns: list of endpoint_refs or an empty list.
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def update_endpoint(self, endpoint_id, endpoint_ref):
+ """Get endpoint by id.
+
+ :returns: endpoint_ref dict
+ :raises: keystone.exception.EndpointNotFound
+ keystone.exception.ServiceNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def delete_endpoint(self, endpoint_id):
+ """Deletes an endpoint for a service.
+
+ :raises: keystone.exception.EndpointNotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ @abc.abstractmethod
+ def get_catalog(self, user_id, tenant_id):
+ """Retrieve and format the current service catalog.
+
+ Example::
+
+ { 'RegionOne':
+ {'compute': {
+ 'adminURL': u'http://host:8774/v1.1/tenantid',
+ 'internalURL': u'http://host:8774/v1.1/tenant_id',
+ 'name': 'Compute Service',
+ 'publicURL': u'http://host:8774/v1.1/tenantid'},
+ 'ec2': {
+ 'adminURL': 'http://host:8773/services/Admin',
+ 'internalURL': 'http://host:8773/services/Cloud',
+ 'name': 'EC2 Service',
+ 'publicURL': 'http://host:8773/services/Cloud'}}
+
+ :returns: A nested dict representing the service catalog or an
+ empty dict.
+ :raises: keystone.exception.NotFound
+
+ """
+ raise exception.NotImplemented() # pragma: no cover
+
+ def get_v3_catalog(self, user_id, tenant_id):
+ """Retrieve and format the current V3 service catalog.
+
+ The default implementation builds the V3 catalog from the V2 catalog.
+
+ Example::
+
+ [
+ {
+ "endpoints": [
+ {
+ "interface": "public",
+ "id": "--endpoint-id--",
+ "region": "RegionOne",
+ "url": "http://external:8776/v1/--project-id--"
+ },
+ {
+ "interface": "internal",
+ "id": "--endpoint-id--",
+ "region": "RegionOne",
+ "url": "http://internal:8776/v1/--project-id--"
+ }],
+ "id": "--service-id--",
+ "type": "volume"
+ }]
+
+ :returns: A list representing the service catalog or an empty list
+ :raises: keystone.exception.NotFound
+
+ """
+ v2_catalog = self.get_catalog(user_id, tenant_id)
+ v3_catalog = []
+
+ for region_name, region in six.iteritems(v2_catalog):
+ for service_type, service in six.iteritems(region):
+ service_v3 = {
+ 'type': service_type,
+ 'endpoints': []
+ }
+
+ for attr, value in six.iteritems(service):
+ # Attributes that end in URL are interfaces. In the V2
+ # catalog, these are internalURL, publicURL, and adminURL.
+ # For example, <region_name>.publicURL=<URL> in the V2
+ # catalog becomes the V3 interface for the service:
+ # { 'interface': 'public', 'url': '<URL>', 'region':
+ # 'region: '<region_name>' }
+ if attr.endswith('URL'):
+ v3_interface = attr[:-len('URL')]
+ service_v3['endpoints'].append({
+ 'interface': v3_interface,
+ 'region': region_name,
+ 'url': value,
+ })
+ continue
+
+ # Other attributes are copied to the service.
+ service_v3[attr] = value
+
+ v3_catalog.append(service_v3)
+
+ return v3_catalog
diff --git a/keystone-moon/keystone/catalog/routers.py b/keystone-moon/keystone/catalog/routers.py
new file mode 100644
index 00000000..f3bd988b
--- /dev/null
+++ b/keystone-moon/keystone/catalog/routers.py
@@ -0,0 +1,40 @@
+# Copyright 2012 OpenStack Foundation
+#
+# 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 keystone.catalog import controllers
+from keystone.common import router
+from keystone.common import wsgi
+
+
+class Routers(wsgi.RoutersBase):
+
+ def append_v3_routers(self, mapper, routers):
+ regions_controller = controllers.RegionV3()
+ routers.append(router.Router(regions_controller,
+ 'regions', 'region',
+ resource_descriptions=self.v3_resources))
+
+ # Need to add an additional route to support PUT /regions/{region_id}
+ mapper.connect(
+ '/regions/{region_id}',
+ controller=regions_controller,
+ action='create_region_with_id',
+ conditions=dict(method=['PUT']))
+
+ routers.append(router.Router(controllers.ServiceV3(),
+ 'services', 'service',
+ resource_descriptions=self.v3_resources))
+ routers.append(router.Router(controllers.EndpointV3(),
+ 'endpoints', 'endpoint',
+ resource_descriptions=self.v3_resources))
diff --git a/keystone-moon/keystone/catalog/schema.py b/keystone-moon/keystone/catalog/schema.py
new file mode 100644
index 00000000..a779ad02
--- /dev/null
+++ b/keystone-moon/keystone/catalog/schema.py
@@ -0,0 +1,96 @@
+# 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 keystone.common.validation import parameter_types
+
+
+_region_properties = {
+ 'description': parameter_types.description,
+ # NOTE(lbragstad): Regions use ID differently. The user can specify the ID
+ # or it will be generated automatically.
+ 'id': {
+ 'type': 'string'
+ },
+ 'parent_region_id': {
+ 'type': ['string', 'null']
+ }
+}
+
+region_create = {
+ 'type': 'object',
+ 'properties': _region_properties,
+ 'additionalProperties': True
+ # NOTE(lbragstad): No parameters are required for creating regions.
+}
+
+region_update = {
+ 'type': 'object',
+ 'properties': _region_properties,
+ 'minProperties': 1,
+ 'additionalProperties': True
+}
+
+_service_properties = {
+ 'enabled': parameter_types.boolean,
+ 'name': parameter_types.name,
+ 'type': {
+ 'type': 'string',
+ 'minLength': 1,
+ 'maxLength': 255
+ }
+}
+
+service_create = {
+ 'type': 'object',
+ 'properties': _service_properties,
+ 'required': ['type'],
+ 'additionalProperties': True,
+}
+
+service_update = {
+ 'type': 'object',
+ 'properties': _service_properties,
+ 'minProperties': 1,
+ 'additionalProperties': True
+}
+
+_endpoint_properties = {
+ 'enabled': parameter_types.boolean,
+ 'interface': {
+ 'type': 'string',
+ 'enum': ['admin', 'internal', 'public']
+ },
+ 'region_id': {
+ 'type': 'string'
+ },
+ 'region': {
+ 'type': 'string'
+ },
+ 'service_id': {
+ 'type': 'string'
+ },
+ 'url': parameter_types.url
+}
+
+endpoint_create = {
+ 'type': 'object',
+ 'properties': _endpoint_properties,
+ 'required': ['interface', 'service_id', 'url'],
+ 'additionalProperties': True
+}
+
+endpoint_update = {
+ 'type': 'object',
+ 'properties': _endpoint_properties,
+ 'minProperties': 1,
+ 'additionalProperties': True
+}