From 6743db6e3dd2a6674425f1665645711807fa94f3 Mon Sep 17 00:00:00 2001 From: Siyuan Date: Wed, 8 Oct 2025 13:39:12 +0000 Subject: [PATCH] fix online state detection --- pkg/nmlite/interface.go | 27 +++++++++++---------------- pkg/nmlite/link/netlink.go | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/pkg/nmlite/interface.go b/pkg/nmlite/interface.go index eea1cd59..b935fc9a 100644 --- a/pkg/nmlite/interface.go +++ b/pkg/nmlite/interface.go @@ -690,24 +690,15 @@ func (im *InterfaceManager) updateInterfaceState() error { return fmt.Errorf("failed to get interface: %w", err) } + // Check if state changed + stateChanged := false + attrs := nl.Attrs() isUp := attrs.OperState == netlink.OperUp // check if the interface has unicast addresses - hasAddrs := false - addrs, err := nl.AddrList(link.AfUnspec) - if err != nil { - return fmt.Errorf("failed to get addresses: %w", err) - } - for _, addr := range addrs { - if addr.IP.IsGlobalUnicast() { - hasAddrs = true - break - } - } + isOnline := isUp && nl.HasGlobalUnicastAddress() - // Check if state changed - stateChanged := false // We should release the lock before calling the callbacks // to avoid deadlocks im.stateMu.Lock() @@ -715,8 +706,9 @@ func (im *InterfaceManager) updateInterfaceState() error { im.state.Up = isUp stateChanged = true } - if im.state.Online != hasAddrs { - im.state.Online = hasAddrs + + if im.state.Online != isOnline { + im.state.Online = isOnline stateChanged = true } @@ -762,7 +754,9 @@ func (im *InterfaceManager) updateIPAddresses(nl *link.Link) error { ) for _, addr := range addrs { - im.logger.Debug().Str("address", addr.IP.String()).Msg("checking address") + im.logger.Debug(). + IPAddr("address", addr.IP). + Msg("checking address") if addr.IP.To4() != nil { // IPv4 address ipv4Addresses = append(ipv4Addresses, addr.IPNet.String()) @@ -811,6 +805,7 @@ func (im *InterfaceManager) updateStateFromDHCPLease(lease *types.DHCPLease) { } } +// ReconcileLinkAddrs reconciles the link addresses func (im *InterfaceManager) ReconcileLinkAddrs(addrs []*types.IPAddress) error { nl := getNetlinkManager() link, err := im.link() diff --git a/pkg/nmlite/link/netlink.go b/pkg/nmlite/link/netlink.go index 93aa9e1d..d726e4b9 100644 --- a/pkg/nmlite/link/netlink.go +++ b/pkg/nmlite/link/netlink.go @@ -118,6 +118,21 @@ func (l *Link) AddrList(family int) ([]netlink.Addr, error) { return netlink.AddrList(l.Link, family) } +// HasGlobalUnicastAddress returns true if the link has a global unicast address +func (l *Link) HasGlobalUnicastAddress() bool { + addrs, err := l.AddrList(AfUnspec) + if err != nil { + return false + } + + for _, addr := range addrs { + if addr.IP.IsGlobalUnicast() { + return true + } + } + return false +} + // IsSame checks if the link is the same as another link func (l *Link) IsSame(other *Link) bool { if l == nil || other == nil {