[Python in OpenStack] Nova Service & Python copy

来源:互联网 发布:android mysql客户端 编辑:程序博客网 时间:2024/06/05 01:39

1.Python拷贝

(1)Python 标准类库copy中的copy方法默认是浅拷贝(shadow copy):shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

(2)Python 标准类库copy中的deepcopy方法默认是浅拷贝(deep copy): deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

(3)对于定义了__copy__方法的类,copy.copy方法会调用类的__copy__方法,在类的__copy__方法中不可以再调用copy.copy方法,否则将会造成死循环。

import copyclass ObDeep(object):    def __init__(self, content):        self.content = content    @staticmethod    def __copy__(self):        rst = copy.deepcopy(self)        print "__copy__ method in Ob is called."        return rstclass ObShadow(object):    def __init__(self, content):        self.content = contentaa = ObDeep(['a', 'aa', 'aaa'])bb = copy.copy(aa)cc = copy.deepcopy(aa)print "test ObDeep "print "aa's content is : %s" % aa.contentprint "bb's content is : %s" % bb.contentprint "cc's content is : %s" % cc.contentaa.content[0] = 'A'print "after changed aa."print "aa's content is : %s" % aa.contentprint "bb's content is : %s" % bb.contentprint "cc's content is : %s" % cc.contentaa = ObShadow(['a', 'aa', 'aaa'])bb = copy.copy(aa)cc = copy.deepcopy(aa)print "test Ob"print "aa's content is : %s" % aa.contentprint "bb's content is : %s" % bb.contentprint "cc's content is : %s" % cc.contentaa.content[0] = 'A'print "after changed aa."print "aa's content is : %s" % aa.contentprint "bb's content is : %s" % bb.contentprint "cc's content is : %s" % cc.content

执行结果:

__copy__ method in Ob is called.test ObDeep aa's content is : ['a', 'aa', 'aaa']bb's content is : ['a', 'aa', 'aaa']cc's content is : ['a', 'aa', 'aaa']after changed aa.aa's content is : ['A', 'aa', 'aaa']bb's content is : ['a', 'aa', 'aaa']cc's content is : ['a', 'aa', 'aaa']test Obaa's content is : ['a', 'aa', 'aaa']bb's content is : ['a', 'aa', 'aaa']cc's content is : ['a', 'aa', 'aaa']after changed aa.aa's content is : ['A', 'aa', 'aaa']bb's content is : ['A', 'aa', 'aaa']cc's content is : ['a', 'aa', 'aaa']Process finished with exit code 0



OpenStack Nova中的Service对象:

Nova中的Service对象用于描述nova服务
首先来service对应在DB中的表:
class Service(BASE, NovaBase, models.SoftDeleteMixin):    """Represents a running service on a host."""    __tablename__ = 'services'    __table_args__ = (        schema.UniqueConstraint("host", "topic", "deleted",                                name="uniq_services0host0topic0deleted"),        schema.UniqueConstraint("host", "binary", "deleted",                                name="uniq_services0host0binary0deleted")        )    id = Column(Integer, primary_key=True)    host = Column(String(255))  # , ForeignKey('hosts.id'))    binary = Column(String(255))    topic = Column(String(255))    report_count = Column(Integer, nullable=False, default=0)    disabled = Column(Boolean, default=False)    disabled_reason = Column(String(255))    last_seen_up = Column(DateTime, nullable=True)    forced_down = Column(Boolean, default=False)    version = Column(Integer, default=0)    instance = orm.relationship(        "Instance",        backref='services',        primaryjoin='and_(Service.host == Instance.host,'                    'Service.binary == "nova-compute",'                    'Instance.deleted == 0)',        foreign_keys=host,    )

Service继承了NovaBase类
class NovaBase(models.TimestampMixin,               models.ModelBase):    metadata = None    def __copy__(self):        """Implement a safe copy.copy().        SQLAlchemy-mapped objects travel with an object        called an InstanceState, which is pegged to that object        specifically and tracks everything about that object.  It's        critical within all attribute operations, including gets        and deferred loading.   This object definitely cannot be        shared among two instances, and must be handled.        The copy routine here makes use of session.merge() which        already essentially implements a "copy" style of operation,        which produces a new instance with a new InstanceState and copies        all the data along mapped attributes without using any SQL.        The mode we are using here has the caveat that the given object        must be "clean", e.g. that it has no database-loaded state        that has been updated and not flushed.   This is a good thing,        as creating a copy of an object including non-flushed, pending        database state is probably not a good idea; neither represents        what the actual row looks like, and only one should be flushed.        """        session = orm.Session()        copy = session.merge(self, load=False)        session.expunge(copy)        return copy
其中定义了__copy__方法,这个自定义拷贝方法的含义涉及数据库和sqlachemy,这里先不展开,我们这里先知道copy.copy(service)对象的时候会调用这里的__copy__方法来完成一个特殊的动作即可。
可以看到service的主键是id,外键是host.id即service所在的物理主机的id,同时还有一个外键约束,要保证instances表(记录虚拟机相关信息)中,任意一个未被删除的虚拟机记录的host上面有nova-compute服务。原因很简单,虚拟机的生命周期管理,依赖nova-compute服务。



0 0