• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python policy.init函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中neutron.policy.init函数的典型用法代码示例。如果您正苦于以下问题:Python init函数的具体用法?Python init怎么用?Python init使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了init函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: update

    def update(self, request, id, body=None, **kwargs):
        """Updates the specified entity's attributes."""
        parent_id = kwargs.get(self._parent_id_name)
        try:
            payload = body.copy()
        except AttributeError:
            msg = _("Invalid format: %s") % request.body
            raise exceptions.BadRequest(resource='body', msg=msg)
        payload['id'] = id
        self._notifier.info(request.context,
                            self._resource + '.update.start',
                            payload)
        body = Controller.prepare_request_body(request.context, body, False,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        action = self._plugin_handlers[self.UPDATE]
        # Load object to check authz
        # but pass only attributes in the original body and required
        # by the policy engine to the policy 'brain'
        field_list = [name for (name, value) in self._attr_info.iteritems()
                      if (value.get('required_by_policy') or
                          value.get('primary_key') or
                          'default' not in value)]
        # Ensure policy engine is initialized
        policy.init()
        orig_obj = self._item(request, id, field_list=field_list,
                              parent_id=parent_id)
        orig_object_copy = copy.copy(orig_obj)
        orig_obj.update(body[self._resource])
        # Make a list of attributes to be updated to inform the policy engine
        # which attributes are set explicitly so that it can distinguish them
        # from the ones that are set to their default values.
        orig_obj[const.ATTRIBUTES_TO_UPDATE] = body[self._resource].keys()
        try:
            policy.enforce(request.context,
                           action,
                           orig_obj)
        except common_policy.PolicyNotAuthorized:
            with excutils.save_and_reraise_exception() as ctxt:
                # If a tenant is modifying it's own object, it's safe to return
                # a 403. Otherwise, pretend that it doesn't exist to avoid
                # giving away information.
                if request.context.tenant_id != orig_obj['tenant_id']:
                    ctxt.reraise = False
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_updater = getattr(self._plugin, action)
        kwargs = {self._resource: body}
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj = obj_updater(request.context, id, **kwargs)
        result = {self._resource: self._view(request.context, obj)}
        notifier_method = self._resource + '.update.end'
        self._notifier.info(request.context, notifier_method, result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)
        self._send_nova_notification(action, orig_object_copy, result)
        return result
开发者ID:insequent,项目名称:neutron,代码行数:60,代码来源:base.py


示例2: delete

    def delete(self, request, id, **kwargs):
        """Deletes the specified entity."""
        self._notifier.info(request.context,
                            self._resource + '.delete.start',
                            {self._resource + '_id': id})
        action = self._plugin_handlers[self.DELETE]

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context,
                           action,
                           obj)
        except common_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_deleter = getattr(self._plugin, action)
        obj_deleter(request.context, id, **kwargs)
        notifier_method = self._resource + '.delete.end'
        self._notifier.info(request.context,
                            notifier_method,
                            {self._resource + '_id': id})
        result = {self._resource: self._view(request.context, obj)}
        self._send_nova_notification(action, {}, result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)
开发者ID:insequent,项目名称:neutron,代码行数:32,代码来源:base.py


