本文整理汇总了Python中nova.context.require_admin_context函数的典型用法代码示例。如果您正苦于以下问题:Python require_admin_context函数的具体用法?Python require_admin_context怎么用?Python require_admin_context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了require_admin_context函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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}
示例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)
示例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
示例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
示例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})
示例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))
示例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}
示例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)
示例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
示例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)}
示例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)
示例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
示例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())
示例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)}
示例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)