diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 70c53f985..fb7006a53 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -714,6 +714,14 @@ type radvPending struct { // carrier, so a guest that restarts gets a fresh, fast retry cycle. failures int retryAt time.Time + // notReady counts consecutive starts that exhausted their retries on + // radv.ErrAddrNotReady. The first radvWarnAfterFailures-1 retry on the next + // reconcile with no backoff, since the address is normally still being + // assigned; from radvWarnAfterFailures on the interface has carrier but no + // usable link-local address (for instance IPv6 disabled), so one warning is + // logged and retries back off. It resets with failures, and on any other + // failure. + notReady int // noCarrier records that the last reconcile found the interface without // carrier, so the wait is logged once rather than on every tick. noCarrier bool @@ -744,11 +752,26 @@ var radvStaleRecordGrace = 30 * time.Second var radvMaxRetryBackoff = 5 * time.Minute // radvWarnAfterFailures is the consecutive failed start that is logged as a -// warning. Earlier failures are routine, since a freshly attached guest's -// link-local address is still completing duplicate address detection, and later -// ones would repeat the same warning for as long as the failure lasts. +// warning. Later ones would repeat the same warning for as long as the failure +// lasts. const radvWarnAfterFailures = 3 +// radvAddrNotReadyRetryDelay and radvAddrNotReadyRetries bound how long an +// actor goroutine keeps retrying a start that failed with radv.ErrAddrNotReady +// before reporting it. The tap's link-local address appears, and leaves the +// tentative state, moments after the tap gains carrier, often just after the +// carrier event that started the actor, so a short local retry serves the +// guest within a fraction of a second instead of waiting for the next tick. +// Vars so tests can shrink them. +var ( + radvAddrNotReadyRetryDelay = 100 * time.Millisecond + radvAddrNotReadyRetries = 20 +) + +// radvRunActor is the actor each started attachment runs. A var so tests can +// fake its result without a real interface. +var radvRunActor = radv.RunActor + // radvNow is the clock reconcileRadvActors reads. A var so tests can move it. var radvNow = time.Now @@ -822,7 +845,15 @@ func reconcileRadvActors(ctx context.Context, actors *radvActorSet) { p.missingSince = time.Time{} seen[r.HostInterface] = struct{}{} - if _, running := actors.cancel[r.HostInterface]; running { + if cancel, running := actors.cancel[r.HostInterface]; running { + if !carrier { + // The guest went away while its actor kept running. Stop the + // actor, so the carrier's return starts a fresh one that sends + // an immediate advertisement and a new initial burst. + cancel() + delete(actors.cancel, r.HostInterface) + radvReadyToStart(p, r.HostInterface, carrier, now) + } continue } if !radvReadyToStart(p, r.HostInterface, carrier, now) { @@ -834,7 +865,7 @@ func reconcileRadvActors(ctx context.Context, actors *radvActorSet) { actors.wg.Add(1) go func(iface string, mtu int) { defer actors.wg.Done() - if err := radv.RunActor(actorCtx, iface, mtu); err != nil { + if err := runRadvActor(actorCtx, iface, mtu); err != nil { select { case actors.failed <- radvActorFailure{iface: iface, err: err}: default: @@ -859,6 +890,23 @@ func reconcileRadvActors(ctx context.Context, actors *radvActorSet) { } } +// runRadvActor runs radvRunActor on iface, retrying a start that fails with +// radv.ErrAddrNotReady every radvAddrNotReadyRetryDelay, up to +// radvAddrNotReadyRetries times, before returning the error. +func runRadvActor(ctx context.Context, iface string, mtu int) error { + for attempt := 0; ; attempt++ { + err := radvRunActor(ctx, iface, mtu) + if !errors.Is(err, radv.ErrAddrNotReady) || attempt >= radvAddrNotReadyRetries { + return err + } + select { + case <-ctx.Done(): + return nil + case <-time.After(radvAddrNotReadyRetryDelay): + } + } +} + // removeStaleRadvRecord handles a record whose host interface is missing. It // notes when the interface was first found missing, and once it has stayed // missing past radvStaleRecordGrace removes the record, reporting true. @@ -905,6 +953,7 @@ func radvReadyToStart(p *radvPending, iface string, carrier bool, now time.Time) } p.noCarrier = true p.failures = 0 + p.notReady = 0 p.retryAt = time.Time{} return false } @@ -923,12 +972,29 @@ func radvPendingFor(actors *radvActorSet, iface string) *radvPending { return p } +// radvBackoff returns the delay after the nth consecutive failure: it starts at +// radvReconcileInterval, doubles each time and stops at radvMaxRetryBackoff. +func radvBackoff(n int) time.Duration { + backoff := radvReconcileInterval << min(max(n-1, 0), 16) + if backoff <= 0 || backoff > radvMaxRetryBackoff { + backoff = radvMaxRetryBackoff + } + return backoff +} + // radvActorFailed clears the map entry for an actor that could not start, so a // later reconcile sees the attachment as unserved and retries it once its // backoff has elapsed. Without it, reconcileRadvActors would stay convinced the // actor is running. A report for an attachment that is already gone is a safe // no-op. // +// A start that failed only because the interface's link-local address is not +// usable yet (radv.ErrAddrNotReady) is retried on the next reconcile and does +// not count toward the backoff: the address is still being assigned, and +// counting it would delay the guest's first advertisement for no fault of its +// own. Only when that keeps happening, radvWarnAfterFailures times in a row, +// does it warn once and back off like an ordinary failure. +// // Each attempt derives its context from one that lives as long as the process. // Only cancelling detaches the derived context. Deleting the entry alone leaves // it attached, so a retry loop grows this daemon's memory without bound. @@ -941,11 +1007,25 @@ func radvActorFailed(actors *radvActorSet, failure radvActorFailure) { delete(actors.cancel, failure.iface) p := radvPendingFor(actors, failure.iface) - p.failures++ - backoff := radvReconcileInterval << min(p.failures-1, 16) - if backoff <= 0 || backoff > radvMaxRetryBackoff { - backoff = radvMaxRetryBackoff + if errors.Is(failure.err, radv.ErrAddrNotReady) { + p.notReady++ + if p.notReady < radvWarnAfterFailures { + p.retryAt = time.Time{} + slog.Debug("Router advertisement interface address not ready yet, will retry", + "err", failure.err, "hostInterface", failure.iface) + return + } + backoff := radvBackoff(p.notReady - radvWarnAfterFailures + 1) + p.retryAt = radvNow().Add(backoff) + if p.notReady == radvWarnAfterFailures { + slog.Warn("Router advertisement interface has carrier but no usable link-local address, backing off", + "err", failure.err, "hostInterface", failure.iface, "attempts", p.notReady, "maxBackoff", radvMaxRetryBackoff) + } + return } + p.notReady = 0 + p.failures++ + backoff := radvBackoff(p.failures) p.retryAt = radvNow().Add(backoff) if p.failures == radvWarnAfterFailures { @@ -983,8 +1063,9 @@ func radvActorFailed(actors *radvActorSet, failure radvActorFailure) { // galactic-router's GC controller because the pinned maps exist only // inside this container. // 8. Runs one radv.RunActor per recorded tap attachment, reconciled on a short -// ticker. Each actor resends Router Advertisements on a jittered schedule -// and replies to that guest's solicitations. This runs here, not from +// ticker and whenever a tap gains carrier. Each actor advertises as soon as +// it starts, resends Router Advertisements on a jittered schedule, and +// replies to that guest's solicitations. This runs here, not from // galactic-tap's cmdAdd, because a guest's boot outlives that short-lived // process. It is independent of the eBPF datapath and runs regardless. func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { @@ -1089,8 +1170,12 @@ func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { reconcileRadvActors(ctx, radvActors) defer radvActors.wg.Wait() - radvReconcileTicker := time.NewTicker(radvReconcileInterval) - defer radvReconcileTicker.Stop() + // Reconciled every radvReconcileInterval, and again the moment a tap + // gains carrier, which is when its VMM opens it, so the guest's first + // advertisement does not wait for the next tick. + radvReconcileCh := make(chan struct{}, 1) + go signalEvery(ctx, radvReconcileInterval, radvReconcileCh) + go watchTapCarrier(ctx, radvReconcileCh) tapNeighTicker := time.NewTicker(tapNeighReconcileInterval) defer tapNeighTicker.Stop() @@ -1164,7 +1249,7 @@ func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { "removed", nptv6Result.EBPFNPTv6EntriesRemoved, "errors", nptv6Result.Errors) } - case <-radvReconcileTicker.C: + case <-radvReconcileCh: reconcileRadvActors(ctx, radvActors) case <-tapNeighTicker.C: diff --git a/internal/installer/installer_test.go b/internal/installer/installer_test.go index 71102c25c..d75064aba 100644 --- a/internal/installer/installer_test.go +++ b/internal/installer/installer_test.go @@ -15,6 +15,7 @@ import ( "os" "path/filepath" "strings" + "sync" "sync/atomic" "testing" "time" @@ -729,6 +730,109 @@ func awaitRadvFailure(t *testing.T, actors *radvActorSet) radvActorFailure { return radvActorFailure{} } +// testRadvCarrierLossCancelsRunningActor covers a guest that restarts: it loses +// and regains carrier while its actor keeps running. The actor is cancelled on +// the loss, so the carrier's return starts a fresh one, with its own initial +// burst. +func testRadvCarrierLossCancelsRunningActor(t *testing.T, env *radvTestEnv, ctx context.Context, actors *radvActorSet) { + const iface = radvTestIface + var mu sync.Mutex + started := 0 + stopped := make(chan struct{}, 4) + orig := radvRunActor + t.Cleanup(func() { radvRunActor = orig }) + radvRunActor = func(ctx context.Context, _ string, _ int) error { + mu.Lock() + started++ + mu.Unlock() + <-ctx.Done() + stopped <- struct{}{} + return nil + } + startedCount := func() int { + mu.Lock() + defer mu.Unlock() + return started + } + awaitStarted := func(want int) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for startedCount() != want { + if time.Now().After(deadline) { + t.Fatalf("actors started = %d, want %d", startedCount(), want) + } + time.Sleep(5 * time.Millisecond) + } + } + + env.links[iface] = radvTestLink{carrier: true} + reconcileRadvActors(ctx, actors) + awaitStarted(1) + + env.links[iface] = radvTestLink{carrier: false} + reconcileRadvActors(ctx, actors) + if _, running := actors.cancel[iface]; running { + t.Fatalf("actor on %q still tracked after carrier was lost", iface) + } + select { + case <-stopped: + case <-time.After(2 * time.Second): + t.Fatalf("actor on %q not cancelled after carrier was lost", iface) + } + + env.links[iface] = radvTestLink{carrier: true} + reconcileRadvActors(ctx, actors) + if _, running := actors.cancel[iface]; !running { + t.Fatalf("no fresh actor on %q after carrier returned", iface) + } + awaitStarted(2) +} + +// testRadvAddrNotReadyBacksOff covers an interface with carrier that never gets +// a usable link-local address: it retries at once at first, then warns and backs +// off. +func testRadvAddrNotReadyBacksOff(t *testing.T, env *radvTestEnv, ctx context.Context, actors *radvActorSet) { + const iface = radvTestIface + env.links[iface] = radvTestLink{carrier: true} + notReady := radvActorFailure{iface: iface, err: radv.ErrAddrNotReady} + + for i := 1; i < radvWarnAfterFailures; i++ { + reconcileRadvActors(ctx, actors) + if _, running := actors.cancel[iface]; !running { + t.Fatalf("exhaustion %d: actor on %q not started", i, iface) + } + radvActorFailed(actors, notReady) + if p := actors.pending[iface]; !p.retryAt.IsZero() || p.failures != 0 { + t.Fatalf("exhaustion %d: retryAt = %v, failures = %d, want an immediate retry", i, p.retryAt, p.failures) + } + } + + reconcileRadvActors(ctx, actors) + radvActorFailed(actors, notReady) + p := actors.pending[iface] + if got := p.retryAt.Sub(env.now); got != radvReconcileInterval { + t.Fatalf("backoff at the warning threshold = %v, want %v", got, radvReconcileInterval) + } + reconcileRadvActors(ctx, actors) + if _, running := actors.cancel[iface]; running { + t.Fatalf("actor on %q retried inside its backoff", iface) + } + + env.now = p.retryAt + reconcileRadvActors(ctx, actors) + radvActorFailed(actors, notReady) + if got := p.retryAt.Sub(env.now); got != 2*radvReconcileInterval { + t.Fatalf("second backoff = %v, want %v", got, 2*radvReconcileInterval) + } + + // Losing carrier starts the count over. + env.links[iface] = radvTestLink{carrier: false} + reconcileRadvActors(ctx, actors) + if p.notReady != 0 || !p.retryAt.IsZero() { + t.Errorf("notReady = %d, retryAt = %v after carrier loss, want both reset", p.notReady, p.retryAt) + } +} + func TestReconcileRadvActors(t *testing.T) { const iface = radvTestIface @@ -841,6 +945,8 @@ func TestReconcileRadvActors(t *testing.T) { awaitRadvFailure(t, actors) }, }, + {name: "CarrierLossCancelsRunningActor", run: testRadvCarrierLossCancelsRunningActor}, + {name: "AddrNotReadyBacksOffAfterRepeatedExhaustion", run: testRadvAddrNotReadyBacksOff}, { // A record whose interface is gone is removed once the grace // period has passed, since no DEL is left to remove it. diff --git a/internal/installer/manifest_test.go b/internal/installer/manifest_test.go index 9961cfaf4..e4d13f69e 100644 --- a/internal/installer/manifest_test.go +++ b/internal/installer/manifest_test.go @@ -95,7 +95,7 @@ func TestDaemonsetManifest_RunContainerMountsSharedTCLockDirWritable(t *testing. // TestDaemonsetManifest_RunContainerMountsHostConflistDir above, this time // for radv.DefaultStateDir ("/var/lib/cni/ra"): reconcileRadvActors calls // radv.ListAttachments(radv.DefaultStateDir) from inside the run container -// on every radvReconcileTicker tick. That directory is populated by +// on every reconcile. That directory is populated by // galactic-tap's cmdAdd/cmdDel (internal/cnitap/ops_add.go, // internal/cnitap/ops_del.go) -- a separate binary invoked directly on the // host by the kubelet's own CNI exec, not inside this or any other diff --git a/internal/installer/radv_carrier.go b/internal/installer/radv_carrier.go new file mode 100644 index 000000000..80bdcafa1 --- /dev/null +++ b/internal/installer/radv_carrier.go @@ -0,0 +1,124 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "context" + "log/slog" + "time" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" +) + +// tapCarrierLinkSubscribe is the netlink link subscription watchTapCarrier +// reads. A var so tests can feed it synthetic updates. +var tapCarrierLinkSubscribe = netlink.LinkSubscribeWithOptions + +// tapCarrierResubscribeDelay is how long watchTapCarrier waits before +// subscribing again after its subscription fails or ends. A var so tests can +// shrink it. +var tapCarrierResubscribeDelay = 5 * time.Second + +// signalEvery signals on trigger every interval until ctx is done, without +// blocking: a signal already pending covers this one. +func signalEvery(ctx context.Context, interval time.Duration, trigger chan<- struct{}) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + select { + case trigger <- struct{}{}: + default: + } + } + } +} + +// watchTapCarrier signals on trigger whenever a tap gains carrier, until ctx is +// done. A tap gains carrier when its VMM opens it, which is the moment its +// guest can start receiving Router Advertisements, so Run reconciles the radv +// actors on the signal instead of waiting for radvReconcileInterval. +// +// trigger should be buffered by one. A send never blocks: a signal already +// pending covers this one, since a reconcile looks at every recorded +// attachment. A failed or ended subscription is retried after +// tapCarrierResubscribeDelay; until then the reconcile ticker still serves +// every tap, only less promptly. +func watchTapCarrier(ctx context.Context, trigger chan<- struct{}) { + for { + if err := watchTapCarrierOnce(ctx, trigger); err != nil { + slog.Warn("Failed to subscribe to tap carrier changes, will retry", + "err", err, "retryIn", tapCarrierResubscribeDelay) + } + select { + case <-ctx.Done(): + return + case <-time.After(tapCarrierResubscribeDelay): + } + } +} + +// watchTapCarrierOnce runs one subscription until ctx is done or the +// subscription ends, returning an error only if subscribing failed. +func watchTapCarrierOnce(ctx context.Context, trigger chan<- struct{}) error { + // Buffered so netlink's own goroutine can hand off an update in flight + // as this function returns. + updates := make(chan netlink.LinkUpdate, 16) + done := make(chan struct{}) + defer close(done) + + if err := tapCarrierLinkSubscribe(updates, done, netlink.LinkSubscribeOptions{ + ErrorCallback: func(err error) { + slog.Debug("Tap carrier subscription error", "err", err) + }, + }); err != nil { + return err + } + + carrier := make(map[int32]bool) + for { + select { + case <-ctx.Done(): + return nil + case u, ok := <-updates: + if !ok { + slog.Warn("Tap carrier subscription ended, will resubscribe") + return nil + } + if tapGainedCarrier(carrier, u) { + select { + case trigger <- struct{}{}: + default: + } + } + } + } +} + +// tapGainedCarrier reports whether u shows a tap gaining carrier, given the +// carrier state last seen per interface index, which it updates. A link is +// reported again on every change to any of its attributes, so only the +// transition counts. A tap seen for the first time with carrier counts as +// gaining it. +func tapGainedCarrier(carrier map[int32]bool, u netlink.LinkUpdate) bool { + index := u.Index + if u.Header.Type == unix.RTM_DELLINK { + delete(carrier, index) + return false + } + link := u.Link + if link == nil || link.Type() != "tuntap" { + return false + } + + up := link.Attrs().RawFlags&unix.IFF_LOWER_UP != 0 + was := carrier[index] + carrier[index] = up + return up && !was +} diff --git a/internal/installer/radv_carrier_test.go b/internal/installer/radv_carrier_test.go new file mode 100644 index 000000000..e5018d0ef --- /dev/null +++ b/internal/installer/radv_carrier_test.go @@ -0,0 +1,253 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/vishvananda/netlink" + "github.com/vishvananda/netlink/nl" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/plumbing/radv" +) + +// linkUpdate builds a netlink link update for interface index carrying link, +// with the given message type and lower-up flag. +func linkUpdate(msgType uint16, index int32, link netlink.Link, lowerUp bool) netlink.LinkUpdate { + if link != nil { + attrs := link.Attrs() + attrs.Index = int(index) + if lowerUp { + attrs.RawFlags |= unix.IFF_LOWER_UP + } + } + return netlink.LinkUpdate{ + IfInfomsg: nl.IfInfomsg{IfInfomsg: unix.IfInfomsg{Index: index}}, + Header: unix.NlMsghdr{Type: msgType}, + Link: link, + } +} + +func newTap() netlink.Link { + return &netlink.Tuntap{LinkAttrs: netlink.LinkAttrs{Name: "tap0"}, Mode: netlink.TUNTAP_MODE_TAP} +} + +func newVeth() netlink.Link { + return &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "veth0"}} +} + +func TestTapGainedCarrier(t *testing.T) { + type step struct { + update netlink.LinkUpdate + want bool + } + tests := []struct { + name string + steps []step + }{ + { + name: "TapGainingCarrierCounts", + steps: []step{ + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), false), false}, + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + }, + }, + { + name: "FirstSightingWithCarrierCounts", + steps: []step{ + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + }, + }, + { + // Every attribute change repeats the link, carrier included. + name: "RepeatedUpdateWhileUpDoesNotCount", + steps: []step{ + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), false}, + }, + }, + { + // A guest restarting closes and reopens its tap. + name: "RegainingCarrierCountsAgain", + steps: []step{ + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), false), false}, + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + }, + }, + { + name: "DeletedAndRecreatedTapCountsAgain", + steps: []step{ + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + {linkUpdate(unix.RTM_DELLINK, 7, newTap(), true), false}, + {linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true), true}, + }, + }, + { + name: "VethIsIgnored", + steps: []step{ + {linkUpdate(unix.RTM_NEWLINK, 8, newVeth(), true), false}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + carrier := map[int32]bool{} + for i, s := range tt.steps { + if got := tapGainedCarrier(carrier, s.update); got != s.want { + t.Errorf("step %d: tapGainedCarrier() = %v, want %v", i, got, s.want) + } + } + }) + } +} + +// TestWatchTapCarrier checks that a tap gaining carrier triggers a reconcile +// at once, without waiting for the reconcile ticker (#828), and that a failed +// subscription is retried. +func TestWatchTapCarrier(t *testing.T) { + origSubscribe, origDelay := tapCarrierLinkSubscribe, tapCarrierResubscribeDelay + t.Cleanup(func() { tapCarrierLinkSubscribe, tapCarrierResubscribeDelay = origSubscribe, origDelay }) + tapCarrierResubscribeDelay = time.Millisecond + + subscribed := make(chan chan<- netlink.LinkUpdate, 1) + calls := 0 + tapCarrierLinkSubscribe = func(ch chan<- netlink.LinkUpdate, _ <-chan struct{}, _ netlink.LinkSubscribeOptions) error { + calls++ + if calls == 1 { + return errors.New("subscribe failed") + } + subscribed <- ch + return nil + } + + ctx, cancel := context.WithCancel(context.Background()) + trigger := make(chan struct{}, 1) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + watchTapCarrier(ctx, trigger) + }() + t.Cleanup(func() { + cancel() + <-stopped + }) + + var updates chan<- netlink.LinkUpdate + select { + case updates = <-subscribed: + case <-time.After(2 * time.Second): + t.Fatal("watchTapCarrier did not resubscribe after a failed subscription") + } + + updates <- linkUpdate(unix.RTM_NEWLINK, 7, newTap(), false) + updates <- linkUpdate(unix.RTM_NEWLINK, 8, newVeth(), true) + select { + case <-trigger: + t.Fatal("triggered without any tap gaining carrier") + case <-time.After(50 * time.Millisecond): + } + + updates <- linkUpdate(unix.RTM_NEWLINK, 7, newTap(), true) + select { + case <-trigger: + case <-time.After(2 * time.Second): + t.Fatal("tap gaining carrier did not trigger a reconcile") + } +} + +// TestRunRadvActor_RetriesAddrNotReady checks that an actor whose tap address +// is still being assigned is retried locally rather than reported as a failed +// start (#828). +func TestRunRadvActor_RetriesAddrNotReady(t *testing.T) { + origRun, origDelay, origRetries := radvRunActor, radvAddrNotReadyRetryDelay, radvAddrNotReadyRetries + t.Cleanup(func() { + radvRunActor, radvAddrNotReadyRetryDelay, radvAddrNotReadyRetries = origRun, origDelay, origRetries + }) + radvAddrNotReadyRetryDelay = time.Millisecond + radvAddrNotReadyRetries = 5 + + notReady := fmt.Errorf("open NDP connection: %w", radv.ErrAddrNotReady) + other := errors.New("permission denied") + + tests := []struct { + name string + results []error + wantErr error + wantCalls int + }{ + {"ReadyAfterTwoAttempts", []error{notReady, notReady, nil}, nil, 3}, + {"OtherErrorIsNotRetried", []error{other}, other, 1}, + { + "GivesUpAfterRetries", + []error{notReady, notReady, notReady, notReady, notReady, notReady, notReady}, + radv.ErrAddrNotReady, 6, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + calls := 0 + radvRunActor = func(context.Context, string, int) error { + err := tt.results[calls] + calls++ + return err + } + + err := runRadvActor(context.Background(), radvTestIface, 1500) + if !errors.Is(err, tt.wantErr) || (tt.wantErr == nil && err != nil) { + t.Errorf("runRadvActor() = %v, want %v", err, tt.wantErr) + } + if calls != tt.wantCalls { + t.Errorf("radvRunActor called %d times, want %d", calls, tt.wantCalls) + } + }) + } +} + +// TestRadvActorFailed_AddrNotReadyDoesNotBackOff checks that a start that +// failed only because the tap's address was not ready yet is retried on the +// next reconcile and does not grow the backoff (#828). +func TestRadvActorFailed_AddrNotReadyDoesNotBackOff(t *testing.T) { + env := newRadvTestEnv(t) + recordRadvAttachment(t) + env.links[radvTestIface] = radvTestLink{carrier: true} + + ctx, cancel := context.WithCancel(context.Background()) + actors := &radvActorSet{} + t.Cleanup(func() { + cancel() + actors.wg.Wait() + }) + + reconcileRadvActors(ctx, actors) + radvActorFailed(actors, awaitRadvFailure(t, actors)) + if got := actors.pending[radvTestIface].failures; got != 1 { + t.Fatalf("failures after an ordinary failed start = %d, want 1", got) + } + + // Started again once the backoff elapses, this time failing on an + // address that is not ready yet. + env.now = actors.pending[radvTestIface].retryAt + reconcileRadvActors(ctx, actors) + awaitRadvFailure(t, actors) + radvActorFailed(actors, radvActorFailure{ + iface: radvTestIface, + err: fmt.Errorf("open NDP connection: %w", radv.ErrAddrNotReady), + }) + + p := actors.pending[radvTestIface] + if p.failures != 1 { + t.Errorf("failures after an address-not-ready start = %d, want it unchanged at 1", p.failures) + } + reconcileRadvActors(ctx, actors) + if _, running := actors.cancel[radvTestIface]; !running { + t.Errorf("actor on %q not retried on the next reconcile after an address-not-ready start", radvTestIface) + } +} diff --git a/internal/plumbing/radv/actor.go b/internal/plumbing/radv/actor.go index fac8cad6f..f94bf3e88 100644 --- a/internal/plumbing/radv/actor.go +++ b/internal/plumbing/radv/actor.go @@ -6,37 +6,59 @@ package radv import ( "context" + "errors" "fmt" "log/slog" "net" "net/netip" "sync" + "syscall" "time" "github.com/mdlayher/ndp" + "golang.org/x/net/ipv6" ) +// ErrAddrNotReady is wrapped by RunActor's error when the interface has no +// usable link-local address yet: the kernel has not assigned one, or duplicate +// address detection still holds it tentative and the kernel refuses to bind +// it. Both clear on their own within moments of the interface gaining carrier, +// so a caller should retry soon rather than count it as a failure. +var ErrAddrNotReady = errors.New("link-local address not ready") + +// raWriter is the part of *ndp.Conn runActorLoop sends through, so a test can +// record what the loop sends and when. +type raWriter interface { + WriteTo(m ndp.Message, cm *ipv6.ControlMessage, dst netip.Addr) error +} + // RunActor owns one tap attachment's whole Router Advertisement lifecycle for // as long as ctx lives: it sends unsolicited advertisements on the jittered // schedule, and replies to solicitations so a freshly booted or reconnected // guest need not wait out a full resend cycle. // -// Both jobs share one connection and one last-sent clock, so a solicited reply -// also reschedules the next unsolicited send rather than the guest receiving a -// redundant advertisement moments later. +// It sends the first advertisement as soon as the connection is open, then +// MaxInitialRtrAdvertisements-1 more MinDelayBetweenRAs apart, so a guest gets +// its default route without having to solicit one. Both jobs share one +// connection and one last-sent clock, so a solicited reply also reschedules the +// next unsolicited send rather than the guest receiving a redundant +// advertisement moments later. A solicited reply counts toward the initial +// burst, which RFC 4861 section 6.2.4 permits, so a guest that solicits early +// may see fewer than MaxInitialRtrAdvertisements unsolicited ones. // // Callers run one per recorded attachment, starting it when the attachment // appears and cancelling when it disappears or the daemon shuts down. It // returns nil on a clean cancellation; a non-nil error means it never got the // connection open, leaving nothing to clean up and the caller free to retry on -// its next tick. +// its next tick. An error wrapping ErrAddrNotReady means the interface's +// link-local address is not usable yet. func RunActor(ctx context.Context, iface string, mtu int) error { ifi, err := net.InterfaceByName(iface) if err != nil { return fmt.Errorf("look up interface %q: %w", iface, err) } - conn, _, err := ndp.Listen(ifi, ndp.LinkLocal) + conn, err := listen(ifi) if err != nil { return fmt.Errorf("open NDP connection on %q: %w", iface, err) } @@ -62,6 +84,51 @@ func RunActor(ctx context.Context, iface string, mtu int) error { return nil } +// listen opens the NDP connection on ifi's link-local address. ndp.Listen +// reports a missing address only as an untyped error, so the address is looked +// for here first to tell that case apart. +func listen(ifi *net.Interface) (*ndp.Conn, error) { + addrs, err := ifi.Addrs() + if err != nil { + return nil, fmt.Errorf("list addresses: %w", err) + } + if !hasLinkLocal(addrs) { + return nil, fmt.Errorf("no IPv6 link-local address assigned: %w", ErrAddrNotReady) + } + + conn, _, err := ndp.Listen(ifi, ndp.LinkLocal) + if err != nil { + // The kernel refuses to bind an address that duplicate address + // detection still holds tentative. + return nil, addrNotReady(err) + } + return conn, nil +} + +// addrNotReady wraps err in ErrAddrNotReady when it is the kernel refusing to +// bind an address, however deeply the net package wrapped EADDRNOTAVAIL, and +// returns it unchanged otherwise. +func addrNotReady(err error) error { + if errors.Is(err, syscall.EADDRNOTAVAIL) { + return fmt.Errorf("%w: %w", ErrAddrNotReady, err) + } + return err +} + +// hasLinkLocal reports whether addrs holds an IPv6 link-local unicast address. +func hasLinkLocal(addrs []net.Addr) bool { + for _, a := range addrs { + ipn, ok := a.(*net.IPNet) + if !ok { + continue + } + if ipn.IP.To4() == nil && ipn.IP.IsLinkLocalUnicast() { + return true + } + } + return false +} + // readSolicitations is the blocking read loop, on its own goroutine since the // read blocks and so cannot share a select with the resend timer. It exits as // soon as the read errors, which is what happens once the main loop closes the @@ -94,19 +161,26 @@ func readSolicitations(wg *sync.WaitGroup, conn *ndp.Conn, rsCh chan<- netip.Add // setup and teardown wrapper. See RunActor for the combined behavior it // implements. func runActorLoop( - ctx context.Context, conn *ndp.Conn, iface string, mtu int, hwAddr net.HardwareAddr, rsCh <-chan netip.Addr, + ctx context.Context, conn raWriter, iface string, mtu int, hwAddr net.HardwareAddr, rsCh <-chan netip.Addr, ) { - resendTimer := time.NewTimer(NextInterval()) + // Fires at once: the first advertisement goes out as soon as the + // connection is open. + resendTimer := time.NewTimer(0) defer resendTimer.Stop() var lastSent time.Time + sent := 0 send := func(dst netip.Addr) { ra := buildAdvertisement(mtu, hwAddr) if err := conn.WriteTo(ra, nil, dst); err != nil { + // A failed write does not use up a slot in the initial burst, but + // the timer is still rescheduled so the next attempt is not lost. slog.Warn("Failed to send router advertisement", "err", err, "hostInterface", iface, "dst", dst) + } else { + lastSent = time.Now() + sent++ } - lastSent = time.Now() - resendTimer.Reset(NextInterval()) + resendTimer.Reset(nextUnsolicitedDelay(sent)) } for { diff --git a/internal/plumbing/radv/actor_test.go b/internal/plumbing/radv/actor_test.go index 208671118..dc52b843a 100644 --- a/internal/plumbing/radv/actor_test.go +++ b/internal/plumbing/radv/actor_test.go @@ -5,11 +5,164 @@ package radv import ( + "context" + "errors" + "net" "net/netip" + "os" + "sync" + "syscall" "testing" "time" + + "github.com/mdlayher/ndp" + "golang.org/x/net/ipv6" ) +// recordingWriter is a raWriter that records when each advertisement was +// sent and where to. +type recordingWriter struct { + mu sync.Mutex + sends []recordedSend +} + +type recordedSend struct { + at time.Time + dst netip.Addr +} + +func (w *recordingWriter) WriteTo(m ndp.Message, _ *ipv6.ControlMessage, dst netip.Addr) error { + if _, ok := m.(*ndp.RouterAdvertisement); !ok { + return nil + } + w.mu.Lock() + defer w.mu.Unlock() + w.sends = append(w.sends, recordedSend{at: time.Now(), dst: dst}) + return nil +} + +func (w *recordingWriter) snapshot() []recordedSend { + w.mu.Lock() + defer w.mu.Unlock() + return append([]recordedSend(nil), w.sends...) +} + +// shrinkRadvTimers scales the protocol delays down so a test of the actor +// loop runs in milliseconds, keeping the regular interval far out of reach. +func shrinkRadvTimers(t *testing.T, minDelay time.Duration) { + t.Helper() + origMin, origMax := MinRtrAdvInterval, MaxRtrAdvInterval + origDelay, origRADelay := MinDelayBetweenRAs, MaxRADelayTime + MinRtrAdvInterval, MaxRtrAdvInterval = time.Hour, 2*time.Hour + MinDelayBetweenRAs, MaxRADelayTime = minDelay, time.Millisecond + t.Cleanup(func() { + MinRtrAdvInterval, MaxRtrAdvInterval = origMin, origMax + MinDelayBetweenRAs, MaxRADelayTime = origDelay, origRADelay + }) +} + +// runLoopFor runs runActorLoop against w for d and returns once it has exited. +func runLoopFor(t *testing.T, w raWriter, rsCh <-chan netip.Addr, d time.Duration) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), d) + defer cancel() + hwAddr := net.HardwareAddr{0x02, 0, 0, 0, 0, 1} + runActorLoop(ctx, w, "tap-test", 1500, hwAddr, rsCh) +} + +// TestRunActorLoop_InitialBurst covers #828: an actor advertises the moment it +// starts, without waiting for a solicitation, then sends the rest of the +// RFC 4861 initial burst no closer together than MinDelayBetweenRAs, then +// falls back to the regular interval. +func TestRunActorLoop_InitialBurst(t *testing.T) { + const minDelay = 100 * time.Millisecond + shrinkRadvTimers(t, minDelay) + + w := &recordingWriter{} + start := time.Now() + runLoopFor(t, w, make(chan netip.Addr), MaxInitialRtrAdvertisements*minDelay+minDelay) + + sends := w.snapshot() + if len(sends) != MaxInitialRtrAdvertisements { + t.Fatalf("sent %d advertisements, want %d (the initial burst, then the regular interval)", + len(sends), MaxInitialRtrAdvertisements) + } + if first := sends[0].at.Sub(start); first >= 2*minDelay { + t.Errorf("first advertisement sent %v after start, want it immediately", first) + } + for i, s := range sends { + if s.dst != allNodesMulticast { + t.Errorf("advertisement %d sent to %v, want %v", i, s.dst, allNodesMulticast) + } + if i == 0 { + continue + } + if gap := s.at.Sub(sends[i-1].at); gap < minDelay { + t.Errorf("advertisement %d sent %v after the previous one, want at least %v", i, gap, minDelay) + } + } +} + +// TestRunActorLoop_SolicitationDuringBurstIsRateLimited checks a solicitation +// arriving right after the first advertisement gets no extra reply inside +// MinDelayBetweenRAs. +func TestRunActorLoop_SolicitationDuringBurstIsRateLimited(t *testing.T) { + const minDelay = 200 * time.Millisecond + shrinkRadvTimers(t, minDelay) + + w := &recordingWriter{} + rsCh := make(chan netip.Addr, 1) + rsCh <- netip.MustParseAddr("fe80::2") + runLoopFor(t, w, rsCh, minDelay/2) + + if sends := w.snapshot(); len(sends) != 1 { + t.Fatalf("sent %d advertisements within %v of start, want 1", len(sends), minDelay/2) + } +} + +func TestNextUnsolicitedDelay(t *testing.T) { + for sent := 1; sent < MaxInitialRtrAdvertisements; sent++ { + if got := nextUnsolicitedDelay(sent); got != MinDelayBetweenRAs { + t.Errorf("nextUnsolicitedDelay(%d) = %v, want %v", sent, got, MinDelayBetweenRAs) + } + } + for _, sent := range []int{MaxInitialRtrAdvertisements, MaxInitialRtrAdvertisements + 5} { + got := nextUnsolicitedDelay(sent) + if got < MinRtrAdvInterval || got >= MaxRtrAdvInterval { + t.Errorf("nextUnsolicitedDelay(%d) = %v, want in [%v, %v)", sent, got, MinRtrAdvInterval, MaxRtrAdvInterval) + } + } +} + +func TestHasLinkLocal(t *testing.T) { + ipnet := func(s string) net.Addr { + _, n, err := net.ParseCIDR(s) + if err != nil { + t.Fatal(err) + } + n.IP = net.ParseIP(s[:len(s)-len("/64")]) + return n + } + + tests := []struct { + name string + addrs []net.Addr + want bool + }{ + {"None", nil, false}, + {"GlobalOnly", []net.Addr{ipnet("2001:db8::1/64")}, false}, + {"IPv4LinkLocalOnly", []net.Addr{&net.IPNet{IP: net.IPv4(169, 254, 0, 1).To4(), Mask: net.CIDRMask(16, 32)}}, false}, + {"LinkLocal", []net.Addr{ipnet("2001:db8::1/64"), ipnet("fe80::1/64")}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := hasLinkLocal(tt.addrs); got != tt.want { + t.Errorf("hasLinkLocal() = %v, want %v", got, tt.want) + } + }) + } +} + func TestRateLimited(t *testing.T) { base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) @@ -52,3 +205,17 @@ func TestResponseDestination(t *testing.T) { }) } } + +// TestAddrNotReady checks EADDRNOTAVAIL is recognised through the wrapping the +// net package puts around a failed bind. +func TestAddrNotReady(t *testing.T) { + bind := &net.OpError{Op: "listen", Err: os.NewSyscallError("bind", syscall.EADDRNOTAVAIL)} + if got := addrNotReady(bind); !errors.Is(got, ErrAddrNotReady) || !errors.Is(got, syscall.EADDRNOTAVAIL) { + t.Errorf("addrNotReady(%v) = %v, want it to wrap ErrAddrNotReady and EADDRNOTAVAIL", bind, got) + } + + other := &net.OpError{Op: "listen", Err: os.NewSyscallError("bind", syscall.EACCES)} + if got := addrNotReady(other); errors.Is(got, ErrAddrNotReady) || !errors.Is(got, error(other)) { + t.Errorf("addrNotReady(%v) = %v, want it returned unchanged", other, got) + } +} diff --git a/internal/plumbing/radv/radv.go b/internal/plumbing/radv/radv.go index 78a69312f..b068f057d 100644 --- a/internal/plumbing/radv/radv.go +++ b/internal/plumbing/radv/radv.go @@ -87,6 +87,27 @@ var ( MaxRADelayTime = 500 * time.Millisecond ) +// MaxInitialRtrAdvertisements is how many advertisements an actor sends +// MinDelayBetweenRAs apart when it starts, before falling back to the jittered +// NextInterval schedule. RFC 4861 section 6.2.4 allows up to three, at intervals +// of at most 16 seconds. +// +// A guest learns its default route only from an RA, and one that solicited +// before the actor was listening has lost that solicitation, so the first +// advertisement goes out the moment the actor starts and the burst covers a +// guest whose network stack was not yet up to receive it. A solicited reply +// counts toward the burst, as the RFC permits. +const MaxInitialRtrAdvertisements = 3 + +// nextUnsolicitedDelay returns the delay before the next unsolicited RA, given +// how many advertisements this actor has sent so far. +func nextUnsolicitedDelay(sent int) time.Duration { + if sent < MaxInitialRtrAdvertisements { + return MinDelayBetweenRAs + } + return NextInterval() +} + // nextResponseDelay returns a random delay in [0, MaxRADelayTime) to wait // before replying to a Router Solicitation. func nextResponseDelay() time.Duration { diff --git a/internal/plumbing/sysctl/sysctl.go b/internal/plumbing/sysctl/sysctl.go index 0f658a33b..481f836cd 100644 --- a/internal/plumbing/sysctl/sysctl.go +++ b/internal/plumbing/sysctl/sysctl.go @@ -163,19 +163,37 @@ func sysctlName(segments []string) string { return strings.Join(parts, ".") } +// tapSettings are the sysctls ConfigureTapSysctls applies to a tap's host side. +// +// accept_dad is off because duplicate address detection holds the tap's +// link-local address tentative for about a second after its VMM opens it, and +// the node daemon's Router Advertisement sender cannot bind a tentative +// address. A tap is a point-to-point link to one guest, so the address has +// nothing to collide with. The tap is up but without carrier when this runs, +// and the kernel assigns the link-local address only once carrier appears, so +// the setting is in place before the address exists. +var tapSettings = []struct { + format string + value string +}{ + {"net.ipv4.conf.%s.rp_filter", "0"}, + {"net.ipv6.conf.%s.rp_filter", "0"}, + {"net.ipv4.conf.%s.forwarding", "1"}, + {"net.ipv6.conf.%s.forwarding", "1"}, + {"net.ipv6.conf.%s.accept_dad", "0"}, +} + // ConfigureTapSysctls applies the sysctls appropriate for a tap connected to a // VM. Unlike ConfigureInterfaceSysctls it skips proxy ARP and NDP, the VM // handling its own address resolution. A sysctl that does not exist is skipped // silently. func ConfigureTapSysctls(iface string) error { - settings := map[string]string{ - fmt.Sprintf("net.ipv4.conf.%s.rp_filter", iface): "0", - fmt.Sprintf("net.ipv6.conf.%s.rp_filter", iface): "0", - fmt.Sprintf("net.ipv4.conf.%s.forwarding", iface): "1", - fmt.Sprintf("net.ipv6.conf.%s.forwarding", iface): "1", - } - for key, val := range settings { - _ = gosysctl.Set(key, val) // silently skip missing entries + for _, entry := range tapSettings { + name := fmt.Sprintf(entry.format, iface) + if err := gosysctl.Set(name, entry.value); err != nil { + // Non-fatal: a sysctl that does not exist is skipped. + logger.Debug("tap sysctl write failed", "sysctl", name, "err", err) + } } return nil } diff --git a/internal/plumbing/sysctl/sysctl_test.go b/internal/plumbing/sysctl/sysctl_test.go index 782cae269..45f428974 100644 --- a/internal/plumbing/sysctl/sysctl_test.go +++ b/internal/plumbing/sysctl/sysctl_test.go @@ -75,6 +75,21 @@ func TestInterfaceSettings_hasAllEntries(t *testing.T) { } } +func TestTapSettings_disablesDAD(t *testing.T) { + // The Router Advertisement sender cannot bind a tentative link-local + // address, so a tap must come up with duplicate address detection off + // (#828). + for _, entry := range tapSettings { + if entry.format == "net.ipv6.conf.%s.accept_dad" { + if entry.value != "0" { + t.Errorf("tapSettings accept_dad = %q, want \"0\"", entry.value) + } + return + } + } + t.Error("tapSettings does not set net.ipv6.conf..accept_dad") +} + // fakeProcSys builds a procfs sysctl root under a temporary directory holding // each of the given sysctls, by path segment, set to value with file mode // mode, and points the FIB-lookup helpers at it for the rest of the test.