示例3: _update

    def _update(self, request, id, body, **kwargs):
        body = Controller.prepare_request_body(
            request.context, copy.deepcopy(body), False, self._resource, self._attr_info, allow_bulk=self._allow_bulk
        )
        action = self._plugin_handlers[self.UPDATE]
        # Load object to check authz
        # but pass only attributes in the original body and required
        # by the policy engine to the policy 'brain'
        field_list = [
            name
            for (name, value) in six.iteritems(self._attr_info)
            if (value.get("required_by_policy") or value.get("primary_key") or "default" not in value)
        ]
        # Ensure policy engine is initialized
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        orig_obj = self._item(request, id, field_list=field_list, parent_id=parent_id)
        orig_object_copy = copy.copy(orig_obj)
        orig_obj.update(body[self._resource])
        # Make a list of attributes to be updated to inform the policy engine
        # which attributes are set explicitly so that it can distinguish them
        # from the ones that are set to their default values.
        orig_obj[n_const.ATTRIBUTES_TO_UPDATE] = body[self._resource].keys()
        try:
            policy.enforce(request.context, action, orig_obj, pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            with excutils.save_and_reraise_exception() as ctxt:
                # If a tenant is modifying it's own object, it's safe to return
                # a 403. Otherwise, pretend that it doesn't exist to avoid
                # giving away information.
                if request.context.tenant_id != orig_obj["tenant_id"]:
                    ctxt.reraise = False
            msg = _("The resource could not be found.")
            raise webob.exc.HTTPNotFound(msg)

        obj_updater = getattr(self._plugin, action)
        kwargs = {self._resource: body}
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj = obj_updater(request.context, id, **kwargs)
        # Usually an update operation does not alter resource usage, but as
        # there might be side effects it might be worth checking for changes
        # in resource usage here as well (e.g: a tenant port is created when a
        # router interface is added)
        resource_registry.set_resources_dirty(request.context)

        result = {self._resource: self._view(request.context, obj)}
        notifier_method = self._resource + ".update.end"
        self._notifier.info(request.context, notifier_method, result)
        registry.notify(
            self._resource,
            events.BEFORE_RESPONSE,
            self,
            context=request.context,
            data=result,
            method_name=notifier_method,
            action=action,
            original=orig_object_copy,
        )
        return result
开发者ID:electrocucaracha,项目名称:neutron,代码行数:60,代码来源:base.py


示例4: _delete

    def _delete(self, request, id, **kwargs):
        action = self._plugin_handlers[self.DELETE]

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context, action, obj, pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _("The resource could not be found.")
            raise webob.exc.HTTPNotFound(msg)

        obj_deleter = getattr(self._plugin, action)
        obj_deleter(request.context, id, **kwargs)
        # A delete operation usually alters resource usage, so mark affected
        # usage trackers as dirty
        resource_registry.set_resources_dirty(request.context)
        notifier_method = self._resource + ".delete.end"
        result = {self._resource: self._view(request.context, obj)}
        notifier_payload = {self._resource + "_id": id}
        notifier_payload.update(result)
        self._notifier.info(request.context, notifier_method, notifier_payload)
        registry.notify(
            self._resource,
            events.BEFORE_RESPONSE,
            self,
            context=request.context,
            data=result,
            method_name=notifier_method,
            action=action,
            original={},
        )
开发者ID:electrocucaracha,项目名称:neutron,代码行数:35,代码来源:base.py


示例5: setUp

    def setUp(self):
        super(BaseTestCase, self).setUp()

        self.useFixture(lockutils.ExternalLockFixture())

        cfg.CONF.set_override("state_path", self.get_default_temp_dir().path)

        self.addCleanup(CONF.reset)
        self.useFixture(ProcessMonitorFixture())

        self.useFixture(
            fixtures.MonkeyPatch(
                "neutron_lib.exceptions.NeutronException.use_fatal_exceptions", fake_use_fatal_exceptions
            )
        )

        self.useFixture(
            fixtures.MonkeyPatch(
                "oslo_config.cfg.find_config_files", lambda project=None, prog=None, extension=None: []
            )
        )

        self.setup_rpc_mocks()
        self.setup_config()
        self.setup_test_registry_instance()
        self.setup_test_directory_instance()

        policy.init()
        self.addCleanup(policy.reset)
        self.addCleanup(resource_registry.unregister_all_resources)
        self.addCleanup(rpc_consumer_reg.clear)
开发者ID:openstack,项目名称:neutron,代码行数:31,代码来源:base.py


示例6: setUp

    def setUp(self):
        super(BaseTestCase, self).setUp()

        self.useFixture(lockutils.ExternalLockFixture())
        self.useFixture(fixture.APIDefinitionFixture())

        cfg.CONF.set_override('state_path', self.get_default_temp_dir().path)

        self.addCleanup(CONF.reset)
        self.useFixture(ProcessMonitorFixture())

        self.useFixture(fixtures.MonkeyPatch(
            'neutron_lib.exceptions.NeutronException.use_fatal_exceptions',
            fake_use_fatal_exceptions))

        self.useFixture(fixtures.MonkeyPatch(
            'oslo_config.cfg.find_config_files',
            lambda project=None, prog=None, extension=None: []))

        self.setup_rpc_mocks()
        self.setup_config()

        self._callback_manager = registry_manager.CallbacksManager()
        self.useFixture(fixture.CallbackRegistryFixture(
            callback_manager=self._callback_manager))
        # Give a private copy of the directory to each test.
        self.useFixture(fixture.PluginDirectoryFixture())

        policy.init()
        self.addCleanup(policy.reset)
        self.addCleanup(resource_registry.unregister_all_resources)
        self.addCleanup(db_api.sqla_remove_all)
        self.addCleanup(rpc_consumer_reg.clear)
        self.addCleanup(rpc_producer_reg.clear)
开发者ID:mmalchuk,项目名称:openstack-neutron,代码行数:34,代码来源:base.py


示例7: _test_enforce_tenant_id_raises

 def _test_enforce_tenant_id_raises(self, bad_rule):
     self.rules["admin_or_owner"] = common_policy.parse_rule(bad_rule)
     # Trigger a policy with rule admin_or_owner
     action = "create_network"
     target = {"tenant_id": "fake"}
     policy.init()
     self.assertRaises(exceptions.PolicyCheckError, policy.enforce, self.context, action, target)
开发者ID:noironetworks,项目名称:neutron2,代码行数:7,代码来源:test_policy.py


示例8: _delete

    def _delete(self, request, id, **kwargs):
        action = self._plugin_handlers[self.DELETE]

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context,
                           action,
                           obj,
                           pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_deleter = getattr(self._plugin, action)
        obj_deleter(request.context, id, **kwargs)
        # A delete operation usually alters resource usage, so mark affected
        # usage trackers as dirty
        resource_registry.set_resources_dirty(request.context)
        notifier_method = self._resource + '.delete.end'
        self._notifier.info(request.context,
                            notifier_method,
                            {self._resource + '_id': id})
        result = {self._resource: self._view(request.context, obj)}
        self._send_nova_notification(action, {}, result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)
开发者ID:Jackwwg,项目名称:neutron,代码行数:32,代码来源:base.py


示例9: before

 def before(self, state):
     if state.request.method not in self.ACTION_MAP:
         pecan.abort(405)
     neutron_context = state.request.context.get('neutron_context')
     resource = state.request.context.get('resource')
     is_update = (state.request.method == 'PUT')
     items = state.request.resources
     policy.init()
     action = '%s_%s' % (self.ACTION_MAP[state.request.method], resource)
     for item in items:
         if is_update:
             obj = copy.copy(state.request.original_object)
             obj.update(item)
             obj[const.ATTRIBUTES_TO_UPDATE] = item.keys()
             item = obj
         try:
             policy.enforce(
                 neutron_context, action, item,
                 pluralized=attribute_population._plural(resource))
         except oslo_policy.PolicyNotAuthorized:
             with excutils.save_and_reraise_exception() as ctxt:
                 # If a tenant is modifying it's own object, it's safe to
                 # return a 403. Otherwise, pretend that it doesn't exist
                 # to avoid giving away information.
                 if (is_update and
                         neutron_context.tenant_id != obj['tenant_id']):
                     ctxt.reraise = False
             msg = _('The resource could not be found.')
             raise webob.exc.HTTPNotFound(msg)
开发者ID:apporc,项目名称:neutron,代码行数:29,代码来源:policy_enforcement.py


示例10: _handle_action

 def _handle_action(request, id, **kwargs):
     arg_list = [request.context, id]
     # Ensure policy engine is initialized
     policy.init()
     # Fetch the resource and verify if the user can access it
     try:
         parent_id = kwargs.get(self._parent_id_name)
         resource = self._item(request,
                               id,
                               do_authz=True,
                               field_list=None,
                               parent_id=parent_id)
     except oslo_policy.PolicyNotAuthorized:
         msg = _('The resource could not be found.')
         raise webob.exc.HTTPNotFound(msg)
     body = copy.deepcopy(kwargs.pop('body', None))
     # Explicit comparison with None to distinguish from {}
     if body is not None:
         arg_list.append(body)
     # It is ok to raise a 403 because accessibility to the
     # object was checked earlier in this method
     policy.enforce(request.context,
                    name,
                    resource,
                    pluralized=self._collection)
     ret_value = getattr(self._plugin, name)(*arg_list, **kwargs)
     # It is simply impossible to predict whether one of this
     # actions alters resource usage. For instance a tenant port
     # is created when a router interface is added. Therefore it is
     # important to mark as dirty resources whose counters have
     # been altered by this operation
     resource_registry.set_resources_dirty(request.context)
     return ret_value
开发者ID:bupthzd,项目名称:neutron,代码行数:33,代码来源:base.py


示例11: delete

    def delete(self, request, id, **kwargs):
        """Deletes the specified entity."""
        self._notifier.info(request.context,
                            self._resource + '.delete.start',
                            {self._resource + '_id': id}) #通知
        action = self._plugin_handlers[self.DELETE]  #获取具体资源操作行为 eg delete_port

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context,
                           action,
                           obj)                                    #检查操作权限
        except exceptions.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_deleter = getattr(self._plugin, action) #获取具体操作方法 eg:M2lplugin类中delete_port
        obj_deleter(request.context, id, **kwargs)  #根据参数,执行具体操作方法
        notifier_method = self._resource + '.delete.end'
        self._notifier.info(request.context,
                            notifier_method,
                            {self._resource + '_id': id}) #消息格式??
        result = {self._resource: self._view(request.context, obj)}
        self._send_nova_notification(action, {}, result)  #通知nova消息,消息内容什么样的?
        self._send_dhcp_notification(request.context,          #通知dhcp消息,消息内容什么样的?
                                     result,
                                     notifier_method)
