Files
tailscale/net/netmon/loghelper.go
Brad Fitzpatrick 6e16dac9e9 net/netmon: make static monitors work without netlink
Userspace-only programs like tailcat don't need to watch the OS
network state, so in sandboxes without netlink access (as in ChatGPT
Work's) they'd like to use netmon.NewStatic instead of netmon.New,
which fails there. But two things broke with a static Monitor:

If reading the interface state failed, NewStatic left it nil, and
callers of InterfaceState don't expect nil.

LinkChangeLogLimiter, used by magicsock, subscribed to the static
Monitor's nil event bus client and panicked. Static monitors never
publish link changes, so skip the subscription.

Updates #22412

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ifa826c8cbac6a82b8a15f57bc8178b364fc30e54
2026-11-15 18:14:23 -08:00

55 lines
1.6 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package netmon
import (
"context"
"sync"
"time"
"tailscale.com/types/logger"
"tailscale.com/util/eventbus"
)
const cooldownSeconds = 300
// LinkChangeLogLimiter returns a new [logger.Logf] that logs each unique
// format string to the underlying logger only once per major LinkChange event
// with a cooldownSeconds second cooldown.
//
// The logger stops tracking seen format strings when the provided context is
// done.
func LinkChangeLogLimiter(ctx context.Context, logf logger.Logf, nm *Monitor) logger.Logf {
var formatLastSeen sync.Map // map[string]int64
// Static monitors never publish link changes and have no event bus client.
if !nm.static {
// The delta is passed by value, but it contains pointers to the old and
// new interface states, which are shared. The delta must not be mutated.
sub := eventbus.SubscribeFunc(nm.b, func(cd ChangeDelta) {
// Any link changes that are flagged as likely require a rebind are
// interesting enough that we should log them.
if cd.RebindLikelyRequired {
formatLastSeen.Clear()
}
})
context.AfterFunc(ctx, sub.Close)
}
return func(format string, args ...any) {
// get the current timestamp
now := time.Now().Unix()
lastSeen, ok := formatLastSeen.Load(format)
if ok {
// if we've seen this format string within the last cooldownSeconds, skip logging
if now-lastSeen.(int64) < cooldownSeconds {
return
}
}
// update the last seen timestamp for this format string
formatLastSeen.Store(format, now)
logf(format, args...)
}
}