From 8e73d0eff9b0c1382eefb4950a14a7882cd1189f Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 21 Oct 2026 07:38:32 -0400 Subject: [PATCH 1/2] feat(gateway): Report if a rule serves traffic To tell whether a NetworkService serves, a client had to know every gateway node, read each node's Programmed condition on the rule, and read each node's NetworkGateway for whether its routes were published. The tenant-facing API (#696) must not reach into NetworkGateway. Each gateway node now writes /Advertised beside /Programmed. It is True once the node published the rule's BGPAdvertisements and galactic-router reports each one Advertised for its current generation, and otherwise False with NotProgrammed, NoRouter, AdvertisementFailed or AdvertisementPending. A status write that changes whether one of the node's rule advertisements is installed now wakes the gateway pass. NetworkServiceReconciler rolls the per-node conditions up into rule-wide ones: - Programmed: every reporting gateway node loaded the rule. - Advertised: every node that loaded it has its routes installed. - BackendsReady: every backend node bound its backends, and no gateway node left one out unresolved. - IPv4Served: on a rule with an IPv4 VIP only, every node that loaded the rule serves that VIP. - Ready: Accepted and the above, reading IPv4Served only for a rule with no IPv6 VIP. IPv4 VIPs are off by default, and a rule whose IPv6 VIP serves must not read as down. Only gateway nodes reporting on the current generation count, since a node that has not reported advertises nothing; Programmed and Ready say how many have not. A per-node condition, or Accepted, from an older generation counts as pending. A failing summary takes the reason every failing node shares, or a generic one. Every input is shared state, so every gateway node computes the same result. The summary is re-read through the uncached APIReader and written only on change. clearNodeRuleConditions recomputes it, since no reconciler is left once the last gateway node leaves. BackendsReady leaves room for the reply-path check (#706) and backend health (#704). docs/gateway/configuration.md gains the reason table the tenant-facing API maps from. Related to #708 Co-Authored-By: Claude Opus 5.5 --- docs/agents/ARCHITECTURE-GATEWAY.md | 33 +- docs/gateway/configuration.md | 79 ++- .../controller/networkgateway_controller.go | 204 +++++-- .../networkgateway_controller_test.go | 98 +++- .../controller/networkservice_controller.go | 11 +- internal/controller/networkservice_summary.go | 398 +++++++++++++ .../controller/networkservice_summary_test.go | 522 ++++++++++++++++++ internal/controller/status.go | 6 +- 8 files changed, 1295 insertions(+), 56 deletions(-) create mode 100644 internal/controller/networkservice_summary.go create mode 100644 internal/controller/networkservice_summary_test.go diff --git a/docs/agents/ARCHITECTURE-GATEWAY.md b/docs/agents/ARCHITECTURE-GATEWAY.md index f1d57916d..2a98d6fad 100644 --- a/docs/agents/ARCHITECTURE-GATEWAY.md +++ b/docs/agents/ARCHITECTURE-GATEWAY.md @@ -305,15 +305,24 @@ that converges this node's whole gateway engine: as its own `/Programmed` condition (`Programmed`, `BackendsUnresolved`, `LoadFailed`, `InvalidRule`, or `NoServedVIP` for an IPv4-only rule, with - the error or the unresolved backends in the message), and, for a rule - with an IPv4 VIP, a `/IPv4Served` condition: `True` with reason + the error or the unresolved backends in the message), a + `/Advertised` condition (`advertisedCondition`: `True` with + `Advertised` once the node published the rule's `BGPAdvertisement`s and + `galactic-router` reports each one `Advertised` for its current + generation (`uninstalledAdvertisements`), or `False` with + `NotProgrammed`, `NoRouter`, `AdvertisementFailed` or + `AdvertisementPending`, so a rule's publish failure is on the rule and not + only on the node's `NetworkGateway`; a status write that changes whether + one of its advertisements is installed wakes the pass, `installedChanged`), + and, for a rule with an IPv4 VIP, a + `/IPv4Served` condition: `True` with reason `Advertised`, or `False` with `NotAdvertised` (loaded over Bound backends but the route not published), `BindingsNotBound` (loaded, no backend Bound), `Unsupported` (switch off), `NoBackend`, `MultipleVIPs` or `NotLoaded` (the rule as a whole is not loaded). The first three mean loaded (`ipv4LoadedReasons`), and `galactic-router` writes a rule's IPv4 bindings only while some node reports one of them. Every pass also - removes the `Programmed` and `IPv4Served` conditions of any node no + removes the `Programmed`, `Advertised` and `IPv4Served` conditions of any node no `NetworkGateway` in the namespace targets (`departedGatewayNodes`, `removeDepartedNodeConditions`), so a node that left without its conditions being cleared cannot keep a loaded reason, and with it the @@ -326,7 +335,23 @@ that converges this node's whole gateway engine: `NetworkService` status is shared by every gateway node while loading is per node; a node writes it only when it changes, and a departing, deleted, or disabled node's conditions are removed with its - advertisements. The `NetworkGateway`'s `EngineDegraded` message + advertisements. `NetworkServiceReconciler` then rolls every node's + conditions up into rule-wide ones, `Programmed`, `Advertised`, + `BackendsReady`, `IPv4Served` (only on a rule with an IPv4 VIP) and + `Ready` (`summaryConditions`, + `internal/controller/networkservice_summary.go`), so a client such as the + tenant-facing API reads one rule and never `NetworkGateway` (#708). Only + gateway nodes reporting a `Programmed` condition for the current + generation count, since a node that has not reported advertises nothing. + `Ready` reads `IPv4Served` only for a rule with no IPv6 VIP, so a rule + whose IPv6 VIP serves is not reported down on gateways with IPv4 VIPs + off. The summary is re-read uncached (`APIReader`), so it computes from + the write that triggered it. + A failing summary takes the reason every failing node shares, or a + generic one when they differ. Every input is shared state, so every + gateway node computes the same summary and writes it only when it + changes; `clearNodeRuleConditions` recomputes it too, for the last + gateway node to leave. The `NetworkGateway`'s `EngineDegraded` message lists every failed rule. Every rule advertisement carries a `networkRuleLabel` label and a plain (not controller, no `blockOwnerDeletion`) owner reference to its diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 06b1ee934..c7624beb4 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -502,15 +502,15 @@ gateway node, named after that node (see the worked example above). ### `NetworkService` — internal ingress load-balancing spec -| Field | Required | Type | Description | -| ---------------------- | -------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `spec.vpcRef` | Yes | `string` | Opaque VPC identifier (owned by the Galactic cell controller, not validated here beyond non-emptiness). Only attachments whose `status.vpc` equals it can be backends. | -| `spec.vipAddresses` | Yes | `[]string` (1–8) | Ingress VIP addresses this rule provisions: at most one IPv6 and at most one IPv4 address, an IPv4 address in dotted form. See below. | -| `spec.protocol` | Yes | `tcp` \| `udp` | IP protocol load-balanced on `vipAddresses`. The API also accepts `sctp`, `esp`, `gre` and `icmp`, but refuses them as not served yet; see below. | -| `spec.port` | tcp, udp | `int32` (1–65535) | Ingress port on `vipAddresses` this rule load-balances. Required for a protocol with ports, refused for one without. | -| `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. | -| `status.conditions` | — | — | `Accepted` (set `True` once gateway nodes exist in the namespace; not an ownership check, see below), `/Programmed` per gateway node, `/IPv4Served` per gateway node for a rule with an IPv4 VIP, and `/BackendsBound` per node hosting a backend. | +| Field | Required | Type | Description | +| ---------------------- | -------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `spec.vpcRef` | Yes | `string` | Opaque VPC identifier (owned by the Galactic cell controller, not validated here beyond non-emptiness). Only attachments whose `status.vpc` equals it can be backends. | +| `spec.vipAddresses` | Yes | `[]string` (1–8) | Ingress VIP addresses this rule provisions: at most one IPv6 and at most one IPv4 address, an IPv4 address in dotted form. See below. | +| `spec.protocol` | Yes | `tcp` \| `udp` | IP protocol load-balanced on `vipAddresses`. The API also accepts `sctp`, `esp`, `gre` and `icmp`, but refuses them as not served yet; see below. | +| `spec.port` | tcp, udp | `int32` (1–65535) | Ingress port on `vipAddresses` this rule load-balances. Required for a protocol with ports, refused for one without. | +| `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. | +| `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`: @@ -615,13 +615,66 @@ node writes a binding for each of them, pairing the IPv4 `vipAddress` with the IPv6 `backendAddress`, but only while some gateway node reports one of the three loaded reasons for the rule, and deletes them once none does, so a cell whose gateways leave IPv4 VIPs out has no IPv4 bindings or rows. Each gateway -pass removes the `/Programmed` and `/IPv4Served` conditions of any -node that no `NetworkGateway` in the namespace targets, so a gateway that left -without clearing its conditions cannot keep the backend nodes' IPv4 bindings -alive. A node missing from the gateway's cache is confirmed missing with an +pass removes the `/Programmed`, `/Advertised` and +`/IPv4Served` conditions of any node that no `NetworkGateway` in the +namespace targets, so a gateway that left without clearing its conditions +cannot keep the backend nodes' IPv4 bindings alive. A node missing from the gateway's cache is confirmed missing with an uncached read of the API server first, so a new gateway node's conditions are never removed while the cache has yet to see its `NetworkGateway`. +#### Reading a rule's status + +Rule-wide conditions say whether a rule serves, without reading +`NetworkGateway` or knowing which nodes exist. Every gateway node computes them +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 | + +Only gateway nodes with a `/Programmed` condition count. A node +that has not reported, for example one whose datapath is turned off, +advertises nothing and so carries none of the rule's traffic. The +`Programmed` and `Ready` messages say how many registered gateway nodes have +not reported. + +`Ready` leaves out `IPv4Served` while the rule has an IPv6 VIP. IPv4 VIPs are +off on most gateways, and a rule whose IPv6 VIP serves is not down because its +IPv4 VIP is not served. Read `IPv4Served` to see whether the IPv4 VIP serves. + +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. | + +`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. + #### What an IPv4 VIP needs Workloads are IPv6 only. An IPv4 VIP needs nothing from its backends but an diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index dc73430a3..dae16c0a6 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -186,6 +186,24 @@ const ( // reports. reasonIPv4NotAdvertised = "NotAdvertised" + // reasonAdvertised is the per-node Advertised reason, with status True, + // for a rule whose BGPAdvertisements this node published. + reasonAdvertised = "Advertised" + + // reasonNotProgrammed is the per-node Advertised reason for a rule this + // node did not load, so it withdrew the rule's routes. + reasonNotProgrammed = "NotProgrammed" + + // reasonAdvertisementPending is the per-node Advertised reason for a rule + // whose BGPAdvertisements this node published but galactic-router does not + // report advertised yet. + reasonAdvertisementPending = "AdvertisementPending" + + // reasonNoRouter is the per-node Advertised reason for a rule this node + // loaded but cannot advertise, because no BGPRouter targets the node or + // more than one does. + reasonNoRouter = "NoRouter" + // reasonIPv4Advertised is the per-node IPv4Served reason, with status // True, for a rule whose IPv4 VIP this node loaded over only the eligible // backends whose ServiceVIPBinding is Bound, at least one, and advertises. @@ -750,7 +768,8 @@ func (r *NetworkGatewayReconciler) publishRuleOutcomes( // only its Bound backends, at least one (ipv4Loaded), and the rule // loaded. advertiseIPv4 := r.IPv4VIPs && o.ipv4 == ipv4Loaded - advertised := false + var publishErr error + var pending []string switch { case cond.Status != metav1.ConditionTrue: if err := withdrawRuleAdvertisements(ctx, r.Client, o.rule, r.NodeName); err != nil { @@ -761,13 +780,19 @@ func (r *NetworkGatewayReconciler) publishRuleOutcomes( if err := r.applyBGPAdvertisements(ctx, o.rule, o.desired, routerName, advertiseIPv4); err != nil { logger.Error(err, "apply BGPAdvertisements for NetworkService", "networkRule", o.rule.Name) advErrs = append(advErrs, fmt.Errorf("networkRule %s: %w", o.rule.Name, err)) - } else { - advertised = true + publishErr = err + break + } + var err error + if pending, err = r.uninstalledAdvertisements(ctx, o.rule, o.desired, advertiseIPv4); err != nil { + statusErrs = append(statusErrs, fmt.Errorf("networkRule %s: %w", o.rule.Name, err)) } } - ipv4 := ipv4ServedCondition(r.NodeName, o.rule, o.ipv4, cond.Status == metav1.ConditionTrue, advertised) - if err := r.setRuleConditions(ctx, o.rule, cond, ipv4, departed); err != nil { + published := cond.Status == metav1.ConditionTrue && routerName != "" && publishErr == nil + adv := advertisedCondition(r.NodeName, cond.Status == metav1.ConditionTrue, routerName, publishErr, pending) + ipv4 := ipv4ServedCondition(r.NodeName, o.rule, o.ipv4, cond.Status == metav1.ConditionTrue, published) + if err := r.setRuleConditions(ctx, o.rule, cond, adv, ipv4, departed); err != nil { logger.Error(err, "update NetworkService conditions", "networkRule", o.rule.Name) statusErrs = append(statusErrs, fmt.Errorf("networkRule %s status: %w", o.rule.Name, err)) } @@ -812,6 +837,81 @@ func programmedCondition(node string, o ruleOutcome, loadErrs map[string]string) return cond } +// advertisedCondition returns node's Advertised condition for a rule: True +// once node published the rule's BGPAdvertisements and galactic-router reports +// each one advertised, and otherwise False with why. programmed is whether +// node's engine loaded the rule, routerName the BGPRouter the advertisements +// hang off ("" when none targets node, or more than one does), publishErr the +// error from publishing them, and pending the published advertisements not +// reported advertised yet (uninstalledAdvertisements). +func advertisedCondition( + node string, programmed bool, routerName string, publishErr error, pending []string, +) metav1.Condition { + cond := metav1.Condition{ + Type: advertisedConditionType(node), + Status: metav1.ConditionFalse, + Reason: reasonNotProgrammed, + Message: "not advertised from node " + node + ": the rule is not loaded there", + } + switch { + case !programmed: + case publishErr != nil: + cond.Reason = reasonAdvertisementFailed + cond.Message = fmt.Sprintf("not advertised from node %s: %v", node, publishErr) + case routerName == "": + cond.Reason = reasonNoRouter + cond.Message = "not advertised from node " + node + ": no single BGPRouter targets the node" + case len(pending) > 0: + cond.Reason = reasonAdvertisementPending + cond.Message = fmt.Sprintf("published from node %s, but galactic-router does not report %s advertised yet", + node, cappedList(pending)) + default: + cond.Status, cond.Reason = metav1.ConditionTrue, reasonAdvertised + cond.Message = "advertised from node " + node + } + return cond +} + +// uninstalledAdvertisements returns the names of this node's BGPAdvertisements +// for rule that applyBGPAdvertisements published from desired, with the +// IPv4 one only when advertiseIPv4, but that galactic-router does not report +// advertised for their current generation yet. One missing from the cache +// counts as not advertised. +func (r *NetworkGatewayReconciler) uninstalledAdvertisements( + ctx context.Context, rule *bgpv1alpha1.NetworkService, desired gateway.DesiredRule, advertiseIPv4 bool, +) ([]string, error) { + v4, v6 := prefixesByFamily(desired.VIPAddresses) + var families []string + if advertiseIPv4 && len(v4) > 0 { + families = append(families, "v4") + } + if len(v6) > 0 { + families = append(families, "v6") + } + var pending []string + for _, family := range families { + name := ruleAdvertisementName(rule.Name, r.NodeName, family) + adv := &bgpv1alpha1.BGPAdvertisement{} + err := r.Get(ctx, types.NamespacedName{Namespace: rule.Namespace, Name: name}, adv) + switch { + case apierrors.IsNotFound(err): + pending = append(pending, name) + case err != nil: + return nil, fmt.Errorf("get BGPAdvertisement %s: %w", name, err) + case !advertisementInstalled(adv): + pending = append(pending, name) + } + } + return pending, nil +} + +// advertisementInstalled reports whether galactic-router reports adv +// advertised for its current generation. +func advertisementInstalled(adv *bgpv1alpha1.BGPAdvertisement) bool { + c := meta.FindStatusCondition(adv.Status.Conditions, ConditionAdvertised) + return c != nil && c.Status == metav1.ConditionTrue && c.ObservedGeneration == adv.Generation +} + // cappedList joins the first maxReadyFailures items with ", ", followed by a // count of the rest, so a long list stays under the metav1.Condition message // limit. @@ -877,6 +977,13 @@ func programmedConditionType(node string) string { return node + "/" + bgpv1alpha1.ConditionTypeProgrammed } +// advertisedConditionType returns the NetworkService condition type that +// records whether node published the rule's routes. Like +// programmedConditionType, each gateway node owns its own. +func advertisedConditionType(node string) string { + return node + "/" + conditionTypeAdvertised +} + // ipv4ServedConditionType returns the NetworkService condition type that records // whether node serves the rule's IPv4 VIPs. Like programmedConditionType, each // gateway node owns its own. @@ -888,6 +995,11 @@ func ipv4ServedConditionType(node string) string { // type. const conditionTypeIPv4Served = "IPv4Served" +// conditionTypeAdvertised is the suffix of every gateway node's Advertised +// condition type, and the type of the rule's summary of them +// (summaryConditions). +const conditionTypeAdvertised = "Advertised" + // ipv4ServedCondition returns node's IPv4Served condition for rule, or nil // when rule has no IPv4 VIP, in which case the condition is removed. Its // reason says what became of the IPv4 VIP on node: ipv4 from buildDesiredRule, @@ -916,7 +1028,7 @@ func ipv4ServedCondition( } reason = reasonIPv4NotAdvertised message = fmt.Sprintf("IPv4 VIP is loaded on node %s but its route is not published: no BGPRouter "+ - "targets the node or the advertisement failed; the NetworkGateway's Ready condition says which", node) + "targets the node or the advertisement failed; the node's Advertised condition says which", node) case ipv4Unbound: reason = reasonIPv4BindingsNotBound message = fmt.Sprintf("IPv4 VIP is loaded on node %s but not advertised: none of its backends' "+ @@ -946,23 +1058,23 @@ func ipv4ServedCondition( } } -// setRuleConditions writes programmed and, when non-nil, ipv4 to rule's -// status in one update, and removes node's IPv4Served condition when ipv4 is -// nil. In the same update it removes the Programmed and IPv4Served conditions -// of every node in departed (departedGatewayNodes), so a gateway node that -// left without its conditions being cleared, for example while no other -// gateway was running to see its NetworkGateway go, cannot keep a stale -// IPv4Served condition telling the backend nodes to keep their IPv4 bindings -// (ipv4LoadedOnSomeNode). It skips the write when nothing changed. Every write fans out to every -// gateway node through the NetworkService watch, so an unconditional write would -// never settle. +// setRuleConditions writes programmed, advertised and, when non-nil, ipv4 to +// rule's status in one update, and removes node's IPv4Served condition when +// ipv4 is nil. In the same update it removes the Programmed, Advertised and +// IPv4Served conditions of every node in departed (departedGatewayNodes), so a +// gateway node that left without its conditions being cleared, for example +// while no other gateway was running to see its NetworkGateway go, cannot keep +// a stale IPv4Served condition telling the backend nodes to keep their IPv4 +// bindings (ipv4LoadedOnSomeNode). It skips the write when nothing changed. +// Every write fans out to every gateway node through the NetworkService watch, +// so an unconditional write would never settle. // // Every gateway node and NetworkServiceReconciler write the same status, so a // write retries on conflict against a fresh read. A rule deleted mid-pass // has nothing left to record and counts as success. func (r *NetworkGatewayReconciler) setRuleConditions( - ctx context.Context, rule *bgpv1alpha1.NetworkService, programmed metav1.Condition, ipv4 *metav1.Condition, - departed map[string]bool, + ctx context.Context, rule *bgpv1alpha1.NetworkService, programmed, advertised metav1.Condition, + ipv4 *metav1.Condition, departed map[string]bool, ) error { key := client.ObjectKeyFromObject(rule) err := retry.RetryOnConflict(retry.DefaultRetry, func() error { @@ -973,6 +1085,9 @@ func (r *NetworkGatewayReconciler) setRuleConditions( c := programmed c.ObservedGeneration = current.Generation changed := meta.SetStatusCondition(¤t.Status.Conditions, c) + a := advertised + a.ObservedGeneration = current.Generation + changed = meta.SetStatusCondition(¤t.Status.Conditions, a) || changed if ipv4 != nil { c4 := *ipv4 c4.ObservedGeneration = current.Generation @@ -992,10 +1107,10 @@ func (r *NetworkGatewayReconciler) setRuleConditions( return err } -// removeDepartedNodeConditions removes from conditions the Programmed and -// IPv4Served condition of every node in departed, and reports whether it -// removed any. Other node-scoped conditions, such as a backend node's -// BackendsBound, are left alone. +// removeDepartedNodeConditions removes from conditions the Programmed, +// Advertised and IPv4Served conditions of every node in departed, and reports +// whether it removed any. Other node-scoped conditions, such as a backend +// node's BackendsBound, are left alone. func removeDepartedNodeConditions(conditions *[]metav1.Condition, departed map[string]bool) bool { var gone []string for _, c := range *conditions { @@ -1009,18 +1124,19 @@ func removeDepartedNodeConditions(conditions *[]metav1.Condition, departed map[s return len(gone) > 0 } -// gatewayNodeConditionNode returns the node of a gateway node's Programmed or -// IPv4Served condition type, and false for any other type. +// gatewayNodeConditionNode returns the node of a gateway node's Programmed, +// Advertised or IPv4Served condition type, and false for any other type. func gatewayNodeConditionNode(condType string) (string, bool) { node, kind, ok := strings.Cut(condType, "/") - if !ok || (kind != bgpv1alpha1.ConditionTypeProgrammed && kind != conditionTypeIPv4Served) { + if !ok || (kind != bgpv1alpha1.ConditionTypeProgrammed && kind != conditionTypeAdvertised && + kind != conditionTypeIPv4Served) { return "", false } return node, true } -// departedGatewayNodes returns the nodes other than this one whose Programmed -// or IPv4Served condition some rule in outcomes carries but that no +// departedGatewayNodes returns the nodes other than this one whose Programmed, +// Advertised or IPv4Served condition some rule in outcomes carries but that no // NetworkGateway in namespace targets. A node missing from the cached // NetworkGateway list is confirmed against the API server through APIReader // before it counts, so a cache that has not yet seen a new gateway node's @@ -1059,15 +1175,21 @@ func (r *NetworkGatewayReconciler) departedGatewayNodes( return candidates, nil } -// clearNodeRuleConditions removes node's Programmed and IPv4Served +// clearNodeRuleConditions removes node's Programmed, Advertised and IPv4Served // conditions from every NetworkService in namespace, for a node that no longer -// serves any of them. A write retries on conflict against a fresh read, and a -// rule deleted mid-pass counts as cleared. +// serves any of them, and recomputes the rule's summary conditions in the same +// write: when node was the last gateway node, no reconciler is left to do it. +// A write retries on conflict against a fresh read, and a rule deleted +// mid-pass counts as cleared. func clearNodeRuleConditions(ctx context.Context, c client.Client, namespace, node string) error { list := &bgpv1alpha1.NetworkServiceList{} if err := c.List(ctx, list, client.InNamespace(namespace)); err != nil { return fmt.Errorf("list NetworkServices to clear node %s conditions: %w", node, err) } + nodes, err := gatewayNodeNames(ctx, c, namespace) + if err != nil { + return fmt.Errorf("list gateway nodes to clear node %s conditions: %w", node, err) + } var errs []error for i := range list.Items { key := client.ObjectKeyFromObject(&list.Items[i]) @@ -1077,10 +1199,14 @@ func clearNodeRuleConditions(ctx context.Context, c client.Client, namespace, no return err } removed := meta.RemoveStatusCondition(¤t.Status.Conditions, programmedConditionType(node)) + removed = meta.RemoveStatusCondition(¤t.Status.Conditions, advertisedConditionType(node)) || removed removed = meta.RemoveStatusCondition(¤t.Status.Conditions, ipv4ServedConditionType(node)) || removed if !removed { return nil } + if current.DeletionTimestamp.IsZero() { + applySummaryConditions(current, nodes) + } return c.Status().Update(ctx, current) }) if err != nil && !apierrors.IsNotFound(err) { @@ -1703,7 +1829,10 @@ func (r *NetworkGatewayReconciler) SetupWithManager(mgr ctrl.Manager) error { // // The gateway's own VIP advertisements carry networkRuleLabel and neither // field. Their creates come from this reconciler and are dropped, but a delete -// or a spec edit passes, so the next pass restores what was lost. +// or a spec edit passes, so the next pass restores what was lost. So does a +// status write that changes whether galactic-router reports one advertised +// (installedChanged), which the node's Advertised condition on the rule +// follows. func backendAdvertisementPredicate() predicate.Predicate { return predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { return locatesBackend(e.Object) }, @@ -1715,7 +1844,10 @@ func backendAdvertisementPredicate() predicate.Predicate { return false } if e.ObjectOld.GetGeneration() == e.ObjectNew.GetGeneration() { - return false + // A status write matters only when it changes whether a rule + // advertisement is installed, which its gateway node reports + // on the rule's Advertised condition. + return isRuleAdvertisement(e.ObjectNew) && installedChanged(e.ObjectOld, e.ObjectNew) } return locatesBackend(e.ObjectOld) || locatesBackend(e.ObjectNew) || isRuleAdvertisement(e.ObjectOld) || isRuleAdvertisement(e.ObjectNew) @@ -1724,6 +1856,14 @@ func backendAdvertisementPredicate() predicate.Predicate { } } +// installedChanged reports whether old and updated, two versions of one +// BGPAdvertisement, differ in advertisementInstalled. +func installedChanged(old, updated client.Object) bool { + o, ok1 := old.(*bgpv1alpha1.BGPAdvertisement) + n, ok2 := updated.(*bgpv1alpha1.BGPAdvertisement) + return ok1 && ok2 && advertisementInstalled(o) != advertisementInstalled(n) +} + // locatesBackend reports whether obj is a BGPAdvertisement buildBackendSIDIndex // would consider: one carrying both a VRFID and a Function. func locatesBackend(obj client.Object) bool { diff --git a/internal/controller/networkgateway_controller_test.go b/internal/controller/networkgateway_controller_test.go index 14b7e1a37..b4496f4f9 100644 --- a/internal/controller/networkgateway_controller_test.go +++ b/internal/controller/networkgateway_controller_test.go @@ -25,6 +25,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/event" cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" @@ -192,6 +193,24 @@ func assertRuleProgrammed(t *testing.T, c client.Client, status metav1.Condition } } +// assertRuleAdvertised fails the test unless testNodeGWA's Advertised +// condition on testRuleName has the given status and reason. +func assertRuleAdvertised(t *testing.T, c client.Client, status metav1.ConditionStatus, reason string) { + t.Helper() + rule := &bgpv1alpha1.NetworkService{} + if err := c.Get(context.Background(), testRuleKey(testRuleName), rule); err != nil { + t.Fatalf("get NetworkService %s: %v", testRuleName, err) + } + cond := meta.FindStatusCondition(rule.Status.Conditions, advertisedConditionType(testNodeGWA)) + if cond == nil { + t.Fatalf("NetworkService %s has no %s condition", testRuleName, advertisedConditionType(testNodeGWA)) + } + if cond.Status != status || cond.Reason != reason { + t.Errorf("NetworkService %s %s = %s/%s, want %s/%s", + testRuleName, cond.Type, cond.Status, cond.Reason, status, reason) + } +} + func TestNetworkGatewayReconciler_SkipsNonMatchingNode(t *testing.T) { scheme := newRuleTestScheme(t) gw := newTestGateway(testNodeGWA) @@ -742,6 +761,7 @@ func TestNetworkGatewayReconciler_SkipsBGPAdvertisementWiringWithoutRouter(t *te if len(advList.Items) != 1 { t.Fatalf("expected only the pre-seeded backend BGPAdvertisement, got %d", len(advList.Items)) } + assertRuleAdvertised(t, fakeClient, metav1.ConditionFalse, reasonNoRouter) } // TestNetworkGatewayReconciler_CreatesBGPAdvertisement covers the anycast @@ -904,6 +924,10 @@ func TestNetworkGatewayReconciler_AdvertisementFailureSurfaces(t *testing.T) { if !strings.Contains(cond.Message, testRuleName) { t.Errorf("Ready message = %q, want it to name the failing NetworkService %q", cond.Message, testRuleName) } + // The failure is on the rule too, so a reader of the rule alone sees it + // (#708). + assertRuleProgrammed(t, fakeClient, metav1.ConditionTrue, reasonProgrammed) + assertRuleAdvertised(t, fakeClient, metav1.ConditionFalse, reasonAdvertisementFailed) } // TestNetworkGatewayReconciler_ReportsEngineHealthyOnCleanPass is the @@ -919,7 +943,7 @@ func TestNetworkGatewayReconciler_ReportsEngineHealthyOnCleanPass(t *testing.T) acceptRule(rule) fakeClient := newIndexedClientBuilder(scheme). - WithStatusSubresource(&bgpv1alpha1.NetworkGateway{}, &bgpv1alpha1.NetworkService{}). + WithStatusSubresource(&bgpv1alpha1.NetworkGateway{}, &bgpv1alpha1.NetworkService{}, &bgpv1alpha1.BGPAdvertisement{}). WithObjects(gwA, router, backendRouter, backendAdv, backendVRF, newBackendAttachment("vpc-1"), rule). Build() @@ -944,6 +968,72 @@ func TestNetworkGatewayReconciler_ReportsEngineHealthyOnCleanPass(t *testing.T) t.Errorf("Ready reason = %q, want %q", cond.Reason, reasonEngineHealthy) } assertRuleProgrammed(t, fakeClient, metav1.ConditionTrue, reasonProgrammed) + // Published, but no galactic-router has reported the route advertised. + assertRuleAdvertised(t, fakeClient, metav1.ConditionFalse, reasonAdvertisementPending) + + markAdvertised(t, fakeClient, testRuleAdv) + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatalf("second Reconcile: unexpected error: %v", err) + } + assertRuleAdvertised(t, fakeClient, metav1.ConditionTrue, reasonAdvertised) +} + +// markAdvertised sets the named BGPAdvertisement's Advertised condition True +// for its current generation, as galactic-router does once GoBGP carries it. +func markAdvertised(t *testing.T, c client.Client, name string) { + t.Helper() + adv := &bgpv1alpha1.BGPAdvertisement{} + if err := c.Get(context.Background(), testRuleKey(name), adv); err != nil { + t.Fatalf("get BGPAdvertisement %s: %v", name, err) + } + meta.SetStatusCondition(&adv.Status.Conditions, metav1.Condition{ + Type: ConditionAdvertised, Status: metav1.ConditionTrue, Reason: reasonAdvertised, + ObservedGeneration: adv.Generation, + }) + if err := c.Status().Update(context.Background(), adv); err != nil { + t.Fatalf("update BGPAdvertisement %s status: %v", name, err) + } +} + +// TestBackendAdvertisementPredicate_RuleAdvertisementInstalled checks a +// status write that changes whether a rule advertisement is installed wakes +// the gateway, and one that changes nothing else does not. +func TestBackendAdvertisementPredicate_RuleAdvertisementInstalled(t *testing.T) { + old := newNodeAdvertisement(testRuleName, testNodeGWA, "v6") + old.Generation = 2 + installed := old.DeepCopy() + meta.SetStatusCondition(&installed.Status.Conditions, metav1.Condition{ + Type: ConditionAdvertised, Status: metav1.ConditionTrue, Reason: reasonAdvertised, ObservedGeneration: 2, + }) + stale := old.DeepCopy() + meta.SetStatusCondition(&stale.Status.Conditions, metav1.Condition{ + Type: ConditionAdvertised, Status: metav1.ConditionTrue, Reason: reasonAdvertised, ObservedGeneration: 1, + }) + backend := newAdvertisement("backend") + backendInstalled := backend.DeepCopy() + meta.SetStatusCondition(&backendInstalled.Status.Conditions, metav1.Condition{ + Type: ConditionAdvertised, Status: metav1.ConditionTrue, Reason: reasonAdvertised, + }) + + p := backendAdvertisementPredicate() + tests := []struct { + name string + old, new client.Object + want bool + }{ + {"rule advertisement installed", old, installed, true}, + {"rule advertisement withdrawn", installed, old, true}, + {"installed for an older generation only", old, stale, false}, + {"unrelated status write", installed, installed.DeepCopy(), false}, + {"backend advertisement status", backend, backendInstalled, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := p.Update(event.UpdateEvent{ObjectOld: tt.old, ObjectNew: tt.new}); got != tt.want { + t.Errorf("Update = %v, want %v", got, tt.want) + } + }) + } } // errLoadQuota is the load failure the #712 regression tests make the fake @@ -1491,6 +1581,9 @@ func TestNetworkGatewayReconciler_ClearsDepartedNodeProgrammedCondition(t *testi meta.SetStatusCondition(&rule.Status.Conditions, metav1.Condition{ Type: programmedConditionType(node), Status: metav1.ConditionTrue, Reason: reasonProgrammed, }) + meta.SetStatusCondition(&rule.Status.Conditions, metav1.Condition{ + Type: advertisedConditionType(node), Status: metav1.ConditionTrue, Reason: reasonAdvertised, + }) } fakeClient := newIndexedClientBuilder(scheme). @@ -1511,6 +1604,9 @@ func TestNetworkGatewayReconciler_ClearsDepartedNodeProgrammedCondition(t *testi if meta.FindStatusCondition(got.Status.Conditions, programmedConditionType(testNodeGWB)) != nil { t.Errorf("departed node %s's condition is still on NetworkService %s", testNodeGWB, testRuleName) } + if meta.FindStatusCondition(got.Status.Conditions, advertisedConditionType(testNodeGWB)) != nil { + t.Errorf("departed node %s's Advertised condition is still on NetworkService %s", testNodeGWB, testRuleName) + } if meta.FindStatusCondition(got.Status.Conditions, programmedConditionType(testNodeGWA)) == nil { t.Errorf("surviving node %s's condition was removed from NetworkService %s", testNodeGWA, testRuleName) } diff --git a/internal/controller/networkservice_controller.go b/internal/controller/networkservice_controller.go index 8eb41b2ce..f312101ab 100644 --- a/internal/controller/networkservice_controller.go +++ b/internal/controller/networkservice_controller.go @@ -83,8 +83,9 @@ func gatewayNodeLabelValue(nodeName string) string { // NetworkServiceReconciler owns the per-object NetworkService lifecycle that // NetworkGatewayReconciler's aggregate, list-driven loop is the wrong place -// for: setting the Accepted condition once gateway nodes exist, and the -// finalizer-guarded teardown ordering on deletion. +// for: setting the Accepted condition once gateway nodes exist, the +// rule-wide summary conditions (summaryConditions), and the finalizer-guarded +// teardown ordering on deletion. // // That is a deliberate divergence from the no-op reconcilers elsewhere here, // which exist only as watch sources. Those objects have no per-object lifecycle @@ -110,7 +111,8 @@ type NetworkServiceReconciler struct { // again after it found an advertisement its cache had missed. const staleAdvertisementRequeue = time.Second -// Reconcile reconciles one NetworkService's finalizer and Accepted condition. +// Reconcile reconciles one NetworkService's finalizer, Accepted condition and +// summary conditions. // Engine convergence and advertisement wiring for accepted rules happen in // NetworkGatewayReconciler, which watches NetworkService and re-lists on every // change, so this reconciler never touches the gateway engine. @@ -146,6 +148,9 @@ func (r *NetworkServiceReconciler) Reconcile(ctx context.Context, req ctrl.Reque if err := r.updateAcceptedCondition(ctx, rule); err != nil { return ctrl.Result{}, fmt.Errorf("update Accepted condition for NetworkService %s: %w", req.NamespacedName, err) } + if err := updateSummaryConditions(ctx, r.Client, r.APIReader, req.NamespacedName); err != nil { + return ctrl.Result{}, fmt.Errorf("update summary conditions for NetworkService %s: %w", req.NamespacedName, err) + } return ctrl.Result{}, nil } diff --git a/internal/controller/networkservice_summary.go b/internal/controller/networkservice_summary.go new file mode 100644 index 000000000..e4644c86e --- /dev/null +++ b/internal/controller/networkservice_summary.go @@ -0,0 +1,398 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "fmt" + "net/netip" + "sort" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" +) + +// conditionTypeBackendsReady is the rule-wide condition summarizing whether +// every backend can be reached and answer on the rule's VIPs. +const conditionTypeBackendsReady = "BackendsReady" + +// Summary condition reasons. A summary that is not True takes the reason every +// failing node agrees on, so a tenant sees InvalidRule or BackendsClaimed +// rather than a generic one; these are the reasons used otherwise. +const ( + // reasonPending is the summary reason while no node has reported for the + // rule's current generation. + reasonPending = "Pending" + + // reasonNoGatewayNodes is the summary reason while no NetworkGateway in the + // rule's namespace reports on it. + reasonNoGatewayNodes = "NoGatewayNodes" + + // reasonNotAdvertised is the Advertised summary reason when the nodes that + // did not advertise the rule disagree on why. + reasonNotAdvertised = "NotAdvertised" + + // reasonIPv4NotServed is the IPv4Served summary reason when the nodes that + // do not serve the rule's IPv4 VIP disagree on why. + reasonIPv4NotServed = "NotServed" + + // reasonBackendsReady is the BackendsReady reason, with status True, once + // every backend node bound its backends and every gateway node resolved + // them. + reasonBackendsReady = "BackendsReady" + + // reasonBackendsNotReady is the BackendsReady reason when the nodes + // reporting a backend problem disagree on what it is. + reasonBackendsNotReady = "BackendsNotReady" + + // reasonReady is the Ready reason, with status True. + reasonReady = "Ready" +) + +// vipFamilies records which address families a rule's VIPs cover. +type vipFamilies struct { + ipv4, ipv6 bool +} + +// ruleVIPFamilies returns which address families rule's VIPs cover. An +// IPv4-mapped IPv6 address counts as IPv4, as it does for the datapath. +func ruleVIPFamilies(rule *bgpv1alpha1.NetworkService) vipFamilies { + var f vipFamilies + for _, v := range rule.Spec.VIPAddresses { + addr, err := netip.ParseAddr(v) + switch { + case err != nil: + case isIPv4VIP(addr): + f.ipv4 = true + default: + f.ipv6 = true + } + } + return f +} + +// nodeReport is one node's failing condition, as a summary lists it. +type nodeReport struct { + node, reason string +} + +// summaryConditions returns the rule-wide Programmed, Advertised, +// BackendsReady and Ready conditions, plus IPv4Served when the rule has an +// IPv4 VIP, for a rule with conditions at generation, VIPs of families, and +// served by the gateway nodes in gatewayNodes. They summarize the per-node +// conditions every gateway and backend node writes, so a client such as the +// tenant-facing API can tell whether the rule serves without reading +// NetworkGateway or knowing which nodes exist. +// +// Every input is shared state, so every writer computes the same result. +// Only gateway nodes that report a Programmed condition count: a node that +// has not reported yet, or whose datapath is turned off, advertises nothing, +// so it carries none of the rule's traffic. Programmed and Ready say how many +// registered nodes have not reported. A per-node condition from an older +// generation counts as not reported. +// +// Advertised covers the routes a node published. Whether the IPv4 VIP is +// served is IPv4Served's alone, and Ready reads it only for a rule with no +// IPv6 VIP: IPv4 VIPs are off on most gateways, and a rule whose IPv6 VIP +// serves must not read as down because its IPv4 VIP does not. +func summaryConditions( + conditions []metav1.Condition, generation int64, families vipFamilies, gatewayNodes []string, +) []metav1.Condition { + current := func(condType string) *metav1.Condition { + c := meta.FindStatusCondition(conditions, condType) + if c == nil || c.ObservedGeneration != generation { + return nil + } + return c + } + + nodes := sortedUnique(gatewayNodes) + + var reporting, programmed []string + var notProgrammed []nodeReport + for _, n := range nodes { + c := current(programmedConditionType(n)) + if c == nil { + continue + } + reporting = append(reporting, n) + if c.Status == metav1.ConditionTrue { + programmed = append(programmed, n) + } else { + notProgrammed = append(notProgrammed, nodeReport{n, c.Reason}) + } + } + unreported := "" + if silent := len(nodes) - len(reporting); silent > 0 { + unreported = fmt.Sprintf("; %d of %d registered gateway nodes have not reported", silent, len(nodes)) + } + + programmedCond := metav1.Condition{Type: bgpv1alpha1.ConditionTypeProgrammed} + switch { + case len(nodes) == 0: + programmedCond.Status, programmedCond.Reason = metav1.ConditionFalse, reasonNoGatewayNodes + programmedCond.Message = "no NetworkGateway nodes are registered in this namespace" + case len(reporting) == 0: + programmedCond.Status, programmedCond.Reason = metav1.ConditionFalse, reasonPending + programmedCond.Message = "no gateway node has loaded this generation yet" + case len(notProgrammed) == 0: + programmedCond.Status, programmedCond.Reason = metav1.ConditionTrue, reasonProgrammed + programmedCond.Message = fmt.Sprintf("loaded on %d of %d reporting gateway nodes%s", + len(programmed), len(reporting), unreported) + default: + programmedCond.Status = metav1.ConditionFalse + programmedCond.Reason = commonReason(notProgrammed, reasonNotProgrammed) + programmedCond.Message = fmt.Sprintf("loaded on %d of %d reporting gateway nodes%s; not loaded on %s", + len(programmed), len(reporting), unreported, reportList(notProgrammed)) + } + + // Only a node that loaded the rule is expected to advertise it. + var advertising int + var notAdvertised []nodeReport + for _, n := range programmed { + switch c := current(advertisedConditionType(n)); { + case c == nil: + notAdvertised = append(notAdvertised, nodeReport{n, reasonPending}) + case c.Status != metav1.ConditionTrue: + notAdvertised = append(notAdvertised, nodeReport{n, c.Reason}) + default: + advertising++ + } + } + + advertisedCond := metav1.Condition{Type: conditionTypeAdvertised} + switch { + case len(programmed) == 0: + advertisedCond.Status, advertisedCond.Reason = metav1.ConditionFalse, reasonNotProgrammed + advertisedCond.Message = "no gateway node has loaded the rule, so none advertises it" + case len(notAdvertised) == 0: + advertisedCond.Status, advertisedCond.Reason = metav1.ConditionTrue, reasonAdvertised + advertisedCond.Message = fmt.Sprintf("advertised from %d of %d gateway nodes that loaded it", + advertising, len(programmed)) + default: + advertisedCond.Status = metav1.ConditionFalse + advertisedCond.Reason = commonReason(notAdvertised, reasonNotAdvertised) + advertisedCond.Message = fmt.Sprintf("advertised from %d of %d gateway nodes that loaded it; not from %s", + advertising, len(programmed), reportList(notAdvertised)) + } + + backendsCond := backendsReadyCondition(conditions, generation, programmed) + + out := []metav1.Condition{programmedCond, advertisedCond, backendsCond} + gate := []metav1.Condition{acceptedGate(current), programmedCond, advertisedCond, backendsCond} + if families.ipv4 { + ipv4Cond := ipv4ServedSummary(current, programmed) + out = append(out, ipv4Cond) + if !families.ipv6 { + gate = append(gate, ipv4Cond) + } + } + + readyCond := metav1.Condition{ + Type: bgpv1alpha1.ConditionTypeReady, Status: metav1.ConditionTrue, + Reason: reasonReady, Message: "the rule is loaded, advertised and its backends are ready" + unreported, + } + for _, c := range gate { + if c.Status != metav1.ConditionTrue { + readyCond.Status, readyCond.Reason = metav1.ConditionFalse, c.Reason + readyCond.Message = c.Type + ": " + c.Message + break + } + } + out = append(out, readyCond) + + for i := range out { + out[i].ObservedGeneration = generation + } + return out +} + +// acceptedGate returns the rule's Accepted condition for Ready to gate on, or +// a False Pending one when it is missing or from an older generation, so a +// spec edit is never reported Ready before it is accepted. +func acceptedGate(current func(string) *metav1.Condition) metav1.Condition { + if c := current(bgpv1alpha1.ConditionTypeAccepted); c != nil { + return *c + } + return metav1.Condition{ + Type: bgpv1alpha1.ConditionTypeAccepted, Status: metav1.ConditionFalse, + Reason: reasonPending, Message: "not accepted for this generation yet", + } +} + +// ipv4ServedSummary returns the rule-wide IPv4Served condition: True once +// every gateway node in programmed serves the rule's IPv4 VIP, and otherwise +// False with the reason those that do not share. +func ipv4ServedSummary(current func(string) *metav1.Condition, programmed []string) metav1.Condition { + cond := metav1.Condition{Type: conditionTypeIPv4Served} + var serving int + var notServed []nodeReport + for _, n := range programmed { + switch c := current(ipv4ServedConditionType(n)); { + case c == nil: + notServed = append(notServed, nodeReport{n, reasonPending}) + case c.Status != metav1.ConditionTrue: + notServed = append(notServed, nodeReport{n, c.Reason}) + default: + serving++ + } + } + switch { + case len(programmed) == 0: + cond.Status, cond.Reason = metav1.ConditionFalse, reasonNotProgrammed + cond.Message = "no gateway node has loaded the rule, so none serves its IPv4 VIP" + case len(notServed) == 0: + cond.Status, cond.Reason = metav1.ConditionTrue, reasonIPv4Advertised + cond.Message = fmt.Sprintf("IPv4 VIP served from %d of %d gateway nodes that loaded the rule", + serving, len(programmed)) + default: + cond.Status = metav1.ConditionFalse + cond.Reason = commonReason(notServed, reasonIPv4NotServed) + cond.Message = fmt.Sprintf("IPv4 VIP served from %d of %d gateway nodes that loaded the rule; not from %s", + serving, len(programmed), reportList(notServed)) + } + return cond +} + +// 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. +// +// 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. +func backendsReadyCondition(conditions []metav1.Condition, generation int64, programmed []string) metav1.Condition { + cond := metav1.Condition{Type: conditionTypeBackendsReady} + + var bound int + var problems []nodeReport + for _, c := range conditions { + node, ok := strings.CutSuffix(c.Type, "/"+conditionTypeBackendsBound) + if !ok { + continue + } + switch { + case c.ObservedGeneration != generation: + problems = append(problems, nodeReport{node, reasonPending}) + case c.Status != metav1.ConditionTrue: + problems = append(problems, nodeReport{node, c.Reason}) + default: + bound++ + } + } + for _, n := range programmed { + c := meta.FindStatusCondition(conditions, programmedConditionType(n)) + if c != nil && c.Reason == reasonBackendsUnresolved { + problems = append(problems, nodeReport{n, reasonBackendsUnresolved}) + } + } + sort.Slice(problems, func(i, j int) bool { + if problems[i].node != problems[j].node { + return problems[i].node < problems[j].node + } + return problems[i].reason < problems[j].reason + }) + + switch { + case len(problems) > 0: + cond.Status = metav1.ConditionFalse + cond.Reason = commonReason(problems, reasonBackendsNotReady) + cond.Message = "backends not ready on " + reportList(problems) + case bound == 0: + cond.Status, cond.Reason = metav1.ConditionFalse, reasonPending + cond.Message = "no backend node has bound the rule's backends yet" + default: + cond.Status, cond.Reason = metav1.ConditionTrue, reasonBackendsReady + cond.Message = fmt.Sprintf("backends bound on %d nodes", bound) + } + return cond +} + +// sortedUnique returns names sorted with duplicates removed, so two +// NetworkGateways targeting one node count it once. +func sortedUnique(names []string) []string { + out := append([]string(nil), names...) + sort.Strings(out) + n := 0 + for i, name := range out { + if i == 0 || name != out[n-1] { + out[n] = name + n++ + } + } + return out[:n] +} + +// commonReason returns the reason every report shares, or fallback when they +// differ. +func commonReason(reports []nodeReport, fallback string) string { + for _, r := range reports[1:] { + if r.reason != reports[0].reason { + return fallback + } + } + return reports[0].reason +} + +// reportList renders reports as "node (reason)", capped by cappedList. +func reportList(reports []nodeReport) string { + items := make([]string, len(reports)) + for i, r := range reports { + items[i] = r.node + " (" + r.reason + ")" + } + return cappedList(items) +} + +// applySummaryConditions sets rule's summary conditions (summaryConditions) on +// its status, removes a rule-wide IPv4Served the rule no longer needs, and +// reports whether anything changed. +func applySummaryConditions(rule *bgpv1alpha1.NetworkService, gatewayNodes []string) bool { + families := ruleVIPFamilies(rule) + conds := &rule.Status.Conditions + changed := false + for _, c := range summaryConditions(*conds, rule.Generation, families, gatewayNodes) { + changed = meta.SetStatusCondition(conds, c) || changed + } + if !families.ipv4 { + changed = meta.RemoveStatusCondition(conds, conditionTypeIPv4Served) || changed + } + return changed +} + +// updateSummaryConditions recomputes key's summary conditions and writes them +// only when they changed. Every node writing the rule's status triggers this +// through the NetworkService watch, so an unconditional write would never +// settle. It reads through reader, uncached, so it computes from the write +// that triggered it rather than a cache that has not seen it yet. A rule being +// deleted is left alone, as is one deleted mid-pass. +func updateSummaryConditions(ctx context.Context, c client.Client, reader client.Reader, key client.ObjectKey) error { + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + current := &bgpv1alpha1.NetworkService{} + if err := reader.Get(ctx, key, current); err != nil { + return err + } + if !current.DeletionTimestamp.IsZero() { + return nil + } + nodes, err := gatewayNodeNames(ctx, c, current.Namespace) + if err != nil { + return err + } + if !applySummaryConditions(current, nodes) { + return nil + } + return c.Status().Update(ctx, current) + }) + if apierrors.IsNotFound(err) { + return nil + } + return err +} diff --git a/internal/controller/networkservice_summary_test.go b/internal/controller/networkservice_summary_test.go new file mode 100644 index 000000000..1e6912f05 --- /dev/null +++ b/internal/controller/networkservice_summary_test.go @@ -0,0 +1,522 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "errors" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" +) + +// summaryGen is the rule generation the summary tests report against. +const summaryGen = 3 + +// testBackendNode is the backend node whose BackendsBound condition the +// summary tests write. +const testBackendNode = "compute-1" + +// cond returns a condition of condType at summaryGen. +func cond(condType string, status metav1.ConditionStatus, reason string) metav1.Condition { + return metav1.Condition{Type: condType, Status: status, Reason: reason, ObservedGeneration: summaryGen} +} + +// servingConditions returns the conditions of a rule every node in nodes +// loads and advertises, with its backends bound on testBackendNode. +func servingConditions(nodes ...string) []metav1.Condition { + conds := make([]metav1.Condition, 0, 2+2*len(nodes)) + conds = append(conds, + cond(bgpv1alpha1.ConditionTypeAccepted, metav1.ConditionTrue, reasonGatewayNodesRegistered), + cond(backendsBoundConditionType(testBackendNode), metav1.ConditionTrue, reasonBindingsBound)) + for _, n := range nodes { + conds = append(conds, + cond(programmedConditionType(n), metav1.ConditionTrue, reasonProgrammed), + cond(advertisedConditionType(n), metav1.ConditionTrue, reasonAdvertised)) + } + return conds +} + +// with returns conds with c set over any condition of the same type. +func with(conds []metav1.Condition, c ...metav1.Condition) []metav1.Condition { + out := append([]metav1.Condition(nil), conds...) + for _, x := range c { + meta.SetStatusCondition(&out, x) + } + return out +} + +// without returns conds without the condition of condType. +func without(conds []metav1.Condition, condType string) []metav1.Condition { + out := append([]metav1.Condition(nil), conds...) + meta.RemoveStatusCondition(&out, condType) + return out +} + +// TestSummaryConditions covers the rule-wide conditions a client reads to tell +// whether a rule serves, without reading NetworkGateway (#708). +func TestSummaryConditions(t *testing.T) { + nodes := []string{testNodeGWA, testNodeGWB} + serving := servingConditions(testNodeGWA, testNodeGWB) + + type want struct { + status metav1.ConditionStatus + reason string + } + dualStack := vipFamilies{ipv4: true, ipv6: true} + ipv4Only := vipFamilies{ipv4: true} + tests := []struct { + name string + conditions []metav1.Condition + families vipFamilies + gatewayNodes []string + want map[string]want + }{ + { + name: "every node serves", conditions: serving, gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + conditionTypeAdvertised: {metav1.ConditionTrue, reasonAdvertised}, + conditionTypeBackendsReady: {metav1.ConditionTrue, reasonBackendsReady}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionTrue, reasonReady}, + }, + }, + { + name: "no gateway nodes", conditions: serving, gatewayNodes: nil, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionFalse, reasonNoGatewayNodes}, + conditionTypeAdvertised: {metav1.ConditionFalse, reasonNotProgrammed}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonNoGatewayNodes}, + }, + }, + { + name: "one node refuses the rule", + conditions: with(serving, + cond(programmedConditionType(testNodeGWB), metav1.ConditionFalse, reasonLoadFailed)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionFalse, reasonLoadFailed}, + // The node that loaded it still advertises it. + conditionTypeAdvertised: {metav1.ConditionTrue, reasonAdvertised}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonLoadFailed}, + }, + }, + { + name: "nodes disagree on why", + conditions: with(serving, + cond(programmedConditionType(testNodeGWA), metav1.ConditionFalse, reasonInvalidRule), + cond(programmedConditionType(testNodeGWB), metav1.ConditionFalse, reasonLoadFailed)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionFalse, reasonNotProgrammed}, + conditionTypeAdvertised: {metav1.ConditionFalse, reasonNotProgrammed}, + }, + }, + { + name: "every node refuses an unserved protocol", + conditions: with(serving, + cond(programmedConditionType(testNodeGWA), metav1.ConditionFalse, reasonUnservedProtocol), + cond(programmedConditionType(testNodeGWB), metav1.ConditionFalse, reasonUnservedProtocol)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionFalse, reasonUnservedProtocol}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonUnservedProtocol}, + }, + }, + { + // A node that has not reported, such as one whose datapath is + // turned off, advertises nothing, so it carries no traffic. + name: "a node that has not reported does not count", + conditions: servingConditions(testNodeGWA), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionTrue, reasonReady}, + }, + }, + { + name: "every node is a generation behind", + conditions: with(serving, + metav1.Condition{Type: programmedConditionType(testNodeGWA), Status: metav1.ConditionTrue, + Reason: reasonProgrammed, ObservedGeneration: summaryGen - 1}, + metav1.Condition{Type: programmedConditionType(testNodeGWB), Status: metav1.ConditionTrue, + Reason: reasonProgrammed, ObservedGeneration: summaryGen - 1}), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionFalse, reasonPending}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonPending}, + }, + }, + { + name: "a departed node's leftover condition is ignored", + conditions: with(serving, + cond(programmedConditionType("gw-gone"), metav1.ConditionFalse, reasonLoadFailed)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + }, + }, + { + name: "advertisement fails on one node", + conditions: with(serving, + cond(advertisedConditionType(testNodeGWB), metav1.ConditionFalse, reasonAdvertisementFailed)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + conditionTypeAdvertised: {metav1.ConditionFalse, reasonAdvertisementFailed}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonAdvertisementFailed}, + }, + }, + { + name: "a loaded rule's advertisement has not been reported", + conditions: without(serving, advertisedConditionType(testNodeGWB)), + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeAdvertised: {metav1.ConditionFalse, reasonPending}, + }, + }, + { + // The IPv6 VIP serves, so the rule is Ready and only IPv4Served + // says the IPv4 VIP does not. + name: "IPv4 VIP turned off on a dual-stack rule", + conditions: with(serving, + cond(ipv4ServedConditionType(testNodeGWA), metav1.ConditionFalse, reasonIPv4Unsupported), + cond(ipv4ServedConditionType(testNodeGWB), metav1.ConditionFalse, reasonIPv4Unsupported)), + families: dualStack, + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeAdvertised: {metav1.ConditionTrue, reasonAdvertised}, + conditionTypeIPv4Served: {metav1.ConditionFalse, reasonIPv4Unsupported}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionTrue, reasonReady}, + }, + }, + { + name: "IPv4 VIP served", + conditions: with(serving, + cond(ipv4ServedConditionType(testNodeGWA), metav1.ConditionTrue, reasonIPv4Advertised), + cond(ipv4ServedConditionType(testNodeGWB), metav1.ConditionTrue, reasonIPv4Advertised)), + families: dualStack, + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeIPv4Served: {metav1.ConditionTrue, reasonIPv4Advertised}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionTrue, reasonReady}, + }, + }, + { + name: "IPv4 VIP unbound on an IPv4-only rule", + conditions: with(serving, + cond(ipv4ServedConditionType(testNodeGWA), metav1.ConditionFalse, reasonIPv4BindingsNotBound), + cond(ipv4ServedConditionType(testNodeGWB), metav1.ConditionTrue, reasonIPv4Advertised)), + families: ipv4Only, + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeIPv4Served: {metav1.ConditionFalse, reasonIPv4BindingsNotBound}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonIPv4BindingsNotBound}, + }, + }, + { + name: "an IPv4Served condition from an older generation is pending", + conditions: with(serving, + cond(ipv4ServedConditionType(testNodeGWA), metav1.ConditionTrue, reasonIPv4Advertised), + metav1.Condition{Type: ipv4ServedConditionType(testNodeGWB), Status: metav1.ConditionTrue, + Reason: reasonIPv4Advertised, ObservedGeneration: summaryGen - 1}), + families: ipv4Only, + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeIPv4Served: {metav1.ConditionFalse, reasonPending}, + }, + }, + { + // #957: a node that cannot turn on IPv4 forwarding keeps serving + // IPv6, so only the IPv4 VIP's condition says so. + name: "IPv4 forwarding fails on a dual-stack rule", + conditions: with(serving, + cond(ipv4ServedConditionType(testNodeGWA), metav1.ConditionFalse, reasonIPv4ForwardingFailed), + cond(ipv4ServedConditionType(testNodeGWB), metav1.ConditionFalse, reasonIPv4ForwardingFailed)), + families: dualStack, + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeIPv4Served: {metav1.ConditionFalse, reasonIPv4ForwardingFailed}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionTrue, reasonReady}, + }, + }, + { + name: "IPv4 forwarding fails on an IPv4-only rule", + conditions: with(serving, + cond(ipv4ServedConditionType(testNodeGWA), metav1.ConditionFalse, reasonIPv4ForwardingFailed), + cond(ipv4ServedConditionType(testNodeGWB), metav1.ConditionTrue, reasonIPv4Advertised)), + families: ipv4Only, + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeIPv4Served: {metav1.ConditionFalse, reasonIPv4ForwardingFailed}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonIPv4ForwardingFailed}, + }, + }, + { + name: "a node named by two NetworkGateways counts once", + conditions: servingConditions(testNodeGWA), + gatewayNodes: []string{testNodeGWA, testNodeGWA}, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + }, + }, + { + name: "Accepted from an older generation is pending", + conditions: with(serving, + metav1.Condition{Type: bgpv1alpha1.ConditionTypeAccepted, Status: metav1.ConditionTrue, + Reason: reasonGatewayNodesRegistered, ObservedGeneration: summaryGen - 1}), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonPending}, + }, + }, + { + name: "a backend is claimed by another rule", + conditions: with(serving, + cond(backendsBoundConditionType(testBackendNode), metav1.ConditionFalse, reasonBindingsClaimed)), + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonBindingsClaimed}, + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonBindingsClaimed}, + }, + }, + { + name: "a gateway node left backends out", + conditions: with(serving, + cond(programmedConditionType(testNodeGWA), metav1.ConditionTrue, reasonBackendsUnresolved)), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeProgrammed: {metav1.ConditionTrue, reasonProgrammed}, + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonBackendsUnresolved}, + }, + }, + { + name: "no backend node has reported", + conditions: without(serving, backendsBoundConditionType(testBackendNode)), + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonPending}, + }, + }, + { + name: "a backend node is a generation behind", + conditions: with(serving, + metav1.Condition{Type: backendsBoundConditionType(testBackendNode), Status: metav1.ConditionTrue, + Reason: reasonBindingsBound, ObservedGeneration: summaryGen - 1}), + gatewayNodes: nodes, + want: map[string]want{ + conditionTypeBackendsReady: {metav1.ConditionFalse, reasonPending}, + }, + }, + { + name: "not accepted", + conditions: without(serving, bgpv1alpha1.ConditionTypeAccepted), + gatewayNodes: nodes, + want: map[string]want{ + bgpv1alpha1.ConditionTypeReady: {metav1.ConditionFalse, reasonPending}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + families := tt.families + if families == (vipFamilies{}) { + families.ipv6 = true + } + got := summaryConditions(tt.conditions, summaryGen, families, tt.gatewayNodes) + wantLen := 4 + if families.ipv4 { + wantLen = 5 + } + if len(got) != wantLen { + t.Fatalf("summaryConditions returned %d conditions, want %d", len(got), wantLen) + } + for condType, w := range tt.want { + c := meta.FindStatusCondition(got, condType) + if c == nil { + t.Fatalf("no %s condition in %v", condType, got) + } + if c.Status != w.status || c.Reason != w.reason { + t.Errorf("%s = %s/%s (%q), want %s/%s", condType, c.Status, c.Reason, c.Message, w.status, w.reason) + } + if c.ObservedGeneration != summaryGen { + t.Errorf("%s observedGeneration = %d, want %d", condType, c.ObservedGeneration, summaryGen) + } + } + }) + } +} + +// TestSummaryConditions_MessageNamesFailingNodes checks a partial failure's +// message names each failing node and its reason. +func TestSummaryConditions_MessageNamesFailingNodes(t *testing.T) { + conds := with(servingConditions(testNodeGWA, testNodeGWB), + cond(programmedConditionType(testNodeGWB), metav1.ConditionFalse, reasonLoadFailed)) + got := meta.FindStatusCondition(summaryConditions(conds, summaryGen, vipFamilies{ipv6: true}, + []string{testNodeGWB, testNodeGWA, "gw-new"}), bgpv1alpha1.ConditionTypeProgrammed) + want := "loaded on 1 of 2 reporting gateway nodes; 1 of 3 registered gateway nodes have not reported; " + + "not loaded on " + testNodeGWB + " (" + reasonLoadFailed + ")" + if got.Message != want { + t.Errorf("Programmed message = %q, want %q", got.Message, want) + } +} + +// TestAdvertisedCondition covers each per-node Advertised outcome. +func TestAdvertisedCondition(t *testing.T) { + errPublish := errors.New("apply failed") + tests := []struct { + name string + programmed bool + router string + err error + pending []string + status metav1.ConditionStatus + reason string + }{ + {"installed", true, testRouterName, nil, nil, metav1.ConditionTrue, reasonAdvertised}, + {"not loaded", false, testRouterName, nil, nil, metav1.ConditionFalse, reasonNotProgrammed}, + {"no router", true, "", nil, nil, metav1.ConditionFalse, reasonNoRouter}, + {"publish failed", true, testRouterName, errPublish, nil, metav1.ConditionFalse, reasonAdvertisementFailed}, + {"published, not installed", true, testRouterName, nil, []string{testRuleAdv}, metav1.ConditionFalse, + reasonAdvertisementPending}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := advertisedCondition(testNodeGWA, tt.programmed, tt.router, tt.err, tt.pending) + if c.Type != advertisedConditionType(testNodeGWA) { + t.Errorf("type = %q, want %q", c.Type, advertisedConditionType(testNodeGWA)) + } + if c.Status != tt.status || c.Reason != tt.reason { + t.Errorf("Advertised = %s/%s, want %s/%s", c.Status, c.Reason, tt.status, tt.reason) + } + if tt.err != nil && !strings.Contains(c.Message, tt.err.Error()) { + t.Errorf("message %q does not carry the publish error", c.Message) + } + }) + } +} + +// TestNetworkServiceReconciler_WritesSummaryConditions checks the reconciler +// writes the summary, and that a second pass with nothing changed writes +// nothing. +func TestNetworkServiceReconciler_WritesSummaryConditions(t *testing.T) { + scheme := newRuleTestScheme(t) + rule := newTestRule(testRuleName, "vpc-1", testVIP) + rule.Generation = summaryGen + rule.Status.Conditions = servingConditions(testNodeGWA) + + fakeClient := fake.NewClientBuilder(). + WithScheme(scheme). + WithStatusSubresource(&bgpv1alpha1.NetworkService{}). + WithObjects(newTestGateway(testNodeGWA), rule). + Build() + + r := &NetworkServiceReconciler{Client: fakeClient, APIReader: fakeClient, Scheme: scheme, NodeName: testNodeGWA} + req := ctrl.Request{NamespacedName: testRuleKey(testRuleName)} + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatalf("Reconcile: %v", err) + } + + got := &bgpv1alpha1.NetworkService{} + if err := fakeClient.Get(context.Background(), req.NamespacedName, got); err != nil { + t.Fatalf("get rule: %v", err) + } + for _, condType := range []string{bgpv1alpha1.ConditionTypeProgrammed, conditionTypeAdvertised, + conditionTypeBackendsReady, bgpv1alpha1.ConditionTypeReady} { + if !meta.IsStatusConditionTrue(got.Status.Conditions, condType) { + t.Errorf("%s is not True: %v", condType, meta.FindStatusCondition(got.Status.Conditions, condType)) + } + } + + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatalf("second Reconcile: %v", err) + } + again := &bgpv1alpha1.NetworkService{} + if err := fakeClient.Get(context.Background(), req.NamespacedName, again); err != nil { + t.Fatalf("get rule: %v", err) + } + if again.ResourceVersion != got.ResourceVersion { + t.Errorf("an unchanged summary was written again (resourceVersion %s -> %s)", + got.ResourceVersion, again.ResourceVersion) + } +} + +// TestClearNodeRuleConditions_RefreshesSummary covers the last gateway node +// leaving: no reconciler is left to recompute the summary, so the clear does. +func TestClearNodeRuleConditions_RefreshesSummary(t *testing.T) { + scheme := newRuleTestScheme(t) + rule := newTestRule(testRuleName, "vpc-1", testVIP) + rule.Generation = summaryGen + rule.Status.Conditions = servingConditions(testNodeGWA) + applySummaryConditions(rule, []string{testNodeGWA}) + + fakeClient := fake.NewClientBuilder(). + WithScheme(scheme). + WithStatusSubresource(&bgpv1alpha1.NetworkService{}). + WithObjects(rule). + Build() + + if err := clearNodeRuleConditions(context.Background(), fakeClient, testNamespace, testNodeGWA); err != nil { + t.Fatalf("clearNodeRuleConditions: %v", err) + } + got := &bgpv1alpha1.NetworkService{} + if err := fakeClient.Get(context.Background(), testRuleKey(testRuleName), got); err != nil { + t.Fatalf("get rule: %v", err) + } + if c := meta.FindStatusCondition(got.Status.Conditions, advertisedConditionType(testNodeGWA)); c != nil { + t.Errorf("node %s's Advertised condition was not cleared", testNodeGWA) + } + ready := meta.FindStatusCondition(got.Status.Conditions, bgpv1alpha1.ConditionTypeReady) + if ready == nil || ready.Status != metav1.ConditionFalse || ready.Reason != reasonNoGatewayNodes { + t.Errorf("Ready = %v, want False/%s once the last gateway node left", ready, reasonNoGatewayNodes) + } +} + +// TestApplySummaryConditions_DropsIPv4ServedWithTheIPv4VIP checks the +// rule-wide IPv4Served goes once the rule no longer has an IPv4 VIP. +func TestApplySummaryConditions_DropsIPv4ServedWithTheIPv4VIP(t *testing.T) { + rule := newTestRule(testRuleName, "vpc-1", testVIP, testVIP4) + rule.Generation = summaryGen + rule.Status.Conditions = servingConditions(testNodeGWA) + applySummaryConditions(rule, []string{testNodeGWA}) + if meta.FindStatusCondition(rule.Status.Conditions, conditionTypeIPv4Served) == nil { + t.Fatal("a rule with an IPv4 VIP has no rule-wide IPv4Served condition") + } + + rule.Spec.VIPAddresses = []string{testVIP} + if !applySummaryConditions(rule, []string{testNodeGWA}) { + t.Error("dropping the IPv4 VIP reported no change") + } + if meta.FindStatusCondition(rule.Status.Conditions, conditionTypeIPv4Served) != nil { + t.Error("the rule-wide IPv4Served condition outlived the rule's IPv4 VIP") + } +} + +// TestSummaryConditions_SilentNodesAreNamed checks a summary that is True +// still says how many registered gateway nodes have not reported, and that a +// backend node left at an older generation is named in BackendsReady. +func TestSummaryConditions_SilentNodesAreNamed(t *testing.T) { + conds := servingConditions(testNodeGWA) + got := summaryConditions(conds, summaryGen, vipFamilies{ipv6: true}, []string{testNodeGWA, testNodeGWB}) + ready := meta.FindStatusCondition(got, bgpv1alpha1.ConditionTypeReady) + if ready.Status != metav1.ConditionTrue || !strings.Contains(ready.Message, "1 of 2 registered gateway nodes") { + t.Errorf("Ready = %s %q, want True naming the gateway node that has not reported", ready.Status, ready.Message) + } + + conds = with(conds, metav1.Condition{Type: backendsBoundConditionType("compute-2"), + Status: metav1.ConditionTrue, Reason: reasonBindingsBound, ObservedGeneration: summaryGen - 1}) + got = summaryConditions(conds, summaryGen, vipFamilies{ipv6: true}, []string{testNodeGWA}) + backends := meta.FindStatusCondition(got, conditionTypeBackendsReady) + want := "backends not ready on compute-2 (" + reasonPending + ")" + if backends.Status != metav1.ConditionFalse || backends.Message != want { + t.Errorf("BackendsReady = %s %q, want False %q", backends.Status, backends.Message, want) + } +} diff --git a/internal/controller/status.go b/internal/controller/status.go index b5b2be717..9ddea2b54 100644 --- a/internal/controller/status.go +++ b/internal/controller/status.go @@ -124,9 +124,9 @@ func setBindingCondition(binding *bgpv1alpha1.ServiceVIPBinding, condition metav meta.SetStatusCondition(&binding.Status.Conditions, condition) } -// setRuleCondition sets or updates a condition on a NetworkService. It uses two -// types: Accepted, once gateway nodes exist to serve it, and Ready, from the -// engine's convergence result for that rule. +// setRuleCondition sets or updates a condition on a NetworkService. Only the +// Accepted condition goes through it; the per-node conditions and the +// rule-wide summary (summaryConditions) are set against a fresh read. func setRuleCondition(rule *bgpv1alpha1.NetworkService, condition metav1.Condition) { condition.ObservedGeneration = rule.Generation meta.SetStatusCondition(&rule.Status.Conditions, condition) From 5aa71969e9cc5c36a719d43a80203280fd925ce5 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 21 Oct 2026 09:17:39 -0400 Subject: [PATCH 2/2] docs(gateway): Note a datapath-off node still gets replies The status docs said a gateway node whose datapath is off advertises nothing and so carries none of a rule's traffic. It advertises none of the rule's VIPs, but a backend node that reaches clients through more than one edge node still sends some replies through it. The node does not claim them, so those TCP connections fail while the rule reports Ready. Say so in the reason docs and in summaryConditions' doc comment, so a reader does not take a node that has not reported as one that carries nothing. Related to #708 Co-Authored-By: Claude Opus 5.5 --- docs/gateway/configuration.md | 9 ++++++++- internal/controller/networkservice_summary.go | 9 +++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index c7624beb4..7d06bbdc5 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -639,10 +639,17 @@ condition, or `Accepted`, from an older generation counts as not reported yet. Only gateway nodes with a `/Programmed` condition count. A node that has not reported, for example one whose datapath is turned off, -advertises nothing and so carries none of the rule's traffic. The +advertises none of the rule's VIPs, so clients never reach it. The `Programmed` and `Ready` messages say how many registered gateway nodes have not reported. +A node with its datapath off can still receive replies. A backend node that +reaches clients through more than one edge node spreads its replies across +them, and a node with its datapath off does not claim the ones that reach it, +so those TCP connections fail. `Ready` stays `True` while this happens. Treat +a gateway node that has not reported as a reason to check the rule's traffic, +not as proof that the node carries none of it. + `Ready` leaves out `IPv4Served` while the rule has an IPv6 VIP. IPv4 VIPs are off on most gateways, and a rule whose IPv6 VIP serves is not down because its IPv4 VIP is not served. Read `IPv4Served` to see whether the IPv4 VIP serves. diff --git a/internal/controller/networkservice_summary.go b/internal/controller/networkservice_summary.go index e4644c86e..6b6e787bd 100644 --- a/internal/controller/networkservice_summary.go +++ b/internal/controller/networkservice_summary.go @@ -94,10 +94,11 @@ type nodeReport struct { // // Every input is shared state, so every writer computes the same result. // Only gateway nodes that report a Programmed condition count: a node that -// has not reported yet, or whose datapath is turned off, advertises nothing, -// so it carries none of the rule's traffic. Programmed and Ready say how many -// registered nodes have not reported. A per-node condition from an older -// generation counts as not reported. +// has not reported yet, or whose datapath is turned off, advertises none of +// the rule's VIPs, so no client is sent to it. It can still receive a reply a +// backend node sends through it, which Ready does not see. Programmed and +// Ready say how many registered nodes have not reported. A per-node +// condition from an older generation counts as not reported. // // Advertised covers the routes a node published. Whether the IPv4 VIP is // served is IPv4Served's alone, and Ready reads it only for a rule with no