Beispiel #1
0
    def setUp(self):
        super(APIPolicyTestCase, self).setUp()

        self.ATTRIBUTE_MAP_COPY = copy.copy(attributes.RESOURCE_ATTRIBUTE_MAP)
        self.extension_path = os.path.abspath(os.path.join(
            TEST_PATH, "../../../extensions"))
        policy.reset()
    def setUp(self):
        super(APIPolicyTestCase, self).setUp()

        self.ATTRIBUTE_MAP_COPY = copy.copy(attributes.RESOURCE_ATTRIBUTE_MAP)
        self.extension_path = os.path.abspath(
            os.path.join(TEST_PATH, "../../../extensions"))
        policy.reset()
Beispiel #3
0
 def setUp(self):
     super(PolicyFileTestCase, self).setUp()
     policy.reset()
     self.addCleanup(policy.reset)
     self.context = context.Context('fake', 'fake', is_admin=False)
     self.target = {}
     self.tempdir = self.useFixture(fixtures.TempDir())
Beispiel #4
0
 def setUp(self):
     super(APIPolicyTestCase, self).setUp()
     self.useFixture(tools.AttributeMapMemento())
     self.extension_path = os.path.abspath(os.path.join(
         TEST_PATH, "../../../extensions"))
     policy.reset()
     self.addCleanup(policy.reset)
Beispiel #5
0
 def setUp(self):
     super(PolicyFileTestCase, self).setUp()
     policy.reset()
     self.addCleanup(policy.reset)
     self.context = context.Context('fake', 'fake', is_admin=False)
     self.target = {}
     self.tempdir = self.useFixture(fixtures.TempDir())
