From 85a26ecd6d57be3eb0dd168daa3dcc4d0bc2bd70 Mon Sep 17 00:00:00 2001 From: Yagnesh Suribhatla Date: Mon, 18 Nov 2024 20:24:33 +0000 Subject: [PATCH] Revert "Use a single syscall for route table for health check IP" This reverts commit ae35229180833f22dfbc0795d642fa5feaf6d577. cr: https://code.amazon.com/reviews/CR-160879895 --- agent/platform/platform.go | 45 ++++++++++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/agent/platform/platform.go b/agent/platform/platform.go index 0ff83c9d1..4aed3bd6b 100644 --- a/agent/platform/platform.go +++ b/agent/platform/platform.go @@ -17,6 +17,7 @@ package platform import ( "fmt" "net" + "sort" "unicode/utf8" "github.com/aws/amazon-ssm-agent/agent/log" @@ -85,16 +86,25 @@ func Hostname(log log.T) (name string, err error) { // IP of the network interface func IP() (selected string, err error) { - if addrs, err := net.InterfaceAddrs(); err == nil { + var interfaces []net.Interface + if interfaces, err = net.Interfaces(); err == nil { + interfaces = filterInterface(interfaces) + sort.Sort(byIndex(interfaces)) candidates := make([]net.IP, 0) - for _, addr := range addrs { - switch v := addr.(type) { - case *net.IPAddr: - candidates = append(candidates, v.IP.To4()) - candidates = append(candidates, v.IP.To16()) - case *net.IPNet: - candidates = append(candidates, v.IP.To4()) - candidates = append(candidates, v.IP.To16()) + for _, i := range interfaces { + var addrs []net.Addr + if addrs, err = i.Addrs(); err != nil { + continue + } + for _, addr := range addrs { + switch v := addr.(type) { + case *net.IPAddr: + candidates = append(candidates, v.IP.To4()) + candidates = append(candidates, v.IP.To16()) + case *net.IPNet: + candidates = append(candidates, v.IP.To4()) + candidates = append(candidates, v.IP.To16()) + } } } selectedIp, err := selectIp(candidates) @@ -147,6 +157,23 @@ func isIpv4(ip net.IP) bool { return ip.To4() != nil } +// filterInterface removes interface that's not up or is a loopback/p2p +func filterInterface(interfaces []net.Interface) (i []net.Interface) { + for _, v := range interfaces { + if (v.Flags&net.FlagUp != 0) && (v.Flags&net.FlagLoopback == 0) && (v.Flags&net.FlagPointToPoint == 0) { + i = append(i, v) + } + } + return +} + +// byIndex implements sorting for net.Interface. +type byIndex []net.Interface + +func (b byIndex) Len() int { return len(b) } +func (b byIndex) Less(i, j int) bool { return b[i].Index < b[j].Index } +func (b byIndex) Swap(i, j int) { b[i], b[j] = b[j], b[i] } + func IsPlatformNanoServer(log log.T) (bool, error) { return isPlatformNanoServer(log) }