def change_password(self, req, id, body): context = req.environ['nova.context'] instance = common.get_instance(self.compute_api, context, id) context.can(ap_policies.BASE_POLICY_NAME, target={ 'user_id': instance.user_id, 'project_id': instance.project_id }) password = body['changePassword']['adminPass'] try: self.compute_api.set_admin_password(context, instance, password) except (exception.InstancePasswordSetFailed, exception.SetAdminPasswdNotSupported, exception.InstanceAgentNotEnabled) as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as e: raise common.raise_http_conflict_for_instance_invalid_state( e, 'changePassword', id) except NotImplementedError: msg = _("Unable to set password on instance") common.raise_feature_not_supported(msg=msg)
def _image_uuid_from_ref(self, image_ref, context): # If the image ref was generated by nova api, strip image_ref # down to an id. image_uuid = None try: image_uuid = image_ref.split('/').pop() except AttributeError: msg = _("Invalid imageRef provided.") raise exc.HTTPBadRequest(explanation=msg) image_service = glance.get_default_image_service() # First see if this is an actual image ID if uuidutils.is_uuid_like(image_uuid): try: image = image_service.show(context, image_uuid) if 'id' in image: return image['id'] except Exception: # Pass and see if there is a matching image name pass # Could not find by ID, check if it is an image name try: params = {'filters': {'name': image_ref}} images = list(image_service.detail(context, **params)) if len(images) > 1: msg = _("Multiple matches found for '%s', use an ID to be more" " specific.") % image_ref raise exc.HTTPConflict(msg) for img in images: return img['id'] except Exception: # Pass and let default not found error handling take care of it pass msg = _("Invalid image identifier or unable to " "access requested image.") raise exc.HTTPBadRequest(explanation=msg)
def _remove_host(self, req, id, body): """Removes a host from the specified aggregate.""" host = body['remove_host']['host'] context = _get_context(req) authorize(context, action='remove_host') try: aggregate = self.api.remove_host_from_aggregate(context, id, host) except (exception.AggregateNotFound, exception.AggregateHostNotFound, exception.ComputeHostNotFound): msg = _('Cannot remove host %(host)s in aggregate %(id)s') % { 'host': host, 'id': id } raise exc.HTTPNotFound(explanation=msg) except exception.InvalidAggregateAction: msg = _('Cannot remove host %(host)s in aggregate %(id)s') % { 'host': host, 'id': id } raise exc.HTTPConflict(explanation=msg) return self._marshall_aggregate(aggregate)
def _resize(self, req, instance_id, flavor_id, **kwargs): """Begin the resize process with given instance/flavor.""" context = req.environ["nova.context"] authorize(context, action='resize') instance = self._get_server(context, req, instance_id) try: self.compute_api.resize(context, instance, flavor_id, **kwargs) except exception.QuotaError as error: raise exc.HTTPForbidden(explanation=error.format_message(), headers={'Retry-After': 0}) except exception.FlavorNotFound: msg = _("Unable to locate requested flavor.") raise exc.HTTPBadRequest(explanation=msg) except exception.CannotResizeToSameFlavor: msg = _("Resize requires a flavor change.") raise exc.HTTPBadRequest(explanation=msg) except (exception.CannotResizeDisk, exception.AutoDiskConfigDisabledByImage) as e: raise exc.HTTPBadRequest(explanation=e.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, 'resize', instance_id) except exception.ImageNotAuthorized: msg = _("You are not authorized to access the image " "the instance was started with.") raise exc.HTTPUnauthorized(explanation=msg) except exception.ImageNotFound: msg = _("Image that the instance was started " "with could not be found.") raise exc.HTTPBadRequest(explanation=msg) except (exception.NoValidHost, exception.AutoDiskConfigDisabledByImage) as e: raise exc.HTTPBadRequest(explanation=e.format_message()) except exception.Invalid: msg = _("Invalid instance image.") raise exc.HTTPBadRequest(explanation=msg)
def _migrate(self, req, id, body): """Permit admins to migrate a server to a new host.""" context = req.environ['nova.context'] authorize(context, 'migrate') instance = common.get_instance(self.compute_api, context, id, want_objects=True) try: self.compute_api.resize(req.environ['nova.context'], instance) except (exception.TooManyInstances, exception.QuotaError) as e: raise exc.HTTPForbidden(explanation=e.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, 'migrate', id) except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.NoValidHost as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return webob.Response(status_int=202)
def delete(self, req, id): """Delete specified share server.""" context = req.environ['manila.context'] try: share_server = db_api.share_server_get(context, id) except exception.ShareServerNotFound as e: raise exc.HTTPNotFound(explanation=e) allowed_statuses = [constants.STATUS_ERROR, constants.STATUS_ACTIVE] if share_server['status'] not in allowed_statuses: data = { 'status': share_server['status'], 'allowed_statuses': allowed_statuses, } msg = _("Share server's actual status is %(status)s, allowed " "statuses for deletion are %(allowed_statuses)s.") % (data) raise exc.HTTPForbidden(explanation=msg) LOG.debug("Deleting share server with id: %s.", id) try: self.share_api.delete_share_server(context, share_server) except exception.ShareServerInUse as e: raise exc.HTTPConflict(explanation=e) return webob.Response(status_int=http_client.ACCEPTED)
def _update_instance_metadata(self, context, server_id, metadata, delete=False): try: server = common.get_instance(self.compute_api, context, server_id, want_objects=True) return self.compute_api.update_instance_metadata( context, server, metadata, delete) except exception.QuotaError as error: raise exc.HTTPForbidden(explanation=error.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, 'update metadata')
def update(self, req, id, body): """Updates the name and/or availability_zone of given aggregate.""" context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: updates = body["aggregate"] except KeyError: raise exc.HTTPBadRequest() if len(updates) < 1: raise exc.HTTPBadRequest() for key in updates.keys(): if key not in ["name", "availability_zone"]: raise exc.HTTPBadRequest() try: if 'name' in updates: utils.check_string_length(updates['name'], "Aggregate name", 1, 255) if updates.get("availability_zone") is not None: utils.check_string_length(updates['availability_zone'], "Availability_zone", 1, 255) except exception.InvalidInput as e: raise exc.HTTPBadRequest(explanation=e.format_message()) try: aggregate = self.api.update_aggregate(context, id, updates) except exception.AggregateNameExists as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.AggregateNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InvalidAggregateAction as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return self._marshall_aggregate(aggregate)
def _shelve(self, req, id, body): """Move an instance into shelved mode.""" context = req.environ["nova.context"] instance = common.get_instance(self.compute_api, context, id) context.can(shelve_policies.POLICY_ROOT % 'shelve', target={ 'user_id': instance.user_id, 'project_id': instance.project_id }) try: self.compute_api.shelve(context, instance) except ( exception.InstanceIsLocked, exception.UnexpectedTaskStateError, ) 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, 'shelve', id) except exception.ForbiddenPortsWithAccelerator as e: raise exc.HTTPBadRequest(explanation=e.format_message())
def _unmanage(self, req, id, body=None, allow_dhss_true=False): """Unmanage a share.""" context = req.environ['manila.context'] LOG.info("Unmanage share with id: %s", id, context=context) try: share = self.share_api.get(context, id) if share.get('has_replicas'): msg = _("Share %s has replicas. It cannot be unmanaged " "until all replicas are removed.") % share['id'] raise exc.HTTPConflict(explanation=msg) if (not allow_dhss_true and share['instance'].get('share_server_id')): msg = _("Operation 'unmanage' is not supported for shares " "that are created on top of share servers " "(created with share-networks).") raise exc.HTTPForbidden(explanation=msg) elif share['status'] in constants.TRANSITIONAL_STATUSES: msg = _("Share with transitional state can not be unmanaged. " "Share '%(s_id)s' is in '%(state)s' state.") % dict( state=share['status'], s_id=share['id']) raise exc.HTTPForbidden(explanation=msg) snapshots = self.share_api.db.share_snapshot_get_all_for_share( context, id) if snapshots: msg = _("Share '%(s_id)s' can not be unmanaged because it has " "'%(amount)s' dependent snapshot(s).") % { 's_id': id, 'amount': len(snapshots) } raise exc.HTTPForbidden(explanation=msg) self.share_api.unmanage(context, share) except exception.NotFound as e: raise exc.HTTPNotFound(explanation=e.msg) except (exception.InvalidShare, exception.PolicyNotAuthorized) as e: raise exc.HTTPForbidden(explanation=e.msg) return webob.Response(status_int=http_client.ACCEPTED)
def update(self, req, server_id, id, body): context = req.environ['nova.context'] context.can(va_policies.POLICY_ROOT % 'update') old_volume_id = id try: old_volume = self.volume_api.get(context, old_volume_id) except exception.VolumeNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) new_volume_id = body['volumeAttachment']['volumeId'] try: new_volume = self.volume_api.get(context, new_volume_id) except exception.VolumeNotFound as e: # NOTE: This BadRequest is different from the above NotFound even # though the same VolumeNotFound exception. This is intentional # because new_volume_id is specified in a request body and if a # nonexistent resource in the body (not URI) the code should be # 400 Bad Request as API-WG guideline. On the other hand, # old_volume_id is specified with URI. So it is valid to return # NotFound response if that is not existent. raise exc.HTTPBadRequest(explanation=e.format_message()) instance = common.get_instance(self.compute_api, context, server_id) try: self.compute_api.swap_volume(context, instance, old_volume, new_volume) except exception.VolumeBDMNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except (exception.InvalidVolume, exception.MultiattachSwapVolumeNotSupported) as e: raise exc.HTTPBadRequest(explanation=e.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, 'swap_volume', server_id)
def _unshelve(self, req, id, body): """Restore an instance from shelved mode.""" context = req.environ["nova.context"] context.can(shelve_policies.POLICY_ROOT % 'unshelve') instance = common.get_instance(self.compute_api, context, id) new_az = None unshelve_dict = body['unshelve'] support_az = api_version_request.is_supported(req, '2.77') if support_az and unshelve_dict: new_az = unshelve_dict['availability_zone'] # We could potentially move this check to conductor and avoid the # extra API call to neutron when we support move operations with ports # having resource requests. if (instance.vm_state == vm_states.SHELVED_OFFLOADED and common.instance_has_port_with_resource_request( instance.uuid, self.network_api) and not common.supports_port_resource_request_during_move( req)): msg = _("The unshelve action on a server with ports having " "resource requests, like a port with a QoS minimum " "bandwidth policy, is not supported with this " "microversion") raise exc.HTTPBadRequest(explanation=msg) try: self.compute_api.unshelve(context, instance, new_az=new_az) except (exception.InstanceIsLocked, exception.UnshelveInstanceInvalidState, exception.MismatchVolumeAZException) 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, 'unshelve', id) except exception.InvalidRequest as e: raise exc.HTTPBadRequest(explanation=e.format_message())
def _migrate(self, req, id, body): """Permit admins to migrate a server to a new host.""" context = req.environ['nova.context'] instance = common.get_instance(self.compute_api, context, id, expected_attrs=['flavor', 'services']) context.can(ms_policies.POLICY_ROOT % 'migrate', target={'project_id': instance.project_id}) host_name = None if (api_version_request.is_supported(req, min_version='2.56') and body['migrate'] is not None): host_name = body['migrate'].get('host') try: self.compute_api.resize(req.environ['nova.context'], instance, host_name=host_name) except (exception.TooManyInstances, exception.QuotaError, exception.ForbiddenWithAccelerators) as e: raise exc.HTTPForbidden(explanation=e.format_message()) except ( exception.InstanceIsLocked, exception.InstanceNotReady, exception.ServiceUnavailable, exception.OperationNotSupportedForVDPAInterface, ) 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, 'migrate', id) except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except (exception.ComputeHostNotFound, exception.CannotMigrateToSameHost) as e: raise exc.HTTPBadRequest(explanation=e.format_message())
def _migrate_extend(self, req, id, body): """Permit admin to migrate a server to a new host lively.""" if not self._get_ics_session(): return dict(vms=[], error='CANNOT_CONNECT_ICS') if not id: return dict(vms=[], error='VM_ID_NULL') context = req.environ['nova.context'] nodeTarget = body["migrateExtend"]["nodeTarget"] # if not hostInfo or hostInfo['id']: # return {'success': False, "vmId": id, "hostId": nodeTarget, "result": "HOST IS NULL"} # instance = common.get_instance(self.compute_api, context, id) hostInfo = None try: # make sure the target host is exist or not hostInfo = self.ics_manager.host.get_host(nodeTarget) if hostInfo.get('code'): return {'success': False, "vmId": id, "hostId": nodeTarget, "result": hostInfo['message']} # do the migration result = self.ics_manager.vm.live_migrate(id, nodeTarget) res = {'success': True, "vmId": id, "hostId": nodeTarget, "result": result} return dict(migrateExtend = res) # body = self.ics_manager.vm.get_info(self, '0557ec0b_4e52_4228_a067_e6a7699ebe97') # result = self.ics_manager.host.get_host('5d85f39c-ef38-4bc3-991a-6f250b32221f') # print json.dumps(result) + "\n\n" except (exception.TooManyInstances, exception.QuotaError) as e: raise exc.HTTPForbidden(explanation=e.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, 'migrateExtend', id) except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.NoValidHost as e: raise exc.HTTPBadRequest(explanation=e.format_message())
def create(self, req, body): context = req.environ['nova.context'] authorize(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) 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)}
def update(self, req, server_id, id, body): """Update address of virtual interfaces.""" context = req.environ['nova.context'] authorize(context) fixed_ip = body['fixed_ips'][0] network_uuid = fixed_ip['net_id'] ip_address = fixed_ip['ip_address'] if not network_uuid or not ip_address: raise exc.HTTPBadRequest() try: instance = self.compute_api.get(context, server_id, want_objects=True) self.network_api.update_interface_address(context, server_id, id, network_uuid, ip_address) self.network_api.update_vif_pg_info(context, instance) except exception.InstanceNotFound: raise exc.HTTPNotFound(_("Server not found")) except exception.NotFound as e: raise exc.HTTPNotFound() except exception.FixedIpAlreadyInUse as e: LOG.exception(e) msg = _("Fixed Ip already in use") raise exc.HTTPConflict(explanation=msg) except NotImplementedError: msg = _("Network driver does not support this function.") raise exc.HTTPNotImplemented(explanation=msg) except exception.InterfaceAttachFailed as e: msg = _("Failed to attach interface") raise exc.HTTPInternalServerError(explanation=msg) except Exception as e: LOG.exception(e) msg = _("Failed to attach interface") raise exc.HTTPInternalServerError(explanation=msg) return webob.Response(status_int=202)
def create(self, req, body): """Creates an aggregate, given its name and optional availability zone. """ context = _get_context(req) authorize(context) if len(body) != 1: raise exc.HTTPBadRequest() try: host_aggregate = body["aggregate"] name = host_aggregate["name"] except KeyError: raise exc.HTTPBadRequest() avail_zone = host_aggregate.get("availability_zone") try: utils.check_string_length(name, "Aggregate name", 1, 255) if avail_zone is not None: utils.check_string_length(avail_zone, "Availability_zone", 1, 255) except exception.InvalidInput as e: raise exc.HTTPBadRequest(explanation=e.format_message()) try: aggregate = self.api.create_aggregate(context, name, avail_zone) except exception.AggregateNameExists as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InvalidAggregateAction as e: raise exc.HTTPBadRequest(explanation=e.format_message()) agg = self._marshall_aggregate(aggregate) # To maintain the same API result as before the changes for returning # nova objects were made. del agg['aggregate']['hosts'] del agg['aggregate']['metadata'] return agg
def update_hwm(self, req, id, body): """Registers a new hwm with the registry. :param req: wsgi Request object :param body: Dictionary of information about the template :retval Returns the newly-created template information as a mapping, which will include the newly-created template's internal id in the 'id' field """ hwm_data = body["hwm"] if id and not utils.is_uuid_like(id): msg = _LI("Rejecting cluster hwm creation request for invalid " "hwm id '%(bad_id)s'") % {'bad_id': id} LOG.info(msg) msg = _("Invalid hwm id format") return exc.HTTPBadRequest(explanation=msg) try: hwm_data = self.db_api.hwm_update(req.context, id, hwm_data) msg = (_LI("Successfully updated hwm %s") % hwm_data["id"]) LOG.info(msg) if 'hwm' not in hwm_data: hwm_data = dict(hwm=hwm_data) return hwm_data except exception.Duplicate: msg = _("hwm with identifier %s already exists!") % id LOG.warning(msg) return exc.HTTPConflict(msg) except exception.Invalid as e: msg = (_("Failed to update hwm metadata.Got error: %s") % utils.exception_to_str(e)) LOG.error(msg) return exc.HTTPBadRequest(msg) except Exception: LOG.exception(_LE("Unable to update hwm %s"), id) raise
def delete(self, req, server_id, id): """Abort an in progress migration of an instance.""" context = req.environ['nova.context'] context.can(sm_policies.POLICY_ROOT % 'delete') support_abort_in_queue = api_version_request.is_supported(req, '2.65') instance = common.get_instance(self.compute_api, context, server_id) try: self.compute_api.live_migrate_abort( context, instance, id, support_abort_in_queue=support_abort_in_queue) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, "abort live migration", server_id) except exception.MigrationNotFoundForInstance as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InvalidMigrationState as e: raise exc.HTTPBadRequest(explanation=e.format_message()) except exception.AbortQueuedLiveMigrationNotYetSupported as e: raise exc.HTTPConflict(explanation=e.format_message())
def delete(self, req, server_id, id): """Deletes an existing metadata.""" context = req.environ['nova.context'] metadata = self._get_metadata(context, server_id) if id not in metadata: msg = _("Metadata item was not found") raise exc.HTTPNotFound(explanation=msg) server = common.get_instance(self.compute_api, context, server_id, want_objects=True) try: self.compute_api.delete_instance_metadata(context, server, id) 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, 'delete metadata', server_id)
def _unpause(self, req, id, body): """Permit Admins to unpause the server.""" ctxt = req.environ['nova.context'] authorize(ctxt, 'unpause') try: server = self.compute_api.get(ctxt, id, want_objects=True) self.compute_api.unpause(ctxt, server) 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, 'unpause') except exception.InstanceNotFound: msg = _("Server not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _("Virt driver does not implement unpause function.") raise exc.HTTPNotImplemented(explanation=msg) except Exception: readable = traceback.format_exc() LOG.exception(_("Compute.api::unpause %s"), readable) raise exc.HTTPUnprocessableEntity() return webob.Response(status_int=202)
def create(self, request, body): LOG.debug('Environments:Create <Body {body}>'.format(body=body)) policy.check('create_environment', request.context) if not ('name' in body and body['name'].strip()): msg = _('Please, specify a name of the environment to create') LOG.error(msg) raise exc.HTTPBadRequest(explanation=msg) name = six.text_type(body['name']) if len(name) > 255: msg = _('Environment name should be 255 characters maximum') LOG.error(msg) raise exc.HTTPBadRequest(explanation=msg) try: environment = envs.EnvironmentServices.create( body.copy(), request.context) except db_exc.DBDuplicateEntry: msg = _('Environment with specified name already exists') LOG.error(msg) raise exc.HTTPConflict(explanation=msg) return environment.to_dict()
def delete(self, req, server_id, id): """Detach an interface from an instance.""" context = req.environ['nova.context'] instance = common.get_instance(self.compute_api, context, server_id, expected_attrs=['device_metadata']) context.can(ai_policies.POLICY_ROOT % 'delete', target={'project_id': instance.project_id}) port_id = id try: self.compute_api.detach_interface(context, instance, port_id=port_id) except exception.PortNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except NotImplementedError: common.raise_feature_not_supported() except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'detach_interface', server_id)
def update(self, req, id, body): """Updates the name and/or availability_zone of given aggregate.""" context = _get_context(req) context.can(aggr_policies.POLICY_ROOT % 'update', target={}) updates = body["aggregate"] if 'name' in updates: updates['name'] = common.normalize_name(updates['name']) try: utils.validate_integer(id, 'id') except exception.InvalidInput as e: raise exc.HTTPBadRequest(explanation=e.format_message()) try: aggregate = self.api.update_aggregate(context, id, updates) except exception.AggregateNameExists as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.AggregateNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InvalidAggregateAction as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return self._marshall_aggregate(req, aggregate)
def _remove_host(self, req, id, host): """Removes a host from the specified aggregate.""" context = _get_context(req) 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) try: aggregate = self.api.remove_host_from_aggregate(context, id, host) except (exception.AggregateNotFound, exception.AggregateHostNotFound, exception.ComputeHostNotFound): msg = _('Cannot remove host %(host)s in aggregate' ' %(id)s: not found') % {'host': host, 'id': id} raise exc.HTTPNotFound(explanation=msg) except exception.InvalidAggregateAction: msg = _('Cannot remove host %(host)s in aggregate' ' %(id)s: invalid') % {'host': host, 'id': id} raise exc.HTTPConflict(explanation=msg) return self._marshall_aggregate(aggregate)
def delete(self, req, server_id, id): """Detach an interface from an instance.""" context = req.environ['nova.context'] authorize(context) port_id = id instance = common.get_instance(self.compute_api, context, server_id) LOG.info(_LI("Detach interface %s"), port_id, instance=instance) try: self.compute_api.detach_interface(context, instance, port_id=port_id) except exception.PortNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except NotImplementedError: msg = _("Network driver does not support this function.") raise webob.exc.HTTPNotImplemented(explanation=msg) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'detach_interface', server_id) return webob.Response(status_int=202)
def delete(self, req, server_id, id): """Detach an interface from an instance.""" context = req.environ['nova.context'] authorize(context) port_id = id instance = common.get_instance(self.compute_api, context, server_id, want_objects=True) LOG.audit(_("Detach interface %s"), port_id, instance=instance) try: self.compute_api.detach_interface(context, instance, port_id=port_id) except exception.PortNotFound: raise exc.HTTPNotFound() except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except NotImplementedError as e: raise webob.exc.HTTPNotImplemented(explanation=e.format_message()) return webob.Response(status_int=202)
def delete(self, req, server_id, id): """Detach an interface from an instance.""" context = req.environ['nova.context'] authorize(context) port_id = id instance = common.get_instance(self.compute_api, context, server_id, want_objects=True) try: self.compute_api.detach_interface(context, instance, port_id=port_id) except exception.PortNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except NotImplementedError as e: raise webob.exc.HTTPNotImplemented(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'detach_interface', server_id)
def create(self, request, body): """Creates the env template from the payload This payload can contain just the template name, or include also service information. :param request: the operation request. :param body: the env template description :return: the description of the created template. """ LOG.debug('EnvTemplates:Create <Body {body}>'.format(body=body)) policy.check('create_env_template', request.context) self._validate_body_name(body) try: LOG.debug( 'ENV TEMP NAME: {templ_name}>'.format(templ_name=body['name'])) template = env_temps.EnvTemplateServices.create( body.copy(), request.context.tenant) return template.to_dict() except db_exc.DBDuplicateEntry: msg = _('Env Template with specified name already exists') LOG.exception(msg) raise exc.HTTPConflict(msg)
def create(self, request, body): LOG.debug(u'Environments:Create <Body {0}>'.format(body)) policy.check('create_environment', request.context) name = unicode(body['name']) if len(name) > 255: msg = _('Environment name should be 255 characters maximum') LOG.exception(msg) raise exc.HTTPBadRequest(explanation=msg) if VALID_NAME_REGEX.match(name): try: environment = envs.EnvironmentServices.create( body.copy(), request.context) except db_exc.DBDuplicateEntry: msg = _('Environment with specified name already exists') LOG.exception(msg) raise exc.HTTPConflict(explanation=msg) else: msg = _('Environment name must contain only alphanumeric ' 'or "_-." characters, must start with alpha') LOG.exception(msg) raise exc.HTTPClientError(explanation=msg) return environment.to_dict()