#!/usr/bin/env python
#-*-coding:utf8-*-
#实时监控snapshot 状态,如果网络 出现异常,直接重置snapshot 状态~
“”
创建snapshot 盘
qemu-img create -b root.img -f qcow2 root.qcow2
snapshot 创建
virtsh snapshot-create-as  vm200001 vm200012
snapshot 重置
virsh snapshot-revert vm200001 vm2000012
”“

import  socket
import os,sys,time
import shutil

class Revert(object):
    def __init__ (self):
        pass
    
    def log(self,info):
        files = open('/var/log/listen.log','a')
        try:
            files.write(info)
        except IOError:
            files.close()
        files.close()
        size = os.path.getsize('/var/log/listen.log') / 1024
        if size >= 1024:
            shutil.move('/var/log/listen.log','/dev/null')
        
        
    def mysock(self):
        while True:
            asock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            asock.settimeout(10)
            try:
                asock.connect(('192.168.10.130',22))
                asock.close()
                time.sleep(3)
                self.log('%s:--: connect done \n'%(time.ctime()))
            except socket.timeout,e:
                self.log('%s:--: connect false:%s \n'%(time.ctime(),e))
                os.system('virsh snapshot-revert vm200001 vm2000012')
        
        
if __name__ == "__main__":
    pid = os.fork()
    if pid > 0 :
        sys.exit(0)
    os.setsid()
    os.chdir('/')
    sys.stdin = open("/dev/null","r+")
    sys.stdout = os.dup(sys.stdin.fileno())
    sys.stderr = os.dup(sys.stdin.fileno())
    reset = Revert()
    reset.mysock()