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

Python context.require_admin_context函数代码示例

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

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



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

示例1: create

    def create(self, req, body):
        context = sg._authorize_context(req)
        authorize(context)
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.
        nova_context.require_admin_context(context)

        sg_rule = self._from_body(body, 'security_group_default_rule')

        try:
            values = self._rule_args_to_dict(to_port=sg_rule.get('to_port'),
                from_port=sg_rule.get('from_port'),
                ip_protocol=sg_rule.get('ip_protocol'),
                cidr=sg_rule.get('cidr'))
        except Exception as exp:
            raise exc.HTTPBadRequest(explanation=six.text_type(exp))

        if values is None:
            msg = _('Not enough parameters to build a valid rule.')
            raise exc.HTTPBadRequest(explanation=msg)

        if self.security_group_api.default_rule_exists(context, values):
            msg = _('This default rule already exists.')
            raise exc.HTTPConflict(explanation=msg)
        security_group_rule = self.security_group_api.add_default_rules(
            context, [values])[0]
        fmt_rule = self._format_security_group_default_rule(
                                                        security_group_rule)
        return {'security_group_default_rule': fmt_rule}
开发者ID:anantk,项目名称:nova,代码行数:29,代码来源:security_group_default_rules.py


示例2: servers

    def servers(self, req, id):
        context = req.environ['nova.context']
        authorize(context)

        # NOTE(eliqiao): back-compatible with db layer hard-code admin
        # permission checks. This has to be left only for API v2.0 because
        # this version has to be stable even if it means that only admins
        # can call this method while the policy could be changed.
        nova_context.require_admin_context(context)

        compute_nodes = self.host_api.compute_node_search_by_hypervisor(
                context, id)
        if not compute_nodes:
            msg = _("No hypervisor matching '%s' could be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)
        hypervisors = []
        for compute_node in compute_nodes:
            instances = self.host_api.instance_get_all_by_host(context,
                    compute_node.host)
            service = self.host_api.service_get_by_compute_host(
                context, compute_node.host)
            hyp = self._view_hypervisor(compute_node, service, False,
                                        instances)
            hypervisors.append(hyp)
        return dict(hypervisors=hypervisors)
开发者ID:375670450,项目名称:nova,代码行数:25,代码来源:hypervisors.py


示例3: _get_floating_ip_info

    def _get_floating_ip_info(self, context, host=None):
        floating_ip_info = {"floating_ip_info": []}
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.
        nova_context.require_admin_context(context)

        if host is None:
            try:
                floating_ips = objects.FloatingIPList.get_all(context)
            except exception.NoFloatingIpsDefined:
                return floating_ip_info
        else:
            try:
                floating_ips = objects.FloatingIPList.get_by_host(context,
                                                                  host)
            except exception.FloatingIpNotFoundForHost as e:
                raise webob.exc.HTTPNotFound(explanation=e.format_message())

        for floating_ip in floating_ips:
            instance_uuid = None
            fixed_ip = None
            if floating_ip.fixed_ip:
                instance_uuid = floating_ip.fixed_ip.instance_uuid
                fixed_ip = str(floating_ip.fixed_ip.address)

            result = {'address': str(floating_ip.address),
                      'pool': floating_ip.pool,
                      'interface': floating_ip.interface,
                      'project_id': floating_ip.project_id,
                      'instance_uuid': instance_uuid,
                      'fixed_ip': fixed_ip}
            floating_ip_info['floating_ip_info'].append(result)

        return floating_ip_info
开发者ID:BeyondTheClouds,项目名称:nova,代码行数:34,代码来源:floating_ips_bulk.py


示例4: _get_services

    def _get_services(self, req):
        api_services = ('nova-osapi_compute', 'nova-ec2', 'nova-metadata')

        context = req.environ['nova.context']
        authorize(context)

        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks
        nova_context.require_admin_context(context)

        services = [
            s
            for s in self.host_api.service_get_all(context, set_zones=True)
            if s['binary'] not in api_services
        ]

        host = ''
        if 'host' in req.GET:
            host = req.GET['host']
        binary = ''
        if 'binary' in req.GET:
            binary = req.GET['binary']
        if host:
            services = [s for s in services if s['host'] == host]
        if binary:
            services = [s for s in services if s['binary'] == binary]

        return services
开发者ID:375670450,项目名称:nova,代码行数:28,代码来源:services.py


示例5: update

    def update(self, req, id, body):
        """Add or modify domain entry."""
        context = req.environ['nova.context']
        authorize(context)
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.
        nova_context.require_admin_context(context)
        fqdomain = _unquote_domain(id)
        try:
            entry = body['domain_entry']
            scope = entry['scope']
        except (TypeError, KeyError):
            raise webob.exc.HTTPUnprocessableEntity()
        project = entry.get('project', None)
        av_zone = entry.get('availability_zone', None)
        if (scope not in ('private', 'public') or
            project and av_zone or
            scope == 'private' and project or
                scope == 'public' and av_zone):
            raise webob.exc.HTTPUnprocessableEntity()
        if scope == 'private':
            create_dns_domain = self.network_api.create_private_dns_domain
            area_name, area = 'availability_zone', av_zone
        else:
            create_dns_domain = self.network_api.create_public_dns_domain
            area_name, area = 'project', project
        try:
            create_dns_domain(context, fqdomain, area)
        except NotImplementedError:
            msg = _("Unable to create dns domain")
            raise webob.exc.HTTPNotImplemented(explanation=msg)

        return _translate_domain_entry_view({'domain': fqdomain,
                                             'scope': scope,
                                             area_name: area})
开发者ID:375670450,项目名称:nova,代码行数:35,代码来源:floating_ip_dns.py


示例6: update

    def update(self, req, id, body):
        """Update a child cell entry.  'id' is the cell name to update."""
        context = req.environ['nova.context']

        authorize(context)
        authorize(context, action="update")
        # NOTE(eliqiao): back-compatible with db layer hard-code admin
        # permission checks.
        nova_context.require_admin_context(context)

        if 'cell' not in body:
            msg = _("No cell information in request")
            raise exc.HTTPBadRequest(explanation=msg)
        cell = body['cell']
        cell.pop('id', None)
        if 'name' in cell:
            self._validate_cell_name(cell['name'])
        try:
            # NOTE(Vek): There is a race condition here if multiple
            #            callers are trying to update the cell
            #            information simultaneously.  Since this
            #            operation is administrative in nature, and
            #            will be going away in the future, I don't see
            #            it as much of a problem...
            existing = self.cells_rpcapi.cell_get(context, id)
        except exception.CellNotFound:
            raise exc.HTTPNotFound()
        self._normalize_cell(cell, existing)
        try:
            cell = self.cells_rpcapi.cell_update(context, id, cell)
        except exception.CellNotFound:
            raise exc.HTTPNotFound()
        except exception.CellsUpdateUnsupported as e:
            raise exc.HTTPForbidden(explanation=e.format_message())
        return dict(cell=_scrub_cell(cell))
开发者ID:EnKalvi,项目名称:nova,代码行数:35,代码来源:cells.py


示例7: index

    def index(self, req):
        """Returns a dict in the format:

        |  {'hosts': [{'host_name': 'some.host.name',
        |     'service': 'cells',
        |     'zone': 'internal'},
        |    {'host_name': 'some.other.host.name',
        |     'service': 'cells',
        |     'zone': 'internal'},
        |    {'host_name': 'some.celly.host.name',
        |     'service': 'cells',
        |     'zone': 'internal'},
        |    {'host_name': 'console1.host.com',
        |     'service': 'consoleauth',
        |     'zone': 'internal'},
        |    {'host_name': 'network1.host.com',
        |     'service': 'network',
        |     'zone': 'internal'},
        |    {'host_name': 'netwwork2.host.com',
        |     'service': 'network',
        |     'zone': 'internal'},
        |    {'host_name': 'compute1.host.com',
        |     'service': 'compute',
        |     'zone': 'nova'},
        |    {'host_name': 'compute2.host.com',
        |     'service': 'compute',
        |     'zone': 'nova'},
        |    {'host_name': 'sched1.host.com',
        |     'service': 'scheduler',
        |     'zone': 'internal'},
        |    {'host_name': 'sched2.host.com',
        |     'service': 'scheduler',
        |     'zone': 'internal'},
        |    {'host_name': 'vol1.host.com',
        |     'service': 'volume',
        |     'zone': 'internal'}]}

        """
        context = req.environ['nova.context']
        authorize(context)

        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks
        nova_context.require_admin_context(context)

        filters = {'disabled': False}
        zone = req.GET.get('zone', None)
        if zone:
            filters['availability_zone'] = zone
        services = self.api.service_get_all(context, filters=filters,
                                            set_zones=True)
        hosts = []
        api_services = ('nova-osapi_compute', 'nova-ec2', 'nova-metadata')
        for service in services:
            if service.binary not in api_services:
                hosts.append({'host_name': service['host'],
                              'service': service['topic'],
                              'zone': service['availability_zone']})
        return {'hosts': hosts}
开发者ID:B3n0n3,项目名称:nova,代码行数:59,代码来源:hosts.py


示例8: detail

 def detail(self, req):
     """Returns a detailed list of availability zone."""
     context = req.environ['nova.context']
     authorize_detail(context)
     # NOTE(alex_xu): back-compatible with db layer hard-code admin
     # permission checks.
     nova_context.require_admin_context(context)
     return self._describe_availability_zones_verbose(context)
开发者ID:375670450,项目名称:nova,代码行数:8,代码来源:availability_zone.py


示例9: update

    def update(self, req, id, body):
        """Updates a specified body.

        :param body: example format {'status': 'enable',
                                     'maintenance_mode': 'enable'}
        """
        def read_enabled(orig_val, msg):
            """Checks a specified orig_val and returns True for 'enabled'
            and False for 'disabled'.

            :param orig_val: A string with either 'enable' or 'disable'. May
                             be surrounded by whitespace, and case doesn't
                             matter
            :param msg: The message to be passed to HTTPBadRequest. A single
                        %s will be replaced with orig_val.
            """
            val = orig_val.strip().lower()
            if val == "enable":
                return True
            elif val == "disable":
                return False
            else:
                raise webob.exc.HTTPBadRequest(explanation=msg % orig_val)
        context = req.environ['nova.context']
        authorize(context)

        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks. This has to be left only for API v2.0 because
        # this version has to be stable even if it means that only admins
        # can call this method while the policy could be changed.
        nova_context.require_admin_context(context)

        # See what the user wants to 'update'
        params = {k.strip().lower(): v for k, v in six.iteritems(body)}
        orig_status = status = params.pop('status', None)
        orig_maint_mode = maint_mode = params.pop('maintenance_mode', None)
        # Validate the request
        if len(params) > 0:
            # Some extra param was passed. Fail.
            explanation = _("Invalid update setting: '%s'") % list(
                params.keys())[0]
            raise webob.exc.HTTPBadRequest(explanation=explanation)
        if orig_status is not None:
            status = read_enabled(orig_status, _("Invalid status: '%s'"))
        if orig_maint_mode is not None:
            maint_mode = read_enabled(orig_maint_mode, _("Invalid mode: '%s'"))
        if status is None and maint_mode is None:
            explanation = _("'status' or 'maintenance_mode' needed for "
                            "host update")
            raise webob.exc.HTTPBadRequest(explanation=explanation)
        # Make the calls and merge the results
        result = {'host': id}
        if status is not None:
            result['status'] = self._set_enabled_status(context, id, status)
        if maint_mode is not None:
            result['maintenance_mode'] = self._set_host_maintenance(context,
                id, maint_mode)
        return result
开发者ID:B3n0n3,项目名称:nova,代码行数:58,代码来源:hosts.py


示例10: index

 def index(self, req):
     """Return all migrations in progress."""
     context = req.environ['nova.context']
     authorize(context, "index")
     # NOTE(alex_xu): back-compatible with db layer hard-code admin
     # permission checks.
     nova_context.require_admin_context(context)
     migrations = self.compute_api.get_migrations(context, req.GET)
     return {'migrations': output(migrations)}
开发者ID:runt18,项目名称:nova,代码行数:9,代码来源:migrations.py


示例11: _create

    def _create(self, req, body):
        context = req.environ['nova.context']
        authorize(context)

        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks.
        nova_context.require_admin_context(context)

        if not self.is_valid_body(body, 'flavor'):
            msg = _("Invalid request body")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        vals = body['flavor']
        name = vals.get('name')
        if name is None:
            msg = _("A valid name parameter is required")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        flavorid = vals.get('id')
        memory = vals.get('ram')
        if memory is None:
            msg = _("A valid ram parameter is required")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        vcpus = vals.get('vcpus')
        if vcpus is None:
            msg = _("A valid vcpus parameter is required")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        root_gb = vals.get('disk')
        if root_gb is None:
            msg = _("A valid disk parameter is required")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        ephemeral_gb = vals.get('OS-FLV-EXT-DATA:ephemeral', 0)
        swap = vals.get('swap', 0)
        rxtx_factor = vals.get('rxtx_factor', 1.0)
        is_public = vals.get('os-flavor-access:is_public', True)

        try:
            flavor = flavors.create(name, memory, vcpus, root_gb,
                                    ephemeral_gb=ephemeral_gb,
                                    flavorid=flavorid, swap=swap,
                                    rxtx_factor=rxtx_factor,
                                    is_public=is_public)
            req.cache_db_flavor(flavor)
        except (exception.FlavorExists,
                exception.FlavorIdExists) as err:
            raise webob.exc.HTTPConflict(explanation=err.format_message())
        except exception.InvalidInput as exc:
            raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
        except exception.FlavorCreateFailed as exc:
            raise webob.exc.HTTPInternalServerError(explanation=
                exc.format_message())

        return self._view_builder.show(req, flavor)
开发者ID:Dynavisor,项目名称:nova,代码行数:55,代码来源:flavormanage.py


示例12: update

    def update(self, req, id, body):
        """Enable/Disable scheduling for a service."""
        context = req.environ['nova.context']
        authorize(context)
        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks
        nova_context.require_admin_context(context)
        ext_loaded = self.ext_mgr.is_loaded('os-extended-services')
        if id == "enable":
            disabled = False
            status = "enabled"
        elif (id == "disable" or
                (id == "disable-log-reason" and ext_loaded)):
            disabled = True
            status = "disabled"
        else:
            msg = _("Unknown action")
            raise webob.exc.HTTPNotFound(explanation=msg)
        try:
            host = body['host']
            binary = body['binary']
            ret_value = {
                'service': {
                    'host': host,
                    'binary': binary,
                    'status': status,
                },
            }
            status_detail = {
                'disabled': disabled,
                'disabled_reason': None,
            }
            if id == "disable-log-reason":
                reason = body['disabled_reason']
                if not self._is_valid_as_reason(reason):
                    msg = _('The string containing the reason for disabling '
                            'the service contains invalid characters or is '
                            'too long.')
                    raise webob.exc.HTTPBadRequest(explanation=msg)

                status_detail['disabled_reason'] = reason
                ret_value['service']['disabled_reason'] = reason
        except (TypeError, KeyError):
            msg = _('Invalid attribute in the request')
            if 'host' in body and 'binary' in body:
                msg = _('Missing disabled reason field')
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            self.host_api.service_update(context, host, binary, status_detail)
        except exception.HostBinaryNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())

        return ret_value
