예제 #1
0
파일: event_2.py 프로젝트: vhnuuh/pyutil
 def __run(self):
     try:
         while self.run:
             print 'virEventRunDefaultImpl'
             libvirt.virEventRunDefaultImpl()
     finally:
         self.run = False
예제 #2
0
 def __run(self):
     try:
         libvirt.virEventRegisterDefaultImpl()
         while self.run:
             libvirt.virEventRunDefaultImpl()
     finally:
         self.run = False
예제 #3
0
    def waitForAction(self, domid, timeout=None, events=None):
        libvirt.virEventRegisterDefaultImpl()
        rocon = libvirt.openReadOnly()
        run = {'state': True, 'timeout': False}

        def timecb(timerid, opaque):
            run['state'] = False
            run['timeout'] = True

        def callback(con, domain, event, detail, opaque):
            if domain.UUIDString() == domid:
                if events is not None and event in events:
                    run['state'] = False
                    return True

        if timeout:
            libvirt.virEventAddTimeout(timeout, timecb, None)
        rocon.domainEventRegisterAny(None,
                                     libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
                                     callback,
                                     rocon)
        while run['state']:
            libvirt.virEventRunDefaultImpl()

        if run['timeout']:
            raise TimeoutError("Failed to wait for state")
예제 #4
0
 def __run(self):
     try:
         libvirt.virEventRegisterDefaultImpl()
         while self.run:
             libvirt.virEventRunDefaultImpl()
     finally:
         self.run = False
예제 #5
0
    def run(self):

        """
        Runs the libvirt event implementation in a tight-loop
        """

        while True:
            libvirt.virEventRunDefaultImpl()
예제 #6
0
    def libvirt_event_loop(self, guest, client):
        """Runs libvirt event loop.
        """
        # stop the event loop when the guest is not running
        while guest.is_running():
            libvirt.virEventRunDefaultImpl()

        # shutdown the client socket to unblock the recv and stop the
        # server as soon as the guest shuts down
        client.shutdown(socket.SHUT_RD)
예제 #7
0
    def libvirt_event_loop(self, guest, client):
        """Runs libvirt event loop.
        """
        # stop the event loop when the guest is not running
        while guest.is_running():
            libvirt.virEventRunDefaultImpl()

        # shutdown the client socket to unblock the recv and stop the
        # server as soon as the guest shuts down
        client.shutdown(socket.SHUT_RD)
예제 #8
0
def _runVirDefaultEventLoop():
    '''Run Libvirt default event loop
    implementaion forever
    '''
    # NOTE(jay): Native threads cannot use LOG.
    # In particular any use of logging is forbidden, since it will confuse
    # eventlet's greenthread integration.
    # Due to limitations with eventlet locking we cannot use the
    # logging API inside the called function.

    while True:
        # Thread blocks until event occurs or times out. virEventPollRunOnce()
        libvirt.virEventRunDefaultImpl()
예제 #9
0
def main():
    print("--> vm_shield_controller started! <--")
    libvirt.virEventRegisterDefaultImpl()
    conn = libvirt.open('qemu:///system')
    domain = conn.lookupByName(vm_name)

    on_start(domain)

    cb_id = conn.domainEventRegisterAny(domain,
                                        libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
                                        vm_lifecycle_event, None)

    # Blocking loop triggered by VM state changes
    while True:
        libvirt.virEventRunDefaultImpl()
예제 #10
0
 def run_default_impl(self):
     try:
         return libvirt.virEventRunDefaultImpl()
     except libvirt.libvirtError, e:
         message = e.get_error_message()
         code = e.get_error_code()
         raise exception.LibvirtAPI(message, code)
예제 #11
0
 def virEventLoopNativeRun():
     self.register_handlers_for_domain()
     try:
         while libvirt:
             if libvirt.virEventRunDefaultImpl() < 0:
                 raise Failure("Error in libvirt event handler")
     except:
         raise Failure("error in libvirt event loop")
예제 #12
0
 def virEventLoopNativeRun():
     self.register_handlers_for_domain()
     try:
         while libvirt:
             if libvirt.virEventRunDefaultImpl() < 0:
                 raise Failure("Error in libvirt event handler")
     except:
         raise Failure("error in libvirt event loop")