Beispiel #6
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)
        self.admin_only_legacy = "role:admin"
        self.admin_or_owner_legacy = "role:admin or tenant_id:%(tenant_id)s"
        # Add a Fake 'something' resource to RESOURCE_ATTRIBUTE_MAP
        attributes.RESOURCE_ATTRIBUTE_MAP.update(FAKE_RESOURCE)
        self.rules = dict((k, common_policy.parse_rule(v)) for k, v in {
            "context_is_admin": "role:admin",
            "admin_or_network_owner": "rule:context_is_admin or "
                                      "tenant_id:%(network:tenant_id)s",
            "admin_or_owner": ("rule:context_is_admin or "
                               "tenant_id:%(tenant_id)s"),
            "admin_only": "rule:context_is_admin",
            "regular_user": "******",
            "shared": "field:networks:shared=True",
            "external": "field:networks:router:external=True",
            "default": '@',

            "create_network": "rule:admin_or_owner",
            "create_network:shared": "rule:admin_only",
            "update_network": '@',
            "update_network:shared": "rule:admin_only",

            "get_network": "rule:admin_or_owner or "
                           "rule:shared or "
                           "rule:external",
            "create_port:mac": "rule:admin_or_network_owner",
            "create_something": "rule:admin_or_owner",
            "create_something:attr": "rule:admin_or_owner",
            "create_something:attr:sub_attr_1": "rule:admin_or_owner",
            "create_something:attr:sub_attr_2": "rule:admin_only",

            "get_firewall_policy": "rule:admin_or_owner or "
                            "rule:shared",
            "get_firewall_rule": "rule:admin_or_owner or "
                            "rule:shared"
        }.items())

        def fakepolicyinit():
            common_policy.set_rules(common_policy.Rules(self.rules))

        def remove_fake_resource():
            del attributes.RESOURCE_ATTRIBUTE_MAP["%ss" % FAKE_RESOURCE_NAME]

        self.patcher = mock.patch.object(neutron.policy,
                                         'init',
                                         new=fakepolicyinit)
        self.patcher.start()
        self.addCleanup(remove_fake_resource)
        self.context = context.Context('fake', 'fake', roles=['user'])
        plugin_klass = importutils.import_class(
            "neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch('neutron.manager.NeutronManager')
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
Beispiel #7
0
def initialize_all():
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for every resource (both core
    # and extensions)
    pecanized_exts = [ext for ext in ext_mgr.extensions.values() if hasattr(ext, "get_pecan_controllers")]
    pecan_controllers = {}
    for ext in pecanized_exts:
        LOG.debug("Extension %s is pecan-enabled. Fetching resources " "and controllers", ext.get_name())
        controllers = ext.get_pecan_controllers()
        # controllers is actually a list of pairs where the first element is
        # the collection name and the second the actual controller
        for (collection, coll_controller) in controllers:
            pecan_controllers[collection] = coll_controller

    for collection in attributes.RESOURCE_ATTRIBUTE_MAP:
        if collection not in pecan_controllers:
            resource = _handle_plurals(collection)
            LOG.debug("Building controller for resource:%s", resource)
            plugin = _plugin_for_resource(collection)
            if plugin:
                manager.NeutronManager.set_plugin_for_resource(resource, plugin)
            controller = root.CollectionsController(collection, resource)
            manager.NeutronManager.set_controller_for_resource(collection, controller)
            LOG.info(
                _LI("Added controller for resource %(resource)s " "via URI path segment:%(collection)s"),
                {"resource": resource, "collection": collection},
            )
        else:
            LOG.debug("There are already controllers for resource:%s", resource)

    # NOTE(salv-orlando): If you are care about code quality, please read below
    # Hackiness is strong with the piece of code below. It is used for
    # populating resource plurals and registering resources with the quota
    # engine, but the method it calls were not conceived with this aim.
    # Therefore it only leverages side-effects from those methods. Moreover,
    # as it is really not advisable to load an instance of
    # neutron.api.v2.router.APIRouter just to register resources with the
    # quota  engine, core resources are explicitly registered here.
    # TODO(salv-orlando): The Pecan WSGI support should provide its own
    # solution to manage resource plurals and registration of resources with
    # the quota engine
    for resource in router.RESOURCES.keys():
        resource_registry.register_resource_by_name(resource)
    for ext in ext_mgr.extensions.values():
        # make each extension populate its plurals
        if hasattr(ext, "get_resources"):
            ext.get_resources()
        if hasattr(ext, "get_extended_resources"):
            ext.get_extended_resources("v2.0")
    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Beispiel #8
0
    def __init__(self, **local_config):
        mapper = routes_mapper.Mapper()
        manager.init()
        plugin = directory.get_plugin()
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)

        col_kwargs = dict(collection_actions=COLLECTION_ACTIONS,
                          member_actions=MEMBER_ACTIONS)

        def _map_resource(collection, resource, params, parent=None):
            allow_bulk = cfg.CONF.allow_bulk
            allow_pagination = cfg.CONF.allow_pagination
            allow_sorting = cfg.CONF.allow_sorting
            controller = base.create_resource(
                collection,
                resource,
                plugin,
                params,
                allow_bulk=allow_bulk,
                parent=parent,
                allow_pagination=allow_pagination,
                allow_sorting=allow_sorting)
            path_prefix = None
            if parent:
                path_prefix = "/%s/{%s_id}/%s" % (parent['collection_name'],
                                                  parent['member_name'],
                                                  collection)
            mapper_kwargs = dict(controller=controller,
                                 requirements=REQUIREMENTS,
                                 path_prefix=path_prefix,
                                 **col_kwargs)
            return mapper.collection(collection, resource, **mapper_kwargs)

        mapper.connect('index', '/', controller=Index(RESOURCES))
        for resource in RESOURCES:
            _map_resource(
                RESOURCES[resource], resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(RESOURCES[resource],
                                                      dict()))
            resource_registry.register_resource_by_name(resource)

        for resource in SUB_RESOURCES:
            _map_resource(
                SUB_RESOURCES[resource]['collection_name'], resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(
                    SUB_RESOURCES[resource]['collection_name'], dict()),
                SUB_RESOURCES[resource]['parent'])

        # Certain policy checks require that the extensions are loaded
        # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
        # properly initialized. This can only be claimed with certainty
        # once this point in the code has been reached. In the event
        # that the policies have been initialized before this point,
        # calling reset will cause the next policy check to
        # re-initialize with all of the required data in place.
        policy.reset()
        super(APIRouter, self).__init__(mapper)
Beispiel #9
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)
        self.admin_only_legacy = "role:admin"
        self.admin_or_owner_legacy = "role:admin or tenant_id:%(tenant_id)s"
        # Add a Fake 'something' resource to RESOURCE_ATTRIBUTE_MAP
        attributes.RESOURCE_ATTRIBUTE_MAP.update(FAKE_RESOURCE)
        self.rules = dict((k, common_policy.parse_rule(v)) for k, v in {
            "context_is_admin": "role:admin",
            "admin_or_network_owner": "rule:context_is_admin or "
                                      "tenant_id:%(network:tenant_id)s",
            "admin_or_owner": ("rule:context_is_admin or "
                               "tenant_id:%(tenant_id)s"),
            "admin_only": "rule:context_is_admin",
            "regular_user": "******",
            "shared": "field:networks:shared=True",
            "external": "field:networks:router:external=True",
            "default": '@',

            "create_network": "rule:admin_or_owner",
            "create_network:shared": "rule:admin_only",
            "update_network": '@',
            "update_network:shared": "rule:admin_only",

            "get_network": "rule:admin_or_owner or "
                           "rule:shared or "
                           "rule:external",
            "create_port:mac": "rule:admin_or_network_owner",
            "create_something": "rule:admin_or_owner",
            "create_something:attr": "rule:admin_or_owner",
            "create_something:attr:sub_attr_1": "rule:admin_or_owner",
            "create_something:attr:sub_attr_2": "rule:admin_only"
        }.items())

        def fakepolicyinit():
            common_policy.set_rules(common_policy.Rules(self.rules))

        def remove_fake_resource():
            del attributes.RESOURCE_ATTRIBUTE_MAP["%ss" % FAKE_RESOURCE_NAME]

        self.patcher = mock.patch.object(neutron.policy,
                                         'init',
                                         new=fakepolicyinit)
        self.patcher.start()
        self.addCleanup(self.patcher.stop)
        self.addCleanup(remove_fake_resource)
        self.context = context.Context('fake', 'fake', roles=['user'])
        plugin_klass = importutils.import_class(
            "neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch('neutron.manager.NeutronManager')
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
        self.addCleanup(self.manager_patcher.stop)
Beispiel #10
0
 def test_after_inits_policy(self):
     self.mock_plugin.get_mehs.return_value = [{
         'id': 'xxx',
         'attr': 'meh',
         'restricted_attr': '',
         'tenant_id': 'tenid'}]
     policy.reset()
     response = self.app.get('/v2.0/mehs',
                             headers={'X-Project-Id': 'tenid'})
     self.assertEqual(200, response.status_int)
Beispiel #11
0
 def test_after_inits_policy(self):
     self.mock_plugin.get_mehs.return_value = [{
         'id': 'xxx',
         'attr': 'meh',
         'restricted_attr': '',
         'tenant_id': 'tenid'}]
     policy.reset()
     response = self.app.get('/v2.0/mehs',
                             headers={'X-Project-Id': 'tenid'})
     self.assertEqual(200, response.status_int)
    def __init__(self, **local_config):
        mapper = routes_mapper.Mapper()
        plugin = manager.NeutronManager.get_plugin()#core plugin    #/usr/lib/python2.7/site-packages/neutron/manager.py(216)get_plugin()
        # #plugin=<weakproxy at 0x4490208 to Ml2Plugin at 0x2fd1f50>
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
        #attributes.RESOURCE_ATTRIBUTE_MAP会被修改为包含neutron/extensions/xx目录下所有插件定义的资源信息,如routers

        col_kwargs = dict(collection_actions=COLLECTION_ACTIONS,
                          member_actions=MEMBER_ACTIONS)
        #col_kwargs ={'member_actions': ['show', 'update', 'delete'], 'collection_actions': ['index', 'create']}

        def _map_resource(collection, resource, params, parent=None):
            allow_bulk = cfg.CONF.allow_bulk
            allow_pagination = cfg.CONF.allow_pagination
            allow_sorting = cfg.CONF.allow_sorting
            controller = base.create_resource(
                collection, resource, plugin, params, allow_bulk=allow_bulk,
                parent=parent, allow_pagination=allow_pagination,
                allow_sorting=allow_sorting)
            path_prefix = None
            if parent:
                path_prefix = "/%s/{%s_id}/%s" % (parent['collection_name'],
                                                  parent['member_name'],
                                                  collection)
            mapper_kwargs = dict(controller=controller,
                                 requirements=REQUIREMENTS,
                                 path_prefix=path_prefix,
                                 **col_kwargs)
            #调用mapper对象的collection方法创建URL映射
            return mapper.collection(collection, resource,
                                     **mapper_kwargs)

        mapper.connect('index', '/', controller=Index(RESOURCES))
        for resource in RESOURCES:
            _map_resource(RESOURCES[resource], resource,
                          attributes.RESOURCE_ATTRIBUTE_MAP.get(
                              RESOURCES[resource], dict()))

        for resource in SUB_RESOURCES:
            _map_resource(SUB_RESOURCES[resource]['collection_name'], resource,
                          attributes.RESOURCE_ATTRIBUTE_MAP.get(
                              SUB_RESOURCES[resource]['collection_name'],
                              dict()),
                          SUB_RESOURCES[resource]['parent'])

        # Certain policy checks require that the extensions are loaded
        # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
        # properly initialized. This can only be claimed with certainty
        # once this point in the code has been reached. In the event
        # that the policies have been initialized before this point,
        # calling reset will cause the next policy check to
        # re-initialize with all of the required data in place.
        policy.reset()
        super(APIRouter, self).__init__(mapper)
Beispiel #13
0
    def __init__(self, **local_config):
        mapper = routes_mapper.Mapper()
        plugin = manager.NeutronManager.get_plugin()
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)

        col_kwargs = dict(collection_actions=COLLECTION_ACTIONS, member_actions=MEMBER_ACTIONS)

        def _map_resource(collection, resource, params, parent=None):
            allow_bulk = cfg.CONF.allow_bulk
            allow_pagination = cfg.CONF.allow_pagination
            allow_sorting = cfg.CONF.allow_sorting
            controller = base.create_resource(
                collection,
                resource,
                plugin,
                params,
                allow_bulk=allow_bulk,
                parent=parent,
                allow_pagination=allow_pagination,
                allow_sorting=allow_sorting,
            )
            path_prefix = None
            if parent:
                path_prefix = "/%s/{%s_id}/%s" % (parent["collection_name"], parent["member_name"], collection)
            mapper_kwargs = dict(
                controller=controller, requirements=REQUIREMENTS, path_prefix=path_prefix, **col_kwargs
            )
            return mapper.collection(collection, resource, **mapper_kwargs)

        mapper.connect("index", "/", controller=Index(RESOURCES))
        for resource in RESOURCES:
            _map_resource(
                RESOURCES[resource], resource, attributes.RESOURCE_ATTRIBUTE_MAP.get(RESOURCES[resource], dict())
            )
            resource_registry.register_resource_by_name(resource)

        for resource in SUB_RESOURCES:
            _map_resource(
                SUB_RESOURCES[resource]["collection_name"],
                resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(SUB_RESOURCES[resource]["collection_name"], dict()),
                SUB_RESOURCES[resource]["parent"],
            )

        # Certain policy checks require that the extensions are loaded
        # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
        # properly initialized. This can only be claimed with certainty
        # once this point in the code has been reached. In the event
        # that the policies have been initialized before this point,
        # calling reset will cause the next policy check to
        # re-initialize with all of the required data in place.
        policy.reset()
        super(APIRouter, self).__init__(mapper)
