diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 187b531a2..3e5820324 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -15,7 +15,6 @@ import ( "github.com/cilium/ebpf" "github.com/cilium/ebpf/link" - "github.com/vishvananda/netlink" "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/config" @@ -29,6 +28,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" "go.datum.net/galactic/internal/plumbing/ebpf/xmitdrops" "go.datum.net/galactic/internal/plumbing/sysctl" + "go.datum.net/galactic/internal/plumbing/transport" ) // gatewayDatapathKeepAlive holds the loaded objects and every attached link for @@ -297,7 +297,7 @@ func installGateway( missing = append(missing, returnSet.reconcile(ctx, returnTargets)...) } coverage.set(missing) - syncVLANEgress(objs.VlanEgress, publicInterface, internalInterfaces, true) + syncVLANEgress(objs.VlanEgress, publicInterface, internalInterfaces) go watchTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage, ipv4, objs.VlanEgress) return nil @@ -309,39 +309,31 @@ func installGateway( // 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. -// logSides logs each tagged side, which startup does once. -func syncVLANEgress(m *ebpf.Map, publicInterface string, internalInterfaces []string, logSides bool) { - names := append([]string{publicInterface}, internalInterfaces...) - lowers, ifindexes, err := vlanegress.FromNetlink(names) +// +// 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( + vlanegress.Side{Side: transport.SidePublic, Names: []string{publicInterface}}, + vlanegress.Side{Side: transport.SideFabric, Names: internalInterfaces}, + ) 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, lowers, ifindexes); err != nil { + if err := vlanegress.Sync(m, set, ifindexes); err != nil { slog.Warn("Cannot update the edge gateway's VLAN egress map", "err", err) } - if !logSides { - return - } - for i, name := range names { - if name == "" { - continue - } - side := "internal" - if i == 0 { - side = "public" - } - l, err := netlink.LinkByName(name) - if err != nil { - continue - } - if lower, vid, ok := lowers.VLANLower(l.Attrs().Index); ok { - slog.Info("Edge gateway side is tagged; its XDP hook runs in generic mode on the VLAN device", - "side", side, "interface", name, "vlanID", vid, "lowerIfindex", lower) - } + if set != nil { + gatewayTransport.Observe(set) } } +// gatewayTransport publishes the gateway's derived transport sides. +var gatewayTransport = transport.NewTracker("galactic-gateway") + // 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. @@ -612,7 +604,7 @@ func watchTargets(ctx context.Context, publicInterface string, internalInterface publicSet, returnSet targetSet, coverage *datapathCoverage, ipv4 *ipv4Forwarding, vlanEgress *ebpf.Map, ) { xdpattach.OnNetlinkChange(ctx, func() { - syncVLANEgress(vlanEgress, publicInterface, internalInterfaces, false) + syncVLANEgress(vlanEgress, publicInterface, internalInterfaces) var ( targets []string err error diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index bae32c543..6aa85390b 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -30,6 +30,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" "go.datum.net/galactic/internal/plumbing/nicstats" "go.datum.net/galactic/internal/plumbing/sysctl" + "go.datum.net/galactic/internal/plumbing/transport" ) // natDatapathKeepAlive holds the loaded objects and the attached link for the @@ -350,7 +351,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, true) + d.syncVLANEgress(uplinks) var ( set *xdpattach.Set @@ -409,31 +410,33 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // 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. logSides logs each -// tagged uplink, which startup does once. -func (d *natDatapath) syncVLANEgress(uplinks []string, logSides bool) { +// native redirect to a VLAN netdevice transmits nothing. +// +// 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 } - lowers, ifindexes, err := vlanegress.FromNetlink(uplinks) + set, ifindexes, err := vlanegress.Resolve(vlanegress.Side{Side: transport.SideUnassigned, Names: uplinks}) 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, lowers, ifindexes); err != nil { + if err := vlanegress.Sync(d.vlanEgress, set, ifindexes); err != nil { slog.Warn("Cannot update the egress translation VLAN egress map", "err", err) } - if !logSides { - return - } - for _, ifindex := range ifindexes { - if lower, vid, ok := lowers.VLANLower(ifindex); ok { - slog.Info("Uplink is tagged; its XDP hook runs in generic mode on the VLAN device", - "ifindex", ifindex, "vlanID", vid, "lowerIfindex", lower) - } + if set != nil { + natTransport.Observe(set) } } +// natTransport publishes the shard's derived uplink transport state. +var natTransport = transport.NewTracker("galactic-nat") + // 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); @@ -567,7 +570,7 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover } return } - d.syncVLANEgress(uplinks, false) + d.syncVLANEgress(uplinks) ready := d.adoptUplinks(uplinks) missing := uncovered(uplinks, cover(ready)) diff --git a/config/galactic-cni/daemonset.yaml b/config/galactic-cni/daemonset.yaml index 3debee5c3..0c05762fa 100644 --- a/config/galactic-cni/daemonset.yaml +++ b/config/galactic-cni/daemonset.yaml @@ -107,6 +107,13 @@ spec: # docs/nat/configuration.md#active-active-egress. - name: GALACTIC_CNI_EGRESS_MODE value: ordered + # Matches this node's entry in + # GALACTIC_CNI_EBPF_INTERFACES_BY_NODE, which both containers + # read. + - name: NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName # Documentation only: hostNetwork: true means these are the # process's actual listen ports on the node, not something # Kubernetes publishes -- containerPort here doesn't change diff --git a/docs/cni/environment-variables.md b/docs/cni/environment-variables.md index 55faa4c9e..a0e8dad09 100644 --- a/docs/cni/environment-variables.md +++ b/docs/cni/environment-variables.md @@ -129,6 +129,30 @@ field; as of this writing it is still env-only. **Type:** comma-separated string · **Default:** _(auto-detected)_ +- **`GALACTIC_CNI_EBPF_INTERFACES_BY_NODE`** gives individual nodes their + own `GALACTIC_CNI_EBPF_INTERFACES` list, so one cluster-wide DaemonSet can + name a tagged transport side on a node where the same interface plays a + different side elsewhere. Entries are separated by semicolons or newlines, + each `node=iface[,iface...]`: + + ```yaml + - name: GALACTIC_CNI_EBPF_INTERFACES_BY_NODE + value: | + edge-a=bond0.101 + compute-b=bond0 + ``` + + `galactic-cni init` and `run` match the entry against `NODE_NAME` (or + `GALACTIC_CNI_NODE_NAME`), so set the variable on both the `install-cni` + and `credential-refresh` containers; the shipped DaemonSet gives both + `NODE_NAME`. A listed node's entry replaces `GALACTIC_CNI_EBPF_INTERFACES` + before anything resolves it, so the conflist carries the node's own list. + Other nodes keep the cluster-wide value or auto-detection. A malformed + value, a node listed twice, or a value set where the node name is unknown + fails startup. + + **Type:** string · **Default:** _(unset)_ + - **`GALACTIC_CNI_EBPF_FILTER_PRIORITY`** — overrides the `tc` priority the ingress filter attaches at. Cilium also runs its own tc/bpf programs on the same native-device ingress hook, and the default has not been @@ -141,6 +165,27 @@ field; as of this writing it is still env-only. **Type:** `uint16` · **Default:** `1` (highest/lowest-numbered priority `tc` allows) +### Transport checks on the selected interfaces + +`galactic-cni run` checks every selected interface, however it was chosen, +against the [transport contract](../designs/vlan-transport/contract.md#validation) +before it attaches. It refuses to start on a named interface that does not +exist, a VLAN with ID 0, an 802.1ad VLAN, a VLAN stacked on another VLAN, or +a VLAN whose parent is missing, is a bond member, or is not a NIC or bond. + +While running, it re-checks on every health check (every 10 seconds) and on +every change to the attached set. A failure then is reported once until it +changes or clears, and does not detach anything. + +| Signal | What it shows | +| ---------------------------------------------- | ----------------------------------------------------------------------------------- | +| `galactic_transport_side_info` | Each selected interface's derived mode, VLAN ID and parent, always 1 | +| `galactic_transport_side_changes_total` | Changes since the last check, such as `recreated` or `members_changed`, by `reason` | +| `galactic_transport_validation_failures_total` | Distinct refusals, by the contract rule in `reason` | + +The log lines `transport: resolved side` and `transport: side changed` carry +the same state, with each interface's members. + ## `GALACTIC_CNI_TCP_MSS_CLAMP` Sets the fabric MTU the uSID datapath sizes tenant traffic to. A tenant diff --git a/docs/designs/vlan-transport/contract.md b/docs/designs/vlan-transport/contract.md index fa7b0b9bb..8c19d663d 100644 --- a/docs/designs/vlan-transport/contract.md +++ b/docs/designs/vlan-transport/contract.md @@ -154,7 +154,9 @@ Seamless live migration is not assumed. Each change below affects only the side | VLAN netdevice recreated with the same ID and parent | Restart the same components | As above | | Bond member replaced or failed | No action; hooks follow bond membership | Bounded by bond failover, measured against the untagged baseline | -A restart must leave no stale hooks, routes or map rows that name the old netdevice. `galactic-gateway` already re-resolves its targets on netlink changes (`watchTargets`, `cmd/galactic-gateway/gateway.go:550`); [#1404](https://github.com/datum-cloud/galactic/issues/1404) may replace restarts with reconciliation, and then updates this table. Rollback is the same procedure with the old values. +A restart must leave no stale hooks, routes or map rows that name the old netdevice. Rollback is the same procedure with the old values. + +Each component also reconciles a change that keeps the selected names. On a netlink link event, `galactic-cni`'s watch loop re-attaches `usid_ingress` by name and rewrites `transport_vlan_table`, and `galactic-gateway` and `galactic-nat` re-resolve their XDP targets and rewrite `vlan_egress`. All three derive the side through `internal/plumbing/transport` and rewrite each ifindex-keyed map in full, so a deleted VLAN's row goes away and a reused ifindex never keeps another device's tag context. Each reports the derived side and every change (`recreated`, `vlan_id_changed`, `parent_changed`, `members_changed`, `mode_changed`) in its log and in `galactic_transport_side_changes_total`, and each refusal in `galactic_transport_validation_failures_total`. Root tests cover the map rewrite after recreation; recovery time without a restart is unmeasured until [#1405](https://github.com/datum-cloud/galactic/issues/1405)'s lab pass, so the restart above stays the documented procedure. ## 6. Supported topologies diff --git a/docs/observability/README.md b/docs/observability/README.md index b9175d011..ef4c1bc52 100644 --- a/docs/observability/README.md +++ b/docs/observability/README.md @@ -78,6 +78,7 @@ the fabric-api gateway are Deployments, scraped per pod. | VPC ingress return path | `galactic-cni` (`credential-refresh`) | `galactic_sidecar_return_*` | 9180 | `galactic-cni` | | VPC ingress backends | `galactic-cni` (`credential-refresh`) | `galactic_endpointslice_repair_*` | 9180 | `galactic-cni` | | VPC host link repair | `galactic-cni` (`credential-refresh`) | `galactic_cni_host_link*` | 9180 | `galactic-cni` | +| Transport sides (VLAN) | `galactic-cni` (`credential-refresh`) | `galactic_transport_*` | 9180 | `galactic-cni` | | Edge load balancer | `galactic-gateway` | `galactic_edge_*`, controller-runtime | 8081 | none shipped | | Tenant routing (GoBGP) | `galactic-router`, `galactic-router-rr` | `galactic_router_*`, controller-runtime | 9179 | `galactic-router` / `galactic-router-rr` | | Private service routes | `galactic-router` (plain mode only) | `galactic_service_route_*` | 9179 | `galactic-router` | diff --git a/internal/config/cni.go b/internal/config/cni.go index b2f20690d..d47121d92 100644 --- a/internal/config/cni.go +++ b/internal/config/cni.go @@ -34,6 +34,14 @@ const ( // ambiguous. EnvCNIEBPFInterfaces = "GALACTIC_CNI_EBPF_INTERFACES" + // EnvCNIEBPFInterfacesByNode gives individual nodes their own + // EnvCNIEBPFInterfaces list: entries separated by semicolons or newlines, + // each "node=iface[,iface...]". A listed node's entry replaces the + // cluster-wide list; other nodes keep it. It lets one DaemonSet name a + // tagged transport side where the same interface plays a different side on + // another node. Read only by galactic-cni init and run. + EnvCNIEBPFInterfacesByNode = "GALACTIC_CNI_EBPF_INTERFACES_BY_NODE" + // EnvCNIEBPFFilterPriority overrides the tc priority the uSID datapath's // ingress filter attaches at, the default being the highest tc allows. A // cluster CNI may run its own programs on the same hook, and that default diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 695f480e8..7e7f197b3 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -376,6 +376,9 @@ func Bootstrap(ctx context.Context, nodeName string) error { logLevel := resolveLogLevel() egressShardSIDs := resolveEgressShardSIDs() nat64Prefix := resolveNAT64Prefix() + if err := applyNodeInterfaces(nodeName); err != nil { + return err + } ebpfInterfaces := resolveEBPFInterfaces() danDir := os.Getenv(config.EnvCNIDANDir) conflistContent := renderConflist(&hostconf.HostConf{ @@ -554,6 +557,13 @@ func startEBPFDatapath(ctx context.Context, m *metrics.Metrics) (ebpfDatapathSta attach.SetHooks(m.Events.Hooks()) + if err := applyNodeInterfaces(""); err != nil { + return ebpfDatapathState{}, nil, err + } + if err := checkTransport(); err != nil { + return ebpfDatapathState{}, nil, fmt.Errorf("eBPF datapath interface selection: %w", err) + } + datapath, ifaces, watcher, err := ebpfStartFn(ctx, attach.PinDir) if err != nil { return ebpfDatapathState{}, nil, fmt.Errorf("start eBPF uSID datapath: %w", err) @@ -568,7 +578,7 @@ func startEBPFDatapath(ctx context.Context, m *metrics.Metrics) (ebpfDatapathSta state.sidecarReturn = m.SidecarReturn state.endpointSliceRepair = m.EndpointSliceRepair m.Egress.SetMode(string(egressCfg.Mode), string(config.EgressModeOrdered), string(config.EgressModeHashed)) - watcher.OnChange(rewriteEBPFInterfaces) + watcher.OnChange(onAttachedSetChange) // The closer is the loaded objects in production. A test fake stands in a // plain mock closer, which correctly leaves the metrics, health, and GC @@ -1431,6 +1441,9 @@ func reportEBPFHealth(st ebpfDatapathState, healthSrv *health.Server, lastHealth if st.objs == nil { return } + // The watcher reports only a changed set of names; a VLAN recreated under + // the same name, a new VLAN ID or a replaced bond member shows up here. + recheckTransport() h := attach.Handle{Objs: st.objs, Watcher: st.watcher} healthErr := h.Healthy() healthy := healthErr == nil diff --git a/internal/installer/transport.go b/internal/installer/transport.go new file mode 100644 index 000000000..4c3924393 --- /dev/null +++ b/internal/installer/transport.go @@ -0,0 +1,112 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "errors" + "fmt" + "log/slog" + "sync" + + "go.datum.net/galactic/internal/plumbing/ebpf/attach" + "go.datum.net/galactic/internal/plumbing/transport" +) + +// cniTransport publishes the transport state of the interfaces galactic-cni +// is pointed at. galactic-cni's list can name both sides (the public side only +// for same-node gateway delivery), so each is reported as SideUnassigned. +var cniTransport = transport.NewTracker("galactic-cni") + +// Override points so tests can drive checkTransport without host netlink. +var ( + selectedInterfacesFn = attach.SelectedInterfaces + resolveTransportFn = transport.ResolveAll +) + +// applyNodeInterfaces applies this node's GALACTIC_CNI_EBPF_INTERFACES_BY_NODE +// entry before anything resolves the interface list. node may be empty, in +// which case the node name comes from the environment. +func applyNodeInterfaces(node string) error { + names, err := attach.ApplyNodeOverride(node) + if err != nil { + return fmt.Errorf("per-node eBPF interface selection: %w", err) + } + if names != nil { + slog.Info("Using this node's own eBPF interface list", "interfaces", names) + } + return nil +} + +// checkTransport resolves the selected interfaces through the transport +// contract and publishes the result: derived mode, VLAN ID, parent and members +// in the log and galactic_transport_side_info, and each change since the last +// check in galactic_transport_side_changes_total. +// +// It returns a *transport.ValidationError, such as a VLAN with ID 0, an +// 802.1ad VLAN, a stacked VLAN or a named interface that does not exist, so the +// caller can refuse to start. Any other failure, such as auto-detection finding +// no route yet, is logged and returns nil: ResolveInterfaces reports it on its +// own path, and the next check retries. +func checkTransport() error { + names, err := selectedInterfacesFn() + if err != nil { + reportTransportFailure(err) + return nil + } + rs, err := resolveTransportFn(transport.SideUnassigned, names) + if err == nil { + var set *transport.Set + if set, err = transport.NewSet(rs...); err == nil { + clearTransportFailure() + cniTransport.Observe(set) + return nil + } + } + reportTransportFailure(err) + var ve *transport.ValidationError + if errors.As(err, &ve) { + return err + } + return nil +} + +// lastTransportFailure is the failure checkTransport last reported, so a +// failure that persists across checks is logged and counted once, and +// galactic_transport_validation_failures_total counts distinct failures +// rather than health-check ticks. A success clears it. +var ( + transportFailureMu sync.Mutex + lastTransportFailure string +) + +func reportTransportFailure(err error) { + transportFailureMu.Lock() + defer transportFailureMu.Unlock() + if err.Error() == lastTransportFailure { + return + } + lastTransportFailure = err.Error() + cniTransport.Fail(err) +} + +func clearTransportFailure() { + transportFailureMu.Lock() + defer transportFailureMu.Unlock() + lastTransportFailure = "" +} + +// recheckTransport re-runs checkTransport after startup. A validation failure +// then is reported, not fatal: the datapath keeps the hooks it has, and +// checkTransport has already logged and counted it. +func recheckTransport() { + _ = checkTransport() +} + +// onAttachedSetChange is the watcher's OnChange callback: it keeps the +// conflist in step with the attached set and re-checks the transport sides. +func onAttachedSetChange(names []string) { + rewriteEBPFInterfaces(names) + recheckTransport() +} diff --git a/internal/installer/transport_test.go b/internal/installer/transport_test.go new file mode 100644 index 000000000..cd47aad2e --- /dev/null +++ b/internal/installer/transport_test.go @@ -0,0 +1,92 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "errors" + "testing" + + "go.datum.net/galactic/internal/plumbing/transport" +) + +func stubTransport(t *testing.T, selected []string, selErr error, + resolve func(transport.Side, []string) ([]transport.Resolution, error), +) { + t.Helper() + origSel, origRes, origTracker := selectedInterfacesFn, resolveTransportFn, cniTransport + t.Cleanup(func() { + selectedInterfacesFn, resolveTransportFn, cniTransport = origSel, origRes, origTracker + }) + selectedInterfacesFn = func() ([]string, error) { return selected, selErr } + resolveTransportFn = resolve + cniTransport = transport.NewTracker("test") + clearTransportFailure() + t.Cleanup(clearTransportFailure) +} + +func TestCheckTransport(t *testing.T) { + valid := func(side transport.Side, names []string) ([]transport.Resolution, error) { + return []transport.Resolution{{ + Side: side, Interface: names[0], Index: 7, Mode: transport.ModeTagged, + VLANID: 101, Parent: "bond0", ParentIndex: 3, Members: []string{"m0"}, + }}, nil + } + + t.Run("valid selection is observed", func(t *testing.T) { + stubTransport(t, []string{"bond0.101"}, nil, valid) + if err := checkTransport(); err != nil { + t.Fatal(err) + } + if lower, vid, ok := cniTransport.Current().VLANLower(7); !ok || lower != 3 || vid != 101 { + t.Fatalf("VLANLower = %d, %d, %v", lower, vid, ok) + } + }) + + t.Run("validation failure is returned", func(t *testing.T) { + stubTransport(t, []string{"bond0.0"}, nil, + func(side transport.Side, names []string) ([]transport.Resolution, error) { + return nil, &transport.ValidationError{Side: side, Interface: names[0], Rule: transport.RuleVLANID} + }) + var ve *transport.ValidationError + if err := checkTransport(); !errors.As(err, &ve) { + t.Fatalf("err = %v, want a *transport.ValidationError", err) + } + }) + + t.Run("a persisting failure is reported once and cleared by success", func(t *testing.T) { + calls := 0 + stubTransport(t, []string{"bond0.0"}, nil, + func(side transport.Side, names []string) ([]transport.Resolution, error) { + calls++ + if calls > 2 { + return valid(side, names) + } + return nil, &transport.ValidationError{Side: side, Interface: names[0], Rule: transport.RuleVLANID} + }) + _ = checkTransport() + first := lastTransportFailure + _ = checkTransport() + if first == "" || lastTransportFailure != first { + t.Fatalf("last failure = %q then %q, want one recorded failure", first, lastTransportFailure) + } + if err := checkTransport(); err != nil || lastTransportFailure != "" { + t.Fatalf("after success: err %v, last failure %q", err, lastTransportFailure) + } + }) + + t.Run("transient failures are not fatal", func(t *testing.T) { + stubTransport(t, nil, errors.New("no default route yet"), valid) + if err := checkTransport(); err != nil { + t.Fatalf("selection failure: %v", err) + } + stubTransport(t, []string{"bond0.101"}, nil, + func(transport.Side, []string) ([]transport.Resolution, error) { + return nil, errors.New("netlink dump interrupted") + }) + if err := checkTransport(); err != nil { + t.Fatalf("netlink failure: %v", err) + } + }) +} diff --git a/internal/plumbing/ebpf/attach/attach.go b/internal/plumbing/ebpf/attach/attach.go index 50cd6e532..f2788421a 100644 --- a/internal/plumbing/ebpf/attach/attach.go +++ b/internal/plumbing/ebpf/attach/attach.go @@ -109,7 +109,7 @@ func Start(pinDir string) (objs *prog.UsidObjects, ifaces []string, err error) { // Written before the attach and readiness-fatal: without its row, a hook on // a tagged side's parent or bond members claims untagged frames only and // leaves that side's SRv6 traffic to the kernel. - transport, err := SyncTransport(objs.TransportVlanTable, ifaces) + transport, err := syncTransportFn(objs.TransportVlanTable, ifaces) if err != nil { _ = objs.Close() return nil, nil, fmt.Errorf("attach: write transport VLAN context: %w", err) diff --git a/internal/plumbing/ebpf/attach/interfaces.go b/internal/plumbing/ebpf/attach/interfaces.go index 04687093e..dff9e4a1b 100644 --- a/internal/plumbing/ebpf/attach/interfaces.go +++ b/internal/plumbing/ebpf/attach/interfaces.go @@ -357,11 +357,12 @@ func expandBondSlaves(names []string) ([]string, error) { // The parent's slaves are what get added, not the parent itself, since // attaching to a bond master is inert for the same reason. // -// The tag is handled in the datapath, not here. NICs that strip it in hardware -// leave the frame at tc with ethertype IPv6 and the VLAN id in skb metadata, -// which usid_ingress pops before redirecting. A deployment whose NICs leave the -// tag in packet data would additionally need 802.1Q parsing, which the datapath -// does not have. +// The tag is handled in the datapath, not here. The kernel moves a single +// 802.1Q tag into skb metadata (vlan_tci) before tc ingress runs on the parent +// or a bond member, whether the NIC stripped it or left it in the frame, so +// usid_ingress checks it against transport_vlan_table and pops it after +// decapsulation. Only an 802.1ad outer tag or a second tag stays in packet +// data, and usid_ingress does not claim those frames. func vlanBondMaster(link netlink.Link) netlink.Link { if link.Type() != vlanLinkType { return nil diff --git a/internal/plumbing/ebpf/attach/selection.go b/internal/plumbing/ebpf/attach/selection.go new file mode 100644 index 000000000..b9ee9bbb2 --- /dev/null +++ b/internal/plumbing/ebpf/attach/selection.go @@ -0,0 +1,111 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "fmt" + "log/slog" + "os" + "strings" + + "go.datum.net/galactic/internal/config" +) + +// ApplyNodeOverride applies this node's entry in +// config.EnvCNIEBPFInterfacesByNode by setting config.EnvCNIEBPFInterfaces in +// the process environment, so ResolveInterfaces and everything downstream of +// it, including the conflist the installer writes for the CNI plugins, use the +// node's own list. It returns the applied list, nil when the variable is unset +// or does not name this node, in which case the environment is untouched. +// +// The per-node entry lets one cluster-wide DaemonSet name a tagged side on a +// node where the same interface name plays a different side elsewhere, such as +// a bond that is public on an edge node and fabric on a compute node. +// +// node is this node's name; empty reads config.EnvCNINodeName, then +// config.EnvNodeNameLegacy. A malformed value, or one set where the node name +// is unknown, is an error rather than a silent fall back to the cluster-wide +// list, which could attach to the other side's interface. +func ApplyNodeOverride(node string) ([]string, error) { + raw := os.Getenv(config.EnvCNIEBPFInterfacesByNode) + if strings.TrimSpace(raw) == "" { + return nil, nil + } + byNode, err := ParseInterfacesByNode(raw) + if err != nil { + return nil, err + } + if node == "" { + node = os.Getenv(config.EnvCNINodeName) + } + if node == "" { + node = os.Getenv(config.EnvNodeNameLegacy) + } + if node == "" { + return nil, fmt.Errorf("attach: %s is set but the node name is unknown; set %s or %s", + config.EnvCNIEBPFInterfacesByNode, config.EnvCNINodeName, config.EnvNodeNameLegacy) + } + names, ok := byNode[node] + if !ok { + return nil, nil + } + joined := strings.Join(names, ",") + if prev := os.Getenv(config.EnvCNIEBPFInterfaces); prev != "" && prev != joined { + slog.Info("attach: this node's interface list replaces the cluster-wide one", + "node", node, "interfaces", names, "clusterWide", prev) + } + if err := os.Setenv(config.EnvCNIEBPFInterfaces, joined); err != nil { + return nil, fmt.Errorf("attach: apply %s for node %q: %w", config.EnvCNIEBPFInterfacesByNode, node, err) + } + return names, nil +} + +// ParseInterfacesByNode parses config.EnvCNIEBPFInterfacesByNode: entries +// separated by semicolons or newlines, each "node=iface[,iface...]". Blank +// entries are skipped, so a YAML block scalar with a trailing newline works. +// A node listed twice, an entry without "=", an empty node name or an entry +// with no interfaces is an error. +func ParseInterfacesByNode(v string) (map[string][]string, error) { + out := make(map[string][]string) + for entry := range strings.FieldsFuncSeq(v, func(r rune) bool { return r == ';' || r == '\n' }) { + entry = strings.TrimSpace(entry) + if entry == "" { + continue + } + node, ifaces, ok := strings.Cut(entry, "=") + node = strings.TrimSpace(node) + if !ok || node == "" { + return nil, fmt.Errorf("attach: %s entry %q is not node=interface[,interface...]", + config.EnvCNIEBPFInterfacesByNode, entry) + } + if _, dup := out[node]; dup { + return nil, fmt.Errorf("attach: %s lists node %q twice", config.EnvCNIEBPFInterfacesByNode, node) + } + names := parseInterfaceList(ifaces) + if len(names) == 0 { + return nil, fmt.Errorf("attach: %s entry for node %q names no interfaces", + config.EnvCNIEBPFInterfacesByNode, node) + } + out[node] = names + } + return out, nil +} + +// SelectedInterfaces returns the logical interfaces the uSID datapath is +// pointed at, before ResolveInterfaces expands bonds into their members: +// config.EnvCNIEBPFInterfaces when set (after ApplyNodeOverride, this node's +// entry), otherwise auto-detection. It is what a component validates and +// reports as its transport sides, since an expanded bond member is not a side. +func SelectedInterfaces() ([]string, error) { + if override := os.Getenv(config.EnvCNIEBPFInterfaces); override != "" { + names := parseInterfaceList(override) + if len(names) == 0 { + return nil, fmt.Errorf("attach: %s is set to %q but contains no usable interface names", + config.EnvCNIEBPFInterfaces, override) + } + return names, nil + } + return autoDetectInterfaces() +} diff --git a/internal/plumbing/ebpf/attach/selection_test.go b/internal/plumbing/ebpf/attach/selection_test.go new file mode 100644 index 000000000..231eee57f --- /dev/null +++ b/internal/plumbing/ebpf/attach/selection_test.go @@ -0,0 +1,112 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "os" + "reflect" + "testing" + + "go.datum.net/galactic/internal/config" +) + +// Synthetic interface names. +const ( + taggedIface = "bond0.101" + otherIface = "bond1" +) + +func TestParseInterfacesByNode(t *testing.T) { + got, err := ParseInterfacesByNode("edge-a=bond0.101, bond1 ;compute-b=bond0\n\n compute-c = eth1;") + if err != nil { + t.Fatal(err) + } + want := map[string][]string{ + "edge-a": {taggedIface, otherIface}, + "compute-b": {"bond0"}, + "compute-c": {"eth1"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %v, want %v", got, want) + } + + for _, bad := range []string{"edge-a", "=bond0", "edge-a=", "edge-a= , ", "edge-a=x;edge-a=y"} { + if _, err := ParseInterfacesByNode(bad); err == nil { + t.Errorf("ParseInterfacesByNode(%q) succeeded, want an error", bad) + } + } +} + +func TestApplyNodeOverride(t *testing.T) { + const byNode = "edge-a=bond0.101,bond1;compute-b=bond0" + + t.Run("listed node replaces the cluster-wide list", func(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfacesByNode, byNode) + t.Setenv(config.EnvCNIEBPFInterfaces, "bond0") + got, err := ApplyNodeOverride("edge-a") + if err != nil || !reflect.DeepEqual(got, []string{taggedIface, otherIface}) { + t.Fatalf("got %v, %v", got, err) + } + if v := os.Getenv(config.EnvCNIEBPFInterfaces); v != "bond0.101,bond1" { + t.Fatalf("%s = %q", config.EnvCNIEBPFInterfaces, v) + } + names, err := SelectedInterfaces() + if err != nil || !reflect.DeepEqual(names, []string{taggedIface, otherIface}) { + t.Fatalf("SelectedInterfaces = %v, %v", names, err) + } + }) + + t.Run("node name from the environment", func(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfacesByNode, byNode) + t.Setenv(config.EnvCNIEBPFInterfaces, "") + t.Setenv(config.EnvCNINodeName, "") + t.Setenv(config.EnvNodeNameLegacy, "compute-b") + if got, err := ApplyNodeOverride(""); err != nil || !reflect.DeepEqual(got, []string{"bond0"}) { + t.Fatalf("got %v, %v", got, err) + } + }) + + t.Run("unlisted node keeps the cluster-wide list", func(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfacesByNode, byNode) + t.Setenv(config.EnvCNIEBPFInterfaces, "eth0") + if got, err := ApplyNodeOverride("other"); err != nil || got != nil { + t.Fatalf("got %v, %v", got, err) + } + if v := os.Getenv(config.EnvCNIEBPFInterfaces); v != "eth0" { + t.Fatalf("%s = %q, want it untouched", config.EnvCNIEBPFInterfaces, v) + } + }) + + t.Run("unset changes nothing", func(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfacesByNode, "") + t.Setenv(config.EnvCNIEBPFInterfaces, "eth0") + if got, err := ApplyNodeOverride("edge-a"); err != nil || got != nil { + t.Fatalf("got %v, %v", got, err) + } + }) + + t.Run("unknown node name is an error", func(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfacesByNode, byNode) + t.Setenv(config.EnvCNINodeName, "") + t.Setenv(config.EnvNodeNameLegacy, "") + if _, err := ApplyNodeOverride(""); err == nil { + t.Fatal("want an error without a node name") + } + }) + + t.Run("malformed value is an error", func(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfacesByNode, "edge-a") + if _, err := ApplyNodeOverride("edge-a"); err == nil { + t.Fatal("want an error for a malformed value") + } + }) +} + +func TestSelectedInterfacesRejectsEmptyOverride(t *testing.T) { + t.Setenv(config.EnvCNIEBPFInterfaces, " , ") + if _, err := SelectedInterfaces(); err == nil { + t.Fatal("want an error for an override with no names") + } +} diff --git a/internal/plumbing/ebpf/attach/transport.go b/internal/plumbing/ebpf/attach/transport.go index 971f64a2e..dcaaa3e91 100644 --- a/internal/plumbing/ebpf/attach/transport.go +++ b/internal/plumbing/ebpf/attach/transport.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "log/slog" - "os" "slices" "strconv" "strings" @@ -16,9 +15,8 @@ import ( "github.com/cilium/ebpf" "github.com/vishvananda/netlink" - "go.datum.net/galactic/internal/config" - "go.datum.net/galactic/internal/plumbing/bond" "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/transport" ) // Transport VLAN context for usid_ingress. @@ -34,80 +32,6 @@ import ( // the parent. transport_vlan_table tells it which of them, and whether // untagged frames, belong to a selected side. This file derives those rows. -// transportResolution is one selected interface's derived transport context. -// It has the shape of the per-side resolution the transport configuration -// work (#1404) adds, which is expected to replace it. -type transportResolution struct { - Interface string - Index int - Tagged bool - VLANID uint16 - Parent string - ParentIndex int - // Members are the bond members under Parent (tagged) or Interface - // (untagged), empty when that is not a bond. - Members []string -} - -// vlanIDMin and vlanIDMax bound a usable transport VLAN ID: 0 marks a -// priority-tagged frame and 4095 is reserved. -const ( - vlanIDMin = 1 - vlanIDMax = 4094 -) - -// resolveTransport derives name's transport context from netlink. A VLAN -// netdevice is tagged with its own ID and parent; anything else is untagged. -// An 802.1ad VLAN, an ID outside 1 to 4094 and a VLAN stacked on another VLAN -// are errors: the contract excludes them. -// -// transportPolicy calls it through resolveTransportFn, the seam the shared -// transport resolution (#1404) replaces it through. -var resolveTransportFn = resolveTransport - -func resolveTransport(name string, links []netlink.Link) (transportResolution, error) { - link, err := linkByNameFn(name) - if err != nil { - return transportResolution{}, fmt.Errorf("look up %q: %w", name, err) - } - r := transportResolution{Interface: name, Index: link.Attrs().Index} - if link.Type() != vlanLinkType { - if bond.IsMaster(link) { - r.Members = bond.SlaveNames(link, links) - } - return r, nil - } - - vlan, ok := link.(*netlink.Vlan) - if !ok { - return transportResolution{}, fmt.Errorf("%q reports type vlan but carries no VLAN attributes", name) - } - if vlan.VlanProtocol != netlink.VLAN_PROTOCOL_UNKNOWN && vlan.VlanProtocol != netlink.VLAN_PROTOCOL_8021Q { - return transportResolution{}, fmt.Errorf("%q uses VLAN protocol %s; only 802.1Q is a transport VLAN", - name, vlan.VlanProtocol) - } - if vlan.VlanId < vlanIDMin || vlan.VlanId > vlanIDMax { - return transportResolution{}, fmt.Errorf("%q has VLAN ID %d, outside %d to %d", - name, vlan.VlanId, vlanIDMin, vlanIDMax) - } - parent, err := linkByIndexFn(link.Attrs().ParentIndex) - if err != nil { - return transportResolution{}, fmt.Errorf("look up parent %d of %q: %w", link.Attrs().ParentIndex, name, err) - } - if parent.Type() == vlanLinkType { - return transportResolution{}, fmt.Errorf("%q is stacked on VLAN %q; stacked tags are not a transport VLAN", - name, parent.Attrs().Name) - } - r.Tagged = true - r.VLANID = uint16(vlan.VlanId) - r.Parent = parent.Attrs().Name - r.ParentIndex = parent.Attrs().Index - if bond.IsMaster(parent) { - r.Members = bond.SlaveNames(parent, links) - } - return r, nil -} - // transportAccept is the transport VLAN context one hook accepts. type transportAccept struct { untagged bool @@ -168,23 +92,20 @@ func transportPolicy(selected []string) (policy map[string]*transportAccept, err return policy[name] } - links, err := linkListFn() - if err != nil { - return policy, []error{fmt.Errorf("enumerate links for bond members: %w", err)} - } for _, name := range selected { - r, err := resolveTransportFn(name, links) + r, err := transport.ResolveWith(attachLinks{}, transport.SideUnassigned, name) if err != nil { errs = append(errs, err) continue } at(r.Interface).untagged = true - if !r.Tagged { + if !r.Tagged() { for _, m := range r.Members { at(m).untagged = true } continue } + // Members is the parent itself when the parent is not a bond. at(r.Parent).addVLAN(r.VLANID) for _, m := range r.Members { at(m).addVLAN(r.VLANID) @@ -194,19 +115,16 @@ func transportPolicy(selected []string) (policy map[string]*transportAccept, err } // resolveSelectedFn returns the interfaces selected for usid_ingress before -// bond expansion: the override, or auto-detection. It is the first half of -// ResolveInterfaces and an override point for tests. -var resolveSelectedFn = func() ([]string, error) { - if override := os.Getenv(config.EnvCNIEBPFInterfaces); override != "" { - names := parseInterfaceList(override) - if len(names) == 0 { - return nil, fmt.Errorf("attach: %s is set to %q but contains no usable interface names", - config.EnvCNIEBPFInterfaces, override) - } - return names, nil - } - return autoDetectInterfaces() -} +// bond expansion. It is an override point for tests. +var resolveSelectedFn = SelectedInterfaces + +// attachLinks is the transport.Links view over this package's netlink +// override vars, so tests that fake those fake the transport resolution too. +type attachLinks struct{} + +func (attachLinks) LinkByName(name string) (netlink.Link, error) { return linkByNameFn(name) } +func (attachLinks) LinkByIndex(index int) (netlink.Link, error) { return linkByIndexFn(index) } +func (attachLinks) LinkList() ([]netlink.Link, error) { return linkListFn() } // transportTable is the part of *ebpf.Map SyncTransport uses, so tests can // substitute a fake without root. @@ -233,6 +151,10 @@ func (t ebpfTransportTable) Keys() ([]uint32, error) { return keys, iter.Err() } +// syncTransportFn is how Start and Watch call SyncTransport, an override point +// so tests can check the rows are written before usid_ingress attaches. +var syncTransportFn = SyncTransport + // SyncTransport writes transport_vlan_table for the attached interfaces from // the current interface selection, and returns the context written per // interface for logging. diff --git a/internal/plumbing/ebpf/attach/transport_order_test.go b/internal/plumbing/ebpf/attach/transport_order_test.go new file mode 100644 index 000000000..2b9f6d5cb --- /dev/null +++ b/internal/plumbing/ebpf/attach/transport_order_test.go @@ -0,0 +1,147 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "context" + "fmt" + "os" + "path/filepath" + "slices" + "sync" + "testing" + "time" + + "github.com/cilium/ebpf" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/config" +) + +// TestWatch_WritesTransportRowsBeforeReattaching checks that every Watch +// re-evaluation rewrites transport_vlan_table before it (re)attaches +// usid_ingress, so a hook placed by that pass never runs without its side's +// VLAN context. +func TestWatch_WritesTransportRowsBeforeReattaching(t *testing.T) { + withWatchTestDefaults(t) + origSync := syncTransportFn + t.Cleanup(func() { syncTransportFn = origSync }) + + var ( + mu sync.Mutex + calls []string + ) + record := func(s string) { + mu.Lock() + defer mu.Unlock() + calls = append(calls, s) + } + syncTransportFn = func(_ *ebpf.Map, attached []string) (map[string]string, error) { + record(fmt.Sprintf("sync %v", attached)) + return nil, nil + } + reconcileFn = func(_ *ebpf.Program, _, next map[string]struct{}) map[string]struct{} { + record("reconcile") + return next + } + resolveInterfacesFn = func() ([]string, error) { return []string{"bond0.101"}, nil } + + trigger := make(chan struct{}, 1) + linkSubscribeFn = stubLinkSubscribe(trigger) + done := make(chan struct{}, 1) + onReconcileDone = func() { + select { + case done <- struct{}{}: + default: + } + } + + w := newWatcher() + w.transport = new(ebpf.Map) // never dereferenced: syncTransportFn is faked + ctx, cancel := context.WithCancel(context.Background()) + errc := make(chan error, 1) + go func() { errc <- Watch(ctx, new(ebpf.Program), []string{"bond0.101"}, w) }() + + trigger <- struct{}{} + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Watch never re-evaluated") + } + cancel() + if err := <-errc; err != nil { + t.Fatalf("Watch: %v", err) + } + + mu.Lock() + defer mu.Unlock() + if want := []string{"sync [bond0.101]", "reconcile"}; !slices.Equal(calls, want) { + t.Fatalf("calls = %v, want %v", calls, want) + } +} + +// TestStart_WritesTransportRowsBeforeAttaching checks on a real kernel that +// Start writes transport_vlan_table while the selected interface still has no +// usid_ingress filter, and attaches it afterwards. +func TestStart_WritesTransportRowsBeforeAttaching(t *testing.T) { + requireRoot(t) + const uplink = "order-uplink" + pin := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-transport-order-%d", os.Getpid())) + t.Cleanup(func() { _ = os.RemoveAll(pin) }) + t.Setenv(config.EnvCNIEBPFInterfaces, uplink) + t.Setenv(config.EnvCNIEBPFInterfacesByNode, "") + + origSync := syncTransportFn + t.Cleanup(func() { syncTransportFn = origSync }) + + network, err := ns.TempNetNS() + if err != nil { + t.Fatal(err) + } + defer func() { _ = network.Close() }() + + err = network.Do(func(_ ns.NetNS) error { + link := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: uplink}} + if err := netlink.LinkAdd(link); err != nil { + return err + } + if err := netlink.LinkSetUp(link); err != nil { + return err + } + + var filtersAtSync = -1 + syncTransportFn = func(table *ebpf.Map, attached []string) (map[string]string, error) { + filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) + if err != nil { + return nil, err + } + filtersAtSync = len(filters) + return SyncTransport(table, attached) + } + + objs, _, err := Start(pin) + if err != nil { + return fmt.Errorf("start: %w", err) + } + defer func() { _ = objs.Close() }() + + if filtersAtSync != 0 { + return fmt.Errorf("transport_vlan_table written with %d ingress filters already on %s, want 0", + filtersAtSync, uplink) + } + filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) + if err != nil { + return err + } + if len(filters) == 0 { + return fmt.Errorf("no usid_ingress filter on %s after Start", uplink) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/plumbing/ebpf/attach/transport_test.go b/internal/plumbing/ebpf/attach/transport_test.go index 27a1a25bd..bed4ae9b6 100644 --- a/internal/plumbing/ebpf/attach/transport_test.go +++ b/internal/plumbing/ebpf/attach/transport_test.go @@ -31,7 +31,9 @@ const ( // VLAN and a VLAN with ID 0. Only synthetic names and IDs. func transportFixture(t *testing.T) { t.Helper() - nic := &fakeLink{attrs: netlink.LinkAttrs{Name: tNIC, Index: 2}} + // The transport contract accepts a VLAN only on a NIC ("device"), a bond + // or a veth. + nic := &fakeLink{attrs: netlink.LinkAttrs{Name: tNIC, Index: 2}, linkType: "device"} bondMaster := &fakeLink{attrs: netlink.LinkAttrs{Name: attachedBond, Index: 3}, linkType: "bond"} m1 := &fakeLink{attrs: netlink.LinkAttrs{Name: "m1", Index: 4, MasterIndex: 3}} m2 := &fakeLink{attrs: netlink.LinkAttrs{Name: "m2", Index: 5, MasterIndex: 3}} diff --git a/internal/plumbing/ebpf/attach/watch.go b/internal/plumbing/ebpf/attach/watch.go index a391262c5..a6ba2e8b2 100644 --- a/internal/plumbing/ebpf/attach/watch.go +++ b/internal/plumbing/ebpf/attach/watch.go @@ -93,7 +93,7 @@ func (w *Watcher) syncTransport(attached []string) { if w == nil || w.transport == nil { return } - written, err := SyncTransport(w.transport, attached) + written, err := syncTransportFn(w.transport, attached) if err != nil { slog.Warn("attach: write transport VLAN context failed, retrying on the next re-evaluation", "err", err) } diff --git a/internal/plumbing/ebpf/edgeattach/vlan_local_usid_root_test.go b/internal/plumbing/ebpf/edgeattach/vlan_local_usid_root_test.go new file mode 100644 index 000000000..d34b19490 --- /dev/null +++ b/internal/plumbing/ebpf/edgeattach/vlan_local_usid_root_test.go @@ -0,0 +1,315 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package edgeattach + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "os" + "slices" + "testing" + "time" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/ebpf/attach" + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/uformat" +) + +// The same-node test below gives the gateway's node a real uSID locator, so +// galactic-cni's usid_ingress can claim what edge_lb hands up for it. +const ( + vtNode = "edge-node-a" + vtLocalBlock = 0x20010db8000b // 2001:db8:b::/48 + vtLocalNodeID = 0x0001 + vtLocalArg = 0x123 + vtTenantTable = 100 + vtEgressTap = 1 // EGRESS_KIND_TAP + vtEndDT46 = 1 // BEHAVIOR_END_DT46 +) + +var vtTenantMAC = net.HardwareAddr{0x02, 0x00, 0x00, 0x00, 0x0a, 0x10} + +// vtNodeUSID returns the uSID for the tenant's VPC on the gateway's node, and +// the node's encapsulation source, which shares its locator. +func vtNodeUSID(t *testing.T) (usid, encapSrc netip.Addr) { + t.Helper() + usid, err := uformat.Encode(uformat.Fields{Block: vtLocalBlock, NodeID: vtLocalNodeID, + Function: uformat.FunctionEndDT46, Argument: vtLocalArg}) + if err != nil { + t.Fatalf("encode the node's uSID: %v", err) + } + src, err := uformat.Encode(uformat.Fields{Block: vtLocalBlock, NodeID: vtLocalNodeID}) + if err != nil { + t.Fatalf("encode the node's locator: %v", err) + } + b := src.As16() + b[15] = 1 + return usid, netip.AddrFrom16(b) +} + +// vtOpenTap creates a tap in the current namespace, owned by the returned +// descriptor, and brings it up. +func vtOpenTap(t *testing.T, name string) (int, error) { + t.Helper() + fd, err := unix.Open("/dev/net/tun", unix.O_RDWR|unix.O_CLOEXEC|unix.O_NONBLOCK, 0) + if err != nil { + return 0, fmt.Errorf("open /dev/net/tun: %w", err) + } + t.Cleanup(func() { _ = unix.Close(fd) }) + ifr, err := unix.NewIfreq(name) + if err != nil { + return 0, err + } + ifr.SetUint16(unix.IFF_TAP | unix.IFF_NO_PI) + if err := unix.IoctlIfreq(fd, unix.TUNSETIFF, ifr); err != nil { + return 0, fmt.Errorf("create tap %s: %w", name, err) + } + return fd, vtUp(name) +} + +// vtTapFrames returns every frame read from the tap within wait that contains +// marker. +func vtTapFrames(t *testing.T, fd int, marker []byte, wait time.Duration) [][]byte { + t.Helper() + var out [][]byte + deadline := time.Now().Add(wait) + buf := make([]byte, 65536) + for time.Now().Before(deadline) { + fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} + n, err := unix.Poll(fds, int(time.Until(deadline).Milliseconds())+1) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + t.Fatalf("poll tap: %v", err) + } + if n == 0 { + break + } + n, err = unix.Read(fd, buf) + if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + t.Fatalf("read tap: %v", err) + } + if bytes.Contains(buf[:n], marker) { + out = append(out, bytes.Clone(buf[:n])) + } + } + return out +} + +// vtUsidDrops returns usid_ingress's nonzero drop_reasons slots, trace slots +// included, to say where an undelivered packet stopped. +func vtUsidDrops(objs *prog.UsidObjects) map[uint32]uint64 { + out := make(map[uint32]uint64) + for i := range objs.DropReasons.MaxEntries() { + var perCPU []uint64 + if err := objs.DropReasons.Lookup(i, &perCPU); err != nil { + continue + } + var total uint64 + for _, v := range perCPU { + total += v + } + if total != 0 { + out[i] = total + } + } + return out +} + +// vtTenant loads usid_ingress and gives the gateway's namespace one tenant +// attachment, the tap dt0 in routing table vtTenantTable with a route and a +// permanent neighbor for vtVIP, registered for usid as CNI ADD registers it. +// It returns the objects and the tap's descriptor. +func (l *vtLab) vtTenant(usid netip.Addr) (*prog.UsidObjects, int) { + t := l.t + t.Helper() + var objs prog.UsidObjects + if err := prog.LoadUsidObjects(&objs, nil); err != nil { + t.Fatalf("load usid objects: %v", err) + } + t.Cleanup(func() { _ = objs.Close() }) + + var tapFd int + in(t, l.gw, func() error { + var err error + if tapFd, err = vtOpenTap(t, "dt0"); err != nil { + return err + } + tap, err := netlink.LinkByName("dt0") + if err != nil { + return err + } + if err := netlink.RouteAdd(&netlink.Route{LinkIndex: tap.Attrs().Index, Table: vtTenantTable, + Dst: &net.IPNet{IP: vtVIP.AsSlice(), Mask: net.CIDRMask(128, 128)}}); err != nil { + return fmt.Errorf("add tenant route: %w", err) + } + if err := netlink.NeighAdd(&netlink.Neigh{LinkIndex: tap.Attrs().Index, Family: netlink.FAMILY_V6, + State: netlink.NUD_PERMANENT, IP: vtVIP.AsSlice(), HardwareAddr: vtTenantMAC}); err != nil { + return fmt.Errorf("add tenant neighbor: %w", err) + } + return objs.IfindexEgressKindTable.Put(uint32(tap.Attrs().Index), uint32(vtEgressTap)) + }) + + locator, err := uformat.LocatorKeyFromAddr(usid) + if err != nil { + t.Fatal(err) + } + function, err := uformat.FunctionKeyFromAddr(usid) + if err != nil { + t.Fatal(err) + } + vrf, err := uformat.VRFKeyFromAddr(usid) + if err != nil { + t.Fatal(err) + } + if err := objs.LocatorTable.Put(uint64(locator), prog.UsidLocatorValue{Generation: 1}); err != nil { + t.Fatalf("populate locator_table: %v", err) + } + if err := objs.FunctionTable.Put(uint64(function), prog.UsidFunctionValue{Behavior: vtEndDT46}); err != nil { + t.Fatalf("populate function_table: %v", err) + } + if err := objs.VrfTable.Put(uint64(vrf), + prog.UsidVrfValue{VrfTableId: vtTenantTable, EgressKind: vtEgressTap}); err != nil { + t.Fatalf("populate vrf_table: %v", err) + } + return &objs, tapFd +} + +// vtAttachUsid selects usid_ingress's interfaces as galactic-cni does, from +// this node's entry in the per-node list, writes their transport_vlan_table +// rows and attaches usid_ingress to them in the gateway's namespace. It +// returns the interfaces it attached to. +func (l *vtLab) vtAttachUsid(objs *prog.UsidObjects) []string { + t := l.t + t.Helper() + t.Setenv(config.EnvCNIEBPFInterfacesByNode, vtNode+"="+l.pubLogical) + t.Setenv(config.EnvCNIEBPFInterfaces, "") // ApplyNodeOverride sets it; restore after + t.Setenv(config.EnvCNINodeName, "") + t.Setenv(config.EnvNodeNameLegacy, vtNode) + + var targets []string + in(t, l.gw, func() error { + applied, err := attach.ApplyNodeOverride("") + if err != nil { + return err + } + if !slices.Equal(applied, []string{l.pubLogical}) { + return fmt.Errorf("node override applied %v, want [%s]", applied, l.pubLogical) + } + if targets, err = attach.ResolveInterfaces(); err != nil { + return err + } + contexts, err := attach.SyncTransport(objs.TransportVlanTable, targets) + if err != nil { + return err + } + t.Logf("usid_ingress targets %v, transport contexts %v", targets, contexts) + return attach.Attach(objs.UsidIngress, targets) + }) + if !slices.Equal(targets, []string{l.pubLogical}) { + t.Fatalf("usid_ingress resolved to %v, want only the public VLAN netdevice %s", targets, l.pubLogical) + } + in(t, l.gw, func() error { + var row prog.UsidTransportVlanValue + if err := objs.TransportVlanTable.Lookup(uint32(mustIndex(l.pubLogical)), &row); err != nil { + return fmt.Errorf("transport_vlan_table has no row for %s: %w", l.pubLogical, err) + } + if row.Allowed[0]&1 == 0 { + return fmt.Errorf("%s's transport_vlan_table row %+v does not accept untagged frames, "+ + "which is how its own VLAN reaches a hook on the VLAN netdevice", l.pubLogical, row.Allowed) + } + return nil + }) + return targets +} + +// TestVLANTransport_SameNodeDeliveryThroughUsidIngress covers same-node +// gateway delivery on a tagged public side end to end, in each host mode. +// edge_lb on the public VLAN netdevice encapsulates a client's VIP packet +// toward a uSID on its own node and hands it up with XDP_PASS. usid_ingress, +// attached to the same VLAN netdevice as galactic-cni selects it from the +// node's interface list, claims it for the node's locator, decapsulates it and +// delivers the client's original packet to the tenant attachment once, with no +// tag, and nothing leaves through the fabric. +func TestVLANTransport_SameNodeDeliveryThroughUsidIngress(t *testing.T) { + requireRoot(t) + if _, err := os.Stat("/dev/net/tun"); err != nil { + t.Skipf("test requires /dev/net/tun: %v", err) + } + for modeName, mode := range vtHostModes(t) { + t.Run(modeName, func(t *testing.T) { + l := newVTLab(t, vtTopo{pubTagged: true, fabTagged: true, localBackend: true}, mode) + + // The lab's own local backend and encapsulation source are the + // node's End.DT46 uSID and locator address, so the gateway + // already encapsulates toward a uSID usid_ingress can deliver. + usid, encapSrc := vtNodeUSID(t) + if usid != vtLocalUSID || encapSrc != vtFabGW { + t.Fatalf("lab fixture uses %s from %s, want the node's uSID %s from %s", + vtLocalUSID, vtFabGW, usid, encapSrc) + } + + usidObjs, tapFd := l.vtTenant(usid) + l.vtAttachUsid(usidObjs) + + m := marker("same-node") + l.send(l.rtr, l.rtrLogical, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40005, vtPort, m)) + frames := vtTapFrames(t, tapFd, m, 2*time.Second) + if len(frames) == 0 { + var delivered []uint64 + _ = l.objs.LocalDeliveries.Lookup(uint32(0), &delivered) + t.Fatalf("the client's packet never reached the tenant tap (vip packets %d, local_deliveries %v, "+ + "usid_ingress nonzero drop_reasons %v)", l.vipPackets(), delivered, vtUsidDrops(usidObjs)) + } + if len(frames) != 1 { + t.Errorf("the tenant received the packet %d times, want once", len(frames)) + } + f := frames[0] + const ether, nexthdr, saddr, daddr = 12, 14 + 6, 14 + 8, 14 + 24 + if len(f) < daddr+16 { + t.Fatalf("tenant frame is %d bytes, too short for IPv6", len(f)) + } + if et := binary.BigEndian.Uint16(f[ether : ether+2]); et != unix.ETH_P_IPV6 { + t.Errorf("tenant frame's EtherType %#04x, want 0x86dd with no tag", et) + } + if !bytes.Equal(f[0:6], vtTenantMAC) { + t.Errorf("tenant frame's destination MAC %x, want the tenant's %s", f[0:6], vtTenantMAC) + } + src := netip.AddrFrom16([16]byte(f[saddr : saddr+16])) + dst := netip.AddrFrom16([16]byte(f[daddr : daddr+16])) + if f[nexthdr] != unix.IPPROTO_UDP || src != vtClient || dst != vtVIP { + t.Errorf("tenant received next header %d from %s to %s, want the client's UDP packet %s to %s", + f[nexthdr], src, dst, vtClient, vtVIP) + } + + var delivered []uint64 + if err := l.objs.LocalDeliveries.Lookup(uint32(0), &delivered); err != nil { + t.Fatalf("read local_deliveries: %v", err) + } + var total uint64 + for _, v := range delivered { + total += v + } + if total != 1 { + t.Errorf("local_deliveries = %d, want 1", total) + } + if _, ok := vtAwait(t, l.nhCap, m, 300*time.Millisecond); ok { + t.Errorf("the locally delivered packet also left through the fabric") + } + }) + } +} diff --git a/internal/plumbing/ebpf/edgeattach/vlan_root_test.go b/internal/plumbing/ebpf/edgeattach/vlan_root_test.go index a666ee07a..c1968e9b1 100644 --- a/internal/plumbing/ebpf/edgeattach/vlan_root_test.go +++ b/internal/plumbing/ebpf/edgeattach/vlan_root_test.go @@ -30,6 +30,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" + "go.datum.net/galactic/internal/plumbing/transport" ) // The VLAN transport tests below run the gateway's programs on a real kernel, @@ -58,11 +59,15 @@ var ( vtPubGW = netip.MustParseAddr("fd00:a::1") vtPubRtr = netip.MustParseAddr("fd00:a::2") vtOtherGW = netip.MustParseAddr("fd00:c::1") - vtFabGW = netip.MustParseAddr("fd00:b::1") - vtFabNH = netip.MustParseAddr("fd00:b::2") - // vtLocalUSID shares its first 64 bits with vtFabGW, the gateway's - // encapsulation source, which makes it a uSID on the gateway's own node. - vtLocalUSID = netip.MustParseAddr("fd00:b::a1b2") + // vtFabGW, the gateway's encapsulation source, sits in its node's uSID + // locator 2001:db8:b:1::/64 (block 2001:db8:b, node 1). + vtFabGW = netip.MustParseAddr("2001:db8:b:1::1") + vtFabNH = netip.MustParseAddr("2001:db8:b:1::2") + // vtLocalUSID shares its first 64 bits with vtFabGW, which makes it a + // uSID on the gateway's own node. It is a deliverable uFMT 48+16 uSID: + // End.DT46 (function 0xe) with argument 0x123, since usid_ingress + // refuses the reserved argument 0. + vtLocalUSID = netip.MustParseAddr("2001:db8:b:1:e123::") ) // vtHostModes are the host modes each case runs in, as GALACTIC_XDP_MODE @@ -423,11 +428,14 @@ func (l *vtLab) load(topo vtTopo, mode xdpmode.Mode) error { return err } } - lowers, ifindexes, err := vlanegress.FromNetlink([]string{l.pubLogical, l.fabLogical}) + set, ifindexes, err := vlanegress.Resolve( + vlanegress.Side{Side: transport.SidePublic, Names: []string{l.pubLogical}}, + vlanegress.Side{Side: transport.SideFabric, Names: []string{l.fabLogical}}, + ) if err != nil { return err } - return vlanegress.Sync(l.objs.VlanEgress, lowers, ifindexes) + return vlanegress.Sync(l.objs.VlanEgress, set, ifindexes) } // vip loads one UDP VIP whose only backend is vtUSID, or vtLocalUSID on diff --git a/internal/plumbing/ebpf/vlanegress/recreate_root_test.go b/internal/plumbing/ebpf/vlanegress/recreate_root_test.go new file mode 100644 index 000000000..8101fb525 --- /dev/null +++ b/internal/plumbing/ebpf/vlanegress/recreate_root_test.go @@ -0,0 +1,150 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package vlanegress + +import ( + "os" + "testing" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/rlimit" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/containernetworking/plugins/pkg/testutils" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/transport" +) + +func requireRoot(t *testing.T) { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("test requires root (CAP_BPF/CAP_NET_ADMIN) to create a BPF map and VLAN netdevices; " + + "re-run via task test:unit-root") + } +} + +// rows returns every vlan_egress row in m. +func rows(t *testing.T, m *ebpf.Map) map[uint32]Value { + t.Helper() + out := map[uint32]Value{} + var ( + k uint32 + v Value + ) + iter := m.Iterate() + for iter.Next(&k, &v) { + out[k] = v + } + if err := iter.Err(); err != nil { + t.Fatalf("iterate vlan_egress: %v", err) + } + return out +} + +// TestSyncFollowsVLANRecreation walks one tagged side through the contract's +// reconfiguration events on a real kernel, re-syncing after each the way the +// gateway's and NAT's link watchers do: the VLAN netdevice recreated with a +// new ID (and so a new ifindex), the side moved to untagged, and back. After +// each, vlan_egress holds exactly the current side's row and nothing keyed by +// an old ifindex. +func TestSyncFollowsVLANRecreation(t *testing.T) { + requireRoot(t) + if err := rlimit.RemoveMemlock(); err != nil { + t.Fatalf("remove memlock limit: %v", err) + } + m, err := ebpf.NewMap(&ebpf.MapSpec{ + Type: ebpf.Hash, KeySize: 4, ValueSize: 8, MaxEntries: 16, + }) + if err != nil { + t.Fatalf("create vlan_egress stand-in: %v", err) + } + t.Cleanup(func() { _ = m.Close() }) + + netns, err := testutils.NewNS() + if err != nil { + t.Fatalf("create netns: %v", err) + } + t.Cleanup(func() { + _ = netns.Close() + _ = testutils.UnmountNS(netns) + }) + + err = netns.Do(func(ns.NetNS) error { + if err := netlink.LinkAdd(&netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "pub0"}, PeerName: "pub0p"}); err != nil { + t.Fatalf("add parent: %v", err) + } + parent, err := netlink.LinkByName("pub0") + if err != nil { + t.Fatal(err) + } + addVLAN := func(vid int) int { + t.Helper() + err := netlink.LinkAdd(&netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: "pub0.v", ParentIndex: parent.Attrs().Index}, + VlanId: vid, + VlanProtocol: netlink.VLAN_PROTOCOL_8021Q, + }) + if err != nil { + t.Fatalf("add VLAN %d: %v", vid, err) + } + l, err := netlink.LinkByName("pub0.v") + if err != nil { + t.Fatal(err) + } + return l.Attrs().Index + } + sync := func(name string) { + t.Helper() + set, ifindexes, err := Resolve(Side{Side: transport.SidePublic, Names: []string{name}}) + if err != nil { + t.Fatalf("resolve %s: %v", name, err) + } + if err := Sync(m, set, ifindexes); err != nil { + t.Fatalf("sync: %v", err) + } + } + want := func(stage string, expect map[uint32]Value) { + t.Helper() + got := rows(t, m) + if len(got) != len(expect) { + t.Fatalf("%s: vlan_egress = %v, want %v", stage, got, expect) + } + for k, v := range expect { + if got[k] != v { + t.Fatalf("%s: vlan_egress = %v, want %v", stage, got, expect) + } + } + } + lower := uint32(parent.Attrs().Index) + + first := addVLAN(101) + sync("pub0.v") + want("tagged", map[uint32]Value{uint32(first): {LowerIfindex: lower, VID: 101}}) + + // Infrastructure replaces the VLAN netdevice with a new ID. + old, _ := netlink.LinkByName("pub0.v") + if err := netlink.LinkDel(old); err != nil { + t.Fatal(err) + } + second := addVLAN(111) + if second == first { + t.Fatalf("recreated VLAN kept ifindex %d; the test needs a new one", first) + } + sync("pub0.v") + want("recreated", map[uint32]Value{uint32(second): {LowerIfindex: lower, VID: 111}}) + + // The side moves to untagged: the setting names the parent. + sync("pub0") + want("untagged", map[uint32]Value{}) + + // And back to tagged. + sync("pub0.v") + want("tagged again", map[uint32]Value{uint32(second): {LowerIfindex: lower, VID: 111}}) + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/plumbing/ebpf/vlanegress/vlanegress.go b/internal/plumbing/ebpf/vlanegress/vlanegress.go index 148b77fa8..7083c02fa 100644 --- a/internal/plumbing/ebpf/vlanegress/vlanegress.go +++ b/internal/plumbing/ebpf/vlanegress/vlanegress.go @@ -10,8 +10,9 @@ // netdevice has no ndo_xdp_xmit. For each configured tagged side the map holds // the VLAN netdevice's lower device and VLAN ID, and the program pushes the tag // and redirects to the lower device instead. Rows are derived from netlink -// only, never from a separate setting, and only for the logical interfaces the -// component is configured with: see docs/designs/vlan-transport/contract.md. +// only, through internal/plumbing/transport, never from a separate setting, +// and only for the logical interfaces the component is configured with: see +// docs/designs/vlan-transport/contract.md. package vlanegress import ( @@ -19,13 +20,13 @@ import ( "fmt" "github.com/cilium/ebpf" - "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/transport" ) // Lowers resolves a configured tagged side's VLAN netdevice to its lower // device and VLAN ID. ok is false for any ifindex that is not a configured -// tagged side. The shared transport resolution's Set implements it; Netlink is -// a minimal implementation over netlink for the named logical interfaces. +// tagged side. *transport.Set implements it. type Lowers interface { VLANLower(ifindex int) (lower int, vid uint16, ok bool) } @@ -89,80 +90,50 @@ func Sync(m Table, lowers Lowers, ifindexes []int) error { return errors.Join(errs...) } -// linkByNameFn and linkByIndexFn are override points so tests can substitute a -// fake netlink view. -var ( - linkByNameFn = netlink.LinkByName - linkByIndexFn = netlink.LinkByIndex -) - -// Netlink is Lowers over netlink for a fixed set of logical interfaces. -type Netlink struct { - rows map[int]Value +// Side names the logical interfaces a component is configured with for one +// transport side. transport.SideUnassigned is for a list that may hold both +// sides, such as the egress translation shard's uplinks. +type Side struct { + Side transport.Side + Names []string } -// VLANLower implements Lowers. -func (n *Netlink) VLANLower(ifindex int) (int, uint16, bool) { - v, ok := n.rows[ifindex] - return int(v.LowerIfindex), v.VID, ok -} +// links is the netlink view Resolve reads; tests substitute a fake. +var links = transport.Netlink -// FromNetlink resolves each of names, the logical interfaces of a component's -// configured sides. It returns their ifindexes, in order, and a Lowers holding -// every one that is an 802.1Q VLAN netdevice with an ID from 1 to 4094 on a -// parent that exists and is not itself a VLAN: a usable tagged side. An empty -// name is skipped. +// Resolve resolves every named logical interface through the shared transport +// resolution and returns the resulting Set, which is the Lowers Sync takes, +// and every resolved interface's ifindex. An empty name is skipped. // -// A name that does not resolve, or a VLAN netdevice that is not a usable -// tagged side, is left out and reported in the returned error; the caller -// decides whether that is fatal. Without a row, the datapath redirects to the -// VLAN netdevice as the FIB names it, which transmits only in generic mode. -func FromNetlink(names []string) (*Netlink, []int, error) { - n := &Netlink{rows: map[int]Value{}} +// A name that does not resolve, or that breaks the transport contract (VLAN ID +// 0, 802.1ad, stacked tags, a missing or unsupported parent), is left out and +// reported in the returned error; the caller decides whether that is fatal. +// Without a row, the datapath redirects to the VLAN netdevice as the FIB names +// 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) { var ( + resolved []transport.Resolution ifindexes []int errs []error ) - for _, name := range names { - if name == "" { - continue + for _, s := range sides { + for _, name := range s.Names { + if name == "" { + continue + } + r, err := transport.ResolveWith(links, s.Side, name) + if err != nil { + errs = append(errs, err) + continue + } + resolved = append(resolved, r) + ifindexes = append(ifindexes, r.Index) } - l, err := linkByNameFn(name) - if err != nil { - errs = append(errs, fmt.Errorf("vlanegress: find link %q: %w", name, err)) - continue - } - ifindex := l.Attrs().Index - ifindexes = append(ifindexes, ifindex) - vlan, ok := l.(*netlink.Vlan) - if !ok { - continue - } - if err := usable(vlan); err != nil { - errs = append(errs, err) - continue - } - n.rows[ifindex] = Value{LowerIfindex: uint32(vlan.ParentIndex), VID: uint16(vlan.VlanId)} - } - return n, ifindexes, errors.Join(errs...) -} - -// usable reports why vlan cannot carry a tagged side, or nil. -func usable(vlan *netlink.Vlan) error { - name := vlan.Attrs().Name - if vlan.VlanProtocol != netlink.VLAN_PROTOCOL_UNKNOWN && vlan.VlanProtocol != netlink.VLAN_PROTOCOL_8021Q { - return fmt.Errorf("vlanegress: %s uses VLAN protocol %s; only 802.1Q is a supported transport tag", - name, vlan.VlanProtocol) } - if vlan.VlanId < 1 || vlan.VlanId > 4094 { - return fmt.Errorf("vlanegress: %s has VLAN ID %d, outside 1 to 4094", name, vlan.VlanId) - } - parent, err := linkByIndexFn(vlan.ParentIndex) + set, err := transport.NewSet(resolved...) if err != nil { - return fmt.Errorf("vlanegress: find parent %d of %s: %w", vlan.ParentIndex, name, err) - } - if _, stacked := parent.(*netlink.Vlan); stacked { - return fmt.Errorf("vlanegress: %s sits on VLAN %s; stacked tags are not supported", name, parent.Attrs().Name) + errs = append(errs, err) } - return nil + return set, ifindexes, errors.Join(errs...) } diff --git a/internal/plumbing/ebpf/vlanegress/vlanegress_test.go b/internal/plumbing/ebpf/vlanegress/vlanegress_test.go index c00c0b35e..7e3745a71 100644 --- a/internal/plumbing/ebpf/vlanegress/vlanegress_test.go +++ b/internal/plumbing/ebpf/vlanegress/vlanegress_test.go @@ -5,35 +5,46 @@ package vlanegress import ( + "errors" "fmt" - "strings" "testing" "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/transport" ) -func fakeLinks(t *testing.T, links ...netlink.Link) { - t.Helper() - byName := map[string]netlink.Link{} - byIndex := map[int]netlink.Link{} - for _, l := range links { - byName[l.Attrs().Name] = l - byIndex[l.Attrs().Index] = l - } - origName, origIndex := linkByNameFn, linkByIndexFn - t.Cleanup(func() { linkByNameFn, linkByIndexFn = origName, origIndex }) - linkByNameFn = func(name string) (netlink.Link, error) { - if l, ok := byName[name]; ok { +// pubVLAN is a synthetic tagged public side. +const pubVLAN = "bond0.101" + +// fakeLinks is an in-memory transport.Links. Names and IDs are synthetic. +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, fmt.Errorf("link %s not found", name) } - linkByIndexFn = func(index int) (netlink.Link, error) { - if l, ok := byIndex[index]; ok { + 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, fmt.Errorf("link %d not found", index) } + return nil, netlink.LinkNotFoundError{} +} + +func (f fakeLinks) LinkList() ([]netlink.Link, error) { return f, nil } + +func useLinks(t *testing.T, l ...netlink.Link) { + t.Helper() + orig := links + t.Cleanup(func() { links = orig }) + links = fakeLinks(l) } func vlan(name string, index, parent, id int, proto netlink.VlanProtocol) *netlink.Vlan { @@ -44,19 +55,22 @@ func vlan(name string, index, parent, id int, proto netlink.VlanProtocol) *netli } } -func TestFromNetlink(t *testing.T) { +func TestResolve(t *testing.T) { bond := &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Name: "bond0", Index: 2}} nic := &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: "eth1", Index: 3}} - pub := vlan("bond0.101", 10, 2, 101, netlink.VLAN_PROTOCOL_8021Q) + pub := vlan(pubVLAN, 10, 2, 101, netlink.VLAN_PROTOCOL_8021Q) fab := vlan("bond0.202", 11, 2, 202, netlink.VLAN_PROTOCOL_8021Q) qinq := vlan("bond0.300", 12, 2, 300, netlink.VLAN_PROTOCOL_8021AD) stacked := vlan("bond0.101.7", 13, 10, 7, netlink.VLAN_PROTOCOL_8021Q) zero := vlan("eth1.0", 14, 3, 0, netlink.VLAN_PROTOCOL_8021Q) - fakeLinks(t, bond, nic, pub, fab, qinq, stacked, zero) + useLinks(t, bond, nic, pub, fab, qinq, stacked, zero) - n, ifindexes, err := FromNetlink([]string{"bond0.101", "", "bond0.202", "eth1"}) + set, ifindexes, err := Resolve( + Side{transport.SidePublic, []string{pubVLAN, ""}}, + Side{transport.SideFabric, []string{"bond0.202", "eth1"}}, + ) if err != nil { - t.Fatalf("FromNetlink: %v", err) + t.Fatalf("Resolve: %v", err) } if want := []int{10, 11, 3}; fmt.Sprint(ifindexes) != fmt.Sprint(want) { t.Fatalf("ifindexes = %v, want %v", ifindexes, want) @@ -71,29 +85,42 @@ func TestFromNetlink(t *testing.T) { {3, 0, 0, false}, {99, 0, 0, false}, } { - lower, vid, ok := n.VLANLower(tt.ifindex) + lower, vid, ok := set.VLANLower(tt.ifindex) if lower != tt.lower || vid != tt.vid || ok != tt.ok { t.Errorf("VLANLower(%d) = %d, %d, %v; want %d, %d, %v", tt.ifindex, lower, vid, ok, tt.lower, tt.vid, tt.ok) } } - for _, tt := range []struct { - name, want string - }{ - {"bond0.300", "only 802.1Q"}, - {"bond0.101.7", "stacked tags"}, - {"eth1.0", "outside 1 to 4094"}, - {"missing0", "find link"}, + for name, rule := range map[string]transport.Rule{ + "bond0.300": transport.RuleVLANProtocol, + "bond0.101.7": transport.RuleStackedVLAN, + "eth1.0": transport.RuleVLANID, + "missing0": transport.RuleNotFound, } { - t.Run(tt.name, func(t *testing.T) { - n, _, err := FromNetlink([]string{tt.name}) - if err == nil || !strings.Contains(err.Error(), tt.want) { - t.Fatalf("FromNetlink(%s) error = %v, want one containing %q", tt.name, err, tt.want) + t.Run(name, func(t *testing.T) { + set, ifindexes, err := Resolve(Side{transport.SideUnassigned, []string{name}}) + var ve *transport.ValidationError + if !errors.As(err, &ve) || ve.Rule != rule { + t.Fatalf("Resolve(%s) error = %v, want rule %s", name, err, rule) } - if len(n.rows) != 0 { - t.Fatalf("FromNetlink(%s) kept rows %v", tt.name, n.rows) + if len(ifindexes) != 0 || len(set.VLANs()) != 0 { + t.Fatalf("Resolve(%s) kept %v, %v", name, ifindexes, set.VLANs()) } }) } + + t.Run("one interface on both sides", func(t *testing.T) { + set, _, err := Resolve( + Side{transport.SidePublic, []string{pubVLAN}}, + Side{transport.SideFabric, []string{pubVLAN}}, + ) + var ve *transport.ValidationError + if !errors.As(err, &ve) || ve.Rule != transport.RuleSidesOverlap { + t.Fatalf("error = %v, want rule %s", err, transport.RuleSidesOverlap) + } + if _, _, ok := set.VLANLower(10); ok { + t.Fatal("a refused Set must hold no rows") + } + }) }