예제 #13
0
def monitor(uris, callback):
    libvirt.virEventRegisterDefaultImpl()

    conns = {}
    for uri in uris:
        conn = libvirt.openReadOnly(uri)
        conns[uri] = conn

        conn.setKeepAlive(5, 3)

        conn.domainEventRegisterAny(
            dom=None,
            eventID=libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
            cb=_handle_event,
            opaque=dict(uri=uri, callback=callback),
            )

    for uri, conn in conns.iteritems():
        for domain in getAllDomains(conn):
            # inject fake defined event for each domain that
            # exists at startup
            _handle_event(
                conn=conn,
                domain=domain,
                event=libvirt.VIR_DOMAIN_EVENT_DEFINED,
                detail=None,
                opaque=dict(uri=uri, callback=callback),
                )

    # signal that all current vms have been observed; that is, pruning
    # old entries is safe
    callback(dict(type='libvirt_complete'))

    while True:
        libvirt.virEventRunDefaultImpl()

        for uri, conn in conns.iteritems():
            if not conn.isAlive() == 1:
                # conn.close() tends to fail at this point, so don't
                # even try
                raise RuntimeError(
                    'Lost connection to {uri}'.format(uri=uri),
                    )
예제 #14
0
def wait_for_guest_agent(conn, domain, timeout):
    done = False

    def timeoutEventCallback(timer, opaque):
        logging.info("timeout event:")
        nonlocal done
        done = True

    def domainEventAgentLifecycleCallback (conn, dom, state, reason, opaque):
        logging.info("agentLifecycle event: domain '%s' state %d reason %d" % (dom.name(), state, reason))
        if state == libvirt.VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_CONNECTED:
            nonlocal done
            done = True

    timer_id = libvirt.virEventAddTimeout(timeout*1000, timeoutEventCallback, None)

    conn.domainEventRegisterAny(domain, libvirt.VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE, domainEventAgentLifecycleCallback, None)

    while not done:
        libvirt.virEventRunDefaultImpl()

    libvirt.virEventRemoveTimeout(timer_id)
예제 #15
0
    def start(self):
        libvirt.virEventRegisterDefaultImpl()
        libvirt.registerErrorHandler(error_handler, None)

        atexit.register(self.reset_term)
        self.attrs = termios.tcgetattr(0)
        tty.setraw(0)

        self.connection = LibvirtConnect.get_connection()
        self.domain = self.connection.lookupByName(self.domain_name)
        self.state = self.domain.state(0)
        self.connection.domainEventRegister(self.lifecycle_callback, self)

        sys.stdout.write('Press Control+] to quit.\n\r')
        sys.stdout.flush()

        libvirt.virEventAddHandle(
            0, libvirt.VIR_EVENT_HANDLE_READABLE, self.stdin_callback, None)

        while self.check_console():
            libvirt.virEventRunDefaultImpl()

        sys.stdout.write('\n\rExited.\n\r')
        sys.stdout.flush()
예제 #16
0
def start(uri=None, tag_prefix="salt/engines/libvirt_events", filters=None):
    """
    Listen to libvirt events and forward them to salt.

    :param uri: libvirt URI to listen on.
                Defaults to None to pick the first available local hypervisor
    :param tag_prefix: the begining of the salt event tag to use.
                       Defaults to 'salt/engines/libvirt_events'
    :param filters: the list of event of listen on. Defaults to 'all'
    """
    if filters is None:
        filters = ["all"]
    try:
        libvirt.virEventRegisterDefaultImpl()

        cnx = libvirt.openReadOnly(uri)
        log.debug("Opened libvirt uri: %s", cnx.getURI())

        callback_ids = {}
        all_filters = "all" in filters

        for obj, event_defs in CALLBACK_DEFS.items():
            for event, real_id in event_defs:
                event_filter = "/".join((obj, event))
                if (
                    event_filter not in filters
                    and obj not in filters
                    and not all_filters
                ):
                    continue
                registered_id = _register_callback(cnx, tag_prefix, obj, event, real_id)
                if registered_id:
                    _append_callback_id(callback_ids, obj, registered_id)

        exit_loop = False
        while not exit_loop:
            exit_loop = libvirt.virEventRunDefaultImpl() < 0
            log.debug("=== in the loop exit_loop %s ===", exit_loop)

    except Exception as err:  # pylint: disable=broad-except
        log.exception(err)
    finally:
        _callbacks_cleanup(cnx, callback_ids)
        _cleanup(cnx)