开发者ID:xiongmeng1108,项目名称:gcloud7_neutron-2014.2.2,代码行数:32,代码来源:base.py


示例12: setUp

    def setUp(self):
        super(BaseTestCase, self).setUp()

        # suppress all but errors here
        capture_logs = bool_from_env('OS_LOG_CAPTURE')
        self.useFixture(
            fixtures.FakeLogger(
                name='neutron.api.extensions',
                format=LOG_FORMAT,
                level=std_logging.ERROR,
                nuke_handlers=capture_logs,
            ))

        self.useFixture(lockutils.ExternalLockFixture())

        cfg.CONF.set_override('state_path', self.get_default_temp_dir().path)

        self.addCleanup(CONF.reset)
        self.useFixture(ProcessMonitorFixture())

        self.useFixture(fixtures.MonkeyPatch(
            'neutron.common.exceptions.NeutronException.use_fatal_exceptions',
            fake_use_fatal_exceptions))

        self.setup_rpc_mocks()
        self.setup_config()

        policy.init()
        self.addCleanup(policy.reset)
开发者ID:CloudA,项目名称:neutron,代码行数:29,代码来源:base.py


示例13: update

    def update(self, request, id, body=None, **kwargs):
        """Updates the specified entity's attributes."""
        parent_id = kwargs.get(self._parent_id_name)
        try:
            payload = body.copy()
        except AttributeError:
            msg = _("Invalid format: %s") % request.body
            raise exceptions.BadRequest(resource='body', msg=msg)
        payload['id'] = id
        notifier_api.notify(request.context,
                            self._publisher_id,
                            self._resource + '.update.start',
                            notifier_api.CONF.default_notification_level,
                            payload)
        body = Controller.prepare_request_body(request.context, body, False,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        action = self._plugin_handlers[self.UPDATE]
        # Load object to check authz
        # but pass only attributes in the original body and required
        # by the policy engine to the policy 'brain'
        field_list = [name for (name, value) in self._attr_info.iteritems()
                      if (value.get('required_by_policy') or
                          value.get('primary_key') or
                          'default' not in value)]
        # Ensure policy engine is initialized
        policy.init()
        orig_obj = self._item(request, id, field_list=field_list,
                              parent_id=parent_id)
        orig_object_copy = copy.copy(orig_obj)
        orig_obj.update(body[self._resource])
        try:
            policy.enforce(request.context,
                           action,
                           orig_obj)
        except exceptions.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_updater = getattr(self._plugin, action)
        kwargs = {self._resource: body}
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj = obj_updater(request.context, id, **kwargs)
        result = {self._resource: self._view(request.context, obj)}
        notifier_method = self._resource + '.update.end'
        notifier_api.notify(request.context,
                            self._publisher_id,
                            notifier_method,
                            notifier_api.CONF.default_notification_level,
                            result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)
        self._nova_notifier.send_network_change(
            action, orig_object_copy, result)
        return result
开发者ID:Zemeio,项目名称:neutron,代码行数:59,代码来源:base.py


示例14: setUp

    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": "role: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()
开发者ID:ArifovicH,项目名称:neutron,代码行数:59,代码来源:test_policy.py


示例15: setUp

 def setUp(self):
     super(TestPaginationAndSorting, self).setUp()
     policy.init()
     self.addCleanup(policy.reset)
     self.plugin = directory.get_plugin()
     self.ctx = context.get_admin_context()
     self._create_networks(self.RESOURCE_COUNT)
     self.networks = self._get_collection()['networks']
开发者ID:eayunstack,项目名称:neutron,代码行数:8,代码来源:test_controllers.py


示例16: delete

    def delete(self, request, id, **kwargs):
        """Deletes the specified entity."""
        self._notifier.info(request.context,
                            self._resource + '.delete.start',
                            {self._resource + '_id': id})
        action = self._plugin_handlers[self.DELETE]

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context,
                           action,
                           obj)
        except exceptions.PolicyNotAuthorized:
            with excutils.save_and_reraise_exception() as ctxt:
                # if the tenant id is same, reraise
                # otherwise pretend
                if request.context.tenant_id != obj['tenant_id']:
                    ctxt.reraise = False
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)
        filters = api_common.get_filters(
            request, self._attr_info, keeps_pre='_x_')
        if not kwargs:
            kwargs = {}
        if filters:
            kwargs['filters'] = filters
        obj_deleter = getattr(self._plugin, action)
        if kwargs:
            obj_deleter(request.context, id, **kwargs)
        else:
            obj_deleter(request.context, id)
        result = {self._resource: self._view(request.context, obj)}
        notifier_method = self._resource + '.delete.end'
        delete_notification_dict = result.copy()
        delete_notification_dict[self._resource + '_id'] = id
        data = {}
        for attr, attr_vals in self._attr_info.iteritems():
            delete_notification = attr_vals.get('delete_notification')
            if delete_notification:
                data[attr] = obj[attr]
        if data:
            delete_notification_dict['_x_data'] = data
        self._notifier.info(request.context,
                            notifier_method,
                            delete_notification_dict)

        self._send_nova_notification(action, {}, result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)