Beispiel #14
0
    def setUp(self):
        super(DefaultPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)

        self.rules = {"default": "", "example:exist": "!"}

        self._set_rules("default")

        self.context = context.Context("fake", "fake")
Beispiel #15
0
 def test_get_child_resource_policy_check(self):
     policy.reset()
     policy.init()
     policy._ENFORCER.set_rules(
         oslo_policy.Rules.from_dict({'get_meh_meh_fake_duplicate': ''}))
     url = '/v2.0/{0}/something/{1}'.format(self.collection,
                                            self.fake_collection)
     resp = self.app.get(url)
     self.assertEqual(200, resp.status_int)
     self.assertEqual({'fake_duplicates': [{
         'fake': 'something'
     }]}, resp.json)
Beispiel #16
0
def initialize_all():
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for every resource (both core
    # and extensions)
    pecanized_exts = [ext for ext in ext_mgr.extensions.values() if
                      hasattr(ext, 'get_pecan_controllers')]
    pecan_controllers = {}
    for ext in pecanized_exts:
        LOG.debug("Extension %s is pecan-enabled. Fetching resources "
                  "and controllers", ext.get_name())
        controllers = ext.get_pecan_controllers()
        # controllers is actually a list of pairs where the first element is
        # the collection name and the second the actual controller
        for (collection, coll_controller) in controllers:
            pecan_controllers[collection] = coll_controller

    for collection in attributes.RESOURCE_ATTRIBUTE_MAP:
        if collection not in pecan_controllers:
            resource = _handle_plurals(collection)
            LOG.debug("Building controller for resource:%s", resource)
            plugin = _plugin_for_resource(collection)
            if plugin:
                manager.NeutronManager.set_plugin_for_resource(
                    resource, plugin)
            controller = root.CollectionsController(collection, resource)
            manager.NeutronManager.set_controller_for_resource(
                collection, controller)
            LOG.info(_LI("Added controller for resource %(resource)s "
                         "via URI path segment:%(collection)s"),
                     {'resource': resource,
                      'collection': collection})
        else:
            LOG.debug("There are already controllers for resource:%s",
                      resource)

    for ext in ext_mgr.extensions.values():
        # make each extension populate its plurals
        if hasattr(ext, 'get_resources'):
            ext.get_resources()
        if hasattr(ext, 'get_extended_resources'):
            ext.get_extended_resources('v2.0')
    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Beispiel #17
0
 def test_get_child_resource_policy_check(self):
     policy.reset()
     policy.init()
     policy._ENFORCER.set_rules(
         oslo_policy.Rules.from_dict(
             {'get_meh_meh_fake_duplicate': ''}
         )
     )
     url = '/v2.0/{0}/something/{1}'.format(self.collection,
                                            self.fake_collection)
     resp = self.app.get(url)
     self.assertEqual(200, resp.status_int)
     self.assertEqual({'fake_duplicates': [{'fake': 'something'}]},
                      resp.json)
Beispiel #18
0
    def setUp(self):
        super(DefaultPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)

        self.rules = {
            "default": '',
            "example:exist": '!',
        }

        self._set_rules('default')

        self.context = context.Context('fake', 'fake')
Beispiel #19
0
    def setUp(self):
        super(DefaultPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)

        self.rules = {
            "default": '',
            "example:exist": '!',
        }

        self._set_rules('default')

        self.context = context.Context('fake', 'fake')
Beispiel #20
0
 def test_proper_load_order(self):
     """
     Verifies that loading policies by way of admin context after
     populating extensions and extending the resource map results in
     networks with router:external are visible to regular tenants.
     """
     policy.reset()
     extension_manager = extensions.ExtensionManager(self.extension_path)
     extension_manager.extend_resources(self.api_version,
                                        attributes.RESOURCE_ATTRIBUTE_MAP)
     policy.init()
     admin_context = context.get_admin_context()
     tenant_context = context.Context('test_user', 'test_tenant_id', False)
     self.assertTrue(self._check_external_router_policy(admin_context))
     self.assertTrue(self._check_external_router_policy(tenant_context))
Beispiel #21
0
 def test_proper_load_order(self):
     """
     Verifies that loading policies by way of admin context after
     populating extensions and extending the resource map results in
     networks with router:external are visible to regular tenants.
     """
     policy.reset()
     extension_manager = extensions.ExtensionManager(self.extension_path)
     extension_manager.extend_resources(self.api_version,
                                        attributes.RESOURCE_ATTRIBUTE_MAP)
     policy.init()
     admin_context = context.get_admin_context()
     tenant_context = context.Context('test_user', 'test_tenant_id', False)
     self.assertTrue(self._check_external_router_policy(admin_context))
     self.assertTrue(self._check_external_router_policy(tenant_context))
Beispiel #22
0
 def setUp(self):
     super(UOSExtensionPolicyTestCase, self).setUp()
     policy.reset()
     policy.init()
     rules = {
         "associate_floatingip_router": "not role:project_observer",
         "get_router_details": "role:admin",
         "remove_router_portforwarding": "role:member"
     }
     common_policy.set_rules(common_policy.Rules(
         dict((k, common_policy.parse_rule(v))
              for k, v in rules.items())))
     self.context = context.Context('fake', 'fake', roles=['member'])
     self.request = FakeRequest(self.context)
     self.target = {}
     self.controller = uos.UosController()
Beispiel #23
0
 def setUp(self):
     super(UOSExtensionPolicyTestCase, self).setUp()
     policy.reset()
     policy.init()
     rules = {
         "associate_floatingip_router": "not role:project_observer",
         "get_router_details": "role:admin",
         "remove_router_portforwarding": "role:member"
     }
     common_policy.set_rules(
         common_policy.Rules(
             dict((k, common_policy.parse_rule(v))
                  for k, v in rules.items())))
     self.context = context.Context('fake', 'fake', roles=['member'])
     self.request = FakeRequest(self.context)
     self.target = {}
     self.controller = uos.UosController()
Beispiel #24
0
    def test_proper_load_order(self):
        """Test proper policy load order

        Verifies that loading policies by way of admin context after
        populating extensions and extending the resource map results in
        networks with router:external are visible to regular tenants.
        """
        policy.reset()
        extension_manager = extensions.ExtensionManager(self.extension_path)
        extension_manager.extend_resources(self.api_version,
                                           attributes.RESOURCES)
        # TODO(amotoki): Consider this should be part of
        # neutron.policy.reset (or refresh), but as of now
        # this is only required for unit testing.
        policies.reload_default_policies()
        policy.init()
        admin_context = context.get_admin_context()
        tenant_context = context.Context('test_user', 'test_tenant_id', False)
        self.assertTrue(self._check_external_router_policy(admin_context))
        self.assertTrue(self._check_external_router_policy(tenant_context))
Beispiel #25
0
    def test_proper_load_order(self):
        """Test proper policy load order

        Verifies that loading policies by way of admin context after
        populating extensions and extending the resource map results in
        networks with router:external are visible to regular tenants.
        """
        policy.reset()
        extension_manager = extensions.ExtensionManager(self.extension_path)
        extension_manager.extend_resources(self.api_version,
                                           attributes.RESOURCES)
        # TODO(amotoki): Consider this should be part of
        # neutron.policy.reset (or refresh), but as of now
        # this is only required for unit testing.
        policies.reload_default_policies()
        policy.init()
        admin_context = context.get_admin_context()
        tenant_context = context.Context('test_user', 'test_tenant_id', False)
        self.assertTrue(self._check_external_router_policy(admin_context))
        self.assertTrue(self._check_external_router_policy(tenant_context))
Beispiel #26
0
 def test_policy_404(self):
     with self.subnet(cidr='12.0.0.0/24') as public_sub:
         self._set_net_external(public_sub['subnet']['network_id'])
         fip = self._make_floatingip(self.fmt,
                                     public_sub['subnet']['network_id'])
         policy.reset()
         policy.init()
         rules = {"delete_floatingip": "role:admin_only"}
         common_policy.set_rules(
             common_policy.Rules(
                 dict((k, common_policy.parse_rule(v))
                      for k, v in rules.items())))
         fip_id = fip['floatingip']['id']
         self.context = context.Context('fake', 'fake', roles=['member'])
         req = self.new_delete_request('floatingips', fip_id)
         req.environ['neutron.context'] = self.context
         res = req.get_response(self._api_for_resource('floatingips'))
         self.assertEqual(404, res.status_int)
         policy.reset()
         policy.init()
         self._delete('floatingips', fip_id)
Beispiel #27
0
 def setUp(self):
     super(PolicyTestCase, self).setUp()
     policy.reset()
     self.addCleanup(policy.reset)
     # NOTE(vish): preload rules to circumvent reloading from file
     policy.init()
     rules = {
         "true": "@",
         "example:allowed": "@",
         "example:denied": "!",
         "example:get_http": "http:http://www.example.com",
         "example:my_file": "role:compute_admin or tenant_id:%(tenant_id)s",
         "example:early_and_fail": "! and @",
         "example:early_or_success": "@ or !",
         "example:lowercase_admin": "role:admin or role:sysadmin",
         "example:uppercase_admin": "role:ADMIN or role:sysadmin",
     }
     # NOTE(vish): then overload underlying rules
     common_policy.set_rules(common_policy.Rules(dict((k, common_policy.parse_rule(v)) for k, v in rules.items())))
     self.context = context.Context("fake", "fake", roles=["member"])
     self.target = {}
Beispiel #28
0
    def setUp(self):
        super(NeutronPolicyTestCase, self).setUp()
        policy.reset()
        policy.init()
        self.addCleanup(policy.reset)
        self.admin_only_legacy = "role:admin"
        self.admin_or_owner_legacy = "role:admin or tenant_id:%(tenant_id)s"
        self.rules = dict(
            (k, common_policy.parse_rule(v))
            for k, v in {
                "context_is_admin": "role:admin",
                "admin_or_network_owner": "rule:context_is_admin or " "tenant_id:%(network:tenant_id)s",
                "admin_or_owner": ("rule:context_is_admin or " "tenant_id:%(tenant_id)s"),
                "admin_only": "rule:context_is_admin",
                "regular_user": "******",
                "shared": "field:networks:shared=True",
                "external": "field:networks:router:external=True",
                "default": "@",
                "create_network": "rule:admin_or_owner",
                "create_network:shared": "rule:admin_only",
                "update_network": "@",
                "update_network:shared": "rule:admin_only",
                "get_network": "rule:admin_or_owner or " "rule:shared or " "rule:external",
                "create_port:mac": "rule:admin_or_network_owner",
            }.items()
        )

        def fakepolicyinit():
            common_policy.set_rules(common_policy.Rules(self.rules))

        self.patcher = mock.patch.object(neutron.policy, "init", new=fakepolicyinit)
        self.patcher.start()
        self.addCleanup(self.patcher.stop)
        self.context = context.Context("fake", "fake", roles=["user"])
        plugin_klass = importutils.import_class("neutron.db.db_base_plugin_v2.NeutronDbPluginV2")
        self.manager_patcher = mock.patch("neutron.manager.NeutronManager")
        fake_manager = self.manager_patcher.start()
        fake_manager_instance = fake_manager.return_value
        fake_manager_instance.plugin = plugin_klass()
        self.addCleanup(self.manager_patcher.stop)
Beispiel #29
0
 def setUp(self):
     super(PolicyTestCase, self).setUp()
     policy.reset()
     self.addCleanup(policy.reset)
     # NOTE(vish): preload rules to circumvent reloading from file
     policy.init()
     rules = {
         "true": '@',
         "example:allowed": '@',
         "example:denied": '!',
         "example:get_http": "http:http://www.example.com",
         "example:my_file": "role:compute_admin or tenant_id:%(tenant_id)s",
         "example:early_and_fail": "! and @",
         "example:early_or_success": "@ or !",
         "example:lowercase_admin": "role:admin or role:sysadmin",
         "example:uppercase_admin": "role:ADMIN or role:sysadmin",
     }
     # NOTE(vish): then overload underlying rules
     common_policy.set_rules(common_policy.Rules(
         dict((k, common_policy.parse_rule(v))
              for k, v in rules.items())))
     self.context = context.Context('fake', 'fake', roles=['member'])
     self.target = {}
Beispiel #30
0
 def test_policy_404(self):
     with self.subnet(cidr='12.0.0.0/24') as public_sub:
         self._set_net_external(public_sub['subnet']['network_id'])
         fip = self._make_floatingip(
             self.fmt,
             public_sub['subnet']['network_id'])
         policy.reset()
         policy.init()
         rules = {
             "delete_floatingip": "role:admin_only"
         }
         common_policy.set_rules(common_policy.Rules(
             dict((k, common_policy.parse_rule(v))
             for k, v in rules.items())))
         fip_id = fip['floatingip']['id']
         self.context = context.Context('fake', 'fake', roles=['member'])
         req = self.new_delete_request('floatingips', fip_id)
         req.environ['neutron.context'] = self.context
         res = req.get_response(self._api_for_resource('floatingips'))
         self.assertEqual(404, res.status_int)
         policy.reset()
         policy.init()
         self._delete('floatingips', fip_id)
Beispiel #31
0
def initialize_all():
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for all core resources
    for resource, collection in router.RESOURCES.items():
        resource_registry.register_resource_by_name(resource)
        plugin = manager.NeutronManager.get_plugin()
        new_controller = res_ctrl.CollectionsController(collection, resource,
                                                        plugin=plugin)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)
        manager.NeutronManager.set_plugin_for_resource(resource, plugin)

    pecanized_resources = ext_mgr.get_pecan_resources()
    for pec_res in pecanized_resources:
        resource = attributes.PLURALS[pec_res.collection]
        manager.NeutronManager.set_controller_for_resource(
            pec_res.collection, pec_res.controller)
        manager.NeutronManager.set_plugin_for_resource(
            resource, pec_res.plugin)

    # Now build Pecan Controllers and routes for all extensions
    resources = ext_mgr.get_resources()
    # Extensions controller is already defined, we don't need it.
    resources.pop(0)
    for ext_res in resources:
        path_prefix = ext_res.path_prefix.strip('/')
        collection = ext_res.collection
        if manager.NeutronManager.get_controller_for_resource(collection):
            # This is a collection that already has a pecan controller, we
            # do not need to do anything else
            continue
        legacy_controller = getattr(ext_res.controller, 'controller',
                                    ext_res.controller)
        new_controller = None
        if isinstance(legacy_controller, base.Controller):
            resource = legacy_controller.resource
            plugin = legacy_controller.plugin
            attr_info = legacy_controller.attr_info
            # Retrieving the parent resource.  It is expected the format of
            # the parent resource to be:
            # {'collection_name': 'name-of-collection',
            #  'member_name': 'name-of-resource'}
            # collection_name does not appear to be used in the legacy code
            # inside the controller logic, so we can assume we do not need it.
            parent = legacy_controller.parent or {}
            parent_resource = parent.get('member_name')
            new_controller = res_ctrl.CollectionsController(
                collection, resource, resource_info=attr_info,
                parent_resource=parent_resource)
            manager.NeutronManager.set_plugin_for_resource(resource, plugin)
            if path_prefix:
                manager.NeutronManager.add_resource_for_path_prefix(
                    collection, path_prefix)
        elif isinstance(legacy_controller, wsgi.Controller):
            new_controller = utils.ShimCollectionsController(
                collection, None, legacy_controller)
        else:
            LOG.warning(_LW("Unknown controller type encountered %s.  It will"
                            "be ignored."), legacy_controller)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)

    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
 def __init__(self, path):
     LOG.info(_("Initializing extension manager."))
     self.path = path
     self.extensions = {}
     self._load_all_extensions()
     policy.reset()