예제 #17
0
def start(uri='qemu:///system',
          tag_prefix='salt/engines/libvirt_events',
          filters=None):
    '''
    Listen to libvirt events and forward them to salt.

    :param uri: libvirt URI to listen on.
                Defaults to 'qemu:///system'
    :param tag_prefix: the begining of the salt event tag to use.
                       Defaults to 'salt/engines/libvirt_events'
    :param filters: the list of event of listen on. Defaults to 'all'
    '''
    if filters is None:
        filters = ['all']
    try:
        libvirt.virEventRegisterDefaultImpl()

        log.debug('Opening libvirt uri: %s', uri)
        cnx = libvirt.openReadOnly(uri)

        callback_ids = {}
        all_filters = "all" in filters

        for obj, event_defs in CALLBACK_DEFS.items():
            for event, real_id in event_defs:
                event_filter = "/".join((obj, event))
                if event_filter not in filters and obj not in filters and not all_filters:
                    continue
                registered_id = _register_callback(cnx, tag_prefix,
                                                   obj, event, real_id)
                if registered_id:
                    _append_callback_id(callback_ids, obj, registered_id)

        exit_loop = False
        while not exit_loop:
            exit_loop = libvirt.virEventRunDefaultImpl() < 0

    except Exception as err:  # pylint: disable=broad-except
        log.exception(err)
    finally:
        _callbacks_cleanup(cnx, callback_ids)
        _cleanup(cnx)
예제 #18
0
 def run(self):
     while True:
         # if this method will fail it raises libvirtError
         # we do not catch the exception here so it will show up
         # in the logs. Not sure when this call will ever fail
         libvirt.virEventRunDefaultImpl()
예제 #19
0
def virEventLoopNativeRun():
    while True:
        libvirt.virEventRunDefaultImpl()
예제 #20
0
 def loop(self):
     while self.check_console():
         libvirt.virEventRunDefaultImpl()
예제 #21
0
    logging.info("%s transitioned to state %d, reason %d",
                 console.uuid, console.state[0], console.state[1])


# main
if len(sys.argv) != 3:
    print("Usage:", sys.argv[0], "URI UUID")
    print("for example:", sys.argv[0], "'qemu:///system' '32ad945f-7e78-c33a-e96d-39f25e025d81'")
    sys.exit(1)

uri = sys.argv[1]
uuid = sys.argv[2]

print("Escape character is ^]")
logging.basicConfig(filename='msg.log', level=logging.DEBUG)
logging.info("URI: %s", uri)
logging.info("UUID: %s", uuid)

libvirt.virEventRegisterDefaultImpl()
libvirt.registerErrorHandler(error_handler, None)

atexit.register(reset_term)
attrs = termios.tcgetattr(0)
tty.setraw(0)

console = Console(uri, uuid)
console.stdin_watch = libvirt.virEventAddHandle(0, libvirt.VIR_EVENT_HANDLE_READABLE, stdin_callback, console)

while check_console(console):
    libvirt.virEventRunDefaultImpl()
예제 #22
0
 def _event_loop():
     while not is_listening:
         libvirt.virEventRunDefaultImpl()
예제 #23
0
 def watch_loop(self):
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #24
0
 def _event_loop_run(self):
     while True:
         if libvirt.virEventRunDefaultImpl() < 0:
             raise OperationFailed('KCHEVENT0003E')
예제 #25
0
 def _event_loop_native(self):
     while self.running:
         libvirt.virEventRunDefaultImpl()
예제 #26
0
 def run(self):
     while not self._terminated.is_set():
         libvirt.virEventRunDefaultImpl()
예제 #27
0
 def __run(self):
     while self.run:
         libvirt.virEventRunDefaultImpl()
예제 #28
0
 def __run(self):
     while self.run:
         libvirt.virEventRunDefaultImpl()
예제 #29
0
def vir_event_loop_native_run():
    while True:
        libvirt.virEventRunDefaultImpl()
예제 #30
0
def virEventLoopNativeRun():
    while True:
        libvirt.virEventRunDefaultImpl()
