Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ See [docs/node-labels.md](docs/node-labels.md) for the full strategy — why `ga
- **`config/galactic-router/overlays/control/`** — the BGP route-reflector role (`galactic-router-rr`, `GALACTIC_ROUTER_REFLECTOR=true`); opt-in only, requires `galactic.datumapis.com/galactic: control` (stays at zero replicas otherwise). Mutually exclusive with `router`'s `galactic: router` value on the same node — one label key, single-valued, so a route-reflector node structurally can't also run plain-mode `galactic-router`. `GALACTIC_ROUTER_BGP_LOCAL_ADDRESS` is auto-detected from the host's `lo` interface by default; see the comments in `daemonset-patch.yaml` for when to override it.
- Apply both roles with `kubectl apply -k config/galactic-router/`, or a single role with e.g. `kubectl apply -k config/galactic-router/overlays/router/`. `galactic-router` no longer runs bundled inside `galactic-gateway`'s pod — see `config/galactic-gateway/` below.
- **`config/galactic-gateway/`** — the edge XDP NAT+LB gateway control plane, a single-container `galactic-gateway` DaemonSet — `galactic-router` used to run as a second container in this same pod; it's now a fully independent DaemonSet (via `galactic.datumapis.com/galactic: router`, which a gateway node may carry like any other), so a crash on either side no longer takes the other's *pod* down with it, not just the other's binary. `config/galactic-gateway/{serviceaccount.yaml,rbac.yaml}` (safe/idempotent to apply cluster-wide) are what `kubectl apply -k config/galactic-gateway/` applies; `config/galactic-gateway/base/` (requiring nodes labeled `galactic.datumapis.com/gateway: enabled` and carrying no `galactic.datumapis.com/node` label, so it never shares a node with `galactic-vrf`) is **not** included in that kustomization and is **not** applied as-is — the same exemption as `config/fabric-router/` below, for the same reason: `GALACTIC_GATEWAY_SRV6_ADDRESS` must be unique per gateway node and has no generic default (no in-cluster mechanism yet derives it automatically — see `internal/config/gateway.go`'s `EnvGatewaySRv6Address` doc comment). It's designed to be instantiated once per gateway node by a further overlay that pins it to one node (`kubernetes.io/hostname`) and sets that node's own public-interface/SRv6-address values; see `deploy/containerlab/resources/galactic-gateway/` as of commit `abdd665b` for a worked example (the containerlab lab no longer deploys the gateway). Also **not** part of the root `config/kustomization.yaml`'s default resource list, matching `config/fabric-router/`'s exemption.
- **`config/galactic-nat/`** — the sharded egress translation (NAT66/NAT64) control plane, one `galactic-nat` DaemonSet per cluster on every node labeled `galactic.datumapis.com/nat: enabled` (and carrying no `galactic.datumapis.com/node` label). It is independent of `galactic-gateway`. A shard's identity (SID, masquerade addresses, NAT64 prefix) comes from the `EgressShard` targeting its node, not from the DaemonSet. The base leaves `GALACTIC_NAT_XDP_ATTACH` at its default, `direct`. On a node that also runs the gateway, which already holds the native XDP hook on the uplinks the shard needs, apply `config/galactic-nat/overlays/chained/`, which sets `chain`: the shard installs its dispatcher in the gateway's pinned `xdp_chain` program array and receives every packet the gateway does not claim. Compute nodes reach their own site's shards over SRv6 via `GALACTIC_CNI_EGRESS_SHARD_SIDS`. `kubectl apply -k config/galactic-nat/` applies only the ServiceAccount/RBAC; `base/` is excluded because uplink auto-detection is deployment-specific (see `config/galactic-nat/kustomization.yaml`). Not part of the root `config/kustomization.yaml`.
- **`config/galactic-nat/`** — the sharded egress translation (NAT66/NAT64) control plane, one `galactic-nat` DaemonSet per cluster on every node labeled `galactic.datumapis.com/nat: enabled` (and carrying no `galactic.datumapis.com/node` label). It is independent of `galactic-gateway`. A shard's identity (SID, masquerade addresses, NAT64 prefix) comes from the `EgressShard` targeting its node, not from the DaemonSet. The base leaves `GALACTIC_NAT_XDP_ATTACH` at its default, `direct`. On a node that also runs the gateway, set it to `dispatch`: an interface takes one native XDP program, so the shard and the gateway (which defaults to `GALACTIC_GATEWAY_XDP_ATTACH=dispatch`) each run from their own slot of the node's shared, pinned XDP dispatcher (`internal/plumbing/ebpf/xdpdispatch`), and either can restart or be turned off (`GALACTIC_*_DATAPATH_ENABLED=false`) without touching the other's traffic. `hack/xdp-dispatch-release.sh` detaches the dispatcher from a node. Compute nodes reach their own site's shards over SRv6 via `GALACTIC_CNI_EGRESS_SHARD_SIDS`. `kubectl apply -k config/galactic-nat/` applies only the ServiceAccount/RBAC; `base/` is excluded because uplink auto-detection is deployment-specific (see `config/galactic-nat/kustomization.yaml`). Not part of the root `config/kustomization.yaml`.
- **`config/fabric-router/`** — the FRR underlay eBGP DaemonSet (`fabric-router`; `galactic-router` needs a working underlay before it can start). Unlike `config/galactic-router/`, this is a single flat DaemonSet with no `default`/`rr`-style role split — its affinity matches any node labeled `galactic.datumapis.com/fabric: router` (a dedicated mode-enum label, independent of whatever `galactic.datumapis.com/node` role value or `galactic.datumapis.com/galactic` mode that node also carries) directly, since there's no env/config difference between running on a regular node vs. those roles — fabric-router itself is identical everywhere; only the per-node BGP underlay config it reads from the ConfigMap differs. That affinity can legitimately match more than one node per cluster, and BGP underlay config (hostname, router-id, interface addresses, remote-AS) inherently differs per physical node — so each node's config lives in its own `fabric-router.<nodename>` ConfigMap (a `frr.conf` key, plus optional `daemons`/`vtysh.conf` overrides of the image defaults) rather than one shared ConfigMap for the whole DaemonSet. `fabric-config-agent` (`cmd/fabric-config-agent`, `internal/fabricconfig`, built into the `fabric-router` image) reads it from the API: as the `frr-init` init container it validates (`vtysh -C`) and installs it, holding the pod in `Init` until a valid one exists; as the `config-agent` sidecar it applies later changes live with `frr-reload.py`, so an edit to one node's ConfigMap neither restarts the pod nor touches other nodes, and reports `Applied`/`Rejected`/`ReloadFailed`/`RestartRequired` events on the ConfigMap. The sidecar also hard-resets any IPv6 session announcing an IPv4-mapped next hop (`internal/fabricconfig/nexthop.go`) and serves that check's metrics on the node's port `9343`. A third container, `frr-exporter` (upstream `tynany/frr_exporter`, pinned by digest), reads the daemons' vty sockets in the same pod-scoped `/run/frr` and serves BGP peer state, message counters and prefix counts for both underlay families on the node's port `9342` (`hostNetwork`); `task verify:fabric-metrics` in `deploy/containerlab/` checks it on every lab node. The image's default `daemons` loads bgpd's BMP module (`-M bmp`), so a node's `frr.conf` can stream to a BMP collector (`config/bmp-collector/`) with a `bmp targets` block; loading it alone streams nothing, and a change to the modules needs a pod restart rather than a reload. Every lab node's `frr.conf` streams its pre-policy Adj-RIB-In and Loc-RIB for both families, sourced from `lo` (`source-interface lo`), since the underlay carries loopbacks but not link subnets. Production `frr.conf`s come from infra's renderer, which has to emit the same block for production nodes to stream. A node with no ConfigMap of its own falls back, with a `DeprecatedConfigSource` warning, to key `frr.conf.<nodename>` of the legacy shared `fabric-config` ConfigMap. **Not** part of the root `config/kustomization.yaml` and not covered by `kubectl apply -k config/` — unlike every other component here, it has no generic default: the deployer must hand-author one `fabric-router.<nodename>` ConfigMap per matching node before applying `kubectl apply -k config/fabric-router/` (which also applies the agent's ServiceAccount and namespaced Role).
- **`config/bmp-collector/`** — a single-replica GoBMP Deployment and its `bmp-collector` Service (TCP `5000`), the BMP (RFC 7854) collector `galactic-router` and `fabric-router` stream to; `galactic-router` does so when `GALACTIC_ROUTER_BMP_STATIONS` names it (`bmp-collector.galactic-system.svc:5000`; see [docs/router/configuration.md](docs/router/configuration.md)). It parses every Peer Up/Down, route-monitoring and statistics message to JSON on stdout, so the cluster's log pipeline is its store; an overlay swapping `--dump=console` for `--kafka-server` publishes to Kafka instead. Opt-in, like `config/fabric-router/`: not part of the root `config/kustomization.yaml`, since nothing streams to it until a router is configured to. The containerlab lab runs one on `iad-worker3`'s host network (`deploy/containerlab/resources/bmp-collector/iad/`), because its three clusters cannot reach each other's Services, and points every node's `fabric-router` and the EVPN route reflector at it. Of the `galactic-router`s, only the reflector streams: its pre-policy Adj-RIB-In already holds every node's advertisements.
- **`config/monitoring/`** — Prometheus Operator resources for BGP and NAT: a `fabric-router` PodMonitor (frr-exporter, port `frr-metrics`/`9342`, as `job=fabric-router`; fabric-config-agent, port `agent-metrics`/`9343`, as `job=fabric-config-agent`), a `galactic-router` PodMonitor covering both roles (port `metrics`/`9179`), a `galactic-nat` PodMonitor for the egress shards (port `metrics`/`9182`), each adding a `node` label, and the `galactic-bgp` PrometheusRule: underlay session down, administratively down for an hour, flapping, received prefixes halved, exporter collector or scrape failing, a session announcing an IPv4-mapped next hop, BGP routes not installed, the agent's metrics scrape down, a `galactic-router` BMP station or metrics scrape down, `galactic-router` routes failing to install, an egress shard's session table evicting live sessions, a single stalled NIC receive queue on a `galactic-nat` uplink (#673), and a `galactic-nat` metrics scrape down. Requires the `monitoring.coreos.com` CRDs, which this repo does not install, so it is not part of the root `config/kustomization.yaml`. `task test:alerts` unit-tests the rules with `promtool` (`config/monitoring/tests/`). Every alert carries what infra's alerting standard checks for (`service: galactic`, `team: connect`, `runbook_url` into infra's `docs/runbooks/galactic/README.md`). The PrometheusRule here is the tested source, not where the rules run on Datum's infra: there the PodMonitors are converted and scraped on each edge cluster, but edge vmalert never notifies, so infra evaluates a copy of the rules centrally. Change the rules here first, with their tests, then update infra's copy.
Expand Down
222 changes: 222 additions & 0 deletions cmd/galactic-gateway/dispatch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package main

import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"

"github.com/cilium/ebpf/rlimit"
"github.com/vishvananda/netlink"

"go.datum.net/galactic/internal/plumbing/ebpf/natattach"
"go.datum.net/galactic/internal/plumbing/ebpf/xdpattach"
"go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch"
)

func requireRoot(t *testing.T) {
t.Helper()
if os.Geteuid() != 0 {
t.Skip("test requires root (CAP_BPF/CAP_NET_ADMIN) to load and attach XDP programs; re-run via sudo")
}
if err := rlimit.RemoveMemlock(); err != nil {
t.Fatalf("rlimit.RemoveMemlock: %v", err)
}
}

// pinDirs are per-test bpffs directories for the dispatcher, the gateway's
// own maps and the egress shard's.
type pinDirs struct{ dispatch, edge, nat string }

func testPinDirs(t *testing.T) pinDirs {
t.Helper()
requireRoot(t)
name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name())
base := filepath.Join("/sys/fs/bpf", "gwdispatch-test-"+name)
_ = os.RemoveAll(base)
d := pinDirs{filepath.Join(base, "xdp"), filepath.Join(base, "edge"), filepath.Join(base, "nat")}
for _, dir := range []string{d.dispatch, d.edge, d.nat} {
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Skipf("bpffs not writable at /sys/fs/bpf: %v", err)
}
}
t.Cleanup(func() { _ = os.RemoveAll(base) })
return d
}

func testUplink(t *testing.T, prefix string) (string, int) {
t.Helper()
name := fmt.Sprintf("%s%d", prefix, os.Getpid()%10000)
veth := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: name}, PeerName: name + "p"}
if err := netlink.LinkAdd(veth); err != nil {
t.Fatalf("add veth %s: %v", name, err)
}
t.Cleanup(func() { _ = netlink.LinkDel(veth) })
for _, n := range []string{name, name + "p"} {
l, err := netlink.LinkByName(n)
if err != nil {
t.Fatalf("find %s: %v", n, err)
}
if err := netlink.LinkSetUp(l); err != nil {
t.Fatalf("set %s up: %v", n, err)
}
}
l, _ := netlink.LinkByName(name)
return name, l.Attrs().Index
}

func xdpProgID(t *testing.T, name string) uint32 {
t.Helper()
l, err := netlink.LinkByName(name)
if err != nil {
t.Fatalf("find %s: %v", name, err)
}
if xdp := l.Attrs().Xdp; xdp != nil && xdp.Attached {
return xdp.ProgId
}
return 0
}

// gatewayProcess is one gateway process joined to the dispatcher; stop is its
// exit.
type gatewayProcess struct {
public targetSet
stop func()
}

func startGateway(t *testing.T, d pinDirs) gatewayProcess {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
objs, dispatcher, public, _, leaseDone, err := joinDispatcher(ctx, d.dispatch, d.edge, false)
if err != nil {
cancel()
t.Fatalf("gateway joinDispatcher: %v", err)
}
stopped := false
stop := func() {
if stopped {
return
}
stopped = true
cancel()
<-leaseDone
_ = dispatcher.Close()
_ = objs.Close()
}
t.Cleanup(stop)
return gatewayProcess{public: public, stop: stop}
}

// startShard joins the egress shard to the dispatcher the way galactic-nat's
// dispatch mode does, and returns its coverage check.
func startShard(t *testing.T, d pinDirs, uplink string) func() error {
t.Helper()
objs, err := natattach.Load(d.nat)
if err != nil {
t.Fatalf("load shard objects: %v", err)
}
t.Cleanup(func() { _ = objs.Close() })
if err := natattach.PopulateProgArray(objs); err != nil {
t.Fatalf("populate nat_progs: %v", err)
}
dispatcher, err := xdpdispatch.Open(context.Background(), d.dispatch)
if err != nil {
t.Fatalf("shard open dispatcher: %v", err)
}
t.Cleanup(func() { _ = dispatcher.Close() })
lock, err := dispatcher.Lock(context.Background())
if err != nil {
t.Fatalf("Lock: %v", err)
}
err = lock.Fill(xdpdispatch.SlotNAT, objs.NatIngress)
lock.Unlock()
if err != nil {
t.Fatalf("fill the egress slot: %v", err)
}
set, err := xdpattach.NewDispatchSet(dispatcher, xdpdispatch.SlotNAT, xdpdispatch.RoleEgress, objs.NatIngress)
if err != nil {
t.Fatalf("NewDispatchSet: %v", err)
}
if missing := set.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 {
t.Fatalf("shard missing %v", missing)
}
l, _ := netlink.LinkByName(uplink)
return func() error { return dispatcher.Coverage(l.Attrs().Index, xdpdispatch.SlotNAT, objs.NatIngress) }
}

// TestGatewayAndShardShareAnUplink is issue #717's acceptance case: the gateway
// and the egress shard hold one uplink through the dispatcher, and the gateway
// restarting leaves the shard's traffic and the uplink's program untouched.
func TestGatewayAndShardShareAnUplink(t *testing.T) {
d := testPinDirs(t)
uplink, ifindex := testUplink(t, "gwsh")

gw := startGateway(t, d)
if missing := gw.public.reconcile(context.Background(), []string{uplink}); len(missing) != 0 {
t.Fatalf("gateway missing %v", missing)
}
shardCovered := startShard(t, d, uplink)
root := xdpProgID(t, uplink)

probe, err := xdpdispatch.Open(context.Background(), d.dispatch)
if err != nil {
t.Fatalf("open dispatcher: %v", err)
}
t.Cleanup(func() { _ = probe.Close() })
if roles, _ := probe.Roles(ifindex); roles != xdpdispatch.RolePublicLB|xdpdispatch.RoleEgress {
t.Errorf("uplink roles = %#x, want public and egress", roles)
}

// The gateway process exits and a new one starts.
gw.stop()
if got := xdpProgID(t, uplink); got != root {
t.Fatalf("uplink runs %d after the gateway exited, want the root %d", got, root)
}
if err := shardCovered(); err != nil {
t.Fatalf("shard lost its uplink when the gateway exited: %v", err)
}
gw2 := startGateway(t, d)
if missing := gw2.public.reconcile(context.Background(), []string{uplink}); len(missing) != 0 {
t.Errorf("restarted gateway missing %v", missing)
}
if got := xdpProgID(t, uplink); got != root {
t.Errorf("uplink runs %d after the gateway restarted, want the same root %d", got, root)
}
if err := shardCovered(); err != nil {
t.Errorf("shard lost its uplink across the gateway restart: %v", err)
}
}

// TestAttachDirect_RefusesAnUplinkTheShardRunsOn: a gateway set to direct mode
// on a node whose shard runs from the dispatcher must not take the hook.
func TestAttachDirect_RefusesAnUplinkTheShardRunsOn(t *testing.T) {
d := testPinDirs(t)
uplink, _ := testUplink(t, "gwdr")
startShard(t, d, uplink)
root := xdpProgID(t, uplink)

_, _, _, err := attachDirect(context.Background(), d.dispatch, d.edge, []string{uplink}, nil)
if !errors.Is(err, xdpattach.ErrDispatcherInUse) {
t.Fatalf("attachDirect over a live shard slot = %v, want ErrDispatcherInUse", err)
}
if got := xdpProgID(t, uplink); got != root {
t.Errorf("uplink runs %d after the refusal, want the root %d untouched", got, root)
}
}

func TestPublicReturnOverlap(t *testing.T) {
const shared = "eth2"
if got := publicReturnOverlap([]string{"eth1", shared}, []string{shared, "eth3"}); len(got) != 1 || got[0] != shared {
t.Errorf("publicReturnOverlap = %v, want [%s]", got, shared)
}
if got := publicReturnOverlap([]string{"eth1"}, []string{"eth3"}); len(got) != 0 {
t.Errorf("publicReturnOverlap = %v, want none", got)
}
}
Loading
Loading