Beispiel #33
0
 def tearDown(self):
     policy.reset()
     if self.ATTRIBUTE_MAP_COPY:
         attributes.RESOURCE_ATTRIBUTE_MAP = self.ATTRIBUTE_MAP_COPY
     super(APIPolicyTestCase, self).tearDown()
Beispiel #34
0
def initialize_all():
    manager.init()
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCES)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for all core resources
    plugin = directory.get_plugin()
    for resource, collection in RESOURCES.items():
        resource_registry.register_resource_by_name(resource)
        new_controller = res_ctrl.CollectionsController(collection, resource,
                                                        plugin=plugin)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)
        manager.NeutronManager.set_plugin_for_resource(collection, plugin)

    pecanized_resources = ext_mgr.get_pecan_resources()
    for pec_res in pecanized_resources:
        manager.NeutronManager.set_controller_for_resource(
            pec_res.collection, pec_res.controller)
        manager.NeutronManager.set_plugin_for_resource(
            pec_res.collection, pec_res.plugin)

    # Now build Pecan Controllers and routes for all extensions
    resources = ext_mgr.get_resources()
    # Extensions controller is already defined, we don't need it.
    resources.pop(0)
    for ext_res in resources:
        path_prefix = ext_res.path_prefix.strip('/')
        collection = ext_res.collection
        # Retrieving the parent resource.  It is expected the format of
        # the parent resource to be:
        # {'collection_name': 'name-of-collection',
        #  'member_name': 'name-of-resource'}
        # collection_name does not appear to be used in the legacy code
        # inside the controller logic, so we can assume we do not need it.
        parent = ext_res.parent or {}
        parent_resource = parent.get('member_name')
        collection_key = collection
        if parent_resource:
            collection_key = '/'.join([parent_resource, collection])
        collection_actions = ext_res.collection_actions
        member_actions = ext_res.member_actions
        if manager.NeutronManager.get_controller_for_resource(collection_key):
            # This is a collection that already has a pecan controller, we
            # do not need to do anything else
            continue
        legacy_controller = getattr(ext_res.controller, 'controller',
                                    ext_res.controller)
        new_controller = None
        if isinstance(legacy_controller, base.Controller):
            resource = legacy_controller.resource
            plugin = legacy_controller.plugin
            attr_info = legacy_controller.attr_info
            member_actions = legacy_controller.member_actions
            pagination = legacy_controller.allow_pagination
            sorting = legacy_controller.allow_sorting
            # NOTE(blogan): legacy_controller and ext_res both can both have
            # member_actions.  the member_actions for ext_res are strictly for
            # routing, while member_actions for legacy_controller are used for
            # handling the request once the routing has found the controller.
            # They're always the same so we will just use the ext_res
            # member_action.
            new_controller = res_ctrl.CollectionsController(
                collection, resource, resource_info=attr_info,
                parent_resource=parent_resource, member_actions=member_actions,
                plugin=plugin, allow_pagination=pagination,
                allow_sorting=sorting, collection_actions=collection_actions)
            # new_controller.collection has replaced hyphens with underscores
            manager.NeutronManager.set_plugin_for_resource(
                new_controller.collection, plugin)
            if path_prefix:
                manager.NeutronManager.add_resource_for_path_prefix(
                    collection, path_prefix)
        else:
            new_controller = utils.ShimCollectionsController(
                collection, None, legacy_controller,
                collection_actions=collection_actions,
                member_actions=member_actions,
                action_status=ext_res.controller.action_status,
                collection_methods=ext_res.collection_methods)

        manager.NeutronManager.set_controller_for_resource(
            collection_key, new_controller)

    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
 def setUp(self):
     super(APIPolicyTestCase, self).setUp()
     self.useFixture(tools.AttributeMapMemento())
     self.extension_path = os.path.abspath(os.path.join(TEST_PATH, "../../../extensions"))
     policy.reset()
 def tearDown(self):
     policy.reset()
     super(APIPolicyTestCase, self).tearDown()
