Debian Codegraph @

examples/event-test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 #
4 #
5 ##############################################################################
6 # Start off by implementing a general purpose event loop for anyone's use
7 ##############################################################################
8
9 import atexit
10 import os
11 import libvirt
12 import select
13 import errno
14 import time
15 import threading
16 from argparse import ArgumentParser
17 from typing import Any, Callable, Optional, TypeVar # noqa F401
18 _T = TypeVar("_T")
19 _EventCallback = Callable[[int, int, int, _T], None]
20 _TimerCallback = Callable[[int, _T], None]
21
22
23 # This example can use three different event loop impls. It defaults
24 # to a portable pure-python impl based on poll that is implemented
25 # in this file.
26 #
27 # When Python >= 3.4, it can optionally use an impl based on the
28 # new asyncio module.
29 #
30 # Finally, it can also use the libvirt native event loop impl
31 #
32 # This setting thus allows 'poll', 'native' or 'asyncio' as valid
33 # choices
34 #
35 event_impl = "poll"
36
37 do_debug = False
38
39
40 def debug(msg: str) -> None:
41 if do_debug:
42 print(msg)
43
44
45 #
46 # This general purpose event loop will support waiting for file handle
47 # I/O and errors events, as well as scheduling repeatable timers with
48 # a fixed interval.
49 #
50 # It is a pure python implementation based around the poll() API
51 #
52 class virEventLoopPoll:
53 # This class contains the data we need to track for a
54 # single file handle
55 class virEventLoopPollHandle:
56 def __init__(self, handle: int, fd: int, events: int, cb: _EventCallback, opaque: _T):
57 self.handle = handle
58 self.fd = fd
59 self.events = events
60 self.cb = cb
61 self.opaque = opaque
62
63 def get_id(self) -> int:
64 return self.handle
65
66 def get_fd(self) -> int:
67 return self.fd
68
69 def get_events(self) -> int:
70 return self.events
71
72 def set_events(self, events: int):
73 self.events = events
74
75 def dispatch(self, events: int):
76 self.cb(self.handle,
77 self.fd,
78 events,
79 self.opaque)
80
81 # This class contains the data we need to track for a
82 # single periodic timer
83 class virEventLoopPollTimer:
84 def __init__(self, timer: int, interval: int, cb: _TimerCallback, opaque: _T):
85 self.timer = timer
86 self.interval = interval
87 self.cb = cb
88 self.opaque = opaque
89 self.lastfired = 0
90
91 def get_id(self) -> int:
92 return self.timer
93
94 def get_interval(self) -> int:
95 return self.interval
96
97 def set_interval(self, interval: int):
98 self.interval = interval
99
100 def get_last_fired(self) -> int:
101 return self.lastfired
102
103 def set_last_fired(self, now: int):
104 self.lastfired = now
105
106 def dispatch(self) -> None:
107 self.cb(self.timer,
108 self.opaque)
109
110 def __init__(self):
111 self.poll = select.poll()
112 self.pipetrick = os.pipe()
113 self.pendingWakeup = False
114 self.runningPoll = False
115 self.nextHandleID = 1
116 self.nextTimerID = 1
117 self.handles = [] # type: list[virEventLoopPollHandle]
118 self.timers = [] # type: list[virEventLoopPollTimer]
119 self.cleanup = []
120 self.quit = False
121
122 # The event loop can be used from multiple threads at once.
123 # Specifically while the main thread is sleeping in poll()
124 # waiting for events to occur, another thread may come along
125 # and add/update/remove a file handle, or timer. When this
126 # happens we need to interrupt the poll() sleep in the other
127 # thread, so that it'll see the file handle / timer changes.
128 #
129 # Using OS level signals for this is very unreliable and
130 # hard to implement correctly. Thus we use the real classic
131 # "self pipe" trick. A anonymous pipe, with one end registered
132 # with the event loop for input events. When we need to force
133 # the main thread out of a poll() sleep, we simple write a
134 # single byte of data to the other end of the pipe.
135 debug("Self pipe watch %d write %d" % (self.pipetrick[0], self.pipetrick[1]))
136 self.poll.register(self.pipetrick[0], select.POLLIN)
137
138 # Calculate when the next timeout is due to occur, returning
139 # the absolute timestamp for the next timeout, or 0 if there is
140 # no timeout due
141 def next_timeout(self) -> int:
142 next = 0
143 for t in self.timers:
144 last = t.get_last_fired()
145 interval = t.get_interval()
146 if interval < 0:
147 continue
148 if next == 0 or (last + interval) < next:
149 next = last + interval
150
151 return next
152
153 # Lookup a virEventLoopPollHandle object based on file descriptor
154 def get_handle_by_fd(self, fd: int) -> Optional[virEventLoopPollHandle]:
155 for h in self.handles:
156 if h.get_fd() == fd:
157 return h
158 return None
159
160 # Lookup a virEventLoopPollHandle object based on its event loop ID
161 def get_handle_by_id(self, handleID: int) -> Optional[virEventLoopPollHandle]:
162 for h in self.handles:
163 if h.get_id() == handleID:
164 return h
165 return None
166
167 # This is the heart of the event loop, performing one single
168 # iteration. It asks when the next timeout is due, and then
169 # calculates the maximum amount of time it is able to sleep
170 # for in poll() pending file handle events.
171 #
172 # It then goes into the poll() sleep.
173 #
174 # When poll() returns, there will zero or more file handle
175 # events which need to be dispatched to registered callbacks
176 # It may also be time to fire some periodic timers.
177 #
178 # Due to the coarse granularity of scheduler timeslices, if
179 # we ask for a sleep of 500ms in order to satisfy a timer, we
180 # may return up to 1 scheduler timeslice early. So even though
181 # our sleep timeout was reached, the registered timer may not
182 # technically be at its expiry point. This leads to us going
183 # back around the loop with a crazy 5ms sleep. So when checking
184 # if timeouts are due, we allow a margin of 20ms, to avoid
185 # these pointless repeated tiny sleeps.
186 def run_once(self) -> None:
187 sleep = -1 # type: float
188 self.runningPoll = True
189
190 for opaque in self.cleanup:
191 libvirt.virEventInvokeFreeCallback(opaque)
192 self.cleanup = []
193
194 try:
195 next = self.next_timeout()
196 debug("Next timeout due at %d" % next)
197 if next > 0:
198 now = int(time.time() * 1000)
199 if now >= next:
200 sleep = 0
201 else:
202 sleep = (next - now) / 1000.0
203
204 debug("Poll with a sleep of %d" % sleep)
205 events = self.poll.poll(sleep)
206
207 # Dispatch any file handle events that occurred
208 for (fd, revents) in events:
209 # See if the events was from the self-pipe
210 # telling us to wakup. if so, then discard
211 # the data just continue
212 if fd == self.pipetrick[0]:
213 self.pendingWakeup = False
214 os.read(fd, 1)
215 continue
216
217 h = self.get_handle_by_fd(fd)
218 if h:
219 debug("Dispatch fd %d handle %d events %d" % (fd, h.get_id(), revents))
220 h.dispatch(self.events_from_poll(revents))
221
222 now = int(time.time() * 1000)
223 for t in self.timers:
224 interval = t.get_interval()
225 if interval < 0:
226 continue
227
228 want = t.get_last_fired() + interval
229 # Deduct 20ms, since scheduler timeslice
230 # means we could be ever so slightly early
231 if now >= want - 20:
232 debug("Dispatch timer %d now %s want %s" % (t.get_id(), str(now), str(want)))
233 t.set_last_fired(now)
234 t.dispatch()
235
236 except (os.error, select.error) as e:
237 if e.args[0] != errno.EINTR:
238 raise
239 finally:
240 self.runningPoll = False
241
242 # Actually run the event loop forever
243 def run_loop(self) -> None:
244 self.quit = False
245 while not self.quit:
246 self.run_once()
247
248 def interrupt(self) -> None:
249 if self.runningPoll and not self.pendingWakeup:
250 self.pendingWakeup = True
251 os.write(self.pipetrick[1], 'c'.encode("UTF-8"))
252
253 # Registers a new file handle 'fd', monitoring for 'events' (libvirt
254 # event constants), firing the callback cb() when an event occurs.
255 # Returns a unique integer identier for this handle, that should be
256 # used to later update/remove it
257 def add_handle(self, fd: int, events: int, cb: _EventCallback, opaque: _T) -> int:
258 handleID = self.nextHandleID + 1
259 self.nextHandleID = self.nextHandleID + 1
260
261 h = self.virEventLoopPollHandle(handleID, fd, events, cb, opaque)
262 self.handles.append(h)
263
264 self.poll.register(fd, self.events_to_poll(events))
265 self.interrupt()
266
267 debug("Add handle %d fd %d events %d" % (handleID, fd, events))
268
269 return handleID
270
271 # Registers a new timer with periodic expiry at 'interval' ms,
272 # firing cb() each time the timer expires. If 'interval' is -1,
273 # then the timer is registered, but not enabled
274 # Returns a unique integer identier for this handle, that should be
275 # used to later update/remove it
276 def add_timer(self, interval: int, cb: _TimerCallback, opaque: _T) -> int:
277 timerID = self.nextTimerID + 1
278 self.nextTimerID = self.nextTimerID + 1
279
280 h = self.virEventLoopPollTimer(timerID, interval, cb, opaque)
281 self.timers.append(h)
282 self.interrupt()
283
284 debug("Add timer %d interval %d" % (timerID, interval))
285
286 return timerID
287
288 # Change the set of events to be monitored on the file handle
289 def update_handle(self, handleID: int, events: int) -> None:
290 h = self.get_handle_by_id(handleID)
291 if h:
292 h.set_events(events)
293 self.poll.unregister(h.get_fd())
294 self.poll.register(h.get_fd(), self.events_to_poll(events))
295 self.interrupt()
296
297 debug("Update handle %d fd %d events %d" % (handleID, h.get_fd(), events))
298
299 # Change the periodic frequency of the timer
300 def update_timer(self, timerID: int, interval: int) -> None:
301 for h in self.timers:
302 if h.get_id() == timerID:
303 h.set_interval(interval)
304 self.interrupt()
305
306 debug("Update timer %d interval %d" % (timerID, interval))
307 break
308
309 # Stop monitoring for events on the file handle
310 def remove_handle(self, handleID: int) -> int:
311 handles = []
312 for h in self.handles:
313 if h.get_id() == handleID:
314 debug("Remove handle %d fd %d" % (handleID, h.get_fd()))
315 self.poll.unregister(h.get_fd())
316 self.cleanup.append(h.opaque)
317 else:
318 handles.append(h)
319 self.handles = handles
320 self.interrupt()
321 return 0
322
323 # Stop firing the periodic timer
324 def remove_timer(self, timerID: int) -> int:
325 timers = []
326 for h in self.timers:
327 if h.get_id() != timerID:
328 timers.append(h)
329 else:
330 debug("Remove timer %d" % timerID)
331 self.cleanup.append(h.opaque)
332 self.timers = timers
333 self.interrupt()
334 return 0
335
336 # Convert from libvirt event constants, to poll() events constants
337 def events_to_poll(self, events: int) -> int:
338 ret = 0
339 if events & libvirt.VIR_EVENT_HANDLE_READABLE:
340 ret |= select.POLLIN
341 if events & libvirt.VIR_EVENT_HANDLE_WRITABLE:
342 ret |= select.POLLOUT
343 if events & libvirt.VIR_EVENT_HANDLE_ERROR:
344 ret |= select.POLLERR
345 if events & libvirt.VIR_EVENT_HANDLE_HANGUP:
346 ret |= select.POLLHUP
347 return ret
348
349 # Convert from poll() event constants, to libvirt events constants
350 def events_from_poll(self, events: int) -> int:
351 ret = 0
352 if events & select.POLLIN:
353 ret |= libvirt.VIR_EVENT_HANDLE_READABLE
354 if events & select.POLLOUT:
355 ret |= libvirt.VIR_EVENT_HANDLE_WRITABLE
356 if events & select.POLLNVAL:
357 ret |= libvirt.VIR_EVENT_HANDLE_ERROR
358 if events & select.POLLERR:
359 ret |= libvirt.VIR_EVENT_HANDLE_ERROR
360 if events & select.POLLHUP:
361 ret |= libvirt.VIR_EVENT_HANDLE_HANGUP
362 return ret
363
364
365 ###########################################################################
366 # Now glue an instance of the general event loop into libvirt's event loop
367 ###########################################################################
368
369 # This single global instance of the event loop wil be used for
370 # monitoring libvirt events
371 eventLoop = virEventLoopPoll()
372
373 # This keeps track of what thread is running the event loop,
374 # (if it is run in a background thread)
375 eventLoopThread = None
376
377
378 # These next set of 6 methods are the glue between the official
379 # libvirt events API, and our particular impl of the event loop
380 #
381 # There is no reason why the 'virEventLoopPoll' has to be used.
382 # An application could easily may these 6 glue methods hook into
383 # another event loop such as GLib's, or something like the python
384 # Twisted event framework.
385
386 def virEventAddHandleImpl(fd: int, events: int, cb: _EventCallback, opaque: _T) -> int:
387 return eventLoop.add_handle(fd, events, cb, opaque)
388
389
390 def virEventUpdateHandleImpl(handleID: int, events: int) -> None:
391 return eventLoop.update_handle(handleID, events)
392
393
394 def virEventRemoveHandleImpl(handleID: int) -> int:
395 return eventLoop.remove_handle(handleID)
396
397
398 def virEventAddTimerImpl(interval: int, cb: _TimerCallback, opaque: _T) -> int:
399 return eventLoop.add_timer(interval, cb, opaque)
400
401
402 def virEventUpdateTimerImpl(timerID: int, interval: int) -> None:
403 return eventLoop.update_timer(timerID, interval)
404
405
406 def virEventRemoveTimerImpl(timerID: int) -> int:
407 return eventLoop.remove_timer(timerID)
408
409
410 # This tells libvirt what event loop implementation it
411 # should use
412 def virEventLoopPollRegister() -> None:
413 libvirt.virEventRegisterImpl(virEventAddHandleImpl,
414 virEventUpdateHandleImpl,
415 virEventRemoveHandleImpl,
416 virEventAddTimerImpl,
417 virEventUpdateTimerImpl,
418 virEventRemoveTimerImpl)
419
420
421 # Directly run the event loop in the current thread
422 def virEventLoopPollRun() -> None:
423 eventLoop.run_loop()
424
425
426 def virEventLoopAIORun(loop) -> None:
427 import asyncio
428 asyncio.set_event_loop(loop)
429 loop.run_forever()
430
431
432 def virEventLoopNativeRun() -> None:
433 while True:
434 libvirt.virEventRunDefaultImpl()
435
436
437 # Spawn a background thread to run the event loop
438 def virEventLoopPollStart() -> None:
439 global eventLoopThread
440 virEventLoopPollRegister()
441 eventLoopThread = threading.Thread(target=virEventLoopPollRun,
442 name="libvirtEventLoop",
443 daemon=True)
444 eventLoopThread.start()
445
446
447 def virEventLoopAIOStart() -> None:
448 global eventLoopThread
449 import libvirtaio
450 import asyncio
451 loop = asyncio.new_event_loop()
452 libvirtaio.virEventRegisterAsyncIOImpl(loop=loop)
453 eventLoopThread = threading.Thread(target=virEventLoopAIORun,
454 args=(loop,),
455 name="libvirtEventLoop",
456 daemon=True)
457 eventLoopThread.start()
458
459
460 def virEventLoopNativeStart() -> None:
461 global eventLoopThread
462 libvirt.virEventRegisterDefaultImpl()
463 eventLoopThread = threading.Thread(target=virEventLoopNativeRun,
464 name="libvirtEventLoop",
465 daemon=True)
466 eventLoopThread.start()
467
468
469 ##########################################################################
470 # Everything that now follows is a simple demo of domain lifecycle events
471 ##########################################################################
472 class Description(object):
473 __slots__ = ('desc', 'args')
474
475 def __init__(self, *args, **kwargs) -> None:
476 self.desc = kwargs.get('desc')
477 self.args = args
478
479 def __str__(self) -> str:
480 return self.desc or ''
481
482 def __getitem__(self, item: int) -> 'Description':
483 try:
484 data = self.args[item]
485 except IndexError:
486 return self.__class__(desc=str(item))
487
488 if isinstance(data, str):
489 return self.__class__(desc=data)
490 elif isinstance(data, (list, tuple)):
491 desc, args = data
492 return self.__class__(*args, desc=desc)
493
494 raise TypeError(args)
495
496
497 DOM_EVENTS = Description(
498 ("Defined", ("Added", "Updated", "Renamed", "Snapshot")),
499 ("Undefined", ("Removed", "Renamed")),
500 ("Started", ("Booted", "Migrated", "Restored", "Snapshot", "Wakeup")),
501 ("Suspended", ("Paused", "Migrated", "IOError", "Watchdog", "Restored", "Snapshot", "API error", "Postcopy", "Postcopy failed")),
502 ("Resumed", ("Unpaused", "Migrated", "Snapshot", "Postcopy")),
503 ("Stopped", ("Shutdown", "Destroyed", "Crashed", "Migrated", "Saved", "Failed", "Snapshot", "Daemon")),
504 ("Shutdown", ("Finished", "On guest request", "On host request")),
505 ("PMSuspended", ("Memory", "Disk")),
506 ("Crashed", ("Panicked",)),
507 )
508 BLOCK_JOB_TYPES = Description("unknown", "Pull", "Copy", "Commit", "ActiveCommit")
509 BLOCK_JOB_STATUS = Description("Completed", "Failed", "Canceled", "Ready")
510 WATCHDOG_ACTIONS = Description("none", "Pause", "Reset", "Poweroff", "Shutdown", "Debug", "Inject NMI")
511 ERROR_EVENTS = Description("None", "Pause", "Report")
512 AGENT_STATES = Description("unknown", "connected", "disconnected")
513 AGENT_REASONS = Description("unknown", "domain started", "channel event")
514 GRAPHICS_PHASES = Description("Connect", "Initialize", "Disconnect")
515 DISK_EVENTS = Description("Change missing on start", "Drop missing on start")
516 TRAY_EVENTS = Description("Opened", "Closed")
517 CHANNEL_STATES = Description("unknown", "connected", "disconnected")
518 CHANNEL_REASONS = Description("unknown", "domain started", "channel event")
519
520
521 def myDomainEventCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, event: int, detail: int, opaque: _T) -> None:
522 print("myDomainEventCallback%s EVENT: Domain %s(%s) %s %s" % (
523 opaque, dom.name(), dom.ID(), DOM_EVENTS[event], DOM_EVENTS[event][detail]))
524
525
526 def myDomainEventRebootCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, opaque: _T) -> None:
527 print("myDomainEventRebootCallback: Domain %s(%s)" % (
528 dom.name(), dom.ID()))
529
530
531 def myDomainEventRTCChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, utcoffset: int, opaque: _T) -> None:
532 print("myDomainEventRTCChangeCallback: Domain %s(%s) %d" % (
533 dom.name(), dom.ID(), utcoffset))
534
535
536 def myDomainEventWatchdogCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, action: int, opaque: _T) -> None:
537 print("myDomainEventWatchdogCallback: Domain %s(%s) %s" % (
538 dom.name(), dom.ID(), WATCHDOG_ACTIONS[action]))
539
540
541 def myDomainEventIOErrorCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, srcpath: str, devalias: str, action: int, opaque: _T) -> None:
542 print("myDomainEventIOErrorCallback: Domain %s(%s) %s %s %s" % (
543 dom.name(), dom.ID(), srcpath, devalias, ERROR_EVENTS[action]))
544
545
546 def myDomainEventIOErrorReasonCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, srcpath: str, devalias: str, action: int, reason: int, opaque: _T) -> None:
547 print("myDomainEventIOErrorReasonCallback: Domain %s(%s) %s %s %s %s" % (
548 dom.name(), dom.ID(), srcpath, devalias, ERROR_EVENTS[action], reason))
549
550
551 def myDomainEventGraphicsCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, phase: int, localAddr: str, remoteAddr: str, authScheme: str, subject: str, opaque: _T) -> None:
552 print("myDomainEventGraphicsCallback: Domain %s(%s) %s %s" % (
553 dom.name(), dom.ID(), GRAPHICS_PHASES[phase], authScheme))
554
555
556 def myDomainEventControlErrorCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, opaque: _T) -> None:
557 print("myDomainEventControlErrorCallback: Domain %s(%s)" % (
558 dom.name(), dom.ID()))
559
560
561 def myDomainEventBlockJobCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, disk, type: int, status: int, opaque: _T) -> None:
562 print("myDomainEventBlockJobCallback: Domain %s(%s) %s on disk %s %s" % (
563 dom.name(), dom.ID(), BLOCK_JOB_TYPES[type], disk, BLOCK_JOB_STATUS[status]))
564
565
566 def myDomainEventDiskChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, oldSrcPath: str, newSrcPath: str, devAlias: str, reason: int, opaque: _T) -> None:
567 print("myDomainEventDiskChangeCallback: Domain %s(%s) disk change oldSrcPath: %s newSrcPath: %s devAlias: %s reason: %s" % (
568 dom.name(), dom.ID(), oldSrcPath, newSrcPath, devAlias, DISK_EVENTS[reason]))
569
570
571 def myDomainEventTrayChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, devAlias: str, reason: int, opaque: _T) -> None:
572 print("myDomainEventTrayChangeCallback: Domain %s(%s) tray change devAlias: %s reason: %s" % (
573 dom.name(), dom.ID(), devAlias, TRAY_EVENTS[reason]))
574
575
576 def myDomainEventPMWakeupCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, reason: int, opaque: _T) -> None:
577 print("myDomainEventPMWakeupCallback: Domain %s(%s) system pmwakeup" % (
578 dom.name(), dom.ID()))
579
580
581 def myDomainEventPMSuspendCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, reason: int, opaque: _T) -> None:
582 print("myDomainEventPMSuspendCallback: Domain %s(%s) system pmsuspend" % (
583 dom.name(), dom.ID()))
584
585
586 def myDomainEventBalloonChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, actual: int, opaque: _T) -> None:
587 print("myDomainEventBalloonChangeCallback: Domain %s(%s) %d" % (
588 dom.name(), dom.ID(), actual))
589
590
591 def myDomainEventPMSuspendDiskCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, reason: int, opaque: _T) -> None:
592 print("myDomainEventPMSuspendDiskCallback: Domain %s(%s) system pmsuspend_disk" % (
593 dom.name(), dom.ID()))
594
595
596 def myDomainEventDeviceRemovedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, opaque: _T) -> None:
597 print("myDomainEventDeviceRemovedCallback: Domain %s(%s) device removed: %s" % (
598 dom.name(), dom.ID(), dev))
599
600
601 def myDomainEventBlockJob2Callback(conn: libvirt.virConnect, dom: libvirt.virDomain, disk: str, type: int, status: int, opaque: _T) -> None:
602 print("myDomainEventBlockJob2Callback: Domain %s(%s) %s on disk %s %s" % (
603 dom.name(), dom.ID(), BLOCK_JOB_TYPES[type], disk, BLOCK_JOB_STATUS[status]))
604
605
606 def myDomainEventTunableCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, params: dict[str, Any], opaque: _T) -> None:
607 print("myDomainEventTunableCallback: Domain %s(%s) %s" % (
608 dom.name(), dom.ID(), params))
609
610
611 def myDomainEventAgentLifecycleCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, state: int, reason: int, opaque: _T) -> None:
612 print("myDomainEventAgentLifecycleCallback: Domain %s(%s) %s %s" % (
613 dom.name(), dom.ID(), AGENT_STATES[state], AGENT_REASONS[reason]))
614
615
616 def myDomainEventDeviceAddedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, opaque: _T) -> None:
617 print("myDomainEventDeviceAddedCallback: Domain %s(%s) device added: %s" % (
618 dom.name(), dom.ID(), dev))
619
620
621 def myDomainEventMigrationIteration(conn: libvirt.virConnect, dom: libvirt.virDomain, iteration: int, opaque: _T) -> None:
622 print("myDomainEventMigrationIteration: Domain %s(%s) started migration iteration %d" % (
623 dom.name(), dom.ID(), iteration))
624
625
626 def myDomainEventJobCompletedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, params: dict[str, Any], opaque: _T) -> None:
627 print("myDomainEventJobCompletedCallback: Domain %s(%s) %s" % (
628 dom.name(), dom.ID(), params))
629
630
631 def myDomainEventDeviceRemovalFailedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, opaque: _T) -> None:
632 print("myDomainEventDeviceRemovalFailedCallback: Domain %s(%s) failed to remove device: %s" % (
633 dom.name(), dom.ID(), dev))
634
635
636 def myDomainEventMetadataChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, mtype: int, nsuri: str, opaque: _T) -> None:
637 print("myDomainEventMetadataChangeCallback: Domain %s(%s) changed metadata mtype=%d nsuri=%s" % (
638 dom.name(), dom.ID(), mtype, nsuri))
639
640
641 def myDomainEventBlockThresholdCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, path: str, threshold: int, excess: int, opaque: _T) -> None:
642 print("myDomainEventBlockThresholdCallback: Domain %s(%s) block device %s(%s) threshold %d exceeded by %d" % (
643 dom.name(), dom.ID(), dev, path, threshold, excess))
644
645 def myDomainEventMemoryFailureCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, recipient: int, action: int, flags: int, opaque: _T) -> None:
646 print("myDomainEventMemoryFailureCallback: Domain %s(%s) memory failure recipient %d action %d flags %d" % (
647 dom.name(), dom.ID(), recipient, action, flags))
648
649 def myDomainEventMemoryDeviceSizeChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, recipient: int, action: int, flags: int, opaque: _T) -> None:
650 print("myDomainEventMemoryDeviceSizeChangeCallback: Domain %s(%s) memory device size change alias %s size %d" % (
651 dom.name(), dom.ID(), alias, size))
652
653 def myDomainEventNICMACChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, alias: str, oldMAC: str, newMAC: str, opaque: _T) -> None:
654 print("myDomainEventNICMACChangeCallback: Domain %s(%s) NIC MAC change alias %s old MAC: %s new MAC: %s" % (
655 dom.name(), dom.ID(), alias, oldMAC, newMAC))
656
657 def myDomainEventVcpuRemovedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, vcpuid: int, opaque: _T) -> None:
658 print("myDomainEventVcpuRemovedCallback: Domain %s(%s) vCPU removed %d" % (
659 dom.name(), dom.ID(), vcpuid))
660
661 def myDomainEventChannelLifecycleCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, state: int, reason: int, opaque: _T) -> None:
662 print("myDomainEventChannelLifecycleCallback: Domain %s(%s) %s %s" % (
663 dom.name(), dom.ID(), CHANNEL_STATES[state], CHANNEL_REASONS[reason]))
664
665
666 ##########################################################################
667 # Network events
668 ##########################################################################
669 NET_EVENTS = Description(
670 ("Defined", ("Added",)),
671 ("Undefined", ("Removed",)),
672 ("Started", ("Started",)),
673 ("Stopped", ("Stopped",)),
674 )
675
676
677 def myNetworkEventLifecycleCallback(conn: libvirt.virConnect, net: libvirt.virNetwork, event: int, detail: int, opaque: _T) -> None:
678 print("myNetworkEventLifecycleCallback: Network %s %s %s" % (
679 net.name(), NET_EVENTS[event], NET_EVENTS[event][detail]))
680
681 def myNetworkEventMetadataChangeCallback(conn: libvirt.virConnect, dom: libvirt.virNetwork, mtype: int, nsuri: str, opaque: _T) -> None:
682 print("myNetworkEventMetadataChangeCallback: Network %s(%s) changed metadata mtype=%d nsuri=%s" % (
683 dom.name(), dom.ID(), mtype, nsuri))
684
685
686 ##########################################################################
687 # Storage pool events
688 ##########################################################################
689 STORAGE_EVENTS = Description(
690 ("Defined", ()),
691 ("Undefined", ()),
692 ("Started", ()),
693 ("Stopped", ()),
694 ("Created", ()),
695 ("Deleted", ()),
696 )
697
698
699 def myStoragePoolEventLifecycleCallback(conn: libvirt.virConnect, pool: libvirt.virStoragePool, event: int, detail: int, opaque: _T) -> None:
700 print("myStoragePoolEventLifecycleCallback: Storage pool %s %s %s" % (
701 pool.name(), STORAGE_EVENTS[event], STORAGE_EVENTS[event][detail]))
702
703
704 def myStoragePoolEventRefreshCallback(conn: libvirt.virConnect, pool: libvirt.virStoragePool, opaque: _T) -> None:
705 print("myStoragePoolEventRefreshCallback: Storage pool %s" % pool.name())
706
707
708 ##########################################################################
709 # Node device events
710 ##########################################################################
711 DEVICE_EVENTS = Description(
712 ("Created", ()),
713 ("Deleted", ()),
714 )
715
716
717 def myNodeDeviceEventLifecycleCallback(conn: libvirt.virConnect, dev: libvirt.virNodeDevice, event: int, detail: int, opaque: _T) -> None:
718 print("myNodeDeviceEventLifecycleCallback: Node device %s %s %s" % (
719 dev.name(), DEVICE_EVENTS[event], DEVICE_EVENTS[event][detail]))
720
721
722 def myNodeDeviceEventUpdateCallback(conn: libvirt.virConnect, dev: libvirt.virNodeDevice, opaque: _T) -> None:
723 print("myNodeDeviceEventUpdateCallback: Node device %s" % dev.name())
724
725
726 ##########################################################################
727 # Secret events
728 ##########################################################################
729 SECRET_EVENTS = Description(
730 ("Defined", ()),
731 ("Undefined", ()),
732 )
733
734
735 def mySecretEventLifecycleCallback(conn: libvirt.virConnect, secret: libvirt.virSecret, event: int, detail: int, opaque: _T) -> None:
736 print("mySecretEventLifecycleCallback: Secret %s %s %s" % (
737 secret.UUIDString(), SECRET_EVENTS[event], SECRET_EVENTS[event][detail]))
738
739
740 def mySecretEventValueChanged(conn: libvirt.virConnect, secret: libvirt.virSecret, opaque: _T) -> None:
741 print("mySecretEventValueChanged: Secret %s" % secret.UUIDString())
742
743
744 ##########################################################################
745 # Set up and run the program
746 ##########################################################################
747
748 run = True
749 CONNECTION_EVENTS = Description("Error", "End-of-file", "Keepalive", "Client")
750
751
752 def myConnectionCloseCallback(conn: libvirt.virConnect, reason: int, opaque: _T) -> None:
753 print("myConnectionCloseCallback: %s: %s" % (
754 conn.getURI(), CONNECTION_EVENTS[reason]))
755 global run
756 run = False
757
758
759 def main() -> None:
760 parser = ArgumentParser()
761 parser.add_argument("--debug", "-d", action="store_true", help="Print debug output")
762 parser.add_argument("--loop", "-l", choices=("native", "poll", "asyncio"), default=event_impl, help="Choose event-loop-implementation")
763 parser.add_argument("--timeout", type=int, default=None, help="Quit after SECS seconds running")
764 parser.add_argument("uri", nargs="?", default="qemu:///system")
765 args = parser.parse_args()
766
767 if args.debug:
768 global do_debug
769 do_debug = True
770
771 print("Using uri '%s' and event loop '%s'" % (args.uri, args.loop))
772
773 # Run a background thread with the event loop
774 if args.loop == "poll":
775 virEventLoopPollStart()
776 elif args.loop == "asyncio":
777 virEventLoopAIOStart()
778 else:
779 virEventLoopNativeStart()
780
781 vc = libvirt.openReadOnly(args.uri)
782
783 # Close connection on exit (to test cleanup paths)
784 def exit() -> None:
785 print("Closing " + vc.getURI())
786 if run:
787 vc.close()
788
789 atexit.register(exit)
790
791 vc.registerCloseCallback(myConnectionCloseCallback, None)
792
793 # Add 2 lifecycle callbacks to prove this works with more than just one
794 vc.domainEventRegister(myDomainEventCallback, 1)
795 domcallbacks = [
796 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, myDomainEventCallback, 2),
797 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_REBOOT, myDomainEventRebootCallback, None),
798 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_RTC_CHANGE, myDomainEventRTCChangeCallback, None),
799 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_WATCHDOG, myDomainEventWatchdogCallback, None),
800 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR, myDomainEventIOErrorCallback, None),
801 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_GRAPHICS, myDomainEventGraphicsCallback, None),
802 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON, myDomainEventIOErrorReasonCallback, None),
803 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_CONTROL_ERROR, myDomainEventControlErrorCallback, None),
804 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BLOCK_JOB, myDomainEventBlockJobCallback, None),
805 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DISK_CHANGE, myDomainEventDiskChangeCallback, None),
806 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_TRAY_CHANGE, myDomainEventTrayChangeCallback, None),
807 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMWAKEUP, myDomainEventPMWakeupCallback, None),
808 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMSUSPEND, myDomainEventPMSuspendCallback, None),
809 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE, myDomainEventBalloonChangeCallback, None),
810 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK, myDomainEventPMSuspendDiskCallback, None),
811 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED, myDomainEventDeviceRemovedCallback, None),
812 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2, myDomainEventBlockJob2Callback, None),
813 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_TUNABLE, myDomainEventTunableCallback, None),
814 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE, myDomainEventAgentLifecycleCallback, None),
815 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_ADDED, myDomainEventDeviceAddedCallback, None),
816 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION, myDomainEventMigrationIteration, None),
817 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_JOB_COMPLETED, myDomainEventJobCompletedCallback, None),
818 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED, myDomainEventDeviceRemovalFailedCallback, None),
819 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_METADATA_CHANGE, myDomainEventMetadataChangeCallback, None),
820 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD, myDomainEventBlockThresholdCallback, None),
821 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE, myDomainEventMemoryFailureCallback, None),
822 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE, myDomainEventMemoryDeviceSizeChangeCallback, None),
823 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_NIC_MAC_CHANGE, myDomainEventNICMACChangeCallback, None),
824 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_VCPU_REMOVED, myDomainEventVcpuRemovedCallback, None),
825 vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_CHANNEL_LIFECYCLE, myDomainEventChannelLifecycleCallback, None),
826 ]
827
828 netcallbacks = [
829 vc.networkEventRegisterAny(None, libvirt.VIR_NETWORK_EVENT_ID_LIFECYCLE, myNetworkEventLifecycleCallback, None),
830 vc.networkEventRegisterAny(None, libvirt.VIR_NETWORK_EVENT_ID_METADATA_CHANGE, myNetworkEventMetadataChangeCallback, None),
831 ]
832
833 poolcallbacks = [
834 vc.storagePoolEventRegisterAny(None, libvirt.VIR_STORAGE_POOL_EVENT_ID_LIFECYCLE, myStoragePoolEventLifecycleCallback, None),
835 vc.storagePoolEventRegisterAny(None, libvirt.VIR_STORAGE_POOL_EVENT_ID_REFRESH, myStoragePoolEventRefreshCallback, None),
836 ]
837
838 devcallbacks = [
839 vc.nodeDeviceEventRegisterAny(None, libvirt.VIR_NODE_DEVICE_EVENT_ID_LIFECYCLE, myNodeDeviceEventLifecycleCallback, None),
840 vc.nodeDeviceEventRegisterAny(None, libvirt.VIR_NODE_DEVICE_EVENT_ID_UPDATE, myNodeDeviceEventUpdateCallback, None),
841 ]
842
843 seccallbacks = [
844 vc.secretEventRegisterAny(None, libvirt.VIR_SECRET_EVENT_ID_LIFECYCLE, mySecretEventLifecycleCallback, None),
845 vc.secretEventRegisterAny(None, libvirt.VIR_SECRET_EVENT_ID_VALUE_CHANGED, mySecretEventValueChanged, None),
846 ]
847
848 vc.setKeepAlive(5, 3)
849
850 # The rest of your app would go here normally, but for sake
851 # of demo we'll just go to sleep. The other option is to
852 # run the event loop in your main thread if your app is
853 # totally event based.
854 count = 0
855 while run and (args.timeout is None or count < args.timeout):
856 count = count + 1
857 time.sleep(1)
858
859 # If the connection was closed, we cannot unregister anything.
860 # Just abort now.
861 if not run:
862 return
863
864 vc.domainEventDeregister(myDomainEventCallback)
865
866 for id in seccallbacks:
867 vc.secretEventDeregisterAny(id)
868 for id in devcallbacks:
869 vc.nodeDeviceEventDeregisterAny(id)
870 for id in poolcallbacks:
871 vc.storagePoolEventDeregisterAny(id)
872 for id in netcallbacks:
873 vc.networkEventDeregisterAny(id)
874 for id in domcallbacks:
875 vc.domainEventDeregisterAny(id)
876
877 vc.unregisterCloseCallback()
878 vc.close()
879
880 # Allow delayed event loop cleanup to run, just for sake of testing
881 time.sleep(2)
882
883
884 if __name__ == "__main__":
885 main()