开发者ID:CingHu,项目名称:neutron-ustack,代码行数:55,代码来源:base.py


示例17: before

    def before(self, state):
        # This hook should be run only for PUT,POST and DELETE methods and for
        # requests targeting a neutron resource
        resources = state.request.context.get('resources', [])
        if state.request.method not in ('POST', 'PUT', 'DELETE'):
            return
        # As this routine will likely alter the resources, do a shallow copy
        resources_copy = resources[:]
        neutron_context = state.request.context.get('neutron_context')
        resource = state.request.context.get('resource')
        # If there is no resource for this request, don't bother running authZ
        # policies
        if not resource:
            return
        collection = state.request.context.get('collection')
        needs_prefetch = (state.request.method == 'PUT' or
                          state.request.method == 'DELETE')
        policy.init()
        action = '%s_%s' % (self.ACTION_MAP[state.request.method], resource)

        # NOTE(salv-orlando): As bulk updates are not supported, in case of PUT
        # requests there will be only a single item to process, and its
        # identifier would have been already retrieved by the lookup process;
        # in the case of DELETE requests there won't be any item to process in
        # the request body
        if needs_prefetch:
            try:
                item = resources_copy.pop()
            except IndexError:
                # Ops... this was a delete after all!
                item = {}
            resource_id = state.request.context.get('resource_id')
            obj = copy.copy(self._fetch_resource(neutron_context,
                                                 resource,
                                                 resource_id))
            obj.update(item)
            obj[const.ATTRIBUTES_TO_UPDATE] = item.keys()
            # Put back the item in the list so that policies could be enforced
            resources_copy.append(obj)

        for item in resources_copy:
            try:
                policy.enforce(
                    neutron_context, action, item,
                    pluralized=collection)
            except oslo_policy.PolicyNotAuthorized:
                with excutils.save_and_reraise_exception() as ctxt:
                    # If a tenant is modifying it's own object, it's safe to
                    # return a 403. Otherwise, pretend that it doesn't exist
                    # to avoid giving away information.
                    if (needs_prefetch and
                        neutron_context.tenant_id != item['tenant_id']):
                        ctxt.reraise = False
                msg = _('The resource could not be found.')
                raise webob.exc.HTTPNotFound(msg)
