Skip to content

Commit f720110

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 86938fc commit f720110

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
@@ -593,21 +593,20 @@ func (d *Driver) getMAC() (string, error) {
593593
}
594594

595595
func (d *Driver) getIPByMACFromAPI(mac string) (string, error) {
596-
network, err := d.conn.LookupNetworkByName(d.PrivateNetwork)
596+
interfaces, err := d.VM.ListAllInterfaceAddresses(uint(libvirt.DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE))
597597
if err != nil {
598-
log.Errorf("Failed to lookup network %s", d.PrivateNetwork)
599598
return "", err
600599
}
601-
leases, err := network.GetDHCPLeases()
602-
if err != nil {
603-
log.Warnf("Failed to retrieve DHCP leases from libvirt: %v", err)
604-
return "", err
605-
}
606-
for _, lease := range leases {
607-
if strings.ToLower(mac) == strings.ToLower(lease.GetMACAddress()) {
608-
return lease.GetIPAddress(), nil
600+
for _, domainInterface := range interfaces {
601+
if strings.ToUpper(domainInterface.Hwaddr) == strings.ToUpper(mac) {
602+
// An interface can have multiple addresses (eg: ipv4 and ipv6)
603+
// Just returns the first one right now...
604+
for _, addr := range domainInterface.Addrs {
605+
return addr.Addr, nil
606+
}
609607
}
610608
}
609+
611610
return "", errors.New("failed to match IP for MAC address")
612611
}
613612

@@ -693,9 +692,9 @@ func (d *Driver) GetIP() (string, error) {
693692
}
694693

695694
methods := []ipLookupFunc{
695+
d.getIPByMACFromAPI,
696696
d.getIPByMACFromLeaseFile,
697697
d.getIPByMacFromSettings,
698-
d.getIPByMACFromAPI,
699698
}
700699
for _, method := range methods {
701700
ip, err := method(mac)

0 commit comments

Comments
 (0)