Skip to content

Commit

Permalink
arp: optimize interface name resolution
Browse files Browse the repository at this point in the history
Fixes: #3075

Signed-off-by: Daniel Swarbrick <[email protected]>
  • Loading branch information
dswarbrick committed Sep 25, 2024
1 parent 71d9b6c commit 6613f53
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions collector/arp_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package collector

import (
"errors"
"fmt"
"log/slog"
"net"
Expand Down Expand Up @@ -87,30 +86,37 @@ func getTotalArpEntriesRTNL() (map[string]uint32, error) {
return nil, err
}

ifIndexEntries := make(map[uint32]uint32)
// Map of interface index to ARP neighbor count.
ifIndexEntries := make(map[int]uint32)

for _, n := range neighbors {
// Neighbors will also contain IPv6 neighbors, but since this is purely an ARP collector,
// restrict to AF_INET. Also skip entries which have state NUD_NOARP to conform to output
// of /proc/net/arp.
if n.Family == unix.AF_INET && n.State&unix.NUD_NOARP == 0 {
ifIndexEntries[n.Index]++
ifIndexEntries[int(n.Index)]++
}
}

// Go's net.InterfaceByIndex(idx) function fetches the _entire_ interface table behind the
// scenes prior to filtering the response. This will result in an exponential amount of
// rtnetlink traffic as the number of interfaces increases. Instead, we fetch the interface
// table _once_, and perform our own filtering / matching.
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}

// Map of interface name to ARP neighbor count.
enumEntries := make(map[string]uint32)

// Convert interface indexes to names.
for ifIndex, entryCount := range ifIndexEntries {
iface, err := net.InterfaceByIndex(int(ifIndex))
if err != nil {
if errors.Unwrap(err).Error() == "no such network interface" {
continue
for x := range ifaces {
if ifaces[x].Index == ifIndex {
enumEntries[ifaces[x].Name] = entryCount
break
}
return nil, err
}

enumEntries[iface.Name] = entryCount
}

return enumEntries, nil
Expand Down

0 comments on commit 6613f53

Please sign in to comment.