开发者ID:Francis-Liu,项目名称:animated-broccoli,代码行数:54,代码来源:services.py


示例13: delete

 def delete(self, req, id):
     """Deletes an existing agent build."""
     context = req.environ['nova.context']
     authorize(context)
     # NOTE(alex_xu): back-compatible with db layer hard-code admin
     # permission checks.
     nova_context.require_admin_context(context)
     try:
         agent = objects.Agent(context=context, id=id)
         agent.destroy()
     except exception.AgentBuildNotFound as ex:
         raise webob.exc.HTTPNotFound(explanation=ex.format_message())
开发者ID:Dynavisor,项目名称:nova,代码行数:12,代码来源:agents.py


示例14: create

    def create(self, req, body):
        context = req.environ["nova.context"]
        authorize(context)
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.  call db API objects.Network.create
        nova_context.require_admin_context(context)

        def bad(e):
            return exc.HTTPBadRequest(explanation=e)

        if not (body and body.get("network")):
            raise bad(_("Missing network in body"))

        params = body["network"]
        if not params.get("label"):
            raise bad(_("Network label is required"))

        cidr = params.get("cidr") or params.get("cidr_v6")
        if not cidr:
            raise bad(_("Network cidr or cidr_v6 is required"))

        if params.get("project_id") == "":
            params["project_id"] = None

        params["num_networks"] = 1
        try:
            params["network_size"] = netaddr.IPNetwork(cidr).size
        except netaddr.AddrFormatError:
            msg = _("%s is not a valid ip network") % cidr
            raise exc.HTTPBadRequest(explanation=msg)

        if not self.extended:
            create_params = ("allowed_start", "allowed_end")
            for field in extended_fields + create_params:
                if field in params:
                    del params[field]

        try:
            network = self.network_api.create(context, **params)[0]
        except (
            exception.InvalidCidr,
            exception.InvalidIntValue,
            exception.InvalidAddress,
            exception.NetworkNotCreated,
        ) as ex:
            raise exc.HTTPBadRequest(explanation=ex.format_message)
        except exception.CidrConflict as ex:
            raise exc.HTTPConflict(explanation=ex.format_message())
        return {"network": network_dict(context, network, self.extended)}
