diff --git a/api/network/v1alpha1/gateway_types.go b/api/network/v1alpha1/gateway_types.go index 99833d325..cdeb46f1d 100644 --- a/api/network/v1alpha1/gateway_types.go +++ b/api/network/v1alpha1/gateway_types.go @@ -68,6 +68,18 @@ type NetworkGatewayStatus struct { // health, an older one included, writes its status without it. // +optional BackendHealthFiltering bool `json:"backendHealthFiltering,omitempty"` + + // LocalDelivery reports that this node's gateway delivers a flow whose + // backend is on this node through the node's own uplink, rather than + // dropping it: GALACTIC_GATEWAY_LOCAL_DELIVERY is on, its encapsulation + // source is the node's locator address and usid_ingress is attached to + // its public interface. Core serves an + // Edge listener backend on a gateway's node only while that gateway + // reports it and is Ready. The gateway sets it on every status write; + // one that cannot deliver locally, an older one included, writes its + // status without it. + // +optional + LocalDelivery bool `json:"localDelivery,omitempty"` } // NetworkGatewayList is a list of NetworkGateway resources. diff --git a/cmd/galactic-gateway/encapsource.go b/cmd/galactic-gateway/encapsource.go index 6e3e9b115..0c8e78442 100644 --- a/cmd/galactic-gateway/encapsource.go +++ b/cmd/galactic-gateway/encapsource.go @@ -10,12 +10,14 @@ import ( "fmt" "log/slog" "net/netip" + "sync" "time" "sigs.k8s.io/controller-runtime/pkg/client" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/ebpf/attach" "go.datum.net/galactic/internal/plumbing/srv6" ) @@ -144,3 +146,90 @@ func encapSourceFromRouters(ctx context.Context, reader client.Reader, nodeName } return found, nil } + +// encapSourceIsNodeLocator reports whether encapSrc, as resolveEncapSource +// returned it, names this node: whether its first 64 bits, the Block and Node +// ID, are those of this node's locator address. edge_lb treats a backend uSID +// with those bits as local and delivers it through the node's own uplink, so +// the gateway reports LocalDelivery only when this holds. +// +// A derived source is the node's locator address by construction. A +// configured one is compared against the BGPRouter targeting this node: one +// that differs, or a router not readable yet, reports false and is logged, +// and nodeLocatorCheck asks again later. +func encapSourceIsNodeLocator( + ctx context.Context, reader client.Reader, nodeName, configured, encapSrc string, +) bool { + if configured == "" { + return true + } + src, err := netip.ParseAddr(encapSrc) + if err != nil { + return false + } + node, err := encapSourceFromRouters(ctx, reader, nodeName) + if err != nil { + slog.Warn("Not delivering to backends on this node: its locator could not be read", + "nodeName", nodeName, "error", err) + return false + } + if a, b := src.As16(), node.As16(); [8]byte(a[:8]) != [8]byte(b[:8]) { + slog.Warn("Not delivering to backends on this node: the configured SRv6 encapsulation source "+ + "is outside this node's locator", "configured", src, "locator", node) + return false + } + return true +} + +// usidIngressAttached reports whether usid_ingress is attached on iface, the +// public interface edge_lb runs on, where a flow for a backend on this node +// is handed up. Without it the packet meets the discard route for the node's +// own locator, so the gateway must not report LocalDelivery. A failure is +// logged at debug level: it is asked on every status write and is expected +// until galactic-cni attaches. +func usidIngressAttached(iface string) bool { + if iface == "" { + return false + } + if err := attach.IngressAttachedTo(iface); err != nil { + slog.Debug("Not delivering to backends on this node: usid_ingress is not attached to the public interface", + "interface", iface, "error", err) + return false + } + return true +} + +// nodeLocatorRecheck is how often nodeLocatorCheck asks again while its answer +// is false. +const nodeLocatorRecheck = 30 * time.Second + +// nodeLocatorCheck answers encapSourceIsNodeLocator for the gateway's life, +// since the gateway asks on every status write: it keeps a true answer, and +// while the answer is false asks again at most every interval, so a router +// that becomes readable after startup turns local delivery on without a +// restart. +type nodeLocatorCheck struct { + check func() bool + interval time.Duration + now func() time.Time + + mu sync.Mutex + ok bool + asked time.Time +} + +// holds reports the current answer, asking check when it is due. +func (c *nodeLocatorCheck) holds() bool { + c.mu.Lock() + defer c.mu.Unlock() + if c.ok { + return true + } + now := c.now() + if !c.asked.IsZero() && now.Sub(c.asked) < c.interval { + return false + } + c.asked = now + c.ok = c.check() + return c.ok +} diff --git a/cmd/galactic-gateway/encapsource_test.go b/cmd/galactic-gateway/encapsource_test.go index f4a181a6f..7f20f0a68 100644 --- a/cmd/galactic-gateway/encapsource_test.go +++ b/cmd/galactic-gateway/encapsource_test.go @@ -24,6 +24,8 @@ const ( testEncapNode = "dfw-worker2" testEncapLocator = "2001:db8:ff01::/48" testEncapDerived = "2001:db8:ff01:1002::" + // testEncapOutside is a configured source outside testEncapLocator. + testEncapOutside = "2001:db8:ffff::1" ) func testEncapRouter(namespace, name, node, locator string, nodeID int32) *bgpv1alpha1.BGPRouter { @@ -56,9 +58,9 @@ func TestResolveEncapSource(t *testing.T) { }{ { name: "configured value wins over the router", - configured: "2001:db8:ffff::1", + configured: testEncapOutside, routers: []client.Object{testEncapRouter("galactic-system", "r", testEncapNode, testEncapLocator, 0x1002)}, - want: "2001:db8:ffff::1", + want: testEncapOutside, }, { name: "derived from this node's router", @@ -235,3 +237,62 @@ func TestResolveEncapSourceListErrorStopsWithContext(t *testing.T) { t.Errorf("resolveEncapSource() error = %v, want it to wrap the last list error", err) } } + +// TestEncapSourceIsNodeLocator covers when the gateway reports LocalDelivery: +// a derived source always names this node; a configured one only while it +// shares the Block and Node ID of this node's locator address. +func TestEncapSourceIsNodeLocator(t *testing.T) { + router := testEncapRouter("galactic-system", "r", testEncapNode, testEncapLocator, 0x1002) + for _, tt := range []struct { + name string + configured string + encapSrc string + routers []client.Object + want bool + }{ + {name: "derived", encapSrc: testEncapDerived, want: true}, + {name: "configured inside the node's locator", configured: "2001:db8:ff01:1002::7", + encapSrc: "2001:db8:ff01:1002::7", routers: []client.Object{router}, want: true}, + {name: "configured outside the node's locator", configured: testEncapOutside, + encapSrc: testEncapOutside, routers: []client.Object{router}, want: false}, + {name: "configured with no router yet", configured: testEncapDerived, + encapSrc: testEncapDerived, want: false}, + } { + t.Run(tt.name, func(t *testing.T) { + got := encapSourceIsNodeLocator(context.Background(), testEncapReader(t, tt.routers...), + testEncapNode, tt.configured, tt.encapSrc) + if got != tt.want { + t.Errorf("encapSourceIsNodeLocator = %t, want %t", got, tt.want) + } + }) + } +} + +// TestNodeLocatorCheck: a false answer is asked again only once the interval +// has passed, so a router readable after startup turns local delivery on +// without a restart, and a true answer is kept without asking again. +func TestNodeLocatorCheck(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + answer, asked := false, 0 + c := &nodeLocatorCheck{ + interval: nodeLocatorRecheck, + now: func() time.Time { return now }, + check: func() bool { asked++; return answer }, + } + if c.holds() || asked != 1 { + t.Fatalf("first answer = true or asked %d times, want false after 1", asked) + } + answer = true + now = now.Add(nodeLocatorRecheck / 2) + if c.holds() || asked != 1 { + t.Errorf("asked again %d times before the interval passed", asked-1) + } + now = now.Add(nodeLocatorRecheck) + if !c.holds() || asked != 2 { + t.Errorf("answer after the interval = false or asked %d times, want true after 2", asked) + } + answer = false + if !c.holds() || asked != 2 { + t.Errorf("a true answer was asked again (%d) or dropped", asked) + } +} diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index 5a775ff7f..47b9d81f3 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -161,6 +161,13 @@ func runCmd(cfg *config.GatewayConfig) error { if ipv4VIPs { ipv4 = newIPv4Forwarding() } + // locator answers whether edge_lb recognizes this node's own backends + // (encapSourceIsNodeLocator); it stays nil, never, with no datapath. + var locator *nodeLocatorCheck + publicInterface := cfg.PublicInterface + // localDeliveryOn is GALACTIC_GATEWAY_LOCAL_DELIVERY: off, the gateway + // never reports local delivery, whatever the checks below answer. + localDeliveryOn := cfg.LocalDelivery if cfg.DatapathEnabled { if err := sysctl.SetProcSysPath(cfg.ProcSysPath); err != nil { return err @@ -169,6 +176,16 @@ func runCmd(cfg *config.GatewayConfig) error { if err != nil { return err } + reader, configured := mgr.GetAPIReader(), cfg.SRv6Address + locator = &nodeLocatorCheck{ + interval: nodeLocatorRecheck, + now: time.Now, + check: func() bool { + checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + return encapSourceIsNodeLocator(checkCtx, reader, nodeName, configured, encapSrc) + }, + } gwDatapath, err = setupGatewayDatapath(ctx, cfg.PublicInterface, cfg.InternalInterfaces, encapSrc, cfg.XDPAttach, ipv4, coverage) if err != nil { @@ -213,6 +230,9 @@ func runCmd(cfg *config.GatewayConfig) error { ReturnPath: returnPath, IPv4VIPs: ipv4VIPs, BackendHealth: backendHealth, + LocalDelivery: func() bool { + return localDeliveryOn && locator != nil && locator.holds() && usidIngressAttached(publicInterface) + }, // Forwarding follows need: on only once an IPv4 VIP is about to load. EnsureIPv4Forwarding: ipv4.enable, Scope: scope, @@ -317,6 +337,9 @@ func newRootCommand() *cobra.Command { cmd.Flags().Bool("gateway-backend-health", false, "Leave a backend its node reports Unhealthy out of the rule's Maglev table, once every gateway "+ "in the namespace does the same") + cmd.Flags().Bool("gateway-local-delivery", false, + "Deliver flows to a backend on this node, reporting status.localDelivery once the SRv6 address "+ + "is the node's locator address and usid_ingress is attached to the public interface") cmd.Flags().String("gateway-proc-sys-path", config.DefaultProcSysPath, "Procfs sysctl root to write the datapath's forwarding sysctls under, such as a writable mount "+ "of the host's /proc/sys/net at /net") diff --git a/config/crd/galactic.datumapis.com_networkgateways.yaml b/config/crd/galactic.datumapis.com_networkgateways.yaml index 254c7a54d..ee2c91d8e 100644 --- a/config/crd/galactic.datumapis.com_networkgateways.yaml +++ b/config/crd/galactic.datumapis.com_networkgateways.yaml @@ -164,6 +164,18 @@ spec: x-kubernetes-list-map-keys: - type x-kubernetes-list-type: map + localDelivery: + description: |- + LocalDelivery reports that this node's gateway delivers a flow whose + backend is on this node through the node's own uplink, rather than + dropping it: GALACTIC_GATEWAY_LOCAL_DELIVERY is on, its encapsulation + source is the node's locator address and usid_ingress is attached to + its public interface. Core serves an + Edge listener backend on a gateway's node only while that gateway + reports it and is Ready. The gateway sets it on every status write; + one that cannot deliver locally, an older one included, writes its + status without it. + type: boolean observedGeneration: description: ObservedGeneration is the .metadata.generation this status was computed from. diff --git a/deploy/containerlab/resources/galactic-gateway/base/gateway-lab-patch.yaml b/deploy/containerlab/resources/galactic-gateway/base/gateway-lab-patch.yaml index 7b04aa42b..79fce7e52 100644 --- a/deploy/containerlab/resources/galactic-gateway/base/gateway-lab-patch.yaml +++ b/deploy/containerlab/resources/galactic-gateway/base/gateway-lab-patch.yaml @@ -27,3 +27,8 @@ spec: # access as IPv4 VIPs covers it. - name: GALACTIC_GATEWAY_BACKEND_HEALTH value: "true" + # Off by default. Every lab gateway delivers flows to a backend + # on its own node, which the listener conformance test's local + # delivery case requires (tests/edgeconformance). + - name: GALACTIC_GATEWAY_LOCAL_DELIVERY + value: "true" diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index f57dda84b..bdab216ed 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -388,6 +388,7 @@ _Appears in:_ | `observedGeneration` _integer_ | ObservedGeneration is the .metadata.generation this status was computed from. | | | | `conditions` _[Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#condition-v1-meta) array_ | Conditions contains the standard conditions for this resource. | | | | `backendHealthFiltering` _boolean_ | BackendHealthFiltering reports that this node's gateway can leave a
backend reported Unhealthy out of a NetworkService's Maglev table.
Every gateway in the namespace applies health only while every
NetworkGateway there reports it, so all of them build the same table.
The gateway sets it on every status write; a gateway that cannot apply
health, an older one included, writes its status without it. | | | +| `localDelivery` _boolean_ | LocalDelivery reports that this node's gateway delivers a flow whose
backend is on this node through the node's own uplink, rather than
dropping it: GALACTIC_GATEWAY_LOCAL_DELIVERY is on, its encapsulation
source is the node's locator address and usid_ingress is attached to
its public interface. Core serves an
Edge listener backend on a gateway's node only while that gateway
reports it and is Ready. The gateway sets it on every status write;
one that cannot deliver locally, an older one included, writes its
status without it. | | | #### NetworkService diff --git a/docs/designs/edge-public-listener.md b/docs/designs/edge-public-listener.md index eda169c8c..10de3dcf7 100644 --- a/docs/designs/edge-public-listener.md +++ b/docs/designs/edge-public-listener.md @@ -1,6 +1,6 @@ # Galactic Edge public listener -Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist. Phase 2, core, is implemented: the ingress gVPC, listener admission and status, `/128` publication and the `NetworkService` writer. Phase 3's unmatched-egress drop is implemented. Phase 4's backend resolution is implemented: gateways and `galactic-router` serve a listener from the backends core reports serving. Its lab failover tests are not done yet. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. +Status: proposed, with its open decisions settled. The Phase 0 lab proof is done (see [Phase 0 results](#phase-0-results)), and Phase 1, the API, is implemented: `EdgeListener`, the `PublicListener` capability and `NetworkService.spec.edgeListenerRef` exist. Phase 2, core, is implemented: the ingress gVPC, listener admission and status, `/128` publication and the `NetworkService` writer. Phase 3's unmatched-egress drop is implemented. Gateways deliver to a backend on their own node (#1526), so the local-delivery exclusion applies only to a gateway that cannot. Phase 4's backend resolution is implemented: gateways and `galactic-router` serve a listener from the backends core reports serving. Its lab failover tests are not done yet. It extends the [Galactic Edge Foundation](galactic-edge.md) and reuses the [XDP/DSR gateway](../gateway/architecture.md). The [provider contract](../edge/provider-contract.md) remains the reference for behavior that exists today. This design follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). @@ -106,7 +106,7 @@ These were open when the design was proposed and were settled in [#1506](https:/ | Who supplies listener addresses | The platform authority, from the cell's gateway VIP prefixes. Core refuses any other address with `AddressOutsidePool`. | This is how gateway-namespace services get addresses today. An allocator can follow later without an API change. | | How many ingress gVPCs exist | One per provider type, not one per listener | It isolates providers from each other at the cost of one VPC identifier each. A provider has one listener, so a gVPC per listener adds no isolation. | | Who registers a listener attachment's host veth in `ifindex_vrf_table` | No new component. The node agent (`galactic-edge`) already registers every edge host link through `attachreg.RegisterHostLink`, which writes the `ifindex_vrf_table` row, sets the veth egress kind and attaches `usid_egress`. | The registration a listener needs exists today, and Phase 0 showed the VIP reverse translation working on an edge host link. | -| What happens to a backend on a node that also advertises the VIP | It is excluded, and the listener reports `LocalBackendsExcluded`. Phase 0 showed local delivery failing, so the exclusion stays until the gateway can deliver to its own node. | Excluding those backends keeps the rest of the work unblocked. | +| What happens to a backend on a node that also advertises the VIP | It is excluded while that node's gateway does not report `localDelivery`, and the listener reports `LocalBackendsExcluded`. A gateway that delivers locally (#1526) reports it, and its node's backends serve. | Excluding those backends keeps the rest of the work unblocked. | | How many listeners one `EdgeService` serves (proposed in #1509, awaiting review) | One. A newer listener naming a service an older listener that is not refused already names is refused with `CapabilityNotGranted`. | Each listener attachment's `/128` advertisement is one object per attachment, so two listeners sharing its service would contend for it; a provider has one listener, so the limit costs nothing. | | Which claim on a listener address wins (proposed in #1509, awaiting review) | The oldest, as the gateway decides between services: an older listener, the `NetworkService`s of an older listener while they exist, and a `galactic-system` `NetworkService` the gateway serves that was created no later than the listener. A project-namespace service, a service the gateway refused and a younger listener's services never claim. | It mirrors the gateway's own precedence, where a gateway-namespace service never loses to a project one, so a listener is never refused for an address the gateway would not give the other service. A younger listener refuses itself rather than both refusing each other while the gateways tear its services down. | @@ -248,7 +248,7 @@ Run on 2026-11-28 on the containerlab gvpc lab by `task verify:edge-listener` (` What this settles: - `RegisterHostLink` and `usid_egress` already carry listener replies, including the IPv4 translation. Phase 3 needs no reply-translation work. -- The gateway cannot deliver to a backend on its own node, so the `LocalBackendsExcluded` exclusion is required, not precautionary. +- The gateway cannot deliver to a backend on its own node, so the `LocalBackendsExcluded` exclusion is required, not precautionary. #1526 adds local delivery to the gateway, and the exclusion now applies only to a gateway node whose gateway does not report `localDelivery`. Limits of the proof: diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md index 1ef37d1ae..245b20394 100644 --- a/docs/edge/provider-contract.md +++ b/docs/edge/provider-contract.md @@ -315,7 +315,7 @@ Core accepts an `EdgeListener` only while all of these hold, and otherwise sets A listener refused at its current generation holds neither its service nor its addresses against a newer one, but its `NetworkService`s claim their addresses against newer listeners until they are gone. A newer listener's `NetworkService`s never claim against an older one, so an older listener that becomes admissible takes its addresses back, and the newer one refuses itself and withdraws. -The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; its instance is its pod's, on its node, holding its lease, until the Lease's `spec.renewTime` plus its `spec.leaseDurationSeconds` (the cell's lease duration when unset) less the maximum skew; and its `/128` can be published (see below). A backend on a node that a `NetworkGateway` in `galactic-system` targets is never serving, since a gateway cannot deliver to its own node. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded that way, or `NoBackends`. Each backend also reports its attachment's `uid` and `hostLink`. +The listener's backends, in `status.backends`, are the attachments made against its `EdgeService`. One is serving while the listener is accepted and the attachment is `Allocated`, `Programmed` and `Ready`, with its node, gVPC, address and host link reported; is `Admitted`, or `Draining` before its `status.drainDeadline`; its instance is its pod's, on its node, holding its lease, until the Lease's `spec.renewTime` plus its `spec.leaseDurationSeconds` (the cell's lease duration when unset) less the maximum skew; and its `/128` can be published (see below). A backend on a node that a `NetworkGateway` in `galactic-system` targets serves only while that gateway reports `status.localDelivery` and is `Ready`. It reports it once it delivers a flow whose backend is on its own node through that node's uplink, and only with `GALACTIC_GATEWAY_LOCAL_DELIVERY` on, which is off by default; a gateway that cannot, an older one included, drops those flows. `Programmed` is True with `BackendsReady` while any backend serves, and otherwise False with `LocalBackendsExcluded` when an eligible backend is excluded because its node's gateway does not report it, or `NoBackends`. Each backend also reports its attachment's `uid` and `hostLink`. Core publishes the `/128` of each serving backend's address as a `BGPAdvertisement` in `galactic-system`, named `edge-listener-`, so the gateways can resolve the backend's uSID. It has the shape of a route's: the router, VRF ID and first export route target of the gVPC's `BGPVRFInstance` on the backend's node, `End.DT46`, and the EVPN address family. It is labelled `galactic.datumapis.com/edge-listener` with the listener's UID, `galactic.datumapis.com/edge-listener-key` with a hash of the listener's namespace and name, and `galactic.datumapis.com/edge-listener-vpc` with the gVPC's identifier, instead of `galactic.datumapis.com/edge-route`, so `galactic-router` advertises it without a forwarding gate, and router GC, finding no netns annotation on it, never reclaims it. A backend whose `BGPVRFInstance` does not exist or names no router or export route target is not serving until it does, and neither is one whose address is not a plain IPv6 address. `Programmed` is not `BackendsReady` while no backend is published, and its message names why each such backend cannot be. A backend in another gVPC than the listener's ingress gVPC never serves. An object at a backend's advertisement name that lacks `galactic.datumapis.com/edge-listener` or the listener's `galactic.datumapis.com/edge-listener-key` is never updated, adopted or withdrawn: the backend does not serve, `Programmed` names it, and core records a `BGPAdvertisementNameTaken` Event. Core withdraws the advertisement, on a precondition of the version read, as soon as the backend stops serving, its attachment goes or its listener is gone. diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 54f1625a9..a13f2be2b 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -21,6 +21,7 @@ Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_GATEWAY` prefix | Datapath enabled | `GALACTIC_GATEWAY_DATAPATH_ENABLED` | `--gateway-datapath-enabled` | `true` | No | | IPv4 VIPs | `GALACTIC_GATEWAY_IPV4_VIPS` | `--gateway-ipv4-vips` | `false` | No | | Backend health | `GALACTIC_GATEWAY_BACKEND_HEALTH` | `--gateway-backend-health` | `false` | No | +| Local delivery | `GALACTIC_GATEWAY_LOCAL_DELIVERY` | `--gateway-local-delivery` | `false` | No | | Procfs sysctl root | `GALACTIC_GATEWAY_PROC_SYS_PATH` | `--gateway-proc-sys-path` | `/proc/sys` | No | | Project services | `GALACTIC_GATEWAY_PROJECT_SERVICES` | `--gateway-project-services` | `false` | No | | Gateway namespace | `GALACTIC_GATEWAY_NAMESPACE` | `--gateway-namespace` | — | With project services | @@ -152,6 +153,22 @@ rejects a set SRv6 address that isn't a native IPv6 address (an IPv4 or one is derived from the node's `BGPRouter`; two `BGPRouter`s for the same node that derive different addresses stop the gateway at startup. +`GALACTIC_GATEWAY_LOCAL_DELIVERY=true` lets this node report +`status.localDelivery`, so core sends Edge listener backends on this node +through its gateway. It is off by default and is set per gateway node. Off, +the gateway never reports it, and core leaves this node's backends out of its +listeners, as it does for a gateway that predates the switch. On, the gateway +reports it once the checks below pass. To roll back, turn it off: the status +clears on the next write and core stops serving this node's backends. + +With the switch on, the gateway delivers a flow whose backend is on its own +node only while its SRv6 address is the node's locator address, since it recognizes the node's +own backends by that address's first 64 bits. A derived address always is. +A set one is compared against the node's `BGPRouter`: while it is outside +the node's locator, or the router is not readable, local delivery stays off, +the gateway logs why, and it compares again every 30 seconds. See +[packet paths](packet-paths.md). + The `8081`/`5181` metrics/gRPC-health port defaults deliberately differ from `galactic-router`'s own `9179`/`5179` defaults, because on a gateway node both run as separate `hostNetwork: true` pods — every port either one diff --git a/docs/gateway/deployment.md b/docs/gateway/deployment.md index 71bb4c7e9..2d4d3f73d 100644 --- a/docs/gateway/deployment.md +++ b/docs/gateway/deployment.md @@ -527,6 +527,9 @@ counted in a VIP's own dropped packets because the port is unknown), `galactic_edge_neigh_fallbacks_total` (load-balanced packets handed to the kernel because the next hop toward the backend had no neighbor entry, for it to resolve the neighbor and forward them; not counted as drops), +`galactic_edge_local_deliveries_total` (load-balanced packets handed to the +kernel because the backend is on this node, for the uplink's `usid_ingress` +to deliver; not counted as drops), `galactic_edge_redirect_xmit_drops_total` (frames the kernel dropped after an XDP program on the node redirected them, labeled by target `interface` and `reason`; see [the observability guide](../observability/gateway.md)), and diff --git a/docs/gateway/packet-paths.md b/docs/gateway/packet-paths.md index cea39a90c..f919aac3a 100644 --- a/docs/gateway/packet-paths.md +++ b/docs/gateway/packet-paths.md @@ -255,9 +255,23 @@ forward half, so it has exactly one branch, not two. Replies are (`galactic_edge_neigh_fallbacks_total`), not as drops. Unlike the XDP path, they cross the node's netfilter FORWARD hook, as new flows from the node's own encapsulation source, so a host firewall that drops forwarded - traffic drops them too. The inner packet travels completely unmodified — - this is DSR's entire premise: no address or port rewriting and no checksum - touch anywhere. + traffic drops them too. A backend on the gateway's own node, one whose uSID + shares the first 64 bits (Block and Node ID) of the node's encapsulation + source, takes the same `XDP_PASS` without the lookup, which would only meet + the discard route for the node's own locator: the uplink's `usid_ingress` + claims the packet by that locator, decapsulates it, applies the backend's + VIP translation row and delivers it, as it does a packet from another + gateway. Those packets are counted in `local_deliveries` + (`galactic_edge_local_deliveries_total`), which counts the handoff; + `usid_ingress`'s per-VRF counters show the delivery. With + `GALACTIC_GATEWAY_LOCAL_DELIVERY` on (it is off by default), the gateway + reports `status.localDelivery` on its `NetworkGateway` while its encapsulation + source is its node's locator address and `usid_ingress` is attached to its + public interface (every member, for a bond), and core serves Edge listener + backends on its node only while it reports that and is `Ready`. + + The inner packet travels completely unmodified, which is DSR's entire + premise: no address or port rewriting and no checksum touch anywhere. See `edgedsr.c`'s own header comment for the full byte-level walkthrough, including the `EDGE_BARRIER_VAR` eBPF-verifier bounds-narrowing workaround diff --git a/docs/observability/gateway.md b/docs/observability/gateway.md index 77ad7bc98..0eaba343d 100644 --- a/docs/observability/gateway.md +++ b/docs/observability/gateway.md @@ -20,6 +20,7 @@ so there is no connection table to report. See | `galactic_edge_return_dropped_packets_total` | counter | same | Those replies that the datapath dropped. A subset of `return_packets_total` | | `galactic_edge_drops_total` | counter | `reason` | Packets `edge_lb` and `edge_return` dropped, by reason | | `galactic_edge_neigh_fallbacks_total` | counter | none | Packets `edge_lb` handed to the kernel to resolve the next hop. Not counted as drops | +| `galactic_edge_local_deliveries_total` | counter | none | Packets `edge_lb` handed to the kernel for a backend on its own node. Not counted as drops | | `galactic_edge_redirect_xmit_drops_total` | counter | `interface`, `reason` | Frames the kernel dropped after any XDP program redirected them, which no other counter shows | | `galactic_edge_control_plane_drops_total` | counter | `rule`, `reason` (`quota_exceeded`) | Rule applications refused before they reached the datapath | | `galactic_edge_dispatch_lease_renewals_total` | counter | `slot`, `result` | Renewals of the gateway's XDP dispatcher slot leases. Dispatch mode only | diff --git a/internal/config/gateway.go b/internal/config/gateway.go index 71217b669..dee0c205d 100644 --- a/internal/config/gateway.go +++ b/internal/config/gateway.go @@ -107,6 +107,14 @@ const ( // cannot list and watch ServiceVIPBindings runs as if it were off. EnvGatewayBackendHealth = "GALACTIC_GATEWAY_BACKEND_HEALTH" + // EnvGatewayLocalDelivery turns on delivering flows to a backend on the + // gateway's own node. Optional, defaulting to false. On, the gateway + // reports status.localDelivery once its SRv6 address is the node's + // locator address and usid_ingress is attached to its public interface, + // and core then sends this node's own backends through it. Off, it never + // reports it, so core leaves this node's backends out of its rules. + EnvGatewayLocalDelivery = "GALACTIC_GATEWAY_LOCAL_DELIVERY" + // EnvGatewayProcSysPath is the procfs sysctl root the datapath writes its // interfaces' forwarding sysctls under. Optional, defaulting to // DefaultProcSysPath. An unprivileged pod gets /proc/sys read-only, so the @@ -184,6 +192,9 @@ type GatewayConfig struct { // BackendHealth is EnvGatewayBackendHealth. BackendHealth bool + // LocalDelivery is EnvGatewayLocalDelivery. + LocalDelivery bool + // ProcSysPath is EnvGatewayProcSysPath. ProcSysPath string @@ -218,6 +229,7 @@ func NewGatewayConfig() *GatewayConfig { v.SetDefault("datapath_enabled", true) v.SetDefault("ipv4_vips", false) v.SetDefault("backend_health", false) + v.SetDefault("local_delivery", false) v.SetDefault("proc_sys_path", DefaultProcSysPath) v.SetDefault("project_services", false) v.SetDefault(keyGatewayNamespace, "") @@ -248,6 +260,7 @@ func (c *GatewayConfig) BindFlags(flags *pflag.FlagSet) { {"gateway-datapath-enabled", "datapath_enabled"}, {"gateway-ipv4-vips", "ipv4_vips"}, {"gateway-backend-health", "backend_health"}, + {"gateway-local-delivery", "local_delivery"}, {"gateway-proc-sys-path", "proc_sys_path"}, {"gateway-project-services", "project_services"}, {"gateway-namespace", keyGatewayNamespace}, @@ -276,6 +289,7 @@ func (c *GatewayConfig) readFields() { c.DatapathEnabled = c.v.GetBool("datapath_enabled") c.IPv4VIPs = c.v.GetBool("ipv4_vips") c.BackendHealth = c.v.GetBool("backend_health") + c.LocalDelivery = c.v.GetBool("local_delivery") c.ProcSysPath = c.v.GetString("proc_sys_path") c.ProjectServices = c.v.GetBool("project_services") c.Namespace = c.v.GetString(keyGatewayNamespace) diff --git a/internal/config/gateway_test.go b/internal/config/gateway_test.go index 4944772f5..2bd1d7116 100644 --- a/internal/config/gateway_test.go +++ b/internal/config/gateway_test.go @@ -271,6 +271,31 @@ func TestGatewayConfigBackendHealth(t *testing.T) { } } +// TestGatewayConfigLocalDelivery covers the local delivery switch: off by +// default, on from the environment, and on from the flag over the +// environment. +func TestGatewayConfigLocalDelivery(t *testing.T) { + if NewGatewayConfig().LocalDelivery { + t.Error("LocalDelivery = true by default, want false") + } + t.Setenv(EnvGatewayLocalDelivery, "true") + if !NewGatewayConfig().LocalDelivery { + t.Error("LocalDelivery = false with the env set to true") + } + + t.Setenv(EnvGatewayLocalDelivery, "false") + cfg := NewGatewayConfig() + flags := pflag.NewFlagSet("test", pflag.ContinueOnError) + flags.Bool("gateway-local-delivery", false, "") + if err := flags.Parse([]string{"--gateway-local-delivery=true"}); err != nil { + t.Fatal(err) + } + cfg.BindFlags(flags) + if !cfg.LocalDelivery { + t.Error("LocalDelivery = false with the flag set to true over the env") + } +} + func TestGatewayConfigProjectServices(t *testing.T) { t.Setenv(EnvGatewayNodeName, testGatewayNodeName) t.Setenv(EnvGatewayDatapathEnabled, "false") diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index 638d4280a..20d16a5ee 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -124,6 +124,15 @@ type NetworkGatewayReconciler struct { // this node then reports too; see passHealthGate. BackendHealth bool + // LocalDelivery reports whether this node's datapath delivers a flow + // whose backend is on this node: edge_lb recognizes the node's own uSIDs + // and usid_ingress is attached where edge_lb receives. It is asked on + // every status write, since galactic-cni may attach after the gateway + // starts. Nil means never. The gateway reports the answer in + // NetworkGateway status unless Disabled (reportsLocalDelivery), and core + // serves Edge listener backends on this node only while it does. + LocalDelivery func() bool + // EnsureIPv4Forwarding turns on the IPv4 forwarding the datapath's IPv4 // FIB lookups need. Each pass calls it before the engine loads any IPv4 // VIP, so a node that serves none never changes its IPv4 forwarding. It @@ -449,6 +458,7 @@ func (r *NetworkGatewayReconciler) reconcileGateway(ctx context.Context, req ctr r.drain.reset() gwCopy := gw.DeepCopy() gwCopy.Status.BackendHealthFiltering = r.BackendHealth + gwCopy.Status.LocalDelivery = r.reportsLocalDelivery() setGatewayCondition(gwCopy, metav1.Condition{ Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionFalse, @@ -469,6 +479,7 @@ func (r *NetworkGatewayReconciler) reconcileGateway(ctx context.Context, req ctr ) gwCopy := gw.DeepCopy() gwCopy.Status.BackendHealthFiltering = r.BackendHealth + gwCopy.Status.LocalDelivery = r.reportsLocalDelivery() gwCopy.Status.ObservedGeneration = gw.Generation gwCopy.Status.Capabilities = nil setGatewayCondition(gwCopy, metav1.Condition{ @@ -583,6 +594,7 @@ func (r *NetworkGatewayReconciler) reconcileServingGateway(ctx context.Context, gwCopy := gw.DeepCopy() gwCopy.Status.BackendHealthFiltering = r.BackendHealth + gwCopy.Status.LocalDelivery = r.reportsLocalDelivery() gwCopy.Status.Capabilities = r.servingCapabilities(leaseSupport) gwCopy.Status.ObservedGeneration = gw.Generation ready := readyConditionFor(status, advErr) @@ -682,6 +694,7 @@ func (r *NetworkGatewayReconciler) reconcileEngine( if err != nil { gwCopy := gw.DeepCopy() gwCopy.Status.BackendHealthFiltering = r.BackendHealth + gwCopy.Status.LocalDelivery = r.reportsLocalDelivery() setGatewayCondition(gwCopy, metav1.Condition{ Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionFalse, @@ -881,6 +894,13 @@ func (r *NetworkGatewayReconciler) gatherRules( return desired, outcomes, r.drain.settle(r.clock(), namespace, desired.Rules, live), nil } +// reportsLocalDelivery is the status.localDelivery this node's gateway +// writes: whether LocalDelivery says it delivers to backends on its own node, +// and never while the gateway is Disabled. +func (r *NetworkGatewayReconciler) reportsLocalDelivery() bool { + return !r.Disabled && r.LocalDelivery != nil && r.LocalDelivery() +} + // clock returns the current time from r.now, or time.Now when unset. func (r *NetworkGatewayReconciler) clock() time.Time { if r.now != nil { diff --git a/internal/controller/networkgateway_localdelivery_test.go b/internal/controller/networkgateway_localdelivery_test.go new file mode 100644 index 000000000..028cb74e6 --- /dev/null +++ b/internal/controller/networkgateway_localdelivery_test.go @@ -0,0 +1,43 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import "testing" + +// TestReportsLocalDelivery covers the status.localDelivery every status write +// of the gateway carries: what LocalDelivery answers now, never while the +// gateway is Disabled, and false when nothing can answer. +func TestReportsLocalDelivery(t *testing.T) { + yes := func() bool { return true } + no := func() bool { return false } + for _, tt := range []struct { + name string + r *NetworkGatewayReconciler + want bool + }{ + {name: "delivers locally", r: &NetworkGatewayReconciler{LocalDelivery: yes}, want: true}, + {name: "cannot deliver locally", r: &NetworkGatewayReconciler{LocalDelivery: no}}, + {name: "nothing to ask", r: &NetworkGatewayReconciler{}}, + {name: "disabled", r: &NetworkGatewayReconciler{LocalDelivery: yes, Disabled: true}}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := tt.r.reportsLocalDelivery(); got != tt.want { + t.Errorf("reportsLocalDelivery = %t, want %t", got, tt.want) + } + }) + } + + // The answer is asked again on every write, so a gateway that starts + // before galactic-cni attaches reports it once the attachment appears. + attached := false + r := &NetworkGatewayReconciler{LocalDelivery: func() bool { return attached }} + if r.reportsLocalDelivery() { + t.Fatal("reported local delivery before usid_ingress was attached") + } + attached = true + if !r.reportsLocalDelivery() { + t.Error("did not report local delivery once usid_ingress was attached") + } +} diff --git a/internal/edge/listener/backends.go b/internal/edge/listener/backends.go index c01404991..1504539f2 100644 --- a/internal/edge/listener/backends.go +++ b/internal/edge/listener/backends.go @@ -29,8 +29,9 @@ type backend struct { // eligible is whether the attachment may receive new flows wherever it // is: programmed, ready, holding its lease and not drained. eligible bool - // local is whether the attachment is on a node that advertises the - // listener's addresses. + // local is whether the attachment is on a node whose gateway advertises + // the listener's addresses but cannot deliver to a backend on its own + // node (gatewayNodes). local bool // adv is the advertisement of its /128, nil while its gVPC's VRF on its // node names no router or export route target. @@ -170,7 +171,11 @@ func (r *Reconciler) instanceHolds(ctx context.Context, att *galacticv1alpha1.Ed } // gatewayNodes is the set of nodes a NetworkGateway in the gateway namespace -// targets: every one of them advertises every accepted service's addresses. +// targets without reporting LocalDelivery. Every gateway advertises every +// accepted service's addresses, and one that cannot deliver to a backend on +// its own node drops the flows that pick it, so a backend there never serves. +// A gateway that reports LocalDelivery hands those flows to the backend +// through its own uplink, and its node's backends serve. func (r *Reconciler) gatewayNodes(ctx context.Context) (map[string]bool, error) { var list bgpv1alpha1.NetworkGatewayList if err := r.Client.List(ctx, &list, client.InNamespace(r.Namespace)); err != nil { @@ -178,13 +183,25 @@ func (r *Reconciler) gatewayNodes(ctx context.Context) (map[string]bool, error) } out := make(map[string]bool, len(list.Items)) for i := range list.Items { - if ref := list.Items[i].Spec.TargetRef; (ref.Kind == "" || ref.Kind == "Node") && ref.Name != "" { + gw := &list.Items[i] + if deliversLocally(gw) { + continue + } + if ref := gw.Spec.TargetRef; (ref.Kind == "" || ref.Kind == "Node") && ref.Name != "" { out[ref.Name] = true } } return out, nil } +// deliversLocally reports whether gw delivers flows to backends on its own +// node: it reports LocalDelivery and is Ready. A gateway that stopped, or +// whose datapath failed, may still carry an old LocalDelivery, so Ready is +// required too. +func deliversLocally(gw *bgpv1alpha1.NetworkGateway) bool { + return gw.Status.LocalDelivery && meta.IsStatusConditionTrue(gw.Status.Conditions, bgpv1alpha1.ConditionTypeReady) +} + // leaseDuration is LeaseDuration, or defaultLeaseDuration when it is zero. func (r *Reconciler) leaseDuration() time.Duration { if r.LeaseDuration == 0 { diff --git a/internal/edge/listener/listener_envtest_test.go b/internal/edge/listener/listener_envtest_test.go index 2a48f8faf..3ae8ea6ab 100644 --- a/internal/edge/listener/listener_envtest_test.go +++ b/internal/edge/listener/listener_envtest_test.go @@ -198,6 +198,19 @@ func TestListenerBackends(t *testing.T) { f.setReady(a, metav1.ConditionTrue) f.expectCondition(publicListener, programmed, metav1.ConditionTrue, galacticv1alpha1.EdgeListenerReasonBackendsReady) + // Once the gateway on that node delivers locally, its backend serves, + // and it is excluded again when the gateway stops reporting it. + f.vrf(vpc, nodeB, "router-b", 6) + f.setLocalDelivery(nodeB, true) + eventually(t, "the local-delivery gateway node's backend to serve", func() bool { + return f.serving()[b.att.Name] + }) + f.setLocalDelivery(nodeB, false) + eventually(t, "the gateway node's backend to be excluded again", func() bool { + s, ok := f.serving()[b.att.Name] + return ok && !s + }) + // A draining backend serves until its drain deadline. f.startDrain(a, time.Now().Add(6*time.Second).Truncate(time.Second)) never(t, "stopped serving before the drain deadline", func() bool { return !f.serving()[a.att.Name] }) diff --git a/internal/edge/listener/listener_fixture_envtest_test.go b/internal/edge/listener/listener_fixture_envtest_test.go index 4bc358d2e..ed97eedc6 100644 --- a/internal/edge/listener/listener_fixture_envtest_test.go +++ b/internal/edge/listener/listener_fixture_envtest_test.go @@ -332,6 +332,27 @@ func (f *fixture) gateway(node string) { }) } +// setLocalDelivery sets whether node's gateway reports LocalDelivery, as the +// gateway does on its own status, and marks it Ready as a running gateway is. +func (f *fixture) setLocalDelivery(node string, on bool) { + f.t.Helper() + ctx := context.Background() + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + var gw bgpv1alpha1.NetworkGateway + if err := f.admin.Get(ctx, client.ObjectKey{Namespace: gatewayNS, Name: node}, &gw); err != nil { + return err + } + gw.Status.LocalDelivery = on + meta.SetStatusCondition(&gw.Status.Conditions, metav1.Condition{ + Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionTrue, Reason: "Ready", + }) + return f.admin.Status().Update(ctx, &gw) + }) + if err != nil { + f.t.Fatalf("set LocalDelivery=%t on NetworkGateway %s: %v", on, node, err) + } +} + // acceptedListener starts the controllers and creates the accepted listener // publicListener against an ingress service, returning the ingress gVPC and // the service. diff --git a/internal/edge/listener/localdelivery_test.go b/internal/edge/listener/localdelivery_test.go new file mode 100644 index 000000000..3e24f79c2 --- /dev/null +++ b/internal/edge/listener/localdelivery_test.go @@ -0,0 +1,72 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package listener + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/event" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" +) + +// testGateway returns a NetworkGateway reporting localDelivery and, when +// ready is set, a True Ready condition. +func testGateway(localDelivery, ready bool) *bgpv1alpha1.NetworkGateway { + gw := &bgpv1alpha1.NetworkGateway{Status: bgpv1alpha1.NetworkGatewayStatus{LocalDelivery: localDelivery}} + status := metav1.ConditionFalse + if ready { + status = metav1.ConditionTrue + } + gw.Status.Conditions = []metav1.Condition{{Type: bgpv1alpha1.ConditionTypeReady, Status: status}} + return gw +} + +// TestDeliversLocally: a gateway counts as delivering to its own node's +// backends only while it reports it and is Ready, so a stopped or failed +// gateway's old report does not keep its node's backends serving. +func TestDeliversLocally(t *testing.T) { + for _, tt := range []struct { + name string + localDelivery, ready bool + want bool + }{ + {name: "reports it and is ready", localDelivery: true, ready: true, want: true}, + {name: "reports it but is not ready", localDelivery: true}, + {name: "ready but does not report it", ready: true}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := deliversLocally(testGateway(tt.localDelivery, tt.ready)); got != tt.want { + t.Errorf("deliversLocally = %t, want %t", got, tt.want) + } + }) + } +} + +// TestLocalDeliveryChanged: a status update re-decides the listeners only +// when it changes whether the gateway delivers locally. +func TestLocalDeliveryChanged(t *testing.T) { + p := localDeliveryChanged() + for _, tt := range []struct { + name string + old, new *bgpv1alpha1.NetworkGateway + want bool + }{ + {name: "starts reporting", old: testGateway(false, true), new: testGateway(true, true), want: true}, + {name: "becomes not ready", old: testGateway(true, true), new: testGateway(true, false), want: true}, + {name: "not ready either way", old: testGateway(true, false), new: testGateway(false, false)}, + {name: "unchanged", old: testGateway(true, true), new: testGateway(true, true)}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := p.Update(event.UpdateEvent{ObjectOld: tt.old, ObjectNew: tt.new}); got != tt.want { + t.Errorf("Update = %t, want %t", got, tt.want) + } + }) + } + if p.Create(event.CreateEvent{Object: testGateway(true, true)}) { + t.Error("Create passed, want it left to the generation predicate") + } +} diff --git a/internal/edge/listener/setup.go b/internal/edge/listener/setup.go index bcbe40d4b..8feeae8a4 100644 --- a/internal/edge/listener/setup.go +++ b/internal/edge/listener/setup.go @@ -213,6 +213,23 @@ var contention = predicate.Or[client.Object](specOrDeletion, predicate.Funcs{ }, }) +// localDeliveryChanged admits updates of a NetworkGateway that change whether +// it delivers locally (deliversLocally), which decides whether a backend on +// its node serves (gatewayNodes). Creates and deletes are left to the +// generation predicate it is combined with. +func localDeliveryChanged() predicate.Funcs { + return predicate.Funcs{ + CreateFunc: func(event.CreateEvent) bool { return false }, + DeleteFunc: func(event.DeleteEvent) bool { return false }, + GenericFunc: func(event.GenericEvent) bool { return false }, + UpdateFunc: func(e event.UpdateEvent) bool { + o, ok1 := e.ObjectOld.(*bgpv1alpha1.NetworkGateway) + n, ok2 := e.ObjectNew.(*bgpv1alpha1.NetworkGateway) + return ok1 && ok2 && deliversLocally(o) != deliversLocally(n) + }, + } +} + // inNamespace admits only objects in namespace. func inNamespace(namespace string) predicate.Predicate { return predicate.NewPredicateFuncs(func(o client.Object) bool { return o.GetNamespace() == namespace }) @@ -353,8 +370,10 @@ func (r *Reconciler) setup(mgr ctrl.Manager) error { // A lease has its instance's namespace and name. Only who holds it // decides a backend, not its renewals. Watches(&coordinationv1.Lease{}, byInstance, builder.WithPredicates(edgeroute.InstanceLeases, r.leaseHolding())). - // A gateway node cannot deliver to a backend on itself. - Watches(&bgpv1alpha1.NetworkGateway{}, all, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + // A backend on a gateway's node serves only while that gateway + // reports LocalDelivery (gatewayNodes). + Watches(&bgpv1alpha1.NetworkGateway{}, all, builder.WithPredicates(predicate.Or( + predicate.GenerationChangedPredicate{}, localDeliveryChanged()))). // An advertisement's listener, from its annotation, withdraws it // once it may no longer publish it. Watches(&bgpv1alpha1.BGPAdvertisement{}, handler.EnqueueRequestsFromMapFunc( diff --git a/internal/plumbing/ebpf/attach/health.go b/internal/plumbing/ebpf/attach/health.go index 02bec7668..cf96b3e6a 100644 --- a/internal/plumbing/ebpf/attach/health.go +++ b/internal/plumbing/ebpf/attach/health.go @@ -89,6 +89,20 @@ func checkMapsReachable(objs *prog.UsidObjects) error { return errors.Join(errs...) } +// IngressAttachedTo reports whether usid_ingress's filter is on the ingress of +// iface, or of every member of iface where it is a bond or a VLAN on one, +// since tc ingress classifies a bond's traffic on its members. A nil error +// means a packet received on iface, or handed up from its XDP hook, reaches +// usid_ingress. galactic-gateway checks its public interface this way before +// it reports that it delivers to backends on its own node. +func IngressAttachedTo(iface string) error { + names, err := expandBondSlaves([]string{iface}) + if err != nil { + return fmt.Errorf("attach: expand %q: %w", iface, err) + } + return checkAttached(names) +} + // checkAttached confirms this package's TC-BPF ingress filter is present on // every interface in ifaces. That proves kernel-level attachment, which the // program and map checks do not: those pass even after the filter itself was diff --git a/internal/plumbing/ebpf/attach/ingress_attached_test.go b/internal/plumbing/ebpf/attach/ingress_attached_test.go new file mode 100644 index 000000000..7ee36014b --- /dev/null +++ b/internal/plumbing/ebpf/attach/ingress_attached_test.go @@ -0,0 +1,75 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "testing" + + "github.com/vishvananda/netlink" +) + +// The links TestIngressAttachedTo fakes: a bond with members testIfaceEth0 +// and attachedMember, and a plain interface. +const ( + attachedBond = "bond0" + attachedMember = "eth1" + attachedNIC = "eth9" +) + +// TestIngressAttachedTo covers galactic-gateway's check before it reports +// local delivery: a bond passes only when usid_ingress's filter is on every +// member, where tc ingress classifies its traffic, and a plain interface +// when the filter is on it. +func TestIngressAttachedTo(t *testing.T) { + bondLink := &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Name: attachedBond, Index: 10}} + member := func(name string, index int) netlink.Link { + return &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: name, Index: index, MasterIndex: 10}} + } + links := map[string]netlink.Link{ + attachedBond: bondLink, + testIfaceEth0: member(testIfaceEth0, 11), + attachedMember: member(attachedMember, 12), + attachedNIC: &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: attachedNIC, Index: 19}}, + } + + for _, tt := range []struct { + name string + iface string + attached map[string]bool + wantErr bool + }{ + {name: "bond with every member attached", iface: attachedBond, + attached: map[string]bool{attachedBond: true, testIfaceEth0: true, attachedMember: true}}, + {name: "bond with a member missing", iface: attachedBond, + attached: map[string]bool{attachedBond: true, testIfaceEth0: true}, wantErr: true}, + {name: "plain interface attached", iface: attachedNIC, attached: map[string]bool{attachedNIC: true}}, + {name: "plain interface not attached", iface: attachedNIC, attached: map[string]bool{}, wantErr: true}, + } { + t.Run(tt.name, func(t *testing.T) { + prevByName, prevList, prevFilters := linkByNameFn, linkListFn, filterListFn + t.Cleanup(func() { linkByNameFn, linkListFn, filterListFn = prevByName, prevList, prevFilters }) + linkByNameFn = func(name string) (netlink.Link, error) { + if l, ok := links[name]; ok { + return l, nil + } + return nil, netlink.LinkNotFoundError{} + } + linkListFn = func() ([]netlink.Link, error) { + return []netlink.Link{links[attachedBond], links[testIfaceEth0], links[attachedMember], links[attachedNIC]}, nil + } + filterListFn = func(link netlink.Link, _ uint32) ([]netlink.Filter, error) { + if tt.attached[link.Attrs().Name] { + return []netlink.Filter{&netlink.BpfFilter{Name: filterName}}, nil + } + return nil, nil + } + + err := IngressAttachedTo(tt.iface) + if (err != nil) != tt.wantErr { + t.Errorf("IngressAttachedTo(%q) = %v, want error %t", tt.iface, err, tt.wantErr) + } + }) + } +} diff --git a/internal/plumbing/ebpf/edgemetrics/collector.go b/internal/plumbing/ebpf/edgemetrics/collector.go index 6c5aa51c0..8421d4495 100644 --- a/internal/plumbing/ebpf/edgemetrics/collector.go +++ b/internal/plumbing/ebpf/edgemetrics/collector.go @@ -47,6 +47,7 @@ type Collector struct { rangeTable *edgemap.VIPTable dropReasons DropReasonsReader neighFallbacks DropReasonsReader + localDelivery DropReasonsReader attribution VPCAttribution } @@ -65,6 +66,13 @@ func (c *Collector) WithNeighFallbacks(m DropReasonsReader) *Collector { return c } +// WithLocalDeliveries adds the local_deliveries map, a single-entry per-CPU +// array, as galactic_edge_local_deliveries_total. +func (c *Collector) WithLocalDeliveries(m DropReasonsReader) *Collector { + c.localDelivery = m + return c +} + // NewCollectorFromObjects builds a Collector reading directly from a loaded // object set's maps. func NewCollectorFromObjects(objs *edgeprog.EdgedsrObjects, attribution VPCAttribution) *Collector { @@ -75,7 +83,7 @@ func NewCollectorFromObjects(objs *edgeprog.EdgedsrObjects, attribution VPCAttri ).WithPeerTable(edgemap.KernelTable{Map: objs.VipRangeBackends}), objs.DropReasons, attribution, - ).WithNeighFallbacks(objs.NeighFallbacks) + ).WithNeighFallbacks(objs.NeighFallbacks).WithLocalDeliveries(objs.LocalDeliveries) collector.rangeTable = edgemap.NewVIPTable(edgemap.KernelTable{Map: objs.VipRangeBackends}, edgemap.KernelTable{Map: objs.VipStatsTable}, edgemap.KernelTable{Map: objs.VipAddrTable}, @@ -144,6 +152,13 @@ var ( "Not counted in drops_total.", nil, nil, ) + localDeliveriesDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "", "local_deliveries_total"), + "Encapsulated packets edge_lb handed to the kernel because the backend Maglev chose is on "+ + "this node, for the uplink's usid_ingress to decapsulate and deliver. Counts the handoff, "+ + "not delivery. Not counted in drops_total.", + nil, nil, + ) returnPacketsDesc = prometheus.NewDesc( prometheus.BuildFQName(namespace, "return", "packets_total"), "Reply packets this node forwarded for traffic sourced from this VIP+port+protocol, bypassing "+ @@ -176,6 +191,7 @@ func (c *Collector) Describe(ch chan<- *prometheus.Desc) { ch <- ruleSecondsSinceLastPacketDesc ch <- dropsDesc ch <- neighFallbacksDesc + ch <- localDeliveriesDesc ch <- returnPacketsDesc ch <- returnBytesDesc ch <- returnDroppedDesc @@ -186,7 +202,8 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric) { c.collectRules(ch) c.collectReturn(ch) c.collectDrops(ch) - c.collectNeighFallbacks(ch) + collectCounter(ch, c.neighFallbacks, neighFallbacksDesc, "neigh_fallbacks") + collectCounter(ch, c.localDelivery, localDeliveriesDesc, "local_deliveries") } // vpcs snapshots the attribution. Callers take it after listing a map: the @@ -308,18 +325,20 @@ func (c *Collector) collectDrops(ch chan<- prometheus.Metric) { } } -func (c *Collector) collectNeighFallbacks(ch chan<- prometheus.Metric) { - if c.neighFallbacks == nil { +// collectCounter reports m, a single-entry per-CPU array named name, as the +// counter desc. A nil m reports nothing. +func collectCounter(ch chan<- prometheus.Metric, m DropReasonsReader, desc *prometheus.Desc, name string) { + if m == nil { return } var perCPU []uint64 - if err := c.neighFallbacks.Lookup(uint32(0), &perCPU); err != nil { - ch <- prometheus.NewInvalidMetric(neighFallbacksDesc, fmt.Errorf("lookup neigh_fallbacks: %w", err)) + if err := m.Lookup(uint32(0), &perCPU); err != nil { + ch <- prometheus.NewInvalidMetric(desc, fmt.Errorf("lookup %s: %w", name, err)) return } var total uint64 for _, v := range perCPU { total += v } - ch <- prometheus.MustNewConstMetric(neighFallbacksDesc, prometheus.CounterValue, float64(total)) + ch <- prometheus.MustNewConstMetric(desc, prometheus.CounterValue, float64(total)) } diff --git a/internal/plumbing/ebpf/edgemetrics/collector_test.go b/internal/plumbing/ebpf/edgemetrics/collector_test.go index 253d494a2..163664a62 100644 --- a/internal/plumbing/ebpf/edgemetrics/collector_test.go +++ b/internal/plumbing/ebpf/edgemetrics/collector_test.go @@ -455,6 +455,25 @@ func TestCollector_CollectsNeighFallbacks(t *testing.T) { } } +// TestCollector_CollectsLocalDeliveries covers the packets edge_lb handed to +// the kernel for a backend on its own node: they report as their own counter, +// apart from neighbor fallbacks and drops. +func TestCollector_CollectsLocalDeliveries(t *testing.T) { + vt := edgemap.NewVIPTable( + newFakeVIPTable(), newFakeStatsTable(), newFakeAddrTable(), newFakeReturnStatsTable()) + c := NewCollector(vt, fakeDropReasons{}, nil). + WithNeighFallbacks(fakeDropReasons{0: 2}). + WithLocalDeliveries(fakeDropReasons{0: 7}) + metrics := collect(t, c) + + if got := metricValue(findMetric(t, metrics, localDeliveriesDesc, "", "")); got != 7 { + t.Errorf("local_deliveries_total = %v, want 7", got) + } + if got := metricValue(findMetric(t, metrics, neighFallbacksDesc, "", "")); got != 2 { + t.Errorf("neigh_fallbacks_total = %v, want 2", got) + } +} + // TestCollector_CollectsReturnCounters covers #1377: the return counters are // keyed per listener, as the forward counters are, so two listeners sharing // one address report separate series. A listener that has not sourced a reply diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr.c b/internal/plumbing/ebpf/edgeprog/edgedsr.c index 7fddb98d9..e7c659612 100644 --- a/internal/plumbing/ebpf/edgeprog/edgedsr.c +++ b/internal/plumbing/ebpf/edgeprog/edgedsr.c @@ -428,6 +428,16 @@ struct { __type(value, __u64); } neigh_fallbacks SEC(".maps"); +// local_deliveries counts the encapsulated packets edge_lb passed to the +// kernel because the backend Maglev chose is on this node; see lb_forward. +// They are deliveries, not drops, so they have their own map. +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, __u64); +} local_deliveries SEC(".maps"); + // struct icmp_bucket is one CPU's token bucket, held as nanoseconds of credit // rather than whole tokens so a refill is an addition, with no division on the // packet path: each message costs EDGE_ICMP_COST_NS, and credit accrues one @@ -722,12 +732,18 @@ static EDGE_ALWAYS_INLINE long resolve_fib4_and_write_eth(void *ctx, __u32 ifind // the backend's uSID, queuing it while it solicits the neighbor, and every // later packet finds the entry and stays in XDP. That case returns // EDGE_PUSH_TO_KERNEL and is counted in neigh_fallbacks, not as a drop. +// +// A local destination, a uSID on this node, takes the same path without the +// lookup, which would only meet the discard route for this node's own +// locator. The uplink's usid_ingress claims the packet by that locator and +// delivers it as it would one from another gateway. It returns +// EDGE_PUSH_TO_KERNEL and is counted in local_deliveries. #define EDGE_PUSH_TO_KERNEL 1 static EDGE_ALWAYS_INLINE int push_outer_header(struct xdp_md *ctx, const __u8 src[16], const __u8 dst[16], __be16 outer_payload_len, __u8 nexthdr, struct vip_stats_value *stats, __u32 *egress_ifindex, - __u16 *frag_mtu) + __u16 *frag_mtu, int local) { struct edge_ethhdr orig_eth; void *orig = (void *) (long) ctx->data; @@ -766,6 +782,17 @@ static EDGE_ALWAYS_INLINE int push_outer_header(struct xdp_md *ctx, const __u8 s __builtin_memcpy(outer->saddr, src, 16); __builtin_memcpy(outer->daddr, dst, 16); + if (local) { + __builtin_memcpy(eth->h_dest, orig_eth.h_dest, sizeof(eth->h_dest)); + __builtin_memcpy(eth->h_source, orig_eth.h_source, sizeof(eth->h_source)); + eth->h_proto = __builtin_bswap16(EDGE_ETH_P_IPV6); + __u32 key = 0; + __u64 *counter = bpf_map_lookup_elem(&local_deliveries, &key); + if (counter) + *counter += 1; + return EDGE_PUSH_TO_KERNEL; + } + long fib_rc = resolve_fib_and_write_eth(ctx, ctx->ingress_ifindex, src, dst, (__u16) (sizeof(*outer) + __builtin_bswap16(outer_payload_len)), eth, egress_ifindex, frag_mtu); @@ -983,6 +1010,19 @@ static EDGE_ALWAYS_INLINE int send_frag_needed4(struct xdp_md *ctx, __u32 mtu) return leave_via(ctx, egress_ifindex, 0); } +// backend_is_local reports whether usid is on this node: whether its first 64 +// bits, the Block and Node ID that name a node, equal those of encap_src, +// this node's locator address. usid_ingress claims a packet by the same 64 +// bits against locator_table, so a local backend's packet is one this node's +// own uplink decapsulates. +static EDGE_ALWAYS_INLINE int backend_is_local(const __u8 usid[16], const __u8 encap_src[16]) +{ + __u64 a, b; + __builtin_memcpy(&a, usid, sizeof(a)); + __builtin_memcpy(&b, encap_src, sizeof(b)); + return a == b; +} + // --------------------------------------------------------------------- // Entry points. // --------------------------------------------------------------------- @@ -1036,10 +1076,11 @@ static EDGE_ALWAYS_INLINE int lb_forward(struct xdp_md *ctx, struct vip_value *r // The inner packet is pushed completely unmodified: no translation and no // checksum touch, the client's packet travelling inside untouched to the - // backend, which replies to the client directly. + // backend, which replies to the client directly. A backend on this node is + // delivered through the kernel instead of the FIB (backend_is_local). __u32 egress_ifindex = 0; int pushed = push_outer_header(ctx, cfg->encap_src, b->usid, outer_payload_len, nexthdr, stats, - &egress_ifindex, frag_mtu); + &egress_ifindex, frag_mtu, backend_is_local(b->usid, cfg->encap_src)); if (pushed == EDGE_PUSH_TO_KERNEL) return XDP_PASS; if (pushed != 0) diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr_local_test.go b/internal/plumbing/ebpf/edgeprog/edgedsr_local_test.go new file mode 100644 index 000000000..d5da300da --- /dev/null +++ b/internal/plumbing/ebpf/edgeprog/edgedsr_local_test.go @@ -0,0 +1,156 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package edgeprog + +import ( + "bytes" + "encoding/binary" + "net/netip" + "testing" +) + +// localEncap is an encapsulation source on testUSID's node: its first 64 +// bits, the Block and Node ID, are testUSID's. +var localEncap = netip.MustParseAddr("fc00:1:2::1") + +// TestEdgeLB_LocalBackendGoesToKernel covers a backend on the gateway's own +// node, for both VIP families: edge_lb pushes the outer header as for any +// backend but hands the packet to the kernel, framed as it arrived, without a +// FIB lookup, so the uplink's usid_ingress decapsulates and delivers it. No +// route to the uSID exists, as on a node whose own locator is a discard +// route. The packet counts in local_deliveries, not as a drop or a neighbor +// fallback. +func TestEdgeLB_LocalBackendGoesToKernel(t *testing.T) { + for _, tt := range []struct { + name string + build func(t *testing.T, objs *EdgedsrObjects) (EdgedsrVipKey, []byte, int) + }{ + {name: "IPv6 VIP", build: func(t *testing.T, objs *EdgedsrObjects) (EdgedsrVipKey, []byte, int) { + vip := netip.MustParseAddr("2001:db8::100") + key := putIPv4VIP(t, objs, ipprotoTCP, 443, vip, testUSID) + pkt := buildL4Packet(t, ipprotoTCP, vip, netip.MustParseAddr("2001:db8:ffff::1"), 41000, 443, nil) + return key, pkt, ipprotoIPv6Encap + }}, + {name: "IPv4 VIP", build: func(t *testing.T, objs *EdgedsrObjects) (EdgedsrVipKey, []byte, int) { + key := putIPv4VIP(t, objs, ipprotoTCP, 443, testVIP4, testUSID) + pkt := buildIPv4Packet(t, ipprotoTCP, testVIP4, testClient4, 41000, 443, nil, ip4Opts{}) + return key, pkt, ipprotoIPIP + }}, + } { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + installChainStub(t, objs, roleGatewayLB|roleEgress) + key, pkt, nexthdr := tt.build(t, objs) + if err := objs.EncapConfigTable.Put(uint32(0), EdgedsrEncapConfig{EncapSrc: localEncap.As16()}); err != nil { + t.Fatalf("populate encap_config_table: %v", err) + } + + ret, out := runLB(t, objs, pkt) + if ret != xdpPass { + t.Fatalf("verdict = %d, want XDP_PASS (%d)", ret, xdpPass) + } + if len(out) < ethLen+ip6Len { + t.Fatalf("output is %d bytes, too short for Ethernet and an outer IPv6 header", len(out)) + } + if !bytes.Equal(out[:12], pkt[:12]) { + t.Errorf("MAC addresses = % x, want the arriving frame's % x", out[:12], pkt[:12]) + } + if got := binary.BigEndian.Uint16(out[12:14]); got != 0x86DD { + t.Errorf("EtherType = %#04x, want IPv6", got) + } + if got := out[ethLen+6]; got != byte(nexthdr) { + t.Errorf("outer next header = %d, want %d", got, nexthdr) + } + if got := netip.AddrFrom16([16]byte(out[ethLen+8 : ethLen+24])); got != localEncap { + t.Errorf("outer source = %v, want the encapsulation source %v", got, localEncap) + } + if got := netip.AddrFrom16([16]byte(out[ethLen+24 : ethLen+40])); got != testUSID { + t.Errorf("outer destination = %v, want the backend's uSID %v", got, testUSID) + } + if !bytes.Equal(out[ethLen+ip6Len:], pkt[ethLen:]) { + t.Errorf("inner packet changed:\n got: % x\nwant: % x", out[ethLen+ip6Len:], pkt[ethLen:]) + } + + if got := sumPerCPU(t, objs.LocalDeliveries, 0); got != 1 { + t.Errorf("local_deliveries = %d, want 1", got) + } + if got := sumPerCPU(t, objs.NeighFallbacks, 0); got != 0 { + t.Errorf("neigh_fallbacks = %d, want 0", got) + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonFibUnreachable); got != 0 { + t.Errorf("drop_reasons[fib_unreachable] = %d, want 0", got) + } + var stats EdgedsrVipStatsValue + if err := objs.VipStatsTable.Lookup(key, &stats); err != nil { + t.Fatalf("lookup vip_stats_table: %v", err) + } + if stats.Packets != 1 || stats.DroppedPackets != 0 { + t.Errorf("vip stats packets/dropped = %d/%d, want 1/0", stats.Packets, stats.DroppedPackets) + } + }) + } +} + +// TestEdgeLB_RemoteBackendIsNotLocal covers the same backend seen from a +// gateway on another node: an encapsulation source whose Node ID differs +// takes the FIB lookup as before. With no route to the uSID that lookup +// fails, so the packet is a counted drop and never a local delivery. +func TestEdgeLB_RemoteBackendIsNotLocal(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + installChainStub(t, objs, roleGatewayLB|roleEgress) + vip := netip.MustParseAddr("2001:db8::100") + putIPv4VIP(t, objs, ipprotoTCP, 443, vip, testUSID) + pkt := buildL4Packet(t, ipprotoTCP, vip, netip.MustParseAddr("2001:db8:ffff::1"), 41000, 443, nil) + + ret, _ := runLB(t, objs, pkt) + if ret == xdpPass { + t.Fatalf("verdict = XDP_PASS, want the remote backend to take the FIB lookup") + } + if got := sumPerCPU(t, objs.LocalDeliveries, 0); got != 0 { + t.Errorf("local_deliveries = %d, want 0", got) + } +} + +// TestEdgeLB_LocalComparisonWidth pins backend_is_local to exactly the first +// 64 bits. testUSID is fc00:1:2::a1b2. An encapsulation source that shares its +// first 48 bits but differs in bits 48 to 63 is another node and takes the FIB +// lookup; one that differs only from bit 64 on, the first bit past the Node +// ID, is this node and is delivered locally. +func TestEdgeLB_LocalComparisonWidth(t *testing.T) { + for _, tt := range []struct { + name string + encap netip.Addr + local bool + }{ + {name: "differs in bits 48 to 63", encap: netip.MustParseAddr("fc00:1:2:1::1"), local: false}, + {name: "differs from bit 64", encap: netip.MustParseAddr("fc00:1:2:0:8000::1"), local: true}, + } { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + installChainStub(t, objs, roleGatewayLB|roleEgress) + vip := netip.MustParseAddr("2001:db8::100") + putIPv4VIP(t, objs, ipprotoTCP, 443, vip, testUSID) + if err := objs.EncapConfigTable.Put(uint32(0), EdgedsrEncapConfig{EncapSrc: tt.encap.As16()}); err != nil { + t.Fatalf("populate encap_config_table: %v", err) + } + pkt := buildL4Packet(t, ipprotoTCP, vip, netip.MustParseAddr("2001:db8:ffff::1"), 41000, 443, nil) + + ret, _ := runLB(t, objs, pkt) + if got := ret == xdpPass; got != tt.local { + t.Errorf("XDP_PASS = %v (verdict %d), want %v", got, ret, tt.local) + } + want := uint64(0) + if tt.local { + want = 1 + } + if got := sumPerCPU(t, objs.LocalDeliveries, 0); got != want { + t.Errorf("local_deliveries = %d, want %d", got, want) + } + }) + } +} diff --git a/tests/edgeconformance/listener_test.go b/tests/edgeconformance/listener_test.go index ff48effa9..25d42234e 100644 --- a/tests/edgeconformance/listener_test.go +++ b/tests/edgeconformance/listener_test.go @@ -47,8 +47,9 @@ import ( // The provider runs on edgeNode2. Remote delivery pins the VIP on the // transit router to edgeNode1, so the gateway that receives each packet is // not the backend's node; it must pass. Local delivery pins the VIP to -// edgeNode2, the backend's own node; it records what happens, including the -// gateway's drop counters, and does not fail the test. Negative egress sends +// edgeNode2, the backend's own node, whose gateway hands each packet to its +// own uplink's usid_ingress (#1526); it must pass too, and it records the +// gateway's drop counters. Negative egress sends // from the listener to an internet address, which the backend's node must // drop and count. func TestListenerBackend(t *testing.T) { @@ -149,22 +150,25 @@ func TestListenerBackend(t *testing.T) { drops := p.l.gatewayDrops(t, p.node) rule := p.l.rulePackets(t, p.node, f.vip) for _, proto := range listenerProtocols { + eventually(t, 2*time.Minute, 2*time.Second, proto+" through "+p.node, func() (bool, error) { + err := p.request(f, proto) + return err == nil, err + }) answered := 0 - var last error for range listenerFlows { if err := p.request(f, proto); err != nil { - last = err + t.Errorf("%s %s through the backend's own gateway: %v", f.name, proto, err) continue } answered++ } p.l.record(t, proto+" flows answered", fmt.Sprintf("%d/%d", answered, listenerFlows)) - if last != nil { - p.l.record(t, proto+" last failure", last) - } } - p.l.record(t, p.node+" rule packets", - p.l.rulePackets(t, p.node, f.vip)-rule) + after := p.l.rulePackets(t, p.node, f.vip) + p.l.record(t, p.node+" rule packets", after-rule) + if after <= rule { + t.Errorf("%s counted no packets for %s: another node served the VIP", p.node, f.vip) + } p.l.record(t, p.node+" drops by reason", diffDrops(drops, p.l.gatewayDrops(t, p.node))) }) }