The RESTAPI of resource protectables

Change-Id: I690d88a92c31e7567110f5fd8d90cc8a4d42868d
Closes-Bug: #1550305
This commit is contained in:
chenying 2016-02-26 20:15:41 +08:00 committed by Eran Gampel
parent 62d11cc0cc
commit 97621c9c9e
8 changed files with 475 additions and 1 deletions

View File

@ -14,5 +14,8 @@
"restore:create": "rule:admin_or_owner",
"restore:update": "rule:admin_or_owner",
"restore:get": "rule:admin_or_owner",
"restore:get_all": "rule:admin_or_owner"
"restore:get_all": "rule:admin_or_owner",
"protectable:get": "rule:admin_or_owner",
"protectable:get_all": "rule:admin_or_owner"
}

View File

@ -0,0 +1,253 @@
# 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.
"""The protectables api."""
from oslo_config import cfg
from oslo_log import log as logging
from webob import exc
from smaug.api import common
from smaug.api.openstack import wsgi
from smaug import exception
from smaug.i18n import _, _LI
import smaug.policy
from smaug.services.protection import api as protection_api
from smaug import utils
import six
query_instance_filters_opt = \
cfg.ListOpt('query_instance_filters',
default=['status'],
help="Instance filter options which "
"non-admin user could use to "
"query instances. Default values "
"are: ['status']")
CONF = cfg.CONF
CONF.register_opt(query_instance_filters_opt)
LOG = logging.getLogger(__name__)
def check_policy(context, action):
target = {
'project_id': context.project_id,
'user_id': context.user_id,
}
_action = 'protectable:%s' % action
smaug.policy.enforce(context, _action, target)
class ProtectableViewBuilder(common.ViewBuilder):
"""Model a server API response as a python dictionary."""
_collection_name = "protectables"
def __init__(self):
"""Initialize view builder."""
super(ProtectableViewBuilder, self).__init__()
def show(self, request, protectable_type):
"""Detailed view of a single protectable_type."""
protectable_type_ref = {
'protectable_type': {
'name': protectable_type.get('name'),
'dependent_types': protectable_type.get('dependent_types'),
}
}
return protectable_type_ref
def detail(self, request, instance):
"""Detailed view of a single instance."""
instance_ref = {
'instance': {
'id': instance.get('id'),
'type': instance.get('type'),
'dependent_resources': instance.get('dependent_resources'),
}
}
return instance_ref
def detail_list(self, request, instances, instance_count=None):
"""Detailed view of a list of instances."""
return self._list_view(self.detail, request, instances,
instance_count,
'instances')
def _list_view(self, func, request, instances, instance_count,
coll_name=_collection_name):
"""Provide a view for a list of instance.
:param func: Function used to format the instance data
:param request: API request
:param instances: List of instances in dictionary format
:param instance_count: Length of the original list of instances
:param coll_name: Name of collection, used to generate the next link
for a pagination query
:returns: instance data in dictionary format
"""
instances_list = [func(request, instance)['instance']
for instance in instances]
instances_links = self._get_collection_links(request,
instances,
coll_name,
instance_count)
instances_dict = {
"instances": instances_list
}
if instances_links:
instances_dict['instances_links'] = instances_links
return instances_dict
class ProtectablesController(wsgi.Controller):
"""The Protectables API controller for the OpenStack API."""
_view_builder_class = ProtectableViewBuilder
def __init__(self):
self.protection_api = protection_api.API()
super(ProtectablesController, self).__init__()
def show(self, req, id):
"""Return data about the given protectable_type."""
context = req.environ['smaug.context']
protectable_type = id
LOG.info(_LI("Show the information of a given"
" protectable type: %s"), protectable_type)
protectable_types = self._get_all(context)
if protectable_type not in protectable_types:
msg = _("Invalid protectable type provided.")
raise exception.InvalidInput(reason=msg)
check_policy(context, 'get')
try:
retval_protectable_type = self.protection_api.\
show_protectable_type(context, protectable_type)
except exception.ProtectableTypeNotFound as error:
raise exc.HTTPNotFound(explanation=error.msg)
LOG.info(_LI("Show the protectable type information"
" issued successfully."))
return self._view_builder.show(req, retval_protectable_type)
def index(self, req):
"""Returns a list of protectable_types,
transformed through view builder.
"""
context = req.environ['smaug.context']
LOG.info(_LI("Show protectable type list"), context=context)
protectable_types = self._get_all(context)
retval_protectable_types = {
"protectable_type": protectable_types
}
LOG.info(_LI("Show protectable type list request issued"
" successfully."))
return retval_protectable_types
def _get_all(self, context):
check_policy(context, 'get_all')
protectable_types = self.protection_api.list_protectable_types(context)
LOG.info(_LI("Get all protectable types completed successfully."))
return protectable_types
def instances_index(self, req, protectable_type):
"""Return data about the given protectable_type."""
context = req.environ['smaug.context']
LOG.info(_LI("Show the instances of a given"
" protectable type: %s"), protectable_type)
params = req.params.copy()
marker, limit, offset = common.get_pagination_params(params)
sort_keys, sort_dirs = common.get_sort_params(params)
filters = params
utils.remove_invalid_filter_options(
context,
filters,
self._get_instance_filter_options())
protectable_types = self._get_all(context)
if protectable_type not in protectable_types:
msg = _("Invalid protectable type provided.")
raise exception.InvalidInput(reason=msg)
utils.check_filters(filters)
instances = self._instances_get_all(
context, protectable_type, marker, limit,
sort_keys=sort_keys, sort_dirs=sort_dirs,
filters=filters, offset=offset)
for instance in instances:
protectable_id = instance.get("id")
instance["type"] = protectable_type
if protectable_id is None:
raise exception.InvalidProtectableInstance(
protectable_id=protectable_id)
dependents = self.protection_api.\
list_protectable_dependents(context, protectable_id,
protectable_type)
instance["dependent_resources"] = dependents
retval_instances = self._view_builder.detail_list(req, instances)
return retval_instances
def _instances_get_all(self, context, protectable_type, marker=None,
limit=None, sort_keys=None, sort_dirs=None,
filters=None, offset=None):
check_policy(context, 'get_all')
if filters is None:
filters = {}
try:
if limit is not None:
limit = int(limit)
if limit <= 0:
msg = _('limit param must be positive')
raise exception.InvalidInput(reason=msg)
except ValueError:
msg = _('limit param must be an integer')
raise exception.InvalidInput(reason=msg)
if filters:
LOG.debug("Searching by: %s.", six.text_type(filters))
instances = self.protection_api.list_protectable_instances(
context, protectable_type, marker, limit,
sort_keys=sort_keys,
sort_dirs=sort_dirs,
filters=filters,
offset=offset)
LOG.info(_LI("Get all instances completed successfully."))
return instances
def _get_instance_filter_options(self):
"""Return instance search options allowed by non-admin."""
return CONF.query_instance_filters
def create_resource():
return wsgi.Resource(ProtectablesController())