开发者ID:TonyChengTW,项目名称:OpenStack_Liberty_Control,代码行数:55,代码来源:policy_enforcement.py


示例18: setUp

    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")
开发者ID:kbijon,项目名称:OpenStack-CVRM,代码行数:11,代码来源:test_policy.py


示例19: before

    def before(self, state):
        # This hook should be run only for PUT,POST and DELETE methods and for
        # requests targeting a neutron resource
        resources = state.request.context.get("resources", [])
        if state.request.method not in ("POST", "PUT", "DELETE"):
            return
        # As this routine will likely alter the resources, do a shallow copy
        resources_copy = resources[:]
        neutron_context = state.request.context.get("neutron_context")
        resource = state.request.context.get("resource")
        # If there is no resource for this request, don't bother running authZ
        # policies
        if not resource:
            return
        collection = state.request.context.get("collection")
        needs_prefetch = state.request.method == "PUT" or state.request.method == "DELETE"
        policy.init()
        action = "%s_%s" % (pecan_constants.ACTION_MAP[state.request.method], resource)

        # NOTE(salv-orlando): As bulk updates are not supported, in case of PUT
        # requests there will be only a single item to process, and its
        # identifier would have been already retrieved by the lookup process;
        # in the case of DELETE requests there won't be any item to process in
        # the request body
        merged_resources = []
        if needs_prefetch:
            try:
                item = resources_copy.pop()
            except IndexError:
                # Ops... this was a delete after all!
                item = {}
            resource_id = state.request.context.get("resource_id")
            obj = copy.copy(self._fetch_resource(neutron_context, resource, resource_id))
            obj.update(item)
            merged_resources.append(obj.copy())
            obj[const.ATTRIBUTES_TO_UPDATE] = item.keys()
            # Put back the item in the list so that policies could be enforced
            resources_copy.append(obj)
        # TODO(salv-orlando): as other hooks might need to prefetch resources,
        # store them in the request context. However, this should be done in a
        # separate hook which is conventietly called before all other hooks
        state.request.context["request_resources"] = merged_resources
        for item in resources_copy:
            try:
                policy.enforce(neutron_context, action, item, pluralized=collection)
            except oslo_policy.PolicyNotAuthorized:
                with excutils.save_and_reraise_exception() as ctxt:
                    # If a tenant is modifying it's own object, it's safe to
                    # return a 403. Otherwise, pretend that it doesn't exist
                    # to avoid giving away information.
                    if needs_prefetch and neutron_context.tenant_id != item["tenant_id"]:
                        ctxt.reraise = False
                msg = _("The resource could not be found.")
                raise webob.exc.HTTPNotFound(msg)
开发者ID:dims,项目名称:neutron,代码行数:54,代码来源:policy_enforcement.py


示例20: setUp

 def setUp(self):
     fake_ext = pecan_utils.FakeExtension()
     fake_plugin = pecan_utils.FakePlugin()
     plugins = {pecan_utils.FakePlugin.PLUGIN_TYPE: fake_plugin}
     new_extensions = {fake_ext.get_alias(): fake_ext}
     super(TestShimControllers, self).setUp(service_plugins=plugins, extensions=new_extensions)
     policy.init()
     policy._ENFORCER.set_rules(
         oslo_policy.Rules.from_dict({"get_meh_meh": "", "get_meh_mehs": "", "get_fake_subresources": ""}),
         overwrite=False,
     )
     self.addCleanup(policy.reset)
开发者ID:sebrandon1,项目名称:neutron,代码行数:12,代码来源:test_controllers.py



注:本文中的neutron.policy.init函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python policy.refresh函数代码示例发布时间:2022-05-27
下一篇:
Python policy.get_admin_roles函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap