Skip to content

Commit ccf9e5a

Browse files
committed
Rework patch that gets the VM IP address using libvirt API
Changed the code to use the native libvirt API provided by the official Go bindings. Signed-off-by: Flavio Castelli <[email protected]>
1 parent 65cc49e commit ccf9e5a

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

kvm.go

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -586,21 +586,20 @@ func (d *Driver) getMAC() (string, error) {
586586
}
587587

588588
func (d *Driver) getIPByMACFromAPI(mac string) (string, error) {
589-
network, err := d.conn.LookupNetworkByName(d.PrivateNetwork)
589+
interfaces, err := d.VM.ListAllInterfaceAddresses(uint(libvirt.DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE))
590590
if err != nil {
591-
log.Errorf("Failed to lookup network %s", d.PrivateNetwork)
592591
return "", err
593592
}
594-
leases, err := network.GetDHCPLeases()
595-
if err != nil {
596-
log.Warnf("Failed to retrieve DHCP leases from libvirt: %v", err)
597-
return "", err
598-
}
599-
for _, lease := range leases {
600-
if strings.ToLower(mac) == strings.ToLower(lease.GetMACAddress()) {
601-
return lease.GetIPAddress(), nil
593+
for _, domainInterface := range interfaces {
594+
if strings.ToUpper(domainInterface.Hwaddr) == strings.ToUpper(mac) {
595+
// An interface can have multiple addresses (eg: ipv4 and ipv6)
596+
// Just returns the first one right now...
597+
for _, addr := range domainInterface.Addrs {
598+
return addr.Addr, nil
599+
}
602600
}
603601
}
602+
604603
return "", errors.New("failed to match IP for MAC address")
605604
}
606605

@@ -686,9 +685,9 @@ func (d *Driver) GetIP() (string, error) {
686685
}
687686

688687
methods := []ipLookupFunc{
688+
d.getIPByMACFromAPI,
689689
d.getIPByMACFromLeaseFile,
690690
d.getIPByMacFromSettings,
691-
d.getIPByMACFromAPI,
692691
}
693692
for _, method := range methods {
694693
ip, err := method(mac)

0 commit comments

Comments
 (0)