diff --git a/cmd/galactic-router/root.go b/cmd/galactic-router/root.go index 1e62f0bd1..d3cc36081 100644 --- a/cmd/galactic-router/root.go +++ b/cmd/galactic-router/root.go @@ -456,7 +456,7 @@ func setupServiceRouteController( ctrl.Log.Error(err, "service route eBPF maps are not available yet; initialization will retry on reconcile") } - return (&controller.ServiceRoutePolicyReconciler{ + if err := (&controller.ServiceRoutePolicyReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), NodeName: nodeName, @@ -465,7 +465,17 @@ func setupServiceRouteController( Metrics: serviceRouteMetrics, FrontendEnabled: frontendEnabled, Applied: make(map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent), - }).SetupWithManager(mgr) + }).SetupWithManager(mgr); err != nil { + return err + } + if err := (&controller.ServiceProducerHealthReconciler{ + Client: mgr.GetClient(), + NodeName: nodeName, + Metrics: serviceRouteMetrics, + }).SetupWithManager(mgr); err != nil { + return fmt.Errorf("setup service producer health controller: %w", err) + } + return nil } // newRootCommand builds the root cobra command with all flags and the diff --git a/config/galactic-router/rbac.yaml b/config/galactic-router/rbac.yaml index 7bd0e71fe..8a6bc49a2 100644 --- a/config/galactic-router/rbac.yaml +++ b/config/galactic-router/rbac.yaml @@ -56,6 +56,7 @@ rules: - servicevipbindings/status - networkservices/status - serviceroutepolicies/status + - serviceendpoints/status verbs: ["get", "update", "patch"] - apiGroups: ["galactic.datumapis.com"] resources: diff --git a/docs/agents/ARCHITECTURE-ROUTER.md b/docs/agents/ARCHITECTURE-ROUTER.md index 3d26d701f..42b634db8 100644 --- a/docs/agents/ARCHITECTURE-ROUTER.md +++ b/docs/agents/ARCHITECTURE-ROUTER.md @@ -172,15 +172,16 @@ lives in `root.go`'s `runCmd`: with the manager — see the peer-FSM design decision below. 9. Register the controllers: BGPRouter, BGPPeer, BGPAdvertisement, BGPVRFInstance, BGPPolicy, Secret, Node, ServiceVIPBinding, - NetworkServiceBinding, NodeDeparture, ServiceRoutePolicy (plain role only; - a route reflector has no service route maps to program and skips it), + NetworkServiceBinding, NodeDeparture, ServiceRoutePolicy and + ServiceProducerHealth (plain role only; a route reflector has no service + route maps to program and skips both), and GC (the GC controller also starts a ticker goroutine that waits for cache sync, then runs on `--gc-interval`, default 5m; NodeDeparture sweeps on the same interval, and when `vip_xlat_table` opened in step 6, each GC tick after the first pass also sweeps it). 10. `mgr.Start(ctx)` — blocks until the signal-handler context is cancelled. -Apart from the ServiceRoutePolicy controller and the `vip_xlat_table` log +Apart from the ServiceRoutePolicy and ServiceProducerHealth controllers and the `vip_xlat_table` log level noted above, this is identical whether the pod is running in the plain role (`config/galactic-router/overlays/router/`, opt-in via `galactic.datumapis.com/galactic=router` — deployed on both `compute` and @@ -278,6 +279,7 @@ co-located `galactic-gateway` container's own health port on the same - **A tenant VRF route that fails to install is retried, not dropped.** `processEVPNPath` writes a VRF-scoped path's route into `egress_route_table` through `internal/runtime/gobgp/vrfroutes.go`. `Register` resolves the SID's uplink and neighbor MAC at write time, which fails while an uplink is still coming up after a restart, and BGP never redelivers an unchanged best path, so before #676 such a route stayed missing until the path changed upstream. `vrfRoutes` keeps each failed route in a pending set and retries it whenever the main table changes (1s debounce) and every 30s, until it installs or its path is withdrawn; removing a VRF drops its pending routes. One mutex serializes every write to the map from this runtime, taken per route during a retry so an unresolvable neighbor (up to 2s) does not hold up the RIB watcher for the whole pass. `EgressRouteTable.Refresh` cannot cover this: it walks existing entries only. The pending count, and the plain-route reconciler's failing count, are exported as `galactic_router_route_install_failing{kind="vrf"|"plain"}`, and `GalacticRouterRoutesNotInstalled` fires when either stays above 0 for 10 minutes. - **`ServiceVIPBinding`s are generated, one per node per backend.** `NetworkServiceBindingReconciler` (`internal/controller/networkservice_binding_controller.go`) runs on every node and writes a binding for each VIP of each accepted `NetworkService`, at most one per family (`ruleTranslatedVIPs`) and, for the IPv4 VIP, only while some gateway node's `/IPv4Served` condition reports it loaded (`ipv4LoadedOnSomeNode`; a status change to that signal passes `ruleBindingInputsChanged`, and the node deletes its IPv4 bindings once no gateway does), and each backend the rule's `backendSelector` places on this node, through the same `selectRuleBackends` the gateway uses, so the gateway never sends a backend's flows to a node with no binding planned for it. Workloads are IPv6 only, so both VIPs' backends are the selected attachments' IPv6 addresses: an IPv4 VIP's binding pairs the IPv4 `vipAddress` with an IPv6 `backendAddress`, which the backend node serves by translating the flows (see [ARCHITECTURE-CNI.md](ARCHITECTURE-CNI.md#key-design-decisions)). `ServiceVIPBindingReconciler` refuses an IPv4 `backendAddress` with `BindFailed`. Each node writes and deletes only its own bindings (labelled `galactic.datum.net/binding-node` and `app.kubernetes.io/managed-by: galactic-router`), so there is one writer per object and no leader election. A binding is owned by its rule, records the rule's `vpcRef` (which names the VRF its rows go in) and takes `egressKind` from the attachment's interface mode. `ServiceVIPBindingReconciler` programs a binding only when a `BGPAdvertisement` on this node's `BGPRouter` with that VRF's ID has a prefix containing `backendAddress`, and otherwise reports `BindFailed`; it watches advertisements on its own router so a binding written before its advertisement converges, and teardown skips the check. A backend serves only the oldest rule (by creation time, then namespace/name) selecting it on the same backend port and protocol, since its node translates the backend's replies back to only one VIP; a claim (`backendClaim`) carries the VIP's family, since a reply to an IPv4 client takes the IPv4 VIP's egress-translated row and any other reply the IPv6 VIP's egress row, so one backend socket answers for one VIP of each family, an IPv4 rule never competes with an IPv6 one, and two rules with IPv4 VIPs on one socket do; both sides compute that owner with `ruleBackendOwners` over every rule in the namespace, so a newer rule gets no binding for the backend and no flows for it from the gateway, and every rule in a namespace is re-queued when one of them changes. Rules compete only within a VPC, so the per-VPC `VPCAttachment` fan-out still reaches every rule an attachment change can affect. The node summarizes its bindings on the rule as `/BackendsBound` (`BackendsClaimed` names a backend an older rule serves); a rule whose spec cannot be built into bindings (a second IPv6 VIP, or a selector that does not parse) keeps the node's existing bindings, the same as a rule that loses `Accepted`, so an invalid edit does not drop the backend nodes' `vip_xlat_table` rows; a second IPv4 VIP does the same for the IPv4 family alone, writing no IPv4 binding and keeping the IPv4 ones it had while the IPv6 VIP's bindings stay current, and both report `InvalidRule`. Only the nodes that hold bindings for such a rule report `InvalidRule`, since the gateways already report the error and a condition from every node would be a status write per node per edit. Each rule reconcile lists only its own VPC's attachments, through the VPCAttachment→`status.vpc` field index (`listVPCAttachmentsInVPC`), and skips the cache's deep copy because nothing it does writes to them. Several backends of one VIP can share a node: the gateway writes each backend's slot into the uSID and `usid.c` keys the ingress row on it (#799). - **Each node probes its own backends and publishes their health.** For a `NetworkService` with `spec.healthCheck`, `BackendHealthReconciler` (`internal/controller/backendhealth_controller.go`) runs one TCP probe loop per backend on its node (`internal/healthprobe`), over the backend's host-side interface (the attachment's `status.hostInterface`) from that interface's link-local address, on `healthCheck.port` or the rule's `backendPort`. The link-local source is what lets the SYN-ACK back: `usid_egress` hands a reply to a link-local destination to the kernel before its VIP rewrite (see [ARCHITECTURE-CNI.md](ARCHITECTURE-CNI.md#key-design-decisions)). A decision moves after `unhealthyThreshold` consecutive failures or `healthyThreshold` consecutive successes; a probe that cannot be sent (no interface, no link-local address) counts toward `Unknown`/`ProbeUnavailable`, never toward `Unhealthy`. The decision goes into `status.health` of each of the backend's bindings, with the attachment UID and probed port, by a merge patch of that field alone and only when it changes, so it never races the `Bound` condition. Every binding of one backend shares one loop. A restarted router seeds each loop from the published decision when its attachment UID and port still match, so a restart changes no gateway's table. A rule losing its `healthCheck` clears `status.health` and stops the loops. The design is [docs/gateway/backend-health.md](../gateway/backend-health.md). +- **A `Spread` service endpoint's producers are probed by their own node, and a consumer's route reads a producer set.** `ServiceProducerHealthReconciler` (`internal/controller/serviceproducerhealth_controller.go`) runs one `internal/healthprobe` loop per producer on its node of each `ServiceEndpoint` with `spec.distribution: Spread`, to the producer attachment's first IPv6 address on `healthCheck.port`, and server-side applies that node's entries of the endpoint's `status.producers` under its own field manager (`galactic-router/`), so nodes never overwrite each other's entries and an entry a node stops applying disappears. `ServiceRoutePolicyReconciler` reads them: for a Spread endpoint, `serviceroute.Compile` emits one `LocalSet` intent per consumer holding every producer on the consumer's node, `Unhealthy` ones marked draining unless all are. `EBPFRouteProgrammer` writes it as a mode-3 `service_route_table` row plus a `service_producer_set_table` row under the same key; `usid_egress` pins each TCP flow in `service_flow_table` and picks a producer per UDP datagram (see [docs/router/private-service-routes.md](../router/private-service-routes.md#several-producers-on-one-node)). A changed `LocalSet` intent is applied before the old one is removed, and the programmer keeps the newest of a key's producer sets in the map, so a health or membership change never drops the consumer's route. A datapath without the producer set map gets `serviceroute.ErrProducerSetsUnavailable` for `LocalSet` intents only. - **Surviving routers clean up after a departed node.** Only a node's own `NetworkServiceBindingReconciler` clears its `/BackendsBound` conditions and deletes its generated bindings, and only its own `ServiceVIPBindingReconciler` removes the teardown finalizer from bindings targeting it. So once a node's `Node` object is deleted, `NodeDepartureReconciler` (`internal/controller/node_departure_controller.go`) on every other router removes that node's `BackendsBound` condition from every `NetworkService`, deletes its generated bindings and removes the finalizer from every binding whose `targetRef.name` names it, hand-written ones included; the kernel rows went with the node. Without it the conditions stayed forever and a deleted rule's bindings stayed `Terminating`. Every Node create and delete maps to one sweep key, so the sweep runs on the initial Node list (startup), on every Node delete and every `--gc-interval`, and a router down during the delete still converges. A node missing from the cached Node list counts as departed only once an uncached `Get` returns NotFound. Every router sweeps, with no leader election: status writes and finalizer patches retry on conflict (the patch carries the resourceVersion) and NotFound counts as done. - **Deleting a `ServiceVIPBinding` does not need its VRF on the node.** A binding's two `vip_xlat_table` rows are keyed on its VRF's uSID Argument. `ServiceVIPBindingReconciler` reads it from the `BGPVRFInstance` its `vpcRef` names on this node, and that is gone once the VPC leaves the node. Before #750, deletion re-derived it, failed, held the finalizer forever and left both rows in the map. Teardown now finds the rows by value with `vipxlatmap.UnregisterBinding`: since #764 each key carries the VIP or backend address, and since #799 the ingress key also carries the backend's slot, so the binding's ingress row (its VIP, port and slot, rewriting to its backend) and egress row (its backend and port, rewriting to its VIP) are found exactly, under any Argument. Each row is removed only while it still holds the binding's values, so a row another binding has since written stays. When the VRF context still resolves, `UnregisterBindingAt` applies the same checks at that location too. Neither pass deletes a row without first reading it, and a process-wide lock keeps a bind from landing between the read and the delete. A value check cannot tell two bindings with identical values apart, so while such a twin is live on the node, deleting one removes nothing. Rows exist only for an IPv6 backend, so an IPv4 or unparseable `backendAddress` skips both passes instead of blocking deletion. Only a failed kernel delete keeps the finalizer. Rows left behind some other way, by a finalizer cleared by hand, a crash or a manual write, are removed by the periodic sweep below; to remove one sooner, use `galactic-router vip xlat list` and `vip xlat remove --protocol --vip --port --backend --backend-port` (`--slot` defaults to the backend's own), run in that node's `galactic-router` pod (`kubectl exec -- /galactic-router vip xlat list`). - **`vip_xlat_table` holds both VIP families in one layout.** The map (`struct vip_xlat_key`, 32 bytes: block, argument, protocol, direction, port, slot, 16-byte address; `struct vip_xlat_value`, 18 bytes: 16-byte address, port) is pinned by `galactic-cni` at `/sys/fs/bpf/galactic/vip_xlat_table` and reused across restarts and upgrades by `attach.Load`; `galactic-router`'s `ServiceVIPBindingReconciler` and the `vip xlat` CLI are its only writers. Its layout is fixed, since CNI ADD and binding time write the rows and a new layout would empty the map until every binding was written again. A binding writes two rows, by its VIP's family (every key also carries block, argument and protocol): diff --git a/docs/enhancements/networking/private-service-connect/README.md b/docs/enhancements/networking/private-service-connect/README.md index 2622b1f6a..a567e9e1e 100644 --- a/docs/enhancements/networking/private-service-connect/README.md +++ b/docs/enhancements/networking/private-service-connect/README.md @@ -335,14 +335,19 @@ in the edge API. It derives current desired programming through these steps: 1. Resolve `serviceRef`, validate the service tuple and placement, and resolve the pinned consumer VPC name and UID. 2. Select producer attachments with current-generation `Ready` and `Programmed` - status, a node, allocated network identities, and a host interface. Service - owners must ensure selected producers are also healthy for the declared tuple. + status, a node, allocated network identities, and a host interface. For a + `Single` endpoint, service owners must ensure selected producers are also + healthy for the declared tuple; a `Spread` endpoint's producers are probed + by their nodes. 3. Select consumer attachments through protected labels and verify their live VPC membership and programmed attachment identity. -4. Choose one producer for each consumer. Prefer a local producer; `NodeLocal` - leaves the consumer without a path if none is available. `PreferNodeLocal` - permits a ready remote producer. Selection uses a deterministic attachment - ordering, not round-robin balancing or application health probes. +4. Choose producers for each consumer. A `Single` endpoint gets one, chosen by + a deterministic attachment ordering, preferring a local producer. A `Spread` + endpoint gets every producer on the consumer's node as one set: new flows go + to the ones its health check has not found `Unhealthy`, each TCP connection + stays with its first producer, and each UDP datagram picks its own. In both, + `NodeLocal` leaves the consumer without a path if no local producer is + available, and `PreferNodeLocal` permits one ready remote producer. 5. Program this node's consumer and producer paths. Remote paths require both sides' trusted attachment identities, matching service grants, and return routing. Grants bind the policy, endpoint, and attachment lifetimes to the @@ -355,9 +360,12 @@ policy intent invalid. A missing endpoint or mismatched VPC identity invalidates the contract and requires stale access to be removed. An unresolved remote path prevents that node from serving even if the shared policy remains accepted. -Service owners withdraw unhealthy producers through the endpoint's selection -contract. Galactic's attachment readiness checks establish network eligibility; -they do not substitute for service health. +Service owners of a `Single` endpoint withdraw unhealthy producers through the +endpoint's selection contract. Galactic's attachment readiness checks establish +network eligibility; they do not substitute for service health. A `Spread` +endpoint's producers are probed over TCP by their own node, which publishes +each decision in the endpoint's `status.producers`; see +[Private service routes](../../../router/private-service-routes.md#several-producers-on-one-node). ### Status and lifecycle @@ -421,8 +429,10 @@ sequenceDiagram `NodeLocal` requires a producer on the consumer's node. `PreferNodeLocal` uses a local producer when available and otherwise selects a ready remote producer. -Selection is deterministic. The current direct-endpoint path rejects multiple -ready producers in the same node and VPC because it cannot distinguish them. +A `Single` endpoint's selection is deterministic, and it rejects multiple ready +producers in the same node and VPC because its one-target route cannot +distinguish them. A `Spread` endpoint routes to a set of up to 16 producers on +the consumer's node instead. Overlapping consumer addresses remain scoped to their attachments. Remote delivery requires matching platform-programmed service grants. Tenant-supplied diff --git a/docs/metrics.md b/docs/metrics.md index cf4e047ce..0318cc3f5 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -873,6 +873,7 @@ labels, so the series stay bounded. | `galactic_service_route_reconcile_duration_seconds` | histogram | none | Time per reconcile (default buckets) | | `galactic_service_route_route_operations_total` | counter | `operation` (`apply`, `remove`), `result` (`success`, `error`) | Datapath writes and removals | | `galactic_service_route_programmed_routes` | gauge | none | Attachment-scoped service paths the controller now tracks | +| `galactic_service_route_producers` | gauge | `state` (`Healthy`, `Unhealthy`, `Unknown`) | Producers of `Spread` endpoints this node probes | Datapath drops on these paths are the `service_route_*` reasons of `galactic_usid_drops_total`. diff --git a/docs/router/private-service-routes.md b/docs/router/private-service-routes.md index 21480c1ac..3c7645cd5 100644 --- a/docs/router/private-service-routes.md +++ b/docs/router/private-service-routes.md @@ -9,8 +9,10 @@ EndpointSlices or select a Kubernetes backend. A translated policy uses endpoint address before delivery. The controller that publishes the `ServiceEndpoint` owns the service -implementation and health. It must ensure every attachment selected by -`attachmentRef` or `attachmentSelector` is ready to receive the declared tuple. +implementation. Unless the endpoint spreads traffic (see +[Several producers on one node](#several-producers-on-one-node)), it also owns +their health: it must ensure every attachment selected by `attachmentRef` or +`attachmentSelector` is ready to receive the declared tuple. `VPCAttachment`'s `Ready` and `Programmed` conditions are necessary networking prerequisites; they do not attest that a service listener is healthy. A listener may bind or configure the address in the producer, use a transparent @@ -27,15 +29,112 @@ Galactic treats an attachment as ready only when its status has from the `BGPAdvertisement` that `galactic-router` publishes for the attachment. Without them no attachment is ready and no route is programmed. -Galactic selects one ready producer for each consumer. A node-local producer is -preferred and ties are resolved deterministically by attachment namespace and -name. More than one ready producer in the same node and VPC is rejected because -the direct-VIP dataplane cannot distinguish those replicas. Replicas on -different nodes or in distinct VPCs remain valid. `NodeLocal` stops there when -no local producer is ready; `PreferNodeLocal` may select a remote producer and -carries the original packet through the SRv6 service tunnel. In both cases the -producer receives the declared destination and the original consumer source -unchanged. +By default (`spec.distribution` unset or `Single`), Galactic selects one ready +producer for each consumer. A node-local producer is preferred and ties are +resolved deterministically by attachment namespace and name. More than one +ready producer in the same node and VPC is rejected because the single-target +route cannot distinguish those replicas. Replicas on different nodes or in +distinct VPCs remain valid. `NodeLocal` stops there when no local producer is +ready; `PreferNodeLocal` may select a remote producer and carries the original +packet through the SRv6 service tunnel. In both cases the producer receives the +declared destination and the original consumer source unchanged. + +## Several producers on one node + +`spec.distribution: Spread` sends each consumer's traffic to every ready +producer on the consumer's node, up to 16 of them, through the one service +address. It requires `spec.healthCheck`, and `healthCheck` is refused without +it: + +```yaml +spec: + address: fd53::53 + port: 53 + protocol: udp + deliveryMode: PreferNodeLocal + attachmentSelector: + matchLabels: + role: resolver + distribution: Spread + healthCheck: + port: 8053 # required for a udp endpoint: a TCP port the producers listen on + intervalSeconds: 5 + timeoutSeconds: 2 + unhealthyThreshold: 3 + healthyThreshold: 3 +``` + +How flows are spread: + +- A TCP connection goes to the producer that received its first packet and + stays there while that producer is in the node's set, even after its health + check fails. A new connection goes to a producer chosen by its flow hash. +- Each UDP datagram picks a producer at random, so the requests of one socket + spread too. This suits request/response protocols such as DNS. It does not + suit a protocol that needs a UDP flow to stay on one producer, such as QUIC; + keep such endpoints on `Single`. +- Replies reach the consumer from whichever producer answered. + +Each producer's own node probes it: `galactic-router` opens a TCP connection to +the producer attachment's first IPv6 address, or its pod subnet's address, +on `healthCheck.port` (the endpoint's port when unset), through the producer's +host-side interface and from that interface's link-local address. Where +interface traffic policy is enforced, the producer's policy must allow that +TCP connection from `fe80::/10` on the Private path. The node publishes the +decision for each of its producers in the endpoint's `status.producers`: + +```console +$ kubectl get serviceendpoint resolver -o jsonpath='{range .status.producers[*]}{.name}{"\t"}{.node}{"\t"}{.state}{"\t"}{.reason}{"\n"}{end}' +resolver-a node-1 Healthy ProbeSucceeded +resolver-b node-1 Unhealthy ProbeFailed +``` + +What the decision does: + +| State | New flows | Existing TCP connections and replies | +| ----------- | --------- | ------------------------------------ | +| `Healthy` | yes | yes | +| `Unknown` | yes | yes | +| `Unhealthy` | no | yes | + +When every producer on a node is `Unhealthy`, all of them keep taking new +flows, because an empty set would drop every request. A producer that crashes +stops getting new flows within `intervalSeconds × unhealthyThreshold` plus +`timeoutSeconds`, plus the time its node takes to publish the decision and the +consumer's node to program it. One whose attachment stops being ready leaves +the set as soon as its node sees the change. Either way only its own +connections move. + +For a rollout or shutdown that loses no requests, make the producer fail its +health check first and keep serving for at least that detection time plus its +longest request, then stop it. Its in-flight requests and open connections +finish while new ones go to the other producers. + +When the consumer's node has no producer, `PreferNodeLocal` sends the consumer +to one remote producer, the first by namespace and name that its node has not +reported `Unhealthy`, through the SRv6 service tunnel as with `Single`. A +remote consumer therefore does not spread. While a health change reaches the +consumer's node and the producer's node at different moments, the two can +briefly disagree on that producer, and its requests are refused until they +agree. + +A TCP connection keeps its producer only while its pin lasts. A pin ends after +300 seconds without traffic, the same idle limit replies already have, or when +the node evicts it under load or reloads the datapath. A packet of an +established connection with no pin goes to the producer its hash picks among +the current eligible ones, so if that set changed since the connection opened, +the connection resets. Changing an endpoint between `Single` and `Spread` +replaces its routes, which can drop a request in flight and moves existing TCP +connections. + +Spread needs a `galactic-cni` whose datapath has the producer set map. A +`galactic-router` that finds the map missing refuses the endpoint's Spread +routes on that node, retrying, and keeps every other route working. Roll out +`galactic-cni` before setting `Spread`. Before rolling back either +`galactic-router` or `galactic-cni` to a version without Spread, set every +endpoint back to `Single`: an older router refuses an endpoint with several +producers on one node, and an older datapath drops the Spread routes a newer +router still writes, since the producer set map's pin outlives the rollback. ## No consumer-visible route @@ -93,8 +192,8 @@ established replies. Persistent access must omit the deadline. Policies claiming the same frontend address, protocol, and port on one consumer attachment are rejected together. Separate VPC attachments can reuse that tuple. -The publisher owns access policy and service health; Galactic enforces -network access and forwards packets. It does not interpret DNS records or zones. +The publisher owns access policy and, for `Single` endpoints, service health; +Galactic enforces network access and forwards packets. It does not interpret DNS records or zones. ## Node programming reports diff --git a/internal/controller/serviceproducerhealth_controller.go b/internal/controller/serviceproducerhealth_controller.go new file mode 100644 index 000000000..1f71020f4 --- /dev/null +++ b/internal/controller/serviceproducerhealth_controller.go @@ -0,0 +1,447 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net" + "net/netip" + "sort" + "strings" + "sync" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/predicate" + ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/healthprobe" + "go.datum.net/galactic/internal/serviceroute" +) + +// ServiceProducerHealthReconciler probes the producers on its node of every +// ServiceEndpoint whose distribution is Spread, and publishes their decisions +// in the endpoint's status.producers. It runs in galactic-router on every +// node, next to ServiceRoutePolicyReconciler, which reads those decisions to +// keep new flows off Unhealthy producers. +// +// Each node applies only its own producers' entries, under its own field +// manager, so nodes never overwrite each other's entries, and an entry this +// node stops applying is removed. Each producer has one probe loop, started +// from the decision already published for the same attachment and port, so a +// restarted galactic-router changes no producer set. A producer with no IPv6 +// address cannot be probed and is published as Unknown. +type ServiceProducerHealthReconciler struct { + client.Client + NodeName string + + // Dial sends one probe; nil means healthprobe.Dial. + Dial healthprobe.DialFunc + + // Prober overrides the probe loop, for tests. Nil means SetupWithManager + // builds one around Dial. + Prober BackendProber + + // Metrics counts this node's producers by state; nil disables it. + Metrics *serviceroute.Metrics + + events chan event.GenericEvent + + mu sync.Mutex + // owners holds each endpoint's probe owners, and states each owner's + // last published state. + owners map[types.NamespacedName]map[string]bool + states map[string]networkv1alpha1.BackendHealthState +} + +// Reconcile converges one endpoint's probes and this node's entries in its +// status.producers. +func (r *ServiceProducerHealthReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + endpoint := &networkv1alpha1.ServiceEndpoint{} + if err := r.Get(ctx, req.NamespacedName, endpoint); err != nil { + if apierrors.IsNotFound(err) { + r.releaseExcept(req.NamespacedName, nil) + return ctrl.Result{}, nil + } + return ctrl.Result{}, fmt.Errorf("get ServiceEndpoint %s: %w", req.NamespacedName, err) + } + if endpoint.Spec.Distribution != networkv1alpha1.ServiceEndpointDistributionSpread || + endpoint.Spec.HealthCheck == nil || !endpoint.DeletionTimestamp.IsZero() { + r.releaseExcept(req.NamespacedName, nil) + return ctrl.Result{}, r.publish(ctx, endpoint, nil) + } + + list := &cloudv1alpha1.VPCAttachmentList{} + if err := r.List(ctx, list); err != nil { + return ctrl.Result{}, fmt.Errorf("list VPCAttachments: %w", err) + } + attachments := make([]*cloudv1alpha1.VPCAttachment, 0, len(list.Items)) + for i := range list.Items { + attachments = append(attachments, &list.Items[i]) + } + producers, err := serviceroute.Producers(endpoint, attachments) + if err != nil { + // The policy controller reports an invalid endpoint; there is + // nothing to probe. + r.releaseExcept(req.NamespacedName, nil) + return ctrl.Result{}, r.publish(ctx, endpoint, nil) + } + + published := make(map[types.NamespacedName]networkv1alpha1.ServiceEndpointProducerStatus) + for _, entry := range endpoint.Status.Producers { + published[types.NamespacedName{Namespace: entry.Namespace, Name: entry.Name}] = entry + } + port := producerHealthCheckPort(endpoint) + wanted := make(map[string]bool) + var entries []networkv1alpha1.ServiceEndpointProducerStatus + for _, producer := range producers { + if producer.Status.Node != r.NodeName { + continue + } + key := types.NamespacedName{Namespace: producer.Namespace, Name: producer.Name} + entry := networkv1alpha1.ServiceEndpointProducerStatus{ + Namespace: producer.Namespace, Name: producer.Name, AttachmentUID: producer.UID, + Node: r.NodeName, Port: port, + } + target, ok := producerHealthTarget(endpoint, producer) + if !ok { + entry.State = networkv1alpha1.BackendHealthUnknown + entry.Reason = healthprobe.ReasonProbeUnavailable + entry.Message = "attachment has no IPv6 address to probe" + entry.LastTransitionTime = keepTransition(published[key], entry, metav1.Now()) + entries = append(entries, entry) + continue + } + owner := producerProbeOwner(req.NamespacedName, key) + wanted[owner] = true + decision := r.Prober.Ensure(owner, healthTargetID(producer.UID, target), target, + seedProducerDecision(published[key], producer.UID, port)) + entry.State = networkv1alpha1.BackendHealthState(decision.State) + entry.Reason = decision.Reason + entry.Message = truncateMessage(decision.Message) + entry.LastTransitionTime = metav1.NewTime(decision.Since.Truncate(time.Second)) + entries = append(entries, entry) + } + r.track(req.NamespacedName, wanted, entries) + return ctrl.Result{}, r.publish(ctx, endpoint, entries) +} + +// producerHealthCheckPort returns the port endpoint's healthCheck probes: its +// port, or the endpoint's port when that is unset. +func producerHealthCheckPort(endpoint *networkv1alpha1.ServiceEndpoint) int32 { + if endpoint.Spec.HealthCheck.Port != 0 { + return endpoint.Spec.HealthCheck.Port + } + return endpoint.Spec.Port +} + +// producerHealthTarget returns the probe target of producer under endpoint's +// healthCheck: the attachment's first IPv6 interface address, or its pod +// subnet's address, over its host-side interface. It reports false when the +// attachment has neither. Fields the API server defaults are read as their +// defaults if a client left them zero anyway. +func producerHealthTarget( + endpoint *networkv1alpha1.ServiceEndpoint, producer *cloudv1alpha1.VPCAttachment, +) (healthprobe.Target, bool) { + var addr netip.Addr + if addrs := attachmentIPv6Addresses(producer); len(addrs) != 0 { + addr = addrs[0] + } else if ip, _, err := net.ParseCIDR(producer.Status.PodSubnet); err == nil && ip.To4() == nil { + addr, _ = netip.AddrFromSlice(ip.To16()) + } + port := producerHealthCheckPort(endpoint) + if !addr.IsValid() || port < 1 || port > 65535 { + return healthprobe.Target{}, false + } + hc := endpoint.Spec.HealthCheck + orDefault := func(v, def int32) int32 { + if v < 1 { + return def + } + return v + } + return healthprobe.Target{ + Interface: producer.Status.HostInterface, + Addr: addr, + Port: uint16(port), + Config: healthprobe.Config{ + Interval: time.Duration(orDefault(hc.IntervalSeconds, 5)) * time.Second, + Timeout: time.Duration(orDefault(hc.TimeoutSeconds, 2)) * time.Second, + UnhealthyThreshold: int(orDefault(hc.UnhealthyThreshold, 3)), + HealthyThreshold: int(orDefault(hc.HealthyThreshold, 3)), + }, + }, true +} + +// seedProducerDecision returns published as a starting decision when it +// describes the producer held by uid on port, and nil otherwise. +func seedProducerDecision(published networkv1alpha1.ServiceEndpointProducerStatus, uid types.UID, + port int32, +) *healthprobe.Decision { + if published.AttachmentUID != uid || published.Port != port || published.State == "" { + return nil + } + return &healthprobe.Decision{ + State: healthprobe.State(published.State), + Reason: published.Reason, + Message: published.Message, + Since: published.LastTransitionTime.Time, + } +} + +// keepTransition returns the published entry's transition time when it holds +// the same decision for the same attachment, and now otherwise. +func keepTransition(published, entry networkv1alpha1.ServiceEndpointProducerStatus, now metav1.Time) metav1.Time { + if published.AttachmentUID == entry.AttachmentUID && published.State == entry.State && + published.Reason == entry.Reason { + return published.LastTransitionTime + } + return metav1.NewTime(now.Truncate(time.Second)) +} + +// producerProbeOwner names one producer's probe loop. Its first part, +// "namespace/name" of the endpoint, is what enqueue reconciles. +func producerProbeOwner(endpoint, producer types.NamespacedName) string { + return endpoint.String() + "|" + producer.String() +} + +// releaseExcept stops every probe of endpoint whose owner is not in keep. +func (r *ServiceProducerHealthReconciler) releaseExcept(endpoint types.NamespacedName, keep map[string]bool) { + r.mu.Lock() + defer r.mu.Unlock() + if r.owners == nil { + r.owners = make(map[types.NamespacedName]map[string]bool) + r.states = make(map[string]networkv1alpha1.BackendHealthState) + } + for owner := range r.owners[endpoint] { + if !keep[owner] { + r.Prober.Release(owner) + delete(r.owners[endpoint], owner) + } + } + if len(r.owners[endpoint]) == 0 { + delete(r.owners, endpoint) + } + r.recordStatesLocked(endpoint, nil) +} + +// track releases endpoint's probes that are no longer wanted, records the +// probes that are, and updates the state counts from entries. +func (r *ServiceProducerHealthReconciler) track(endpoint types.NamespacedName, wanted map[string]bool, + entries []networkv1alpha1.ServiceEndpointProducerStatus, +) { + r.releaseExcept(endpoint, wanted) + r.mu.Lock() + defer r.mu.Unlock() + if len(wanted) != 0 { + if r.owners[endpoint] == nil { + r.owners[endpoint] = make(map[string]bool, len(wanted)) + } + for owner := range wanted { + r.owners[endpoint][owner] = true + } + } + r.recordStatesLocked(endpoint, entries) +} + +// recordStatesLocked replaces endpoint's producer states with entries and +// exports the node's counts. +func (r *ServiceProducerHealthReconciler) recordStatesLocked(endpoint types.NamespacedName, + entries []networkv1alpha1.ServiceEndpointProducerStatus, +) { + prefix := endpoint.String() + "|" + for key := range r.states { + if strings.HasPrefix(key, prefix) { + delete(r.states, key) + } + } + for _, entry := range entries { + r.states[producerProbeOwner(endpoint, types.NamespacedName{Namespace: entry.Namespace, Name: entry.Name})] = + entry.State + } + counts := make(map[string]int) + for _, state := range r.states { + counts[string(state)]++ + } + r.Metrics.SetProducers(counts) +} + +// publish applies entries as this node's part of endpoint's status.producers, +// unless this node's published entries already equal them. +func (r *ServiceProducerHealthReconciler) publish(ctx context.Context, endpoint *networkv1alpha1.ServiceEndpoint, + entries []networkv1alpha1.ServiceEndpointProducerStatus, +) error { + var current []networkv1alpha1.ServiceEndpointProducerStatus + for _, entry := range endpoint.Status.Producers { + if entry.Node == r.NodeName { + current = append(current, entry) + } + } + sortProducerEntries(current) + sortProducerEntries(entries) + if producerEntriesEqual(current, entries) { + return nil + } + if entries == nil { + entries = []networkv1alpha1.ServiceEndpointProducerStatus{} + } + body, err := json.Marshal(map[string]any{ + "apiVersion": networkv1alpha1.GroupVersion.String(), + "kind": "ServiceEndpoint", + "metadata": map[string]string{"name": endpoint.Name, "namespace": endpoint.Namespace}, + "status": map[string]any{"producers": entries}, + }) + if err != nil { + return err + } + obj := &networkv1alpha1.ServiceEndpoint{} + obj.Name, obj.Namespace = endpoint.Name, endpoint.Namespace + err = r.Status().Patch(ctx, obj, client.RawPatch(types.ApplyPatchType, body), + client.FieldOwner(nodeFieldOwner(r.NodeName)), client.ForceOwnership) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + return fmt.Errorf("apply status.producers of ServiceEndpoint %s/%s: %w", endpoint.Namespace, endpoint.Name, err) + } + return nil +} + +func sortProducerEntries(entries []networkv1alpha1.ServiceEndpointProducerStatus) { + sort.Slice(entries, func(i, j int) bool { + if entries[i].Namespace != entries[j].Namespace { + return entries[i].Namespace < entries[j].Namespace + } + return entries[i].Name < entries[j].Name + }) +} + +func producerEntriesEqual(a, b []networkv1alpha1.ServiceEndpointProducerStatus) bool { + if len(a) != len(b) { + return false + } + for i := range a { + x, y := a[i], b[i] + if x.Namespace != y.Namespace || x.Name != y.Name || x.AttachmentUID != y.AttachmentUID || + x.Node != y.Node || x.Port != y.Port || x.State != y.State || x.Reason != y.Reason || + x.Message != y.Message || !x.LastTransitionTime.Equal(&y.LastTransitionTime) { + return false + } + } + return true +} + +// SetupWithManager registers the reconciler, and the probe loop when Prober +// is nil, with the manager. The probe loops stop with the manager. +func (r *ServiceProducerHealthReconciler) SetupWithManager(mgr ctrl.Manager) error { + r.events = make(chan event.GenericEvent, 1024) + r.owners = make(map[types.NamespacedName]map[string]bool) + r.states = make(map[string]networkv1alpha1.BackendHealthState) + if r.Prober == nil { + dial := r.Dial + if dial == nil { + dial = healthprobe.Dial + } + ctx, cancel := context.WithCancel(context.Background()) + if err := mgr.Add(manager.RunnableFunc(func(stop context.Context) error { + <-stop.Done() + cancel() + return nil + })); err != nil { + cancel() + return fmt.Errorf("register service producer probe loops: %w", err) + } + r.Prober = healthprobe.NewProber(ctx, dial, func(owner string) { r.enqueue(ctx, owner) }) + } + + return ctrl.NewControllerManagedBy(mgr). + // Status writes, this node's included, change no probe. + For(&networkv1alpha1.ServiceEndpoint{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + // A producer arriving on, leaving or changing on this node changes + // what it probes. + Watches(&cloudv1alpha1.VPCAttachment{}, handler.EnqueueRequestsFromMapFunc(r.spreadEndpoints), + builder.WithPredicates(r.attachmentOnNode())). + // A probe loop's decision changed. + WatchesRawSource(source.Channel(r.events, &handler.EnqueueRequestForObject{})). + Named("service-producer-health"). + Complete(r) +} + +// enqueue asks for a reconcile of the endpoint whose probe owner changed. +func (r *ServiceProducerHealthReconciler) enqueue(ctx context.Context, owner string) { + endpoint, _, _ := strings.Cut(owner, "|") + namespace, name, ok := strings.Cut(endpoint, "/") + if !ok { + return + } + select { + case r.events <- event.GenericEvent{Object: &networkv1alpha1.ServiceEndpoint{ + ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, + }}: + case <-ctx.Done(): + } +} + +// spreadEndpoints maps any attachment event to every Spread endpoint. +func (r *ServiceProducerHealthReconciler) spreadEndpoints( + ctx context.Context, _ client.Object, +) []ctrlreconcile.Request { + list := &networkv1alpha1.ServiceEndpointList{} + if err := r.List(ctx, list); err != nil { + log.FromContext(ctx).Error(err, "list ServiceEndpoints for VPCAttachment change") + return nil + } + var reqs []ctrlreconcile.Request + for i := range list.Items { + if list.Items[i].Spec.Distribution == networkv1alpha1.ServiceEndpointDistributionSpread { + reqs = append(reqs, ctrlreconcile.Request{NamespacedName: client.ObjectKeyFromObject(&list.Items[i])}) + } + } + return reqs +} + +// attachmentOnNode passes events of attachments that are, or were, on this +// node. +func (r *ServiceProducerHealthReconciler) attachmentOnNode() predicate.Predicate { + onNode := func(obj client.Object) bool { + attachment, ok := obj.(*cloudv1alpha1.VPCAttachment) + return ok && attachment.Status.Node == r.NodeName + } + return predicate.Funcs{ + CreateFunc: func(e event.CreateEvent) bool { return onNode(e.Object) }, + DeleteFunc: func(e event.DeleteEvent) bool { return onNode(e.Object) }, + GenericFunc: func(e event.GenericEvent) bool { return onNode(e.Object) }, + UpdateFunc: func(e event.UpdateEvent) bool { + return onNode(e.ObjectOld) || onNode(e.ObjectNew) + }, + } +} + +// nodeFieldOwner is this node's server-side apply field manager, within the +// 128-byte limit for any node name. +func nodeFieldOwner(node string) string { + owner := "galactic-router/" + node + if len(owner) <= 128 { + return owner + } + sum := sha256.Sum256([]byte(node)) + return "galactic-router/" + node[:64] + "-" + hex.EncodeToString(sum[:8]) +} diff --git a/internal/controller/serviceproducerhealth_controller_test.go b/internal/controller/serviceproducerhealth_controller_test.go new file mode 100644 index 000000000..e7fe23f53 --- /dev/null +++ b/internal/controller/serviceproducerhealth_controller_test.go @@ -0,0 +1,254 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/healthprobe" +) + +const ( + producerHealthEndpoint = "resolver" + producerHealthLabel = "role" + producerHealthAddress = "fd53::53" + producerHealthRefused = "connection refused" + producerHealthNamespace = "dns" + producerHealthNode = "node-a" + producerHealthOtherNode = "node-b" +) + +// ownerProber returns a decision per probe owner, Unknown/Pending for any +// owner without one, and records the calls. +type ownerProber struct { + decisions map[string]healthprobe.Decision + owners map[string]string + targets map[string]healthprobe.Target + seeds map[string]*healthprobe.Decision +} + +func newOwnerProber() *ownerProber { + return &ownerProber{ + decisions: map[string]healthprobe.Decision{}, owners: map[string]string{}, + targets: map[string]healthprobe.Target{}, seeds: map[string]*healthprobe.Decision{}, + } +} + +func (p *ownerProber) Ensure(owner, id string, t healthprobe.Target, seed *healthprobe.Decision) healthprobe.Decision { + p.owners[owner], p.targets[owner], p.seeds[owner] = id, t, seed + if d, ok := p.decisions[owner]; ok { + return d + } + return healthprobe.Decision{State: healthprobe.StateUnknown, Reason: healthprobe.ReasonPending, + Since: time.Unix(1_700_000_000, 0)} +} + +func (p *ownerProber) Release(owner string) { delete(p.owners, owner) } + +func startProducerHealthAPI(t *testing.T) client.Client { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + if os.Getenv("CI") != "" { + t.Fatal("KUBEBUILDER_ASSETS not set in CI") + } + t.Skip("KUBEBUILDER_ASSETS not set") + } + environment := &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd")}, + ErrorIfCRDPathMissing: true, + } + cfg, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + scheme := runtime.NewScheme() + _ = corev1.AddToScheme(scheme) + _ = networkv1alpha1.AddToScheme(scheme) + _ = cloudv1alpha1.AddToScheme(scheme) + c, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + if err := c.Create(context.Background(), &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{Name: producerHealthNamespace}, + }); err != nil { + t.Fatal(err) + } + return c +} + +func createProducer(t *testing.T, c client.Client, name, node, address string) *cloudv1alpha1.VPCAttachment { + t.Helper() + ctx := context.Background() + attachment := &cloudv1alpha1.VPCAttachment{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: producerHealthNamespace, + Labels: map[string]string{producerHealthLabel: producerHealthEndpoint}}, + Spec: cloudv1alpha1.VPCAttachmentSpec{ + VPC: cloudv1alpha1.VPCRef{Name: "vpc"}, + Interface: cloudv1alpha1.VPCAttachmentInterface{ + Name: "net1", Addresses: []cloudv1alpha1.IPAddress{cloudv1alpha1.IPAddress(address)}, + }, + }, + } + if err := c.Create(ctx, attachment); err != nil { + t.Fatal(err) + } + attachment.Status = cloudv1alpha1.VPCAttachmentStatus{ + ObservedGeneration: attachment.Generation, Node: node, VPC: "vpc1", VPCAttachment: "att" + name, + HostInterface: "host-" + name, + Conditions: []metav1.Condition{ + {Type: cloudv1alpha1.ConditionTypeReady, Status: metav1.ConditionTrue, Reason: "Fixture", + LastTransitionTime: metav1.Now()}, + {Type: cloudv1alpha1.ConditionTypeProgrammed, Status: metav1.ConditionTrue, Reason: "Fixture", + LastTransitionTime: metav1.Now()}, + }, + } + if err := c.Status().Update(ctx, attachment); err != nil { + t.Fatal(err) + } + return attachment +} + +func producerEntries(t *testing.T, c client.Client) map[string]networkv1alpha1.ServiceEndpointProducerStatus { + t.Helper() + endpoint := &networkv1alpha1.ServiceEndpoint{} + key := types.NamespacedName{Namespace: producerHealthNamespace, Name: producerHealthEndpoint} + if err := c.Get(context.Background(), key, + endpoint); err != nil { + t.Fatal(err) + } + out := map[string]networkv1alpha1.ServiceEndpointProducerStatus{} + for _, entry := range endpoint.Status.Producers { + out[entry.Name] = entry + } + return out +} + +func TestServiceProducerHealthReconcilerPublishesThisNodesProducers(t *testing.T) { + c := startProducerHealthAPI(t) + ctx := context.Background() + endpoint := &networkv1alpha1.ServiceEndpoint{ + ObjectMeta: metav1.ObjectMeta{Name: producerHealthEndpoint, Namespace: producerHealthNamespace}, + Spec: networkv1alpha1.ServiceEndpointSpec{ + ServiceClass: "dns", Address: producerHealthAddress, Port: 53, Protocol: networkv1alpha1.NetworkServiceProtocolUDP, + DeliveryMode: networkv1alpha1.ServiceEndpointDeliveryModeNodeLocal, + AttachmentSelector: &metav1.LabelSelector{ + MatchLabels: map[string]string{producerHealthLabel: producerHealthEndpoint}, + }, + Distribution: networkv1alpha1.ServiceEndpointDistributionSpread, + HealthCheck: &networkv1alpha1.ServiceEndpointHealthCheck{ + Port: 8053, IntervalSeconds: 2, TimeoutSeconds: 1, UnhealthyThreshold: 2, HealthyThreshold: 1, + }, + }, + } + if err := c.Create(ctx, endpoint); err != nil { + t.Fatal(err) + } + first := createProducer(t, c, "resolver-a", producerHealthNode, "fd00:1::a/64") + second := createProducer(t, c, "resolver-b", producerHealthNode, "fd00:1::b/64") + other := createProducer(t, c, "resolver-c", producerHealthOtherNode, "fd00:1::c/64") + + key := types.NamespacedName{Namespace: producerHealthNamespace, Name: producerHealthEndpoint} + firstOwner := producerProbeOwner(key, client.ObjectKeyFromObject(first)) + secondOwner := producerProbeOwner(key, client.ObjectKeyFromObject(second)) + since := time.Unix(1_700_000_100, 0) + prober := newOwnerProber() + prober.decisions[firstOwner] = healthprobe.Decision{State: healthprobe.StateHealthy, + Reason: healthprobe.ReasonProbeSucceeded, Since: since} + prober.decisions[secondOwner] = healthprobe.Decision{State: healthprobe.StateUnhealthy, + Reason: healthprobe.ReasonProbeFailed, Message: producerHealthRefused, Since: since} + reconcilerA := &ServiceProducerHealthReconciler{Client: c, NodeName: producerHealthNode, Prober: prober} + reconcilerB := &ServiceProducerHealthReconciler{Client: c, NodeName: producerHealthOtherNode, + Prober: newOwnerProber()} + reconcile := func(r *ServiceProducerHealthReconciler) { + t.Helper() + if _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: key}); err != nil { + t.Fatalf("Reconcile on %s: %v", r.NodeName, err) + } + } + + reconcile(reconcilerB) + reconcile(reconcilerA) + entries := producerEntries(t, c) + if len(entries) != 3 { + t.Fatalf("status.producers = %v, want resolver-a, resolver-b and resolver-c", entries) + } + if got := entries["resolver-a"]; got.State != networkv1alpha1.BackendHealthHealthy || + got.Node != producerHealthNode || got.AttachmentUID != first.UID || got.Port != 8053 || + !got.LastTransitionTime.Time.Equal(since) { + t.Errorf("resolver-a = %+v, want Healthy on %s for its UID and port 8053", got, producerHealthNode) + } + if got := entries["resolver-b"]; got.State != networkv1alpha1.BackendHealthUnhealthy || + got.Message != producerHealthRefused { + t.Errorf("resolver-b = %+v, want Unhealthy with the probe error", got) + } + if got := entries["resolver-c"]; got.Node != producerHealthOtherNode || + got.State != networkv1alpha1.BackendHealthUnknown { + t.Errorf("resolver-c = %+v, want Unknown from %s", got, producerHealthOtherNode) + } + target := prober.targets[firstOwner] + if target.Interface != "host-resolver-a" || target.Addr.String() != "fd00:1::a" || target.Port != 8053 || + target.Config != (healthprobe.Config{Interval: 2 * time.Second, Timeout: time.Second, + UnhealthyThreshold: 2, HealthyThreshold: 1}) { + t.Errorf("resolver-a target = %+v", target) + } + if _, probed := prober.owners[producerProbeOwner(key, client.ObjectKeyFromObject(other))]; probed { + t.Error("node-a probes a producer on node-b") + } + + // A restarted router starts each probe from its published decision. + restarted := newOwnerProber() + reconcile(&ServiceProducerHealthReconciler{Client: c, NodeName: producerHealthNode, Prober: restarted}) + if seed := restarted.seeds[secondOwner]; seed == nil || seed.State != healthprobe.StateUnhealthy { + t.Errorf("seed for resolver-b = %+v, want its published Unhealthy decision", seed) + } + + // A producer that stops being selected loses its probe and its entry; + // the other node's entry stays. + second.Labels = map[string]string{producerHealthLabel: "retired"} + if err := c.Update(ctx, second); err != nil { + t.Fatal(err) + } + reconcile(reconcilerA) + entries = producerEntries(t, c) + if _, ok := entries["resolver-b"]; ok || len(entries) != 2 { + t.Errorf("status.producers after deselecting resolver-b = %v, want resolver-a and resolver-c", entries) + } + if _, probed := prober.owners[secondOwner]; probed { + t.Error("deselected producer is still probed") + } + + // Turning Spread off removes this node's entries and stops its probes. + if err := c.Get(ctx, key, endpoint); err != nil { + t.Fatal(err) + } + endpoint.Spec.Distribution, endpoint.Spec.HealthCheck = networkv1alpha1.ServiceEndpointDistributionSingle, nil + if err := c.Update(ctx, endpoint); err != nil { + t.Fatal(err) + } + reconcile(reconcilerA) + entries = producerEntries(t, c) + if _, ok := entries["resolver-a"]; ok || len(entries) != 1 { + t.Errorf("status.producers after Single = %v, want only node-b's resolver-c", entries) + } + if len(prober.owners) != 0 { + t.Errorf("probes after Single = %v, want none", prober.owners) + } +} diff --git a/internal/controller/serviceroute_controller.go b/internal/controller/serviceroute_controller.go index 0b3cd3135..ea82dfd88 100644 --- a/internal/controller/serviceroute_controller.go +++ b/internal/controller/serviceroute_controller.go @@ -618,6 +618,36 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked( desired[intent.Attachment] = intent } + // A LocalSet intent whose producers or their health changed is replaced + // in place: the new one goes in before the old one comes out, so the + // consumer's route never disappears and the flows of producers that stay + // keep going. + for attachment, existing := range current { + next, ok := desired[attachment] + if !ok || existing.Kind != serviceroute.RouteIntentLocalSet || next.Kind != serviceroute.RouteIntentLocalSet || + reflect.DeepEqual(existing, next) { + continue + } + if err := r.Programmer.Apply(next); err != nil { + // The two cannot coexist, for example because the route's + // authorization changed too. Fall back to the replacement below. + r.Metrics.ObserveOperation("apply", err) + if cleanupErr := r.Programmer.Cleanup(next); cleanupErr != nil { + return errors.Join(err, &serviceRoutePolicyCleanupError{err: cleanupErr}) + } + continue + } + r.Metrics.ObserveOperation("apply", nil) + if err := r.Programmer.Remove(existing); err != nil { + r.Metrics.ObserveOperation("remove", err) + // Take the new intent back out so the programmer again holds only + // what Applied records. + return errors.Join(&serviceRoutePolicyCleanupError{err: err}, r.Programmer.Remove(next)) + } + r.Metrics.ObserveOperation("remove", nil) + current[attachment] = next + } + // Revoke obsolete or changed intents first. Each successful operation is // reflected in Applied immediately, so a later failure leaves an accurate, // retryable snapshot rather than leaking untracked kernel state. diff --git a/internal/controller/serviceroute_spread_test.go b/internal/controller/serviceroute_spread_test.go new file mode 100644 index 000000000..99d7ba9b9 --- /dev/null +++ b/internal/controller/serviceroute_spread_test.go @@ -0,0 +1,95 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "errors" + "testing" + + "k8s.io/apimachinery/pkg/types" + + "go.datum.net/galactic/internal/serviceroute" +) + +// orderedRouteProgrammer logs every Apply and Remove as "apply " or +// "remove ", naming an intent by its first producer's device. +type orderedRouteProgrammer struct { + retryRouteProgrammer + log []string + applyErr error +} + +func (p *orderedRouteProgrammer) Apply(intent serviceroute.RouteIntent) error { + p.log = append(p.log, "apply "+intent.Producers[0].Device) + return p.applyErr +} + +func (p *orderedRouteProgrammer) Remove(intent serviceroute.RouteIntent) error { + p.log = append(p.log, "remove "+intent.Producers[0].Device) + return nil +} + +const applyNew = "apply new" + +func localSetTestIntent(device string, draining bool) serviceroute.RouteIntent { + return serviceroute.RouteIntent{ + Attachment: types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName}, + Kind: serviceroute.RouteIntentLocalSet, + Producers: []serviceroute.ProducerTarget{{Device: device, Draining: draining}}, + } +} + +// A LocalSet intent whose producer set changes is applied before the old one +// is removed, so the consumer's route never disappears. +func TestServiceRouteReplacePolicyAppliesChangedProducerSetFirst(t *testing.T) { + programmer := &orderedRouteProgrammer{} + reconciler := &ServiceRoutePolicyReconciler{Programmer: programmer} + policy := types.NamespacedName{Namespace: testServiceRoutePolicyNamespace, Name: testServiceRouteName} + + if err := reconciler.replacePolicy(policy, []serviceroute.RouteIntent{localSetTestIntent("old", false)}); err != nil { + t.Fatal(err) + } + if err := reconciler.replacePolicy(policy, []serviceroute.RouteIntent{localSetTestIntent("new", true)}); err != nil { + t.Fatal(err) + } + want := []string{"apply old", applyNew, "remove old"} + if len(programmer.log) != len(want) { + t.Fatalf("operations = %v, want %v", programmer.log, want) + } + for i := range want { + if programmer.log[i] != want[i] { + t.Fatalf("operations = %v, want %v", programmer.log, want) + } + } + consumer := types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName} + if got := reconciler.Applied[policy][consumer].Producers[0].Device; got != "new" { + t.Fatalf("applied intent producer = %s, want new", got) + } +} + +// When the new intent cannot coexist with the old one, the replacement falls +// back to removing the old intent first. +func TestServiceRouteReplacePolicyFallsBackWhenProducerSetsCannotCoexist(t *testing.T) { + programmer := &orderedRouteProgrammer{} + reconciler := &ServiceRoutePolicyReconciler{Programmer: programmer} + policy := types.NamespacedName{Namespace: testServiceRoutePolicyNamespace, Name: testServiceRouteName} + if err := reconciler.replacePolicy(policy, []serviceroute.RouteIntent{localSetTestIntent("old", false)}); err != nil { + t.Fatal(err) + } + programmer.log = nil + programmer.applyErr = errors.New("conflicting redirect targets") + if err := reconciler.replacePolicy(policy, []serviceroute.RouteIntent{localSetTestIntent("new", false)}); err == nil { + t.Fatal("replacePolicy succeeded with a failing Apply") + } + want := []string{applyNew, "remove old", applyNew} + if len(programmer.log) != len(want) { + t.Fatalf("operations = %v, want %v", programmer.log, want) + } + for i := range want { + if programmer.log[i] != want[i] { + t.Fatalf("operations = %v, want %v", programmer.log, want) + } + } +} diff --git a/internal/serviceroute/dataplane.go b/internal/serviceroute/dataplane.go index f584d7371..1526e8dfe 100644 --- a/internal/serviceroute/dataplane.go +++ b/internal/serviceroute/dataplane.go @@ -84,6 +84,25 @@ type appliedEntry struct { access *accessRef grant *grantRef deny *denyRef + set *setRef +} + +// setRef is a LocalSet route's producer set, under the route's key. +type setRef struct { + ingressIfindex uint32 + address string + protocol uint8 + port uint16 + count int + members [serviceroutemap.MaxProducers]serviceroutemap.ProducerMember +} + +// setState is every applied ref of one producer set key, oldest first. The +// newest one is in the map: an intent that replaces another is applied before +// the old one is removed, so its set must win, and removing the newer one +// first puts the older one back. +type setState struct { + refs []setRef } type grantRef struct { @@ -118,6 +137,7 @@ type EBPFRouteProgrammer struct { accessRefs map[accessKey]accessState denyRefs map[denyKey]denyState grantRefs map[grantRef]int + setRefs map[string]setState appliedRefs map[string][][]appliedEntry desiredIntents map[string][]RouteIntent pendingRollbacks map[string][]appliedEntry @@ -303,6 +323,16 @@ func (p *EBPFRouteProgrammer) finalizeLocked() error { IngressIfindex: deny.ingressIfindex, Address: net.ParseIP(deny.address), }) } + for _, state := range p.setRefs { + if len(state.refs) == 0 { + continue + } + ref := state.refs[len(state.refs)-1] + snapshot.ProducerSets = append(snapshot.ProducerSets, serviceroutemap.RouteIdentity{ + IngressIfindex: ref.ingressIfindex, Address: net.ParseIP(ref.address), + Protocol: ref.protocol, Port: ref.port, + }) + } for grant, count := range p.grantRefs { if count == 0 { continue @@ -348,6 +378,7 @@ func (p *EBPFRouteProgrammer) ensureOpen() error { p.accessRefs = make(map[accessKey]accessState) p.denyRefs = make(map[denyKey]denyState) p.grantRefs = make(map[grantRef]int) + p.setRefs = make(map[string]setState) p.appliedRefs = make(map[string][][]appliedEntry) p.pendingRollbacks = make(map[string][]appliedEntry) p.failedMutations = make(map[string]struct{}) @@ -552,6 +583,7 @@ func (p *EBPFRouteProgrammer) repairDesired() error { p.accessRefs = make(map[accessKey]accessState) p.denyRefs = make(map[denyKey]denyState) p.grantRefs = make(map[grantRef]int) + p.setRefs = make(map[string]setState) p.appliedRefs = make(map[string][][]appliedEntry) p.pendingRollbacks = make(map[string][]appliedEntry) p.failedMutations = make(map[string]struct{}) @@ -729,12 +761,21 @@ func (p *EBPFRouteProgrammer) entries(intent RouteIntent) ([]appliedEntry, error var targetIfindex uint32 var producerToken uint64 var targetSID [16]byte - if intent.Kind == RouteIntentRemoteConsumer { + var set *setRef + switch intent.Kind { + case RouteIntentLocalSet: + var producerEntries []appliedEntry + set, producerEntries, err = p.producerSet(intent) + if err != nil { + return nil, err + } + entries = append(entries, producerEntries...) + case RouteIntentRemoteConsumer: targetSID, err = ipv6Bytes(intent.ServiceSID) if err != nil { return nil, err } - } else { + default: targetIfindex, err = p.target(intent.ServiceDevice) if err != nil { return nil, fmt.Errorf("resolve service interface %q: %w", intent.ServiceDevice, err) @@ -767,6 +808,14 @@ func (p *EBPFRouteProgrammer) entries(intent RouteIntent) ([]appliedEntry, error ingressIfindex: consumerIfindex, address: frontendIP.String(), protocol: protocol, port: uint16(port.Port), attachmentToken: consumerToken, }}) + // The set goes in before the route that reads it, and so comes out + // after it. + if set != nil { + portSet := *set + portSet.ingressIfindex, portSet.address = consumerIfindex, frontendIP.String() + portSet.protocol, portSet.port = protocol, uint16(port.Port) + entries = append(entries, appliedEntry{set: &portSet}) + } ref := routeRef{ingressIfindex: consumerIfindex, address: frontendIP.String(), backendAddress: serviceIP.String(), mode: intent.Kind, protocol: protocol, port: uint16(port.Port), grantID: intent.GrantID, @@ -777,6 +826,47 @@ func (p *EBPFRouteProgrammer) entries(intent RouteIntent) ([]appliedEntry, error return entries, nil } +// producerSet resolves a LocalSet intent's producers to their interfaces and +// identity tokens. It returns the set, without its route key, and each +// producer's reply markers. +func (p *EBPFRouteProgrammer) producerSet(intent RouteIntent) (*setRef, []appliedEntry, error) { + if !p.tables.ProducerSetsAvailable() { + return nil, nil, ErrProducerSetsUnavailable + } + if len(intent.Producers) == 0 || len(intent.Producers) > serviceroutemap.MaxProducers { + return nil, nil, fmt.Errorf("service route producer set has %d members, want 1-%d", + len(intent.Producers), serviceroutemap.MaxProducers) + } + serviceIP := intent.Service.IP.String() + set := &setRef{count: len(intent.Producers)} + entries := make([]appliedEntry, 0, 2*len(intent.Producers)) + for i, producer := range intent.Producers { + ifindex, err := p.target(producer.Device) + if err != nil { + return nil, nil, fmt.Errorf("resolve service interface %q: %w", producer.Device, err) + } + token, err := p.tables.IdentityToken(ifindex) + if err != nil { + return nil, nil, err + } + if err := p.tables.SetPeer(ifindex, token, producer.NextHop); err != nil { + return nil, nil, err + } + set.members[i] = serviceroutemap.ProducerMember{Ifindex: ifindex, Token: token, Eligible: !producer.Draining} + entries = append(entries, + appliedEntry{access: &accessRef{ + ingressIfindex: ifindex, address: serviceIP, attachmentToken: token, + markerDirections: serviceroutemap.MarkerReply, + }}, + appliedEntry{deny: &denyRef{ + ingressIfindex: ifindex, address: serviceIP, attachmentToken: token, + markerDirections: serviceroutemap.MarkerReply, + }}, + ) + } + return set, entries, nil +} + func ipv6Bytes(ip net.IP) ([16]byte, error) { var out [16]byte if ip == nil || ip.To4() != nil || ip.To16() == nil { @@ -825,6 +915,18 @@ func (p *EBPFRouteProgrammer) acquire(entry appliedEntry) error { p.accessRefs[key] = state return nil } + if entry.set != nil { + key := setRefKey(*entry.set) + state := p.setRefs[key] + if len(state.refs) == 0 || state.refs[len(state.refs)-1] != *entry.set { + if err := p.writeSet(*entry.set); err != nil { + return err + } + } + state.refs = append(state.refs, *entry.set) + p.setRefs[key] = state + return nil + } if entry.deny != nil { key := denyRefKey(*entry.deny) state := p.denyRefs[key] @@ -852,12 +954,17 @@ func (p *EBPFRouteProgrammer) acquire(entry appliedEntry) error { return nil } var err error - if entry.route.mode == RouteIntentRemoteConsumer { + switch entry.route.mode { + case RouteIntentLocalSet: + err = p.tables.RegisterLocalSetRoute(entry.route.ingressIfindex, net.ParseIP(entry.route.address), + net.ParseIP(entry.route.backendAddress), entry.route.protocol, entry.route.port, + entry.route.consumerToken, authorizationTime(entry.route.authorizationValidUntil)) + case RouteIntentRemoteConsumer: err = p.tables.RegisterRemoteRoute(entry.route.ingressIfindex, net.ParseIP(entry.route.address), net.ParseIP(entry.route.backendAddress), [16]byte(entry.route.grantID), entry.route.protocol, entry.route.port, net.IP(entry.route.targetSID[:]), entry.route.consumerToken, authorizationTime(entry.route.authorizationValidUntil)) - } else { + default: err = p.tables.RegisterRoute(entry.route.ingressIfindex, net.ParseIP(entry.route.address), net.ParseIP(entry.route.backendAddress), entry.route.protocol, entry.route.port, entry.route.targetIfindex, @@ -871,6 +978,9 @@ func (p *EBPFRouteProgrammer) acquire(entry appliedEntry) error { } func (p *EBPFRouteProgrammer) release(entry appliedEntry) error { + if entry.set != nil { + return p.releaseSet(*entry.set) + } if entry.grant != nil { count := p.grantRefs[*entry.grant] if count > 1 { @@ -949,6 +1059,50 @@ func (p *EBPFRouteProgrammer) release(entry appliedEntry) error { return nil } +func (p *EBPFRouteProgrammer) releaseSet(ref setRef) error { + key := setRefKey(ref) + state, ok := p.setRefs[key] + if !ok { + return nil + } + index := -1 + for i := len(state.refs) - 1; i >= 0; i-- { + if state.refs[i] == ref { + index = i + break + } + } + if index < 0 { + return nil + } + if len(state.refs) == 1 { + if err := p.tables.UnregisterProducerSet(ref.ingressIfindex, net.ParseIP(ref.address), + ref.protocol, ref.port); err != nil { + return err + } + delete(p.setRefs, key) + return nil + } + top := state.refs[len(state.refs)-1] + remaining := append(append([]setRef(nil), state.refs[:index]...), state.refs[index+1:]...) + if next := remaining[len(remaining)-1]; next != top { + if err := p.writeSet(next); err != nil { + return err + } + } + p.setRefs[key] = setState{refs: remaining} + return nil +} + +func (p *EBPFRouteProgrammer) writeSet(ref setRef) error { + return p.tables.RegisterProducerSet(ref.ingressIfindex, net.ParseIP(ref.address), ref.protocol, ref.port, + ref.members[:ref.count]) +} + +func setRefKey(ref setRef) string { + return fmt.Sprintf("%d|%s|%d|%d", ref.ingressIfindex, ref.address, ref.protocol, ref.port) +} + func protocolNumber(protocol api.NetworkServiceProtocol) (uint8, error) { switch protocol { case api.NetworkServiceProtocolTCP: @@ -1050,6 +1204,10 @@ func intentKey(intent RouteIntent) string { for _, port := range intent.Ports { fmt.Fprintf(&builder, "|%s:%d", port.Protocol, port.Port) } + for _, producer := range intent.Producers { + fmt.Fprintf(&builder, "|producer:%s,%s,%s,%t", + producer.Attachment, producer.Device, producer.NextHop, producer.Draining) + } return builder.String() } @@ -1070,6 +1228,13 @@ func cloneRouteIntent(intent RouteIntent) RouteIntent { cloned.ConsumerNextHop = append(net.IP(nil), intent.ConsumerNextHop...) cloned.ServiceNextHop = append(net.IP(nil), intent.ServiceNextHop...) cloned.Ports = append([]api.ServiceRouteProtocolPort(nil), intent.Ports...) + if intent.Producers != nil { + cloned.Producers = make([]ProducerTarget, len(intent.Producers)) + for i, producer := range intent.Producers { + cloned.Producers[i] = producer + cloned.Producers[i].NextHop = append(net.IP(nil), producer.NextHop...) + } + } return cloned } diff --git a/internal/serviceroute/dataplane_spread_test.go b/internal/serviceroute/dataplane_spread_test.go new file mode 100644 index 000000000..1f32fda10 --- /dev/null +++ b/internal/serviceroute/dataplane_spread_test.go @@ -0,0 +1,209 @@ +//go:build linux + +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package serviceroute + +import ( + "errors" + "fmt" + "net" + "reflect" + "testing" + + "k8s.io/apimachinery/pkg/types" + + api "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/plumbing/ebpf/serviceroutemap" +) + +// spreadTestProgrammer returns a programmer over persisted fakes with a +// producer set map, its route and producer set tables, and the interfaces +// consumer0=10, producer-a=20, producer-b=21 and producer-c=22. +func spreadTestProgrammer() (*EBPFRouteProgrammer, *persistedPolicyTable, *persistedPolicyTable) { + routes, sets := &persistedPolicyTable{}, &persistedPolicyTable{} + programmer := testRouteProgrammer(&recordingTable{}, &recordingTable{}, &recordingTable{}) + programmer.tables = serviceroutemap.New(routes, &persistedPolicyTable{}, &persistedPolicyTable{}, + &persistedPolicyTable{}, + &recordingTable{identityTokens: map[uint32]uint64{10: 100, 20: 200, 21: 210, 22: 220}}, + &persistedPolicyTable{}, &persistedPolicyTable{}, &persistedPolicyTable{}).WithProducerSets(sets) + programmer.mapIDs = mapSetIDs{1, 2, 3, 4, 5, 6, 7, 8, 9} + programmer.mapIDsValid = true + programmer.readMapIDsFn = func(string) (mapSetIDs, error) { return programmer.mapIDs, nil } + programmer.targetIndexFn = func(name string) (uint32, error) { + switch name { + case testConsumerDeviceName: + return 10, nil + case "producer-a": + return 20, nil + case "producer-b": + return 21, nil + case "producer-c": + return 22, nil + default: + return 0, fmt.Errorf("unknown interface %q", name) + } + } + return programmer, routes, sets +} + +func localSetIntent(producers ...ProducerTarget) RouteIntent { + _, service, _ := net.ParseCIDR("fd00::53/128") + return RouteIntent{ + Attachment: types.NamespacedName{Namespace: eligibilityNamespace, Name: spreadConsumerName}, + Kind: RouteIntentLocalSet, + Service: service, + ConsumerDevice: testConsumerDeviceName, + Ports: []api.ServiceRouteProtocolPort{{Protocol: api.NetworkServiceProtocolUDP, Port: 53}}, + Producers: producers, + } +} + +func producer(device string, draining bool) ProducerTarget { + return ProducerTarget{Attachment: types.NamespacedName{Namespace: spreadProducerNamespace, Name: device}, + Device: device, + Draining: draining} +} + +// onlySet returns the members and eligible member ifindexes of the one row in +// sets. +func onlySet(t *testing.T, sets *persistedPolicyTable) (members, eligible []uint32) { + t.Helper() + if len(sets.rows) != 1 { + t.Fatalf("producer set rows = %d, want 1", len(sets.rows)) + } + for _, row := range sets.rows { + value := reflect.ValueOf(row) + count := int(value.FieldByName("Count").Uint()) + for i := range count { + members = append(members, uint32(value.FieldByName("Members").Index(i).FieldByName("Ifindex").Uint())) + } + for i := range int(value.FieldByName("EligibleCount").Uint()) { + index := int(value.FieldByName("Eligible").Index(i).Uint()) + eligible = append(eligible, members[index]) + } + } + return members, eligible +} + +func onlyRouteMode(t *testing.T, routes *persistedPolicyTable) uint64 { + t.Helper() + if len(routes.rows) != 1 { + t.Fatalf("route rows = %d, want 1", len(routes.rows)) + } + for _, row := range routes.rows { + return reflect.ValueOf(row).FieldByName("Mode").Uint() + } + return 0 +} + +func TestApplyLocalSetWritesRouteAndProducerSet(t *testing.T) { + programmer, routes, sets := spreadTestProgrammer() + intent := localSetIntent(producer("producer-a", false), producer("producer-b", true)) + if err := programmer.Apply(intent); err != nil { + t.Fatalf("Apply: %v", err) + } + if mode := onlyRouteMode(t, routes); mode != 3 { + t.Fatalf("route mode = %d, want LocalSet (3)", mode) + } + members, eligible := onlySet(t, sets) + if !reflect.DeepEqual(members, []uint32{20, 21}) || !reflect.DeepEqual(eligible, []uint32{20}) { + t.Fatalf("set members=%v eligible=%v, want [20 21] and [20]", members, eligible) + } + if err := programmer.Finalize(); err != nil { + t.Fatalf("Finalize: %v", err) + } + if len(routes.rows) != 1 || len(sets.rows) != 1 { + t.Fatalf("finalize swept live state: routes=%d sets=%d", len(routes.rows), len(sets.rows)) + } + if err := programmer.Remove(intent); err != nil { + t.Fatalf("Remove: %v", err) + } + if len(routes.rows) != 0 || len(sets.rows) != 0 { + t.Fatalf("remove left routes=%d sets=%d", len(routes.rows), len(sets.rows)) + } +} + +// Replacing a LocalSet intent applies the new one before the old one is +// removed, so the route row stays throughout and the newer set wins. +func TestLocalSetReplacementKeepsRouteAndPrefersNewestSet(t *testing.T) { + programmer, routes, sets := spreadTestProgrammer() + old := localSetIntent(producer("producer-a", false), producer("producer-b", false)) + next := localSetIntent(producer("producer-a", false), producer("producer-b", true), producer("producer-c", false)) + if intentKey(old) == intentKey(next) { + t.Fatal("intents with different producer sets share an identity") + } + if err := programmer.Apply(old); err != nil { + t.Fatal(err) + } + if err := programmer.Apply(next); err != nil { + t.Fatalf("Apply replacement alongside the old intent: %v", err) + } + if _, eligible := onlySet(t, sets); !reflect.DeepEqual(eligible, []uint32{20, 22}) { + t.Fatalf("eligible after replacement = %v, want [20 22]", eligible) + } + if err := programmer.Remove(old); err != nil { + t.Fatal(err) + } + if onlyRouteMode(t, routes) != 3 { + t.Fatal("route row lost while replacing its producer set") + } + if members, eligible := onlySet(t, sets); !reflect.DeepEqual(members, []uint32{20, 21, 22}) || + !reflect.DeepEqual(eligible, []uint32{20, 22}) { + t.Fatalf("set after removing old intent = %v/%v, want the replacement's", members, eligible) + } + + // Undoing a replacement, the newer intent removed first, restores the + // older set. + if err := programmer.Apply(old); err != nil { + t.Fatal(err) + } + if err := programmer.Remove(old); err != nil { + t.Fatal(err) + } + if _, eligible := onlySet(t, sets); !reflect.DeepEqual(eligible, []uint32{20, 22}) { + t.Fatalf("eligible after undoing a replacement = %v, want [20 22]", eligible) + } +} + +func TestLocalSetNeedsProducerSetMap(t *testing.T) { + programmer, _, _ := spreadTestProgrammer() + programmer.tables.WithProducerSets(nil) + err := programmer.Apply(localSetIntent(producer("producer-a", false))) + if !errors.Is(err, ErrProducerSetsUnavailable) { + t.Fatalf("Apply without a producer set map: %v, want ErrProducerSetsUnavailable", err) + } + if err := programmer.Apply(localTestIntentFor(testConsumerDeviceName, "producer-a")); err != nil { + t.Fatalf("Apply of a single-producer intent without a producer set map: %v", err) + } +} + +func localTestIntentFor(consumer, producer string) RouteIntent { + intent := localTestIntent() + intent.ConsumerDevice, intent.ServiceDevice = consumer, producer + return intent +} + +func TestFinalizeSweepsStaleProducerSets(t *testing.T) { + programmer, _, sets := spreadTestProgrammer() + stale := localSetIntent(producer("producer-a", false)) + stale.ConsumerDevice = testConsumerDeviceName + if err := programmer.tables.RegisterProducerSet(99, net.ParseIP("fd00::99"), serviceroutemap.ProtocolUDP, 53, + []serviceroutemap.ProducerMember{{Ifindex: 20, Token: 200, Eligible: true}}); err != nil { + t.Fatal(err) + } + if err := programmer.Apply(stale); err != nil { + t.Fatal(err) + } + if len(sets.rows) != 2 { + t.Fatalf("producer set rows = %d, want 2", len(sets.rows)) + } + if err := programmer.Finalize(); err != nil { + t.Fatal(err) + } + if members, _ := onlySet(t, sets); !reflect.DeepEqual(members, []uint32{20}) { + t.Fatalf("set left after sweep = %v", members) + } +} diff --git a/internal/serviceroute/dataplane_test.go b/internal/serviceroute/dataplane_test.go index b33633d3f..7c2fed9ee 100644 --- a/internal/serviceroute/dataplane_test.go +++ b/internal/serviceroute/dataplane_test.go @@ -129,6 +129,7 @@ func testRouteProgrammer(routes, access, grants *recordingTable) *EBPFRouteProgr accessRefs: make(map[accessKey]accessState), denyRefs: make(map[denyKey]denyState), grantRefs: make(map[grantRef]int), + setRefs: make(map[string]setState), appliedRefs: make(map[string][][]appliedEntry), desiredIntents: make(map[string][]RouteIntent), pendingRollbacks: make(map[string][]appliedEntry), @@ -295,6 +296,7 @@ func TestInitializeDoesNotDisableFinalizedPolicy(t *testing.T) { accessRefs: make(map[accessKey]accessState), denyRefs: make(map[denyKey]denyState), grantRefs: make(map[grantRef]int), + setRefs: make(map[string]setState), appliedRefs: make(map[string][][]appliedEntry), desiredIntents: make(map[string][]RouteIntent), pendingRollbacks: make(map[string][]appliedEntry), diff --git a/internal/serviceroute/metrics.go b/internal/serviceroute/metrics.go index 609456b3c..2fbcf98aa 100644 --- a/internal/serviceroute/metrics.go +++ b/internal/serviceroute/metrics.go @@ -20,6 +20,7 @@ type Metrics struct { reconcileTime prometheus.Histogram operations *prometheus.CounterVec programmed prometheus.Gauge + producers *prometheus.GaugeVec } // NewMetrics creates the service-route metrics. Call MustRegister once during @@ -48,12 +49,18 @@ func NewMetrics() *Metrics { Name: "programmed_routes", Help: "Number of attachment-scoped eBPF service paths currently tracked by the controller.", }), + producers: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: metricsNamespace, + Name: "producers", + Help: "Producers of Spread ServiceEndpoints on this node, by health state. " + + "Each endpoint's status.producers names them.", + }, []string{"state"}), } } // MustRegister registers all metrics owned by this package. func (m *Metrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.reconciliations, m.reconcileTime, m.operations, m.programmed) + reg.MustRegister(m.reconciliations, m.reconcileTime, m.operations, m.programmed, m.producers) } func (m *Metrics) ObserveReconcile(result string, duration time.Duration) { @@ -80,3 +87,14 @@ func (m *Metrics) SetProgrammedRoutes(count int) { m.programmed.Set(float64(count)) } } + +// SetProducers records how many producers this node probes in each health +// state. A state missing from counts is set to zero. +func (m *Metrics) SetProducers(counts map[string]int) { + if m == nil { + return + } + for _, state := range []string{"Healthy", "Unhealthy", "Unknown"} { + m.producers.WithLabelValues(state).Set(float64(counts[state])) + } +} diff --git a/internal/serviceroute/planner.go b/internal/serviceroute/planner.go index 98f243226..d79d4f6c6 100644 --- a/internal/serviceroute/planner.go +++ b/internal/serviceroute/planner.go @@ -26,6 +26,7 @@ type RouteIntentKind string const ( RouteIntentLocal RouteIntentKind = "Local" + RouteIntentLocalSet RouteIntentKind = "LocalSet" RouteIntentRemoteConsumer RouteIntentKind = "RemoteConsumer" RouteIntentRemoteProducer RouteIntentKind = "RemoteProducer" ) @@ -48,8 +49,27 @@ type RouteIntent struct { GrantID ServiceGrantID AuthorizationValidUntil time.Time Ports []networkv1alpha1.ServiceRouteProtocolPort + // Producers holds every producer on the consumer's node for a + // RouteIntentLocalSet intent, ordered by attachment name. It is empty for + // every other kind. + Producers []ProducerTarget } +// ProducerTarget is one member of a LocalSet intent's producer set. +type ProducerTarget struct { + Attachment types.NamespacedName + Device string + NextHop net.IP + // Draining keeps the producer's existing flows and replies but gives it + // no new flow. + Draining bool +} + +// ErrProducerSetsUnavailable is returned for a LocalSet intent while the +// node's datapath predates LocalSet routes. Every other intent still applies. +var ErrProducerSetsUnavailable = errors.New( + "node's eBPF datapath has no producer set map; LocalSet routes need a newer galactic-cni") + type RouteProgrammer interface { Initialize() error Apply(RouteIntent) error @@ -69,8 +89,11 @@ type DependencyNotReadyError struct{ Err error } func (e *DependencyNotReadyError) Error() string { return e.Err.Error() } func (e *DependencyNotReadyError) Unwrap() error { return e.Err } -// Compile deterministically picks one ready producer for every selected -// consumer and emits only intent halves owned by localNode. +// Compile deterministically picks the ready producers for every selected +// consumer and emits only intent halves owned by localNode. A Single endpoint +// gets one producer per consumer; a Spread endpoint gets every producer on the +// consumer's node as one LocalSet intent, or one remote producer when its node +// has none and DeliveryMode allows it. func Compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, localNode string, resolveSID SIDResolver, ) ([]RouteIntent, error) { @@ -123,6 +146,7 @@ func compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alph if err := validateProducerTopology(endpoint, producers); err != nil { return nil, err } + unhealthy := unhealthyProducers(endpoint, producers) consumers := readyAttachments(attachments) intents := make([]RouteIntent, 0, len(consumers)) @@ -133,11 +157,22 @@ func compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alph if !consumerMatchesVPC(policy, consumer, consumerVPCIdentity) { continue } - producer := chooseProducer(endpoint.Spec.DeliveryMode, consumer.Status.Node, producers) + local, producer := selectProducers(endpoint, consumer.Status.Node, producers, unhealthy) + consumerKey := types.NamespacedName{Namespace: consumer.Namespace, Name: consumer.Name} + if len(local) != 0 { + if consumer.Status.Node == localNode { + intents = append(intents, RouteIntent{ + Attachment: consumerKey, Kind: RouteIntentLocalSet, + Service: cloneIPNet(service), Frontend: cloneIPNet(frontend), ConsumerDevice: consumer.Status.HostInterface, + Ports: clonePorts(ports), ConsumerNextHop: attachmentNextHop(consumer, service.IP), + Producers: producerTargets(local, unhealthy, service.IP), + }) + } + continue + } if producer == nil { continue } - consumerKey := types.NamespacedName{Namespace: consumer.Namespace, Name: consumer.Name} producerKey := types.NamespacedName{Namespace: producer.Namespace, Name: producer.Name} if producer.Status.Node == consumer.Status.Node { if consumer.Status.Node == localNode { @@ -203,9 +238,24 @@ func attachmentNextHop(attachment *cloudv1alpha1.VPCAttachment, service net.IP) return ip } +// validateProducerTopology refuses a Single endpoint with two ready producers +// in one node and VPC, which its one-target route cannot tell apart, and a +// Spread endpoint with more producers on one node than a producer set holds. func validateProducerTopology(endpoint *networkv1alpha1.ServiceEndpoint, producers []*cloudv1alpha1.VPCAttachment, ) error { + if spread(endpoint) { + perNode := make(map[string]int, len(producers)) + for _, producer := range producers { + perNode[producer.Status.Node]++ + if perNode[producer.Status.Node] > networkv1alpha1.ServiceEndpointMaxProducersPerNode { + return fmt.Errorf("service endpoint %s/%s selects more than %d ready producer attachments on node %q", + endpoint.Namespace, endpoint.Name, networkv1alpha1.ServiceEndpointMaxProducersPerNode, + producer.Status.Node) + } + } + return nil + } type producerLocation struct { node string vpc string @@ -228,6 +278,14 @@ func validateProducerTopology(endpoint *networkv1alpha1.ServiceEndpoint, return nil } +// Producers returns the endpoint's ready producer attachments, ordered by +// namespace and name. +func Producers(endpoint *networkv1alpha1.ServiceEndpoint, + attachments []*cloudv1alpha1.VPCAttachment, +) ([]*cloudv1alpha1.VPCAttachment, error) { + return producerCandidates(endpoint, attachments) +} + func producerCandidates(endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, ) ([]*cloudv1alpha1.VPCAttachment, error) { @@ -279,6 +337,41 @@ func readyAttachments(attachments []*cloudv1alpha1.VPCAttachment) []*cloudv1alph return ready } +func spread(endpoint *networkv1alpha1.ServiceEndpoint) bool { + return endpoint.Spec.Distribution == networkv1alpha1.ServiceEndpointDistributionSpread +} + +// selectProducers returns, for a Spread endpoint, every producer on +// consumerNode as local. Otherwise, or when consumerNode has none, it returns +// the one producer a consumer there is sent to, or nil. A Spread endpoint's +// remote producer is the first one not Unhealthy, or the first one when all +// are. +func selectProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumerNode string, + producers []*cloudv1alpha1.VPCAttachment, unhealthy map[types.UID]bool, +) (local []*cloudv1alpha1.VPCAttachment, remote *cloudv1alpha1.VPCAttachment) { + if spread(endpoint) { + for _, producer := range producers { + if producer.Status.Node == consumerNode { + local = append(local, producer) + } + } + if len(local) != 0 { + return local, nil + } + if endpoint.Spec.DeliveryMode != networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal || + len(producers) == 0 { + return nil, nil + } + for _, producer := range producers { + if !unhealthy[producer.UID] { + return nil, producer + } + } + return nil, producers[0] + } + return nil, chooseProducer(endpoint.Spec.DeliveryMode, consumerNode, producers) +} + func chooseProducer(mode networkv1alpha1.ServiceEndpointDeliveryMode, consumerNode string, producers []*cloudv1alpha1.VPCAttachment, ) *cloudv1alpha1.VPCAttachment { @@ -293,6 +386,56 @@ func chooseProducer(mode networkv1alpha1.ServiceEndpointDeliveryMode, consumerNo return nil } +// unhealthyProducers returns the UIDs of a Spread endpoint's producers whose +// status entry, written by their own node for that same attachment, says +// Unhealthy. A producer with no current entry is not in it. +func unhealthyProducers(endpoint *networkv1alpha1.ServiceEndpoint, + producers []*cloudv1alpha1.VPCAttachment, +) map[types.UID]bool { + if !spread(endpoint) { + return nil + } + reported := make(map[types.NamespacedName]networkv1alpha1.ServiceEndpointProducerStatus, + len(endpoint.Status.Producers)) + for _, entry := range endpoint.Status.Producers { + reported[types.NamespacedName{Namespace: entry.Namespace, Name: entry.Name}] = entry + } + unhealthy := make(map[types.UID]bool) + for _, producer := range producers { + entry, ok := reported[types.NamespacedName{Namespace: producer.Namespace, Name: producer.Name}] + if ok && entry.AttachmentUID == producer.UID && entry.Node == producer.Status.Node && + entry.State == networkv1alpha1.BackendHealthUnhealthy { + unhealthy[producer.UID] = true + } + } + return unhealthy +} + +// producerTargets builds a LocalSet intent's members. Unhealthy producers +// drain, unless every one of them is Unhealthy: then all stay eligible, since +// an empty set would drop every new flow. +func producerTargets(local []*cloudv1alpha1.VPCAttachment, unhealthy map[types.UID]bool, + service net.IP, +) []ProducerTarget { + allUnhealthy := true + for _, producer := range local { + if !unhealthy[producer.UID] { + allUnhealthy = false + break + } + } + targets := make([]ProducerTarget, 0, len(local)) + for _, producer := range local { + targets = append(targets, ProducerTarget{ + Attachment: types.NamespacedName{Namespace: producer.Namespace, Name: producer.Name}, + Device: producer.Status.HostInterface, + NextHop: attachmentNextHop(producer, service), + Draining: unhealthy[producer.UID] && !allUnhealthy, + }) + } + return targets +} + func servicePorts(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, ) ([]networkv1alpha1.ServiceRouteProtocolPort, error) { diff --git a/internal/serviceroute/planner_spread_test.go b/internal/serviceroute/planner_spread_test.go new file mode 100644 index 000000000..9ca2ae39b --- /dev/null +++ b/internal/serviceroute/planner_spread_test.go @@ -0,0 +1,200 @@ +// Copyright 2026 Datum Cloud, Inc. +// SPDX-License-Identifier: AGPL-3.0-or-later + +package serviceroute + +import ( + "fmt" + "net" + "strings" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" + networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" +) + +const ( + spreadProducerNamespace = "service" + spreadConsumerName = "consumer" + bothLocalProducers = "producer-a,producer-z" +) + +func spreadEndpoint(mode networkv1alpha1.ServiceEndpointDeliveryMode) ( + *networkv1alpha1.ServiceRoutePolicy, *networkv1alpha1.ServiceEndpoint, +) { + policy, endpoint := testPolicyAndEndpoint(mode) + endpoint.Spec.Distribution = networkv1alpha1.ServiceEndpointDistributionSpread + endpoint.Spec.HealthCheck = &networkv1alpha1.ServiceEndpointHealthCheck{Port: 8053} + return policy, endpoint +} + +func spreadConsumer() *cloudv1alpha1.VPCAttachment { + return readyAttachment(eligibilityNamespace, spreadConsumerName, "consumer-uid", testNodeName, "consumer0", + testLabels(testAccessLabel, "yes")) +} + +func reportHealth(endpoint *networkv1alpha1.ServiceEndpoint, producer *cloudv1alpha1.VPCAttachment, + state networkv1alpha1.BackendHealthState, +) { + endpoint.Status.Producers = append(endpoint.Status.Producers, networkv1alpha1.ServiceEndpointProducerStatus{ + Namespace: producer.Namespace, Name: producer.Name, AttachmentUID: producer.UID, + Node: producer.Status.Node, Port: 8053, State: state, LastTransitionTime: metav1.Now(), + }) +} + +func producerSummary(intent RouteIntent) string { + parts := make([]string, 0, len(intent.Producers)) + for _, p := range intent.Producers { + part := p.Device + if p.Draining { + part += "(draining)" + } + parts = append(parts, part) + } + return strings.Join(parts, ",") +} + +func TestCompileSpreadAcceptsEveryLocalProducer(t *testing.T) { + policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModeNodeLocal) + consumer := spreadConsumer() + first := readyAttachment(spreadProducerNamespace, "a-producer", "first-uid", testNodeName, "producer-a", + testLabels(testProducerLabel, "yes")) + last := readyAttachment(spreadProducerNamespace, "z-producer", "last-uid", testNodeName, "producer-z", + testLabels(testProducerLabel, "yes")) + attachments := []*cloudv1alpha1.VPCAttachment{last, consumer, first} + + got, err := Compile(policy, endpoint, attachments, testNodeName, nil) + if err != nil { + t.Fatalf("Compile: %v", err) + } + if len(got) != 1 || got[0].Kind != RouteIntentLocalSet || got[0].ConsumerDevice != "consumer0" || + producerSummary(got[0]) != bothLocalProducers { + t.Fatalf("intents = %+v, want one LocalSet intent through producer-a and producer-z", got) + } + if got[0].ServiceDevice != "" || got[0].ProducerAttachment != (types.NamespacedName{}) { + t.Fatalf("LocalSet intent names a single producer: %+v", got[0]) + } + if _, err := ProgrammingPlan(policy, endpoint, attachments, ""); err != nil { + t.Fatalf("ProgrammingPlan: %v", err) + } + + endpoint.Spec.Distribution, endpoint.Spec.HealthCheck = "", nil + if _, err := Compile(policy, endpoint, attachments, testNodeName, nil); err == nil { + t.Fatal("Compile accepted two producers on one node and VPC without Spread") + } +} + +func TestCompileSpreadDrainsUnhealthyProducers(t *testing.T) { + policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModeNodeLocal) + consumer := spreadConsumer() + first := readyAttachment(spreadProducerNamespace, "a-producer", "first-uid", testNodeName, "producer-a", + testLabels(testProducerLabel, "yes")) + last := readyAttachment(spreadProducerNamespace, "z-producer", "last-uid", testNodeName, "producer-z", + testLabels(testProducerLabel, "yes")) + attachments := []*cloudv1alpha1.VPCAttachment{consumer, first, last} + compile := func() string { + t.Helper() + got, err := Compile(policy, endpoint, attachments, testNodeName, nil) + if err != nil { + t.Fatalf("Compile: %v", err) + } + if len(got) != 1 { + t.Fatalf("intents = %+v, want one", got) + } + return producerSummary(got[0]) + } + + reportHealth(endpoint, first, networkv1alpha1.BackendHealthUnhealthy) + reportHealth(endpoint, last, networkv1alpha1.BackendHealthHealthy) + if got := compile(); got != "producer-a(draining),producer-z" { + t.Fatalf("producers = %s, want producer-a draining", got) + } + + endpoint.Status.Producers[1].State = networkv1alpha1.BackendHealthUnhealthy + if got := compile(); got != bothLocalProducers { + t.Fatalf("producers with every one Unhealthy = %s, want all eligible", got) + } + + // A decision written for an earlier attachment of the same name, or by + // another node, does not describe this producer. + endpoint.Status.Producers[0].AttachmentUID = "earlier-uid" + endpoint.Status.Producers[1].Node = testRemoteNodeName + if got := compile(); got != bothLocalProducers { + t.Fatalf("producers with stale decisions = %s, want all eligible", got) + } + + endpoint.Status.Producers = nil + reportHealth(endpoint, first, networkv1alpha1.BackendHealthUnknown) + if got := compile(); got != bothLocalProducers { + t.Fatalf("producers with an Unknown decision = %s, want all eligible", got) + } +} + +func TestCompileSpreadFallsBackToHealthyRemoteProducer(t *testing.T) { + policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal) + consumer := spreadConsumer() + first := readyAttachment(spreadProducerNamespace, "a-remote", "first-uid", testRemoteNodeName, "remote-a", + testLabels(testProducerLabel, "yes")) + last := readyAttachment(spreadProducerNamespace, "z-remote", "last-uid", testRemoteNodeName, "remote-z", + testLabels(testProducerLabel, "yes")) + resolver := func(attachment *cloudv1alpha1.VPCAttachment) (net.IP, error) { + return net.ParseIP("fd00::" + string(attachment.UID[0])), nil + } + attachments := []*cloudv1alpha1.VPCAttachment{consumer, first, last} + remote := func() types.NamespacedName { + t.Helper() + got, err := Compile(policy, endpoint, attachments, testNodeName, resolver) + if err != nil { + t.Fatalf("Compile: %v", err) + } + if len(got) != 1 || got[0].Kind != RouteIntentRemoteConsumer { + t.Fatalf("intents = %+v, want one RemoteConsumer intent", got) + } + return got[0].ProducerAttachment + } + + if got := remote(); got.Name != "a-remote" { + t.Fatalf("remote producer = %s, want a-remote", got) + } + reportHealth(endpoint, first, networkv1alpha1.BackendHealthUnhealthy) + if got := remote(); got.Name != "z-remote" { + t.Fatalf("remote producer with a-remote Unhealthy = %s, want z-remote", got) + } + reportHealth(endpoint, last, networkv1alpha1.BackendHealthUnhealthy) + if got := remote(); got.Name != "a-remote" { + t.Fatalf("remote producer with both Unhealthy = %s, want a-remote", got) + } + + // Two producers on one remote node are told apart by their SIDs. + got, err := Compile(policy, endpoint, attachments, testRemoteNodeName, resolver) + if err != nil { + t.Fatalf("Compile on the producer node: %v", err) + } + if len(got) != 1 || got[0].Kind != RouteIntentRemoteProducer || got[0].ServiceDevice != "remote-a" { + t.Fatalf("producer node intents = %+v, want one RemoteProducer half through remote-a", got) + } +} + +func TestCompileSpreadRefusesMoreProducersThanASetHolds(t *testing.T) { + policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModeNodeLocal) + attachments := make([]*cloudv1alpha1.VPCAttachment, 0, networkv1alpha1.ServiceEndpointMaxProducersPerNode+2) + attachments = append(attachments, spreadConsumer()) + for i := range networkv1alpha1.ServiceEndpointMaxProducersPerNode { + attachments = append(attachments, readyAttachment(spreadProducerNamespace, fmt.Sprintf("producer-%02d", i), + fmt.Sprintf("uid-%02d", i), testNodeName, fmt.Sprintf("p%02d", i), testLabels(testProducerLabel, "yes"))) + } + got, err := Compile(policy, endpoint, attachments, testNodeName, nil) + if err != nil || len(got) != 1 || len(got[0].Producers) != networkv1alpha1.ServiceEndpointMaxProducersPerNode { + t.Fatalf("Compile with a full set: intents=%+v err=%v", got, err) + } + attachments = append(attachments, readyAttachment(spreadProducerNamespace, "producer-extra", "uid-extra", testNodeName, + "pextra", testLabels(testProducerLabel, "yes"))) + if _, err := Compile(policy, endpoint, attachments, testNodeName, nil); err == nil || + !strings.Contains(err.Error(), `node "node-a"`) { + t.Fatalf("Compile with %d producers on one node: err=%v, want a refusal naming the node", + len(attachments)-1, err) + } +} diff --git a/internal/serviceroute/programming.go b/internal/serviceroute/programming.go index 45d074b5f..24e5d93b9 100644 --- a/internal/serviceroute/programming.go +++ b/internal/serviceroute/programming.go @@ -48,6 +48,7 @@ func ProgrammingPlan(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *netwo if err := validateProducerTopology(endpoint, producers); err != nil { return plan, err } + unhealthy := unhealthyProducers(endpoint, producers) ready := map[types.NamespacedName]bool{} for _, a := range readyAttachments(attachments) { ready[types.NamespacedName{Namespace: a.Namespace, Name: a.Name}] = a.Status.HostInterface != "" @@ -79,7 +80,10 @@ func ProgrammingPlan(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *netwo continue } selected++ - p := chooseProducer(endpoint.Spec.DeliveryMode, a.Status.Node, producers) + local, p := selectProducers(endpoint, a.Status.Node, producers, unhealthy) + if len(local) != 0 { + p = local[0] + } if p == nil { return plan, fmt.Errorf("consumer attachment %s/%s has no eligible producer", a.Namespace, a.Name) } diff --git a/internal/serviceroute/spread_kernel_linux_test.go b/internal/serviceroute/spread_kernel_linux_test.go new file mode 100644 index 000000000..f2edb99cc --- /dev/null +++ b/internal/serviceroute/spread_kernel_linux_test.go @@ -0,0 +1,531 @@ +//go:build linux + +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package serviceroute + +import ( + "bufio" + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/vishvananda/netlink" + "github.com/vishvananda/netns" + "k8s.io/apimachinery/pkg/types" + + api "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/plumbing/ebpf/attach" +) + +// spreadLab is one node's network namespace holding a consumer and two +// producers of one service address, each behind a veth whose host side runs +// the production service classifier. +type spreadLab struct { + node, consumer string + producers map[string]string // name -> namespace path + programmer *EBPFRouteProgrammer +} + +const ( + spreadLabService = "fd53::53" + spreadLabUDPPort = 5353 + spreadLabTCPPort = 5354 +) + +func requireRoot(t *testing.T) { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("requires root (CAP_NET_ADMIN, CAP_BPF); re-run via sudo") + } +} + +func spreadNS(t *testing.T, name string) string { + t.Helper() + runtime.LockOSThread() + defer runtime.UnlockOSThread() + orig, err := netns.Get() + if err != nil { + t.Fatal(err) + } + defer func() { _ = orig.Close() }() + handle, err := netns.NewNamed(name) + if err != nil { + t.Fatal(err) + } + _ = handle.Close() + // Links created later skip duplicate address detection, so the lab is + // usable as soon as it is built. + err = os.WriteFile("/proc/sys/net/ipv6/conf/default/accept_dad", []byte("0"), 0o644) + if err == nil { + var lo netlink.Link + if lo, err = netlink.LinkByName("lo"); err == nil { + err = netlink.LinkSetUp(lo) + } + } + if setErr := netns.Set(orig); setErr != nil { + t.Fatal(setErr) + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = netns.DeleteNamed(name) }) + return filepath.Join("/run/netns", name) +} + +// inNS runs fn with the calling thread in the namespace at path. +func inNS(path string, fn func() error) error { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + orig, err := netns.Get() + if err != nil { + return err + } + defer func() { _ = orig.Close() }() + target, err := netns.GetFromPath(path) + if err != nil { + return err + } + defer func() { _ = target.Close() }() + if err := netns.Set(target); err != nil { + return err + } + fnErr := fn() + if err := netns.Set(orig); err != nil { + return errors.Join(fnErr, err) + } + return fnErr +} + +func mustInNS(t *testing.T, path string, fn func() error) { + t.Helper() + if err := inNS(path, fn); err != nil { + t.Fatal(err) + } +} + +func addr(t *testing.T, cidr string) *netlink.Addr { + t.Helper() + a, err := netlink.ParseAddr(cidr) + if err != nil { + t.Fatal(err) + } + a.Flags |= 0x02 // IFA_F_NODAD + return a +} + +// connect puts a veth between the node and namespace peer: hostName with +// hostCIDR on the node, guestName with guestCIDR in peer. +func connect(t *testing.T, node, peer, hostName, guestName, hostCIDR, guestCIDR string) { + t.Helper() + peerNS, err := netns.GetFromPath(peer) + if err != nil { + t.Fatal(err) + } + defer func() { _ = peerNS.Close() }() + mustInNS(t, node, func() error { + veth := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: hostName}, PeerName: guestName} + if err := netlink.LinkAdd(veth); err != nil { + return err + } + guest, err := netlink.LinkByName(guestName) + if err != nil { + return err + } + if err := netlink.LinkSetNsFd(guest, int(peerNS)); err != nil { + return err + } + host, err := netlink.LinkByName(hostName) + if err != nil { + return err + } + if err := netlink.AddrAdd(host, addr(t, hostCIDR)); err != nil { + return err + } + return netlink.LinkSetUp(host) + }) + mustInNS(t, peer, func() error { + guest, err := netlink.LinkByName(guestName) + if err != nil { + return err + } + if err := netlink.AddrAdd(guest, addr(t, guestCIDR)); err != nil { + return err + } + return netlink.LinkSetUp(guest) + }) +} + +func newSpreadLab(t *testing.T) *spreadLab { + t.Helper() + requireRoot(t) + suffix := strconv.Itoa(os.Getpid()) + pinDir := filepath.Join("/sys/fs/bpf", "galactic-spread-test-"+suffix) + if err := os.MkdirAll(pinDir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + objects, err := attach.Load(pinDir) + if err != nil { + t.Fatalf("load datapath: %v", err) + } + t.Cleanup(func() { _ = objects.Close() }) + + lab := &spreadLab{ + node: spreadNS(t, "gspread-n-"+suffix), + consumer: spreadNS(t, "gspread-c-"+suffix), + producers: map[string]string{}, + } + connect(t, lab.node, lab.consumer, "hc", "c0", "fd00:c::1/64", "fd00:c::2/64") + mustInNS(t, lab.consumer, func() error { + c0, err := netlink.LinkByName("c0") + if err != nil { + return err + } + _, service, _ := net.ParseCIDR(spreadLabService + "/128") + return netlink.RouteAdd(&netlink.Route{LinkIndex: c0.Attrs().Index, Dst: service, + Gw: net.ParseIP("fd00:c::1")}) + }) + for i, name := range []string{"p1", "p2"} { + path := spreadNS(t, fmt.Sprintf("gspread-%s-%s", name, suffix)) + lab.producers[name] = path + subnet := fmt.Sprintf("fd00:%d::", i+1) + connect(t, lab.node, path, "h"+name, "p0", subnet+"1/64", subnet+"2/64") + mustInNS(t, path, func() error { + lo, err := netlink.LinkByName("lo") + if err != nil { + return err + } + if err := netlink.AddrAdd(lo, addr(t, spreadLabService+"/128")); err != nil { + return err + } + p0, err := netlink.LinkByName("p0") + if err != nil { + return err + } + return netlink.RouteAdd(&netlink.Route{LinkIndex: p0.Attrs().Index, Gw: net.ParseIP(subnet + "1")}) + }) + serveProducer(t, path, name) + } + mustInNS(t, lab.node, func() error { + for _, name := range []string{"hc", "hp1", "hp2"} { + link, err := netlink.LinkByName(name) + if err != nil { + return err + } + if err := attach.AttachEgressWithIdentity(objects.UsidServiceEgress, objects.UsidEgress, + objects.AttachmentIdentityTable, uint32(link.Attrs().Index), name); err != nil { + return fmt.Errorf("attach %s: %w", name, err) + } + } + return nil + }) + lab.programmer = &EBPFRouteProgrammer{PinDir: pinDir} + mustInNS(t, lab.node, lab.programmer.Initialize) + return lab +} + +// serveProducer answers on the service address in namespace path: every UDP +// datagram, and every line of every TCP connection, with "name payload". +func serveProducer(t *testing.T, path, name string) { + t.Helper() + var udp net.PacketConn + var tcp net.Listener + mustInNS(t, path, func() error { + var listen net.ListenConfig + var err error + udp, err = listen.ListenPacket(context.Background(), "udp6", + fmt.Sprintf("[%s]:%d", spreadLabService, spreadLabUDPPort)) + if err != nil { + return err + } + tcp, err = listen.Listen(context.Background(), "tcp6", fmt.Sprintf("[%s]:%d", spreadLabService, spreadLabTCPPort)) + return err + }) + t.Cleanup(func() { _ = udp.Close(); _ = tcp.Close() }) + go func() { + buf := make([]byte, 512) + for { + n, from, err := udp.ReadFrom(buf) + if err != nil { + return + } + _, _ = udp.WriteTo([]byte(name+" "+string(buf[:n])), from) + } + }() + go func() { + for { + conn, err := tcp.Accept() + if err != nil { + return + } + go func() { + defer func() { _ = conn.Close() }() + scanner := bufio.NewScanner(conn) + for scanner.Scan() { + if _, err := fmt.Fprintf(conn, "%s %s\n", name, scanner.Text()); err != nil { + return + } + } + if err := scanner.Err(); err != nil { + t.Logf("%s: read TCP request: %v", name, err) + } + }() + } + }() +} + +// apply replaces the consumer's LocalSet intent the way the policy +// controller does: the new one goes in before the old one comes out. +func (lab *spreadLab) apply(t *testing.T, old *RouteIntent, producers ...ProducerTarget) RouteIntent { + t.Helper() + _, service, _ := net.ParseCIDR(spreadLabService + "/128") + next := RouteIntent{ + Attachment: types.NamespacedName{Namespace: eligibilityNamespace, Name: spreadConsumerName}, + Kind: RouteIntentLocalSet, Service: service, ConsumerDevice: "hc", + ConsumerNextHop: net.ParseIP("fd00:c::2"), + Ports: []api.ServiceRouteProtocolPort{ + {Protocol: api.NetworkServiceProtocolUDP, Port: spreadLabUDPPort}, + {Protocol: api.NetworkServiceProtocolTCP, Port: spreadLabTCPPort}, + }, + Producers: producers, + } + mustInNS(t, lab.node, func() error { + if err := lab.programmer.Apply(next); err != nil { + return err + } + if old != nil { + if err := lab.programmer.Remove(*old); err != nil { + return err + } + } + return lab.programmer.Finalize() + }) + return next +} + +func spreadProducer(name string, draining bool) ProducerTarget { + index := strings.TrimPrefix(name, "p") + return ProducerTarget{Attachment: types.NamespacedName{Namespace: spreadProducerNamespace, Name: name}, + Device: "h" + name, + NextHop: net.ParseIP("fd00:" + index + "::2"), Draining: draining} +} + +// udpClient is one consumer UDP socket. +type udpClient struct{ conn net.Conn } + +func (lab *spreadLab) udpClient(t *testing.T) *udpClient { + t.Helper() + var conn net.Conn + mustInNS(t, lab.consumer, func() error { + var dialer net.Dialer + var err error + conn, err = dialer.DialContext(context.Background(), "udp6", + fmt.Sprintf("[%s]:%d", spreadLabService, spreadLabUDPPort)) + return err + }) + t.Cleanup(func() { _ = conn.Close() }) + return &udpClient{conn: conn} +} + +// query sends one request and returns the producer that answered. +func (c *udpClient) query(payload string) (string, error) { + if _, err := c.conn.Write([]byte(payload)); err != nil { + return "", err + } + _ = c.conn.SetReadDeadline(time.Now().Add(2 * time.Second)) + buf := make([]byte, 512) + for { + n, err := c.conn.Read(buf) + if err != nil { + return "", err + } + producer, got, _ := strings.Cut(string(buf[:n]), " ") + if got == payload { + return producer, nil + } + } +} + +// tcpClient is one consumer TCP connection. +type tcpClient struct { + conn net.Conn + scanner *bufio.Scanner +} + +func (lab *spreadLab) tcpClient(t *testing.T) *tcpClient { + t.Helper() + var conn net.Conn + mustInNS(t, lab.consumer, func() error { + dialer := net.Dialer{Timeout: 2 * time.Second} + var err error + conn, err = dialer.DialContext(context.Background(), "tcp6", + fmt.Sprintf("[%s]:%d", spreadLabService, spreadLabTCPPort)) + return err + }) + t.Cleanup(func() { _ = conn.Close() }) + return &tcpClient{conn: conn, scanner: bufio.NewScanner(conn)} +} + +func (c *tcpClient) query(payload string) (string, error) { + _ = c.conn.SetDeadline(time.Now().Add(2 * time.Second)) + if _, err := fmt.Fprintf(c.conn, "%s\n", payload); err != nil { + return "", err + } + if !c.scanner.Scan() { + return "", fmt.Errorf("read reply: %w", errors.Join(c.scanner.Err(), errors.New("connection closed"))) + } + producer, got, _ := strings.Cut(c.scanner.Text(), " ") + if got != payload { + return "", fmt.Errorf("reply %q to %q", c.scanner.Text(), payload) + } + return producer, nil +} + +// waitReady waits up to 5 seconds for the first answer through a fresh +// topology, which needs its neighbors resolved, before anything is measured. +func (lab *spreadLab) waitReady(t *testing.T, udp *udpClient) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for i := 0; ; i++ { + _, err := udp.query(fmt.Sprintf("ready%d", i)) + if err == nil { + if i != 0 { + t.Logf("service path answered after %d lost requests", i) + } + return + } + if time.Now().After(deadline) { + t.Fatalf("service path never answered: %v", err) + } + } +} + +// TestSpreadKernelPath sends real UDP and TCP traffic from a consumer through +// the production classifier and route programmer to two producers of one +// service address on one node, then drains and removes one of them. +func TestSpreadKernelPath(t *testing.T) { + lab := newSpreadLab(t) + intent := lab.apply(t, nil, spreadProducer("p1", false), spreadProducer("p2", false)) + udp := lab.udpClient(t) + lab.waitReady(t, udp) + + checkUDPSpread(t, udp) + connections := openPinnedConnections(t, lab) + + // Drain p1: no request fails meanwhile, new requests and connections + // avoid p1, and p1's open connection keeps working. + intent = drainWithoutFailures(t, lab, intent) + for i := range 100 { + if producer, err := udp.query(fmt.Sprintf("d%d", i)); err != nil || producer != "p2" { + t.Fatalf("UDP request %d after draining p1: producer %q err %v, want p2", i, producer, err) + } + } + expectProducer(t, connections["p1"], "p1", "after draining p1") + for i := range 8 { + if got, err := lab.tcpClient(t).query(fmt.Sprintf("new%d", i)); err != nil || got != "p2" { + t.Fatalf("new TCP connection %d after draining p1: producer %q err %v, want p2", i, got, err) + } + } + + // Remove p1: p2's connections are untouched. + lab.apply(t, &intent, spreadProducer("p2", false)) + expectProducer(t, connections["p2"], "p2", "after removing p1") + if producer, err := udp.query("last"); err != nil || producer != "p2" { + t.Fatalf("UDP request after removing p1: producer %q err %v", producer, err) + } +} + +// checkUDPSpread checks that the requests of one UDP socket reach both +// producers. +func checkUDPSpread(t *testing.T, udp *udpClient) { + t.Helper() + seen := map[string]int{} + for i := range 200 { + producer, err := udp.query(fmt.Sprintf("u%d", i)) + if err != nil { + t.Fatalf("UDP query %d: %v", i, err) + } + seen[producer]++ + } + if seen["p1"] == 0 || seen["p2"] == 0 { + t.Fatalf("UDP requests by producer = %v, want both", seen) + } + t.Logf("UDP requests by producer: %v", seen) +} + +// openPinnedConnections opens TCP connections until each producer holds one, +// checking that every connection stays on its producer. +func openPinnedConnections(t *testing.T, lab *spreadLab) map[string][]*tcpClient { + t.Helper() + connections := map[string][]*tcpClient{} + for i := 0; i < 64 && (len(connections["p1"]) == 0 || len(connections["p2"]) == 0); i++ { + client := lab.tcpClient(t) + producer, err := client.query("hello") + if err != nil { + t.Fatalf("TCP connection %d: %v", i, err) + } + expectProducer(t, []*tcpClient{client, client, client}, producer, fmt.Sprintf("connection %d", i)) + connections[producer] = append(connections[producer], client) + } + if len(connections["p1"]) == 0 || len(connections["p2"]) == 0 { + t.Fatalf("64 TCP connections did not reach both producers: %v", connections) + } + return connections +} + +// drainWithoutFailures drains p1 while another UDP socket keeps sending +// requests, and fails the test if any request fails. +func drainWithoutFailures(t *testing.T, lab *spreadLab, intent RouteIntent) RouteIntent { + t.Helper() + var failures, sent atomic.Int64 + stop := make(chan struct{}) + var wg sync.WaitGroup + client := lab.udpClient(t) + wg.Go(func() { + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + sent.Add(1) + if _, err := client.query(fmt.Sprintf("bg%d", i)); err != nil { + failures.Add(1) + } + } + }) + time.Sleep(200 * time.Millisecond) + intent = lab.apply(t, &intent, spreadProducer("p1", true), spreadProducer("p2", false)) + time.Sleep(200 * time.Millisecond) + close(stop) + wg.Wait() + if failures.Load() != 0 { + t.Fatalf("%d of %d UDP requests failed while p1 drained", failures.Load(), sent.Load()) + } + t.Logf("UDP requests while draining p1: %d sent, 0 failed", sent.Load()) + return intent +} + +// expectProducer sends one request over each connection and fails unless +// producer answers it. +func expectProducer(t *testing.T, connections []*tcpClient, producer, when string) { + t.Helper() + for i, client := range connections { + if got, err := client.query(fmt.Sprintf("check%d", i)); err != nil || got != producer { + t.Fatalf("TCP request %s: producer %q err %v, want %s", when, got, err, producer) + } + } +}