Debian Codegraph @

udp/netchange.go

raw
1 package udp
2
3 import (
4 "context"
5 "log/slog"
6
7 "github.com/slackhq/nebula/config"
8 )
9
10 // NetworkChangeMonitor rebinds the udp listener when the local network moves out from under it.
11 //
12 // Detection lives here in the udp package, next to the socket it concerns and the platform matrix that already knows
13 // which sockets go stale. What to do about a change — updating the lighthouse, requerying tunnels — is not the udp
14 // package's business, so Start takes the reaction as a plain function. Passing it at Start rather than holding it
15 // keeps this package from referencing whatever owns the rebind.
16 //
17 // On platforms whose sockets do not go stale, watchNetworkChanges hands back a nil channel and Start returns.
18 type NetworkChangeMonitor struct {
19 l *slog.Logger
20 ctx context.Context
21 enabled bool
22 }
23
24 // NewNetworkChangeMonitor builds a monitor for local network changes. The returned monitor is always usable: Start
25 // is safe to call unconditionally, it no-ops when disabled or on a platform that does not need it.
26 func NewNetworkChangeMonitor(ctx context.Context, l *slog.Logger, c *config.C) *NetworkChangeMonitor {
27 return &NetworkChangeMonitor{
28 l: l,
29 ctx: ctx,
30 enabled: c.GetBool("listen.rebind_on_network_change", true),
31 }
32 }
33
34 // Start watches for network changes until the context is cancelled, calling rebind once per settled change. It
35 // blocks, so callers run it in a goroutine, and it no-ops when disabled, unsupported, or with nothing to rebind.
36 func (m *NetworkChangeMonitor) Start(rebind func()) {
37 if !m.enabled || rebind == nil || m.ctx.Err() != nil {
38 return
39 }
40
41 changes, err := watchNetworkChanges(m.ctx, m.l)
42 if err != nil {
43 // Not fatal. Everything else still works, we just won't notice a network change on our own.
44 m.l.Error("Failed to watch for network changes, will not rebind the udp listener when the network moves",
45 "error", err,
46 )
47 return
48 }
49
50 if changes == nil {
51 // This platform's sockets don't go stale, so there is nothing to watch for.
52 return
53 }
54
55 m.l.Info("Watching for network changes to rebind the udp listener")
56
57 for range changes {
58 m.l.Info("Local network changed, rebinding the udp listener")
59 rebind()
60 }
61 }