def create(self, req, body): """Bulk create floating IPs.""" context = req.environ['nova.context'] authorize(context) if 'floating_ips_bulk_create' not in body: raise webob.exc.HTTPUnprocessableEntity() params = body['floating_ips_bulk_create'] if 'ip_range' not in params: raise webob.exc.HTTPUnprocessableEntity() ip_range = params['ip_range'] pool = params.get('pool', CONF.default_floating_pool) interface = params.get('interface', CONF.public_interface) try: ips = [objects.FloatingIPList.make_ip_info(addr, pool, interface) for addr in self._address_to_hosts(ip_range)] except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: objects.FloatingIPList.create(context, ips) except exception.FloatingIpExists as exc: raise webob.exc.HTTPConflict(explanation=exc.format_message()) return {"floating_ips_bulk_create": {"ip_range": ip_range, "pool": pool, "interface": interface}}
def _create(self, req, body, **keypair_filters): context = req.environ["patron.context"] authorize(context, action="create") params = body["keypair"] name = params["name"] key_type = params.get("type", keypair_obj.KEYPAIR_TYPE_SSH) try: if "public_key" in params: keypair = self.api.import_key_pair(context, context.user_id, name, params["public_key"], key_type) keypair = self._filter_keypair(keypair, user_id=True, **keypair_filters) else: keypair, private_key = self.api.create_key_pair(context, context.user_id, name, key_type) keypair = self._filter_keypair(keypair, user_id=True, **keypair_filters) keypair["private_key"] = private_key return {"keypair": keypair} except exception.KeypairLimitExceeded: msg = _("Quota exceeded, too many key pairs.") raise webob.exc.HTTPForbidden(explanation=msg) except exception.InvalidKeypair as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) except exception.KeyPairExists as exc: raise webob.exc.HTTPConflict(explanation=exc.format_message())
def _create(self, req, body, user_id=None, **keypair_filters): context = req.environ['nova.context'] params = body['keypair'] name = common.normalize_name(params['name']) key_type = params.get('type', keypair_obj.KEYPAIR_TYPE_SSH) user_id = user_id or context.user_id context.can(kp_policies.POLICY_ROOT % 'create', target={'user_id': user_id, 'project_id': context.project_id}) try: if 'public_key' in params: keypair = self.api.import_key_pair(context, user_id, name, params['public_key'], key_type) keypair = self._filter_keypair(keypair, user_id=True, **keypair_filters) else: keypair, private_key = self.api.create_key_pair( context, user_id, name, key_type) keypair = self._filter_keypair(keypair, user_id=True, **keypair_filters) keypair['private_key'] = private_key return {'keypair': keypair} except exception.KeypairLimitExceeded: msg = _("Quota exceeded, too many key pairs.") raise webob.exc.HTTPForbidden(explanation=msg) except exception.InvalidKeypair as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) except exception.KeyPairExists as exc: raise webob.exc.HTTPConflict(explanation=exc.format_message())
def create(self, req, body): """Bulk create floating ips.""" context = req.environ['nova.context'] authorize(context) if 'floating_ips_bulk_create' not in body: raise webob.exc.HTTPUnprocessableEntity() params = body['floating_ips_bulk_create'] LOG.debug(params) if 'ip_range' not in params: raise webob.exc.HTTPUnprocessableEntity() ip_range = params['ip_range'] pool = params.get('pool', CONF.default_floating_pool) interface = params.get('interface', CONF.public_interface) try: ips = ({'address': str(address), 'pool': pool, 'interface': interface} for address in self._address_to_hosts(ip_range)) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: db.floating_ip_bulk_create(context, ips) except exception.FloatingIpExists as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) return {"floating_ips_bulk_create": {"ip_range": ip_range, "pool": pool, "interface": interface}}
def _update(self, context, host, binary, payload): """Do the actual PUT/update""" try: self.host_api.service_update(context, host, binary, payload) except (exception.HostBinaryNotFound, exception.HostMappingNotFound) as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message())
def _show(self, req, id, **keypair_filters): """Return data for the given key name.""" context = req.environ["patron.context"] authorize(context, action="show") try: # The return object needs to be a dict in order to pop the 'type' # field, if the api_version < 2.2. keypair = self.api.get_key_pair(context, context.user_id, id) keypair = self._filter_keypair( keypair, created_at=True, deleted=True, deleted_at=True, id=True, user_id=True, updated_at=True, **keypair_filters ) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message()) # TODO(oomichi): It is necessary to filter a response of keypair with # _filter_keypair() when v2.1+microversions for implementing consistent # behaviors in this keypair resource. return {"keypair": keypair}
def index(self, req): """List of attributes for a user.""" context = req.environ['nova.context'] #authorize(context, action='create') ''' try: params = body['attribute'] name = params['name'] except KeyError: msg = _("Invalid request body") raise webob.exc.HTTPBadRequest(explanation=msg) ''' try: #print "IASDASDASDASDASDI am here" attlist=self.api.list(context) attribute = [] for att in attlist: attribute.append({'id': att.id, 'name': att.name}) print attribute return {'attribute': attribute} except exception.InvalidAttribute as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) '''
def create(self, req, body): """Create or import attribute. Sending name will generate a key and return private_key and fingerprint. You can send a public_key to add an existing ssh key params: attribute object with: name (required) - string public_key (optional) - string """ # traceback.print_stack() context = req.environ["nova.context"] authorize(context, action="create") try: params = body["attribute"] name = params["name"] except KeyError: msg = _("Invalid request body") raise webob.exc.HTTPBadRequest(explanation=msg) try: attribute = self.api.create_attribute(context, name) return {"attribute": attribute} except exception.InvalidAttribute as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
def update(self, req, id, body): """Update an existing agent build.""" context = req.environ['nova.context'] authorize(context) try: para = body['para'] url = para['url'] md5hash = para['md5hash'] version = para['version'] except (TypeError, KeyError): raise webob.exc.HTTPUnprocessableEntity() try: utils.check_string_length(url, 'url', max_length=255) utils.check_string_length(md5hash, 'md5hash', max_length=255) utils.check_string_length(version, 'version', max_length=255) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: db.agent_build_update(context, id, {'version': version, 'url': url, 'md5hash': md5hash}) except exception.AgentBuildNotFound as ex: raise webob.exc.HTTPNotFound(explanation=ex.format_message()) # NOTE(alex_xu): The agent_id should be integer that consistent with # create/index actions. But parameter 'id' is string type that parsed # from url. This is a bug, but because back-compatibility, it can't be # fixed for v2 API. This will be fixed after v3 API feature exposed by # micro-version in the future. lp bug #1333494 return {"agent": {'agent_id': id, 'version': version, 'url': url, 'md5hash': md5hash}}
def delete(self, req, id): """Deletes the specified service.""" context = req.environ['nova.context'] context.can(services_policies.BASE_POLICY_NAME) try: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: service = self.host_api.service_get_by_id(context, id) # remove the service from all the aggregates in which it's included if service.binary == 'nova-compute': aggrs = self.aggregate_api.get_aggregates_by_host(context, service.host) for ag in aggrs: self.aggregate_api.remove_host_from_aggregate(context, ag.id, service.host) self.host_api.service_delete(context, id) except exception.ServiceNotFound: explanation = _("Service %s not found.") % id raise webob.exc.HTTPNotFound(explanation=explanation)
def update(self, req, id, body): """Update an existing agent build.""" context = req.environ['nova.context'] authorize(context) try: para = body['agent'] url = para['url'] md5hash = para['md5hash'] version = para['version'] except TypeError as e: raise webob.exc.HTTPBadRequest() except KeyError as e: raise webob.exc.HTTPBadRequest(explanation=_( "Could not find %s parameter in the request") % e.args[0]) try: utils.check_string_length(url, 'url', max_length=255) utils.check_string_length(md5hash, 'md5hash', max_length=255) utils.check_string_length(version, 'version', max_length=255) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: db.agent_build_update(context, id, {'version': version, 'url': url, 'md5hash': md5hash}) except exception.AgentBuildNotFound as ex: raise webob.exc.HTTPNotFound(explanation=ex.format_message()) return {"agent": {'agent_id': id, 'version': version, 'url': url, 'md5hash': md5hash}}
def _common_policy_check(self, rules, rule_name, func, *arg, **kwarg): self.policy.set_rules(rules) exc = self.assertRaises( exception.PolicyNotAuthorized, func, *arg, **kwarg) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def test_remove_host_no_admin(self): exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller._remove_host, self.user_req, "1", body={"remove_host": {"host": "host1"}}) self.assertIn("compute_extension:v3:os-aggregates:remove_host", exc.format_message())
def test_delete_attach_interfaces_policy_failed(self): exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller.delete, self.req, fakes.FAKE_UUID, FAKE_PORT_ID1) self.assertEqual( "Policy doesn't allow %s to be performed." % self.rule_name, exc.format_message())
def list(self, req): """Create or import attribute. Sending name will generate a key and return private_key and fingerprint. You can send a public_key to add an existing ssh key params: attribute object with: name (required) - string public_key (optional) - string """ traceback.print_stack() context = req.environ["nova.context"] # authorize(context, action='create') """ try: params = body['attribute'] name = params['name'] except KeyError: msg = _("Invalid request body") raise webob.exc.HTTPBadRequest(explanation=msg) """ try: # for att in attribute: # print att.name attribute = self.api.attribute_list(context) except exception.InvalidAttribute as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message())
def test_create_attach_interfaces_policy_failed(self): exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller.create, self.req, fakes.FAKE_UUID, body={}) self.assertEqual( "Policy doesn't allow {0!s} to be performed.".format(self.rule_name), exc.format_message())
def create(self, req, body): """ Create or import keypair. Sending name will generate a key and return private_key and fingerprint. You can send a public_key to add an existing ssh key params: keypair object with: name (required) - string public_key (optional) - string """ context = req.environ['nova.context'] authorize(context, action='create') try: params = body['keypair'] name = params['name'] except KeyError: msg = _("Invalid request body") raise webob.exc.HTTPBadRequest(explanation=msg) try: if 'public_key' in params: keypair = self.api.import_key_pair(context, context.user_id, name, params['public_key']) keypair = self._filter_keypair(keypair, user_id=True) else: keypair, private_key = self.api.create_key_pair( context, context.user_id, name) keypair = self._filter_keypair(keypair, user_id=True) keypair['private_key'] = private_key return {'keypair': keypair} except exception.KeypairLimitExceeded: msg = _("Quota exceeded, too many key pairs.") raise webob.exc.HTTPRequestEntityTooLarge( explanation=msg, headers={'Retry-After': 0}) except exception.InvalidKeypair as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) except exception.KeyPairExists as exc: raise webob.exc.HTTPConflict(explanation=exc.format_message())
def test_create_no_admin(self): exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.create, self.user_req, {"aggregate": {"name": "test", "availability_zone": "nova1"}}) self.assertIn("compute_extension:v3:os-aggregates:create", exc.format_message())
def test_set_metadata_no_admin(self): exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller._set_metadata, self.user_req, "1", body={"set_metadata": {"metadata": {"foo": "bar"}}}) self.assertIn("compute_extension:v3:os-aggregates:set_metadata", exc.format_message())
def delete(self, req, id): """Delete a keypair with a given name.""" context = req.environ["nova.context"] authorize(context, action="delete") try: self.api.delete_key_pair(context, context.user_id, id) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message())
def delete(self, req, id): """Delete a keypair with a given name.""" context = req.environ['nova.context'] authorize(context, action='delete') try: self.api.delete_key_pair(context, context.user_id, id) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message()) return webob.Response(status_int=202)
def test_index_policy_failed(self): rule_name = "os_compute_api:os-services" self.policy.set_rules({rule_name: "project_id:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller.index, self.req) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def test_certificates_create_policy_failed(self): rules = { self.certificate_create_extension: "!" } policy.set_rules(oslo_policy.Rules.from_dict(rules)) exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.create, self.req) self.assertIn(self.certificate_create_extension, exc.format_message())
def _common_policy_check(self, func, *arg, **kwarg): rule_name = "os_compute_api:os-cloudpipe" rule = {rule_name: "project:non_fake"} self.policy.set_rules(rule) exc = self.assertRaises( exception.PolicyNotAuthorized, func, *arg, **kwarg) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def delete(self, req, id): """Deletes the specified service.""" context = req.environ['nova.context'] context.can(services_policies.BASE_POLICY_NAME) if api_version_request.is_supported( req, min_version=UUID_FOR_ID_MIN_VERSION): if not uuidutils.is_uuid_like(id): msg = _('Invalid uuid %s') % id raise webob.exc.HTTPBadRequest(explanation=msg) else: try: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest( explanation=exc.format_message()) try: service = self.host_api.service_get_by_id(context, id) # remove the service from all the aggregates in which it's included if service.binary == 'nova-compute': # Check to see if there are any instances on this compute host # because if there are, we need to block the service (and # related compute_nodes record) delete since it will impact # resource accounting in Placement and orphan the compute node # resource provider. # TODO(mriedem): Use a COUNT SQL query-based function instead # of InstanceList.get_uuids_by_host for performance. instance_uuids = objects.InstanceList.get_uuids_by_host( context, service['host']) if instance_uuids: raise webob.exc.HTTPConflict( explanation=_('Unable to delete compute service that ' 'is hosting instances. Migrate or ' 'delete the instances first.')) aggrs = self.aggregate_api.get_aggregates_by_host(context, service.host) for ag in aggrs: self.aggregate_api.remove_host_from_aggregate(context, ag.id, service.host) # remove the corresponding resource provider record from # placement for this compute node self.placementclient.delete_resource_provider( context, service.compute_node, cascade=True) # remove the host_mapping of this host. hm = objects.HostMapping.get_by_host(context, service.host) hm.destroy() self.host_api.service_delete(context, id) except exception.ServiceNotFound: explanation = _("Service %s not found.") % id raise webob.exc.HTTPNotFound(explanation=explanation) except exception.ServiceNotUnique: explanation = _("Service id %s refers to multiple services.") % id raise webob.exc.HTTPBadRequest(explanation=explanation)
def test_delete_policy_failed(self): rule_name = "os_compute_api:os-agents" self.policy.set_rules({rule_name: "project_id:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller.delete, self.req, fakes.FAKE_UUID) self.assertEqual( "Policy doesn't allow {0!s} to be performed.".format(rule_name), exc.format_message())
def test_add_tenant_access_policy_failed(self): rule_name = "os_compute_api:os-flavor-access:add_tenant_access" self.policy.set_rules({rule_name: "project:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.act_controller._add_tenant_access, self.req, fakes.FAKE_UUID, body={'addTenantAccess': {'tenant': fakes.FAKE_UUID}}) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def test_delete_assisted_volumes_snapshots_policy_failed(self): rule_name = "os_compute_api:os-assisted-volume-snapshots:delete" self.policy.set_rules({rule_name: "project:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller.delete, self.req, '5') self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def test_certificates_create_policy_failed(self): rules = { self.certificate_create_extension: common_policy.parse_rule("!") } policy.set_rules(rules) exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.create, self.req) self.assertIn(self.certificate_create_extension, exc.format_message())
def show(self, req, id): """Return data for the given key name.""" context = req.environ['nova.context'] authorize(context, action='show') try: keypair = self.api.get_key_pair(context, context.user_id, id) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message()) return {'keypair': keypair}
def test_create_assisted_volumes_snapshots_policy_failed(self): rule_name = "os_compute_api:os-assisted-volume-snapshots:create" self.policy.set_rules({rule_name: "project:non_fake"}) body = { 'snapshot': { 'volume_id': '1', 'create_info': { 'type': 'qcow2', 'new_file': 'new_file', 'snapshot_id': 'snapshot_id' } } } exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.create, self.req, body=body) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def test_update_policy_failed(self): rule_name = "os_compute_api:os-agents" self.policy.set_rules({rule_name: "project_id:non_fake"}) exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.update, self.req, fakes.FAKE_UUID, body={ 'para': { 'version': '7.0', 'url': 'xxx://xxxx/xxx/xxx', 'md5hash': 'add6bb58e139be103324d04d82d8f545' } }) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def update(self, req, id, body): """Update an existing agent build.""" context = req.environ['nova.context'] authorize(context) try: para = body['agent'] url = para['url'] md5hash = para['md5hash'] version = para['version'] except TypeError as e: raise webob.exc.HTTPBadRequest() except KeyError as e: raise webob.exc.HTTPBadRequest( explanation=_("Could not find %s parameter in the request") % e.args[0]) try: utils.check_string_length(url, 'url', max_length=255) utils.check_string_length(md5hash, 'md5hash', max_length=255) utils.check_string_length(version, 'version', max_length=255) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: db.agent_build_update(context, id, { 'version': version, 'url': url, 'md5hash': md5hash }) except exception.AgentBuildNotFound as ex: raise webob.exc.HTTPNotFound(explanation=ex.format_message()) return { "agent": { 'agent_id': id, 'version': version, 'url': url, 'md5hash': md5hash } }
def update(self, req, id, body): """Bulk delete floating IPs.""" context = req.environ['nova.context'] authorize(context) if id != "delete": raise webob.exc.HTTPNotFound("Unknown action") try: ip_range = body['ip_range'] except (TypeError, KeyError): raise webob.exc.HTTPUnprocessableEntity() try: ips = ({'address': str(address)} for address in self._address_to_hosts(ip_range)) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) db.floating_ip_bulk_destroy(context, ips) return {"floating_ips_bulk_delete": ip_range}
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: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: self.host_api.service_delete(context, id) except exception.ServiceNotFound: explanation = _("Service %s not found.") % id raise webob.exc.HTTPNotFound(explanation=explanation)
def create(self, req, body): """Creates a new agent build.""" context = req.environ['nova.context'] authorize(context) try: agent = body['agent'] hypervisor = agent['hypervisor'] os = agent['os'] architecture = agent['architecture'] version = agent['version'] url = agent['url'] md5hash = agent['md5hash'] except (TypeError, KeyError): raise webob.exc.HTTPUnprocessableEntity() try: utils.check_string_length(hypervisor, 'hypervisor', max_length=255) utils.check_string_length(os, 'os', max_length=255) utils.check_string_length(architecture, 'architecture', max_length=255) utils.check_string_length(version, 'version', max_length=255) utils.check_string_length(url, 'url', max_length=255) utils.check_string_length(md5hash, 'md5hash', max_length=255) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: agent_obj = objects.Agent(context=context) agent_obj.hypervisor = hypervisor agent_obj.os = os agent_obj.architecture = architecture agent_obj.version = version agent_obj.url = url agent_obj.md5hash = md5hash agent_obj.create() agent['agent_id'] = agent_obj.id except exception.AgentBuildExists as ex: raise webob.exc.HTTPServerError(explanation=ex.format_message()) return {'agent': agent}
def update(self, req, id, body): """Update an existing agent build.""" context = req.environ['nova.context'] authorize(context) try: para = body['para'] url = para['url'] md5hash = para['md5hash'] version = para['version'] except (TypeError, KeyError): raise webob.exc.HTTPUnprocessableEntity() try: utils.check_string_length(url, 'url', max_length=255) utils.check_string_length(md5hash, 'md5hash', max_length=255) utils.check_string_length(version, 'version', max_length=255) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: agent = objects.Agent(context=context, id=id) agent.obj_reset_changes() agent.version = version agent.url = url agent.md5hash = md5hash agent.save() except ValueError: raise webob.exc.HTTPUnprocessableEntity() except exception.AgentBuildNotFound as ex: raise webob.exc.HTTPNotFound(explanation=ex.format_message()) # NOTE(alex_xu): The agent_id should be integer that consistent with # create/index actions. But parameter 'id' is string type that parsed # from url. This is a bug, but because back-compatibility, it can't be # fixed for v2 API. This will be fixed after v3 API feature exposed by # micro-version in the future. lp bug #1333494 return {"agent": {'agent_id': id, 'version': version, 'url': url, 'md5hash': md5hash}}
def update(self, req, id, body): """Bulk delete floating IPs.""" context = req.environ['patron.context'] authorize(context) if id != "delete": msg = _("Unknown action") raise webob.exc.HTTPNotFound(explanation=msg) try: ip_range = body['ip_range'] except (TypeError, KeyError): raise webob.exc.HTTPUnprocessableEntity() try: ips = (objects.FloatingIPList.make_ip_info(address, None, None) for address in self._address_to_hosts(ip_range)) except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) objects.FloatingIPList.destroy(context, ips) return {"floating_ips_bulk_delete": ip_range}
def _show(self, req, id, user_id=None, **keypair_filters): """Return data for the given key name.""" context = req.environ['nova.context'] user_id = user_id or context.user_id context.can(kp_policies.POLICY_ROOT % 'show', target={'user_id': user_id, 'project_id': context.project_id}) try: # The return object needs to be a dict in order to pop the 'type' # field, if the api_version < 2.2. keypair = self.api.get_key_pair(context, user_id, id) keypair = self._filter_keypair(keypair, created_at=True, deleted=True, deleted_at=True, id=True, user_id=True, updated_at=True, **keypair_filters) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message()) # TODO(oomichi): It is necessary to filter a response of keypair with # _filter_keypair() when v2.1+microversions for implementing consistent # behaviors in this keypair resource. return {'keypair': keypair}
def show(self, req, id): """Return data for the given key name.""" context = req.environ['nova.context'] authorize(context, action='show') try: # Since this method returns the whole object, functional test # test_keypairs_get is failing, receiving an unexpected field # 'type', which was added to the keypair object. # TODO(claudiub): Revert the changes in the next commit, which will # enable nova-api to return the keypair type. keypair = self.api.get_key_pair(context, context.user_id, id) keypair = self._filter_keypair(keypair, created_at=True, deleted=True, deleted_at=True, id=True, user_id=True, updated_at=True) except exception.KeypairNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message()) # TODO(oomichi): It is necessary to filter a response of keypair with # _filter_keypair() when v2.1+microversions for implementing consistent # behaviors in this keypair resource. return {'keypair': keypair}
def update(self, req, id, body): """Update an existing agent build.""" context = req.environ['nova.context'] context.can(agents_policies.BASE_POLICY_NAME % 'update', target={}) # TODO(oomichi): This parameter name "para" is different from the ones # of the other APIs. Most other names are resource names like "server" # etc. This name should be changed to "agent" for consistent naming # with v2.1+microversions. para = body['para'] url = para['url'] md5hash = para['md5hash'] version = para['version'] try: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) agent = objects.Agent(context=context, id=id) agent.obj_reset_changes() agent.version = version agent.url = url agent.md5hash = md5hash try: agent.save() except exception.AgentBuildNotFound as ex: raise webob.exc.HTTPNotFound(explanation=ex.format_message()) # TODO(alex_xu): The agent_id should be integer that consistent with # create/index actions. But parameter 'id' is string type that parsed # from url. This is a bug, but because back-compatibility, it can't be # fixed for v2 API. This will be fixed in v2.1 API by Microversions in # the future. lp bug #1333494 return {"agent": {'agent_id': id, 'version': version, 'url': url, 'md5hash': md5hash}}
def delete(self, req, id): """Deletes the specified service.""" context = req.environ['nova.context'] context.can(services_policies.BASE_POLICY_NAME) try: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) try: service = self.host_api.service_get_by_id(context, id) # remove the service from all the aggregates in which it's included if service.binary == 'nova-compute': aggrs = self.aggregate_api.get_aggregates_by_host( context, service.host) for ag in aggrs: self.aggregate_api.remove_host_from_aggregate( context, ag.id, service.host) self.host_api.service_delete(context, id) except exception.ServiceNotFound: explanation = _("Service %s not found.") % id raise webob.exc.HTTPNotFound(explanation=explanation)
def index(self, req): """List of attributes for a user.""" context = req.environ['nova.context'] #authorize(context, action='create') ''' try: params = body['attribute'] name = params['name'] except KeyError: msg = _("Invalid request body") raise webob.exc.HTTPBadRequest(explanation=msg) ''' try: #print "IASDASDASDASDASDI am here" attlist = self.api.list(context) attribute = [] for att in attlist: attribute.append({'id': att.id, 'name': att.name}) print attribute return {'attribute': attribute} except exception.InvalidAttribute as exc: raise webob.exc.HTTPBadRequest(explanation=exc.format_message()) '''
def _update(self, context, host, binary, payload): """Do the actual PUT/update""" try: self.host_api.service_update(context, host, binary, payload) except exception.HostBinaryNotFound as exc: raise webob.exc.HTTPNotFound(explanation=exc.format_message())
def delete(self, req, id): """Deletes the specified service.""" context = req.environ['nova.context'] context.can(services_policies.BASE_POLICY_NAME) if api_version_request.is_supported( req, min_version=UUID_FOR_ID_MIN_VERSION): if not uuidutils.is_uuid_like(id): msg = _('Invalid uuid %s') % id raise webob.exc.HTTPBadRequest(explanation=msg) else: try: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest( explanation=exc.format_message()) try: service = self.host_api.service_get_by_id(context, id) # remove the service from all the aggregates in which it's included if service.binary == 'nova-compute': # Check to see if there are any instances on this compute host # because if there are, we need to block the service (and # related compute_nodes record) delete since it will impact # resource accounting in Placement and orphan the compute node # resource provider. # TODO(mriedem): Use a COUNT SQL query-based function instead # of InstanceList.get_uuids_by_host for performance. instance_uuids = objects.InstanceList.get_uuids_by_host( context, service['host']) if instance_uuids: raise webob.exc.HTTPConflict( explanation=_('Unable to delete compute service that ' 'is hosting instances. Migrate or ' 'delete the instances first.')) aggrs = self.aggregate_api.get_aggregates_by_host( context, service.host) for ag in aggrs: self.aggregate_api.remove_host_from_aggregate( context, ag.id, service.host) # remove the corresponding resource provider record from # placement for this compute node self.placementclient.delete_resource_provider( context, service.compute_node, cascade=True) # remove the host_mapping of this host. try: hm = objects.HostMapping.get_by_host(context, service.host) hm.destroy() except exception.HostMappingNotFound: # It's possible to startup a nova-compute service and then # delete it (maybe it was accidental?) before mapping it to # a cell using discover_hosts, so we just ignore this. pass self.host_api.service_delete(context, id) except exception.ServiceNotFound: explanation = _("Service %s not found.") % id raise webob.exc.HTTPNotFound(explanation=explanation) except exception.ServiceNotUnique: explanation = _("Service id %s refers to multiple services.") % id raise webob.exc.HTTPBadRequest(explanation=explanation)
def delete(self, req, id): """Deletes the specified service.""" context = req.environ['nova.context'] context.can(services_policies.BASE_POLICY_NAME % 'delete', target={}) if api_version_request.is_supported( req, min_version=UUID_FOR_ID_MIN_VERSION): if not uuidutils.is_uuid_like(id): msg = _('Invalid uuid %s') % id raise webob.exc.HTTPBadRequest(explanation=msg) else: try: utils.validate_integer(id, 'id') except exception.InvalidInput as exc: raise webob.exc.HTTPBadRequest( explanation=exc.format_message()) try: service = self.host_api.service_get_by_id(context, id) # remove the service from all the aggregates in which it's included if service.binary == 'nova-compute': # Check to see if there are any instances on this compute host # because if there are, we need to block the service (and # related compute_nodes record) delete since it will impact # resource accounting in Placement and orphan the compute node # resource provider. num_instances = objects.InstanceList.get_count_by_hosts( context, [service['host']]) if num_instances: raise webob.exc.HTTPConflict( explanation=_('Unable to delete compute service that ' 'is hosting instances. Migrate or ' 'delete the instances first.')) # Similarly, check to see if the are any in-progress migrations # involving this host because if there are we need to block the # service delete since we could orphan resource providers and # break the ability to do things like confirm/revert instances # in VERIFY_RESIZE status. compute_nodes = objects.ComputeNodeList.get_all_by_host( context, service.host) self._assert_no_in_progress_migrations(context, id, compute_nodes) aggrs = self.aggregate_api.get_aggregates_by_host( context, service.host) for ag in aggrs: self.aggregate_api.remove_host_from_aggregate( context, ag.id, service.host) # remove the corresponding resource provider record from # placement for the compute nodes managed by this service; # remember that an ironic compute service can manage multiple # nodes for compute_node in compute_nodes: try: self.placementclient.delete_resource_provider( context, compute_node, cascade=True) except ks_exc.ClientException as e: LOG.error( "Failed to delete compute node resource provider " "for compute node %s: %s", compute_node.uuid, six.text_type(e)) # remove the host_mapping of this host. try: hm = objects.HostMapping.get_by_host(context, service.host) hm.destroy() except exception.HostMappingNotFound: # It's possible to startup a nova-compute service and then # delete it (maybe it was accidental?) before mapping it to # a cell using discover_hosts, so we just ignore this. pass service.destroy() except exception.ServiceNotFound: explanation = _("Service %s not found.") % id raise webob.exc.HTTPNotFound(explanation=explanation) except exception.ServiceNotUnique: explanation = _("Service id %s refers to multiple services.") % id raise webob.exc.HTTPBadRequest(explanation=explanation)
def test_show_no_admin(self): exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.show, self.user_req, "1") self.assertIn("compute_extension:v3:os-aggregates:show", exc.format_message())
def _check_rule(self, exc, rule_name): self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
def test_certificates_create_policy_failed(self): rules = {self.certificate_create_extension: "!"} policy.set_rules(oslo_policy.Rules.from_dict(rules)) exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.create, self.req) self.assertIn(self.certificate_create_extension, exc.format_message())
def test_index_no_admin(self): exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller.index, self.user_req) self.assertIn("compute_extension:v3:os-aggregates:index", exc.format_message())