Beispiel #37
0
def initialize_all():
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for all core resources
    for resource, collection in router.RESOURCES.items():
        resource_registry.register_resource_by_name(resource)
        plugin = manager.NeutronManager.get_plugin()
        new_controller = res_ctrl.CollectionsController(collection,
                                                        resource,
                                                        plugin=plugin)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)
        manager.NeutronManager.set_plugin_for_resource(resource, plugin)

    pecanized_resources = ext_mgr.get_pecan_resources()
    for pec_res in pecanized_resources:
        resource = attributes.PLURALS[pec_res.collection]
        manager.NeutronManager.set_controller_for_resource(
            pec_res.collection, pec_res.controller)
        manager.NeutronManager.set_plugin_for_resource(resource,
                                                       pec_res.plugin)

    # Now build Pecan Controllers and routes for all extensions
    resources = ext_mgr.get_resources()
    # Extensions controller is already defined, we don't need it.
    resources.pop(0)
    for ext_res in resources:
        path_prefix = ext_res.path_prefix.strip('/')
        collection = ext_res.collection
        if manager.NeutronManager.get_controller_for_resource(collection):
            # This is a collection that already has a pecan controller, we
            # do not need to do anything else
            continue
        legacy_controller = getattr(ext_res.controller, 'controller',
                                    ext_res.controller)
        new_controller = None
        if isinstance(legacy_controller, base.Controller):
            resource = legacy_controller.resource
            plugin = legacy_controller.plugin
            attr_info = legacy_controller.attr_info
            # Retrieving the parent resource.  It is expected the format of
            # the parent resource to be:
            # {'collection_name': 'name-of-collection',
            #  'member_name': 'name-of-resource'}
            # collection_name does not appear to be used in the legacy code
            # inside the controller logic, so we can assume we do not need it.
            parent = legacy_controller.parent or {}
            parent_resource = parent.get('member_name')
            new_controller = res_ctrl.CollectionsController(
                collection,
                resource,
                resource_info=attr_info,
                parent_resource=parent_resource)
            manager.NeutronManager.set_plugin_for_resource(resource, plugin)
            if path_prefix:
                manager.NeutronManager.add_resource_for_path_prefix(
                    collection, path_prefix)
        elif isinstance(legacy_controller, wsgi.Controller):
            new_controller = utils.ShimCollectionsController(
                collection, None, legacy_controller)
        else:
            LOG.warning(
                _LW("Unknown controller type encountered %s.  It will"
                    "be ignored."), legacy_controller)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)

    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Beispiel #38
