1
0
mirror of https://gitlab.com/libvirt/libvirt-python.git synced 2025-07-28 15:41:52 +03:00

event-test.py: Fix blanks

Closer to pep8

Signed-off-by: Philipp Hahn <hahn@univention.de>
This commit is contained in:
Philipp Hahn
2018-09-21 15:35:17 +02:00
committed by Michal Privoznik
parent 10ba71a0a0
commit 9dff88056c

View File

@ -30,11 +30,14 @@ import threading
event_impl = "poll" event_impl = "poll"
do_debug = False do_debug = False
def debug(msg): def debug(msg):
global do_debug global do_debug
if do_debug: if do_debug:
print(msg) print(msg)
# #
# This general purpose event loop will support waiting for file handle # This general purpose event loop will support waiting for file handle
# I/O and errors events, as well as scheduling repeatable timers with # I/O and errors events, as well as scheduling repeatable timers with
@ -100,7 +103,6 @@ class virEventLoopPoll:
self.cb(self.timer, self.cb(self.timer,
self.opaque) self.opaque)
def __init__(self): def __init__(self):
self.poll = select.poll() self.poll = select.poll()
self.pipetrick = os.pipe() self.pipetrick = os.pipe()
@ -126,10 +128,9 @@ class virEventLoopPoll:
# with the event loop for input events. When we need to force # with the event loop for input events. When we need to force
# the main thread out of a poll() sleep, we simple write a # the main thread out of a poll() sleep, we simple write a
# single byte of data to the other end of the pipe. # single byte of data to the other end of the pipe.
debug("Self pipe watch %d write %d" %(self.pipetrick[0], self.pipetrick[1])) debug("Self pipe watch %d write %d" % (self.pipetrick[0], self.pipetrick[1]))
self.poll.register(self.pipetrick[0], select.POLLIN) self.poll.register(self.pipetrick[0], select.POLLIN)
# Calculate when the next timeout is due to occur, returning # Calculate when the next timeout is due to occur, returning
# the absolute timestamp for the next timeout, or 0 if there is # the absolute timestamp for the next timeout, or 0 if there is
# no timeout due # no timeout due
@ -159,7 +160,6 @@ class virEventLoopPoll:
return h return h
return None return None
# This is the heart of the event loop, performing one single # This is the heart of the event loop, performing one single
# iteration. It asks when the next timeout is due, and then # iteration. It asks when the next timeout is due, and then
# calculates the maximum amount of time it is able to sleep # calculates the maximum amount of time it is able to sleep
@ -235,7 +235,6 @@ class virEventLoopPoll:
finally: finally:
self.runningPoll = False self.runningPoll = False
# Actually run the event loop forever # Actually run the event loop forever
def run_loop(self): def run_loop(self):
self.quit = False self.quit = False
@ -247,7 +246,6 @@ class virEventLoopPoll:
self.pendingWakeup = True self.pendingWakeup = True
os.write(self.pipetrick[1], 'c'.encode("UTF-8")) os.write(self.pipetrick[1], 'c'.encode("UTF-8"))
# Registers a new file handle 'fd', monitoring for 'events' (libvirt # Registers a new file handle 'fd', monitoring for 'events' (libvirt
# event constants), firing the callback cb() when an event occurs. # event constants), firing the callback cb() when an event occurs.
# Returns a unique integer identier for this handle, that should be # Returns a unique integer identier for this handle, that should be
@ -301,7 +299,7 @@ class virEventLoopPoll:
h.set_interval(interval) h.set_interval(interval)
self.interrupt() self.interrupt()
debug("Update timer %d interval %d" % (timerID, interval)) debug("Update timer %d interval %d" % (timerID, interval))
break break
# Stop monitoring for events on the file handle # Stop monitoring for events on the file handle
@ -383,26 +381,32 @@ def virEventAddHandleImpl(fd, events, cb, opaque):
global eventLoop global eventLoop
return eventLoop.add_handle(fd, events, cb, opaque) return eventLoop.add_handle(fd, events, cb, opaque)
def virEventUpdateHandleImpl(handleID, events): def virEventUpdateHandleImpl(handleID, events):
global eventLoop global eventLoop
return eventLoop.update_handle(handleID, events) return eventLoop.update_handle(handleID, events)
def virEventRemoveHandleImpl(handleID): def virEventRemoveHandleImpl(handleID):
global eventLoop global eventLoop
return eventLoop.remove_handle(handleID) return eventLoop.remove_handle(handleID)
def virEventAddTimerImpl(interval, cb, opaque): def virEventAddTimerImpl(interval, cb, opaque):
global eventLoop global eventLoop
return eventLoop.add_timer(interval, cb, opaque) return eventLoop.add_timer(interval, cb, opaque)
def virEventUpdateTimerImpl(timerID, interval): def virEventUpdateTimerImpl(timerID, interval):
global eventLoop global eventLoop
return eventLoop.update_timer(timerID, interval) return eventLoop.update_timer(timerID, interval)
def virEventRemoveTimerImpl(timerID): def virEventRemoveTimerImpl(timerID):
global eventLoop global eventLoop
return eventLoop.remove_timer(timerID) return eventLoop.remove_timer(timerID)
# This tells libvirt what event loop implementation it # This tells libvirt what event loop implementation it
# should use # should use
def virEventLoopPollRegister(): def virEventLoopPollRegister():
@ -413,20 +417,24 @@ def virEventLoopPollRegister():
virEventUpdateTimerImpl, virEventUpdateTimerImpl,
virEventRemoveTimerImpl) virEventRemoveTimerImpl)
# Directly run the event loop in the current thread # Directly run the event loop in the current thread
def virEventLoopPollRun(): def virEventLoopPollRun():
global eventLoop global eventLoop
eventLoop.run_loop() eventLoop.run_loop()
def virEventLoopAIORun(loop): def virEventLoopAIORun(loop):
import asyncio import asyncio
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
loop.run_forever() loop.run_forever()
def virEventLoopNativeRun(): def virEventLoopNativeRun():
while True: while True:
libvirt.virEventRunDefaultImpl() libvirt.virEventRunDefaultImpl()
# Spawn a background thread to run the event loop # Spawn a background thread to run the event loop
def virEventLoopPollStart(): def virEventLoopPollStart():
global eventLoopThread global eventLoopThread
@ -435,6 +443,7 @@ def virEventLoopPollStart():
eventLoopThread.setDaemon(True) eventLoopThread.setDaemon(True)
eventLoopThread.start() eventLoopThread.start()
def virEventLoopAIOStart(): def virEventLoopAIOStart():
global eventLoopThread global eventLoopThread
import libvirtaio import libvirtaio
@ -445,6 +454,7 @@ def virEventLoopAIOStart():
eventLoopThread.setDaemon(True) eventLoopThread.setDaemon(True)
eventLoopThread.start() eventLoopThread.start()
def virEventLoopNativeStart(): def virEventLoopNativeStart():
global eventLoopThread global eventLoopThread
libvirt.virEventRegisterDefaultImpl() libvirt.virEventRegisterDefaultImpl()
@ -509,10 +519,13 @@ def myDomainEventCallback(conn, dom, event, detail, opaque):
def myDomainEventRebootCallback(conn, dom, opaque): def myDomainEventRebootCallback(conn, dom, opaque):
print("myDomainEventRebootCallback: Domain %s(%s)" % (dom.name(), dom.ID())) print("myDomainEventRebootCallback: Domain %s(%s)" % (
dom.name(), dom.ID()))
def myDomainEventRTCChangeCallback(conn, dom, utcoffset, opaque): def myDomainEventRTCChangeCallback(conn, dom, utcoffset, opaque):
print("myDomainEventRTCChangeCallback: Domain %s(%s) %d" % (dom.name(), dom.ID(), utcoffset)) print("myDomainEventRTCChangeCallback: Domain %s(%s) %d" % (
dom.name(), dom.ID(), utcoffset))
def myDomainEventWatchdogCallback(conn, dom, action, opaque): def myDomainEventWatchdogCallback(conn, dom, action, opaque):
@ -521,7 +534,8 @@ def myDomainEventWatchdogCallback(conn, dom, action, opaque):
def myDomainEventIOErrorCallback(conn, dom, srcpath, devalias, action, opaque): def myDomainEventIOErrorCallback(conn, dom, srcpath, devalias, action, opaque):
print("myDomainEventIOErrorCallback: Domain %s(%s) %s %s %d" % (dom.name(), dom.ID(), srcpath, devalias, action)) print("myDomainEventIOErrorCallback: Domain %s(%s) %s %s %d" % (
dom.name(), dom.ID(), srcpath, devalias, action))
def myDomainEventIOErrorReasonCallback(conn, dom, srcpath, devalias, action, reason, opaque): def myDomainEventIOErrorReasonCallback(conn, dom, srcpath, devalias, action, reason, opaque):
@ -535,7 +549,8 @@ def myDomainEventGraphicsCallback(conn, dom, phase, localAddr, remoteAddr, authS
def myDomainEventControlErrorCallback(conn, dom, opaque): def myDomainEventControlErrorCallback(conn, dom, opaque):
print("myDomainEventControlErrorCallback: Domain %s(%s)" % (dom.name(), dom.ID())) print("myDomainEventControlErrorCallback: Domain %s(%s)" % (
dom.name(), dom.ID()))
def myDomainEventBlockJobCallback(conn, dom, disk, type, status, opaque): def myDomainEventBlockJobCallback(conn, dom, disk, type, status, opaque):
@ -555,18 +570,27 @@ def myDomainEventTrayChangeCallback(conn, dom, devAlias, reason, opaque):
def myDomainEventPMWakeupCallback(conn, dom, reason, opaque): def myDomainEventPMWakeupCallback(conn, dom, reason, opaque):
print("myDomainEventPMWakeupCallback: Domain %s(%s) system pmwakeup" % ( print("myDomainEventPMWakeupCallback: Domain %s(%s) system pmwakeup" % (
dom.name(), dom.ID())) dom.name(), dom.ID()))
def myDomainEventPMSuspendCallback(conn, dom, reason, opaque): def myDomainEventPMSuspendCallback(conn, dom, reason, opaque):
print("myDomainEventPMSuspendCallback: Domain %s(%s) system pmsuspend" % ( print("myDomainEventPMSuspendCallback: Domain %s(%s) system pmsuspend" % (
dom.name(), dom.ID())) dom.name(), dom.ID()))
def myDomainEventBalloonChangeCallback(conn, dom, actual, opaque): def myDomainEventBalloonChangeCallback(conn, dom, actual, opaque):
print("myDomainEventBalloonChangeCallback: Domain %s(%s) %d" % (dom.name(), dom.ID(), actual)) print("myDomainEventBalloonChangeCallback: Domain %s(%s) %d" % (
dom.name(), dom.ID(), actual))
def myDomainEventPMSuspendDiskCallback(conn, dom, reason, opaque): def myDomainEventPMSuspendDiskCallback(conn, dom, reason, opaque):
print("myDomainEventPMSuspendDiskCallback: Domain %s(%s) system pmsuspend_disk" % ( print("myDomainEventPMSuspendDiskCallback: Domain %s(%s) system pmsuspend_disk" % (
dom.name(), dom.ID())) dom.name(), dom.ID()))
def myDomainEventDeviceRemovedCallback(conn, dom, dev, opaque): def myDomainEventDeviceRemovedCallback(conn, dom, dev, opaque):
print("myDomainEventDeviceRemovedCallback: Domain %s(%s) device removed: %s" % ( print("myDomainEventDeviceRemovedCallback: Domain %s(%s) device removed: %s" % (
dom.name(), dom.ID(), dev)) dom.name(), dom.ID(), dev))
def myDomainEventBlockJob2Callback(conn, dom, disk, type, status, opaque): def myDomainEventBlockJob2Callback(conn, dom, disk, type, status, opaque):
@ -575,7 +599,8 @@ def myDomainEventBlockJob2Callback(conn, dom, disk, type, status, opaque):
def myDomainEventTunableCallback(conn, dom, params, opaque): def myDomainEventTunableCallback(conn, dom, params, opaque):
print("myDomainEventTunableCallback: Domain %s(%s) %s" % (dom.name(), dom.ID(), params)) print("myDomainEventTunableCallback: Domain %s(%s) %s" % (
dom.name(), dom.ID(), params))
def myDomainEventAgentLifecycleCallback(conn, dom, state, reason, opaque): def myDomainEventAgentLifecycleCallback(conn, dom, state, reason, opaque):
@ -585,21 +610,33 @@ def myDomainEventAgentLifecycleCallback(conn, dom, state, reason, opaque):
def myDomainEventDeviceAddedCallback(conn, dom, dev, opaque): def myDomainEventDeviceAddedCallback(conn, dom, dev, opaque):
print("myDomainEventDeviceAddedCallback: Domain %s(%s) device added: %s" % ( print("myDomainEventDeviceAddedCallback: Domain %s(%s) device added: %s" % (
dom.name(), dom.ID(), dev)) dom.name(), dom.ID(), dev))
def myDomainEventMigrationIteration(conn, dom, iteration, opaque): def myDomainEventMigrationIteration(conn, dom, iteration, opaque):
print("myDomainEventMigrationIteration: Domain %s(%s) started migration iteration %d" % ( print("myDomainEventMigrationIteration: Domain %s(%s) started migration iteration %d" % (
dom.name(), dom.ID(), iteration)) dom.name(), dom.ID(), iteration))
def myDomainEventJobCompletedCallback(conn, dom, params, opaque): def myDomainEventJobCompletedCallback(conn, dom, params, opaque):
print("myDomainEventJobCompletedCallback: Domain %s(%s) %s" % (dom.name(), dom.ID(), params)) print("myDomainEventJobCompletedCallback: Domain %s(%s) %s" % (
dom.name(), dom.ID(), params))
def myDomainEventDeviceRemovalFailedCallback(conn, dom, dev, opaque): def myDomainEventDeviceRemovalFailedCallback(conn, dom, dev, opaque):
print("myDomainEventDeviceRemovalFailedCallback: Domain %s(%s) failed to remove device: %s" % ( print("myDomainEventDeviceRemovalFailedCallback: Domain %s(%s) failed to remove device: %s" % (
dom.name(), dom.ID(), dev)) dom.name(), dom.ID(), dev))
def myDomainEventMetadataChangeCallback(conn, dom, mtype, nsuri, opaque): def myDomainEventMetadataChangeCallback(conn, dom, mtype, nsuri, opaque):
print("myDomainEventMetadataChangeCallback: Domain %s(%s) changed metadata mtype=%d nsuri=%s" % ( print("myDomainEventMetadataChangeCallback: Domain %s(%s) changed metadata mtype=%d nsuri=%s" % (
dom.name(), dom.ID(), mtype, nsuri)) dom.name(), dom.ID(), mtype, nsuri))
def myDomainEventBlockThresholdCallback(conn, dom, dev, path, threshold, excess, opaque): def myDomainEventBlockThresholdCallback(conn, dom, dev, path, threshold, excess, opaque):
print("myDomainEventBlockThresholdCallback: Domain %s(%s) block device %s(%s) threshold %d exceeded by %d" % ( print("myDomainEventBlockThresholdCallback: Domain %s(%s) block device %s(%s) threshold %d exceeded by %d" % (
dom.name(), dom.ID(), dev, path, threshold, excess)) dom.name(), dom.ID(), dev, path, threshold, excess))
########################################################################## ##########################################################################
# Network events # Network events
@ -638,6 +675,7 @@ def myStoragePoolEventLifecycleCallback(conn, pool, event, detail, opaque):
def myStoragePoolEventRefreshCallback(conn, pool, opaque): def myStoragePoolEventRefreshCallback(conn, pool, opaque):
print("myStoragePoolEventRefreshCallback: Storage pool %s" % pool.name()) print("myStoragePoolEventRefreshCallback: Storage pool %s" % pool.name())
########################################################################## ##########################################################################
# Node device events # Node device events
########################################################################## ##########################################################################
@ -655,6 +693,7 @@ def myNodeDeviceEventLifecycleCallback(conn, dev, event, detail, opaque):
def myNodeDeviceEventUpdateCallback(conn, dev, opaque): def myNodeDeviceEventUpdateCallback(conn, dev, opaque):
print("myNodeDeviceEventUpdateCallback: Node device %s" % dev.name()) print("myNodeDeviceEventUpdateCallback: Node device %s" % dev.name())
########################################################################## ##########################################################################
# Secret events # Secret events
########################################################################## ##########################################################################
@ -672,6 +711,7 @@ def mySecretEventLifecycleCallback(conn, secret, event, detail, opaque):
def mySecretEventValueChanged(conn, secret, opaque): def mySecretEventValueChanged(conn, secret, opaque):
print("mySecretEventValueChanged: Secret %s" % secret.UUIDString()) print("mySecretEventValueChanged: Secret %s" % secret.UUIDString())
########################################################################## ##########################################################################
# Set up and run the program # Set up and run the program
########################################################################## ##########################################################################
@ -695,12 +735,13 @@ def usage():
print(" --loop=TYPE, -l Choose event-loop-implementation (native, poll, asyncio)") print(" --loop=TYPE, -l Choose event-loop-implementation (native, poll, asyncio)")
print(" --timeout=SECS Quit after SECS seconds running") print(" --timeout=SECS Quit after SECS seconds running")
def main(): def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "hdl:", ["help", "debug", "loop=", "timeout="]) opts, args = getopt.getopt(sys.argv[1:], "hdl:", ["help", "debug", "loop=", "timeout="])
except getopt.GetoptError as err: except getopt.GetoptError as err:
# print help information and exit: # print help information and exit:
print(str(err)) # will print something like "option -a not recognized" print(str(err)) # will print something like "option -a not recognized"
usage() usage()
sys.exit(2) sys.exit(2)
timeout = None timeout = None
@ -736,16 +777,19 @@ def main():
# Close connection on exit (to test cleanup paths) # Close connection on exit (to test cleanup paths)
old_exitfunc = getattr(sys, 'exitfunc', None) old_exitfunc = getattr(sys, 'exitfunc', None)
def exit(): def exit():
print("Closing " + vc.getURI()) print("Closing " + vc.getURI())
if run: if run:
vc.close() vc.close()
if (old_exitfunc): old_exitfunc() if (old_exitfunc):
old_exitfunc()
sys.exitfunc = exit sys.exitfunc = exit
vc.registerCloseCallback(myConnectionCloseCallback, None) vc.registerCloseCallback(myConnectionCloseCallback, None)
#Add 2 lifecycle callbacks to prove this works with more than just one # Add 2 lifecycle callbacks to prove this works with more than just one
vc.domainEventRegister(myDomainEventCallback, 1) vc.domainEventRegister(myDomainEventCallback, 1)
domcallbacks = [ domcallbacks = [
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, myDomainEventCallback, 2), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, myDomainEventCallback, 2),
@ -829,5 +873,6 @@ def main():
# Allow delayed event loop cleanup to run, just for sake of testing # Allow delayed event loop cleanup to run, just for sake of testing
time.sleep(2) time.sleep(2)
if __name__ == "__main__": if __name__ == "__main__":
main() main()