5 from xml
.dom
import minidom
11 uri
= "qemu:///system"
12 customXMLuri
= "guest-cpu.python.libvirt.org"
13 connectRetryTimeout
= 5
16 print("usage: "+os
.path
.basename(sys
.argv
[0])+" [-h] [uri]")
17 print(" uri will default to qemu:///system")
18 print(" --help, -h Print(this help message")
20 print("This service waits for the guest agent lifecycle event and reissues " +
21 "guest agent calls to modify the cpu count according to the metadata " +
22 "set by guest-vcpu.py example")
28 self
.cond
= threading
.Condition()
40 def addDomainNotify(self
, dom
):
44 def closeConnectNotify(self
):
50 def setConnect(self
, conn
):
54 return self
.conn
is not None
57 return len(self
.doms
) > 0
60 return self
.doms
.pop()
62 def setDoms(self
, doms
):
66 def virEventLoopNativeRun():
68 libvirt
.virEventRunDefaultImpl()
70 def handleAgentLifecycleEvent(conn
, dom
, state
, reason
, opaque
):
71 if state
== libvirt
.VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_CONNECTED
:
72 opaque
.addDomainNotify(dom
)
74 def handleConnectClose(conn
, reason
, opaque
):
75 print('Disconnected from ' + uri
)
76 opaque
.closeConnectNotify()
78 def handleLibvirtLibraryError(opaque
, error
):
81 def processAgentConnect(dom
):
83 cpus
= dom
.metadata(libvirt
.VIR_DOMAIN_METADATA_ELEMENT
, customXMLuri
,
84 libvirt
.VIR_DOMAIN_AFFECT_LIVE
)
85 doc
= minidom
.parseString(cpus
)
86 ncpus
= int(doc
.getElementsByTagName('ncpus')[0].getAttribute('count'))
91 dom
.setVcpusFlags(ncpus
, libvirt
.VIR_DOMAIN_AFFECT_LIVE | libvirt
.VIR_DOMAIN_VCPU_GUEST
)
92 print("set vcpu count for domain " + dom
.name() + " to " + str(ncpus
))
94 print("failed to set vcpu count for domain " + dom
.name())
99 print("Using uri: " + uri
)
102 if not data
.hasConn():
104 conn
= libvirt
.open(uri
)
106 print('Failed to connect to ' + uri
+ ', retry in ' + str(connectRetryTimeout
)) + ' seconds'
107 time
.sleep(connectRetryTimeout
)
110 print('Connected to ' + uri
)
112 data
.setConnect(conn
)
113 conn
.registerCloseCallback(handleConnectClose
, data
)
114 conn
.setKeepAlive(5, 3)
115 conn
.domainEventRegisterAny(None,
116 libvirt
.VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE
,
117 handleAgentLifecycleEvent
,
120 data
.setDoms(conn
.listAllDomains(libvirt
.VIR_CONNECT_LIST_DOMAINS_ACTIVE
))
122 while data
.hasConn() and data
.hasDom():
123 processAgentConnect(data
.getDom())
128 libvirt
.virEventRegisterDefaultImpl()
129 libvirt
.registerErrorHandler(handleLibvirtLibraryError
, None)
131 worker
= threading
.Thread(target
=work
)
132 worker
.setDaemon(True)
135 eventLoop
= threading
.Thread(target
=virEventLoopNativeRun
)
136 eventLoop
.setDaemon(True)
142 if __name__
== "__main__":
144 opts
, args
= getopt
.getopt(sys
.argv
[1:], "h", ["help"])
145 except getopt
.GetoptError
as err
:
150 if o
in ("-h", "--help"):