From d4637096c0005d0f6561ae512c2b8a84f53725b7 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 14:33:39 -0400 Subject: [PATCH 1/4] feat(api): Report on NetworkGateway whether a gateway applies backend health Every gateway must build the same Maglev table, so a gateway may take an unhealthy backend out only while every other gateway in its namespace does too. Gateways need a way to tell each other that. NetworkGateway.status.backendHealthFiltering is set by a gateway that applies backend health. It is a typed status field rather than a condition on purpose: a gateway that predates it decodes its own NetworkGateway without the field and writes its status back without it, so an older or rolled-back gateway clears the report instead of leaving a stale claim behind. Co-Authored-By: Claude Opus 5.5 --- api/network/v1alpha1/gateway_types.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/api/network/v1alpha1/gateway_types.go b/api/network/v1alpha1/gateway_types.go index 3729095cd..8273b95ee 100644 --- a/api/network/v1alpha1/gateway_types.go +++ b/api/network/v1alpha1/gateway_types.go @@ -55,6 +55,15 @@ type NetworkGatewayStatus struct { // +listMapKey=type // +optional Conditions []metav1.Condition `json:"conditions,omitempty"` + + // 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. + // +optional + BackendHealthFiltering bool `json:"backendHealthFiltering,omitempty"` } // NetworkGatewayList is a list of NetworkGateway resources. From 538dd2a40f8466479b0ce76be167b6030d8390e0 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 14:33:39 -0400 Subject: [PATCH 2/4] chore(api): Regenerate the NetworkGateway CRD and API reference Generated by controller-gen v0.21.0 and crd-ref-docs from NetworkGatewayStatus.BackendHealthFiltering. Co-Authored-By: Claude Opus 5.5 --- config/crd/galactic.datumapis.com_networkgateways.yaml | 9 +++++++++ docs/api/network-gateway.md | 1 + 2 files changed, 10 insertions(+) diff --git a/config/crd/galactic.datumapis.com_networkgateways.yaml b/config/crd/galactic.datumapis.com_networkgateways.yaml index d9b39e41f..bbf5b5667 100644 --- a/config/crd/galactic.datumapis.com_networkgateways.yaml +++ b/config/crd/galactic.datumapis.com_networkgateways.yaml @@ -88,6 +88,15 @@ spec: status: description: NetworkGatewayStatus defines the observed state of a NetworkGateway. properties: + backendHealthFiltering: + description: |- + 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. + type: boolean conditions: description: Conditions contains the standard conditions for this resource. diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index 99c2c6c0c..391fbc954 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -378,6 +378,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. | | | #### NetworkService From e1738990af21aa916ea1304a485e70085931482d Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 14:33:39 -0400 Subject: [PATCH 3/4] feat(gateway): Take unhealthy backends out of the Maglev table A backend that stops serving keeps its share of every gateway's Maglev table, so every flow hashed to it fails until the NetworkService is edited, even though its own node now publishes that it is unhealthy. With GALACTIC_GATEWAY_BACKEND_HEALTH on, buildDesiredRule leaves out a backend whose ServiceVIPBinding reports it Unhealthy for its current VPCAttachment and the rule's health check port. Unknown, a missing decision and a decision about another attachment or port all keep the backend. A family whose backends are all Unhealthy keeps them all and stays advertised, because an empty table drops every flow and the cause is often the probe itself. The datapath is unchanged: health only filters the table's input. A gateway applies health only while every NetworkGateway in its namespace reports backendHealthFiltering, so all gateways read the same decisions and build the same table. One gateway that does not filter, not yet upgraded, rolled back or with the switch off, turns filtering off for all of them. Gateway status changes to that field re-queue every gateway in the namespace. The switch is off by default and reuses the IPv4 VIPs startup check of ServiceVIPBinding access: a gateway whose ClusterRole lacks it runs with the switch off instead of stalling its cache. Rules report BackendsUnhealthy, NoHealthyBackends or HealthChecksNotApplied on each gateway's Programmed condition, and BackendsReady rolls them up. Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-gateway/main.go | 20 +- cmd/galactic-gateway/root.go | 32 +- docs/agents/ARCHITECTURE-GATEWAY.md | 41 +- docs/gateway/backend-health.md | 33 +- docs/gateway/configuration.md | 100 +++-- internal/config/gateway.go | 16 + internal/config/gateway_test.go | 25 ++ .../controller/networkgateway_controller.go | 270 ++++++++--- .../networkgateway_controller_test.go | 11 +- internal/controller/networkgateway_health.go | 113 +++++ .../controller/networkgateway_health_test.go | 425 ++++++++++++++++++ .../controller/networkgateway_ipv4_test.go | 35 +- .../controller/networkgateway_ipv4gate.go | 43 +- .../networkgateway_ipv4gate_test.go | 2 +- internal/controller/networkservice_summary.go | 23 +- .../controller/networkservice_summary_test.go | 29 ++ internal/controller/rulebackends.go | 4 + 17 files changed, 1032 insertions(+), 190 deletions(-) create mode 100644 internal/controller/networkgateway_health.go create mode 100644 internal/controller/networkgateway_health_test.go diff --git a/cmd/galactic-gateway/main.go b/cmd/galactic-gateway/main.go index eb595c9a3..ccd587d98 100644 --- a/cmd/galactic-gateway/main.go +++ b/cmd/galactic-gateway/main.go @@ -152,6 +152,22 @@ var ipv4ReviewRetry = time.Second // bindings once no gateway reports it loaded, so a brief API server outage // while every gateway restarts must not do that. func resolveIPv4VIPs(ctx context.Context, c client.Client, requested bool) (bool, error) { + return resolveBindingReader(ctx, c, requested, "IPv4 VIPs") +} + +// resolveBackendHealth returns whether this process applies backend health: +// requested, from GALACTIC_GATEWAY_BACKEND_HEALTH, and allowed by +// ipv4VIPsAllowed's check of ServiceVIPBinding access, which reading health +// needs as much as IPv4 VIPs do. It behaves as resolveIPv4VIPs does. +func resolveBackendHealth(ctx context.Context, c client.Client, requested bool) (bool, error) { + return resolveBindingReader(ctx, c, requested, "backend health") +} + +// resolveBindingReader returns whether feature, which reads ServiceVIPBindings, +// is on: requested and allowed by ipv4VIPsAllowed. A denial is logged and +// turns it off; a review that cannot be made is retried until ctx ends and +// then returned as an error. +func resolveBindingReader(ctx context.Context, c client.Client, requested bool, feature string) (bool, error) { if !requested { return false, nil } @@ -162,12 +178,12 @@ func resolveIPv4VIPs(ctx context.Context, c client.Client, requested bool) (bool return true, nil case errors.Is(err, errIPv4AccessDenied): ctrl.Log.WithName("rbac-preflight").Error(err, - "IPv4 VIPs turned off on this node: grant get, list and watch on servicevipbindings and restart") + feature+" turned off on this node: grant get, list and watch on servicevipbindings and restart") return false, nil } select { case <-ctx.Done(): - return false, fmt.Errorf("could not confirm access for IPv4 VIPs: %w", err) + return false, fmt.Errorf("could not confirm access for %s: %w", feature, err) case <-time.After(ipv4ReviewRetry): } } diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index a135ea5ac..49cb6317a 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -121,11 +121,17 @@ func runCmd(cfg *config.GatewayConfig) error { // Pre-flight RBAC check. checkWatchPermissions(mgr) - // IPv4 VIPs need read access to ServiceVIPBindings; without it they stay - // off for this process rather than stalling the manager's cache. A check - // that cannot be made fails startup instead, so the restart checks again. + // IPv4 VIPs and backend health need read access to ServiceVIPBindings; + // without it they stay off for this process rather than stalling the + // manager's cache. A check that cannot be made fails startup instead, so + // the restart checks again. reviewCtx, cancelReview := context.WithTimeout(ctx, 30*time.Second) ipv4VIPs, err := resolveIPv4VIPs(reviewCtx, mgr.GetClient(), cfg.IPv4VIPs) + if err != nil { + cancelReview() + return err + } + backendHealth, err := resolveBackendHealth(reviewCtx, mgr.GetClient(), cfg.BackendHealth) cancelReview() if err != nil { return err @@ -198,14 +204,15 @@ func runCmd(cfg *config.GatewayConfig) error { // rewrites nothing, so a gateway node has no translation source of its own // to publish. if err := (&controller.NetworkGatewayReconciler{ - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), - Engine: gwEngine, - NodeName: nodeName, - APIReader: mgr.GetAPIReader(), - Disabled: !cfg.DatapathEnabled, - ReturnPath: returnPath, - IPv4VIPs: ipv4VIPs, + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + Engine: gwEngine, + NodeName: nodeName, + APIReader: mgr.GetAPIReader(), + Disabled: !cfg.DatapathEnabled, + ReturnPath: returnPath, + IPv4VIPs: ipv4VIPs, + BackendHealth: backendHealth, // Forwarding follows need: on only once an IPv4 VIP is about to load. EnsureIPv4Forwarding: ipv4.enable, }).SetupWithManager(mgr); err != nil { @@ -307,6 +314,9 @@ func newRootCommand() *cobra.Command { cmd.Flags().Bool("gateway-ipv4-vips", false, "Serve IPv4 VIPs: load them over the rule's IPv6 backends, which translate them, and advertise "+ "each once its backends' ServiceVIPBindings are Bound") + 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().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/docs/agents/ARCHITECTURE-GATEWAY.md b/docs/agents/ARCHITECTURE-GATEWAY.md index a771e66b3..813b2053a 100644 --- a/docs/agents/ARCHITECTURE-GATEWAY.md +++ b/docs/agents/ARCHITECTURE-GATEWAY.md @@ -727,6 +727,7 @@ normal while ingress traffic quietly stopped being intercepted at all. | `GALACTIC_GATEWAY_METRICS_PORT` | No | `8081` | Prometheus metrics port | | `GALACTIC_GATEWAY_GRPC_HEALTH_PORT` | No | `5181` | gRPC health check port | | `GALACTIC_GATEWAY_IPV4_VIPS` | No | `false` | Serves IPv4 VIPs: turns on IPv4 forwarding on every target once its first IPv4 VIP is due to load, loads each rule's IPv4 VIP over its IPv6 backends, which translate it, and advertises it once their bindings are Bound | +| `GALACTIC_GATEWAY_BACKEND_HEALTH` | No | `false` | Leaves a backend reported `Unhealthy` out of a rule with a `healthCheck`, while every `NetworkGateway` in the namespace reports `backendHealthFiltering`; needs the same `servicevipbindings` access as IPv4 VIPs | Both required fields are enforced by `GatewayConfig.Validate` at startup, not deferred to a later, less obvious kernel-datapath error — a @@ -800,13 +801,15 @@ separate pod spec entirely, not part of this manifest. `NetworkGatewayReconciler`/`NetworkServiceReconciler` touch: `networkgateways`/`networkservices` (+ `/status`) read-write, `bgpadvertisements` full CRUD, and read-only `get`/`list`/`watch` on -`servicevipbindings` (the IPv4 readiness gate; read and watched only with -`GALACTIC_GATEWAY_IPV4_VIPS` on. With the switch on, `resolveIPv4VIPs` checks -`list` and `watch` at startup and, if either is denied, logs the missing -access and runs the process with IPv4 VIPs off rather than let the watch -stall the cache and every rule with it; a check that cannot be made is -retried for 30 seconds and then fails startup. Infra's copy of this -ClusterRole must carry the grant before the switch is turned on), +`servicevipbindings` (the IPv4 readiness gate and backend health; read and +watched only with `GALACTIC_GATEWAY_IPV4_VIPS` or +`GALACTIC_GATEWAY_BACKEND_HEALTH` on. With either switch on, +`resolveIPv4VIPs` or `resolveBackendHealth` checks `list` and `watch` at +startup and, if either is denied, logs the missing access and runs the +process with that switch off rather than let the watch stall the cache and +every rule with it; a check that cannot be made is retried for 30 seconds and +then fails startup. Infra's copy of this ClusterRole must carry the grant +before either switch is turned on), `bgprouters` (for `usidresolver.go` — see above), `vpcattachments` in `galactic.datumapis.com` (a rule's backends, selected and watched cluster-wide) and `bgpvrfinstances` @@ -929,8 +932,28 @@ pod on that node is not a supported configuration. Maglev table depends only on the backend set. A per-node cache of the last resolved uSID was rejected: a restarted gateway starts with an empty cache, so nodes would disagree for longer, and traffic would keep - going to a pod that no longer exists. Dropping a backend because it is - unhealthy is #704. + going to a pod that no longer exists. +- **An unhealthy backend leaves the table on a decision every gateway reads, + not one each gateway makes.** For a `NetworkService` with + `spec.healthCheck`, `galactic-router` on each backend's own node probes it + (TCP over the backend's host-side interface, from its link-local address) + and publishes one damped decision in `status.health` of the backend's + `ServiceVIPBinding`s. With `GALACTIC_GATEWAY_BACKEND_HEALTH` on, + `buildDesiredRule` leaves out a backend whose binding reports it + `Unhealthy` for its current attachment UID and the rule's health check port + (`serviceBindings.unhealthy`), keeps every backend of a family when all are + `Unhealthy`, and keeps the VIP advertised. `Unknown` and a missing or + stale decision keep a backend in, so turning checks on never shrinks a pool + before the first probes finish. Health applies only while every + `NetworkGateway` in the namespace reports `status.backendHealthFiltering` + (`passHealthGate`): it is a typed status field, so an older gateway's + status write drops it, and a single gateway that does not filter turns + filtering off everywhere rather than building a different table. Gateways + probing for themselves was rejected: with DSR they never see a backend's + replies, and per-gateway results would give each gateway its own table. The + datapath is unchanged. Removing a backend also moves a few slots between + the remaining backends, and recovery reverses it; see + [backend-health.md](../gateway/backend-health.md#flow-disruption). - **SRv6 encap-source address is derived, not published.** `GALACTIC_GATEWAY_SRV6_ADDRESS` defaults to the node's locator address, derived once at startup from its own `BGPRouter` (#707), rather than a diff --git a/docs/gateway/backend-health.md b/docs/gateway/backend-health.md index 4a21df6e0..ca3d81342 100644 --- a/docs/gateway/backend-health.md +++ b/docs/gateway/backend-health.md @@ -1,11 +1,5 @@ # Backend health checks -> [!NOTE] -> The uSID carve-out, the API, and `galactic-router`'s probing and publishing -> are implemented. The gateway side, everything from -> [Every backend unhealthy](#every-backend-unhealthy) on that a gateway -> does with a decision, is the intended design and not implemented yet. - A `NetworkService` balances flows over the backends its `backendSelector` picks. A backend that resolves and advertises but has stopped serving keeps its slots in the Maglev table, so every flow hashed to it fails. Health checks @@ -212,14 +206,16 @@ is outside this design. ### Mixed versions A gateway that predates health checks would ignore `status.health` and keep -an unhealthy backend that the other gateways drop. To prevent that, each -gateway reports `status.backendHealthFiltering: true` on its own -`NetworkGateway`, and a gateway applies health only while every -`NetworkGateway` in the namespace reports it. An older gateway never writes the -field, and its status update removes it, so a single older gateway, whether -not yet upgraded or rolled back, turns filtering off on all of them. +an unhealthy backend that the other gateways drop. To prevent that, a gateway +with `GALACTIC_GATEWAY_BACKEND_HEALTH` on reports +`status.backendHealthFiltering: true` on its own `NetworkGateway`, and applies +health only while every `NetworkGateway` in the namespace reports it. An older +gateway never writes the field, and its status update removes it, so a single +gateway that does not filter, whether not yet upgraded, rolled back or with the +switch off, turns filtering off on all of them. -The rule's status says when filtering is off for this reason. +The rule's status says when filtering is off for this reason +(`HealthChecksNotApplied`). ## API @@ -262,8 +258,10 @@ problem, as it reports `BackendsUnresolved`. fails. 3. Upgrade `galactic-router` on every node. It probes only services with a health check, so this changes nothing yet. -4. Upgrade `galactic-gateway` on every gateway node. Filtering starts once the - last one reports `backendHealthFiltering`. +4. Upgrade `galactic-gateway` on every gateway node, with + `GALACTIC_GATEWAY_BACKEND_HEALTH=true` and a ClusterRole that grants + `get`, `list` and `watch` on `servicevipbindings`. Filtering starts once + the last one reports `backendHealthFiltering`. 5. Set `spec.healthCheck` on a service, and allow the probes in its traffic policy where policy is enforced. @@ -271,8 +269,9 @@ To turn health checks off for one service, remove `spec.healthCheck`. The routers clear `status.health` and stop probing, and the gateways put every backend back. -To roll back, downgrade the gateways first: the first downgraded gateway turns -filtering off on all of them. Then downgrade the routers, then `galactic-cni`. +To roll back, turn `GALACTIC_GATEWAY_BACKEND_HEALTH` off on any gateway, or +downgrade the gateways, first: the first gateway that stops reporting +`backendHealthFiltering` turns filtering off on all of them. Then downgrade the routers, then `galactic-cni`. A router downgraded first drops `status.health` from its bindings on its next status write, which returns its backends to the table. `galactic-cni` downgraded while gateways still filter makes every probe on its node's diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 24b6b7420..9700ad71b 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -157,6 +157,7 @@ flags, or a combination of both (CLI flags take precedence), with the | XDP attach mode | `GALACTIC_GATEWAY_XDP_ATTACH` | `--gateway-xdp-attach` | `dispatch` | No | | 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 | | Procfs sysctl root | `GALACTIC_GATEWAY_PROC_SYS_PATH` | `--gateway-proc-sys-path` | `/proc/sys` | No | | Metrics port | `GALACTIC_GATEWAY_METRICS_PORT` | `--metrics-port` | `8081` | No | | gRPC health port | `GALACTIC_GATEWAY_GRPC_HEALTH_PORT` | `--grpc-health-port` | `5181` | No | @@ -227,6 +228,17 @@ Turning the switch back off withdraws every IPv4 VIP the node advertises and unloads them, and leaves IPv6 untouched. See [Rolling out and rolling back IPv4 VIPs](#rolling-out-and-rolling-back-ipv4-vips). +`GALACTIC_GATEWAY_BACKEND_HEALTH=true` lets this node take a backend its node +reports `Unhealthy` out of a `NetworkService`'s Maglev table. It applies only +to a service with `spec.healthCheck`, and only while every `NetworkGateway` in +the namespace reports `status.backendHealthFiltering: true`, which each node +sets when the switch is on. A single node without it, not yet upgraded, rolled +back or with the switch off, turns health off on every node, so they keep +building the same table. Health is read from `ServiceVIPBinding`s, so the +switch needs the same `servicevipbindings` access, and the same startup check, +as IPv4 VIPs above: without the access the node runs with the switch off and +logs why. See [Backend health checks](backend-health.md). + `GALACTIC_GATEWAY_DATAPATH_ENABLED=false` keeps the process up and its pod ready, empties the gateway's load-balancing dispatcher slot, and withdraws every one of this node's VIP advertisements. The NetworkGateway's `Ready` @@ -501,10 +513,11 @@ object. ### `NetworkGateway` — one per gateway node -| Field | Required | Type | Description | -| --------------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `spec.targetRef.name` | Yes | `string` | Kubernetes node name this gateway engine executes on. | -| `status.conditions` | — | — | `Ready` condition, reason `EngineHealthy` (converged and fully advertised), `AdvertisementFailed` (converged but couldn't publish one or more rule routes), `DatapathDisabled`, `IPv4ForwardingFailed` (an IPv4 VIP is due to load but the node's IPv4 forwarding could not be turned on, so IPv4 VIPs are left out and IPv6 is served), or `Terminating`. | +| Field | Required | Type | Description | +| ------------------------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `spec.targetRef.name` | Yes | `string` | Kubernetes node name this gateway engine executes on. | +| `status.conditions` | — | — | `Ready` condition, reason `EngineHealthy` (converged and fully advertised), `AdvertisementFailed` (converged but couldn't publish one or more rule routes), `DatapathDisabled`, `IPv4ForwardingFailed` (an IPv4 VIP is due to load but the node's IPv4 forwarding could not be turned on, so IPv4 VIPs are left out and IPv6 is served), or `Terminating`. | +| `status.backendHealthFiltering` | — | `bool` | `true` while this node can take `Unhealthy` backends out of a rule's Maglev table (`GALACTIC_GATEWAY_BACKEND_HEALTH`). Health applies only while every `NetworkGateway` in the namespace reports it. | There is deliberately **no** self-address or primary-node field on this status — DSR has nothing analogous to publish. Create one object per @@ -521,6 +534,7 @@ gateway node, named after that node (see the worked example above). | `spec.backendSelector` | Yes | `metav1.LabelSelector` | Selects the `VPCAttachment`s (`galactic.datumapis.com`, any namespace) that serve the rule. Each contributes its IPv6 interface addresses as backends of both VIPs; its IPv4 addresses are never backends. Must not be empty. | | `spec.backendPort` | tcp, udp | `int32` (1–65535) | Destination port on every selected backend. Required for a protocol with ports, refused for one without. | | `spec.sessionAffinity` | No | `string` enum | `None` (default), `ClientIP` or `ClientIPAndProtocol`: which connections from one client share a backend. See [Session affinity](#session-affinity). | +| `spec.healthCheck` | No | object | Turns on TCP health checks of the backends: `port` (default `backendPort`, required for `udp`), `intervalSeconds` (5), `timeoutSeconds` (2), `unhealthyThreshold` (3), `healthyThreshold` (3). See [Backend health checks](backend-health.md). | | `status.conditions` | — | — | `Accepted` (set `True` once gateway nodes exist in the namespace; not an ownership check, see below); the rule-wide `Programmed`, `Advertised`, `BackendsReady`, `Ready` and, with an IPv4 VIP, `IPv4Served` (see [Reading a rule's status](#reading-a-rules-status)); `/Programmed` and `/Advertised` per gateway node, `/IPv4Served` per gateway node for a rule with an IPv4 VIP, and `/BackendsBound` per node hosting a backend. | Example, the TCP rule from `deploy/containerlab/resources/galactic-gateway/iad/networkservices.yaml`: @@ -672,13 +686,13 @@ Rule-wide conditions say whether a rule serves, without reading from the per-node conditions and writes them only when they change. A per-node condition, or `Accepted`, from an older generation counts as not reported yet. -| Condition | `True` when | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Programmed` | every gateway node that reports on the rule loaded it | -| `Advertised` | every gateway node that loaded the rule published its routes, and `galactic-router` reports each one advertised | -| `BackendsReady` | every backend node bound its backends, and no gateway node left a backend out because its uSID did not resolve | -| `IPv4Served` | every gateway node that loaded the rule serves its IPv4 VIP. Present only on a rule with an IPv4 VIP | -| `Ready` | `Accepted`, `Programmed`, `Advertised` and `BackendsReady` are `True`, and so is `IPv4Served` on a rule whose only VIP is IPv4. Otherwise it carries the reason and message of the first one that isn't | +| Condition | `True` when | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Programmed` | every gateway node that reports on the rule loaded it | +| `Advertised` | every gateway node that loaded the rule published its routes, and `galactic-router` reports each one advertised | +| `BackendsReady` | every backend node bound its backends, and no gateway node left a backend out because its uSID did not resolve or its node reports it `Unhealthy`, kept every backend because all are `Unhealthy`, or could not apply the rule's health check | +| `IPv4Served` | every gateway node that loaded the rule serves its IPv4 VIP. Present only on a rule with an IPv4 VIP | +| `Ready` | `Accepted`, `Programmed`, `Advertised` and `BackendsReady` are `True`, and so is `IPv4Served` on a rule whose only VIP is IPv4. Otherwise it carries the reason and message of the first one that isn't | Only gateway nodes with a `/Programmed` condition count. A node that has not reported, for example one whose datapath is turned off, @@ -694,29 +708,31 @@ A condition that is not `True` takes the reason every failing node reports, and its message names each failing node with its reason. When the nodes disagree, it takes the generic reason in this table instead. -| Reason | On | What to do | -| ---------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Pending` | any | Nothing. No node has reported on the current generation yet. | -| `NoGatewayNodes` | `Programmed` | Platform: no `NetworkGateway` is registered in the namespace. | -| `InvalidRule` | `Programmed`, `BackendsReady` | Fix the spec. The message says what could not be built, such as a port or a backend set that resolves to nothing. | -| `UnservedProtocol` | `Programmed` | Use `tcp` or `udp`. | -| `NoServedVIP` | `Programmed` | Add an IPv6 VIP, or ask for IPv4 VIPs to be turned on. | -| `LoadFailed` | `Programmed` | Platform: the gateway refused the rule, for example over quota. The message carries the error. | -| `NotProgrammed` | `Programmed`, `Advertised` | Gateway nodes failed for different reasons, or none loaded the rule. Read the message. | -| `AdvertisementFailed` | `Advertised` | Platform: writing the route failed. It is retried. | -| `AdvertisementPending` | `Advertised` | Wait. The route is written, but `galactic-router` does not report it advertised yet. If it persists, the route's own `BGPAdvertisement` status says why. | -| `NoRouter` | `Advertised` | Platform: no single `BGPRouter` targets the gateway node. | -| `` | `IPv4Served` | The IPv4 VIP is not served. See the `IPv4Served` table above for the reason. | -| `NotAdvertised` | `Advertised` | Gateway nodes failed for different reasons. Read the message. | -| `NotServed` | `IPv4Served` | Gateway nodes failed for different reasons. Read the message. | -| `BackendsClaimed` | `BackendsReady` | Another rule already serves these backends on the same port. Change `backendPort`, or move the backends off the other rule. | -| `BindingsNotBound` | `BackendsReady` | Wait. If it persists, the backend nodes' `BackendsBound` messages name each binding and why it is not bound. | -| `BackendsUnresolved` | `BackendsReady` | A backend's node has no route yet, usually while its pod is recreated. The rule serves through the rest. | -| `BackendsNotReady` | `BackendsReady` | Nodes reported different backend problems. Read the message. | +| Reason | On | What to do | +| ------------------------ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Pending` | any | Nothing. No node has reported on the current generation yet. | +| `NoGatewayNodes` | `Programmed` | Platform: no `NetworkGateway` is registered in the namespace. | +| `InvalidRule` | `Programmed`, `BackendsReady` | Fix the spec. The message says what could not be built, such as a port or a backend set that resolves to nothing. | +| `UnservedProtocol` | `Programmed` | Use `tcp` or `udp`. | +| `NoServedVIP` | `Programmed` | Add an IPv6 VIP, or ask for IPv4 VIPs to be turned on. | +| `LoadFailed` | `Programmed` | Platform: the gateway refused the rule, for example over quota. The message carries the error. | +| `NotProgrammed` | `Programmed`, `Advertised` | Gateway nodes failed for different reasons, or none loaded the rule. Read the message. | +| `AdvertisementFailed` | `Advertised` | Platform: writing the route failed. It is retried. | +| `AdvertisementPending` | `Advertised` | Wait. The route is written, but `galactic-router` does not report it advertised yet. If it persists, the route's own `BGPAdvertisement` status says why. | +| `NoRouter` | `Advertised` | Platform: no single `BGPRouter` targets the gateway node. | +| `` | `IPv4Served` | The IPv4 VIP is not served. See the `IPv4Served` table above for the reason. | +| `NotAdvertised` | `Advertised` | Gateway nodes failed for different reasons. Read the message. | +| `NotServed` | `IPv4Served` | Gateway nodes failed for different reasons. Read the message. | +| `BackendsClaimed` | `BackendsReady` | Another rule already serves these backends on the same port. Change `backendPort`, or move the backends off the other rule. | +| `BindingsNotBound` | `BackendsReady` | Wait. If it persists, the backend nodes' `BackendsBound` messages name each binding and why it is not bound. | +| `BackendsUnresolved` | `BackendsReady` | A backend's node has no route yet, usually while its pod is recreated. The rule serves through the rest. | +| `BackendsUnhealthy` | `BackendsReady` | Backends failed their health check and are out of the table; the message names them. Fix the backends. The rule serves through the rest. | +| `NoHealthyBackends` | `BackendsReady` | Every backend fails its health check, so all of them are kept. Check the backends, and that traffic policy allows the probe. | +| `HealthChecksNotApplied` | `BackendsReady` | Platform: some gateway node does not apply health, so none does. The message names the nodes. | +| `BackendsNotReady` | `BackendsReady` | Nodes reported different backend problems. Read the message. | `BackendsReady` will also cover a backend cluster that lacks the rule, so -replies have no path back (#706), and backend health (#704), once they are -built. +replies have no path back (#706), once that is built. #### What an IPv4 VIP needs @@ -928,6 +944,26 @@ the gateways already report the error in their `Programmed` conditions. A rule can be `Programmed` on every gateway and still fail to reach a backend; this condition is where that shows. +For a rule with `spec.healthCheck`, the same node also probes each backend and +writes the result to `status.health` of the backend's bindings: + +```yaml +status: + health: + state: Unhealthy # Healthy, Unhealthy or Unknown + reason: ProbeFailed # ProbeSucceeded, ProbeFailed, Pending or ProbeUnavailable + message: dial tcp6 [fe80::a060:bbff:fe37:4f09%G00000006060aH]:0->[fd20:60:ff01:a::100]:80: connect: connection refused + attachmentUID: 6d0f6f9e-0c4e-4b6d-9a4c-1c2f3e4d5a6b + port: 80 + lastTransitionTime: "2026-10-22T18:00:00Z" +``` + +`state` is the damped decision, not the last probe. It is written only when it +changes, and every binding of one backend carries the same one. A gateway +reads it only while `attachmentUID` and `port` match the backend's current +attachment and the rule's health check port. See +[Backend health checks](backend-health.md). + A node's own `galactic-router` is the only one that clears its condition, deletes its bindings and removes the teardown finalizer from bindings targeting it. When a node is decommissioned and its `Node` object deleted, diff --git a/internal/config/gateway.go b/internal/config/gateway.go index 4b112380f..ea9e9f7e9 100644 --- a/internal/config/gateway.go +++ b/internal/config/gateway.go @@ -97,6 +97,16 @@ const ( // watch ServiceVIPBindings runs as if it were off. EnvGatewayIPv4VIPs = "GALACTIC_GATEWAY_IPV4_VIPS" + // EnvGatewayBackendHealth turns on taking unhealthy backends out of the + // Maglev table. Optional, defaulting to false. On, the gateway reads the + // health galactic-router publishes on each ServiceVIPBinding and, for a + // NetworkService with a healthCheck, leaves a backend reported Unhealthy + // out of the rule's table, keeping every backend when all are Unhealthy. + // It applies health only while every NetworkGateway in its namespace + // reports doing so, so every gateway builds the same table. A gateway that + // cannot list and watch ServiceVIPBindings runs as if it were off. + EnvGatewayBackendHealth = "GALACTIC_GATEWAY_BACKEND_HEALTH" + // 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 @@ -146,6 +156,9 @@ type GatewayConfig struct { // IPv4VIPs is EnvGatewayIPv4VIPs. IPv4VIPs bool + // BackendHealth is EnvGatewayBackendHealth. + BackendHealth bool + // ProcSysPath is EnvGatewayProcSysPath. ProcSysPath string } @@ -166,6 +179,7 @@ func NewGatewayConfig() *GatewayConfig { v.SetDefault("xdp_attach", GatewayXDPAttachDispatch) v.SetDefault("datapath_enabled", true) v.SetDefault("ipv4_vips", false) + v.SetDefault("backend_health", false) v.SetDefault("proc_sys_path", DefaultProcSysPath) cfg := &GatewayConfig{ @@ -192,6 +206,7 @@ func (c *GatewayConfig) BindFlags(flags *pflag.FlagSet) { {"gateway-xdp-attach", "xdp_attach"}, {"gateway-datapath-enabled", "datapath_enabled"}, {"gateway-ipv4-vips", "ipv4_vips"}, + {"gateway-backend-health", "backend_health"}, {"gateway-proc-sys-path", "proc_sys_path"}, } for _, b := range bindings { @@ -216,6 +231,7 @@ func (c *GatewayConfig) readFields() { c.XDPAttach = c.v.GetString("xdp_attach") c.DatapathEnabled = c.v.GetBool("datapath_enabled") c.IPv4VIPs = c.v.GetBool("ipv4_vips") + c.BackendHealth = c.v.GetBool("backend_health") c.ProcSysPath = c.v.GetString("proc_sys_path") } diff --git a/internal/config/gateway_test.go b/internal/config/gateway_test.go index d2482bc28..9053aaf5e 100644 --- a/internal/config/gateway_test.go +++ b/internal/config/gateway_test.go @@ -245,3 +245,28 @@ func TestGatewayConfigIPv4VIPs(t *testing.T) { t.Error("IPv4VIPs = false with the flag set to true over the env") } } + +// TestGatewayConfigBackendHealth covers the backend health switch: off by +// default, on from the environment, and on from the flag over the +// environment. +func TestGatewayConfigBackendHealth(t *testing.T) { + if NewGatewayConfig().BackendHealth { + t.Error("BackendHealth = true by default, want false") + } + t.Setenv(EnvGatewayBackendHealth, "true") + if !NewGatewayConfig().BackendHealth { + t.Error("BackendHealth = false with the env set to true") + } + + t.Setenv(EnvGatewayBackendHealth, "false") + cfg := NewGatewayConfig() + flags := pflag.NewFlagSet("test", pflag.ContinueOnError) + flags.Bool("gateway-backend-health", false, "") + if err := flags.Parse([]string{"--gateway-backend-health=true"}); err != nil { + t.Fatal(err) + } + cfg.BindFlags(flags) + if !cfg.BackendHealth { + t.Error("BackendHealth = false with the flag set to true over the env") + } +} diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index 1687d1dd1..dfa81d63a 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -117,6 +117,12 @@ type NetworkGatewayReconciler struct { // applyBGPAdvertisements. Off, no IPv4 VIP is loaded or advertised. IPv4VIPs bool + // BackendHealth leaves a backend its node reports Unhealthy out of a rule + // with a healthCheck (config.EnvGatewayBackendHealth), while every + // NetworkGateway in the namespace reports BackendHealthFiltering, which + // this node then reports too; see passHealthGate. + BackendHealth 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 @@ -379,6 +385,7 @@ func (r *NetworkGatewayReconciler) Reconcile(ctx context.Context, req ctrl.Reque } r.drain.reset() gwCopy := gw.DeepCopy() + gwCopy.Status.BackendHealthFiltering = r.BackendHealth setGatewayCondition(gwCopy, metav1.Condition{ Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionFalse, @@ -398,6 +405,7 @@ func (r *NetworkGatewayReconciler) Reconcile(ctx context.Context, req ctrl.Reque r.syncReturnPath(ctx, gw.Namespace), ) gwCopy := gw.DeepCopy() + gwCopy.Status.BackendHealthFiltering = r.BackendHealth gwCopy.Status.ObservedGeneration = gw.Generation setGatewayCondition(gwCopy, metav1.Condition{ Type: bgpv1alpha1.ConditionTypeReady, @@ -460,6 +468,7 @@ func (r *NetworkGatewayReconciler) Reconcile(ctx context.Context, req ctrl.Reque advErr, ruleStatusErr := r.publishRuleOutcomes(ctx, gw.Namespace, outcomes, status, routerName) gwCopy := gw.DeepCopy() + gwCopy.Status.BackendHealthFiltering = r.BackendHealth gwCopy.Status.ObservedGeneration = gw.Generation ready := readyConditionFor(status, advErr) if fwdErr != nil { @@ -553,6 +562,7 @@ func (r *NetworkGatewayReconciler) reconcileEngine( status, err := r.Engine.Reconcile(ctx, desired) if err != nil { gwCopy := gw.DeepCopy() + gwCopy.Status.BackendHealthFiltering = r.BackendHealth setGatewayCondition(gwCopy, metav1.Condition{ Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionFalse, @@ -622,22 +632,24 @@ func loadsIPv4VIP(desired gateway.EngineState) bool { return false } -// passIPv4Bindings returns namespace's IPv4 bindings for one pass, which IPv4 -// VIPs are balanced over and advertised by, or nil while IPv4VIPs is off, when -// nothing reads them. -func (r *NetworkGatewayReconciler) passIPv4Bindings(ctx context.Context, namespace string) (ipv4Bindings, error) { - if !r.IPv4VIPs { +// passBindings returns namespace's generated bindings for one pass, which IPv4 +// VIPs are balanced over and advertised by and backend health is read from, +// or nil while IPv4VIPs and BackendHealth are both off, when nothing reads +// them. +func (r *NetworkGatewayReconciler) passBindings(ctx context.Context, namespace string) (serviceBindings, error) { + if !r.IPv4VIPs && !r.BackendHealth { return nil, nil } - return listIPv4Bindings(ctx, r.Client, namespace) + return listServiceBindings(ctx, r.Client, namespace) } // gatherRules builds this pass's engine state and rule outcomes from rules, // every NetworkService in namespace, and settles the drain tracker against it. // attachments holds every VPCAttachment in the cluster; each rule selects from -// those in its own VPC (groupAttachmentsByVPC). It reads the namespace's IPv4 -// bindings once, while IPv4VIPs is on (passIPv4Bindings). It returns how long -// until a held rule's drain delay ends, or zero. +// those in its own VPC (groupAttachmentsByVPC). It reads the namespace's +// generated bindings once, while IPv4VIPs or BackendHealth is on +// (passBindings), and whether health applies (passHealthGate). It returns how +// long until a held rule's drain delay ends, or zero. func (r *NetworkGatewayReconciler) gatherRules( ctx context.Context, namespace string, rules []bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, sidIndex *backendSIDIndex, @@ -645,7 +657,11 @@ func (r *NetworkGatewayReconciler) gatherRules( logger := log.FromContext(ctx) desired := gateway.EngineState{Rules: make(map[string]gateway.DesiredRule)} - bindings, err := r.passIPv4Bindings(ctx, namespace) + bindings, err := r.passBindings(ctx, namespace) + if err != nil { + return desired, nil, 0, err + } + health, err := r.passHealthGate(ctx, namespace) if err != nil { return desired, nil, 0, err } @@ -676,7 +692,8 @@ func (r *NetworkGatewayReconciler) gatherRules( // the Programmed condition alone. Once they are gone, the drain // tracker keeps it for ruleDrainDelay so the withdrawal can reach // every peer before the datapath drops it. - o, draining, err := r.drainingOutcome(ctx, rule, byVPC[rule.Spec.VPCRef], sidIndex, owners, bindings) + o, draining, err := r.drainingOutcome(ctx, rule, byVPC[rule.Spec.VPCRef], sidIndex, owners, bindings, + health) if err != nil { return desired, nil, 0, err } @@ -696,8 +713,8 @@ func (r *NetworkGatewayReconciler) gatherRules( continue } - dr, unresolved, ipv4, err := buildDesiredRule(rule, byVPC[rule.Spec.VPCRef], sidIndex, owners, r.IPv4VIPs, - bindings) + dr, unresolved, ipv4, rh, err := buildDesiredRule(rule, byVPC[rule.Spec.VPCRef], sidIndex, owners, r.IPv4VIPs, + bindings, health) if err != nil { logger.Error(err, "build desired rule; skipping", "networkRule", rule.Name) outcomes = append(outcomes, ruleOutcome{rule: rule, buildErr: err, ipv4: ipv4}) @@ -706,8 +723,13 @@ func (r *NetworkGatewayReconciler) gatherRules( if len(unresolved) > 0 { logger.Info("loading rule without unresolved backends", "networkRule", rule.Name, "unresolved", unresolved) } + if len(rh.unhealthy) > 0 { + logger.Info("loading rule without unhealthy backends", "networkRule", rule.Name, "unhealthy", rh.unhealthy) + } desired.Rules[dr.Key] = dr - outcomes = append(outcomes, ruleOutcome{rule: rule, desired: dr, unresolved: unresolved, ipv4: ipv4}) + outcomes = append(outcomes, ruleOutcome{ + rule: rule, desired: dr, unresolved: unresolved, ipv4: ipv4, health: rh, + }) } return desired, outcomes, r.drain.settle(r.clock(), namespace, desired.Rules, live), nil @@ -729,11 +751,10 @@ func (r *NetworkGatewayReconciler) clock() time.Time { // The rule is rebuilt as usual. If it no longer builds, for example because // its backends were deleted with it, the rule as this node last loaded it is // kept instead. If this node never loaded it, there is nothing to keep. -// attachments and bindings are the candidates for rule's backends and their -// IPv4 bindings, as for buildDesiredRule. +// attachments, bindings and health are as for buildDesiredRule. func (r *NetworkGatewayReconciler) drainingOutcome( ctx context.Context, rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, - sidIndex *backendSIDIndex, owners backendOwners, bindings ipv4Bindings, + sidIndex *backendSIDIndex, owners backendOwners, bindings serviceBindings, health healthGate, ) (ruleOutcome, bool, error) { if !controllerutil.ContainsFinalizer(rule, networkRuleFinalizer) { return ruleOutcome{}, false, nil @@ -750,7 +771,7 @@ func (r *NetworkGatewayReconciler) drainingOutcome( return ruleOutcome{}, false, nil } - dr, _, _, err := buildDesiredRule(rule, attachments, sidIndex, owners, r.IPv4VIPs, bindings) + dr, _, _, _, err := buildDesiredRule(rule, attachments, sidIndex, owners, r.IPv4VIPs, bindings, health) if err != nil { var ok bool if dr, ok = r.drain.lastLoaded(rule.Namespace + "/" + rule.Name); !ok { @@ -773,6 +794,9 @@ type ruleOutcome struct { // condition. ipv4 ipv4Family + // health is what backend health did to the rule's backends. + health ruleHealth + // draining marks a deleting rule kept loaded until its route is // withdrawn. Nothing is advertised or written to its status. draining bool @@ -882,12 +906,37 @@ func programmedCondition(node string, o ruleOutcome, loadErrs map[string]string) cond.Message = fmt.Sprintf("not loaded on node %s: %s", node, loadErr) return cond } + loaded := len(o.desired.Backends) + len(o.desired.IPv4Backends) + left := len(o.unresolved) + if !o.health.noneHealthy { + left += len(o.health.unhealthy) + } + var details []string if len(o.unresolved) > 0 { - loaded := len(o.desired.Backends) + len(o.desired.IPv4Backends) + details = append(details, "unresolved: "+cappedList(o.unresolved)) + } + switch { + case o.health.noneHealthy: + details = append(details, "every backend is Unhealthy, so all are kept: "+cappedList(o.health.unhealthy)) + case len(o.health.unhealthy) > 0: + details = append(details, "unhealthy: "+cappedList(o.health.unhealthy)) + case o.health.notApplied != "": + details = append(details, "health checks not applied: "+o.health.notApplied) + } + switch { + case len(o.unresolved) > 0: cond.Reason = reasonBackendsUnresolved - cond.Message = fmt.Sprintf("loaded on node %s with %d of %d backends; unresolved: %s", - node, loaded, loaded+len(o.unresolved), cappedList(o.unresolved)) + case o.health.noneHealthy: + cond.Reason = reasonNoHealthyBackends + case len(o.health.unhealthy) > 0: + cond.Reason = reasonBackendsUnhealthy + case o.health.notApplied != "": + cond.Reason = reasonHealthChecksNotApplied + default: + return cond } + cond.Message = fmt.Sprintf("loaded on node %s with %d of %d backends; %s", + node, loaded, loaded+left, strings.Join(details, "; ")) return cond } @@ -1374,32 +1423,38 @@ func hasIPv4VIP(rule *bgpv1alpha1.NetworkService) bool { // is set. Without it the rule's IPv6 VIPs serve without them, and a rule with // no other VIP fails with errNoServedVIP. With it they load beside the IPv6 // ones, over the IPv6 backends whose ServiceVIPBinding for the IPv4 VIP in -// bindings is Bound -// (ipv4Bindings.unbound); the rest are returned in unresolved, so a flow never -// reaches a backend that cannot answer it. While none is Bound the VIP loads -// over every eligible backend, so that the backend nodes write their -// bindings, and ipv4 is ipv4Unbound, which keeps it unadvertised. A rule with -// more than one IPv4 VIP, like one whose IPv4 VIP has no backend, serves its -// IPv6 VIPs without them. ipv4 says which of these happened to the rule's -// IPv4 VIPs; see ipv4Family. +// bindings is Bound (serviceBindings.unbound); the rest are returned in +// unresolved, so a flow never reaches a backend that cannot answer it. While +// none is Bound the VIP loads over every eligible backend, so that the backend +// nodes write their bindings, and ipv4 is ipv4Unbound, which keeps it +// unadvertised. A rule with more than one IPv4 VIP, like one whose IPv4 VIP has +// no backend, serves its IPv6 VIPs without them. ipv4 says which of these +// happened to the rule's IPv4 VIPs; see ipv4Family. +// +// For a rule with a healthCheck, while health applies, each family then leaves +// out the backends whose binding for that family's VIP reports them Unhealthy +// (serviceBindings.unhealthy), unless that is every one of them: a family +// whose backends are all Unhealthy keeps them all, since an empty table would +// drop every flow. rh says what health did. A family still waiting for its +// first Bound binding is not filtered. func buildDesiredRule( rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, - sidIndex *backendSIDIndex, owners backendOwners, serveIPv4 bool, bindings ipv4Bindings, -) (dr gateway.DesiredRule, unresolved []string, ipv4 ipv4Family, err error) { + sidIndex *backendSIDIndex, owners backendOwners, serveIPv4 bool, bindings serviceBindings, health healthGate, +) (dr gateway.DesiredRule, unresolved []string, ipv4 ipv4Family, rh ruleHealth, err error) { ipv4 = ipv4Off if serveIPv4 { ipv4 = ipv4NotLoaded } port, _, err := rulePorts(rule) if err != nil { - return gateway.DesiredRule{}, nil, ipv4, err + return gateway.DesiredRule{}, nil, ipv4, rh, err } var v6VIPs, v4VIPs []netip.Addr var withheld int for _, v := range rule.Spec.VIPAddresses { addr, err := netip.ParseAddr(v) if err != nil { - return gateway.DesiredRule{}, nil, ipv4, fmt.Errorf("invalid VIP address %q: %w", v, err) + return gateway.DesiredRule{}, nil, ipv4, rh, fmt.Errorf("invalid VIP address %q: %w", v, err) } if !isIPv4VIP(addr) { v6VIPs = append(v6VIPs, addr) @@ -1414,12 +1469,12 @@ func buildDesiredRule( v4VIPs = append(v4VIPs, addr.Unmap()) } if len(v6VIPs) == 0 && len(v4VIPs) == 0 && withheld > 0 { - return gateway.DesiredRule{}, nil, ipv4, errNoServedVIP + return gateway.DesiredRule{}, nil, ipv4, rh, errNoServedVIP } translated, err := ruleTranslatedVIPs(rule) if err != nil { - return gateway.DesiredRule{}, nil, ipv4, err + return gateway.DesiredRule{}, nil, ipv4, rh, err } var firstFamilyError error if len(v4VIPs) > 0 && translated.v4Err != nil { @@ -1444,18 +1499,23 @@ func buildDesiredRule( if len(f.vips) == 0 { continue } + vip := f.vips[0] var unbound func(ruleBackend) string if f.family == familyIPv4 { - vip := f.vips[0] unbound = func(b ruleBackend) string { return bindings.unbound(rule, vip, b) } } - backends, familyUnresolved, noneBound, err := resolveFamilyBackends( - rule, attachments, sidIndex, owners, f.family, unbound) - unresolved = append(unresolved, familyUnresolved...) + var unhealthy func(ruleBackend) bool + if rule.Spec.HealthCheck != nil && health.apply { + unhealthy = func(b ruleBackend) bool { return bindings.unhealthy(rule, vip, b) } + } + fam, err := resolveFamilyBackends(rule, attachments, sidIndex, owners, f.family, unbound, unhealthy) + unresolved = append(unresolved, fam.unresolved...) + rh.unhealthy = append(rh.unhealthy, fam.unhealthy...) + rh.noneHealthy = rh.noneHealthy || fam.noneHealthy if err != nil { var selErr *backendSelectionError if !errors.As(err, &selErr) { - return gateway.DesiredRule{}, nil, ipv4, err + return gateway.DesiredRule{}, nil, ipv4, rh, err } if firstFamilyError == nil { firstFamilyError = err @@ -1466,17 +1526,21 @@ func buildDesiredRule( continue } vips = append(vips, f.vips...) - *f.backends = backends + *f.backends = fam.backends if f.family == familyIPv4 { ipv4 = ipv4Loaded - if noneBound { + if fam.noneBound { ipv4 = ipv4Unbound } } } if len(vips) == 0 { - return gateway.DesiredRule{}, nil, ipv4, firstFamilyError + return gateway.DesiredRule{}, nil, ipv4, rh, firstFamilyError } + if rule.Spec.HealthCheck != nil && !health.apply { + rh.notApplied = health.why + } + sort.Strings(rh.unhealthy) return gateway.DesiredRule{ Key: rule.Namespace + "/" + rule.Name, @@ -1487,7 +1551,7 @@ func buildDesiredRule( Affinity: string(rule.Spec.SessionAffinity), Backends: v6Backends, IPv4Backends: v4Backends, - }, unresolved, ipv4, nil + }, unresolved, ipv4, rh, nil } // backendSelectionError is resolveFamilyBackends' error for a family none of @@ -1498,6 +1562,27 @@ type backendSelectionError struct{ err error } func (e *backendSelectionError) Error() string { return e.err.Error() } func (e *backendSelectionError) Unwrap() error { return e.err } +// familyBackends is what resolveFamilyBackends returns for one VIP family. +type familyBackends struct { + // backends are the family's Maglev input. + backends []gateway.DesiredBackend + + // unresolved lists the selected attachments and backends left out, as + // status messages. + unresolved []string + + // noneBound is set when no resolved backend's binding is Bound yet, so + // backends holds every resolved backend. + noneBound bool + + // unhealthy lists the backends left out as Unhealthy, as "address:port". + unhealthy []string + + // noneHealthy is set when every candidate backend is Unhealthy, so + // backends keeps them all. + noneHealthy bool +} + // resolveFamilyBackends returns rule's backends of family, each resolved to its // node's uSID with its slot, and the selected attachments and backends that are // not part of it, as status messages. An invalid selector is returned as is. @@ -1507,21 +1592,32 @@ func (e *backendSelectionError) Unwrap() error { return e.err } // Bound, or "" when it is. Only Bound backends are returned then, and the rest // join unresolved; while none is Bound, every resolved backend is returned and // noneBound is set. +// +// A non-nil unhealthy reports whether a backend is Unhealthy. Those backends +// are left out and listed in unhealthy, unless every remaining backend is +// Unhealthy, when all are kept and noneHealthy is set. It does not apply while +// noneBound is set. func resolveFamilyBackends( rule *bgpv1alpha1.NetworkService, attachments []*cloudv1alpha1.VPCAttachment, sidIndex *backendSIDIndex, owners backendOwners, family addrFamily, unbound func(ruleBackend) string, -) (backends []gateway.DesiredBackend, unresolved []string, noneBound bool, err error) { + unhealthy func(ruleBackend) bool, +) (familyBackends, error) { sel, err := selectRuleBackends(rule, attachments, owners, family) if err != nil { - return nil, nil, false, err + return familyBackends{}, err } - unresolved = sel.pending + var out familyBackends + out.unresolved = sel.pending for _, c := range sel.claimed { - unresolved = append(unresolved, c.String()) + out.unresolved = append(out.unresolved, c.String()) } - backends = make([]gateway.DesiredBackend, 0, len(sel.backends)) - bound := make([]gateway.DesiredBackend, 0, len(sel.backends)) + type resolved struct { + rb ruleBackend + db gateway.DesiredBackend + } + all := make([]resolved, 0, len(sel.backends)) + bound := make([]resolved, 0, len(sel.backends)) var held []string var firstResolveErr error for _, b := range sel.backends { @@ -1533,11 +1629,11 @@ func resolveFamilyBackends( if firstResolveErr == nil { firstResolveErr = fmt.Errorf("resolve backend %s: %w", b, err) } - unresolved = append(unresolved, b.String()) + out.unresolved = append(out.unresolved, b.String()) continue } - backend := gateway.DesiredBackend{Address: b.addr, Port: b.port, USID: usid} - backends = append(backends, backend) + r := resolved{rb: b, db: gateway.DesiredBackend{Address: b.addr, Port: b.port, USID: usid}} + all = append(all, r) if unbound == nil { continue } @@ -1545,29 +1641,51 @@ func resolveFamilyBackends( held = append(held, b.String()+": "+why) continue } - bound = append(bound, backend) + bound = append(bound, r) } - if len(backends) > 0 { + if len(all) > 0 { + candidates := all switch { case unbound == nil: - return backends, unresolved, false, nil case len(bound) > 0: - return bound, append(unresolved, held...), false, nil + candidates = bound + out.unresolved = append(out.unresolved, held...) default: - return backends, unresolved, true, nil + out.noneBound = true + unhealthy = nil + } + if unhealthy != nil { + healthy := make([]resolved, 0, len(candidates)) + for _, c := range candidates { + if unhealthy(c.rb) { + out.unhealthy = append(out.unhealthy, c.rb.String()) + continue + } + healthy = append(healthy, c) + } + if len(healthy) == 0 { + out.noneHealthy = true + } else { + candidates = healthy + } + } + out.backends = make([]gateway.DesiredBackend, 0, len(candidates)) + for _, c := range candidates { + out.backends = append(out.backends, c.db) } + return out, nil } switch { case firstResolveErr != nil: - err = fmt.Errorf("none of %d backends resolves: %w", len(unresolved), firstResolveErr) + err = fmt.Errorf("none of %d backends resolves: %w", len(out.unresolved), firstResolveErr) case len(sel.claimed) > 0 && len(sel.pending) == 0: - err = fmt.Errorf("every selected backend is served by an older rule: %s", cappedList(unresolved)) - case len(unresolved) > 0: - err = fmt.Errorf("no selected attachment is a backend yet: %s", cappedList(unresolved)) + err = fmt.Errorf("every selected backend is served by an older rule: %s", cappedList(out.unresolved)) + case len(out.unresolved) > 0: + err = fmt.Errorf("no selected attachment is a backend yet: %s", cappedList(out.unresolved)) default: err = fmt.Errorf("backendSelector matches no VPCAttachment in VPC %s", rule.Spec.VPCRef) } - return nil, unresolved, false, &backendSelectionError{err: err} + return familyBackends{unresolved: out.unresolved}, &backendSelectionError{err: err} } // routerNameForNode returns the name of this node's Galactic-owned @@ -1858,17 +1976,31 @@ func (r *NetworkGatewayReconciler) SetupWithManager(mgr ctrl.Manager) error { }), builder.WithPredicates(vpcAttachmentBackendChanged()), ) - if r.IPv4VIPs { + if r.IPv4VIPs || r.BackendHealth { // A rule's IPv4 VIP is balanced over, and advertised for, only the - // backends whose bindings are Bound, so a binding appearing, going, - // changing or becoming Bound or not opens or closes the gate. Bindings - // live in the gateways' namespace. Without IPv4VIPs nothing reads them, - // and the gateway needs no access to them. + // backends whose bindings are Bound, and a rule with a healthCheck + // over only the backends no binding reports Unhealthy, so a binding + // appearing, going, changing, becoming Bound or not, or changing its + // health changes some rule. Bindings live in the gateways' namespace. + // With neither IPv4VIPs nor BackendHealth nothing reads them, and the + // gateway needs no access to them. b = b.Watches(&bgpv1alpha1.ServiceVIPBinding{}, handler.EnqueueRequestsFromMapFunc( func(ctx context.Context, obj client.Object) []ctrlreconcile.Request { return broadcastToGatewayRequests(ctx, r.Client, obj.GetNamespace(), "ServiceVIPBinding", obj.GetName()) }), - builder.WithPredicates(ipv4BindingReadinessChanged()), + builder.WithPredicates(bindingReadinessChanged(r.BackendHealth)), + ) + } + if r.BackendHealth { + // Health applies only while every NetworkGateway in the namespace + // reports BackendHealthFiltering, so a gateway appearing, going, or + // changing that report re-queues every gateway in the namespace, not + // only its own node's. + b = b.Watches(&bgpv1alpha1.NetworkGateway{}, handler.EnqueueRequestsFromMapFunc( + func(ctx context.Context, obj client.Object) []ctrlreconcile.Request { + return broadcastToGatewayRequests(ctx, r.Client, obj.GetNamespace(), "NetworkGateway", obj.GetName()) + }), + builder.WithPredicates(gatewayHealthFilteringChanged()), ) } return b.Named("networkgateway").Complete(r) diff --git a/internal/controller/networkgateway_controller_test.go b/internal/controller/networkgateway_controller_test.go index 988b58716..226c665c6 100644 --- a/internal/controller/networkgateway_controller_test.go +++ b/internal/controller/networkgateway_controller_test.go @@ -589,7 +589,7 @@ func TestBuildDesiredRule_BackendResolution(t *testing.T) { } rule := newTestRule(testRuleName, "vpc-1", testVIP) - dr, unresolved, _, err := buildDesiredRule(rule, tt.attachments, idx, nil, false, nil) + dr, unresolved, _, _, err := buildDesiredRule(rule, tt.attachments, idx, nil, false, nil, healthGate{}) if tt.wantErr { if err == nil { t.Fatalf("buildDesiredRule: err = nil, want an error; got %+v", dr) @@ -625,12 +625,12 @@ func TestBuildDesiredRule_RefusesSecondIPv6VIP(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1")} rule := newTestRule(testRuleName, "vpc-1", "2001:db8:100::32", "2001:db8:100::33", testVIP4) - if _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil); err == nil { + if _, _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil, healthGate{}); err == nil { t.Fatal("buildDesiredRule: err = nil, want an error for two IPv6 VIPs") } rule.Spec.VIPAddresses = []string{"2001:db8:100::32", testVIP4} - if _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil); err != nil { + if _, _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil, healthGate{}); err != nil { t.Fatalf("buildDesiredRule with one IPv6 and one IPv4 VIP: %v", err) } } @@ -700,7 +700,8 @@ func TestBuildDesiredRule_SameNodeBackendsGetTheirOwnSlot(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1", testBackendAddr, "fd00:10::2")} - dr, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP), attachments, idx, nil, false, nil) + dr, _, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP), attachments, idx, nil, false, nil, + healthGate{}) if err != nil { t.Fatalf("buildDesiredRule: %v", err) } @@ -2005,7 +2006,7 @@ func TestBuildDesiredRule_CarriesSessionAffinity(t *testing.T) { } { rule := newTestRule(testRuleName, "vpc-1", testVIP) rule.Spec.SessionAffinity = affinity - dr, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil) + dr, _, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil, healthGate{}) if err != nil { t.Fatalf("affinity %q: %v", affinity, err) } diff --git a/internal/controller/networkgateway_health.go b/internal/controller/networkgateway_health.go new file mode 100644 index 000000000..509502ba6 --- /dev/null +++ b/internal/controller/networkgateway_health.go @@ -0,0 +1,113 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "fmt" + "net/netip" + "sort" + + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/predicate" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" +) + +// Per-node Programmed reasons for a loaded rule with a healthCheck. Each is +// reported with status True: the rule serves. +const ( + // reasonBackendsUnhealthy: the rule is loaded without the backends their + // nodes report Unhealthy. + reasonBackendsUnhealthy = "BackendsUnhealthy" + + // reasonNoHealthyBackends: every backend of a VIP family is reported + // Unhealthy, so all of them are kept. + reasonNoHealthyBackends = "NoHealthyBackends" + + // reasonHealthChecksNotApplied: some gateway node in the namespace does + // not apply backend health, so none of them does. + reasonHealthChecksNotApplied = "HealthChecksNotApplied" +) + +// healthGate is whether one pass applies backend health, and why not. +// +// Health changes a rule's Maglev table, so a gateway applies it only while +// every NetworkGateway in its namespace reports BackendHealthFiltering: every +// gateway then reads the same decisions, and a gateway that does not apply +// health, an older one included, turns it off for all of them instead of +// building a different table. +type healthGate struct { + // apply is set when this pass applies health. + apply bool + + // why says why health is not applied, for a rule with a healthCheck. + why string +} + +// passHealthGate returns this pass's healthGate for namespace. +func (r *NetworkGatewayReconciler) passHealthGate(ctx context.Context, namespace string) (healthGate, error) { + if !r.BackendHealth { + return healthGate{why: "backend health is off on gateway node " + r.NodeName}, nil + } + list := &bgpv1alpha1.NetworkGatewayList{} + if err := r.List(ctx, list, client.InNamespace(namespace)); err != nil { + return healthGate{}, fmt.Errorf("list NetworkGateways in %s: %w", namespace, err) + } + var missing []string + for i := range list.Items { + if !list.Items[i].Status.BackendHealthFiltering { + missing = append(missing, list.Items[i].Spec.TargetRef.Name) + } + } + if len(missing) > 0 { + sort.Strings(missing) + return healthGate{why: "backend health is not applied by gateway nodes " + cappedList(missing)}, nil + } + return healthGate{apply: true}, nil +} + +// unhealthy reports whether b's node reports b Unhealthy for rule's VIP vip: +// the binding b's node writes for rule today (generatedBinding), not being +// deleted, carries a status.health of Unhealthy for b's attachment and rule's +// health check port. Any other decision, or none, keeps b. +func (idx serviceBindings) unhealthy(rule *bgpv1alpha1.NetworkService, vip netip.Addr, b ruleBackend) bool { + want := generatedBinding(rule, b.node, vip, b) + got, ok := idx[want.Name] + if !ok || !got.DeletionTimestamp.IsZero() || got.Labels[networkRuleLabel] != rule.Name || got.Spec != want.Spec { + return false + } + h := got.Status.Health + return h != nil && h.State == bgpv1alpha1.BackendHealthUnhealthy && + h.AttachmentUID == b.uid && h.Port == ruleHealthCheckPort(rule) +} + +// ruleHealth is what health did to one rule's backends in a pass. +type ruleHealth struct { + // unhealthy lists the backends left out, or kept with noneHealthy, as + // "address:port", sorted, once per VIP family. + unhealthy []string + + // noneHealthy is set when every backend of some VIP family was reported + // Unhealthy, so all of them were kept. + noneHealthy bool + + // notApplied says why the rule's healthCheck was not applied, or "". + notApplied string +} + +// gatewayHealthFilteringChanged passes NetworkGateway events that can change +// whether every gateway in a namespace applies health: a create or delete, and +// an update of BackendHealthFiltering. +func gatewayHealthFilteringChanged() predicate.Predicate { + return predicate.Funcs{ + UpdateFunc: func(e event.UpdateEvent) bool { + oldGW, okOld := e.ObjectOld.(*bgpv1alpha1.NetworkGateway) + newGW, okNew := e.ObjectNew.(*bgpv1alpha1.NetworkGateway) + return !okOld || !okNew || oldGW.Status.BackendHealthFiltering != newGW.Status.BackendHealthFiltering + }, + } +} diff --git a/internal/controller/networkgateway_health_test.go b/internal/controller/networkgateway_health_test.go new file mode 100644 index 000000000..7024c0bc2 --- /dev/null +++ b/internal/controller/networkgateway_health_test.go @@ -0,0 +1,425 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "net/netip" + "slices" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/gateway" +) + +const ( + // testHealthyAddr and testSickAddr are the two backends of + // newHealthAttachment, both resolving through newBackendFixtures. + testHealthyAddr = testBackendAddr + testSickAddr = "fd00:10::2" + + testGatewayHealthUID = types.UID("health-attachment-uid") +) + +// newHealthRule returns an accepted rule on testVIP with a healthCheck that +// probes backendPort. +func newHealthRule() *bgpv1alpha1.NetworkService { + rule := newTestRule(testRuleName, "vpc-1", testVIP) + rule.Spec.HealthCheck = &bgpv1alpha1.NetworkServiceHealthCheck{ + IntervalSeconds: 5, TimeoutSeconds: 2, UnhealthyThreshold: 3, HealthyThreshold: 3, + } + acceptRule(rule) + return rule +} + +// newHealthAttachment returns one attachment holding testHealthyAddr and +// testSickAddr, so the rule has two backends. +func newHealthAttachment() *cloudv1alpha1.VPCAttachment { + a := newBackendAttachment("vpc-1", testHealthyAddr, testSickAddr) + a.UID = testGatewayHealthUID + return a +} + +// healthBinding returns the binding testComputeNodeName writes for rule's +// IPv6 VIP and the backend at addr, with health h. +func healthBinding( + rule *bgpv1alpha1.NetworkService, addr string, h *bgpv1alpha1.ServiceVIPBindingHealth, +) *bgpv1alpha1.ServiceVIPBinding { + b := generatedBinding(rule, testComputeNodeName, netip.MustParseAddr(testVIP), ruleBackend{ + node: testComputeNodeName, + addr: netip.MustParseAddr(addr), + port: testBackendPort, + egressKind: bgpv1alpha1.ServiceVIPBindingEgressKindVeth, + }) + b.Status.Health = h + return b +} + +// decision returns a published decision of state for testGatewayHealthUID on +// backendPort. +func decision(state bgpv1alpha1.BackendHealthState) *bgpv1alpha1.ServiceVIPBindingHealth { + return &bgpv1alpha1.ServiceVIPBindingHealth{ + State: state, Reason: "ProbeFailed", AttachmentUID: testGatewayHealthUID, Port: testBackendPort, + } +} + +func backendAddrs(backends []gateway.DesiredBackend) []string { + out := make([]string, 0, len(backends)) + for _, b := range backends { + out = append(out, b.Address.String()) + } + slices.Sort(out) + return out +} + +// TestBuildDesiredRule_Health covers which backends a rule with a healthCheck +// is balanced over: only an Unhealthy decision about the backend's current +// attachment and port takes it out, every backend stays when all are +// Unhealthy, and nothing is filtered while health does not apply. +func TestBuildDesiredRule_Health(t *testing.T) { + backendRouter, backendAdv, backendVRF := newBackendFixtures("vpc-1") + idx := &backendSIDIndex{ + routers: map[string]*bgpv1alpha1.BGPRouter{backendRouter.Name: backendRouter}, + advs: []*bgpv1alpha1.BGPAdvertisement{backendAdv}, + vrfInstances: map[string]*bgpv1alpha1.BGPVRFInstance{backendVRF.Name: backendVRF}, + } + applied := healthGate{apply: true} + sickAddrPort := "[" + testSickAddr + "]:8443" + + otherUID := decision(bgpv1alpha1.BackendHealthUnhealthy) + otherUID.AttachmentUID = "an-earlier-attachment" + otherPort := decision(bgpv1alpha1.BackendHealthUnhealthy) + otherPort.Port = 9000 + + tests := []struct { + name string + noHealthCheck bool + gate healthGate + healthy, sick *bgpv1alpha1.ServiceVIPBindingHealth + staleSick bool + wantBackends []string + want ruleHealth + }{ + { + name: "an Unhealthy backend is left out", + gate: applied, + sick: decision(bgpv1alpha1.BackendHealthUnhealthy), + wantBackends: []string{testHealthyAddr}, + want: ruleHealth{unhealthy: []string{sickAddrPort}}, + }, + { + name: "every backend Unhealthy keeps them all", + gate: applied, + healthy: decision(bgpv1alpha1.BackendHealthUnhealthy), + sick: decision(bgpv1alpha1.BackendHealthUnhealthy), + wantBackends: []string{testHealthyAddr, testSickAddr}, + want: ruleHealth{ + unhealthy: []string{"[" + testHealthyAddr + "]:8443", sickAddrPort}, noneHealthy: true, + }, + }, + { + name: "Unknown stays in", + gate: applied, + sick: decision(bgpv1alpha1.BackendHealthUnknown), + wantBackends: []string{testHealthyAddr, testSickAddr}, + }, + { + name: "a decision about another attachment is ignored", + gate: applied, + sick: otherUID, + wantBackends: []string{testHealthyAddr, testSickAddr}, + }, + { + name: "a decision about another port is ignored", + gate: applied, + sick: otherPort, + wantBackends: []string{testHealthyAddr, testSickAddr}, + }, + { + name: "a binding not updated to the rule is ignored", + gate: applied, + sick: decision(bgpv1alpha1.BackendHealthUnhealthy), + staleSick: true, + wantBackends: []string{testHealthyAddr, testSickAddr}, + }, + { + name: "nothing is filtered while health does not apply", + gate: healthGate{why: "backend health is not applied by gateway nodes gw-b"}, + sick: decision(bgpv1alpha1.BackendHealthUnhealthy), + wantBackends: []string{testHealthyAddr, testSickAddr}, + want: ruleHealth{notApplied: "backend health is not applied by gateway nodes gw-b"}, + }, + { + name: "a rule without a healthCheck ignores health", + noHealthCheck: true, + gate: applied, + sick: decision(bgpv1alpha1.BackendHealthUnhealthy), + wantBackends: []string{testHealthyAddr, testSickAddr}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rule := newHealthRule() + if tt.noHealthCheck { + rule.Spec.HealthCheck = nil + } + sick := healthBinding(rule, testSickAddr, tt.sick) + if tt.staleSick { + sick.Spec.VPCRef = "another-vpc" + } + bindings := serviceBindings{} + for _, b := range []*bgpv1alpha1.ServiceVIPBinding{healthBinding(rule, testHealthyAddr, tt.healthy), sick} { + bindings[b.Name] = b + } + + dr, _, _, rh, err := buildDesiredRule(rule, []*cloudv1alpha1.VPCAttachment{newHealthAttachment()}, idx, + nil, false, bindings, tt.gate) + if err != nil { + t.Fatalf("buildDesiredRule: %v", err) + } + if got := backendAddrs(dr.Backends); !slices.Equal(got, tt.wantBackends) { + t.Errorf("backends = %v, want %v", got, tt.wantBackends) + } + if !slices.Equal(rh.unhealthy, tt.want.unhealthy) || rh.noneHealthy != tt.want.noneHealthy || + rh.notApplied != tt.want.notApplied { + t.Errorf("health = %+v, want %+v", rh, tt.want) + } + }) + } +} + +// TestBuildDesiredRule_HealthIsDeterministic: two gateways reading the same +// objects build the same backend list, whatever order the bindings were +// listed in. +func TestBuildDesiredRule_HealthIsDeterministic(t *testing.T) { + backendRouter, backendAdv, backendVRF := newBackendFixtures("vpc-1") + idx := &backendSIDIndex{ + routers: map[string]*bgpv1alpha1.BGPRouter{backendRouter.Name: backendRouter}, + advs: []*bgpv1alpha1.BGPAdvertisement{backendAdv}, + vrfInstances: map[string]*bgpv1alpha1.BGPVRFInstance{backendVRF.Name: backendVRF}, + } + rule := newHealthRule() + healthy := healthBinding(rule, testHealthyAddr, decision(bgpv1alpha1.BackendHealthHealthy)) + sick := healthBinding(rule, testSickAddr, decision(bgpv1alpha1.BackendHealthUnhealthy)) + attachments := []*cloudv1alpha1.VPCAttachment{newHealthAttachment()} + + a, _, _, _, errA := buildDesiredRule(rule, attachments, idx, nil, false, + serviceBindings{healthy.Name: healthy, sick.Name: sick}, healthGate{apply: true}) + b, _, _, _, errB := buildDesiredRule(rule, attachments, idx, nil, false, + serviceBindings{sick.Name: sick, healthy.Name: healthy}, healthGate{apply: true}) + if errA != nil || errB != nil { + t.Fatalf("buildDesiredRule: %v, %v", errA, errB) + } + if !slices.Equal(a.Backends, b.Backends) { + t.Errorf("backends differ: %v vs %v", a.Backends, b.Backends) + } +} + +// reconcileHealthGateway builds a testNodeGWA reconciler with BackendHealth +// on, over objs plus a second gateway testNodeGWB reporting gwBFilters. +func reconcileHealthGateway( + t *testing.T, gwBFilters bool, objs ...client.Object, +) (client.Client, *fakeGatewayEngine, *NetworkGatewayReconciler) { + t.Helper() + scheme := newRuleTestScheme(t) + gwB := newTestGateway(testNodeGWB) + gwB.Status.BackendHealthFiltering = gwBFilters + c := newIndexedClientBuilder(scheme). + WithStatusSubresource(&bgpv1alpha1.NetworkGateway{}, &bgpv1alpha1.NetworkService{}, + &bgpv1alpha1.ServiceVIPBinding{}). + WithObjects(append(objs, newTestGateway(testNodeGWA), gwB)...). + Build() + engine := newFakeGatewayEngine() + r := newGatewayReconciler(c, scheme, engine, testNodeGWA) + r.BackendHealth = true + return c, engine, r +} + +func healthFixtureObjects() []client.Object { + backendRouter, backendAdv, backendVRF := newBackendFixtures("vpc-1") + rule := newHealthRule() + return []client.Object{ + newTestRouter(), backendRouter, backendAdv, backendVRF, newHealthAttachment(), rule, + healthBinding(rule, testHealthyAddr, decision(bgpv1alpha1.BackendHealthHealthy)), + healthBinding(rule, testSickAddr, decision(bgpv1alpha1.BackendHealthUnhealthy)), + } +} + +func setGatewayHealthFiltering(t *testing.T, c client.Client, node string, on bool) { + t.Helper() + gw := &bgpv1alpha1.NetworkGateway{} + if err := c.Get(context.Background(), testRuleKey(node), gw); err != nil { + t.Fatalf("get NetworkGateway %s: %v", node, err) + } + gw.Status.BackendHealthFiltering = on + if err := c.Status().Update(context.Background(), gw); err != nil { + t.Fatalf("update NetworkGateway %s status: %v", node, err) + } +} + +func engineBackends(engine *fakeGatewayEngine) []string { + engine.mu.Lock() + defer engine.mu.Unlock() + return backendAddrs(engine.lastDesired.Rules[testNamespace+"/"+testRuleName].Backends) +} + +func programmedFor(t *testing.T, c client.Client) *metav1.Condition { + t.Helper() + cond := meta.FindStatusCondition(ruleConditions(t, c, testRuleName), programmedConditionType(testNodeGWA)) + if cond == nil { + t.Fatal("no Programmed condition for gw-a") + } + return cond +} + +// TestGatewayHealth_AppliesOnlyWhenEveryGatewayFilters: a gateway applies +// health only while every NetworkGateway in the namespace reports it, reports +// that it does on its own NetworkGateway, and stops when a gateway stops +// reporting it, as an older gateway's status write does. +func TestGatewayHealth_AppliesOnlyWhenEveryGatewayFilters(t *testing.T) { + c, engine, r := reconcileHealthGateway(t, false, healthFixtureObjects()...) + + runGatewayPass(t, r) + gw := &bgpv1alpha1.NetworkGateway{} + if err := c.Get(context.Background(), testRuleKey(testNodeGWA), gw); err != nil { + t.Fatal(err) + } + if !gw.Status.BackendHealthFiltering { + t.Error("gw-a does not report BackendHealthFiltering") + } + if got := engineBackends(engine); !slices.Equal(got, []string{testHealthyAddr, testSickAddr}) { + t.Errorf("backends with gw-b not filtering = %v, want both", got) + } + if cond := programmedFor(t, c); cond.Status != metav1.ConditionTrue || + cond.Reason != reasonHealthChecksNotApplied || !strings.Contains(cond.Message, testNodeGWB) { + t.Errorf("Programmed = %s/%s %q, want True/%s naming %s", + cond.Status, cond.Reason, cond.Message, reasonHealthChecksNotApplied, testNodeGWB) + } + + setGatewayHealthFiltering(t, c, testNodeGWB, true) + runGatewayPass(t, r) + if got := engineBackends(engine); !slices.Equal(got, []string{testHealthyAddr}) { + t.Errorf("backends with every gateway filtering = %v, want only %s", got, testHealthyAddr) + } + if cond := programmedFor(t, c); cond.Status != metav1.ConditionTrue || cond.Reason != reasonBackendsUnhealthy || + !strings.Contains(cond.Message, testSickAddr) { + t.Errorf("Programmed = %s/%s %q, want True/%s naming %s", + cond.Status, cond.Reason, cond.Message, reasonBackendsUnhealthy, testSickAddr) + } + + setGatewayHealthFiltering(t, c, testNodeGWB, false) + runGatewayPass(t, r) + if got := engineBackends(engine); !slices.Equal(got, []string{testHealthyAddr, testSickAddr}) { + t.Errorf("backends after gw-b stopped filtering = %v, want both", got) + } +} + +// TestGatewayHealth_OffReportsNotApplied: with BackendHealth off, the gateway +// reports no filtering and leaves every backend in a rule with a healthCheck. +func TestGatewayHealth_OffReportsNotApplied(t *testing.T) { + c, engine, r := reconcileHealthGateway(t, true, healthFixtureObjects()...) + r.BackendHealth = false + + runGatewayPass(t, r) + + gw := &bgpv1alpha1.NetworkGateway{} + if err := c.Get(context.Background(), testRuleKey(testNodeGWA), gw); err != nil { + t.Fatal(err) + } + if gw.Status.BackendHealthFiltering { + t.Error("gw-a reports BackendHealthFiltering with BackendHealth off") + } + if got := engineBackends(engine); !slices.Equal(got, []string{testHealthyAddr, testSickAddr}) { + t.Errorf("backends = %v, want both", got) + } + if cond := programmedFor(t, c); cond.Reason != reasonHealthChecksNotApplied { + t.Errorf("Programmed reason = %s, want %s", cond.Reason, reasonHealthChecksNotApplied) + } +} + +// TestGatewayHealth_AllUnhealthyKeepsServing: every backend Unhealthy keeps all +// of them and keeps the rule advertised. +func TestGatewayHealth_AllUnhealthyKeepsServing(t *testing.T) { + objs := healthFixtureObjects() + for _, o := range objs { + if b, ok := o.(*bgpv1alpha1.ServiceVIPBinding); ok { + b.Status.Health = decision(bgpv1alpha1.BackendHealthUnhealthy) + } + } + c, engine, r := reconcileHealthGateway(t, true, objs...) + + runGatewayPass(t, r) + // gw-a reports filtering after its first pass; the second applies it. + runGatewayPass(t, r) + + if got := engineBackends(engine); !slices.Equal(got, []string{testHealthyAddr, testSickAddr}) { + t.Errorf("backends = %v, want both kept", got) + } + if cond := programmedFor(t, c); cond.Status != metav1.ConditionTrue || cond.Reason != reasonNoHealthyBackends { + t.Errorf("Programmed = %s/%s, want True/%s", cond.Status, cond.Reason, reasonNoHealthyBackends) + } + if _, ok := advertisedPrefixes(t, c, testRuleAdv); !ok { + t.Error("the rule's VIP is not advertised while every backend is Unhealthy") + } +} + +// TestBindingReadinessChanged_Health: with health on, bindings of IPv6 VIPs +// pass and a change of status.health does, while an unrelated status write +// does not. +func TestBindingReadinessChanged_Health(t *testing.T) { + rule := newHealthRule() + v6 := healthBinding(rule, testSickAddr, nil) + sick := v6.DeepCopy() + sick.Status.Health = decision(bgpv1alpha1.BackendHealthUnhealthy) + reworded := sick.DeepCopy() + reworded.Status.Conditions = []metav1.Condition{{Type: "Other", Status: metav1.ConditionTrue}} + + on, off := bindingReadinessChanged(true), bindingReadinessChanged(false) + for _, tc := range []struct { + name string + got bool + want bool + }{ + {"CreateIPv6On", on.Create(event.CreateEvent{Object: v6}), true}, + {"CreateIPv6Off", off.Create(event.CreateEvent{Object: v6}), false}, + {"HealthChanged", on.Update(event.UpdateEvent{ObjectOld: v6, ObjectNew: sick}), true}, + {"UnrelatedStatus", on.Update(event.UpdateEvent{ObjectOld: sick, ObjectNew: reworded}), false}, + } { + if tc.got != tc.want { + t.Errorf("%s: passed = %v, want %v", tc.name, tc.got, tc.want) + } + } +} + +// TestGatewayHealthFilteringChanged: only a change in BackendHealthFiltering, +// a create or a delete re-queues the namespace's gateways. +func TestGatewayHealthFilteringChanged(t *testing.T) { + p := gatewayHealthFilteringChanged() + off := newTestGateway(testNodeGWB) + on := off.DeepCopy() + on.Status.BackendHealthFiltering = true + conditioned := on.DeepCopy() + conditioned.Status.Conditions = []metav1.Condition{ + {Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionTrue}, + } + + if !p.Update(event.UpdateEvent{ObjectOld: off, ObjectNew: on}) { + t.Error("BackendHealthFiltering turning on did not pass") + } + if p.Update(event.UpdateEvent{ObjectOld: on, ObjectNew: conditioned}) { + t.Error("a condition-only update passed") + } + if !p.Create(event.CreateEvent{Object: off}) || !p.Delete(event.DeleteEvent{Object: off}) { + t.Error("a create or delete did not pass") + } +} diff --git a/internal/controller/networkgateway_ipv4_test.go b/internal/controller/networkgateway_ipv4_test.go index ffadc88ee..52b69c09f 100644 --- a/internal/controller/networkgateway_ipv4_test.go +++ b/internal/controller/networkgateway_ipv4_test.go @@ -196,8 +196,8 @@ func TestBuildDesiredRule_LeavesOutIPv4VIPs(t *testing.T) { } attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1")} - dr, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, testVIP), attachments, idx, nil, - false, nil) + dr, _, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, testVIP), attachments, idx, nil, + false, nil, healthGate{}) if err != nil { t.Fatalf("dual-stack rule: %v", err) } @@ -205,14 +205,14 @@ func TestBuildDesiredRule_LeavesOutIPv4VIPs(t *testing.T) { t.Errorf("dual-stack rule VIPs = %v, want only %s", dr.VIPAddresses, testVIP) } - _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, idx, - nil, false, nil) + _, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, idx, + nil, false, nil, healthGate{}) if !errors.Is(err, errNoServedVIP) { t.Errorf("IPv4-only rule: err = %v, want errNoServedVIP", err) } - _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "not-an-ip"), attachments, idx, - nil, false, nil) + _, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "not-an-ip"), attachments, idx, + nil, false, nil, healthGate{}) if err == nil || errors.Is(err, errNoServedVIP) { t.Errorf("rule with an unparseable VIP: err = %v, want a parse error", err) } @@ -221,7 +221,7 @@ func TestBuildDesiredRule_LeavesOutIPv4VIPs(t *testing.T) { if !hasIPv4VIP(mapped) { t.Error("hasIPv4VIP missed an IPv4-mapped IPv6 VIP") } - dr, _, _, err = buildDesiredRule(mapped, attachments, idx, nil, false, nil) + dr, _, _, _, err = buildDesiredRule(mapped, attachments, idx, nil, false, nil, healthGate{}) if err != nil { t.Fatalf("rule with an IPv4-mapped VIP: %v", err) } @@ -265,7 +265,7 @@ func TestDrainingOutcome_WithholdsIPv4VIPs(t *testing.T) { fakeClient := newIndexedClientBuilder(scheme).WithObjects(rule, stillAdvertised).Build() r := newGatewayReconciler(fakeClient, scheme, newFakeGatewayEngine(), testNodeGWA) - o, draining, err := r.drainingOutcome(context.Background(), rule, attachments, idx, nil, nil) + o, draining, err := r.drainingOutcome(context.Background(), rule, attachments, idx, nil, nil, healthGate{}) if err != nil { t.Fatalf("drainingOutcome: %v", err) } @@ -288,8 +288,8 @@ func TestBuildDesiredRule_ServesIPv4WhenEnabled(t *testing.T) { idx := newTestSIDIndex() attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1", testBackendAddr, testBackendAddr4)} - dr, unresolved, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP, "::ffff:"+testVIP4), - attachments, idx, nil, true, nil) + dr, unresolved, _, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP, "::ffff:"+testVIP4), + attachments, idx, nil, true, nil, healthGate{}) if err != nil { t.Fatalf("dual-stack rule: %v", err) } @@ -328,7 +328,8 @@ func TestBuildDesiredRule_ServesIPv4WhenEnabled(t *testing.T) { dr.IPv4Backends[0], dr.Backends[0]) } - dr, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), attachments, idx, nil, true, nil) + dr, _, _, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), attachments, idx, nil, true, nil, + healthGate{}) if err != nil { t.Fatalf("IPv4-only rule with IPv4 VIPs served: %v", err) } @@ -351,7 +352,7 @@ func TestBuildDesiredRule_IPv4FamilyWithoutBackends(t *testing.T) { backendClaimFor(rule, backend, familyIPv4): {Namespace: testNamespace, Name: "older-rule"}, } - dr, unresolved, ipv4, err := buildDesiredRule(rule, attachments, idx, owners, true, nil) + dr, unresolved, ipv4, _, err := buildDesiredRule(rule, attachments, idx, owners, true, nil, healthGate{}) if err != nil { t.Fatalf("dual-stack rule: %v", err) } @@ -368,8 +369,8 @@ func TestBuildDesiredRule_IPv4FamilyWithoutBackends(t *testing.T) { } ipv4Only := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1", testBackendAddr4)} - _, unresolved, ipv4, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), ipv4Only, idx, nil, - true, nil) + _, unresolved, ipv4, _, err = buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4), ipv4Only, idx, nil, + true, nil, healthGate{}) if err == nil || ipv4 != ipv4NoBackend { t.Errorf("IPv4-only rule over an IPv4-only attachment: err = %v, ipv4 = %d; want an error and %d", err, ipv4, ipv4NoBackend) @@ -393,7 +394,7 @@ func TestBuildDesiredRule_SecondIPv4VIP(t *testing.T) { serveIPv4 bool want ipv4Family }{{true, ipv4MultipleVIPs}, {false, ipv4Off}} { - dr, _, ipv4, err := buildDesiredRule(rule, attachments, idx, nil, tc.serveIPv4, nil) + dr, _, ipv4, _, err := buildDesiredRule(rule, attachments, idx, nil, tc.serveIPv4, nil, healthGate{}) if err != nil { t.Fatalf("IPv4VIPs %v: %v", tc.serveIPv4, err) } @@ -406,8 +407,8 @@ func TestBuildDesiredRule_SecondIPv4VIP(t *testing.T) { } } - _, _, ipv4, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, - idx, nil, true, nil) + _, _, ipv4, _, err := buildDesiredRule(newTestRule(testRuleName, "vpc-1", testVIP4, "198.51.100.7"), attachments, + idx, nil, true, nil, healthGate{}) if err == nil || ipv4 != ipv4MultipleVIPs { t.Errorf("IPv4-only rule with two IPv4 VIPs: err = %v, ipv4 = %d; want an error and %d", err, ipv4, ipv4MultipleVIPs) diff --git a/internal/controller/networkgateway_ipv4gate.go b/internal/controller/networkgateway_ipv4gate.go index 1ac3a867c..5d343bf2e 100644 --- a/internal/controller/networkgateway_ipv4gate.go +++ b/internal/controller/networkgateway_ipv4gate.go @@ -17,15 +17,15 @@ import ( bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" ) -// ipv4Bindings holds the generated ServiceVIPBindings of IPv4 VIPs in one -// namespace, by name. The gateway reads them to decide which backends a rule's -// IPv4 VIP may be balanced over and whether it may be advertised. -type ipv4Bindings map[string]*bgpv1alpha1.ServiceVIPBinding +// serviceBindings holds the generated ServiceVIPBindings in one namespace, by +// name. The gateway reads them to decide which backends a rule's IPv4 VIP may +// be balanced over and whether it may be advertised, and which backends their +// nodes report Unhealthy. +type serviceBindings map[string]*bgpv1alpha1.ServiceVIPBinding -// listIPv4Bindings returns the generated ServiceVIPBindings of IPv4 VIPs in -// namespace. Bindings for IPv6 VIPs, and bindings galactic-router did not -// write, are left out. -func listIPv4Bindings(ctx context.Context, c client.Client, namespace string) (ipv4Bindings, error) { +// listServiceBindings returns the generated ServiceVIPBindings in namespace. +// Bindings galactic-router did not write are left out. +func listServiceBindings(ctx context.Context, c client.Client, namespace string) (serviceBindings, error) { list := &bgpv1alpha1.ServiceVIPBindingList{} if err := c.List(ctx, list, client.InNamespace(namespace), @@ -33,11 +33,9 @@ func listIPv4Bindings(ctx context.Context, c client.Client, namespace string) (i ); err != nil { return nil, fmt.Errorf("list ServiceVIPBindings in %s: %w", namespace, err) } - out := make(ipv4Bindings, len(list.Items)) + out := make(serviceBindings, len(list.Items)) for i := range list.Items { - if bindingIsIPv4(&list.Items[i]) { - out[list.Items[i].Name] = &list.Items[i] - } + out[list.Items[i].Name] = &list.Items[i] } return out, nil } @@ -48,7 +46,7 @@ func listIPv4Bindings(ctx context.Context, c client.Client, namespace string) (i // b's IPv6 address: same name, rule label and spec, so a binding left from an // earlier spec, or not yet updated to the current one, does not open the gate. // A binding being deleted does not count either. -func (idx ipv4Bindings) unbound(rule *bgpv1alpha1.NetworkService, vip netip.Addr, b ruleBackend) string { +func (idx serviceBindings) unbound(rule *bgpv1alpha1.NetworkService, vip netip.Addr, b ruleBackend) string { want := generatedBinding(rule, b.node, vip, b) got, ok := idx[want.Name] switch { @@ -67,15 +65,17 @@ func (idx ipv4Bindings) unbound(rule *bgpv1alpha1.NetworkService, vip netip.Addr return "" } -// ipv4BindingReadinessChanged passes ServiceVIPBinding events that can change -// whether a gateway may balance over or advertise an IPv4 VIP: a create or -// delete of a generated IPv4 binding, and an update that changes its spec, -// whether it is Bound, or whether it is being deleted. Bindings of IPv6 VIPs are dropped, since the gateway -// reads only IPv4 ones. -func ipv4BindingReadinessChanged() predicate.Predicate { +// bindingReadinessChanged passes ServiceVIPBinding events that can change +// which backends a gateway balances a rule over or whether it advertises an +// IPv4 VIP: a create or delete of a generated binding, and an update that +// changes its spec, labels, whether it is Bound, whether it is being deleted, +// or its status.health. Only bindings of IPv4 VIPs pass unless health is set, +// since without backend health the gateway reads no other. +func bindingReadinessChanged(health bool) predicate.Predicate { relevant := func(obj client.Object) bool { binding, ok := obj.(*bgpv1alpha1.ServiceVIPBinding) - return ok && binding.Labels[bindingManagedByLabel] == bindingManagedByValue && bindingIsIPv4(binding) + return ok && binding.Labels[bindingManagedByLabel] == bindingManagedByValue && + (health || bindingIsIPv4(binding)) } return predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { return relevant(e.Object) }, @@ -90,7 +90,8 @@ func ipv4BindingReadinessChanged() predicate.Predicate { return oldBinding.Generation != newBinding.Generation || oldBinding.DeletionTimestamp.IsZero() != newBinding.DeletionTimestamp.IsZero() || !maps.Equal(oldBinding.Labels, newBinding.Labels) || - (bindingUnboundReason(oldBinding) == "") != (bindingUnboundReason(newBinding) == "") + (bindingUnboundReason(oldBinding) == "") != (bindingUnboundReason(newBinding) == "") || + !healthEqual(oldBinding.Status.Health, newBinding.Status.Health) }, } } diff --git a/internal/controller/networkgateway_ipv4gate_test.go b/internal/controller/networkgateway_ipv4gate_test.go index 69853a461..c4ff53864 100644 --- a/internal/controller/networkgateway_ipv4gate_test.go +++ b/internal/controller/networkgateway_ipv4gate_test.go @@ -440,7 +440,7 @@ func TestIPv4BindingReadinessChanged(t *testing.T) { now := metav1.Now() deleting.DeletionTimestamp = &now - p := ipv4BindingReadinessChanged() + p := bindingReadinessChanged(false) for _, tc := range []struct { name string got bool diff --git a/internal/controller/networkservice_summary.go b/internal/controller/networkservice_summary.go index 6b6e787bd..e29864139 100644 --- a/internal/controller/networkservice_summary.go +++ b/internal/controller/networkservice_summary.go @@ -57,6 +57,16 @@ const ( reasonReady = "Ready" ) +// backendProblemReasons are the Programmed reasons, all reported with status +// True, that say a gateway node loaded the rule but not over every backend as +// intended. +var backendProblemReasons = map[string]bool{ + reasonBackendsUnresolved: true, + reasonBackendsUnhealthy: true, + reasonNoHealthyBackends: true, + reasonHealthChecksNotApplied: true, +} + // vipFamilies records which address families a rule's VIPs cover. type vipFamilies struct { ipv4, ipv6 bool @@ -265,11 +275,12 @@ func ipv4ServedSummary(current func(string) *metav1.Condition, programmed []stri // backendsReadyCondition summarizes the backend side of a rule: every backend // node's BackendsBound condition, and whether any gateway node in programmed -// left backends out because their uSID did not resolve. +// left backends out because their uSID did not resolve, left them out or kept +// them all because their nodes report them Unhealthy, or could not apply the +// rule's health check. // -// Two inputs are planned and not written yet: whether every cluster holding a -// backend has the rule, so replies have a path back (#706), and backend health -// (#704). Each adds failing reports here. +// One input is planned and not written yet: whether every cluster holding a +// backend has the rule, so replies have a path back (#706). func backendsReadyCondition(conditions []metav1.Condition, generation int64, programmed []string) metav1.Condition { cond := metav1.Condition{Type: conditionTypeBackendsReady} @@ -291,8 +302,8 @@ func backendsReadyCondition(conditions []metav1.Condition, generation int64, pro } for _, n := range programmed { c := meta.FindStatusCondition(conditions, programmedConditionType(n)) - if c != nil && c.Reason == reasonBackendsUnresolved { - problems = append(problems, nodeReport{n, reasonBackendsUnresolved}) + if c != nil && backendProblemReasons[c.Reason] { + problems = append(problems, nodeReport{n, c.Reason}) } } sort.Slice(problems, func(i, j int) bool { diff --git a/internal/controller/networkservice_summary_test.go b/internal/controller/networkservice_summary_test.go index 1e6912f05..690f6ae72 100644 --- a/internal/controller/networkservice_summary_test.go +++ b/internal/controller/networkservice_summary_test.go @@ -298,6 +298,35 @@ func TestSummaryConditions(t *testing.T) { conditionTypeBackendsReady: {metav1.ConditionFalse, reasonBackendsUnresolved}, }, }, + { + name: "a gateway node left Unhealthy backends out", + conditions: with(serving, + cond(programmedConditionType(testNodeGWA), metav1.ConditionTrue, reasonBackendsUnhealthy)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonBackendsUnhealthy}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonBackendsUnhealthy}, + }, + }, + { + name: "every backend is Unhealthy", + conditions: with(serving, + cond(programmedConditionType(testNodeGWA), metav1.ConditionTrue, reasonNoHealthyBackends)), + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonNoHealthyBackends}, + }, + }, + { + name: "a gateway node cannot apply health checks", + conditions: with(serving, + cond(programmedConditionType(testNodeGWA), metav1.ConditionTrue, reasonHealthChecksNotApplied)), + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonHealthChecksNotApplied}, + }, + }, { name: "no backend node has reported", conditions: without(serving, backendsBoundConditionType(testBackendNode)), diff --git a/internal/controller/rulebackends.go b/internal/controller/rulebackends.go index d2abf2b71..c4b09718a 100644 --- a/internal/controller/rulebackends.go +++ b/internal/controller/rulebackends.go @@ -36,6 +36,9 @@ import ( // to a node that has no binding planned for it. type ruleBackend struct { attachment types.NamespacedName + // uid is the attachment's UID, which a published health decision must + // name to apply to this backend. + uid types.UID node string addr netip.Addr port uint16 @@ -238,6 +241,7 @@ func ruleCandidateBackends( for _, addr := range addrs { backends = append(backends, ruleBackend{ attachment: key, + uid: attachment.UID, node: attachment.Status.Node, addr: addr, port: port, From f75b7e12a2712f5f193c333dfcc31ae89cd445ae Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 14:33:45 -0400 Subject: [PATCH 4/4] test(lab): Check that gateways follow backend health The containerlab lab had no service with a health check, so nothing exercised a backend failing while its pod stays up and its attachment still resolves. ns60's services in every site now carry a healthCheck, the UDP one probing TCP port 80, and every lab gateway runs with GALACTIC_GATEWAY_BACKEND_HEALTH on. ns60's traffic policy allows the probes: TCP to port 80 from fe80::/10 on the Private path, and the replies back. verify:traffic-policy's temporary ns60 policy keeps that grant, so its own checks never take the backends out. verify:gateway-backend-health stops one dfw backend's TCP listener and checks that both gateways drop it within the detection and convergence limits, that new TCP and UDP flows through each gateway reach only the other backend, that the decision survives a galactic-router restart on the backend's node and a gateway restart, and that the backend returns once it listens again. Fixed client ports must reach the same backend through both gateways in every phase, and map where they did before after recovery. Co-Authored-By: Claude Opus 5.5 --- deploy/containerlab/README.md | 1 + deploy/containerlab/Taskfile.yaml | 11 + .../base/gateway-lab-patch.yaml | 6 + .../galactic-gateway/dfw/networkservices.yaml | 5 + .../galactic-gateway/iad/networkservices.yaml | 5 + .../galactic-gateway/sjc/networkservices.yaml | 5 + .../resources/tenants/policies/README.md | 10 +- .../policies/public-service/policies.yaml | 22 +- .../scripts/verify-gateway-backend-health.sh | 337 ++++++++++++++++++ .../scripts/verify-traffic-policy.sh | 7 + 10 files changed, 401 insertions(+), 8 deletions(-) create mode 100755 deploy/containerlab/scripts/verify-gateway-backend-health.sh diff --git a/deploy/containerlab/README.md b/deploy/containerlab/README.md index 445ee5e04..195245e09 100644 --- a/deploy/containerlab/README.md +++ b/deploy/containerlab/README.md @@ -534,6 +534,7 @@ task deploy | `verify:gateway` | Check every NetworkGateway is Ready, every NetworkService Accepted, every generated ServiceVIPBinding Bound | | `verify:gateway-ingress` | TCP and UDP from the off-fabric host to each site's VIP, through every gateway node in turn | | `verify:gateway-ingress-ipv4` | IPv4 TCP and UDP to each site's IPv4 VIP through every gateway node, translated to the IPv6-only backends | +| `verify:gateway-backend-health` | Stops a dfw backend's listener; both gateways must drop it, keep it out across restarts, and take it back once it listens | | `verify:gateway-node-loss` | Take dfw-worker2's fabric links down: ingress through dfw-worker3 must pass, then through dfw-worker2 once restored (not in `verify`) | | `verify:gateway-restart` | Restart dfw-worker2's gateway and shard in turn while the other carries traffic (#710) | | `verify:gateway-detach` | Turn dfw-worker2's gateway datapath off: ingress through it must fail and through dfw-worker3 pass, then through it pass (not in `verify`) | diff --git a/deploy/containerlab/Taskfile.yaml b/deploy/containerlab/Taskfile.yaml index 62668706b..f6b6eda60 100644 --- a/deploy/containerlab/Taskfile.yaml +++ b/deploy/containerlab/Taskfile.yaml @@ -431,6 +431,7 @@ tasks: - task: "verify:gateway" - task: "verify:gateway-ingress" - task: "verify:gateway-ingress-ipv4" + - task: "verify:gateway-backend-health" - task: "verify:gateway-restart" - task: "verify:nat-sharding" - task: "verify:nat-egress" @@ -616,6 +617,16 @@ tasks: cmds: - LAB={{.LAB}} ./scripts/verify-gateway-ingress-ipv4.sh + # dfw's VIP drops a backend whose listener stops while its pod stays up, + # on both gateway nodes and with no operator action, keeps it out across a + # galactic-router and a galactic-gateway restart, and takes it back once it + # listens again. Fixed client ports must map to the same backend through + # both gateways, and back where they were after recovery. + "verify:gateway-backend-health": + desc: Stop one dfw backend's listener and check both gateways drop it, then restore it + cmds: + - LAB={{.LAB}} ./scripts/verify-gateway-backend-health.sh + # #710: the gateway and the egress shard share each edge node's uplinks # through its XDP dispatcher, so restarting either must leave the other's # traffic flowing. 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 89a8e8477..7b04aa42b 100644 --- a/deploy/containerlab/resources/galactic-gateway/base/gateway-lab-patch.yaml +++ b/deploy/containerlab/resources/galactic-gateway/base/gateway-lab-patch.yaml @@ -21,3 +21,9 @@ spec: # it needs (verify:gateway-ingress-ipv4). - name: GALACTIC_GATEWAY_IPV4_VIPS value: "true" + # Off by default. Every lab gateway takes a backend its node + # reports Unhealthy out of ns60's services, which carry a + # healthCheck (verify:gateway-backend-health). The same binding + # access as IPv4 VIPs covers it. + - name: GALACTIC_GATEWAY_BACKEND_HEALTH + value: "true" diff --git a/deploy/containerlab/resources/galactic-gateway/dfw/networkservices.yaml b/deploy/containerlab/resources/galactic-gateway/dfw/networkservices.yaml index 14e278049..bf2e5f3a1 100644 --- a/deploy/containerlab/resources/galactic-gateway/dfw/networkservices.yaml +++ b/deploy/containerlab/resources/galactic-gateway/dfw/networkservices.yaml @@ -17,6 +17,8 @@ spec: matchLabels: app: backend backendPort: 80 + # Each backend's node probes it on backendPort (verify:gateway-backend-health). + healthCheck: {} --- # ns60's port 80 over UDP, served by every ns60 backend its selector picks in dfw. # Both VIPs reach the same IPv6-only backends: the backend's node translates @@ -37,3 +39,6 @@ spec: matchLabels: app: backend backendPort: 80 + # A UDP service names a TCP port to probe: the backends answer TCP on 80 too. + healthCheck: + port: 80 diff --git a/deploy/containerlab/resources/galactic-gateway/iad/networkservices.yaml b/deploy/containerlab/resources/galactic-gateway/iad/networkservices.yaml index eb1dba189..1ca73392f 100644 --- a/deploy/containerlab/resources/galactic-gateway/iad/networkservices.yaml +++ b/deploy/containerlab/resources/galactic-gateway/iad/networkservices.yaml @@ -17,6 +17,8 @@ spec: matchLabels: app: backend backendPort: 80 + # Each backend's node probes it on backendPort (verify:gateway-backend-health). + healthCheck: {} --- # ns60's port 80 over UDP, served by every ns60 backend its selector picks in iad. # Both VIPs reach the same IPv6-only backends: the backend's node translates @@ -37,3 +39,6 @@ spec: matchLabels: app: backend backendPort: 80 + # A UDP service names a TCP port to probe: the backends answer TCP on 80 too. + healthCheck: + port: 80 diff --git a/deploy/containerlab/resources/galactic-gateway/sjc/networkservices.yaml b/deploy/containerlab/resources/galactic-gateway/sjc/networkservices.yaml index 1ff7a0f14..173772f41 100644 --- a/deploy/containerlab/resources/galactic-gateway/sjc/networkservices.yaml +++ b/deploy/containerlab/resources/galactic-gateway/sjc/networkservices.yaml @@ -17,6 +17,8 @@ spec: matchLabels: app: backend backendPort: 80 + # Each backend's node probes it on backendPort (verify:gateway-backend-health). + healthCheck: {} --- # ns60's port 80 over UDP, served by every ns60 backend its selector picks in sjc. # Both VIPs reach the same IPv6-only backends: the backend's node translates @@ -37,3 +39,6 @@ spec: matchLabels: app: backend backendPort: 80 + # A UDP service names a TCP port to probe: the backends answer TCP on 80 too. + healthCheck: + port: 80 diff --git a/deploy/containerlab/resources/tenants/policies/README.md b/deploy/containerlab/resources/tenants/policies/README.md index 6ee26feef..ece9a1c03 100644 --- a/deploy/containerlab/resources/tenants/policies/README.md +++ b/deploy/containerlab/resources/tenants/policies/README.md @@ -5,11 +5,11 @@ in `resources/galactic-cni/shared/`), so a tenant interface forwards only what its bindings grant. These are the grants, one set per kind of tenant, each an ingress and an egress policy granting only the paths that tenant's checks use: -| Set | Tenants | Egress grants | Ingress grants | -| ---------------- | ---------------------- | ------------------ | --------------------------------- | -| `private-nat` | ns10, ns20, ns30, ns71 | Private, PublicNAT | Private (except TCP 9), PublicNAT | -| `private` | ns40 | Private | Private (except TCP 9) | -| `public-service` | ns60 | PublicService | PublicService | +| Set | Tenants | Egress grants | Ingress grants | +| ---------------- | ---------------------- | ------------------------------------------------------ | ------------------------------------------------------ | +| `private-nat` | ns10, ns20, ns30, ns71 | Private, PublicNAT | Private (except TCP 9), PublicNAT | +| `private` | ns40 | Private | Private (except TCP 9) | +| `public-service` | ns60 | PublicService, Private TCP from port 80 to `fe80::/10` | PublicService, Private TCP to port 80 from `fe80::/10` | The TCP 9 deny on Private ingress, and every path a set leaves out, are what `verify:traffic-policy` uses to prove a denial is enforced and counted. Each diff --git a/deploy/containerlab/resources/tenants/policies/public-service/policies.yaml b/deploy/containerlab/resources/tenants/policies/public-service/policies.yaml index b5ea1c18c..185c4e731 100644 --- a/deploy/containerlab/resources/tenants/policies/public-service/policies.yaml +++ b/deploy/containerlab/resources/tenants/policies/public-service/policies.yaml @@ -1,7 +1,9 @@ # ns60's VIP backends: they receive the gateways' public service traffic and -# answer it, and nothing else (verify:gateway-ingress). verify:traffic-policy -# inserts a temporary deny ahead of allow-service to prove a denial on this -# path, then restores this policy. +# answer it, and the TCP health probes their own node sends from its host-side +# link-local address, and nothing else (verify:gateway-ingress, +# verify:gateway-backend-health). verify:traffic-policy inserts a temporary +# deny ahead of allow-service to prove a denial on this path, then restores +# this policy. apiVersion: galactic.datumapis.com/v1alpha1 kind: TrafficPolicy metadata: @@ -12,6 +14,13 @@ spec: action: Allow match: path: PublicService + - name: allow-health-probe-replies + action: Allow + match: + path: Private + protocol: TCP + destinationCIDRs: ["fe80::/10"] + sourcePorts: [{start: 80, end: 80}] --- apiVersion: galactic.datumapis.com/v1alpha1 kind: TrafficPolicy @@ -23,3 +32,10 @@ spec: action: Allow match: path: PublicService + - name: allow-health-probe + action: Allow + match: + path: Private + protocol: TCP + sourceCIDRs: ["fe80::/10"] + destinationPorts: [{start: 80, end: 80}] diff --git a/deploy/containerlab/scripts/verify-gateway-backend-health.sh b/deploy/containerlab/scripts/verify-gateway-backend-health.sh new file mode 100755 index 000000000..e3efc15d0 --- /dev/null +++ b/deploy/containerlab/scripts/verify-gateway-backend-health.sh @@ -0,0 +1,337 @@ +#!/bin/bash +# verify-gateway-backend-health.sh — prove that a VIP stops sending new flows +# to a backend that stops serving, on every gateway node and with no operator +# action, and sends them again once it recovers. +# +# dfw's VIP has two ns60 backends on dfw-worker and two gateway nodes, +# dfw-worker2 and dfw-worker3. ns60-tcp and ns60-udp both carry a +# healthCheck that probes TCP port 80. The check stops backend-a's TCP +# listener while its pod, container and VPCAttachment stay as they are, so +# the backend still resolves and advertises and only its health says it is +# gone. Then: +# +# 1. Both backends are Healthy, and both gateways report applying health. +# 2. backend-a's bindings turn Unhealthy within DETECT_S, and within +# CONVERGE_S of that both gateways hold one backend for the VIP +# (galactic_edge_rule_backends, read from each node's datapath). +# 3. Through each gateway pinned in turn, every new TCP and UDP flow is +# answered, and by backend-b only. The UDP service drops backend-a too: +# its health check probes TCP port 80. +# 4. Restarting galactic-router on dfw-worker leaves backend-a's published +# decision as it was, and restarting galactic-gateway on dfw-worker2 +# brings that gateway back without backend-a. +# 5. backend-a's listener restarts, its bindings turn Healthy within +# DETECT_S, both gateways hold two backends within CONVERGE_S, and both +# backends answer flows again. +# +# Throughout, FIXED_PORTS fixed UDP source ports must map to the same backend +# through both gateways, which is what identical Maglev tables look like from +# a client, and after recovery each must map where it did before. The run +# reports how many of them changed backend on removal and on recovery. +# +# Usage: verify-gateway-backend-health.sh +set -euo pipefail + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +source "${SCRIPT_DIR}/lib.sh" + +LAB=${LAB:-gvpc} +CP=$(control_plane dfw) +CLIENT_HOST="clab-${LAB}-remote-host" +VIP=2001:db8:6060:1::1 +PORT=80 +FLOWS=16 +FIXED_PORTS=32 +DETECT_S=30 +CONVERGE_S=5 +GATEWAY_METRICS_PORT=8081 +BACKEND_NODE=dfw-worker +GATEWAYS=(dfw-worker2 dfw-worker3) +# " ", +# as in verify-gateway-ingress.sh. +declare -A UPLINK=( + [dfw-worker2]="tr1 2001:db8:1:11::2 bond1" + [dfw-worker3]="tr1 2001:db8:1:12::2 bond2" +) + +kc() { docker exec -i "${CP}" kubectl "$@"; } +transit() { docker exec "clab-${LAB}-$1" "${@:2}"; } + +rc=0 +fail() { + echo " FAIL $*" >&2 + rc=1 +} +die() { + echo "FAIL: $*" >&2 + exit 1 +} + +listening() { + kc -n ns60 exec deploy/backend-a -- sh -c 'pgrep -f "TCP6-LISTE[N]" >/dev/null' 2>/dev/null +} +stop_listener() { + kc -n ns60 exec deploy/backend-a -- sh -c 'pkill -f "TCP6-LISTE[N]"' +} +start_listener() { + kc -n ns60 exec -i deploy/backend-a -- sh -s <<'EOF' +reply='echo "$POD_NAME $SOCAT_PEERADDR"' +setsid socat TCP6-LISTEN:80,reuseaddr,fork SYSTEM:"$reply" /dev/null 2>&1 & +EOF +} + +work=$(mktemp -d) +cleanup() { + transit tr1 ip -6 route del "${VIP}/128" 2>/dev/null || true + listening || start_listener || true + rm -rf "${work}" +} +trap cleanup EXIT + +# rule_backends NODE PROTO prints NODE's backend count for the VIP's PROTO rule. +rule_backends() { + docker exec "$1" curl -s --max-time 4 "http://localhost:${GATEWAY_METRICS_PORT}/metrics" | + awk -v p="proto=\"$2\"" -v v="vip=\"${VIP}\"" \ + 'index($0, "galactic_edge_rule_backends{") == 1 && index($0, p) && index($0, v) && index($0, "port=\"80\"") {print $NF; exit}' +} + +# backend_health SERVICE ADDR prints "state lastTransitionTime" of the +# binding dfw-worker writes for SERVICE's IPv6 VIP and the backend at ADDR. +backend_health() { + kc -n galactic-system get servicevipbindings \ + -l "galactic.datum.net/network-rule=$1,galactic.datum.net/binding-node=${BACKEND_NODE}" \ + -o jsonpath="{range .items[?(@.spec.vipAddress==\"${VIP}\")]}{.spec.backendAddress} {.status.health.state} {.status.health.lastTransitionTime}{\"\\n\"}{end}" | + awk -v a="$2" '$1 == a {print $2, $3}' +} + +# request PROTO SPORT prints the answering backend pod, or nothing. +request() { + local addr + case "$1" in + tcp) addr="TCP6:[${VIP}]:${PORT},sourceport=$2,reuseaddr" ;; + udp) addr="UDP6:[${VIP}]:${PORT},sourceport=$2,reuseaddr" ;; + esac + echo probe | docker exec -i "${CLIENT_HOST}" timeout 5 socat -t2 -T3 - "${addr}" 2>/dev/null | + head -1 | awk '{print $1}' || true +} + +pin() { + local tr nexthop dev + read -r tr nexthop dev <<<"${UPLINK[$1]}" + transit "${tr}" ip -6 route replace "${VIP}/128" via "${nexthop}" dev "${dev}" +} +unpin() { transit tr1 ip -6 route del "${VIP}/128" 2>/dev/null || true; } + +# wait_for SECONDS DESCRIPTION COMMAND... polls COMMAND every half second and +# sets WAITED to the seconds it took, failing past SECONDS. +wait_for() { + local limit="$1" what="$2" start now + shift 2 + start=$(date +%s.%N) + while :; do + if "$@"; then + now=$(date +%s.%N) + WAITED=$(awk -v a="${start}" -v b="${now}" 'BEGIN {printf "%.1f", b - a}') + return 0 + fi + now=$(date +%s.%N) + if awk -v a="${start}" -v b="${now}" -v l="${limit}" 'BEGIN {exit !(b - a > l)}'; then + fail "${what}: not within ${limit}s" + WAITED="" + return 1 + fi + sleep 0.5 + done +} + +health_is() { # SERVICE ADDR STATE + local got + got=$(backend_health "$1" "$2") + [ "${got%% *}" = "$3" ] +} +both_health_is() { health_is ns60-tcp "$1" "$2" && health_is ns60-udp "$1" "$2"; } +holds() { # GATEWAY COUNT + [ "$(rule_backends "$1" tcp)" = "$2" ] && [ "$(rule_backends "$1" udp)" = "$2" ] +} +gateways_hold() { # COUNT + local gw + for gw in "${GATEWAYS[@]}"; do + holds "${gw}" "$1" || return 1 + done +} +gateway_ready() { # GATEWAY + [ "$(kc -n galactic-system get pods -l app.kubernetes.io/name=galactic-gateway \ + --field-selector "spec.nodeName=$1" -o jsonpath='{.items[0].status.containerStatuses[0].ready}')" = true ] +} + +# flows_through GATEWAY WANT: FLOWS new TCP and UDP flows through GATEWAY must +# all be answered, by WANT when it is set. It prints the backends seen. +flows_through() { + local gw="$1" want="${2:-}" proto pod seen="" + pin "${gw}" + for proto in tcp udp; do + local answered=0 + for _ in $(seq "${FLOWS}"); do + pick_port + pod=$(request "${proto}" "${PORT_PICKED}") + if [ -z "${pod}" ]; then + fail "${gw} ${proto} from port ${PORT_PICKED}: no reply" + elif [ -n "${want}" ] && [ "${pod}" != "${want}" ]; then + fail "${gw} ${proto} from port ${PORT_PICKED}: answered by ${pod}, want ${want}" + else + answered=$((answered + 1)) + seen="${seen} ${pod}" + fi + done + echo " ${gw} ${proto}: ${answered}/${FLOWS} answered${want:+, all by ${want}}" + done + unpin + SEEN=$(tr ' ' '\n' <<<"${seen}" | sort -u | tr '\n' ' ') +} + +# mapping GATEWAY prints "port backend" for each fixed UDP source port +# through GATEWAY. One TCP request goes first: edge_lb drops a packet whose +# next hop has no neighbor entry yet (fib_no_neigh), and only TCP's +# retransmits ride that out, so on a path idle long enough for the entry to +# expire the first UDP probes would be lost for a reason this check does not +# test. +mapping() { + local p + pin "$1" + pick_port + request tcp "${PORT_PICKED}" >/dev/null + for p in "${PORTS[@]}"; do + echo "${p} $(request udp "${p}")" + done + unpin +} + +# map_phase NAME records both gateways' mappings for NAME and checks they agree. +map_phase() { + local name="$1" + mapping "${GATEWAYS[0]}" >"${work}/${name}.${GATEWAYS[0]}" + mapping "${GATEWAYS[1]}" >"${work}/${name}.${GATEWAYS[1]}" + if grep -q ' $' "${work}/${name}.${GATEWAYS[0]}" "${work}/${name}.${GATEWAYS[1]}"; then + fail "${name}: a fixed port drew no reply" + fi + if cmp -s "${work}/${name}.${GATEWAYS[0]}" "${work}/${name}.${GATEWAYS[1]}"; then + echo " ok ${name}: all ${FIXED_PORTS} fixed ports map to the same backend through both gateways" + else + fail "${name}: the gateways map fixed ports to different backends:" + diff "${work}/${name}.${GATEWAYS[0]}" "${work}/${name}.${GATEWAYS[1]}" | sed 's/^/ /' >&2 + fi +} + +# moved FROM TO prints how many fixed ports changed backend between phases. +moved() { + join "${work}/$1.${GATEWAYS[0]}" "${work}/$2.${GATEWAYS[0]}" | awk '$2 != $3' | wc -l +} + +ADDR_A=$(kc -n ns60 get vpcattachment backend-a -o jsonpath='{.spec.interface.addresses[0]}') +ADDR_A=${ADDR_A%/*} +ADDR_B=$(kc -n ns60 get vpcattachment backend-b -o jsonpath='{.spec.interface.addresses[0]}') +ADDR_B=${ADDR_B%/*} +POD_A=$(pod_name "${CP}" ns60 app=backend,instance=a) +POD_B=$(pod_name "${CP}" ns60 app=backend,instance=b) +identity() { + echo "$(kc -n ns60 get pod "${POD_A}" -o jsonpath='{.metadata.uid} {.status.containerStatuses[0].restartCount}')" \ + "$(kc -n ns60 get vpcattachment backend-a -o jsonpath='{.metadata.uid}')" +} +ID_BEFORE=$(identity) + +declare -a PORTS=() +for _ in $(seq "${FIXED_PORTS}"); do + pick_port + PORTS+=("${PORT_PICKED}") +done +mapfile -t PORTS < <(printf '%s\n' "${PORTS[@]}" | sort) + +echo "--- 1. baseline: both backends Healthy, both gateways apply health" +listening || start_listener +wait_for "${DETECT_S}" "backend-a Healthy" both_health_is "${ADDR_A}" Healthy || true +wait_for "${DETECT_S}" "backend-b Healthy" both_health_is "${ADDR_B}" Healthy || true +for gw in "${GATEWAYS[@]}"; do + f=$(kc -n galactic-system get networkgateway "${gw}" -o jsonpath='{.status.backendHealthFiltering}') + [ "${f}" = "true" ] || fail "${gw} does not report backendHealthFiltering (got '${f}')" +done +wait_for "${CONVERGE_S}" "both gateways hold 2 backends" gateways_hold 2 || true +map_phase baseline +[ "${rc}" -eq 0 ] || die "baseline is not healthy; fix it before testing a failure" + +echo "--- 2. stop backend-a's TCP listener" +stop_listener +listening && die "backend-a's TCP listener is still running" +if wait_for "${DETECT_S}" "backend-a Unhealthy" both_health_is "${ADDR_A}" Unhealthy; then + echo " ok backend-a Unhealthy after ${WAITED}s" +fi +if wait_for "${CONVERGE_S}" "both gateways drop backend-a" gateways_hold 1; then + echo " ok both gateways hold 1 backend ${WAITED}s after the decision was seen" +fi + +echo "--- 3. new flows avoid backend-a through each gateway" +for gw in "${GATEWAYS[@]}"; do + flows_through "${gw}" "${POD_B}" +done +map_phase unhealthy +removed=$(moved baseline unhealthy) +stolen=$(join "${work}/baseline.${GATEWAYS[0]}" "${work}/unhealthy.${GATEWAYS[0]}" | + awk -v a="${POD_A}" '$2 != a && $2 != $3' | wc -l) +echo " removal moved ${removed}/${FIXED_PORTS} fixed ports, ${stolen} of them between remaining backends" +[ "${stolen}" -eq 0 ] || fail "removing backend-a moved ${stolen} fixed ports that were on backend-b" + +echo "--- 4. restarts while backend-a is Unhealthy" +before=$(backend_health ns60-tcp "${ADDR_A}") +router_pod=$(kc -n galactic-system get pods -l app.kubernetes.io/name=galactic-router \ + --field-selector "spec.nodeName=${BACKEND_NODE}" -o jsonpath='{.items[0].metadata.name}') +kc -n galactic-system delete pod "${router_pod}" --wait=true >/dev/null +kc -n galactic-system rollout status ds/galactic-router --timeout=180s >/dev/null +sleep 30 +after=$(backend_health ns60-tcp "${ADDR_A}") +if [ "${before}" = "${after}" ]; then + echo " ok galactic-router restarted on ${BACKEND_NODE}; backend-a's decision unchanged (${after})" +else + fail "backend-a's decision changed across a galactic-router restart: '${before}' -> '${after}'" +fi +gw_pod=$(kc -n galactic-system get pods -l app.kubernetes.io/name=galactic-gateway \ + --field-selector "spec.nodeName=${GATEWAYS[0]}" -o jsonpath='{.items[0].metadata.name}') +kc -n galactic-system delete pod "${gw_pod}" --wait=true >/dev/null +wait_for 120 "${GATEWAYS[0]}'s gateway pod Ready again" gateway_ready "${GATEWAYS[0]}" || true +if wait_for 60 "${GATEWAYS[0]} holds 1 backend after its restart" holds "${GATEWAYS[0]}" 1; then + echo " ok galactic-gateway restarted on ${GATEWAYS[0]}; it holds 1 backend ${WAITED}s after Ready" +fi +flows_through "${GATEWAYS[0]}" "${POD_B}" + +echo "--- 5. restart backend-a's TCP listener" +start_listener +if wait_for "${DETECT_S}" "backend-a Healthy again" both_health_is "${ADDR_A}" Healthy; then + echo " ok backend-a Healthy after ${WAITED}s" +fi +if wait_for "${CONVERGE_S}" "both gateways restore backend-a" gateways_hold 2; then + echo " ok both gateways hold 2 backends ${WAITED}s after the decision was seen" +fi +for gw in "${GATEWAYS[@]}"; do + flows_through "${gw}" "" + [[ " ${SEEN} " == *" ${POD_A} "* ]] || fail "${gw}: backend-a answered no flow after recovering" +done +map_phase recovered +restored=$(moved unhealthy recovered) +echo " recovery moved ${restored}/${FIXED_PORTS} fixed ports" +if cmp -s "${work}/baseline.${GATEWAYS[0]}" "${work}/recovered.${GATEWAYS[0]}"; then + echo " ok every fixed port maps where it did before backend-a failed" +else + fail "the recovered table differs from the baseline:" + diff "${work}/baseline.${GATEWAYS[0]}" "${work}/recovered.${GATEWAYS[0]}" | sed 's/^/ /' >&2 +fi + +ID_AFTER=$(identity) +if [ "${ID_BEFORE}" = "${ID_AFTER}" ]; then + echo " ok backend-a's pod, container and attachment never changed (${ID_AFTER})" +else + fail "backend-a's identity changed during the check: '${ID_BEFORE}' -> '${ID_AFTER}'" +fi + +if [ "${rc}" -ne 0 ]; then + echo "FAIL: the gateways did not follow backend-a's health" >&2 + exit 1 +fi +echo "PASS: both gateways dropped backend-a while it was down and restored it once it served again" diff --git a/deploy/containerlab/scripts/verify-traffic-policy.sh b/deploy/containerlab/scripts/verify-traffic-policy.sh index a34754b1c..7e3425710 100755 --- a/deploy/containerlab/scripts/verify-traffic-policy.sh +++ b/deploy/containerlab/scripts/verify-traffic-policy.sh @@ -196,6 +196,13 @@ spec: action: Allow match: path: PublicService + - name: allow-health-probe + action: Allow + match: + path: Private + protocol: TCP + sourceCIDRs: ["fe80::/10"] + destinationPorts: [{start: 80, end: 80}] EOF if ! wait_policy_applied dfw ns60 lab-ingress; then fail "dfw did not install ns60's edited lab-ingress"