View File

@ -12,6 +12,7 @@
from smaug.api.openstack import ProjectMapper
from smaug.api.v1 import plans
from smaug.api.v1 import protectables
from smaug.api.v1 import restores
from smaug.api.v1 import scheduled_operations
from smaug.wsgi import common as wsgi_common
@ -25,6 +26,7 @@ class APIRouter(wsgi_common.Router):
def __init__(self, mapper):
plans_resources = plans.create_resource()
restores_resources = restores.create_resource()
protectables_resources = protectables.create_resource()
scheduled_operation_resources = scheduled_operations.create_resource()
mapper.resource("plan", "plans",
controller=plans_resources,
@ -34,6 +36,17 @@ class APIRouter(wsgi_common.Router):
controller=restores_resources,
collection={},
member={'action': 'POST'})
mapper.resource("protectable", "protectables",
controller=protectables_resources,
collection={},
member={})
mapper.connect("protectable",
"/{project_id}/protectables/"
"{protectable_type}/instances",
controller=protectables_resources,
action='instances_index',
conditions={"method": ['GET']})
mapper.resource("scheduled_operation", "scheduled_operations",
controller=scheduled_operation_resources,
collection={'detail': 'GET'},

View File

@ -172,6 +172,10 @@ class InvalidContentType(Invalid):
message = _("Invalid content type %(content_type)s.")
class InvalidProtectableInstance(Invalid):
message = _("Invalid protectable instance %(protectable_id)s.")
class PasteAppNotFound(NotFound):
message = _("Could not load paste app '%(name)s' from %(path)s")
@ -214,3 +218,8 @@ class RestoreNotFound(NotFound):
class InvalidPlan(Invalid):
message = _("Invalid plan: %(reason)s")
class ProtectableTypeNotFound(NotFound):
message = _("ProtectableType %(protectable_type)s could"
" not be found.")

View File

@ -34,3 +34,26 @@ class API(base.Base):
def restore(self, context, restore):
return self.protection_rpcapi.restore(context, restore)
def list_protectable_types(self, context):
return self.protection_rpcapi.list_protectable_types(context)
def show_protectable_type(self, context, protectable_type):
return self.protection_rpcapi.\
show_protectable_type(context, protectable_type)
def list_protectable_instances(self, context, protectable_type,
marker, limit, sort_keys,
sort_dirs, filters, offset):
return self.protection_rpcapi.\
list_protectable_instances(context, protectable_type,
marker, limit, sort_keys,
sort_dirs, filters)
def list_protectable_dependents(self, context,
protectable_id,
protectable_type):
return self.protection_rpcapi.\
list_protectable_dependents(context,
protectable_id,
protectable_type)

View File

@ -112,3 +112,66 @@ class ProtectionManager(manager.Manager):
def show_provider(self, provider_id):
# TODO(wangliuan)
pass
def list_protectable_types(self, context):
# TODO(zengyingzhe)
LOG.info(_LI("Starting list protectable types."))
return_stub = [
"OS::Keystone::Project",
"OS::Nova::Server",
"OS::Glance::Image",
"OS::Cinder::Volume",
"OS::Neutron::Topology"
]
return return_stub
def show_protectable_type(self, context, protectable_type):
# TODO(zengyingzhe)
LOG.info(_LI("Starting show protectable "
"type. tpye:%s"), protectable_type)
return_stub = {
"name": "OS::Nova::Server",
"dependent_types": [
"OS::Cinder::Volume",
"OS::Glance::Image"
]
}
return return_stub
def list_protectable_instances(self, context, protectable_type,
marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None):
# TODO(zengyingzhe)
LOG.info(_LI("Starting list protectable instances. "
"tpye:%s"), protectable_type)
return_stub = [
{
"id": "557d0cd2-fd8d-4279-91a5-24763ebc6cbc",
},
{
"id": "557d0cd2-fd8d-4279-91a5-24763ebc6cbc",
}
]
return return_stub
def list_protectable_dependents(self, context,
protectable_id,
protectable_type):
# TODO(zengyingzhe)
LOG.info(_LI("Starting list protectable dependents."
"id:%s."), protectable_id)
return_stub = [
{
"id": "5fad94de-2926-486b-ae73-ff5d3477f80d",
"type": "OS::Cinder::Volume"
},
{
"id": "5fad94de-2926-486b-ae73-ff5d34775555",
"type": "OS::Cinder::Volume"
}
]
return return_stub

View File

@ -50,3 +50,41 @@ class ProtectionAPI(object):
ctxt,
'restore',
restore=restore)
def list_protectable_types(self, ctxt):
cctxt = self.client.prepare(version='1.0')
return cctxt.call(
ctxt,
'list_protectable_types')
def show_protectable_type(self, ctxt, protectable_type=None):
cctxt = self.client.prepare(version='1.0')
return cctxt.call(
ctxt,
'show_protectable_type',
protectable_type=protectable_type)
def list_protectable_instances(
self, ctxt, protectable_type=None,
marker=None, limit=None, sort_keys=None,
sort_dirs=None, filters=None):
cctxt = self.client.prepare(version='1.0')
return cctxt.call(
ctxt,
'list_protectable_instances',
protectable_type=protectable_type,
marker=marker,
limit=limit,
sort_keys=sort_keys,
sort_dirs=sort_dirs,
filters=filters)
def list_protectable_dependents(self,
ctxt, protectable_id=None,
protectable_type=None):
cctxt = self.client.prepare(version='1.0')
return cctxt.call(
ctxt,
'list_protectable_dependents',
protectable_id=protectable_id,
protectable_type=protectable_type)

