From 15b667f3bfa870a11ace5e7d6d27a38f7d789eec Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 30 Nov 2026 19:16:19 -0500 Subject: [PATCH 1/2] fix(transport): Refuse invalid sides in the gateway and NAT galactic-gateway and galactic-nat logged a transport side that failed validation and stayed Ready. Both now resolve their configured logical interfaces through internal/plumbing/transport before anything is expanded to hook targets or attached: - At startup a transport.ValidationError fails the process with the side, interface and rule, as galactic-cni does. A missing interface now fails as interface_not_found instead of an unnamed netlink error. - On a later link or route change a failure turns the readiness service NOT_SERVING, keeps the current attachments, and is logged and counted once until it changes or clears (Tracker.Record). galactic-nat reported its bond members as sides because it resolved the list natattach.ResolveUplinks had already expanded. SelectUplinks now returns the logical uplinks the shard validates, reports and fills vlan_egress from; UplinkTargets expands them for attachment and the uplink sysctls only. An uplink listed twice is refused as sides_overlap. Fixes #1546 Fixes #1547 --- cmd/galactic-gateway/gateway.go | 186 ++++++++----- cmd/galactic-gateway/root.go | 6 +- cmd/galactic-gateway/transport_root_test.go | 133 ++++++++++ cmd/galactic-gateway/transport_test.go | 225 ++++++++++++++++ cmd/galactic-nat/nat.go | 202 ++++++++++---- cmd/galactic-nat/root.go | 22 +- cmd/galactic-nat/transport_root_test.go | 175 ++++++++++++ cmd/galactic-nat/transport_test.go | 248 ++++++++++++++++++ docs/gateway/configuration.md | 12 + docs/nat/configuration.md | 15 ++ internal/plumbing/ebpf/natattach/uplinks.go | 54 ++-- .../plumbing/ebpf/natattach/uplinks_test.go | 24 ++ .../plumbing/ebpf/vlanegress/vlanegress.go | 8 +- internal/plumbing/transport/report.go | 59 +++++ internal/plumbing/transport/transport_test.go | 40 +++ 15 files changed, 1271 insertions(+), 138 deletions(-) create mode 100644 cmd/galactic-gateway/transport_root_test.go create mode 100644 cmd/galactic-gateway/transport_test.go create mode 100644 cmd/galactic-nat/transport_root_test.go create mode 100644 cmd/galactic-nat/transport_test.go diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 3e5820324..3da0b6c6f 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -15,6 +15,7 @@ import ( "github.com/cilium/ebpf" "github.com/cilium/ebpf/link" + "go.miloapis.com/instrumentation/labels" "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/config" @@ -160,6 +161,14 @@ func installGateway( ipv4 *ipv4Forwarding, coverage *datapathCoverage, build func(*edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error), ) error { + // Each side's logical interface must pass the transport contract before + // anything is resolved to hook targets or attached. A side that breaks a + // rule, including one that does not exist, fails startup naming the side, + // the interface and the rule. + if invalid, _ := syncVLANEgress(nil, publicInterface, internalInterfaces); invalid != nil { + return fmt.Errorf("edge gateway interfaces break the transport contract: %w", invalid) + } + withLB := publicInterface != "" var targets []string if withLB { @@ -297,43 +306,57 @@ func installGateway( missing = append(missing, returnSet.reconcile(ctx, returnTargets)...) } coverage.set(missing) - syncVLANEgress(objs.VlanEgress, publicInterface, internalInterfaces) + // A side that broke a rule since the check above turns readiness off, as + // a later re-resolution would. + if invalid, _ := syncVLANEgress(objs.VlanEgress, publicInterface, internalInterfaces); invalid != nil { + coverage.setTransport(invalid) + } go watchTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage, ipv4, objs.VlanEgress) return nil } -// syncVLANEgress fills edgedsr.c's vlan_egress from the gateway's configured -// sides: the public interface and every internal interface that is a VLAN -// netdevice. A route the datapath resolves through one of them leaves through -// its lower device with that side's tag pushed in XDP, since a native redirect -// to a VLAN netdevice transmits nothing. A side that cannot be resolved keeps -// no row and is reported; the attachment itself reports a missing interface. +// syncVLANEgress resolves the gateway's configured sides through the +// transport contract, publishes them through gatewayTransport, and fills +// edgedsr.c's vlan_egress from them: the public interface and every internal +// interface that is a VLAN netdevice. A route the datapath resolves through +// one of them leaves through its lower device with that side's tag pushed in +// XDP, since a native redirect to a VLAN netdevice transmits nothing. A side +// that cannot be resolved keeps no row. A nil map skips it and only resolves +// and reports. // -// Every call publishes the derived sides through gatewayTransport: the first -// logs each side's mode, VLAN ID, parent and members, later ones log and count -// what changed, such as a VLAN recreated with a new ifindex. -func syncVLANEgress(m *ebpf.Map, publicInterface string, internalInterfaces []string) { - set, ifindexes, err := vlanegress.Resolve( +// The first call logs each side's mode, VLAN ID, parent and members, later +// ones log and count what changed, such as a VLAN recreated with a new +// ifindex. A failure is logged and counted once while it persists. +// +// It returns the contract rule a side broke, nil when none, and whether that +// changed since the previous call. +func syncVLANEgress(m *ebpf.Map, publicInterface string, internalInterfaces []string, +) (*transport.ValidationError, bool) { + set, ifindexes, err := vlanegress.ResolveWith(transportLinks, vlanegress.Side{Side: transport.SidePublic, Names: []string{publicInterface}}, vlanegress.Side{Side: transport.SideFabric, Names: internalInterfaces}, ) + invalid, changed := gatewayTransport.Record(set, err) if err != nil { - gatewayTransport.Fail(err) slog.Warn("Cannot resolve every edge gateway interface for VLAN egress; routes through the ones "+ "left out are redirected to the VLAN device as the FIB names it", "err", err) } - if err := vlanegress.Sync(m, set, ifindexes); err != nil { - slog.Warn("Cannot update the edge gateway's VLAN egress map", "err", err) - } - if set != nil { - gatewayTransport.Observe(set) + if m != nil { + if err := vlanegress.Sync(m, set, ifindexes); err != nil { + slog.Warn("Cannot update the edge gateway's VLAN egress map", "err", err) + } } + return invalid, changed } // gatewayTransport publishes the gateway's derived transport sides. var gatewayTransport = transport.NewTracker("galactic-gateway") +// transportLinks is the netlink view the sides are resolved through; tests +// substitute a fake. +var transportLinks = transport.Netlink + // targetSet keeps one of the gateway's programs on a set of interfaces and // reports the ones it does not cover: xdpattach.Set in direct mode, // xdpattach.DispatchSet in dispatch mode. @@ -532,14 +555,17 @@ func turnOffDatapath(ctx context.Context, pinDir string, slots ...xdpdispatch.Sl } // datapathCoverage is which of the datapath's resolved targets it is not -// attached to, kept by watchTargets and read by the readiness reporter. Its -// onChange, when set, is called whenever that changes, from watchTargets' -// goroutine. +// attached to, and the transport contract rule a configured side breaks, kept +// by watchTargets and read by the readiness reporter. Its onChange, when set, +// is called whenever either changes, from watchTargets' goroutine. type datapathCoverage struct { onChange func() mu sync.Mutex missing []string + // invalid is the rule a side broke at the latest re-resolution, nil + // while every side passes. + invalid *transport.ValidationError // configured is the targets whose forwarding sysctls have been applied. // Only watchTargets touches it once setup returns. configured map[string]bool @@ -556,6 +582,31 @@ func (c *datapathCoverage) Missing() []string { return slices.Clone(c.missing) } +// TransportInvalid reports the transport contract rule a configured side +// broke at the latest re-resolution, nil while every side passes. +func (c *datapathCoverage) TransportInvalid() *transport.ValidationError { + c.mu.Lock() + defer c.mu.Unlock() + return c.invalid +} + +// setTransport records invalid as the rule a side breaks, nil for none, and +// calls onChange. +func (c *datapathCoverage) setTransport(invalid *transport.ValidationError) { + c.mu.Lock() + c.invalid = invalid + c.mu.Unlock() + if invalid != nil { + slog.Error("Edge gateway interfaces break the transport contract; reporting not ready", + "side", string(invalid.Side), "interface", invalid.Interface, labels.Reason, string(invalid.Rule)) + } else { + slog.Info("Edge gateway interfaces pass the transport contract again") + } + if c.onChange != nil { + c.onChange() + } +} + func (c *datapathCoverage) set(missing []string) { c.mu.Lock() changed := !slices.Equal(c.missing, missing) @@ -599,52 +650,67 @@ func (c *datapathCoverage) configure(targets []string) []string { // link or route change, until ctx is done, and attaches each set's program to // any resolved target it does not hold yet. A nil set is skipped. A // resolution failure, such as a bond in the moment between losing a member and -// enslaving its replacement, keeps every attachment and skips that pass. +// enslaving its replacement, keeps every attachment and skips that pass. So +// does a side that breaks the transport contract, which coverage then reports +// as not ready until the side passes again. func watchTargets(ctx context.Context, publicInterface string, internalInterfaces []string, publicSet, returnSet targetSet, coverage *datapathCoverage, ipv4 *ipv4Forwarding, vlanEgress *ebpf.Map, ) { xdpattach.OnNetlinkChange(ctx, func() { - syncVLANEgress(vlanEgress, publicInterface, internalInterfaces) - var ( - targets []string - err error - ) - if publicSet != nil { - if targets, err = edgeattach.ResolveTargets(publicInterface); err != nil { - slog.Warn("Re-resolve edge gateway public interface failed; keeping current attachments", - "interface", publicInterface, "err", err) - return - } - } - var returnTargets []string - if returnSet != nil { - if returnTargets, err = resolveReturnTargets(internalInterfaces); err != nil { - slog.Warn("Re-resolve edge gateway internal interfaces failed; keeping current attachments", - "err", err) - return - } - if overlap := publicReturnOverlap(targets, returnTargets); len(overlap) > 0 { - slog.Warn("Internal interfaces now resolve to public ones; keeping the return program off them", - "interfaces", overlap) - returnTargets = slices.DeleteFunc(returnTargets, func(t string) bool { return slices.Contains(overlap, t) }) - } - } + resyncTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage, ipv4, vlanEgress) + }) +} - // A target whose forwarding sysctls failed is left out of the set and - // counted missing; configure retries it on the next pass. - var missing []string - if publicSet != nil { - ready := coverage.configure(targets) - missing = append(publicSet.reconcile(ctx, ready), uncovered(targets, ready)...) +// resyncTargets is one watchTargets pass. +func resyncTargets(ctx context.Context, publicInterface string, internalInterfaces []string, + publicSet, returnSet targetSet, coverage *datapathCoverage, ipv4 *ipv4Forwarding, vlanEgress *ebpf.Map, +) { + invalid, changed := syncVLANEgress(vlanEgress, publicInterface, internalInterfaces) + if changed { + coverage.setTransport(invalid) + } + if invalid != nil { + return + } + var ( + targets []string + err error + ) + if publicSet != nil { + if targets, err = edgeattach.ResolveTargets(publicInterface); err != nil { + slog.Warn("Re-resolve edge gateway public interface failed; keeping current attachments", + "interface", publicInterface, "err", err) + return } - if returnSet != nil { - ready := coverage.configure(returnTargets) - missing = append(missing, returnSet.reconcile(ctx, ready)...) - missing = append(missing, uncovered(returnTargets, ready)...) + } + var returnTargets []string + if returnSet != nil { + if returnTargets, err = resolveReturnTargets(internalInterfaces); err != nil { + slog.Warn("Re-resolve edge gateway internal interfaces failed; keeping current attachments", + "err", err) + return } - coverage.set(dedupe(missing)) - ipv4.track(append(slices.Clone(targets), returnTargets...)) - }) + if overlap := publicReturnOverlap(targets, returnTargets); len(overlap) > 0 { + slog.Warn("Internal interfaces now resolve to public ones; keeping the return program off them", + "interfaces", overlap) + returnTargets = slices.DeleteFunc(returnTargets, func(t string) bool { return slices.Contains(overlap, t) }) + } + } + + // A target whose forwarding sysctls failed is left out of the set and + // counted missing; configure retries it on the next pass. + var missing []string + if publicSet != nil { + ready := coverage.configure(targets) + missing = append(publicSet.reconcile(ctx, ready), uncovered(targets, ready)...) + } + if returnSet != nil { + ready := coverage.configure(returnTargets) + missing = append(missing, returnSet.reconcile(ctx, ready)...) + missing = append(missing, uncovered(returnTargets, ready)...) + } + coverage.set(dedupe(missing)) + ipv4.track(append(slices.Clone(targets), returnTargets...)) } // dedupe drops repeated names, keeping the first of each. diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index b1faf6bea..ee5c2562b 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -262,14 +262,14 @@ func runCmd(cfg *config.GatewayConfig) error { } // followCoverage keeps the readiness service SERVING only while coverage -// reports no missing interface, until ctx is done: once at the start, then on -// every nudge from changed. +// reports no missing interface and no side breaking the transport contract, +// until ctx is done: once at the start, then on every nudge from changed. func followCoverage(ctx context.Context, coverage *datapathCoverage, healthSrv *grpchealth.Server, changed <-chan struct{}, ) { for { status := grpc_health_v1.HealthCheckResponse_SERVING - if len(coverage.Missing()) > 0 { + if len(coverage.Missing()) > 0 || coverage.TransportInvalid() != nil { status = grpc_health_v1.HealthCheckResponse_NOT_SERVING } healthSrv.SetServingStatus(config.GRPCReadinessService, status) diff --git a/cmd/galactic-gateway/transport_root_test.go b/cmd/galactic-gateway/transport_root_test.go new file mode 100644 index 000000000..a327ce850 --- /dev/null +++ b/cmd/galactic-gateway/transport_root_test.go @@ -0,0 +1,133 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "context" + "errors" + "testing" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/transport" +) + +// Synthetic interface names, created in a private network namespace. +const ( + kBond = "kbond0" + kMember1 = "km0" + kMember2 = "km1" + kNIC = "knic0" + kVLAN = "knic0.100" + kVLANZero = "knic0.0" + kVLANQinQ = "knic0.ad" + kStacked = "kstack" + kBridge = "kbr0" + kOnBridge = "kbr0.100" + kMissing = "kmissing" +) + +// inNetNS runs f in a fresh network namespace that is removed afterwards. +func inNetNS(t *testing.T, f func()) { + t.Helper() + n, err := testutils.NewNS() + if err != nil { + t.Fatalf("create netns: %v", err) + } + t.Cleanup(func() { + _ = n.Close() + _ = testutils.UnmountNS(n) + }) + if err := n.Do(func(ns.NetNS) error { f(); return nil }); err != nil { + t.Fatal(err) + } +} + +func addKernelLink(t *testing.T, l netlink.Link) netlink.Link { + t.Helper() + if err := netlink.LinkAdd(l); err != nil { + t.Fatalf("add %s %q: %v", l.Type(), l.Attrs().Name, err) + } + got, err := netlink.LinkByName(l.Attrs().Name) + if err != nil { + t.Fatalf("find %q: %v", l.Attrs().Name, err) + } + return got +} + +func addKernelVLAN(t *testing.T, name string, parent netlink.Link, vid int, proto netlink.VlanProtocol) { + t.Helper() + addKernelLink(t, &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: name, ParentIndex: parent.Attrs().Index}, + VlanId: vid, + VlanProtocol: proto, + }) +} + +// kernelTransportTopology builds, in the current netns, a bond of two veths, +// a veth "NIC", a bridge, and on them every VLAN the kernel accepts that the +// transport contract refuses: ID 0, 802.1ad, one stacked on another VLAN, and +// one on a bridge. +func kernelTransportTopology(t *testing.T) { + t.Helper() + b := netlink.NewLinkBond(netlink.LinkAttrs{Name: kBond}) + b.Mode = netlink.BOND_MODE_802_3AD + bondLink := addKernelLink(t, b) + for _, m := range []string{kMember1, kMember2} { + ml := addKernelLink(t, &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: m}, PeerName: m + "p"}) + if err := netlink.LinkSetBondSlave(ml, bondLink.(*netlink.Bond)); err != nil { + t.Fatalf("enslave %s: %v", m, err) + } + } + nicLink := addKernelLink(t, &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: kNIC}, PeerName: kNIC + "p"}) + brLink := addKernelLink(t, &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: kBridge}}) + q := netlink.VLAN_PROTOCOL_8021Q + addKernelVLAN(t, kVLANZero, nicLink, 0, q) + addKernelVLAN(t, kVLANQinQ, nicLink, 200, netlink.VLAN_PROTOCOL_8021AD) + addKernelVLAN(t, kVLAN, nicLink, 100, q) + vlanLink, err := netlink.LinkByName(kVLAN) + if err != nil { + t.Fatal(err) + } + addKernelVLAN(t, kStacked, vlanLink, 300, q) + addKernelVLAN(t, kOnBridge, brLink, 100, q) +} + +// TestInstallGatewayKernelTransport runs the gateway's startup check against +// real kernel devices (#1546): every refused side fails startup with its side +// and rule, before anything is attached. +func TestInstallGatewayKernelTransport(t *testing.T) { + requireRoot(t) + orig := gatewayTransport + t.Cleanup(func() { gatewayTransport = orig }) + inNetNS(t, func() { + kernelTransportTopology(t) + for _, tt := range []struct { + public string + internal []string + side transport.Side + rule transport.Rule + }{ + {kMissing, nil, transport.SidePublic, transport.RuleNotFound}, + {kVLANZero, []string{kBond}, transport.SidePublic, transport.RuleVLANID}, + {kBond, []string{kVLANQinQ}, transport.SideFabric, transport.RuleVLANProtocol}, + {kStacked, nil, transport.SidePublic, transport.RuleStackedVLAN}, + {kBond, []string{kOnBridge}, transport.SideFabric, transport.RuleParentType}, + {kBond, []string{kBond}, transport.SideFabric, transport.RuleSidesOverlap}, + } { + gatewayTransport = transport.NewTracker("galactic-gateway") + err := installGateway(context.Background(), tt.public, tt.internal, xdpConfig{}, nil, + newDatapathCoverage(nil), nil) + var ve *transport.ValidationError + if !errors.As(err, &ve) || ve.Rule != tt.rule || ve.Side != tt.side { + t.Errorf("installGateway(%q, %v) error = %v, want %s side %s", tt.public, tt.internal, err, + tt.side, tt.rule) + } + t.Logf("%q %v: %v", tt.public, tt.internal, err) + } + }) +} diff --git a/cmd/galactic-gateway/transport_test.go b/cmd/galactic-gateway/transport_test.go new file mode 100644 index 000000000..480ec44d2 --- /dev/null +++ b/cmd/galactic-gateway/transport_test.go @@ -0,0 +1,225 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "testing" + + "github.com/vishvananda/netlink" + grpchealth "google.golang.org/grpc/health" + "google.golang.org/grpc/health/grpc_health_v1" + + "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/transport" +) + +// Synthetic interface names. None is expected to exist on a test host. +const ( + tBond = "tgbond0" + tMember1 = "tgmem1" + tMember2 = "tgmem2" + tNIC = "tgnic0" + tVLAN = "tgnic0.100" + tVLANZero = "tgnic0.0" + tVLANQinQ = "tgnic0.ad" + tStacked = "tgstack" + tBridge = "tgbr0" + tOnBridge = "tgbr0.100" + tMissing = "tgmissing" +) + +// fakeLinks is an in-memory transport.Links. +type fakeLinks []netlink.Link + +func (f fakeLinks) LinkByName(name string) (netlink.Link, error) { + for _, l := range f { + if l.Attrs().Name == name { + return l, nil + } + } + return nil, netlink.LinkNotFoundError{} +} + +func (f fakeLinks) LinkByIndex(index int) (netlink.Link, error) { + for _, l := range f { + if l.Attrs().Index == index { + return l, nil + } + } + return nil, netlink.LinkNotFoundError{} +} + +func (f fakeLinks) LinkList() ([]netlink.Link, error) { return f, nil } + +func fakeVLAN(name string, index, parent, id int, proto netlink.VlanProtocol) *netlink.Vlan { + return &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: name, Index: index, ParentIndex: parent}, + VlanId: id, + VlanProtocol: proto, + } +} + +// topology is a bond with two members, a NIC carrying one valid VLAN and one +// of each VLAN the contract refuses, and a bridge with a VLAN on it. vlanID is +// the valid VLAN's ID, so a test can break it. +func topology(vlanID int) fakeLinks { + return fakeLinks{ + &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Name: tBond, Index: 10}}, + &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: tMember1, Index: 11, MasterIndex: 10}}, + &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: tMember2, Index: 12, MasterIndex: 10}}, + &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: tNIC, Index: 13}}, + fakeVLAN(tVLAN, 14, 13, vlanID, netlink.VLAN_PROTOCOL_8021Q), + fakeVLAN(tVLANZero, 15, 13, 0, netlink.VLAN_PROTOCOL_8021Q), + fakeVLAN(tVLANQinQ, 16, 13, 200, netlink.VLAN_PROTOCOL_8021AD), + fakeVLAN(tStacked, 17, 14, 300, netlink.VLAN_PROTOCOL_8021Q), + &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: tBridge, Index: 18}}, + fakeVLAN(tOnBridge, 19, 18, 100, netlink.VLAN_PROTOCOL_8021Q), + } +} + +// useTransport points the gateway's transport resolution at links and gives +// it a fresh tracker, whose series are removed when the test ends. +func useTransport(t *testing.T, links fakeLinks) { + t.Helper() + origLinks, origTracker := transportLinks, gatewayTransport + transportLinks = links + gatewayTransport = transport.NewTracker("galactic-gateway") + t.Cleanup(func() { + gatewayTransport.Observe(nil) + transportLinks, gatewayTransport = origLinks, origTracker + }) +} + +// captureLog sends the default logger to a buffer for the rest of the test. +func captureLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + orig := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil))) + t.Cleanup(func() { slog.SetDefault(orig) }) + return &buf +} + +// TestInstallGatewayRefusesInvalidTransport covers #1546: a public or +// internal interface that breaks a transport contract rule fails the +// gateway's startup before anything is resolved to hook targets or attached, +// and the log names the side, the interface and the rule. +func TestInstallGatewayRefusesInvalidTransport(t *testing.T) { + tests := []struct { + name string + public string + internal []string + side transport.Side + rule transport.Rule + iface string + }{ + {"missing public interface", tMissing, nil, transport.SidePublic, transport.RuleNotFound, tMissing}, + {"missing internal interface", tBond, []string{tMissing}, transport.SideFabric, transport.RuleNotFound, tMissing}, + {"VLAN ID 0", tVLANZero, []string{tBond}, transport.SidePublic, transport.RuleVLANID, tVLANZero}, + {"802.1ad VLAN", tBond, []string{tVLANQinQ}, transport.SideFabric, transport.RuleVLANProtocol, tVLANQinQ}, + {"stacked VLAN", tStacked, nil, transport.SidePublic, transport.RuleStackedVLAN, tStacked}, + {"unsupported parent type", tOnBridge, nil, transport.SidePublic, transport.RuleParentType, tOnBridge}, + {"public and internal on one interface", tBond, []string{tBond}, transport.SideFabric, + transport.RuleSidesOverlap, tBond}, + {"return path only, VLAN ID 0", "", []string{tVLANZero}, transport.SideFabric, transport.RuleVLANID, tVLANZero}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + useTransport(t, topology(100)) + log := captureLog(t) + + err := installGateway(context.Background(), tt.public, tt.internal, xdpConfig{}, nil, + newDatapathCoverage(nil), nil) + var ve *transport.ValidationError + if !errors.As(err, &ve) { + t.Fatalf("installGateway(%q, %v) error = %v, want a *transport.ValidationError", + tt.public, tt.internal, err) + } + if ve.Side != tt.side || ve.Rule != tt.rule || ve.Interface != tt.iface { + t.Errorf("installGateway(%q, %v) refused %s side %q for %s, want %s side %q for %s", + tt.public, tt.internal, ve.Side, ve.Interface, ve.Rule, tt.side, tt.iface, tt.rule) + } + for _, want := range []string{"reason=" + string(tt.rule), "interface=" + tt.iface, + "side=" + string(tt.side)} { + if !strings.Contains(log.String(), want) { + t.Errorf("log does not contain %q:\n%s", want, log) + } + } + t.Logf("startup error: %v", err) + }) + } +} + +// TestResyncTargetsReportsNotReadyOnInvalidTransport covers the +// re-resolution half of #1546: a side that starts breaking a rule after +// startup turns readiness off, naming the rule, and readiness returns once it +// passes again. +func TestResyncTargetsReportsNotReadyOnInvalidTransport(t *testing.T) { + useTransport(t, topology(100)) + log := captureLog(t) + nudges := 0 + coverage := newDatapathCoverage(func() { nudges++ }) + + readiness := func() grpc_health_v1.HealthCheckResponse_ServingStatus { + t.Helper() + srv := grpchealth.NewServer() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + followCoverage(ctx, coverage, srv, nil) + resp, err := srv.Check(context.Background(), + &grpc_health_v1.HealthCheckRequest{Service: config.GRPCReadinessService}) + if err != nil { + t.Fatalf("readiness check: %v", err) + } + return resp.GetStatus() + } + // No program sets: a pass only resolves and reports the sides. + resync := func() { + resyncTargets(context.Background(), tVLAN, []string{tBond}, nil, nil, coverage, nil, nil) + } + + resync() + if coverage.TransportInvalid() != nil || nudges != 0 { + t.Fatalf("valid sides: TransportInvalid() = %v, nudges = %d; want nil, 0", coverage.TransportInvalid(), nudges) + } + if got := readiness(); got != grpc_health_v1.HealthCheckResponse_SERVING { + t.Errorf("readiness with valid sides = %v, want SERVING", got) + } + + transportLinks = topology(0) + resync() + invalid := coverage.TransportInvalid() + if invalid == nil || invalid.Rule != transport.RuleVLANID || invalid.Side != transport.SidePublic || nudges != 1 { + t.Fatalf("VLAN ID 0: TransportInvalid() = %v, nudges = %d; want public %s, 1", invalid, nudges, + transport.RuleVLANID) + } + if got := readiness(); got != grpc_health_v1.HealthCheckResponse_NOT_SERVING { + t.Errorf("readiness with VLAN ID 0 = %v, want NOT_SERVING", got) + } + if !strings.Contains(log.String(), "reason="+string(transport.RuleVLANID)) { + t.Errorf("log does not name %s:\n%s", transport.RuleVLANID, log) + } + + // The same failure on the next event is neither a change nor logged again. + before := strings.Count(log.String(), "side failed validation") + resync() + if nudges != 1 || strings.Count(log.String(), "side failed validation") != before { + t.Errorf("a persisting failure nudged or logged again: nudges = %d", nudges) + } + + transportLinks = topology(100) + resync() + if coverage.TransportInvalid() != nil || nudges != 2 { + t.Fatalf("fixed side: TransportInvalid() = %v, nudges = %d; want nil, 2", coverage.TransportInvalid(), nudges) + } + if got := readiness(); got != grpc_health_v1.HealthCheckResponse_SERVING { + t.Errorf("readiness once the side passes = %v, want SERVING", got) + } +} diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 6aa85390b..6dcddf894 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -17,6 +17,7 @@ import ( "github.com/cilium/ebpf/link" "github.com/prometheus/client_golang/prometheus" "github.com/safchain/ethtool" + "go.miloapis.com/instrumentation/labels" "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/config" @@ -263,8 +264,13 @@ func (d *natDatapath) Programmed() (controller.EgressShardIdentity, bool) { // one of this node's uplinks and registers this shard's metrics. It returns // the datapath the reconciler programs from the node's EgressShard. // -// Uplinks come from natattach.ResolveUplinks: the override when one is +// Uplinks come from natattach.SelectUplinks: the override when one is // configured, otherwise the same auto-detection the CNI's SRv6 datapath uses. +// Those logical uplinks are the shard's transport sides. Each must pass the +// transport contract (checkUplinkTransport) before anything is attached: one +// that breaks a rule, including one that does not exist, fails startup naming +// the interface and the rule. Only then is each bond expanded to its members +// (natattach.UplinkTargets), which are what the program attaches to. // Every one is attached, not only the one this node's traffic uses today: a // packet arriving on an uplink with no program reaches no translation at all // and leaves untranslated and uncounted, so a multi-homed shard node that @@ -295,7 +301,7 @@ func (d *natDatapath) Programmed() (controller.EgressShardIdentity, bool) { // itself, must survive for the life of this process. func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, onCoverage func()) (*natDatapath, error) { - uplinks, err := waitForUplinks(ctx, cfg.UplinkInterfaces) + logical, uplinks, err := waitForUplinks(ctx, cfg.UplinkInterfaces) if err != nil { return nil, err } @@ -351,7 +357,7 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // from the EgressShard spec -- or clears it, if that shard is gone. d.shardConfig = natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}) d.vlanEgress = objs.VlanEgress - d.syncVLANEgress(uplinks) + d.syncVLANEgress(logical) var ( set *xdpattach.Set @@ -406,37 +412,87 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, return d, nil } -// syncVLANEgress fills nat.c's vlan_egress from the resolved uplinks: every -// one that is a VLAN netdevice, a tagged uplink, gets a row naming its lower -// device and VLAN ID. A translated packet whose route leaves through it is -// then sent through the lower device with that tag pushed in XDP, since a -// native redirect to a VLAN netdevice transmits nothing. +// TransportInvalid reports the transport contract rule the shard's logical +// uplinks broke at their latest re-resolution, nil while they pass. Readiness +// is NOT_SERVING while it is non-nil (followCoverage). +func (d *natDatapath) TransportInvalid() *transport.ValidationError { + return natTransport.Invalid() +} + +// syncVLANEgress resolves the shard's logical uplinks through the transport +// contract, publishes them through natTransport, and fills nat.c's +// vlan_egress from them: every one that is a VLAN netdevice, a tagged uplink, +// gets a row naming its lower device and VLAN ID. A translated packet whose +// route leaves through it is then sent through the lower device with that tag +// pushed in XDP, since a native redirect to a VLAN netdevice transmits +// nothing. A nil vlan_egress map skips the map and only resolves and reports. // -// The uplink list can hold both sides, so each uplink is reported as -// unassigned. Every call publishes them through natTransport: the first logs -// each uplink's mode, VLAN ID, parent and members, later ones log and count -// what changed. -func (d *natDatapath) syncVLANEgress(uplinks []string) { - if d.vlanEgress == nil { - return - } - set, ifindexes, err := vlanegress.Resolve(vlanegress.Side{Side: transport.SideUnassigned, Names: uplinks}) +// uplinks are the logical uplinks (natattach.SelectUplinks), never the bond +// members the program attaches to: a member is not a side, and the contract +// reports the interface the shard was pointed at. The list can hold both +// sides, so each uplink is reported as unassigned. The first call logs each +// uplink's mode, VLAN ID, parent and members, later ones log and count what +// changed. A failure is logged and counted once while it persists. +// +// It returns the contract rule the uplinks broke, nil when none, and whether +// that changed since the previous call. +func (d *natDatapath) syncVLANEgress(uplinks []string) (*transport.ValidationError, bool) { + set, ifindexes, err := resolveUplinkSides(uplinks) + invalid, changed := natTransport.Record(set, err) if err != nil { - natTransport.Fail(err) slog.Warn("Cannot resolve every uplink for VLAN egress; routes through the ones left out are "+ "redirected to the VLAN device as the FIB names it", "err", err) } - if err := vlanegress.Sync(d.vlanEgress, set, ifindexes); err != nil { - slog.Warn("Cannot update the egress translation VLAN egress map", "err", err) + if d.vlanEgress != nil { + if err := vlanegress.Sync(d.vlanEgress, set, ifindexes); err != nil { + slog.Warn("Cannot update the egress translation VLAN egress map", "err", err) + } } - if set != nil { - natTransport.Observe(set) + return invalid, changed +} + +// resolveUplinkSides resolves uplinks through the transport contract +// (vlanegress.Resolve). An uplink listed twice is refused as +// transport.RuleSidesOverlap: whichever side each entry was meant for, one +// netdevice cannot be two of them (contract section 1, rule 2). The first entry +// of a repeated name is still resolved, so its vlan_egress row stays. +func resolveUplinkSides(uplinks []string) (*transport.Set, []int, error) { + var ( + unique []string + errs []error + ) + for _, name := range uplinks { + if slices.Contains(unique, name) { + errs = append(errs, &transport.ValidationError{ + Side: transport.SideUnassigned, Interface: name, Rule: transport.RuleSidesOverlap, + Detail: "listed more than once in the uplink interfaces", + }) + continue + } + unique = append(unique, name) } + set, ifindexes, err := vlanegress.ResolveWith(transportLinks, + vlanegress.Side{Side: transport.SideUnassigned, Names: unique}) + return set, ifindexes, errors.Join(append(errs, err)...) +} + +// checkUplinkTransport resolves and reports the logical uplinks, before +// anything is attached, and returns the contract rule they break, nil when +// none. A netlink failure that is not a contract rule is reported and returns +// nil: the attach path meets it again and fails on its own. +func checkUplinkTransport(uplinks []string) *transport.ValidationError { + set, _, err := resolveUplinkSides(uplinks) + invalid, _ := natTransport.Record(set, err) + return invalid } // natTransport publishes the shard's derived uplink transport state. var natTransport = transport.NewTracker("galactic-nat") +// transportLinks is the netlink view the uplinks are resolved through; tests +// substitute a fake. +var transportLinks = transport.Netlink + // registerUplinkQueueStats exports the per-queue receive counters of every // uplink d currently resolves. A single stalled NIC receive queue drops packets // before the datapath sees them, so drops_total stays flat through it (#673); @@ -527,20 +583,29 @@ func coverageFor(ctx context.Context, set *xdpattach.Set, dispatchSet *xdpattach // resolve. const uplinkRetryInterval = 2 * time.Second -// waitForUplinks resolves this node's uplinks, waiting while auto-detection -// finds none: a shard that starts before its node has learned any fabric -// route is ordinary, and the startup probe bounds the wait. Any other failure, -// and every failure of an override, is returned at once: retrying cannot fix a -// configuration error. -func waitForUplinks(ctx context.Context, override []string) ([]string, error) { +// waitForUplinks selects this node's logical uplinks and expands them to the +// interfaces the program attaches to, waiting while auto-detection finds none: +// a shard that starts before its node has learned any fabric route is +// ordinary, and the startup probe bounds the wait. The logical uplinks are +// checked against the transport contract first (checkUplinkTransport), and a +// broken rule is returned at once, naming the interface and the rule. Any +// other failure, and every failure of an override, is returned at once too: +// retrying cannot fix a configuration error. +func waitForUplinks(ctx context.Context, override []string) (logical, targets []string, err error) { logged := false for { - uplinks, err := natattach.ResolveUplinks(override) + logical, err = natattach.SelectUplinks(override) if err == nil { - return uplinks, nil + if invalid := checkUplinkTransport(logical); invalid != nil { + return nil, nil, fmt.Errorf("uplink interfaces break the transport contract: %w", invalid) + } + targets, err = natattach.UplinkTargets(logical) + } + if err == nil { + return logical, targets, nil } if len(override) != 0 || !errors.Is(err, natattach.ErrNoUplinks) { - return nil, fmt.Errorf("resolve uplink interfaces: %w", err) + return nil, nil, fmt.Errorf("resolve uplink interfaces: %w", err) } if !logged { slog.Info("Waiting for a fabric route to auto-detect an uplink from") @@ -548,7 +613,7 @@ func waitForUplinks(ctx context.Context, override []string) ([]string, error) { } select { case <-ctx.Done(): - return nil, fmt.Errorf("waiting for an uplink to auto-detect: %w", ctx.Err()) + return nil, nil, fmt.Errorf("waiting for an uplink to auto-detect: %w", ctx.Err()) case <-time.After(uplinkRetryInterval): } } @@ -557,38 +622,65 @@ func waitForUplinks(ctx context.Context, override []string) ([]string, error) { // watchUplinks keeps the datapath on every uplink ResolveUplinks returns, for // the life of ctx, re-resolving on every netlink link or route change. cover // brings the ready uplinks under the datapath and returns the ones it covers -// (coverageFor). onCoverage is called whenever the missing uplinks change. +// (coverageFor). onCoverage is called whenever the missing uplinks change, or +// the logical uplinks start or stop breaking the transport contract +// (TransportInvalid). A broken rule keeps the current attachments. func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover func([]string) []string, onCoverage func(), ) { xdpattach.OnNetlinkChange(ctx, func() { - uplinks, err := natattach.ResolveUplinks(override) - if err != nil { - slog.Warn("Re-resolve uplink interfaces failed; keeping current coverage", "err", err) - if d.resolveErrors != nil { - d.resolveErrors.Inc() + d.resyncUplinks(override, cover, onCoverage) + }) +} + +// resyncUplinks is one watchUplinks pass. +func (d *natDatapath) resyncUplinks(override []string, cover func([]string) []string, onCoverage func()) { + logical, err := natattach.SelectUplinks(override) + if err == nil { + invalid, changed := d.syncVLANEgress(logical) + if changed { + if invalid != nil { + slog.Error("Egress translation uplinks break the transport contract; reporting not ready", + "side", string(invalid.Side), "interface", invalid.Interface, labels.Reason, string(invalid.Rule)) + } else { + slog.Info("Egress translation uplinks pass the transport contract again") + } + if onCoverage != nil { + onCoverage() } - return } - d.syncVLANEgress(uplinks) - ready := d.adoptUplinks(uplinks) - - missing := uncovered(uplinks, cover(ready)) - - if !d.setCoverage(uplinks, missing) { + if invalid != nil { return } - switch { - case len(missing) == 0: - slog.Info("Egress translation datapath covers every uplink", "uplinks", uplinks) - default: - slog.Warn("Egress translation datapath does not cover every uplink; traffic arriving on these "+ - "leaves untranslated", "missing", missing) - } - if onCoverage != nil { - onCoverage() + } + var uplinks []string + if err == nil { + uplinks, err = natattach.UplinkTargets(logical) + } + if err != nil { + slog.Warn("Re-resolve uplink interfaces failed; keeping current coverage", "err", err) + if d.resolveErrors != nil { + d.resolveErrors.Inc() } - }) + return + } + ready := d.adoptUplinks(uplinks) + + missing := uncovered(uplinks, cover(ready)) + + if !d.setCoverage(uplinks, missing) { + return + } + switch { + case len(missing) == 0: + slog.Info("Egress translation datapath covers every uplink", "uplinks", uplinks) + default: + slog.Warn("Egress translation datapath does not cover every uplink; traffic arriving on these "+ + "leaves untranslated", "missing", missing) + } + if onCoverage != nil { + onCoverage() + } } // uncovered returns every one of uplinks not in covered, in uplinks' order. diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index 6800876cb..0865ff3a6 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -32,6 +32,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" "go.datum.net/galactic/internal/plumbing/sysctl" + "go.datum.net/galactic/internal/plumbing/transport" ) const ( @@ -182,7 +183,8 @@ func runCmd(cfg *config.NATConfig) error { // followCoverage publishes datapath's uplink coverage until ctx is done: once // at the start, then on every nudge from changed. Readiness is SERVING only -// while no uplink is missing, and each change also sends on events, which +// while no uplink is missing and the uplinks pass the transport contract +// (transportInvalid), and each change also sends on events, which // re-publishes the EgressShard's Ready condition. Both sends coalesce, since // either consumer reads the current state rather than the event. func followCoverage(ctx context.Context, datapath controller.EgressDatapath, healthSrv *grpchealth.Server, @@ -190,7 +192,7 @@ func followCoverage(ctx context.Context, datapath controller.EgressDatapath, hea ) { for { status := grpc_health_v1.HealthCheckResponse_SERVING - if len(datapath.MissingUplinks()) > 0 { + if len(datapath.MissingUplinks()) > 0 || transportInvalid(datapath) != nil { status = grpc_health_v1.HealthCheckResponse_NOT_SERVING } healthSrv.SetServingStatus(config.GRPCReadinessService, status) @@ -207,6 +209,22 @@ func followCoverage(ctx context.Context, datapath controller.EgressDatapath, hea } } +// transportValidity is the datapath's view of whether its logical uplinks +// pass the transport contract. natDatapath implements it; a turned-off +// datapath has no uplinks and does not. +type transportValidity interface { + TransportInvalid() *transport.ValidationError +} + +// transportInvalid returns the transport contract rule datapath's uplinks +// break, nil when they pass or datapath has no uplinks. +func transportInvalid(datapath controller.EgressDatapath) *transport.ValidationError { + if v, ok := datapath.(transportValidity); ok { + return v.TransportInvalid() + } + return nil +} + // newRootCommand builds the root cobra command with all flags and the // application startup logic. func newRootCommand() *cobra.Command { diff --git a/cmd/galactic-nat/transport_root_test.go b/cmd/galactic-nat/transport_root_test.go new file mode 100644 index 000000000..4d1376561 --- /dev/null +++ b/cmd/galactic-nat/transport_root_test.go @@ -0,0 +1,175 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "context" + "errors" + "io" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" + "github.com/vishvananda/netlink" + "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/plumbing/transport" +) + +// Synthetic interface names, created in a private network namespace. +const ( + kBond = "kbond0" + kMember1 = "km0" + kMember2 = "km1" + kNIC = "knic0" + kVLAN = "knic0.100" + kVLANZero = "knic0.0" + kVLANQinQ = "knic0.ad" + kStacked = "kstack" + kBridge = "kbr0" + kOnBridge = "kbr0.100" + kMissing = "kmissing" +) + +// inNetNS runs f in a fresh network namespace that is removed afterwards. +func inNetNS(t *testing.T, f func()) { + t.Helper() + n, err := testutils.NewNS() + if err != nil { + t.Fatalf("create netns: %v", err) + } + t.Cleanup(func() { + _ = n.Close() + _ = testutils.UnmountNS(n) + }) + if err := n.Do(func(ns.NetNS) error { f(); return nil }); err != nil { + t.Fatal(err) + } +} + +func addKernelLink(t *testing.T, l netlink.Link) netlink.Link { + t.Helper() + if err := netlink.LinkAdd(l); err != nil { + t.Fatalf("add %s %q: %v", l.Type(), l.Attrs().Name, err) + } + got, err := netlink.LinkByName(l.Attrs().Name) + if err != nil { + t.Fatalf("find %q: %v", l.Attrs().Name, err) + } + return got +} + +func addKernelVLAN(t *testing.T, name string, parent netlink.Link, vid int, proto netlink.VlanProtocol) { + t.Helper() + addKernelLink(t, &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: name, ParentIndex: parent.Attrs().Index}, + VlanId: vid, + VlanProtocol: proto, + }) +} + +// kernelTransportTopology builds, in the current netns, a bond of two veths, +// a veth "NIC", a bridge, and on them every VLAN the kernel accepts that the +// transport contract refuses: ID 0, 802.1ad, one stacked on another VLAN, and +// one on a bridge. +func kernelTransportTopology(t *testing.T) { + t.Helper() + b := netlink.NewLinkBond(netlink.LinkAttrs{Name: kBond}) + b.Mode = netlink.BOND_MODE_802_3AD + bondLink := addKernelLink(t, b) + for _, m := range []string{kMember1, kMember2} { + ml := addKernelLink(t, &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: m}, PeerName: m + "p"}) + if err := netlink.LinkSetBondSlave(ml, bondLink.(*netlink.Bond)); err != nil { + t.Fatalf("enslave %s: %v", m, err) + } + } + nicLink := addKernelLink(t, &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: kNIC}, PeerName: kNIC + "p"}) + brLink := addKernelLink(t, &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: kBridge}}) + q := netlink.VLAN_PROTOCOL_8021Q + addKernelVLAN(t, kVLANZero, nicLink, 0, q) + addKernelVLAN(t, kVLANQinQ, nicLink, 200, netlink.VLAN_PROTOCOL_8021AD) + addKernelVLAN(t, kVLAN, nicLink, 100, q) + vlanLink, err := netlink.LinkByName(kVLAN) + if err != nil { + t.Fatal(err) + } + addKernelVLAN(t, kStacked, vlanLink, 300, q) + addKernelVLAN(t, kOnBridge, brLink, 100, q) +} + +// TestWaitForUplinksKernelTransport runs the shard's startup selection against +// real kernel devices (#1546, #1547). Every refused VLAN fails startup with +// its rule. A bond uplink resolves to its members as hook targets, while the +// transport side reported in galactic_transport_side_info is the bond. +func TestWaitForUplinksKernelTransport(t *testing.T) { + requireRoot(t) + orig := natTransport + t.Cleanup(func() { natTransport = orig }) + inNetNS(t, func() { + kernelTransportTopology(t) + + for _, tt := range []struct { + name string + rule transport.Rule + }{ + {kMissing, transport.RuleNotFound}, + {kVLANZero, transport.RuleVLANID}, + {kVLANQinQ, transport.RuleVLANProtocol}, + {kStacked, transport.RuleStackedVLAN}, + {kOnBridge, transport.RuleParentType}, + } { + natTransport = transport.NewTracker("galactic-nat") + _, _, err := waitForUplinks(context.Background(), []string{tt.name}) + var ve *transport.ValidationError + if !errors.As(err, &ve) || ve.Rule != tt.rule || ve.Interface != tt.name { + t.Errorf("waitForUplinks(%s) error = %v, want %s", tt.name, err, tt.rule) + } + t.Logf("%s: %v", tt.name, err) + } + natTransport = transport.NewTracker("galactic-nat") + _, _, err := waitForUplinks(context.Background(), []string{kBond, kBond}) + var ve *transport.ValidationError + if !errors.As(err, &ve) || ve.Rule != transport.RuleSidesOverlap { + t.Errorf("waitForUplinks(%s,%s) error = %v, want %s", kBond, kBond, err, transport.RuleSidesOverlap) + } + + natTransport = transport.NewTracker("galactic-nat") + defer natTransport.Observe(nil) + logical, targets, err := waitForUplinks(context.Background(), []string{kBond, kVLAN}) + if err != nil { + t.Fatalf("waitForUplinks(%s,%s) error = %v", kBond, kVLAN, err) + } + if !slices.Equal(logical, []string{kBond, kVLAN}) { + t.Errorf("logical uplinks = %v, want [%s %s]", logical, kBond, kVLAN) + } + slices.Sort(targets) + if !slices.Equal(targets, []string{kMember1, kMember2, kVLAN}) { + t.Errorf("hook targets = %v, want the bond's members and the VLAN", targets) + } + + rec := httptest.NewRecorder() + metrics.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) + body, _ := io.ReadAll(rec.Result().Body) + var info []string + for line := range strings.SplitSeq(string(body), "\n") { + if strings.HasPrefix(line, "galactic_transport_side_info{") { + info = append(info, line) + } + } + joined := strings.Join(info, "\n") + t.Logf("galactic_transport_side_info:\n%s", joined) + if !strings.Contains(joined, `interface="`+kBond+`"`) { + t.Errorf("galactic_transport_side_info does not report the bond %s", kBond) + } + for _, m := range []string{kMember1, kMember2} { + if strings.Contains(joined, `interface="`+m+`"`) { + t.Errorf("galactic_transport_side_info reports bond member %s as a side", m) + } + } + }) +} diff --git a/cmd/galactic-nat/transport_test.go b/cmd/galactic-nat/transport_test.go new file mode 100644 index 000000000..38893d031 --- /dev/null +++ b/cmd/galactic-nat/transport_test.go @@ -0,0 +1,248 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "bytes" + "context" + "errors" + "io" + "log/slog" + "net/http/httptest" + "strings" + "testing" + + "github.com/vishvananda/netlink" + "go.miloapis.com/instrumentation/metrics" + grpchealth "google.golang.org/grpc/health" + "google.golang.org/grpc/health/grpc_health_v1" + + "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/transport" +) + +// Synthetic interface names. None is expected to exist on a test host. +const ( + tBond = "tnbond0" + tMember1 = "tnmem1" + tMember2 = "tnmem2" + tNIC = "tnnic0" + tVLAN = "tnnic0.100" + tVLANZero = "tnnic0.0" + tVLANQinQ = "tnnic0.ad" + tStacked = "tnstack" + tBridge = "tnbr0" + tOnBridge = "tnbr0.100" + tMissing = "tnmissing" +) + +// fakeLinks is an in-memory transport.Links. +type fakeLinks []netlink.Link + +func (f fakeLinks) LinkByName(name string) (netlink.Link, error) { + for _, l := range f { + if l.Attrs().Name == name { + return l, nil + } + } + return nil, netlink.LinkNotFoundError{} +} + +func (f fakeLinks) LinkByIndex(index int) (netlink.Link, error) { + for _, l := range f { + if l.Attrs().Index == index { + return l, nil + } + } + return nil, netlink.LinkNotFoundError{} +} + +func (f fakeLinks) LinkList() ([]netlink.Link, error) { return f, nil } + +func fakeVLAN(name string, index, parent, id int, proto netlink.VlanProtocol) *netlink.Vlan { + return &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: name, Index: index, ParentIndex: parent}, + VlanId: id, + VlanProtocol: proto, + } +} + +// topology is a bond with two members, a NIC carrying one valid VLAN and one +// of each VLAN the contract refuses, and a bridge with a VLAN on it. vlanID is +// the valid VLAN's ID, so a test can break it. +func topology(vlanID int) fakeLinks { + return fakeLinks{ + &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Name: tBond, Index: 10}}, + &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: tMember1, Index: 11, MasterIndex: 10}}, + &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: tMember2, Index: 12, MasterIndex: 10}}, + &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: tNIC, Index: 13}}, + fakeVLAN(tVLAN, 14, 13, vlanID, netlink.VLAN_PROTOCOL_8021Q), + fakeVLAN(tVLANZero, 15, 13, 0, netlink.VLAN_PROTOCOL_8021Q), + fakeVLAN(tVLANQinQ, 16, 13, 200, netlink.VLAN_PROTOCOL_8021AD), + fakeVLAN(tStacked, 17, 14, 300, netlink.VLAN_PROTOCOL_8021Q), + &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: tBridge, Index: 18}}, + fakeVLAN(tOnBridge, 19, 18, 100, netlink.VLAN_PROTOCOL_8021Q), + } +} + +// useTransport points the shard's transport resolution at links and gives it +// a fresh tracker, whose series are removed when the test ends. +func useTransport(t *testing.T, links fakeLinks) { + t.Helper() + origLinks, origTracker := transportLinks, natTransport + transportLinks = links + natTransport = transport.NewTracker("galactic-nat") + t.Cleanup(func() { + natTransport.Observe(nil) + transportLinks, natTransport = origLinks, origTracker + }) +} + +// captureLog sends the default logger to a buffer for the rest of the test. +func captureLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + orig := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil))) + t.Cleanup(func() { slog.SetDefault(orig) }) + return &buf +} + +// TestWaitForUplinksRefusesInvalidTransport covers #1546: every uplink that +// breaks a transport contract rule fails the shard's startup, before +// anything is resolved to hook targets or attached, and the log names the +// interface and the rule. +func TestWaitForUplinksRefusesInvalidTransport(t *testing.T) { + tests := []struct { + name string + override []string + rule transport.Rule + iface string + }{ + {"missing interface", []string{tMissing}, transport.RuleNotFound, tMissing}, + {"VLAN ID 0", []string{tBond, tVLANZero}, transport.RuleVLANID, tVLANZero}, + {"802.1ad VLAN", []string{tVLANQinQ}, transport.RuleVLANProtocol, tVLANQinQ}, + {"stacked VLAN", []string{tStacked}, transport.RuleStackedVLAN, tStacked}, + {"unsupported parent type", []string{tOnBridge}, transport.RuleParentType, tOnBridge}, + {"uplink listed twice", []string{tBond, tBond}, transport.RuleSidesOverlap, tBond}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + useTransport(t, topology(100)) + log := captureLog(t) + + _, _, err := waitForUplinks(context.Background(), tt.override) + var ve *transport.ValidationError + if !errors.As(err, &ve) { + t.Fatalf("waitForUplinks(%v) error = %v, want a *transport.ValidationError", tt.override, err) + } + if ve.Rule != tt.rule || ve.Interface != tt.iface { + t.Errorf("waitForUplinks(%v) refused %q for %s, want %q for %s", + tt.override, ve.Interface, ve.Rule, tt.iface, tt.rule) + } + for _, want := range []string{"reason=" + string(tt.rule), "interface=" + tt.iface} { + if !strings.Contains(log.String(), want) { + t.Errorf("log does not contain %q:\n%s", want, log) + } + } + t.Logf("startup error: %v", err) + }) + } +} + +// TestUplinkTransportReportsTheBondNotItsMembers covers #1547: a bond uplink +// is published in galactic_transport_side_info as the bond the shard was +// pointed at, never as the members its program attaches to. +func TestUplinkTransportReportsTheBondNotItsMembers(t *testing.T) { + useTransport(t, topology(100)) + if invalid := checkUplinkTransport([]string{tBond, tVLAN}); invalid != nil { + t.Fatalf("checkUplinkTransport() = %v, want nil", invalid) + } + + rec := httptest.NewRecorder() + metrics.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) + body, _ := io.ReadAll(rec.Result().Body) + var info []string + for line := range strings.SplitSeq(string(body), "\n") { + if strings.HasPrefix(line, "galactic_transport_side_info{") { + info = append(info, line) + } + } + t.Logf("galactic_transport_side_info:\n%s", strings.Join(info, "\n")) + joined := strings.Join(info, "\n") + for _, want := range []string{`interface="` + tBond + `"`, `interface="` + tVLAN + `"`} { + if !strings.Contains(joined, want) { + t.Errorf("galactic_transport_side_info has no series with %s", want) + } + } + for _, member := range []string{tMember1, tMember2} { + if strings.Contains(joined, `interface="`+member+`"`) { + t.Errorf("galactic_transport_side_info reports bond member %q as a side", member) + } + } +} + +// TestResyncUplinksReportsNotReadyOnInvalidTransport covers the re-resolution +// half of #1546: an uplink that starts breaking a rule after startup turns +// readiness off, naming the rule, and readiness returns once it passes again. +func TestResyncUplinksReportsNotReadyOnInvalidTransport(t *testing.T) { + useTransport(t, topology(100)) + log := captureLog(t) + d := &natDatapath{configured: map[string]bool{}} + override := []string{tVLAN} + nudges := 0 + onCoverage := func() { nudges++ } + cover := func(ready []string) []string { return ready } + + readiness := func() grpc_health_v1.HealthCheckResponse_ServingStatus { + t.Helper() + srv := grpchealth.NewServer() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + followCoverage(ctx, d, srv, nil, nil) + resp, err := srv.Check(context.Background(), + &grpc_health_v1.HealthCheckRequest{Service: config.GRPCReadinessService}) + if err != nil { + t.Fatalf("readiness check: %v", err) + } + return resp.GetStatus() + } + + // The synthetic VLAN does not exist on the host, so the pass stops at + // expanding hook targets; the transport check before it is what counts. + d.resyncUplinks(override, cover, onCoverage) + if d.TransportInvalid() != nil || nudges != 0 { + t.Fatalf("valid uplink: TransportInvalid() = %v, nudges = %d; want nil, 0", d.TransportInvalid(), nudges) + } + + transportLinks = topology(0) + d.resyncUplinks(override, cover, onCoverage) + invalid := d.TransportInvalid() + if invalid == nil || invalid.Rule != transport.RuleVLANID || nudges != 1 { + t.Fatalf("VLAN ID 0: TransportInvalid() = %v, nudges = %d; want %s, 1", invalid, nudges, transport.RuleVLANID) + } + if got := readiness(); got != grpc_health_v1.HealthCheckResponse_NOT_SERVING { + t.Errorf("readiness with VLAN ID 0 = %v, want NOT_SERVING", got) + } + if !strings.Contains(log.String(), "reason="+string(transport.RuleVLANID)) { + t.Errorf("log does not name %s:\n%s", transport.RuleVLANID, log) + } + + // The same failure on the next event is neither a change nor logged again. + before := strings.Count(log.String(), "side failed validation") + d.resyncUplinks(override, cover, onCoverage) + if nudges != 1 || strings.Count(log.String(), "side failed validation") != before { + t.Errorf("a persisting failure nudged or logged again: nudges = %d", nudges) + } + + transportLinks = topology(100) + d.resyncUplinks(override, cover, onCoverage) + if d.TransportInvalid() != nil || nudges != 2 { + t.Fatalf("fixed uplink: TransportInvalid() = %v, nudges = %d; want nil, 2", d.TransportInvalid(), nudges) + } + if got := readiness(); got != grpc_health_v1.HealthCheckResponse_SERVING { + t.Errorf("readiness once the uplink passes = %v, want SERVING", got) + } +} diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 5903a95ac..95787bd78 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -49,6 +49,18 @@ through the VLAN's parent with exactly that side's tag. The and the [transport contract](../designs/vlan-transport/contract.md#logical-interface-to-hook-targets) give the details. Name the parent instead and the side runs untagged. +Both settings are checked against the +[transport contract](../designs/vlan-transport/contract.md#validation) before +anything is attached. `galactic-gateway` refuses to start on an interface that +does not exist, a VLAN with ID 0, an 802.1ad VLAN, a VLAN stacked on another +VLAN, a VLAN whose parent is missing, is a bond member or is not a NIC or bond, +or an internal interface that is also the public one (`sides_overlap`). The +error and the log name the side, the interface and the rule. The gateway +re-checks on every link or route change; a failure then turns readiness off, +keeps the current attachments, and is logged once until it changes or clears. +`galactic_transport_side_info` and `galactic_transport_validation_failures_total` +report each side and each refusal. + `GALACTIC_XDP_MODE` has no `GALACTIC_GATEWAY` prefix. `galactic-nat` reads the same name, and both must resolve the same mode on a host. `auto` decides native or generic from the host's NIC drivers, and `native` or `generic` forces that diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 56936e6f9..4315d95a0 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -61,6 +61,21 @@ routed through it leaves through the VLAN's parent with exactly that uplink's tag. See the [XDP attach mode guide](../operations/xdp-attach-mode.md#vlan-netdevices-always-use-generic-mode). +Every uplink, named or detected, is checked against the +[transport contract](../designs/vlan-transport/contract.md#validation) before +its bond is expanded or anything is attached. `galactic-nat` refuses to start +on an uplink that does not exist, a VLAN with ID 0, an 802.1ad VLAN, a VLAN +stacked on another VLAN, a VLAN whose parent is missing, is a bond member or +is not a NIC or bond, or an uplink named twice (`sides_overlap`). The error +and the log name the interface and the rule. The shard re-checks on every link +or route change; a failure then turns readiness off, keeps the current +attachments, and is logged once until it changes or clears. + +The shard reports each uplink as the interface it was given, such as `bond0`, +never as the bond's members, in `galactic_transport_side_info` and the +`transport: resolved side` log line. Refusals are counted in +`galactic_transport_validation_failures_total` by rule. + Set it on a node where detection is ambiguous — typically one whose management NIC carries the IPv6 default route, as Kind's `eth0` does in the containerlab lab. Detection would attach there too. diff --git a/internal/plumbing/ebpf/natattach/uplinks.go b/internal/plumbing/ebpf/natattach/uplinks.go index c0e260f80..e87807faf 100644 --- a/internal/plumbing/ebpf/natattach/uplinks.go +++ b/internal/plumbing/ebpf/natattach/uplinks.go @@ -25,18 +25,39 @@ var detectUplinksFn = attach.DetectUplinks // route has been learned, which waiting fixes. var ErrNoUplinks = errors.New("natattach: no uplink interfaces resolved") -// ResolveUplinks returns the interfaces Attach should attach the egress -// translation program to. +// SelectUplinks returns this node's logical uplinks: the interfaces the +// egress translation shard is pointed at, before any bond is expanded to its +// members. These are the transport sides the shard validates and reports +// (docs/designs/vlan-transport/contract.md). // // A non-empty override is used as given. Otherwise the uplinks are // auto-detected with the same derivation the CNI's SRv6 datapath uses // (attach.DetectUplinks), so the shard and the CNI on one node converge on the -// same physical uplinks with no per-node configuration. The override exists for -// a multi-homed node where that derivation cannot be confident. +// same uplinks with no per-node configuration. The override exists for a +// multi-homed node where that derivation cannot be confident. // -// Either way, every name then passes through ResolveTargets: a bonding master -// resolves to its slaves and never to itself, native XDP on a master being -// unreliable. +// A detection that finds no route yet is ErrNoUplinks. +func SelectUplinks(override []string) ([]string, error) { + if len(override) != 0 { + return override, nil + } + detected, err := detectUplinksFn() + if errors.Is(err, attach.ErrNoUplinkRoute) { + return nil, fmt.Errorf("%w: %w", ErrNoUplinks, err) + } + if err != nil { + return nil, fmt.Errorf("natattach: auto-detect uplinks: %w", err) + } + if len(detected) == 0 { + return nil, ErrNoUplinks + } + return detected, nil +} + +// ResolveUplinks returns the interfaces Attach should attach the egress +// translation program to: SelectUplinks' logical uplinks passed through +// ResolveTargets, so a bonding master resolves to its slaves and never to +// itself, native XDP on a master being unreliable. // // An empty result is ErrNoUplinks. The datapath claims a packet only on an // interface it is attached to, so too few uplinks is a silent blackhole rather @@ -46,18 +67,17 @@ var ErrNoUplinks = errors.New("natattach: no uplink interfaces resolved") // keeps it current by calling again as routes change, which // xdpattach.Watch does. func ResolveUplinks(override []string) ([]string, error) { - names := override - if len(names) == 0 { - detected, err := detectUplinksFn() - if errors.Is(err, attach.ErrNoUplinkRoute) { - return nil, fmt.Errorf("%w: %w", ErrNoUplinks, err) - } - if err != nil { - return nil, fmt.Errorf("natattach: auto-detect uplinks: %w", err) - } - names = detected + names, err := SelectUplinks(override) + if err != nil { + return nil, err } + return UplinkTargets(names) +} +// UplinkTargets expands logical uplinks, from SelectUplinks, to the +// interfaces Attach attaches to (ResolveTargets). An empty result is +// ErrNoUplinks. +func UplinkTargets(names []string) ([]string, error) { targets, err := ResolveTargets(names) if err != nil { return nil, err diff --git a/internal/plumbing/ebpf/natattach/uplinks_test.go b/internal/plumbing/ebpf/natattach/uplinks_test.go index 9c1784bed..642d60aa2 100644 --- a/internal/plumbing/ebpf/natattach/uplinks_test.go +++ b/internal/plumbing/ebpf/natattach/uplinks_test.go @@ -111,3 +111,27 @@ func TestResolveUplinks_NoRouteYetIsErrNoUplinks(t *testing.T) { t.Errorf("ResolveUplinks() error = %v; a real detection failure must not read as ErrNoUplinks", err) } } + +// TestSelectUplinksKeepsLogicalInterfaces covers #1547: the shard's logical +// uplinks, which it validates and reports as transport sides, are the +// interfaces it was pointed at, a bond and not its members. +func TestSelectUplinksKeepsLogicalInterfaces(t *testing.T) { + fakeUplinkHost(t, []string{testUplink, testBond}, nil) + for _, override := range [][]string{nil, {testBond, testUplink}} { + names, err := SelectUplinks(override) + if err != nil { + t.Fatalf("SelectUplinks(%v) error = %v", override, err) + } + want := override + if want == nil { + want = []string{testUplink, testBond} + } + if !slices.Equal(names, want) { + t.Errorf("SelectUplinks(%v) = %v, want %v", override, names, want) + } + targets, err := UplinkTargets(names) + if err != nil || slices.Contains(targets, testBond) { + t.Errorf("UplinkTargets(%v) = %v, %v; want the bond's members, not the bond", names, targets, err) + } + } +} diff --git a/internal/plumbing/ebpf/vlanegress/vlanegress.go b/internal/plumbing/ebpf/vlanegress/vlanegress.go index 7083c02fa..9dd6e16ef 100644 --- a/internal/plumbing/ebpf/vlanegress/vlanegress.go +++ b/internal/plumbing/ebpf/vlanegress/vlanegress.go @@ -112,6 +112,12 @@ var links = transport.Netlink // it, which transmits only in generic mode. When the sides themselves conflict // (public and fabric on one interface), the Set is nil and holds no rows. func Resolve(sides ...Side) (*transport.Set, []int, error) { + return ResolveWith(links, sides...) +} + +// ResolveWith is Resolve over view, the netlink view a component's tests +// substitute. +func ResolveWith(view transport.Links, sides ...Side) (*transport.Set, []int, error) { var ( resolved []transport.Resolution ifindexes []int @@ -122,7 +128,7 @@ func Resolve(sides ...Side) (*transport.Set, []int, error) { if name == "" { continue } - r, err := transport.ResolveWith(links, s.Side, name) + r, err := transport.ResolveWith(view, s.Side, name) if err != nil { errs = append(errs, err) continue diff --git a/internal/plumbing/transport/report.go b/internal/plumbing/transport/report.go index 9c780d47b..f8e7ac098 100644 --- a/internal/plumbing/transport/report.go +++ b/internal/plumbing/transport/report.go @@ -129,6 +129,11 @@ type Tracker struct { mu sync.Mutex current *Set seen bool + + // failMu guards the failure Record last reported. + failMu sync.Mutex + lastFailure string + invalid *ValidationError } // NewTracker returns a Tracker whose log lines name component, such as @@ -198,6 +203,60 @@ func (t *Tracker) Fail(err error) { slog.Warn("transport: could not resolve sides", "component", t.component, "err", err) } +// Record publishes one resolution of the component's sides: set, which may be +// partial or nil, and err, the resolution's failure or nil. +// +// A failure is logged and counted once while it persists (Fail), so a check +// that runs on every netlink event does not repeat it, and +// galactic_transport_validation_failures_total counts distinct failures. A +// nil err clears it. A non-nil set is then observed (Observe). +// +// It returns the *ValidationError err carries, nil when it carries none, and +// whether that differs from the previous call's. A component treats a +// non-nil result as a broken contract: at startup it refuses to start, later +// it reports not-ready until a resolution succeeds. +func (t *Tracker) Record(set *Set, err error) (invalid *ValidationError, changed bool) { + t.failMu.Lock() + var ve *ValidationError + if !errors.As(err, &ve) { + ve = nil + } + changed = !sameValidation(t.invalid, ve) + t.invalid = ve + report := false + switch { + case err == nil: + t.lastFailure = "" + case err.Error() != t.lastFailure: + t.lastFailure = err.Error() + report = true + } + t.failMu.Unlock() + + if report { + t.Fail(err) + } + if set != nil { + t.Observe(set) + } + return ve, changed +} + +// Invalid returns the *ValidationError the last Record call carried, nil +// when it carried none or Record was never called. +func (t *Tracker) Invalid() *ValidationError { + t.failMu.Lock() + defer t.failMu.Unlock() + return t.invalid +} + +func sameValidation(a, b *ValidationError) bool { + if a == nil || b == nil { + return a == b + } + return *a == *b +} + func infoLabels(r Resolution) []string { return []string{string(r.Side), r.Interface, string(r.Mode), r.vlanLabel(), r.Parent} } diff --git a/internal/plumbing/transport/transport_test.go b/internal/plumbing/transport/transport_test.go index 67271062a..379c816c2 100644 --- a/internal/plumbing/transport/transport_test.go +++ b/internal/plumbing/transport/transport_test.go @@ -320,3 +320,43 @@ func TestTrackerReplacesInfoSeriesAndCounts(t *testing.T) { t.Fatal("Fail must keep the observed sides") } } + +func TestTrackerRecordReportsAFailureOnceAndKeepsItForReadiness(t *testing.T) { + sideInfo.Reset() + validationFailures.Reset() + + links := topology() + tr := NewTracker("test") + good, _ := NewSet(mustResolve(t, links, SidePublic, "bond0.101")) + if invalid, changed := tr.Record(good, nil); invalid != nil || changed { + t.Fatalf("Record(valid) = %v, %v; want nil, false", invalid, changed) + } + if tr.Current() != good { + t.Fatal("Record did not observe the set") + } + + _, err := ResolveWith(links, SideFabric, "qinq") + for i := range 3 { + invalid, changed := tr.Record(nil, fmt.Errorf("wrapped: %w", err)) + if invalid == nil || invalid.Rule != RuleVLANProtocol || changed != (i == 0) { + t.Fatalf("Record(invalid) #%d = %v, %v; want %s, %v", i, invalid, changed, RuleVLANProtocol, i == 0) + } + } + if v := testutil.ToFloat64(validationFailures.WithLabelValues("fabric", string(RuleVLANProtocol))); v != 1 { + t.Fatalf("a persisting failure was counted %v times, want 1", v) + } + if tr.Invalid() == nil || tr.Current() != good { + t.Fatal("Record(invalid) must keep the failure and the observed sides") + } + + if invalid, changed := tr.Record(nil, errors.New("transient")); invalid != nil || !changed { + t.Fatalf("Record(transient) = %v, %v; want nil, true", invalid, changed) + } + if invalid, changed := tr.Record(good, nil); invalid != nil || changed { + t.Fatalf("Record(valid again) = %v, %v; want nil, false", invalid, changed) + } + tr.Record(nil, err) + if v := testutil.ToFloat64(validationFailures.WithLabelValues("fabric", string(RuleVLANProtocol))); v != 2 { + t.Fatalf("a failure after a success was counted %v times in all, want 2", v) + } +} From 004725236ea899e90008e75ec44eb448b56d48d4 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 30 Nov 2026 19:27:41 -0500 Subject: [PATCH 2/2] fix(transport): Satisfy errcheck and noctx in the transport checks --- cmd/galactic-nat/nat.go | 4 +++- cmd/galactic-nat/transport_root_test.go | 2 +- cmd/galactic-nat/transport_test.go | 2 +- internal/plumbing/transport/transport_test.go | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 6dcddf894..5e3862fd7 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -357,7 +357,9 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // from the EgressShard spec -- or clears it, if that shard is gone. d.shardConfig = natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}) d.vlanEgress = objs.VlanEgress - d.syncVLANEgress(logical) + // waitForUplinks refused a broken rule already. One that appeared since + // is kept in natTransport, which readiness reads (TransportInvalid). + _, _ = d.syncVLANEgress(logical) var ( set *xdpattach.Set diff --git a/cmd/galactic-nat/transport_root_test.go b/cmd/galactic-nat/transport_root_test.go index 4d1376561..d9838a9ee 100644 --- a/cmd/galactic-nat/transport_root_test.go +++ b/cmd/galactic-nat/transport_root_test.go @@ -153,7 +153,7 @@ func TestWaitForUplinksKernelTransport(t *testing.T) { } rec := httptest.NewRecorder() - metrics.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) + metrics.Handler().ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), "GET", "/metrics", nil)) body, _ := io.ReadAll(rec.Result().Body) var info []string for line := range strings.SplitSeq(string(body), "\n") { diff --git a/cmd/galactic-nat/transport_test.go b/cmd/galactic-nat/transport_test.go index 38893d031..dacb889b1 100644 --- a/cmd/galactic-nat/transport_test.go +++ b/cmd/galactic-nat/transport_test.go @@ -162,7 +162,7 @@ func TestUplinkTransportReportsTheBondNotItsMembers(t *testing.T) { } rec := httptest.NewRecorder() - metrics.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) + metrics.Handler().ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), "GET", "/metrics", nil)) body, _ := io.ReadAll(rec.Result().Body) var info []string for line := range strings.SplitSeq(string(body), "\n") { diff --git a/internal/plumbing/transport/transport_test.go b/internal/plumbing/transport/transport_test.go index 379c816c2..d0c8ec7be 100644 --- a/internal/plumbing/transport/transport_test.go +++ b/internal/plumbing/transport/transport_test.go @@ -355,7 +355,7 @@ func TestTrackerRecordReportsAFailureOnceAndKeepsItForReadiness(t *testing.T) { if invalid, changed := tr.Record(good, nil); invalid != nil || changed { t.Fatalf("Record(valid again) = %v, %v; want nil, false", invalid, changed) } - tr.Record(nil, err) + _, _ = tr.Record(nil, err) if v := testutil.ToFloat64(validationFailures.WithLabelValues("fabric", string(RuleVLANProtocol))); v != 2 { t.Fatalf("a failure after a success was counted %v times in all, want 2", v) }