开发者ID:jorgevgut,项目名称:nova,代码行数:49,代码来源:os_networks.py


示例15: _disassociate_host_and_project

    def _disassociate_host_and_project(self, req, id, body):
        context = req.environ["nova.context"]
        authorize(context)
        # NOTE(shaohe-feng): back-compatible with db layer hard-code
        # admin permission checks.  call db API objects.Network.associate
        nova_context.require_admin_context(context)

        try:
            self.network_api.associate(context, id, host=None, project=None)
        except exception.NetworkNotFound:
            msg = _("Network not found")
            raise exc.HTTPNotFound(explanation=msg)
        except NotImplementedError:
            msg = _("Disassociate network is not implemented by the " "configured Network API")
            raise exc.HTTPNotImplemented(explanation=msg)
        return webob.Response(status_int=202)
开发者ID:jorgevgut,项目名称:nova,代码行数:16,代码来源:os_networks.py


示例16: index

    def index(self, req, flavor_id):
        context = req.environ['nova.context']
        authorize(context)
        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks.
        nova_context.require_admin_context(context)

        flavor = common.get_flavor(context, flavor_id)

        # public flavor to all projects
        if flavor.is_public:
            explanation = _("Access list not available for public flavors.")
            raise webob.exc.HTTPNotFound(explanation=explanation)

        # private flavor to listed projects only
        return _marshall_flavor_access(flavor)