View File

@ -0,0 +1,72 @@
# 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 mock
from oslo_config import cfg
from smaug.api.v1 import protectables
from smaug import context
from smaug import exception
from smaug.tests import base
from smaug.tests.unit.api import fakes
CONF = cfg.CONF
class ProtectablesApiTest(base.TestCase):
def setUp(self):
super(ProtectablesApiTest, self).setUp()
self.controller = protectables.ProtectablesController()
self.ctxt = context.RequestContext('admin', 'fakeproject', True)
@mock.patch(
'smaug.api.v1.protectables.ProtectablesController._get_all')
def test_protectables_list_detail(self, moak_get_all):
req = fakes.HTTPRequest.blank('/v1/protectables')
self.controller.index(req)
self.assertTrue(moak_get_all.called)
@mock.patch(
'smaug.services.protection.api.API.show_protectable_type')
@mock.patch(
'smaug.api.v1.protectables.ProtectablesController._get_all')
def test_protectables_show(self, moak_get_all, moak_show_protectable_type):
req = fakes.HTTPRequest.blank('/v1/protectables')
moak_get_all.return_value = ["OS::Keystone::Project"]
self.controller.\
show(req, 'OS::Keystone::Project')
self.assertTrue(moak_get_all.called)
self.assertTrue(moak_show_protectable_type.called)
@mock.patch(
'smaug.api.v1.protectables.ProtectablesController._get_all')
def test_protectables_show_Invalid(self, moak_get_all):
req = fakes.HTTPRequest.blank('/v1/protectables')
moak_get_all.return_value = ["OS::Keystone::Project"]
self.assertRaises(exception.InvalidInput, self.controller.show,
req, "1")
self.assertTrue(moak_get_all.called)
@mock.patch(
'smaug.services.protection.api.API.'
'list_protectable_instances')
@mock.patch(
'smaug.api.v1.protectables.ProtectablesController._get_all')
def test_protectables_instances_show(self, moak_get_all,
list_protectable_instances_type):
req = fakes.HTTPRequest.blank('/v1/protectables')
moak_get_all.return_value = ["OS::Keystone::Project"]
self.controller.\
instances_index(req, 'OS::Keystone::Project')
self.assertTrue(moak_get_all.called)
self.assertTrue(list_protectable_instances_type.called)