本文整理汇总了Python中nova.api.openstack.api_version_request.is_supported函数的典型用法代码示例。如果您正苦于以下问题:Python is_supported函数的具体用法?Python is_supported怎么用?Python is_supported使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_supported函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _format_server_group
def _format_server_group(self, context, group, req):
# the id field has its value as the uuid of the server group
# There is no 'uuid' key in server_group seen by clients.
# In addition, clients see policies as a ["policy-name"] list;
# and they see members as a ["server-id"] list.
server_group = {}
server_group['id'] = group.uuid
server_group['name'] = group.name
if api_version_request.is_supported(
req, min_version=GROUP_POLICY_OBJ_MICROVERSION):
server_group['policy'] = group.policy
server_group['rules'] = group.rules
else:
server_group['policies'] = group.policies or []
# NOTE(yikun): Before v2.64, a empty metadata is exposed to the
# user, and it is removed since v2.64.
server_group['metadata'] = {}
members = []
if group.members:
# Display the instances that are not deleted.
members = _get_not_deleted(context, group.members)
server_group['members'] = members
# Add project id information to the response data for
# API version v2.13
if api_version_request.is_supported(req, min_version="2.13"):
server_group['project_id'] = group.project_id
server_group['user_id'] = group.user_id
return server_group
示例2: _get_server_search_options
def _get_server_search_options(self, req):
"""Return server search options allowed by non-admin."""
opt_list = ('reservation_id', 'name', 'status', 'image', 'flavor',
'ip', 'changes-since', 'all_tenants')
if api_version_request.is_supported(req, min_version='2.5'):
opt_list += ('ip6',)
if api_version_request.is_supported(req, min_version='2.26'):
opt_list += TAG_SEARCH_FILTERS
return opt_list
示例3: _migrate_live
def _migrate_live(self, req, id, body):
"""Permit admins to (live) migrate a server to a new host."""
context = req.environ["nova.context"]
context.can(ms_policies.POLICY_ROOT % 'migrate_live')
host = body["os-migrateLive"]["host"]
block_migration = body["os-migrateLive"]["block_migration"]
force = None
async_ = api_version_request.is_supported(req, min_version='2.34')
if api_version_request.is_supported(req, min_version='2.30'):
force = self._get_force_param_for_live_migration(body, host)
if api_version_request.is_supported(req, min_version='2.25'):
if block_migration == 'auto':
block_migration = None
else:
block_migration = strutils.bool_from_string(block_migration,
strict=True)
disk_over_commit = None
else:
disk_over_commit = body["os-migrateLive"]["disk_over_commit"]
block_migration = strutils.bool_from_string(block_migration,
strict=True)
disk_over_commit = strutils.bool_from_string(disk_over_commit,
strict=True)
instance = common.get_instance(self.compute_api, context, id)
try:
self.compute_api.live_migrate(context, instance, block_migration,
disk_over_commit, host, force,
async_)
except exception.InstanceUnknownCell as e:
raise exc.HTTPNotFound(explanation=e.format_message())
except (exception.NoValidHost,
exception.ComputeServiceUnavailable,
exception.InvalidHypervisorType,
exception.InvalidCPUInfo,
exception.UnableToMigrateToSelf,
exception.DestinationHypervisorTooOld,
exception.InvalidLocalStorage,
exception.InvalidSharedStorage,
exception.HypervisorUnavailable,
exception.MigrationPreCheckError) as ex:
if async_:
with excutils.save_and_reraise_exception():
LOG.error("Unexpected exception received from "
"conductor during pre-live-migration checks "
"'%(ex)s'", {'ex': ex})
else:
raise exc.HTTPBadRequest(explanation=ex.format_message())
except exception.InstanceIsLocked as e:
raise exc.HTTPConflict(explanation=e.format_message())
except exception.ComputeHostNotFound as e:
raise exc.HTTPBadRequest(explanation=e.format_message())
except exception.InstanceInvalidState as state_error:
common.raise_http_conflict_for_instance_invalid_state(state_error,
'os-migrateLive', id)
示例4: test_is_supported_max_version
def test_is_supported_max_version(self):
req = fakes.HTTPRequest.blank('/fake', version='2.5')
self.assertFalse(api_version_request.is_supported(
req, max_version='2.4'))
self.assertTrue(api_version_request.is_supported(
req, max_version='2.5'))
self.assertTrue(api_version_request.is_supported(
req, max_version='2.6'))
示例5: _evacuate
def _evacuate(self, req, id, body):
"""Permit admins to evacuate a server from a failed host
to a new one.
"""
context = req.environ["nova.context"]
instance = common.get_instance(self.compute_api, context, id)
context.can(evac_policies.BASE_POLICY_NAME,
target={'user_id': instance.user_id,
'project_id': instance.project_id})
evacuate_body = body["evacuate"]
host = evacuate_body.get("host")
force = None
on_shared_storage = self._get_on_shared_storage(req, evacuate_body)
if api_version_request.is_supported(req, min_version='2.29'):
force = body["evacuate"].get("force", False)
force = strutils.bool_from_string(force, strict=True)
if force is True and not host:
message = _("Can't force to a non-provided destination")
raise exc.HTTPBadRequest(explanation=message)
if api_version_request.is_supported(req, min_version='2.14'):
password = self._get_password_v214(req, evacuate_body)
else:
password = self._get_password(req, evacuate_body,
on_shared_storage)
if host is not None:
try:
self.host_api.service_get_by_compute_host(context, host)
except (exception.ComputeHostNotFound,
exception.HostMappingNotFound):
msg = _("Compute host %s not found.") % host
raise exc.HTTPNotFound(explanation=msg)
if instance.host == host:
msg = _("The target host can't be the same one.")
raise exc.HTTPBadRequest(explanation=msg)
try:
self.compute_api.evacuate(context, instance, host,
on_shared_storage, password, force)
except exception.InstanceUnknownCell as e:
raise exc.HTTPNotFound(explanation=e.format_message())
except exception.InstanceInvalidState as state_error:
common.raise_http_conflict_for_instance_invalid_state(state_error,
'evacuate', id)
except exception.ComputeServiceInUse as e:
raise exc.HTTPBadRequest(explanation=e.format_message())
if (not api_version_request.is_supported(req, min_version='2.14') and
CONF.api.enable_instance_password):
return {'adminPass': password}
else:
return None
示例6: _create_backup
def _create_backup(self, req, id, body):
"""Backup a server instance.
Images now have an `image_type` associated with them, which can be
'snapshot' or the backup type, like 'daily' or 'weekly'.
If the image_type is backup-like, then the rotation factor can be
included and that will cause the oldest backups that exceed the
rotation factor to be deleted.
"""
context = req.environ["nova.context"]
context.can(cb_policies.BASE_POLICY_NAME)
entity = body["createBackup"]
image_name = common.normalize_name(entity["name"])
backup_type = entity["backup_type"]
rotation = int(entity["rotation"])
props = {}
metadata = entity.get('metadata', {})
# Starting from microversion 2.39 we don't check quotas on createBackup
if api_version_request.is_supported(
req, max_version=
api_version_request.MAX_IMAGE_META_PROXY_API_VERSION):
common.check_img_metadata_properties_quota(context, metadata)
props.update(metadata)
instance = common.get_instance(self.compute_api, context, id)
try:
image = self.compute_api.backup(context, instance, image_name,
backup_type, rotation, extra_properties=props)
except exception.InstanceUnknownCell as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
except exception.InstanceInvalidState as state_error:
common.raise_http_conflict_for_instance_invalid_state(state_error,
'createBackup', id)
except exception.InvalidRequest as e:
raise webob.exc.HTTPBadRequest(explanation=e.format_message())
# Starting with microversion 2.45 we return a response body containing
# the snapshot image id without the Location header.
if api_version_request.is_supported(req, '2.45'):
return {'image_id': image['id']}
resp = webob.Response(status_int=202)
# build location of newly-created image entity if rotation is not zero
if rotation > 0:
image_id = str(image['id'])
image_ref = common.url_join(req.application_url, 'images',
image_id)
resp.headers['Location'] = image_ref
return resp
示例7: _create
def _create(self, req, body):
context = req.environ['nova.context']
# TODO(rb560u): remove this check in future release
using_old_action = \
policy.verify_deprecated_policy(fm_policies.BASE_POLICY_NAME,
fm_policies.POLICY_ROOT % 'create',
base.RULE_ADMIN_API,
context)
if not using_old_action:
context.can(fm_policies.POLICY_ROOT % 'create')
vals = body['flavor']
name = vals['name']
flavorid = vals.get('id')
memory = vals['ram']
vcpus = vals['vcpus']
root_gb = vals['disk']
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)
# The user can specify a description starting with microversion 2.55.
include_description = api_version_request.is_supported(
req, flavors_view.FLAVOR_DESCRIPTION_MICROVERSION)
description = vals.get('description') if include_description else None
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,
description=description)
# NOTE(gmann): For backward compatibility, non public flavor
# access is not being added for created tenant. Ref -bug/1209101
req.cache_db_flavor(flavor)
except (exception.FlavorExists,
exception.FlavorIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
include_extra_specs = False
if api_version_request.is_supported(
req, flavors_view.FLAVOR_EXTRA_SPECS_MICROVERSION):
include_extra_specs = context.can(
fes_policies.POLICY_ROOT % 'index', fatal=False)
# NOTE(yikun): This empty extra_spec only for keeping consistent
# with other related flavor api.
flavor.extra_specs = {}
return self._view_builder.show(req, flavor, include_description,
include_extra_specs=include_extra_specs)
示例8: show
def show(self, req, server_id, id):
"""Return data about the given instance action."""
context = req.environ['nova.context']
instance = self._get_instance(req, context, server_id)
context.can(ia_policies.BASE_POLICY_NAME, instance)
action = self.action_api.action_get_by_request_id(context, instance,
id)
if action is None:
msg = _("Action %s not found") % id
raise exc.HTTPNotFound(explanation=msg)
action_id = action['id']
if api_version_request.is_supported(req, min_version="2.58"):
action = self._format_action(action, ACTION_KEYS_V258)
else:
action = self._format_action(action, ACTION_KEYS)
# Prior to microversion 2.51, events would only be returned in the
# response for admins by default policy rules. Starting in
# microversion 2.51, events are returned for admin_or_owner (of the
# instance) but the "traceback" field is only shown for admin users
# by default.
show_events = False
show_traceback = False
show_host = False
if context.can(ia_policies.POLICY_ROOT % 'events', fatal=False):
# For all microversions, the user can see all event details
# including the traceback.
show_events = show_traceback = True
show_host = api_version_request.is_supported(req, '2.62')
elif api_version_request.is_supported(req, '2.51'):
# The user is not able to see all event details, but they can at
# least see the non-traceback event details.
show_events = True
# An obfuscated hashed host id is returned since microversion 2.62
# for all users.
show_hostid = api_version_request.is_supported(req, '2.62')
if show_events:
events_raw = self.action_api.action_events_get(context, instance,
action_id)
# NOTE(takashin): The project IDs of instance action events
# become null (None) when instance action events are created
# by periodic tasks. If the project ID is null (None),
# it causes an error when 'hostId' is generated.
# If the project ID is null (None), pass the project ID of
# the server instead of that of instance action events.
action['events'] = [self._format_event(
evt, action['project_id'] or instance.project_id,
show_traceback=show_traceback,
show_host=show_host, show_hostid=show_hostid
) for evt in events_raw]
return {'instanceAction': action}
示例9: _migrate_live
def _migrate_live(self, req, id, body):
"""Permit admins to (live) migrate a server to a new host."""
context = req.environ["nova.context"]
authorize(context, action='migrate_live')
host = body["os-migrateLive"]["host"]
block_migration = body["os-migrateLive"]["block_migration"]
force = None
if api_version_request.is_supported(req, min_version='2.30'):
force = body["os-migrateLive"].get("force", False)
force = strutils.bool_from_string(force, strict=True)
if force is True and not host:
message = _("Can't force to a non-provided destination")
raise exc.HTTPBadRequest(explanation=message)
if api_version_request.is_supported(req, min_version='2.25'):
if block_migration == 'auto':
block_migration = None
else:
block_migration = strutils.bool_from_string(block_migration,
strict=True)
disk_over_commit = None
else:
disk_over_commit = body["os-migrateLive"]["disk_over_commit"]
block_migration = strutils.bool_from_string(block_migration,
strict=True)
disk_over_commit = strutils.bool_from_string(disk_over_commit,
strict=True)
try:
instance = common.get_instance(self.compute_api, context, id)
self.compute_api.live_migrate(context, instance, block_migration,
disk_over_commit, host, force)
except exception.InstanceUnknownCell as e:
raise exc.HTTPNotFound(explanation=e.format_message())
except (exception.NoValidHost,
exception.ComputeServiceUnavailable,
exception.InvalidHypervisorType,
exception.InvalidCPUInfo,
exception.UnableToMigrateToSelf,
exception.DestinationHypervisorTooOld,
exception.InvalidLocalStorage,
exception.InvalidSharedStorage,
exception.HypervisorUnavailable,
exception.MigrationPreCheckError,
exception.LiveMigrationWithOldNovaNotSupported) as ex:
raise exc.HTTPBadRequest(explanation=ex.format_message())
except exception.InstanceIsLocked as e:
raise exc.HTTPConflict(explanation=e.format_message())
except exception.InstanceInvalidState as state_error:
common.raise_http_conflict_for_instance_invalid_state(state_error,
'os-migrateLive', id)
示例10: show
def show(self, request, instance, extend_address=True):
"""Detailed view of a single instance."""
ip_v4 = instance.get('access_ip_v4')
ip_v6 = instance.get('access_ip_v6')
server = {
"server": {
"id": instance["uuid"],
"name": instance["display_name"],
"status": self._get_vm_status(instance),
"tenant_id": instance.get("project_id") or "",
"user_id": instance.get("user_id") or "",
"metadata": self._get_metadata(instance),
"hostId": self._get_host_id(instance) or "",
"image": self._get_image(request, instance),
"flavor": self._get_flavor(request, instance),
"created": utils.isotime(instance["created_at"]),
"updated": utils.isotime(instance["updated_at"]),
"addresses": self._get_addresses(request, instance,
extend_address),
"accessIPv4": str(ip_v4) if ip_v4 is not None else '',
"accessIPv6": str(ip_v6) if ip_v6 is not None else '',
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
# NOTE(sdague): historically this was the
# os-disk-config extension, but now that extensions
# are gone, we merge these attributes here.
"OS-DCF:diskConfig": (
'AUTO' if instance.get('auto_disk_config') else 'MANUAL'),
},
}
if server["server"]["status"] in self._fault_statuses:
_inst_fault = self._get_fault(request, instance)
if _inst_fault:
server['server']['fault'] = _inst_fault
if server["server"]["status"] in self._progress_statuses:
server["server"]["progress"] = instance.get("progress", 0)
if api_version_request.is_supported(request, min_version="2.9"):
server["server"]["locked"] = (True if instance["locked_by"]
else False)
if api_version_request.is_supported(request, min_version="2.19"):
server["server"]["description"] = instance.get(
"display_description")
if api_version_request.is_supported(request, min_version="2.26"):
server["server"]["tags"] = [t.tag for t in instance.tags]
return server
示例11: _extend_server
def _extend_server(self, context, server, instance, req):
key = "OS-EXT-SRV-ATTR:hypervisor_hostname"
server[key] = instance.node
properties = ["host", "name"]
if api_version_request.is_supported(req, min_version="2.3"):
# NOTE(mriedem): These will use the OS-EXT-SRV-ATTR prefix below
# and that's OK for microversion 2.3 which is being compatible
# with v2.0 for the ec2 API split out from Nova. After this,
# however, new microversoins should not be using the
# OS-EXT-SRV-ATTR prefix.
properties += [
"reservation_id",
"launch_index",
"hostname",
"kernel_id",
"ramdisk_id",
"root_device_name",
"user_data",
]
for attr in properties:
if attr == "name":
key = "OS-EXT-SRV-ATTR:instance_%s" % attr
else:
# NOTE(mriedem): Nothing after microversion 2.3 should use the
# OS-EXT-SRV-ATTR prefix for the attribute key name.
key = "OS-EXT-SRV-ATTR:%s" % attr
server[key] = instance[attr]
示例12: _get_services
def _get_services(self, req):
# The API services are filtered out since they are not RPC services
# and therefore their state is not reported through the service group
# API, so they would always be reported as 'down' (see bug 1543625).
api_services = ('nova-osapi_compute', 'nova-metadata')
context = req.environ['nova.context']
context.can(services_policies.BASE_POLICY_NAME)
cell_down_support = api_version_request.is_supported(
req, min_version=PARTIAL_CONSTRUCT_FOR_CELL_DOWN_MIN_VERSION)
_services = [
s
for s in self.host_api.service_get_all(context, set_zones=True,
all_cells=True, cell_down_support=cell_down_support)
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
示例13: show
def show(self, req, server_id, id):
"""Return data about the given instance action."""
context = req.environ['nova.context']
instance = self._get_instance(req, context, server_id)
context.can(ia_policies.BASE_POLICY_NAME, instance)
action = self.action_api.action_get_by_request_id(context, instance,
id)
if action is None:
msg = _("Action %s not found") % id
raise exc.HTTPNotFound(explanation=msg)
action_id = action['id']
action = self._format_action(action)
# Prior to microversion 2.51, events would only be returned in the
# response for admins by default policy rules. Starting in
# microversion 2.51, events are returned for admin_or_owner (of the
# instance) but the "traceback" field is only shown for admin users
# by default.
show_events = False
show_traceback = False
if context.can(ia_policies.POLICY_ROOT % 'events', fatal=False):
# For all microversions, the user can see all event details
# including the traceback.
show_events = show_traceback = True
elif api_version_request.is_supported(req, '2.51'):
# The user is not able to see all event details, but they can at
# least see the non-traceback event details.
show_events = True
if show_events:
events_raw = self.action_api.action_events_get(context, instance,
action_id)
action['events'] = [self._format_event(evt, show_traceback)
for evt in events_raw]
return {'instanceAction': action}
示例14: index
def index(self, request, flavors):
"""Return the 'index' view of flavors."""
coll_name = self._collection_name
include_description = api_version_request.is_supported(
request, FLAVOR_DESCRIPTION_MICROVERSION)
return self._list_view(self.basic, request, flavors, coll_name,
include_description=include_description)
示例15: _validate_id
def _validate_id(req, hypervisor_id):
"""Validates that the id is a uuid for microversions that require it.
:param req: The HTTP request object which contains the requested
microversion information.
:param hypervisor_id: The provided hypervisor id.
:raises: webob.exc.HTTPBadRequest if the requested microversion is
greater than or equal to 2.53 and the id is not a uuid.
:raises: webob.exc.HTTPNotFound if the requested microversion is
less than 2.53 and the id is not an integer.
"""
expect_uuid = api_version_request.is_supported(
req, min_version=UUID_FOR_ID_MIN_VERSION)
if expect_uuid:
if not uuidutils.is_uuid_like(hypervisor_id):
msg = _('Invalid uuid %s') % hypervisor_id
raise webob.exc.HTTPBadRequest(explanation=msg)
else:
# This API is supported for cells v1 and as such the id can be
# a cell v1 delimited string, so we have to parse it first.
if cells_utils.CELL_ITEM_SEP in str(hypervisor_id):
hypervisor_id = cells_utils.split_cell_and_item(
hypervisor_id)[1]
try:
utils.validate_integer(hypervisor_id, 'id')
except exception.InvalidInput:
msg = (_("Hypervisor with ID '%s' could not be found.") %
hypervisor_id)
raise webob.exc.HTTPNotFound(explanation=msg)