def extract_flavor(instance, prefix=''): """Create a Flavor object from instance's system_metadata information. """ flavor = objects.Flavor() sys_meta = utils.instance_sys_meta(instance) if not sys_meta: return None for key in system_metadata_flavor_props.keys(): type_key = '%sinstance_type_%s' % (prefix, key) setattr(flavor, key, sys_meta[type_key]) # NOTE(danms): We do NOT save all of extra_specs, but only the # NUMA-related ones that we need to avoid an uglier alternative. This # should be replaced by a general split-out of flavor information from # system_metadata very soon. extra_specs = [(k, v) for k, v in sys_meta.items() if k.startswith('%sinstance_type_extra_' % prefix)] if extra_specs: flavor.extra_specs = {} for key, value in extra_specs: extra_key = key[len('%sinstance_type_extra_' % prefix):] flavor.extra_specs[extra_key] = value return flavor
def _from_flavor(self, flavor): if isinstance(flavor, objects.Flavor): self.flavor = flavor elif isinstance(flavor, dict): # NOTE(sbauza): Again, request_spec is primitived by # sched_utils.build_request_spec() and passed to # select_destinations() like this # TODO(sbauza): To be removed once all RequestSpec hydrations are # done on the conductor side self.flavor = objects.Flavor(**flavor)
def destroy(name): """Marks flavor as deleted.""" try: if not name: raise ValueError() flavor = objects.Flavor(context=context.get_admin_context(), name=name) flavor.destroy() except (ValueError, exception.NotFound): LOG.exception(_LE('Instance type %s not found for deletion'), name) raise exception.FlavorNotFoundByName(flavor_name=name)
def _remove_tenant_access(self, req, id, body): context = req.environ['compute.context'] authorize(context, action="remove_tenant_access") vals = body['removeTenantAccess'] tenant = vals['tenant'] flavor = objects.Flavor(context=context, flavorid=id) try: flavor.remove_access(tenant) except (exception.FlavorAccessNotFound, exception.FlavorNotFound) as e: raise webob.exc.HTTPNotFound(explanation=e.format_message()) except exception.AdminRequired as e: raise webob.exc.HTTPForbidden(explanation=e.format_message()) return _marshall_flavor_access(flavor)
def _removeTenantAccess(self, req, id, body): context = req.environ['compute.context'] authorize(context, action="removeTenantAccess") # NOTE(alex_xu): back-compatible with db layer hard-code admin # permission checks. nova_context.require_admin_context(context) self._check_body(body) vals = body['removeTenantAccess'] tenant = vals.get('tenant') if not tenant: msg = _("Missing tenant parameter") raise webob.exc.HTTPBadRequest(explanation=msg) flavor = objects.Flavor(context=context, flavorid=id) try: flavor.remove_access(tenant) except (exception.FlavorNotFound, exception.FlavorAccessNotFound) as err: raise webob.exc.HTTPNotFound(explanation=err.format_message()) return _marshall_flavor_access(flavor)
def build_instances(self, ctxt, build_inst_kwargs): """Pick a cell (possibly ourselves) to build new instance(s) and forward the request accordingly. """ # Target is ourselves first. filter_properties = build_inst_kwargs.get('filter_properties') if (filter_properties is not None and not isinstance( filter_properties['instance_type'], objects.Flavor)): # NOTE(danms): Handle pre-1.30 build_instances() call. Remove me # when we bump the RPC API version to 2.0. flavor = objects.Flavor(**filter_properties['instance_type']) build_inst_kwargs['filter_properties'] = dict(filter_properties, instance_type=flavor) instances = build_inst_kwargs['instances'] if not isinstance(instances[0], objects.Instance): # NOTE(danms): Handle pre-1.32 build_instances() call. Remove me # when we bump the RPC API version to 2.0 build_inst_kwargs['instances'] = instance_obj._make_instance_list( ctxt, objects.InstanceList(), instances, ['system_metadata', 'metadata']) our_cell = self.state_manager.get_my_state() self.msg_runner.build_instances(ctxt, our_cell, build_inst_kwargs)
def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None, swap=0, rxtx_factor=1.0, is_public=True): """Creates flavors.""" if not flavorid: flavorid = uuid.uuid4() kwargs = { 'memory_mb': memory, 'vcpus': vcpus, 'root_gb': root_gb, 'ephemeral_gb': ephemeral_gb, 'swap': swap, 'rxtx_factor': rxtx_factor, } if isinstance(name, six.string_types): name = name.strip() # ensure name do not exceed 255 characters utils.check_string_length(name, 'name', min_length=1, max_length=255) # ensure name does not contain any special characters valid_name = parameter_types.valid_name_regex_obj.search(name) if not valid_name: msg = _("Flavor names can only contain printable characters " "and horizontal spaces.") raise exception.InvalidInput(reason=msg) # NOTE(vish): Internally, flavorid is stored as a string but it comes # in through json as an integer, so we convert it here. flavorid = six.text_type(flavorid) # ensure leading/trailing whitespaces not present. if flavorid.strip() != flavorid: msg = _("id cannot contain leading and/or trailing whitespace(s)") raise exception.InvalidInput(reason=msg) # ensure flavor id does not exceed 255 characters utils.check_string_length(flavorid, 'id', min_length=1, max_length=255) # ensure flavor id does not contain any special characters valid_flavor_id = VALID_ID_REGEX.search(flavorid) if not valid_flavor_id: msg = _("Flavor id can only contain letters from A-Z (both cases), " "periods, dashes, underscores and spaces.") raise exception.InvalidInput(reason=msg) # NOTE(wangbo): validate attributes of the creating flavor. # ram and vcpus should be positive ( > 0) integers. # disk, ephemeral and swap should be non-negative ( >= 0) integers. flavor_attributes = { 'memory_mb': ('ram', 1), 'vcpus': ('vcpus', 1), 'root_gb': ('disk', 0), 'ephemeral_gb': ('ephemeral', 0), 'swap': ('swap', 0) } for key, value in flavor_attributes.items(): kwargs[key] = utils.validate_integer(kwargs[key], value[0], value[1], db.MAX_INT) # rxtx_factor should be a positive float try: kwargs['rxtx_factor'] = float(kwargs['rxtx_factor']) if (kwargs['rxtx_factor'] <= 0 or kwargs['rxtx_factor'] > SQL_SP_FLOAT_MAX): raise ValueError() except ValueError: msg = (_("'rxtx_factor' argument must be a float between 0 and %g") % SQL_SP_FLOAT_MAX) raise exception.InvalidInput(reason=msg) kwargs['name'] = name kwargs['flavorid'] = flavorid # ensure is_public attribute is boolean try: kwargs['is_public'] = strutils.bool_from_string(is_public, strict=True) except ValueError: raise exception.InvalidInput(reason=_("is_public must be a boolean")) flavor = objects.Flavor(context=context.get_admin_context(), **kwargs) flavor.create() return flavor