class ServerNic(base.MoganObject, object_base.VersionedObjectDictCompat): # Version 1.0: Initial version VERSION = '1.0' dbapi = dbapi.get_instance() fields = { 'port_id': object_fields.UUIDField(nullable=False), 'server_uuid': object_fields.UUIDField(nullable=True), 'mac_address': object_fields.MACAddressField(nullable=True), 'network_id': object_fields.UUIDField(nullable=True), 'fixed_ips': object_fields.ListOfDictOfNullableStringsField(nullable=True), 'floating_ip': object_fields.StringField(nullable=True), 'preserve_on_delete': object_fields.BooleanField(), } @staticmethod def _from_db_object(context, obj, db_object, server_uuid=None): if server_uuid: db_object = copy.deepcopy(db_object) db_object.update(server_uuid=server_uuid) if not isinstance(db_object, dict): db_object_dict = db_object.as_dict() else: db_object_dict = db_object obj = ServerNic(context) obj.update(db_object_dict) obj.obj_reset_changes() return obj @classmethod def delete_by_port_id(cls, context, port_id): cls.dbapi.server_nic_delete(context, port_id) @classmethod def get_by_port_id(cls, context, port_id): return cls.dbapi.server_nic_get(context, port_id) def save(self, context): updates = self.obj_get_changes() self.dbapi.server_nic_update_or_create(context, self.port_id, updates) def create(self, context): values = self.obj_to_primitive()['mogan_object.data'] self.dbapi.server_nic_update_or_create(context, self.port_id, values) def delete(self, context): self.dbapi.server_nic_delete(context, self.port_id)
class Server(base.MoganObject, object_base.VersionedObjectDictCompat): # Version 1.0: Initial version VERSION = '1.0' dbapi = dbapi.get_instance() fields = { 'id': object_fields.IntegerField(), 'uuid': object_fields.UUIDField(nullable=True), 'name': object_fields.StringField(nullable=True), 'description': object_fields.StringField(nullable=True), 'project_id': object_fields.UUIDField(nullable=True), 'user_id': object_fields.UUIDField(nullable=True), 'status': object_fields.StringField(nullable=True), 'power_state': object_fields.StringField(nullable=True), 'flavor_uuid': object_fields.UUIDField(nullable=True), 'availability_zone': object_fields.StringField(nullable=True), 'image_uuid': object_fields.UUIDField(nullable=True), 'nics': object_fields.ObjectField('ServerNics', nullable=True), 'fault': object_fields.ObjectField('ServerFault', nullable=True), 'node_uuid': object_fields.UUIDField(nullable=True), 'launched_at': object_fields.DateTimeField(nullable=True), 'metadata': object_fields.FlexibleDictField(nullable=True), 'locked': object_fields.BooleanField(default=False), 'locked_by': object_fields.StringField(nullable=True), } def __init__(self, context=None, **kwargs): server_nics = kwargs.pop('nics', None) if server_nics and isinstance(server_nics, list): nics_obj = objects.ServerNics(context) for nic in server_nics: nic_obj = objects.ServerNic(context, server_uuid=kwargs['uuid'], **nic) nics_obj.objects.append(nic_obj) kwargs['nics'] = nics_obj super(Server, self).__init__(context=context, **kwargs) @staticmethod def _from_db_object(server, db_server, expected_attrs=None): """Method to help with migration to objects. Converts a database entity to a formal object. :param server: An object of the Server class. :param db_server: A DB Server model of the object :return: The object of the class with the database entity added """ for field in set(server.fields) - set(OPTIONAL_ATTRS): if field == 'metadata': server[field] = db_server['extra'] else: server[field] = db_server[field] if expected_attrs is None: expected_attrs = [] if 'nics' in expected_attrs: server._load_server_nics(server._context, server.uuid) else: server.nics = None if 'fault' in expected_attrs: server._load_fault(server._context, server.uuid) server.obj_reset_changes() return server def _load_server_nics(self, context, server_uuid): self.nics = objects.ServerNics.get_by_server_uuid( context=context, server_uuid=server_uuid) @staticmethod def _from_db_object_list(db_objects, cls, context): """Converts a list of database entities to a list of formal objects.""" servers = [] for obj in db_objects: expected_attrs = ['nics', 'fault'] servers.append( Server._from_db_object(cls(context), obj, expected_attrs)) return servers def _load_fault(self, context, server_uuid): self.fault = objects.ServerFault.get_latest_for_server( context=context, server_uuid=server_uuid) def _save_nics(self, context): for nic_obj in self.nics or []: nic_obj.save(context) def as_dict(self): data = dict(self.items()) if 'nics' in data: data.update(nics=data['nics'].as_list_of_dict()) return data @classmethod def list(cls, context, project_only=False, filters=None): """Return a list of Server objects.""" db_servers = cls.dbapi.server_get_all(context, project_only=project_only, filters=filters) return Server._from_db_object_list(db_servers, cls, context) @classmethod def get(cls, context, uuid): """Find a server and return a Server object.""" expected_attrs = ['nics', 'fault'] db_server = cls.dbapi.server_get(context, uuid) server = Server._from_db_object(cls(context), db_server, expected_attrs) return server def create(self, context=None): """Create a Server record in the DB.""" values = self.obj_get_changes() metadata = values.pop('metadata', None) if metadata is not None: values['extra'] = metadata server_nics = values.pop('nics', None) if server_nics: values['nics'] = server_nics.as_list_of_dict() db_server = self.dbapi.server_create(context, values) expected_attrs = None if server_nics: expected_attrs = ['nics'] self._from_db_object(self, db_server, expected_attrs) def destroy(self, context=None): """Delete the Server from the DB.""" self.dbapi.server_destroy(context, self.uuid) self.obj_reset_changes() def save(self, context=None): """Save updates to this Server.""" updates = self.obj_get_changes() for field in list(updates): if (self.obj_attr_is_set(field) and isinstance( self.fields[field], object_fields.ObjectField) and getattr(self, field, None) is not None): try: getattr(self, '_save_%s' % field)(context) except AttributeError: LOG.exception('No save handler for %s', field, server=self) except db_exc.DBReferenceError as exp: if exp.key != 'server_uuid': raise updates.pop(field) metadata = updates.pop('metadata', None) if metadata is not None: updates['extra'] = metadata self.dbapi.server_update(context, self.uuid, updates) self.obj_reset_changes() def refresh(self, context=None): """Refresh the object by re-fetching from the DB.""" current = self.__class__.get(context, self.uuid) self.obj_refresh(current) self.obj_reset_changes()
class Flavor(base.MoganObject, object_base.VersionedObjectDictCompat): # Version 1.0: Initial version VERSION = '1.0' dbapi = dbapi.get_instance() fields = { 'uuid': object_fields.UUIDField(nullable=True), 'name': object_fields.StringField(nullable=True), 'description': object_fields.StringField(nullable=True), 'is_public': object_fields.BooleanField(), 'disabled': object_fields.BooleanField(), 'resources': object_fields.FlexibleDictField(nullable=True), 'resource_traits': object_fields.FlexibleDictField(nullable=True), 'projects': object_fields.ListOfStringsField(), } def __init__(self, *args, **kwargs): super(Flavor, self).__init__(*args, **kwargs) self._orig_projects = {} @staticmethod def _from_db_object(context, flavor, db_flavor, expected_attrs=None): if expected_attrs is None: expected_attrs = [] for name, field in flavor.fields.items(): if name in OPTIONAL_FIELDS: continue value = db_flavor[name] if isinstance(field, object_fields.IntegerField): value = value if value is not None else 0 flavor[name] = value if 'projects' in expected_attrs: flavor._load_projects(context) flavor.obj_reset_changes() return flavor def _load_projects(self, context): self.projects = [x['project_id'] for x in self.dbapi.flavor_access_get(context, self.uuid)] self.obj_reset_changes(['projects']) def obj_reset_changes(self, fields=None, recursive=False): super(Flavor, self).obj_reset_changes(fields=fields, recursive=recursive) if fields is None or 'projects' in fields: self._orig_projects = (list(self.projects) if self.obj_attr_is_set('projects') else []) def obj_what_changed(self): changes = super(Flavor, self).obj_what_changed() if 'projects' in self and self.projects != self._orig_projects: changes.add('projects') return changes @staticmethod def _from_db_object_list(db_objects, cls, context): """Converts a list of database entities to a list of formal objects.""" return [Flavor._from_db_object(context, cls(context), obj) for obj in db_objects] @classmethod def list(cls, context): """Return a list of Flavor objects.""" db_flavors = cls.dbapi.flavor_get_all(context) return Flavor._from_db_object_list(db_flavors, cls, context) @classmethod def get(cls, context, flavor_uuid): """Find a Flavor and return a Flavor object.""" db_flavor = cls.dbapi.flavor_get(context, flavor_uuid) flavor = Flavor._from_db_object( context, cls(context), db_flavor, expected_attrs=['projects']) return flavor def create(self, context=None): """Create a Flavor record in the DB.""" values = self.obj_get_changes() db_flavor = self.dbapi.flavor_create(context, values) self._from_db_object(context, self, db_flavor) def destroy(self, context=None): """Delete the Flavor from the DB.""" self.dbapi.flavor_destroy(context, self.uuid) self.obj_reset_changes() def save(self, context=None): updates = self.obj_get_changes() projects = updates.pop('projects', None) # access projects if projects is not None: deleted_projects = set(self._orig_projects) - set(projects) added_projects = set(projects) - set(self._orig_projects) else: added_projects = deleted_projects = None if added_projects or deleted_projects: self.save_projects(context, added_projects, deleted_projects) self.dbapi.flavor_update(context, self.uuid, updates) def save_projects(self, context, to_add=None, to_delete=None): """Add or delete projects. :param:to_add: A list of projects to add :param:to_delete: A list of projects to remove """ ident = self.uuid to_add = to_add if to_add is not None else [] to_delete = to_delete if to_delete is not None else [] for project_id in to_add: self.dbapi.flavor_access_add(context, ident, project_id) for project_id in to_delete: self.dbapi.flavor_access_remove(context, ident, project_id) self.obj_reset_changes(['projects'])