开发者ID:375670450,项目名称:nova,代码行数:16,代码来源:flavor_access.py


示例17: delete

    def delete(self, req, id):
        """Deletes the specified service."""
        if not self.ext_mgr.is_loaded('os-extended-services-delete'):
            raise webob.exc.HTTPMethodNotAllowed()

        context = req.environ['nova.context']
        authorize(context)
        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks
        nova_context.require_admin_context(context)

        try:
            self.host_api.service_delete(context, id)
        except exception.ServiceNotFound:
            explanation = _("Service %s not found.") % id
            raise webob.exc.HTTPNotFound(explanation=explanation)
开发者ID:Dynavisor,项目名称:nova,代码行数:16,代码来源:services.py


示例18: _delete

    def _delete(self, req, id):
        context = req.environ['nova.context']
        authorize(context)

        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks.
        nova_context.require_admin_context(context)

        try:
            flavor = flavors.get_flavor_by_flavor_id(
                    id, ctxt=context, read_deleted="no")
        except exception.FlavorNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())

        flavors.destroy(flavor['name'])

        return webob.Response(status_int=202)
开发者ID:Dynavisor,项目名称:nova,代码行数:17,代码来源:flavormanage.py


示例19: delete

    def delete(self, req, id):
        """Delete a child or parent cell entry.  'id' is a cell name."""
        context = req.environ['nova.context']

        authorize(context)
        authorize(context, action="delete")
        # NOTE(eliqiao): back-compatible with db layer hard-code admin
        # permission checks.
        nova_context.require_admin_context(context)

        try:
            num_deleted = self.cells_rpcapi.cell_delete(context, id)
        except exception.CellsUpdateUnsupported as e:
            raise exc.HTTPForbidden(explanation=e.format_message())
        if num_deleted == 0:
            raise exc.HTTPNotFound()
        return {}
开发者ID:EnKalvi,项目名称:nova,代码行数:17,代码来源:cells.py


示例20: index

    def index(self, req):
        context = req.environ['nova.context']
        authorize(context)

        # NOTE(eliqiao): back-compatible with db layer hard-code admin
        # permission checks. This has to be left only for API v2.0 because
        # this version has to be stable even if it means that only admins
        # can call this method while the policy could be changed.
        nova_context.require_admin_context(context)

        compute_nodes = self.host_api.compute_node_get_all(context)
        req.cache_db_compute_nodes(compute_nodes)
        return dict(hypervisors=[self._view_hypervisor(
                                 hyp,
                                 self.host_api.service_get_by_compute_host(
                                     context, hyp.host),
                                 False)
                                 for hyp in compute_nodes])
开发者ID:375670450,项目名称:nova,代码行数:18,代码来源:hypervisors.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python context.target_cell函数代码示例发布时间:2022-05-27
下一篇:
Python context.get_context函数代码示例发布时间: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