0
 def tearDown(self):
     policy.reset()
     super(APIPolicyTestCase, self).tearDown()
Beispiel #39
0
def initialize_all():
    manager.init()
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for all core resources
    plugin = directory.get_plugin()
    for resource, collection in router.RESOURCES.items():
        resource_registry.register_resource_by_name(resource)
        new_controller = res_ctrl.CollectionsController(collection,
                                                        resource,
                                                        plugin=plugin)
        manager.NeutronManager.set_controller_for_resource(
            collection, new_controller)
        manager.NeutronManager.set_plugin_for_resource(collection, plugin)

    pecanized_resources = ext_mgr.get_pecan_resources()
    for pec_res in pecanized_resources:
        manager.NeutronManager.set_controller_for_resource(
            pec_res.collection, pec_res.controller)
        manager.NeutronManager.set_plugin_for_resource(pec_res.collection,
                                                       pec_res.plugin)

    # Now build Pecan Controllers and routes for all extensions
    resources = ext_mgr.get_resources()
    # Extensions controller is already defined, we don't need it.
    resources.pop(0)
    for ext_res in resources:
        path_prefix = ext_res.path_prefix.strip('/')
        collection = ext_res.collection
        # Retrieving the parent resource.  It is expected the format of
        # the parent resource to be:
        # {'collection_name': 'name-of-collection',
        #  'member_name': 'name-of-resource'}
        # collection_name does not appear to be used in the legacy code
        # inside the controller logic, so we can assume we do not need it.
        parent = ext_res.parent or {}
        parent_resource = parent.get('member_name')
        collection_key = collection
        if parent_resource:
            collection_key = '/'.join([parent_resource, collection])
        collection_actions = ext_res.collection_actions
        member_actions = ext_res.member_actions
        if manager.NeutronManager.get_controller_for_resource(collection_key):
            # This is a collection that already has a pecan controller, we
            # do not need to do anything else
            continue
        legacy_controller = getattr(ext_res.controller, 'controller',
                                    ext_res.controller)
        new_controller = None
        if isinstance(legacy_controller, base.Controller):
            resource = legacy_controller.resource
            plugin = legacy_controller.plugin
            attr_info = legacy_controller.attr_info
            member_actions = legacy_controller.member_actions
            pagination = legacy_controller.allow_pagination
            sorting = legacy_controller.allow_sorting
            # NOTE(blogan): legacy_controller and ext_res both can both have
            # member_actions.  the member_actions for ext_res are strictly for
            # routing, while member_actions for legacy_controller are used for
            # handling the request once the routing has found the controller.
            # They're always the same so we will just use the ext_res
            # member_action.
            new_controller = res_ctrl.CollectionsController(
                collection,
                resource,
                resource_info=attr_info,
                parent_resource=parent_resource,
                member_actions=member_actions,
                plugin=plugin,
                allow_pagination=pagination,
                allow_sorting=sorting,
                collection_actions=collection_actions)
            # new_controller.collection has replaced hyphens with underscores
            manager.NeutronManager.set_plugin_for_resource(
                new_controller.collection, plugin)
            if path_prefix:
                manager.NeutronManager.add_resource_for_path_prefix(
                    collection, path_prefix)
        elif isinstance(legacy_controller, wsgi.Controller):
            new_controller = utils.ShimCollectionsController(
                collection,
                None,
                legacy_controller,
                collection_actions=collection_actions,
                member_actions=member_actions)
        else:
            LOG.warning(
                _LW("Unknown controller type encountered %s.  It will"
                    "be ignored."), legacy_controller)
        manager.NeutronManager.set_controller_for_resource(
            collection_key, new_controller)

    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Beispiel #40
0
    def __init__(self, **local_config):
        mapper = routes_mapper.Mapper()
        plugin = manager.NeutronManager.get_plugin(
        )  #core plugin    #/usr/lib/python2.7/site-packages/neutron/manager.py(216)get_plugin()
        # #plugin=<weakproxy at 0x4490208 to Ml2Plugin at 0x2fd1f50>
        ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
        ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
        #attributes.RESOURCE_ATTRIBUTE_MAP会被修改为包含neutron/extensions/xx目录下所有插件定义的资源信息,如routers

        col_kwargs = dict(collection_actions=COLLECTION_ACTIONS,
                          member_actions=MEMBER_ACTIONS)

        #col_kwargs ={'member_actions': ['show', 'update', 'delete'], 'collection_actions': ['index', 'create']}

        def _map_resource(collection, resource, params, parent=None):
            allow_bulk = cfg.CONF.allow_bulk
            allow_pagination = cfg.CONF.allow_pagination
            allow_sorting = cfg.CONF.allow_sorting
            controller = base.create_resource(
                collection,
                resource,
                plugin,
                params,
                allow_bulk=allow_bulk,
                parent=parent,
                allow_pagination=allow_pagination,
                allow_sorting=allow_sorting)
            path_prefix = None
            if parent:
                path_prefix = "/%s/{%s_id}/%s" % (parent['collection_name'],
                                                  parent['member_name'],
                                                  collection)
            mapper_kwargs = dict(controller=controller,
                                 requirements=REQUIREMENTS,
                                 path_prefix=path_prefix,
                                 **col_kwargs)
            #调用mapper对象的collection方法创建URL映射
            return mapper.collection(collection, resource, **mapper_kwargs)

        mapper.connect('index', '/', controller=Index(RESOURCES))
        for resource in RESOURCES:
            _map_resource(
                RESOURCES[resource], resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(RESOURCES[resource],
                                                      dict()))

        for resource in SUB_RESOURCES:
            _map_resource(
                SUB_RESOURCES[resource]['collection_name'], resource,
                attributes.RESOURCE_ATTRIBUTE_MAP.get(
                    SUB_RESOURCES[resource]['collection_name'], dict()),
                SUB_RESOURCES[resource]['parent'])

        # Certain policy checks require that the extensions are loaded
        # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
        # properly initialized. This can only be claimed with certainty
        # once this point in the code has been reached. In the event
        # that the policies have been initialized before this point,
        # calling reset will cause the next policy check to
        # re-initialize with all of the required data in place.
        policy.reset()
        super(APIRouter, self).__init__(mapper)
Beispiel #41
0
 def __init__(self, path):
     LOG.info(_('Initializing extension manager.'))
     self.path = path
     self.extensions = {}
     self._load_all_extensions()
     policy.reset()
Beispiel #42
0
def initialize_all():
    ext_mgr = extensions.PluginAwareExtensionManager.get_instance()
    ext_mgr.extend_resources("2.0", attributes.RESOURCE_ATTRIBUTE_MAP)
    # At this stage we have a fully populated resource attribute map;
    # build Pecan controllers and routes for every resource (both core
    # and extensions)
    pecanized_exts = [
        ext for ext in ext_mgr.extensions.values()
        if hasattr(ext, 'get_pecan_controllers')
    ]
    pecan_controllers = {}
    for ext in pecanized_exts:
        LOG.info(
            _LI("Extension %s is pecan-aware. Fetching resources "
                "and controllers"), ext.get_name())
        controllers = ext.get_pecan_controllers()
        # controllers is actually a list of pairs where the first element is
        # the collection name and the second the actual controller
        for (collection, coll_controller) in controllers:
            pecan_controllers[collection] = coll_controller

    for collection in attributes.RESOURCE_ATTRIBUTE_MAP:
        resource = _handle_plurals(collection)
        controller = pecan_controllers.get(collection)
        if not controller:
            LOG.debug("Building controller for resource:%s", resource)
            plugin = _plugin_for_resource(collection)
            if plugin:
                manager.NeutronManager.set_plugin_for_resource(
                    resource, plugin)
            else:
                LOG.warn(
                    _LW("No plugin found for resource:%s. API calls "
                        "may not be correctly dispatched"), resource)
            controller = root.CollectionsController(collection, resource)
        else:
            LOG.debug("There are already controllers for resource:%s",
                      resource)

        manager.NeutronManager.set_controller_for_resource(
            collection, controller)
        LOG.info(
            _LI("Added controller for resource %(resource)s "
                "via URI path segment:%(collection)s"), {
                    'resource': resource,
                    'collection': collection
                })
    # NOTE(salv-orlando): If you are care about code quality, please read below
    # Hackiness is strong with the piece of code below. It is used for
    # populating resource plurals and registering resources with the quota
    # engine, but the method it calls were not conceived with this aim.
    # Therefore it only leverages side-effects from those methods. Moreover,
    # as it is really not advisable to load an instance of
    # neutron.api.v2.router.APIRouter just to register resources with the
    # quota  engine, core resources are explicitly registered here.
    # TODO(salv-orlando): The Pecan WSGI support should provide its own
    # solution to manage resource plurals and registration of resources with
    # the quota engine
    for resource in router.RESOURCES.keys():
        resource_registry.register_resource_by_name(resource)
    for ext in ext_mgr.extensions.values():
        # make each extension populate its plurals
        if hasattr(ext, 'get_resources'):
            ext.get_resources()
        if hasattr(ext, 'get_extended_resources'):
            ext.get_extended_resources('v2.0')
    # Certain policy checks require that the extensions are loaded
    # and the RESOURCE_ATTRIBUTE_MAP populated before they can be
    # properly initialized. This can only be claimed with certainty
    # once this point in the code has been reached. In the event
    # that the policies have been initialized before this point,
    # calling reset will cause the next policy check to
    # re-initialize with all of the required data in place.
    policy.reset()
Beispiel #43
0
 def tearDown(self):
     policy.reset()
     if self.ATTRIBUTE_MAP_COPY:
         attributes.RESOURCE_ATTRIBUTE_MAP = self.ATTRIBUTE_MAP_COPY
     super(APIPolicyTestCase, self).tearDown()