예제 #31
0
 def runVirEventLoop():
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #32
0
 def __run(self):
     libvirt.virEventRegisterDefaultImpl()
     while self.run:
         libvirt.virEventRunDefaultImpl()
 def _native_loop(self):
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #34
0
 def _event_loop_native(self):
     while self.running:
         libvirt.virEventRunDefaultImpl()
예제 #35
0
    console.state = console.domain.state(0)
    logging.info("%s transitioned to state %d, reason %d",
                 console.uuid, console.state[0], console.state[1])

# main
if len(sys.argv) != 3:
    print("Usage:", sys.argv[0], "URI UUID")
    print("for example:", sys.argv[0], "'qemu:///system' '32ad945f-7e78-c33a-e96d-39f25e025d81'")
    sys.exit(1)

uri = sys.argv[1]
uuid = sys.argv[2]

print("Escape character is ^]")
logging.basicConfig(filename='msg.log', level=logging.DEBUG)
logging.info("URI: %s", uri)
logging.info("UUID: %s", uuid)

libvirt.virEventRegisterDefaultImpl()
libvirt.registerErrorHandler(error_handler, None)

atexit.register(reset_term)
attrs = termios.tcgetattr(0)
tty.setraw(0)

console = Console(uri, uuid)
console.stdin_watch = libvirt.virEventAddHandle(0, libvirt.VIR_EVENT_HANDLE_READABLE, stdin_callback, console)

while check_console(console):
    libvirt.virEventRunDefaultImpl()
예제 #36
0
    def event_run():

        if libvirt is not None: libvirt.virEventRunDefaultImpl()
예제 #37
0
 def event_loop_execution():
     while self.LIBVIRT_CONNECTION._o and self.LIBVIRT_CONNECTION.isAlive(
     ):
         libvirt.virEventRunDefaultImpl()
예제 #38
0
def virEventLoopNativeRun(stop):
    while stop[0] is False:
        libvirt.virEventRunDefaultImpl()
예제 #39
0
 def _native_thread(self):
     """Do not use LOG here!"""
     print("In native thread %s" % native_threading._get_ident())
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #40
0
 def run(self):
     while True:
         # if this method will fail it raises libvirtError
         # we do not catch the exception here so it will show up
         # in the logs. Not sure when this call will ever fail
         libvirt.virEventRunDefaultImpl()
예제 #41
0
파일: events.py 프로젝트: stattin42/freenas
 def event_loop_execution():
     while libvirt_connection._o and libvirt_connection.isAlive():
         libvirt.virEventRunDefaultImpl()
예제 #42
0
def efunc(conn):
    conn.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
                                foo, None)
    while True:
        libvirt.virEventRunDefaultImpl()
        eventlet.sleep(0)
예제 #43
0
def _event_loop_run():
    while True:
        libvirt.virEventRunDefaultImpl()
예제 #44
0
def virEventLoopNativeRun(stop):
    while stop[0] is False:
        libvirt.virEventRunDefaultImpl()
예제 #45
0
def run_native_event_loop():
    """Runs native libvirt event loop"""

    while True:
        libvirt.virEventRunDefaultImpl()
예제 #46
0
def loop_run():
    global looping
    while looping:
        libvirt.virEventRunDefaultImpl()

    return 0
예제 #47
0
def loop_run():
    global looping
    while looping:
        libvirt.virEventRunDefaultImpl()

    return 0
예제 #48
0
 def __virEventLoopNativeRun(self):
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #49
0
 def _event_loop():
     while not is_listening:
         libvirt.virEventRunDefaultImpl()
예제 #50
0
 def _event_loop_run(self):
     while True:
         if libvirt.virEventRunDefaultImpl() < 0:
             raise OperationFailed('KCHEVENT0003E')
예제 #51
0
 def run(self):
     while not self._terminated.is_set():
         libvirt.virEventRunDefaultImpl()
예제 #52
0
 def runVirEventLoop():
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #53
0
 def _vir_event_loop_native_run(self):
     # Directly run the event loop in the current thread
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #54
0
파일: event_hook.py 프로젝트: vhnuuh/pyutil
 def loop():
     while True:
         libvirt.virEventRunDefaultImpl()
예제 #55
0
def run_native_event_loop():
    """Runs native libvirt event loop"""

    while True:
        libvirt.virEventRunDefaultImpl()