diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index 2422d8a43..f5233c724 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -156,10 +156,11 @@ func runCmd(cfg *config.NATConfig) error { // EgressShard's Programmed condition reports that instead. healthSrv.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING) - if cfg.WorkerSocket != "" && cfg.DatapathEnabled { - if err := startLocalDelivery(ctx, cfg, mgr); err != nil { - return fmt.Errorf("start local shard delivery: %w", err) - } + if err := settleLocalDelivery(cfg, + func() error { return startLocalDelivery(ctx, cfg, mgr) }, + func() (localPlumbing, func(), error) { return openLocalPlumbing(cfg) }, + ); err != nil { + return fmt.Errorf("start local shard delivery: %w", err) } // Register EgressShard controller. diff --git a/cmd/galactic-nat/workerlocal.go b/cmd/galactic-nat/workerlocal.go index 8687f1a39..87604e1c2 100644 --- a/cmd/galactic-nat/workerlocal.go +++ b/cmd/galactic-nat/workerlocal.go @@ -267,7 +267,23 @@ func (k *kernelLocal) Prune(keep []localTarget) error { } } } + // nat_vlan_egress serves only Local forwards, and syncVLANs is its only + // writer, so with no pair to keep none of its rows is needed. + if len(keep) == 0 { + vlans, err := k.vlans.All() + if err != nil { + return err + } + for ifx := range vlans { + if err := k.vlans.Delete(ifx); err != nil { + return err + } + } + } entries, err := os.ReadDir(k.linkDir) + if errors.Is(err, os.ErrNotExist) { + return nil + } if err != nil { return fmt.Errorf("read %s: %w", k.linkDir, err) } @@ -281,3 +297,57 @@ func (k *kernelLocal) Prune(keep []localTarget) error { } return nil } + +// openPinnedLocal opens the Local state a previous process pinned under +// pinDir, for a start that has no datapath loaded to prune it with. A missing +// map or link directory is read as empty, and nothing is created, so a node +// that never ran the integration is left as it is. The result only prunes: +// it holds no program to attach. close releases the opened maps. +func openPinnedLocal(pinDir string) (plumb *kernelLocal, closeMaps func(), err error) { + var opened []*ebpf.Map + closeMaps = func() { + for _, m := range opened { + _ = m.Close() + } + } + open := func(name string) (natmap.Table, error) { + m, err := ebpf.LoadPinnedMap(filepath.Join(pinDir, name), nil) + if errors.Is(err, os.ErrNotExist) { + return emptyTable{}, nil + } + if err != nil { + return nil, fmt.Errorf("open the pinned map %s: %w", name, err) + } + opened = append(opened, m) + return natmap.KernelTable{Map: m}, nil + } + tables := make([]natmap.Table, 0, 3) + for _, name := range []string{"nat_local_pair", "nat_local_return", "nat_vlan_egress"} { + t, err := open(name) + if err != nil { + closeMaps() + return nil, nil, err + } + tables = append(tables, t) + } + return &kernelLocal{ + linkDir: filepath.Join(pinDir, "links"), + tables: natmap.LocalTables{Pair: tables[0], Return: tables[1]}, + vlans: natmap.VLANTable{Table: tables[2]}, + }, closeMaps, nil +} + +// emptyTable is a map that holds nothing: a pinned map that does not exist. +type emptyTable struct{} + +func (emptyTable) Put(any, any) error { return errors.New("the map is not pinned") } +func (emptyTable) Lookup(any, any) error { return ebpf.ErrKeyNotExist } +func (emptyTable) Delete(any) error { return ebpf.ErrKeyNotExist } +func (emptyTable) Iterate() natmap.Iterator { + return emptyIterator{} +} + +type emptyIterator struct{} + +func (emptyIterator) Next(any, any) bool { return false } +func (emptyIterator) Err() error { return nil } diff --git a/cmd/galactic-nat/workerlocal_test.go b/cmd/galactic-nat/workerlocal_test.go index 858edbe20..68a949fc6 100644 --- a/cmd/galactic-nat/workerlocal_test.go +++ b/cmd/galactic-nat/workerlocal_test.go @@ -5,15 +5,18 @@ package main import ( + "errors" "net/netip" "os" "path/filepath" "runtime" "testing" + "github.com/cilium/ebpf" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" + "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/plumbing/ebpf/natattach" "go.datum.net/galactic/internal/plumbing/ebpf/natmap" ) @@ -92,12 +95,13 @@ func TestKernelLocal_AttachesNativePinnedAndPrunes(t *testing.T) { t.Fatalf("newKernelLocal: %v", err) } - nat, tenant := addVeth(t, "gn0", "gt0") + nat, tenant := addVeth(t, testNATEnd, testTenantEnd) if peer, err := vethPeer(nat, netlink.LinkByIndex); err != nil || peer.Attrs().Index != tenant.Attrs().Index { t.Fatalf("vethPeer(gn0) = %v, %v; want gt0", peer, err) } sid := netip.MustParseAddr("fc00:0:1:1:123::") - target := localTarget{VPC: "A", NATName: "gn0", NATIfindex: nat.Attrs().Index, TenantName: "gt0", TenantSID: sid} + target := localTarget{VPC: "A", NATName: testNATEnd, NATIfindex: nat.Attrs().Index, TenantName: testTenantEnd, + TenantSID: sid} if err := k.Program(target); err != nil { t.Fatalf("Program: %v", err) } @@ -125,7 +129,7 @@ func TestKernelLocal_AttachesNativePinnedAndPrunes(t *testing.T) { if err := netlink.LinkDel(nat); err != nil { t.Fatalf("delete pair: %v", err) } - nat2, _ := addVeth(t, "gn0", "gt0") + nat2, _ := addVeth(t, testNATEnd, testTenantEnd) target2 := target target2.NATIfindex = nat2.Attrs().Index if err := k.Program(target2); err != nil { @@ -150,6 +154,200 @@ func TestKernelLocal_AttachesNativePinnedAndPrunes(t *testing.T) { } } +// testNATEnd and testTenantEnd name a test pair's two ends. +const ( + testNATEnd = "gn0" + testTenantEnd = "gt0" +) + +// testWorkerSocket is a Worker socket path; nothing listens on it. +const testWorkerSocket = "/run/worker.sock" + +func TestSettleLocalDelivery(t *testing.T) { + for _, tc := range []struct { + name string + socket string + enabled bool + wantStart bool + }{ + {name: "integration on", socket: testWorkerSocket, enabled: true, wantStart: true}, + {name: "no worker socket", socket: "", enabled: true}, + {name: "datapath disabled", socket: testWorkerSocket, enabled: false}, + {name: "both off", socket: "", enabled: false}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.NATConfig{WorkerSocket: tc.socket, DatapathEnabled: tc.enabled} + plumb := &fakePlumbing{} + started, opened, closed := false, false, false + err := settleLocalDelivery(cfg, + func() error { started = true; return nil }, + func() (localPlumbing, func(), error) { + opened = true + return plumb, func() { closed = true }, nil + }) + if err != nil { + t.Fatalf("settleLocalDelivery: %v", err) + } + if started != tc.wantStart { + t.Errorf("started = %v, want %v", started, tc.wantStart) + } + if tc.wantStart { + if opened || len(plumb.pruned) != 0 { + t.Errorf("opened = %v, pruned = %v; want no prune while the integration runs", opened, plumb.pruned) + } + return + } + if len(plumb.pruned) != 1 || len(plumb.pruned[0]) != 0 { + t.Errorf("pruned = %v, want one Prune with an empty keep set", plumb.pruned) + } + if !closed { + t.Error("the opened state was not closed") + } + }) + } +} + +func TestSettleLocalDelivery_StartError(t *testing.T) { + want := errors.New("boom") + cfg := &config.NATConfig{WorkerSocket: testWorkerSocket, DatapathEnabled: true} + err := settleLocalDelivery(cfg, func() error { return want }, + func() (localPlumbing, func(), error) { t.Fatal("opened with the integration on"); return nil, nil, nil }) + if !errors.Is(err, want) { + t.Errorf("err = %v, want %v", err, want) + } +} + +func TestSettleLocalDelivery_OpenErrorIsLogged(t *testing.T) { + cfg := &config.NATConfig{DatapathEnabled: false} + err := settleLocalDelivery(cfg, func() error { t.Fatal("started"); return nil }, + func() (localPlumbing, func(), error) { return nil, nil, errors.New("boom") }) + if err != nil { + t.Errorf("err = %v, want nil: a failed cleanup does not stop startup", err) + } +} + +// pinnedRows counts the rows of the map pinned at path. +func pinnedRows(t *testing.T, path string) int { + t.Helper() + m, err := ebpf.LoadPinnedMap(path, nil) + if err != nil { + t.Fatalf("open %s: %v", path, err) + } + defer func() { _ = m.Close() }() + n := 0 + it := m.Iterate() + key := make([]byte, m.KeySize()) + value := make([]byte, m.ValueSize()) + for it.Next(&key, &value) { + n++ + } + if err := it.Err(); err != nil { + t.Fatalf("iterate %s: %v", path, err) + } + return n +} + +// TestSettleLocalDelivery_RemovesPinnedState starts with the integration off +// after a process that programmed a pair and exited, leaving its link and rows +// pinned. +func TestSettleLocalDelivery_RemovesPinnedState(t *testing.T) { + requireRoot(t) + pinDir, err := os.MkdirTemp("/sys/fs/bpf", "galactic-nat-test-") + if err != nil { + t.Skipf("bpffs unavailable: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + enterNetns(t) + + // The previous process. + objs, err := natattach.Load(pinDir) + if err != nil { + t.Fatalf("load: %v", err) + } + k, err := newKernelLocal(objs.NatIngress, pinDir, + natmap.LocalTables{Pair: natmap.KernelTable{Map: objs.NatLocalPair}, + Return: natmap.KernelTable{Map: objs.NatLocalReturn}}, + natmap.VLANTable{Table: natmap.KernelTable{Map: objs.NatVlanEgress}}) + if err != nil { + t.Fatalf("newKernelLocal: %v", err) + } + if err := netlink.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: "gd0"}}); err != nil { + t.Fatalf("add dummy: %v", err) + } + lower, err := netlink.LinkByName("gd0") + if err != nil { + t.Fatalf("find gd0: %v", err) + } + if err := netlink.LinkAdd(&netlink.Vlan{LinkAttrs: netlink.LinkAttrs{Name: "gd0.42", + ParentIndex: lower.Attrs().Index}, VlanId: 42}); err != nil { + t.Fatalf("add VLAN: %v", err) + } + nat, _ := addVeth(t, testNATEnd, testTenantEnd) + target := localTarget{VPC: "A", NATName: testNATEnd, NATIfindex: nat.Attrs().Index, TenantName: testTenantEnd, + TenantSID: netip.MustParseAddr("fc00:0:1:1:123::")} + if err := k.Program(target); err != nil { + t.Fatalf("Program: %v", err) + } + if err := objs.Close(); err != nil { + t.Fatalf("close: %v", err) + } + linkPin := filepath.Join(pinDir, "links", "local-gn0") + maps := []string{"nat_local_pair", "nat_local_return", "nat_vlan_egress"} + for _, m := range maps { + if n := pinnedRows(t, filepath.Join(pinDir, m)); n != 1 { + t.Fatalf("%s holds %d rows before the start, want 1", m, n) + } + } + if xdpDriverProgram(t, nat.Attrs().Index) == 0 { + t.Fatal("no native XDP program on the NAT end before the start") + } + + // Two starts with the datapath disabled; the second finds nothing to do. + cfg := &config.NATConfig{WorkerSocket: testWorkerSocket, DatapathEnabled: false} + open := func() (localPlumbing, func(), error) { return openPinnedLocal(pinDir) } + for i := range 2 { + if err := settleLocalDelivery(cfg, func() error { t.Fatal("started"); return nil }, open); err != nil { + t.Fatalf("start %d: %v", i, err) + } + if _, err := os.Stat(linkPin); !errors.Is(err, os.ErrNotExist) { + t.Errorf("start %d: the link pin remains: %v", i, err) + } + if xdpDriverProgram(t, nat.Attrs().Index) != 0 { + t.Errorf("start %d: the NAT end still runs the program", i) + } + for _, m := range maps { + if n := pinnedRows(t, filepath.Join(pinDir, m)); n != 0 { + t.Errorf("start %d: %s holds %d rows, want 0", i, m, n) + } + } + } + plumb, closeMaps, err := openPinnedLocal(pinDir) + if err != nil { + t.Fatalf("openPinnedLocal: %v", err) + } + defer closeMaps() + if err := plumb.Prune(nil); err != nil { + t.Errorf("Prune with nothing left: %v", err) + } +} + +// TestOpenPinnedLocal_NothingPinned prunes on a node where galactic-nat never +// pinned anything, which must neither fail nor create anything. +func TestOpenPinnedLocal_NothingPinned(t *testing.T) { + pinDir := filepath.Join(t.TempDir(), "galactic-nat") + plumb, closeMaps, err := openPinnedLocal(pinDir) + if err != nil { + t.Fatalf("openPinnedLocal: %v", err) + } + defer closeMaps() + if err := plumb.Prune(nil); err != nil { + t.Errorf("Prune: %v", err) + } + if _, err := os.Stat(pinDir); !errors.Is(err, os.ErrNotExist) { + t.Errorf("the pin directory was created: %v", err) + } +} + // xdpAttachedDrv is IFLA_XDP_ATTACHED's value for a native program // (XDP_ATTACHED_DRV in linux/if_link.h). const xdpAttachedDrv = 1 @@ -159,7 +357,7 @@ const xdpAttachedDrv = 1 func TestVethPeer(t *testing.T) { link := func(idx, peer, netnsid int) netlink.Link { attrs := netlink.NewLinkAttrs() - attrs.Name, attrs.Index, attrs.ParentIndex, attrs.NetNsID = "gn0", idx, peer, netnsid + attrs.Name, attrs.Index, attrs.ParentIndex, attrs.NetNsID = testNATEnd, idx, peer, netnsid return &netlink.Veth{LinkAttrs: attrs} } links := map[int]netlink.Link{10: link(10, 9, -1), 11: link(11, 12, -1)} diff --git a/cmd/galactic-nat/workerwatch.go b/cmd/galactic-nat/workerwatch.go index 66bcf62ad..67694b37b 100644 --- a/cmd/galactic-nat/workerwatch.go +++ b/cmd/galactic-nat/workerwatch.go @@ -196,19 +196,12 @@ func (c *workerCollector) Collect(ch chan<- prometheus.Metric) { // local pairs: it claims a pair per VPC from Galactic Worker and attaches the // loaded datapath to each. func startLocalDelivery(ctx context.Context, cfg *config.NATConfig, mgr ctrl.Manager) error { - objs := natDatapathKeepAlive.objs - if objs == nil { - return errors.New("the datapath is not loaded") - } - plumb, err := newKernelLocal(objs.NatIngress, natattach.PinDir, - natmap.LocalTables{Pair: natmap.KernelTable{Map: objs.NatLocalPair}, - Return: natmap.KernelTable{Map: objs.NatLocalReturn}}, - natmap.VLANTable{Table: natmap.KernelTable{Map: objs.NatVlanEgress}}) + plumb, err := loadedLocal() if err != nil { return err } w := newNATWorker(cfg.NodeName, workerclientDial(cfg.WorkerSocket, cfg.WorkerTokenFile), plumb) - metrics.MustRegister(&workerCollector{worker: w, stats: objs.NatLocalStats}) + metrics.MustRegister(&workerCollector{worker: w, stats: natDatapathKeepAlive.objs.NatLocalStats}) if err := watchWorkerSources(ctx, mgr.GetCache(), mgr.GetClient(), cfg.NodeName, w); err != nil { return err } @@ -216,3 +209,57 @@ func startLocalDelivery(ctx context.Context, cfg *config.NATConfig, mgr ctrl.Man slog.Info("Local shard delivery through Galactic Worker is on", "socket", cfg.WorkerSocket) return nil } + +// loadedLocal returns the Local plumbing over the datapath this process +// loaded. +func loadedLocal() (*kernelLocal, error) { + objs := natDatapathKeepAlive.objs + if objs == nil { + return nil, errors.New("the datapath is not loaded") + } + return newKernelLocal(objs.NatIngress, natattach.PinDir, + natmap.LocalTables{Pair: natmap.KernelTable{Map: objs.NatLocalPair}, + Return: natmap.KernelTable{Map: objs.NatLocalReturn}}, + natmap.VLANTable{Table: natmap.KernelTable{Map: objs.NatVlanEgress}}) +} + +// openLocalPlumbing opens the Local state to prune on a start with the Worker +// integration off: through the loaded datapath when there is one, otherwise +// from what a previous process pinned. +func openLocalPlumbing(cfg *config.NATConfig) (localPlumbing, func(), error) { + if cfg.DatapathEnabled { + plumb, err := loadedLocal() + return plumb, func() {}, err + } + return openPinnedLocal(natattach.PinDir) +} + +// settleLocalDelivery runs start when cfg turns the Worker integration on. +// Otherwise it prunes every Local pin and row a previous process left, so +// a pair that still exists stops translating now rather than when Worker +// withdraws its claim at session-lease expiry. +// +// A failure to prune is logged, not returned, like turnOffDatapath's: a +// crash-looping process would not remove the state either, and Worker +// deletes the pairs once their claims lapse. +func settleLocalDelivery(cfg *config.NATConfig, start func() error, + open func() (localPlumbing, func(), error), +) error { + if cfg.WorkerSocket != "" && cfg.DatapathEnabled { + return start() + } + plumb, closeFn, err := open() + if err != nil { + slog.Error("Cannot open the Local pair state to remove it; "+ + "Local pairs keep translating until Worker withdraws their claims", "err", err) + return nil + } + defer closeFn() + if err := plumb.Prune(nil); err != nil { + slog.Error("Cannot remove the Local pair state; "+ + "Local pairs keep translating until Worker withdraws their claims", "err", err) + return nil + } + slog.Info("Local shard delivery is off; removed any Local pair links and rows left by a previous process") + return nil +} diff --git a/deploy/containerlab/scripts/verify-nat-local.sh b/deploy/containerlab/scripts/verify-nat-local.sh index 48ac212c9..430a03803 100755 --- a/deploy/containerlab/scripts/verify-nat-local.sh +++ b/deploy/containerlab/scripts/verify-nat-local.sh @@ -125,18 +125,47 @@ json.dump(d, sys.stdout)' "${STATE}/nat-ds.json" | kci replace -f - >/dev/null exit "${rc}" } +# nat_local_state_gone checks that galactic-nat, restarted without its Worker +# socket, removed its pinned NAT-end links and the rows of nat_local_pair, +# nat_local_return and nat_vlan_egress on its own, within 60 s of its +# rollout. It reports how many Local pairs still exist at that point: the +# cleanup must not wait for Worker to withdraw them. +nat_local_state_gone() { + local deadline=$((SECONDS + 60)) pid pins rows m n pairs + pid=$(docker inspect -f '{{.State.Pid}}' "${EDGE}") + pairs=$(docker exec "${EDGE}" ip -o link show type veth | grep -c 'alias galactic-local:' || true) + while :; do + pins=$(docker exec "${EDGE}" sh -c 'ls /sys/fs/bpf/galactic-nat/links 2>/dev/null | grep "^local-" || true') + rows="" + for m in nat_local_pair nat_local_return nat_vlan_egress; do + n=$(sudo -n bpftool -j map dump pinned "/proc/${pid}/root/sys/fs/bpf/galactic-nat/${m}" | + python3 -c 'import json,sys; print(len(json.load(sys.stdin)))') || return 1 + [ "${n}" = 0 ] || rows="${rows} ${m}=${n}" + done + [ -n "${pins}" ] || [ -n "${rows}" ] || break + if [ ${SECONDS} -ge ${deadline} ]; then + echo "FAIL: galactic-nat left its Local state after restarting without Worker: pins [${pins}] rows [${rows}]" >&2 + return 1 + fi + sleep 2 + done + echo " galactic-nat removed its local link pins and pair rows at startup (${pairs} Local pair links still present)" +} + # teardown_local removes what Worker and galactic-nat's Local integration # left on dfw-worker2, in the order that lets each owner remove its own: # with galactic-nat no longer renewing its Worker session, Worker withdraws # its claims once the session lease expires (120 s), and the Local module # removes the pairs, its tc filters and the egress_local_shard rows. Only -# then is Worker stopped. galactic-nat leaves its pinned NAT-end links and -# pair rows behind when its Worker integration is switched off, and Worker -# leaves Local's pinned maps, so those are removed here. Last, the handback +# then is Worker stopped. galactic-nat, restarted without its Worker socket, +# removes its own pinned NAT-end links and pair rows at startup, which is +# checked first, while Local's pairs still exist. Worker leaves Local's +# pinned maps, so those are removed here. Last, the handback # returns the VPC scopes Worker took over (docs/worker/operations.md), and # galactic-router on the node restarts to write their tenant routes again. teardown_local() { local deadline=$((SECONDS + 300)) pid + nat_local_state_gone || return 1 echo " waiting for Worker to withdraw galactic-nat's claims (session lease 120 s)" until [ -z "$(docker exec "${EDGE}" ip -o link show type veth | grep 'alias galactic-local:' || true)" ]; do if [ ${SECONDS} -ge ${deadline} ]; then @@ -147,22 +176,8 @@ teardown_local() { done echo " Local's pairs are gone" NODES="${EDGE}" "${SCRIPT_DIR}/worker-fabric.sh" stop || return 1 - pid=$(docker inspect -f '{{.State.Pid}}' "${EDGE}") - docker exec "${EDGE}" sh -c 'rm -f /sys/fs/bpf/galactic-nat/links/local-*' || return 1 - local m keys - for m in nat_local_pair nat_local_return nat_vlan_egress; do - keys=$(sudo -n bpftool -j map dump pinned "/proc/${pid}/root/sys/fs/bpf/galactic-nat/${m}" 2>/dev/null | - python3 -c 'import json,sys -for e in json.load(sys.stdin): - print(" ".join(b[2:] for b in e["key"]))') || return 1 - while read -r k; do - [ -n "${k}" ] || continue - # shellcheck disable=SC2086 # the key is space-separated hex bytes - sudo -n bpftool map delete pinned "/proc/${pid}/root/sys/fs/bpf/galactic-nat/${m}" key hex ${k} || return 1 - done <<<"${keys}" - done docker exec "${EDGE}" rm -rf /sys/fs/bpf/galactic-local || return 1 - echo " removed galactic-nat's pinned local links and pair rows, and Local's pin directory" + echo " removed Local's pin directory" echo " handing ${EDGE}'s VPC scopes back" docker exec "${EDGE}" /opt/galactic-worker/galactic-worker handback --node-name "${EDGE}" || return 1 kc -n galactic-system delete pod -l app.kubernetes.io/name=galactic-router \ diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index ef3f1cb93..6bd5e5254 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -222,8 +222,14 @@ Empty, the default, leaves all of this off. The shard then claims no pair and behaves exactly as without Worker. The pinned links and rows survive a restart, so a pair keeps translating while the process is down; the next process prunes the ones whose claim it no longer holds once every claim has -reported. `galactic_nat_worker_session_up`, -`galactic_nat_worker_capability_available`, +reported. A process that starts with this empty, or with the datapath +disabled, removes every pinned link under `links` and every row of +`nat_local_pair`, `nat_local_return` and `nat_vlan_egress` at startup, so its +pairs stop translating at once rather than when Worker withdraws their +claims. Before uninstalling galactic-nat from a node that used Worker, restart +it once with this empty, or remove `/sys/fs/bpf/galactic-nat/links/local-*` +and the pinned maps under `/sys/fs/bpf/galactic-nat` by hand. +`galactic_nat_worker_session_up`, `galactic_nat_worker_capability_available`, `galactic_nat_local_handoff_ready` and `galactic_nat_local_packets_total` report the integration's state.