libvirt 监听虚拟机的启动、关机等生命周期事件

下面是一个使用libvirt监听虚拟机事件的代码。

以前写过类似的代码,做了一下优化,分享出来,不过下面的代码依然有优化的空间,平时工作比较繁忙,所以不在继续优化了。

import logging as log
import libvirt
import threading
class _Monitor(object):
    def __init__(self):
        super(_Monitor, self).__init__()
        self.conn = libvirt.open("qemu:///system")
        self.regist_event()
    def regist_event(self):
        for ev in (libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,):
            self.conn.domainEventRegisterAny(None, ev, self.dispatch_libvirt_events, ev)
    def dispatch_libvirt_events(self, conn, dom, *args):
        try:
            eventid = args[-1]
            if eventid == libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE:
                event, detail = args[:-1]
                self.on_libvirt_lifecycle_event(dom.name(), event, detail, None)
        except Exception, e:
            log.exception(e)
            raise Exception(e)
    def on_libvirt_lifecycle_event(self, name, event, detail, opaque):
        msg = '%s event %s(%d) detail %s(%d) opaque %s' % \
              (name,
               self.event_to_string(event),
               event,
               self.detail_to_string(event,
                                     detail),
               detail,
               opaque)
        print msg
        log.info(msg)
        if event == libvirt.VIR_DOMAIN_EVENT_STARTED:
            pass
        elif event == libvirt.VIR_DOMAIN_EVENT_STOPPED and\
                detail in (libvirt.VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN,
                           libvirt.VIR_DOMAIN_EVENT_STOPPED_DESTROYED):
            log.info('shutdown event triggered.')
        else:
            pass
    def event_to_string(self, event):
        eventStrings = ("Defined",
                        "Undefined",
                        "Started",
                        "Suspended",
                        "Resumed",
                        "Stopped",
                        "Shutdown",
                        "PMSuspended")
        return eventStrings[event]
    def detail_to_string(self, event, detail):
        eventStrings = (
            ("Added", "Updated"),
            ("Removed", ),
            ("Booted", "Migrated", "Restored", "Snapshot", "Wakeup"),
            ("Paused", "Migrated", "IOError", "Watchdog",
                "Restored", "Snapshot", "API error"),
            ("Unpaused", "Migrated", "Snapshot"),
            ("Shutdown", "Destroyed", "Crashed", "Migrated",
                "Saved", "Failed", "Snapshot"),
            ("Finished", ),
            ("Memory", "Disk")
        )
        return eventStrings[event][detail]
class _EventLoop:
    def __init__(self):
        self.run = False
        self.__thread = None
    def start(self):
                                               
        assert not self.run
        self.__thread = threading.Thread(target=self.__run, name="libvirtEventLoop")
        self.__thread.setDaemon(True)
        self.run = True
        self.__thread.start()
    def stop(self, wait=True):
        if self.run:
            self.run = False
            if wait:
                self.__thread.join()
            self.__thread = None
    def __run(self):
        try:
            libvirt.virEventRegisterDefaultImpl()
            monitor = _Monitor()
            while self.run:
                libvirt.virEventRunDefaultImpl()
        except Exception as e:
            log.exception(e)
        finally:
            self.run = False
__event_loop = _EventLoop()
def start_event_loop():
    __event_loop.start()
def stop_event_loop(wait=True):
    __event_loop.stop(wait)
if __name__ == "__main__":
    start_event_loop()
    while True:
        pass

No comments yet.

Leave a comment

Comment form

All fields marked (*) are required

返回顶部
跳到底部