From 7bda7c728ab258c6c8b431ba101ffde418c39daf Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 22:03:11 -0400 Subject: [PATCH 1/4] fix(router): Spread remote consumers across Spread producers A Spread endpoint consumer with no producer on its node was sent to the first producer, by namespace and name, that was not reported Unhealthy. Every such consumer landed on that one producer, and all of them moved together when it flapped. selectProducers now picks the remote producer by rendezvous hashing of the consumer's attachment UID with each producer's UID, or namespace/name for an attachment with no UID. It keeps the existing tiers: producers reported Healthy or Unknown or not reported, then producers whose report expired, then all producers. Each consumer goes to the highest-scoring producer in the first non-empty tier. Consumers spread across the remote producers, and a producer joining, leaving or turning Unhealthy changes the choice only for consumers whose top producer it is. ProgrammingPlan calls the same function, so the nodes it schedules match the intents Compile emits. The consumer's node and the producer's node each compute the pairing. While routers run mixed versions, a remote Spread consumer whose pairing changed is refused until both nodes run this version. Single endpoints are unaffected. TestCompileSpreadSpreadsConsumersAcrossRemoteProducers sends 64 consumers to 4 remote producers and checks that each producer takes some. It then adds a fifth producer, removes one and reports one Unhealthy, and checks that only the consumers gained or lost move. It also compiles on each producer's node and checks that the producer halves match the consumer node's choices. Without the fix, all 64 consumers go to producer-0. Two existing tests that expected the first producer by name now check the same properties without depending on which producer wins, including that a consumer with every report expired goes where it would with no reports. Related to #1097 --- docs/private-services/README.md | 19 +-- internal/serviceroute/planner.go | 75 ++++++++-- internal/serviceroute/planner_spread_test.go | 143 +++++++++++++++++-- internal/serviceroute/programming.go | 2 +- 4 files changed, 204 insertions(+), 35 deletions(-) diff --git a/docs/private-services/README.md b/docs/private-services/README.md index 36d0dec69..4fff31ed4 100644 --- a/docs/private-services/README.md +++ b/docs/private-services/README.md @@ -132,14 +132,17 @@ 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, through the SRv6 service tunnel as with `Single`. It is -the first producer by namespace and name whose node currently reports it -`Healthy` or `Unknown`, or has no entry for it. If there is none, it is the -first producer whose entry expired, and failing that the first producer. So -when a node goes down while its producers' attachments still read ready, -consumers on other nodes move off those producers within 60 seconds of the -node's last renewal, as long as another node currently reports a producer that -can take them. A remote consumer does not spread. While a health change reaches the +to one remote producer, through the SRv6 service tunnel as with `Single`. +Rendezvous hashing of the consumer's and each producer's attachment UID picks +it, among the producers whose node currently reports them `Healthy` or +`Unknown`, or has no entry for them. If there are none, it picks among the +producers whose entry expired, and failing that among all producers. So +consumers spread across the remote producers, and a producer joining, leaving +or turning `Unhealthy` moves only the consumers it gains or loses. When a node +goes down while its producers' attachments still read ready, its consumers move +to other producers within 60 seconds of the node's last renewal, as long as +another node currently reports a producer that can take them. Each consumer's +requests all go to its one remote producer. 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. diff --git a/internal/serviceroute/planner.go b/internal/serviceroute/planner.go index df21226b5..d0e5b74b4 100644 --- a/internal/serviceroute/planner.go +++ b/internal/serviceroute/planner.go @@ -9,6 +9,7 @@ import ( "encoding/binary" "errors" "fmt" + "hash/fnv" "net" "sort" "time" @@ -157,7 +158,7 @@ func compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alph if !consumerMatchesVPC(policy, consumer, consumerVPCIdentity) { continue } - local, producer := selectProducers(endpoint, consumer.Status.Node, producers, health) + local, producer := selectProducers(endpoint, consumer, producers, health) consumerKey := types.NamespacedName{Namespace: consumer.Namespace, Name: consumer.Name} if len(local) != 0 { if consumer.Status.Node == localNode { @@ -342,17 +343,20 @@ func spread(endpoint *networkv1alpha1.ServiceEndpoint) bool { } // 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 whose node currently reports it Healthy or -// Unknown, or has never reported it; failing that, the first one whose report -// expired, since its node may be down; failing that, the first one. -func selectProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumerNode string, +// consumer's node as local. Otherwise, or when that node has none, it returns +// the one producer the consumer is sent to, or nil. A Spread endpoint's remote +// producer is chosen by rendezvous hashing of the consumer's UID with each +// candidate's UID (see rendezvousKey), among the producers whose node currently reports them +// Healthy or Unknown, or has never reported them; failing that, among those +// whose report expired, since their node may be down; failing that, among all +// of them. A producer joining or leaving a candidate set then moves only the +// consumers it gains or loses. +func selectProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumer *cloudv1alpha1.VPCAttachment, producers []*cloudv1alpha1.VPCAttachment, health map[types.UID]producerHealth, ) (local []*cloudv1alpha1.VPCAttachment, remote *cloudv1alpha1.VPCAttachment) { if spread(endpoint) { for _, producer := range producers { - if producer.Status.Node == consumerNode { + if producer.Status.Node == consumer.Status.Node { local = append(local, producer) } } @@ -364,15 +368,58 @@ func selectProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumerNode str return nil, nil } for _, want := range []producerHealth{producerEligible, producerReportExpired} { - for _, producer := range producers { - if health[producer.UID] == want { - return nil, producer - } + if producer := rendezvousProducer(consumer, producers, func(p *cloudv1alpha1.VPCAttachment) bool { + return health[p.UID] == want + }); producer != nil { + return nil, producer } } - return nil, producers[0] + return nil, rendezvousProducer(consumer, producers, func(*cloudv1alpha1.VPCAttachment) bool { return true }) } - return nil, chooseProducer(endpoint.Spec.DeliveryMode, consumerNode, producers) + return nil, chooseProducer(endpoint.Spec.DeliveryMode, consumer.Status.Node, producers) +} + +// rendezvousProducer returns the producer accepted by include with the highest +// score for consumer, or nil when include accepts none. Producers are sorted +// by name, so equal scores resolve the same way on every node. +func rendezvousProducer(consumer *cloudv1alpha1.VPCAttachment, producers []*cloudv1alpha1.VPCAttachment, + include func(*cloudv1alpha1.VPCAttachment) bool, +) *cloudv1alpha1.VPCAttachment { + var best *cloudv1alpha1.VPCAttachment + var bestScore uint64 + for _, producer := range producers { + if !include(producer) { + continue + } + hash := fnv.New64a() + _, _ = hash.Write([]byte(rendezvousKey(consumer))) + _, _ = hash.Write([]byte{0}) + _, _ = hash.Write([]byte(rendezvousKey(producer))) + if score := mix64(hash.Sum64()); best == nil || score > bestScore { + best, bestScore = producer, score + } + } + return best +} + +// rendezvousKey identifies attachment for rendezvous hashing: its UID, or its +// namespace and name when it has none. +func rendezvousKey(attachment *cloudv1alpha1.VPCAttachment) string { + if attachment.UID != "" { + return string(attachment.UID) + } + return attachment.Namespace + "/" + attachment.Name +} + +// mix64 is the SplitMix64 finalizer. FNV-1a alone leaves inputs that differ +// only in their last bytes with correlated high bits, which would bias the +// rendezvous comparison. +func mix64(x uint64) uint64 { + x ^= x >> 30 + x *= 0xbf58476d1ce4e5b9 + x ^= x >> 27 + x *= 0x94d049bb133111eb + return x ^ x>>31 } func chooseProducer(mode networkv1alpha1.ServiceEndpointDeliveryMode, consumerNode string, diff --git a/internal/serviceroute/planner_spread_test.go b/internal/serviceroute/planner_spread_test.go index caa483d40..52f782b1b 100644 --- a/internal/serviceroute/planner_spread_test.go +++ b/internal/serviceroute/planner_spread_test.go @@ -170,16 +170,19 @@ func TestCompileSpreadFallsBackToHealthyRemoteProducer(t *testing.T) { return got[0].ProducerAttachment } - if got := remote(); got.Name != firstRemoteProducer { - t.Fatalf("remote producer = %s, want a-remote", got) + chosen := remote() + other := map[string]*cloudv1alpha1.VPCAttachment{first.Name: last, last.Name: first}[chosen.Name] + if other == nil { + t.Fatalf("remote producer = %s, want a-remote or z-remote", chosen) } - 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, map[string]*cloudv1alpha1.VPCAttachment{first.Name: first, last.Name: last}[chosen.Name], + networkv1alpha1.BackendHealthUnhealthy) + if got := remote(); got.Name != other.Name { + t.Fatalf("remote producer with %s Unhealthy = %s, want %s", chosen.Name, got, other.Name) } - reportHealth(endpoint, last, networkv1alpha1.BackendHealthUnhealthy) - if got := remote(); got.Name != firstRemoteProducer { - t.Fatalf("remote producer with both Unhealthy = %s, want a-remote", got) + reportHealth(endpoint, other, networkv1alpha1.BackendHealthUnhealthy) + if got := remote(); got != chosen { + t.Fatalf("remote producer with both Unhealthy = %s, want %s again", got, chosen) } // Two producers on one remote node are told apart by their SIDs. @@ -187,8 +190,9 @@ func TestCompileSpreadFallsBackToHealthyRemoteProducer(t *testing.T) { 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) + want := map[string]string{first.Name: "remote-a", last.Name: "remote-z"}[chosen.Name] + if len(got) != 1 || got[0].Kind != RouteIntentRemoteProducer || got[0].ServiceDevice != want { + t.Fatalf("producer node intents = %+v, want one RemoteProducer half through %s", got, want) } } @@ -269,9 +273,15 @@ func TestCompileSpreadAvoidsRemoteProducersWithExpiredReports(t *testing.T) { t.Fatalf("remote producer with z-remote Unhealthy = %s, want a-remote", got) } endpoint.Status.Producers[1].State = networkv1alpha1.BackendHealthHealthy + // With every report expired, the consumer goes where it would with no + // reports at all. expireReport(endpoint) - if got := remote(); got != firstRemoteProducer { - t.Fatalf("remote producer with every report expired = %s, want a-remote", got) + reports := endpoint.Status.Producers + endpoint.Status.Producers = nil + unreported := remote() + endpoint.Status.Producers = reports + if got := remote(); got != unreported { + t.Fatalf("remote producer with every report expired = %s, want %s as with no reports", got, unreported) } } @@ -396,3 +406,112 @@ func TestWithProducerReportsPrefersReportsOverStatus(t *testing.T) { t.Fatalf("producers after rollback = %s, want producer-a drained by its newer status entry", got) } } + +// remoteAssignments compiles policy on testNodeName and returns the remote +// producer each consumer there is sent to. +func remoteAssignments(t *testing.T, policy *networkv1alpha1.ServiceRoutePolicy, + endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, +) map[string]string { + t.Helper() + resolver := func(attachment *cloudv1alpha1.VPCAttachment) (net.IP, error) { + return net.ParseIP("fd00::1"), nil + } + intents, err := Compile(policy, endpoint, attachments, testNodeName, resolver) + if err != nil { + t.Fatalf("Compile: %v", err) + } + got := map[string]string{} + for _, intent := range intents { + if intent.Kind != RouteIntentRemoteConsumer { + t.Fatalf("intent = %+v, want RemoteConsumer", intent) + } + got[intent.Attachment.Name] = intent.ProducerAttachment.Name + } + return got +} + +// Consumers with no producer on their node spread across the remote +// producers, and a producer joining, leaving or turning Unhealthy moves only +// the consumers it gains or loses. +func TestCompileSpreadSpreadsConsumersAcrossRemoteProducers(t *testing.T) { + policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal) + consumers := make([]*cloudv1alpha1.VPCAttachment, 0, 64) + producers := make([]*cloudv1alpha1.VPCAttachment, 0, 5) + for i := range cap(consumers) { + consumers = append(consumers, readyAttachment(eligibilityNamespace, fmt.Sprintf("consumer-%02d", i), + fmt.Sprintf("consumer-uid-%02d", i), testNodeName, fmt.Sprintf("consumer%d", i), + testLabels(testAccessLabel, "yes"))) + } + for i := range cap(producers) { + producers = append(producers, readyAttachment(spreadProducerNamespace, fmt.Sprintf("producer-%d", i), + fmt.Sprintf("producer-uid-%d", i), fmt.Sprintf("node-p%d", i), fmt.Sprintf("remote%d", i), + testLabels(testProducerLabel, "yes"))) + } + all := slices.Concat(consumers, producers[:4]) + before := remoteAssignments(t, policy, endpoint, all) + if len(before) != len(consumers) { + t.Fatalf("assignments = %d, want %d", len(before), len(consumers)) + } + load := map[string]int{} + for _, producer := range before { + load[producer]++ + } + for _, producer := range producers[:4] { + if load[producer.Name] == 0 { + t.Fatalf("producer %s took no consumer: %v", producer.Name, load) + } + } + + // moved returns the consumers whose producer changed, failing if any + // moved for a reason other than allowed. + moved := func(after map[string]string, allowed func(from, to string) bool) int { + t.Helper() + n := 0 + for consumer, from := range before { + to := after[consumer] + if from == to { + continue + } + if !allowed(from, to) { + t.Fatalf("consumer %s moved from %s to %s", consumer, from, to) + } + n++ + } + return n + } + + // Each producer's node installs the producer half of exactly the + // pairings the consumer's node chose. + for _, producer := range producers[:4] { + intents, err := Compile(policy, endpoint, all, producer.Status.Node, + func(*cloudv1alpha1.VPCAttachment) (net.IP, error) { return net.ParseIP("fd00::1"), nil }) + if err != nil { + t.Fatalf("Compile on %s: %v", producer.Status.Node, err) + } + if len(intents) != load[producer.Name] { + t.Fatalf("%s has %d producer halves, want %d", producer.Name, len(intents), load[producer.Name]) + } + for _, intent := range intents { + if intent.Kind != RouteIntentRemoteProducer || before[intent.Attachment.Name] != producer.Name { + t.Fatalf("%s installs %+v, but the consumer's node chose %s", + producer.Name, intent, before[intent.Attachment.Name]) + } + } + } + + joined := remoteAssignments(t, policy, endpoint, slices.Concat(consumers, producers)) + if moved(joined, func(_, to string) bool { return to == producers[4].Name }) == 0 { + t.Fatalf("producer-4 joined but took no consumer") + } + left := remoteAssignments(t, policy, endpoint, slices.Concat(consumers, producers[1:4])) + fromFirst := func(from, _ string) bool { return from == producers[0].Name } + if got := moved(left, fromFirst); got != load[producers[0].Name] { + t.Fatalf("producer-0 left: %d consumers moved, want its %d", got, load[producers[0].Name]) + } + reportHealth(endpoint, producers[1], networkv1alpha1.BackendHealthUnhealthy) + unhealthy := remoteAssignments(t, policy, endpoint, all) + fromSecond := func(from, _ string) bool { return from == producers[1].Name } + if got := moved(unhealthy, fromSecond); got != load[producers[1].Name] { + t.Fatalf("producer-1 Unhealthy: %d consumers moved, want its %d", got, load[producers[1].Name]) + } +} diff --git a/internal/serviceroute/programming.go b/internal/serviceroute/programming.go index add320c3e..c7e43aa4e 100644 --- a/internal/serviceroute/programming.go +++ b/internal/serviceroute/programming.go @@ -81,7 +81,7 @@ func ProgrammingPlan(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *netwo continue } selected++ - local, p := selectProducers(endpoint, a.Status.Node, producers, health) + local, p := selectProducers(endpoint, a, producers, health) if len(local) != 0 { p = local[0] } From 7eb5b65eeaee08d26dee50fecd400b7f7f8d82b2 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 22:03:24 -0400 Subject: [PATCH 2/4] fix(cni): Keep a TCP connection's producer when its pin is lost A LocalSet route keeps a TCP connection on its producer through a pin in service_flow_table. That table is an LRU holding a quarter of service_reverse_table's flows, and a pin also ends after 300 seconds idle. A packet with no live pin was placed by hash % eligible_count. When a producer joined or left after the connection opened, most pin-less connections mapped to a different producer and reset, even though the connection's own reverse row still named its producer. service_select_producer now does three things in order: - A TCP packet with no live pin checks each member of the set for the reverse row this flow's packets left: the reply tuple on that member's interface, in LOCAL mode, for this consumer interface and that member's token, used within the flow timeout. If one matches and the member's interface identity still matches its token, the connection keeps that producer, draining or not, and is pinned again. This uses the same rule as the pin. An opening SYN (SYN without ACK) skips the probe, so a client reusing a recent tuple cannot reach a draining producer. - Only a flow with neither a pin nor a reverse row is placed by hash. The hash is now rendezvous over the eligible members' identity tokens, so a producer joining or leaving moves only the connections it gains or loses. - UDP still picks at random, through the same rendezvous step with a random hash. No map layout changes, so loading this datapath recreates no pinned map. TestUsidServiceEgress_LocalSetKeepsTCPFlowsWithoutPins opens 64 connections across two producers, adds a third and evicts every pin. Each connection must keep its producer. Without the fix, port 44030 moved from producer 50 to producer 1. The test then clears all flow state, adds the third producer again, and checks that each connection either stays or moves to the new producer, then that removing that producer moves only its own connections. TestUsidServiceEgress_LocalSetReverseRowFallback checks that a pin-less connection keeps a draining producer, that an opening SYN on the same tuple goes to an eligible producer, and that a producer whose interface was replaced is skipped. Removing the SYN check or the identity check makes it fail. Related to #1097 --- docs/private-services/README.md | 21 +- internal/plumbing/ebpf/prog/usid.c | 134 +++++++++--- .../ebpf/prog/usid_service_spread_test.go | 204 ++++++++++++++++++ 3 files changed, 320 insertions(+), 39 deletions(-) diff --git a/docs/private-services/README.md b/docs/private-services/README.md index 4fff31ed4..daa684090 100644 --- a/docs/private-services/README.md +++ b/docs/private-services/README.md @@ -68,7 +68,9 @@ 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. + check fails. A new connection goes to the eligible producer that rendezvous + hashing of its flow ranks first, so a producer joining or leaving moves only + the connections it gains or loses. - 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; @@ -147,14 +149,15 @@ 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. +A TCP connection's pin ends after 300 seconds without traffic, the same idle +limit replies have, or when the node evicts it under load or reloads the +datapath. A packet of an established connection with no pin stays with the +producer whose reply row, which the node keeps for four times as many flows, +shows it already carries the connection. Only a connection with neither is +placed by its hash again: it stays with its producer unless a producer that +joined since ranks first for it. Changing an endpoint between `Single` and +`Spread` replaces its routes, which can drop a request in flight and moves +existing TCP connections. Apply the `ServiceEndpointProducerReport` CRD and the `galactic-router` RBAC for it before upgrading `galactic-router` to a version that writes diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index 82009036f..0d5e258d3 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -250,6 +250,7 @@ static long (*bpf_skb_change_head)(struct __sk_buff *skb, __u32 len, __u64 flags // bytes, the space a 4-bit data offset leaves after the 20-byte fixed header. #define USID_TCP_FLAGS_OFFSET 13 #define USID_TCP_FLAG_SYN 0x02 +#define USID_TCP_FLAG_ACK 0x10 #define USID_TCP_MAX_OPTIONS_LEN 40 // How many options clamp_tcp_mss walks before giving up, NOPs included. The // verifier's cost for the walk grows linearly up to about 20 steps and then @@ -1590,8 +1591,8 @@ struct { // service_reverse_table: a pin only chooses among the route's current // members, so a stale one grants nothing. An LRU map is always preallocated, // and galactic-cni's memory cgroup pays for it, so it holds a quarter of the -// reverse table's flows; an evicted pin's next packet takes the producer its -// hash picks, the same one while the set is unchanged. +// reverse table's flows; an evicted pin's next packet keeps the producer its +// reverse row names, and only a flow with neither is placed by its hash. struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768); @@ -4036,7 +4037,7 @@ static USID_ALWAYS_INLINE int parse_service_packet(struct __sk_buff *skb, __be16 struct service_fib_scratch_value *scratch); static USID_NOINLINE int service_install_reverse(struct service_fib_scratch_value *s); static USID_NOINLINE int service_select_producer(struct service_fib_scratch_value *s, __u32 ifindex, - __u32 *target_ifindex, __u64 *producer_token); + __u32 *target_ifindex, __u64 *producer_token, int opening); static USID_ALWAYS_INLINE int service_local_route_has_producer(const struct service_route_key *key, const struct service_route_value *route, __u32 producer_ifindex, __u64 producer_token); @@ -5049,19 +5050,50 @@ static USID_ALWAYS_INLINE __u32 service_flow_hash(const struct service_reverse_k return h; } +// service_load_flow_key fills s->reverse with the consumer flow's forward +// tuple on ifindex, the key of its pin in service_flow_table. +static USID_ALWAYS_INLINE void service_load_flow_key(struct service_fib_scratch_value *s, __u32 ifindex) +{ + __builtin_memset(&s->reverse, 0, sizeof(s->reverse)); + s->reverse.ingress_ifindex = ifindex; + s->reverse.family = s->meta_family; + s->reverse.protocol = s->protocol; + s->reverse.source_port = s->source_port; + s->reverse.dest_port = s->dest_port; + __builtin_memcpy(s->reverse.source_addr, s->source_addr, 16); + __builtin_memcpy(s->reverse.dest_addr, s->dest_addr, 16); +} + +// service_rendezvous_score ranks member token for a flow hash. The member with +// the highest score takes the flow, so a member joining or leaving the +// eligible set moves only the flows it gains or loses. The SplitMix64 +// finalizer spreads tokens that differ in few bits. +static USID_ALWAYS_INLINE __u64 service_rendezvous_score(__u32 hash, __u64 token) +{ + __u64 x = ((__u64) hash * 0x9e3779b97f4a7c15ULL) ^ token; + x ^= x >> 30; + x *= 0xbf58476d1ce4e5b9ULL; + x ^= x >> 27; + x *= 0x94d049bb133111ebULL; + return x ^ (x >> 31); +} + // service_select_producer picks the producer of the LocalSet route under // s->route for the packet s describes, arriving on ifindex. A TCP packet keeps // the producer its flow is pinned to while that producer is still a member, -// draining or not; otherwise, and for a new TCP flow, it takes an eligible -// producer by the flow's hash and pins it. A UDP packet takes an eligible -// producer at random, so the requests of one socket spread too. A member -// whose interface identity no longer matches its token is never kept or -// pinned, so a flow retried while the router repairs the set is not held to -// it. It returns nonzero when the route has no producer set, no eligible -// producer, or picked a member with a stale identity. It overwrites -// s->reverse. +// draining or not. Without a live pin, a packet other than an opening SYN +// keeps the member whose live reverse row shows it already carries this +// consumer's flow, since service_reverse_table holds four times the flows +// service_flow_table does; an opening SYN skips that row, so a reused tuple +// cannot reach a draining producer. Otherwise, and for a new TCP flow, it takes the eligible producer that rendezvous hashing of the +// flow ranks first, and pins it. A UDP packet takes an eligible producer at +// random, so the requests of one socket spread too. A member whose interface +// identity no longer matches its token is never kept or pinned, so a flow +// retried while the router repairs the set is not held to it. It returns +// nonzero when the route has no producer set, no eligible producer, or picked +// a member with a stale identity. It overwrites s->reverse. static USID_NOINLINE int service_select_producer(struct service_fib_scratch_value *s, __u32 ifindex, - __u32 *target_ifindex, __u64 *producer_token) + __u32 *target_ifindex, __u64 *producer_token, int opening) { struct service_producer_set_value *set = bpf_map_lookup_elem(&service_producer_set_table, &s->route); if (!set) @@ -5071,15 +5103,9 @@ static USID_NOINLINE int service_select_producer(struct service_fib_scratch_valu return -1; __u64 now = bpf_ktime_get_ns(); int tcp = s->protocol == USID_IPPROTO_TCP; + __u32 index = SERVICE_PRODUCER_SET_MAX; if (tcp) { - __builtin_memset(&s->reverse, 0, sizeof(s->reverse)); - s->reverse.ingress_ifindex = ifindex; - s->reverse.family = s->meta_family; - s->reverse.protocol = s->protocol; - s->reverse.source_port = s->source_port; - s->reverse.dest_port = s->dest_port; - __builtin_memcpy(s->reverse.source_addr, s->source_addr, 16); - __builtin_memcpy(s->reverse.dest_addr, s->dest_addr, 16); + service_load_flow_key(s, ifindex); struct service_flow_value *pin = bpf_map_lookup_elem(&service_flow_table, &s->reverse); if (pin && now - pin->last_seen_ns <= SERVICE_FLOW_TIMEOUT_NS) { #pragma unroll @@ -5094,17 +5120,58 @@ static USID_NOINLINE int service_select_producer(struct service_fib_scratch_valu } } } + + // Probe each member for the reply row this flow's packets left. + if (opening) + goto place; + __builtin_memset(&s->reverse, 0, sizeof(s->reverse)); + s->reverse.family = s->meta_family; + s->reverse.protocol = s->protocol; + s->reverse.source_port = s->dest_port; + s->reverse.dest_port = s->source_port; + __builtin_memcpy(s->reverse.source_addr, s->dest_addr, 16); + __builtin_memcpy(s->reverse.dest_addr, s->source_addr, 16); +#pragma unroll + for (int i = 0; i < SERVICE_PRODUCER_SET_MAX; i++) { + if ((__u32) i >= count || index != SERVICE_PRODUCER_SET_MAX) + continue; + s->reverse.ingress_ifindex = set->members[i].ifindex; + struct service_reverse_value *row = bpf_map_lookup_elem(&service_reverse_table, &s->reverse); + if (row && row->mode == SERVICE_ROUTE_MODE_LOCAL && row->consumer_ifindex == ifindex && + row->producer_token == set->members[i].token && + now - row->last_seen_ns <= SERVICE_FLOW_TIMEOUT_NS && + service_identity_matches(set->members[i].ifindex, set->members[i].token)) + index = i; + } +place: + service_load_flow_key(s, ifindex); + } + if (index == SERVICE_PRODUCER_SET_MAX) { + __u32 eligible = set->eligible_count; + if (eligible == 0 || eligible > count) + return -1; + __u32 hash = tcp ? service_flow_hash(&s->reverse) : bpf_get_prandom_u32(); + __u64 best = 0; +#pragma unroll + for (int i = 0; i < SERVICE_PRODUCER_SET_MAX; i++) { + if ((__u32) i >= eligible) + continue; + __u32 candidate = set->eligible[i]; + if (candidate >= count) + return -1; + USID_BARRIER_VAR(candidate); + __u64 score = service_rendezvous_score(hash, + set->members[candidate & (SERVICE_PRODUCER_SET_MAX - 1)].token); + if (index == SERVICE_PRODUCER_SET_MAX || score > best) { + index = candidate; + best = score; + } + } + if (index >= count) + return -1; } - __u32 eligible = set->eligible_count; - if (eligible == 0 || eligible > count) - return -1; - __u32 slot = (tcp ? service_flow_hash(&s->reverse) : bpf_get_prandom_u32()) % eligible; - // The compiler knows slot < 16 and drops a plain mask, which the verifier + // The compiler knows index < 16 and drops a plain mask, which the verifier // needs to bound the map value offsets. - USID_BARRIER_VAR(slot); - __u32 index = set->eligible[slot & (SERVICE_PRODUCER_SET_MAX - 1)]; - if (index >= count) - return -1; USID_BARRIER_VAR(index); struct service_producer_member *member = &set->members[index & (SERVICE_PRODUCER_SET_MAX - 1)]; if (!service_identity_matches(member->ifindex, member->token)) @@ -5399,7 +5466,14 @@ static USID_NOINLINE long service_path(struct __sk_buff *skb, __be16 h_proto, __ __u32 target_ifindex = route->target_ifindex; __u64 producer_token = route->producer_token; if (route->mode == SERVICE_ROUTE_MODE_LOCAL_SET) { - if (service_select_producer(s, ifindex, &target_ifindex, &producer_token) || + __u8 flags = 0; + if (s->protocol == USID_IPPROTO_TCP && + bpf_skb_load_bytes(skb, s->l4_offset + USID_TCP_FLAGS_OFFSET, &flags, 1)) { + count_drop(DROP_REASON_SERVICE_ROUTE_DENIED); + return TC_ACT_SHOT; + } + int opening = (flags & (USID_TCP_FLAG_SYN | USID_TCP_FLAG_ACK)) == USID_TCP_FLAG_SYN; + if (service_select_producer(s, ifindex, &target_ifindex, &producer_token, opening) || !service_identity_matches(target_ifindex, producer_token)) { count_drop(DROP_REASON_SERVICE_ROUTE_DENIED); return TC_ACT_SHOT; diff --git a/internal/plumbing/ebpf/prog/usid_service_spread_test.go b/internal/plumbing/ebpf/prog/usid_service_spread_test.go index 5c737826d..48e620a33 100644 --- a/internal/plumbing/ebpf/prog/usid_service_spread_test.go +++ b/internal/plumbing/ebpf/prog/usid_service_spread_test.go @@ -284,3 +284,207 @@ func TestUsidServiceEgress_LocalSetFailsClosed(t *testing.T) { t.Fatalf("request with no producer set: verdict=%d err=%v, want TC_ACT_SHOT", ret, err) } } + +// A TCP connection whose flow pin is lost keeps its producer while that +// producer stays in the set, and a producer joining takes only the pin-less +// connections it gains. +func TestUsidServiceEgress_LocalSetKeepsTCPFlowsWithoutPins(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + const ( + tcp = uint8(6) + joinedMember = uint32(51) + joinedToken = uint64(51) + firstPort = uint16(44000) + connections = 64 + ) + setUpLocalSet(t, objs, tcp, spreadLocalProducer, spreadRemoteProducer) + pinKey := func(port uint16) UsidServiceReverseKey { + return UsidServiceReverseKey{ + IngressIfindex: 1, Family: egressRouteFamilyINET6, Protocol: tcp, + SourcePort: bits.ReverseBytes16(port), DestPort: bits.ReverseBytes16(spreadServicePort), + SourceAddr: spreadConsumer.As16(), DestAddr: spreadService.As16(), + } + } + pinned := func(port uint16) uint32 { + t.Helper() + var pin UsidServiceFlowValue + if err := objs.ServiceFlowTable.Lookup(pinKey(port), &pin); err != nil { + t.Fatalf("flow pin for port %d: %v", port, err) + } + return pin.ProducerIfindex + } + dropPins := func() { + t.Helper() + for port := firstPort; port < firstPort+connections; port++ { + if err := objs.ServiceFlowTable.Delete(pinKey(port)); err != nil { + t.Fatalf("evict pin for port %d: %v", port, err) + } + } + } + // A third member joins the set, eligible for new flows. + join := func() { + t.Helper() + if err := objs.AttachmentIdentityTable.Put(joinedMember, joinedToken); err != nil { + t.Fatal(err) + } + var set UsidServiceProducerSetValue + set.Count, set.EligibleCount = 3, 3 + for i, member := range []struct { + ifindex uint32 + token uint64 + }{{spreadLocalProducer, spreadConsumerToken}, {spreadRemoteProducer, spreadOtherToken}, {joinedMember, joinedToken}} { + set.Members[i].Ifindex, set.Members[i].Token = member.ifindex, member.token + set.Eligible[i] = uint8(i) + } + if err := objs.ServiceProducerSetTable.Put(spreadRouteKey(tcp), set); err != nil { + t.Fatalf("populate producer set: %v", err) + } + } + + before := map[uint16]uint32{} + for port := firstPort; port < firstPort+connections; port++ { + sendRequest(t, objs, tcp, port) + before[port] = pinned(port) + } + + // The pins are evicted, but each connection's reverse row still names its + // producer. + join() + dropPins() + for port, producer := range before { + sendRequest(t, objs, tcp, port) + if got := pinned(port); got != producer { + t.Fatalf("connection from port %d lost its pin and moved from producer %d to %d", port, producer, got) + } + } + + // With no flow state left at all, a connection is placed by its hash: it + // stays where it was or moves to the producer that joined. + setUpLocalSet(t, objs, tcp, spreadLocalProducer, spreadRemoteProducer) + dropPins() + clearReverse(t, objs) + for port := firstPort; port < firstPort+connections; port++ { + sendRequest(t, objs, tcp, port) + before[port] = pinned(port) + } + join() + dropPins() + clearReverse(t, objs) + gained := 0 + for port, producer := range before { + sendRequest(t, objs, tcp, port) + switch got := pinned(port); got { + case producer: + case joinedMember: + gained++ + default: + t.Fatalf("connection from port %d moved from producer %d to %d, not to the one that joined", + port, producer, got) + } + } + if gained == 0 { + t.Fatalf("the producer that joined gained none of %d connections", connections) + } + + // With no flow state, the producer that joined leaving moves only its + // own connections. + for port := firstPort; port < firstPort+connections; port++ { + before[port] = pinned(port) + } + setUpLocalSet(t, objs, tcp, spreadLocalProducer, spreadRemoteProducer) + dropPins() + clearReverse(t, objs) + for port, producer := range before { + sendRequest(t, objs, tcp, port) + if got := pinned(port); producer != joinedMember && got != producer { + t.Fatalf("connection from port %d moved from producer %d to %d when another left", port, producer, got) + } + } +} + +func spreadFlowKey(port uint16) UsidServiceReverseKey { + return UsidServiceReverseKey{ + IngressIfindex: 1, Family: egressRouteFamilyINET6, Protocol: 6, + SourcePort: bits.ReverseBytes16(port), DestPort: bits.ReverseBytes16(spreadServicePort), + SourceAddr: spreadConsumer.As16(), DestAddr: spreadService.As16(), + } +} + +// spreadPinned returns the producer the TCP flow from port is pinned to, or 0 +// when it has no pin. +func spreadPinned(t *testing.T, objs *UsidObjects, port uint16) uint32 { + t.Helper() + var pin UsidServiceFlowValue + err := objs.ServiceFlowTable.Lookup(spreadFlowKey(port), &pin) + if errors.Is(err, ebpf.ErrKeyNotExist) { + return 0 + } + if err != nil { + t.Fatal(err) + } + return pin.ProducerIfindex +} + +// Without its pin, a TCP connection keeps a draining producer through its +// reverse row, but an opening SYN on the same tuple, or a producer whose +// interface was replaced, does not. +func TestUsidServiceEgress_LocalSetReverseRowFallback(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + const tcp = uint8(6) + setUpLocalSet(t, objs, tcp, spreadLocalProducer, spreadRemoteProducer) + port := uint16(0) + for p := uint16(45000); p < 45064; p++ { + sendRequest(t, objs, tcp, p) + if spreadPinned(t, objs, p) == spreadRemoteProducer { + port = p + break + } + } + if port == 0 { + t.Fatal("64 TCP connections all went to producer 1") + } + members := []uint32{spreadLocalProducer, spreadRemoteProducer} + putProducerSet(t, objs, tcp, members, []uint32{spreadLocalProducer}) + evict := func() { + t.Helper() + if err := objs.ServiceFlowTable.Delete(spreadFlowKey(port)); err != nil { + t.Fatal(err) + } + } + + evict() + sendRequest(t, objs, tcp, port) + if got := spreadPinned(t, objs, port); got != spreadRemoteProducer { + t.Fatalf("connection lost its pin and left draining producer %d for %d", spreadRemoteProducer, got) + } + + evict() + syn := spreadPacket(t, tcp, spreadConsumer, spreadService, port, spreadServicePort) + syn[ethHeaderLen+ip6HeaderLen+13] = 0x02 + if ret, _, err := objs.UsidServiceEgress.Test(syn); err != nil || ret != tcActRedirect { + t.Fatalf("SYN on a reused tuple: verdict=%d err=%v, want TC_ACT_REDIRECT", ret, err) + } + if got := spreadPinned(t, objs, port); got != spreadLocalProducer { + t.Fatalf("SYN on a reused tuple went to %d, want eligible producer %d", got, spreadLocalProducer) + } + + // Put the flow back on the producer, drain it, then replace its interface. + evict() + clearReverse(t, objs) + putProducerSet(t, objs, tcp, members, []uint32{spreadRemoteProducer}) + sendRequest(t, objs, tcp, port) + if got := spreadPinned(t, objs, port); got != spreadRemoteProducer { + t.Fatalf("connection pinned to %d, want %d", got, spreadRemoteProducer) + } + putProducerSet(t, objs, tcp, members, []uint32{spreadLocalProducer}) + evict() + if err := objs.AttachmentIdentityTable.Put(spreadRemoteProducer, spreadOtherToken+1); err != nil { + t.Fatal(err) + } + sendRequest(t, objs, tcp, port) + if got := spreadPinned(t, objs, port); got != spreadLocalProducer { + t.Fatalf("connection of a replaced producer interface went to %d, want %d", got, spreadLocalProducer) + } +} From 0d2e86cd28b833ab93076177a40ba9da94788306 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 22:20:16 -0400 Subject: [PATCH 3/4] docs(cni): Rewrap the producer selection comment One line of the service_select_producer comment ran to 130 columns. This rewraps the paragraph to the width the rest of the file uses. The comment text and the code are unchanged. --- internal/plumbing/ebpf/prog/usid.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index 0d5e258d3..22dc71ba7 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -5081,17 +5081,18 @@ static USID_ALWAYS_INLINE __u64 service_rendezvous_score(__u32 hash, __u64 token // service_select_producer picks the producer of the LocalSet route under // s->route for the packet s describes, arriving on ifindex. A TCP packet keeps // the producer its flow is pinned to while that producer is still a member, -// draining or not. Without a live pin, a packet other than an opening SYN -// keeps the member whose live reverse row shows it already carries this -// consumer's flow, since service_reverse_table holds four times the flows +// draining or not. Without a live pin, a packet other than an opening SYN keeps +// the member whose live reverse row shows it already carries this consumer's +// flow, since service_reverse_table holds four times the flows // service_flow_table does; an opening SYN skips that row, so a reused tuple -// cannot reach a draining producer. Otherwise, and for a new TCP flow, it takes the eligible producer that rendezvous hashing of the -// flow ranks first, and pins it. A UDP packet takes an eligible producer at -// random, so the requests of one socket spread too. A member whose interface -// identity no longer matches its token is never kept or pinned, so a flow -// retried while the router repairs the set is not held to it. It returns -// nonzero when the route has no producer set, no eligible producer, or picked -// a member with a stale identity. It overwrites s->reverse. +// cannot reach a draining producer. Otherwise, and for a new TCP flow, it takes +// the eligible producer that rendezvous hashing of the flow ranks first, and +// pins it. A UDP packet takes an eligible producer at random, so the requests +// of one socket spread too. A member whose interface identity no longer matches +// its token is never kept or pinned, so a flow retried while the router repairs +// the set is not held to it. It returns nonzero when the route has no producer +// set, no eligible producer, or picked a member with a stale identity. It +// overwrites s->reverse. static USID_NOINLINE int service_select_producer(struct service_fib_scratch_value *s, __u32 ifindex, __u32 *target_ifindex, __u64 *producer_token, int opening) { From 5b86f2faf0db541ead9a9ec81b21637c2f38d549 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 2 Nov 2026 20:11:58 -0500 Subject: [PATCH 4/4] fix(router): Accept Spread consumers under either pairing The consumer's node and the producer's node each choose a Spread consumer's remote producer. Switching that choice from first-by-name to rendezvous hashing in one release refused every consumer whose pairing changed while routers ran mixed versions, for the whole rolling upgrade. A producer's node now installs a producer half for the producer each pairing picks, whatever its own setting. The consumer's own pairing is chosen by the new --service-spread-pairing (GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING) option, which defaults to first, the previous behavior. Once every node runs this router, setting rendezvous node by node refuses nothing, since every producer node already accepts both pairings. A later release can make rendezvous the default and then drop the first pairing. Applied intents are now keyed by consumer and producer, so the two producer halves of one consumer can coexist on a node. ProgrammingPlan counts the nodes of every accepting producer. --- cmd/galactic-router/root.go | 15 +- docs/private-services/README.md | 23 +- docs/router/configuration.md | 13 + internal/config/router.go | 26 ++ internal/config/router_test.go | 19 ++ internal/controller/serviceroute_access.go | 2 +- .../controller/serviceroute_controller.go | 47 ++-- .../serviceroute_controller_test.go | 18 +- .../controller/serviceroute_spread_test.go | 33 ++- internal/serviceroute/planner.go | 224 +++++++++++++++--- internal/serviceroute/planner_spread_test.go | 184 +++++++++----- internal/serviceroute/programming.go | 35 ++- 12 files changed, 497 insertions(+), 142 deletions(-) diff --git a/cmd/galactic-router/root.go b/cmd/galactic-router/root.go index e552deeed..efd3d02db 100644 --- a/cmd/galactic-router/root.go +++ b/cmd/galactic-router/root.go @@ -307,7 +307,7 @@ func runCmd(cfg *config.RouterConfig) error { // serviceRouteControllerEnabled). if serviceRouteControllerEnabled(cfg) { if err := setupServiceRouteController(mgr, nodeName, cfg.GCNamespace, cfg.ServiceFrontendEnabled, - serviceRouteMetrics); err != nil { + cfg.ServiceSpreadPairing, serviceRouteMetrics); err != nil { return fmt.Errorf("setup ServiceRoutePolicy controller: %w", err) } } else { @@ -475,9 +475,13 @@ func serviceRouteControllerEnabled(cfg *config.RouterConfig) bool { func setupServiceRouteController( mgr ctrl.Manager, - nodeName, bgpNamespace string, frontendEnabled bool, + nodeName, bgpNamespace string, frontendEnabled bool, spreadPairingName string, serviceRouteMetrics *serviceroute.Metrics, ) error { + spreadPairing, err := serviceroute.ParseSpreadPairing(spreadPairingName) + if err != nil { + return err + } programmer := &serviceroute.EBPFRouteProgrammer{} if err := programmer.Initialize(); err != nil { ctrl.Log.Error(err, "service route eBPF maps are not available yet; initialization will retry on reconcile") @@ -491,7 +495,8 @@ func setupServiceRouteController( Programmer: programmer, Metrics: serviceRouteMetrics, FrontendEnabled: frontendEnabled, - Applied: make(map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent), + SpreadPairing: spreadPairing, + Applied: make(map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent), }).SetupWithManager(mgr); err != nil { return err } @@ -556,6 +561,10 @@ func newRootCommand() *cobra.Command { "Cleanup interval") cmd.Flags().Bool("service-frontend-enabled", false, "Enable consumer-facing private-service address translation") + cmd.Flags().String("service-spread-pairing", config.DefaultRouterServiceSpreadPairing, + "Remote producer for this node's consumers of a Spread endpoint whose node has no producer: "+ + "first (first producer by name) or rendezvous (spread across producers); set rendezvous only "+ + "once every node runs a router that has this flag") cmd.Flags().Bool("traffic-policy", false, "Enforce TrafficPolicy on this node's tenant interfaces; needs the galactic.datumapis.com CRDs") cmd.Flags().String("bmp-stations", "", diff --git a/docs/private-services/README.md b/docs/private-services/README.md index daa684090..434726780 100644 --- a/docs/private-services/README.md +++ b/docs/private-services/README.md @@ -134,13 +134,22 @@ 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, through the SRv6 service tunnel as with `Single`. -Rendezvous hashing of the consumer's and each producer's attachment UID picks -it, among the producers whose node currently reports them `Healthy` or -`Unknown`, or has no entry for them. If there are none, it picks among the -producers whose entry expired, and failing that among all producers. So -consumers spread across the remote producers, and a producer joining, leaving -or turning `Unhealthy` moves only the consumers it gains or loses. When a node +to one remote producer, through the SRv6 service tunnel as with `Single`. It +is picked among the producers whose node currently reports them `Healthy` or +`Unknown`, or has no entry for them. If there are none, it is picked among the +producers whose entry expired, and failing that among all producers. The +consumer's node picks by its `galactic-router` setting +[`--service-spread-pairing`](../router/configuration.md#--service-spread-pairing--galactic_router_service_spread_pairing). +With `first`, the default, it picks the first producer by namespace and name, +so every remote consumer goes to the same producer. With `rendezvous`, +rendezvous hashing of the consumer's and each producer's attachment UID picks +it, so consumers spread across the remote producers, and a producer joining, +leaving or turning `Unhealthy` moves only the consumers it gains or loses. A +producer's node installs the producer half for the producer each pairing +picks, whatever its own setting, so the consumer's traffic is accepted while +its node and the producer's node use different settings. Set `rendezvous` only +after every node runs a router that has the option, since an older router +accepts only the `first` pairing. When a node goes down while its producers' attachments still read ready, its consumers move to other producers within 60 seconds of the node's last renewal, as long as another node currently reports a producer that can take them. Each consumer's diff --git a/docs/router/configuration.md b/docs/router/configuration.md index 1cc5330f9..15ab5cb3b 100644 --- a/docs/router/configuration.md +++ b/docs/router/configuration.md @@ -32,6 +32,7 @@ Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_ROUTER` prefix | GoBGP API directory | `GALACTIC_ROUTER_GOBGP_API_DIR` | `--gobgp-api-dir` | _(empty; no API)_ | | Traffic policy | `GALACTIC_ROUTER_TRAFFIC_POLICY` | `--traffic-policy` | `false` | | Service frontends | `GALACTIC_ROUTER_SERVICE_FRONTEND_ENABLED` | `--service-frontend-enabled` | `false` | +| Spread remote pairing | `GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING` | `--service-spread-pairing` | `first` | ## Required Options @@ -263,6 +264,18 @@ CNI datapaths support the frontend maps. The publishing controller supplies the producer address and `ServiceRoutePolicy.spec.frontend.address` supplies the consumer address; ports are not translated. See [private service frontends](../private-services/README.md#consumer-service-frontends) for lifecycle, rollout and compatibility requirements. +### `--service-spread-pairing` / `GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING` + +Chooses the remote producer that this node's consumers of a `Spread` +`PreferNodeLocal` endpoint are sent to when their node has no producer. With +`first`, the default, every such consumer goes to the first eligible producer +by namespace and name. With `rendezvous`, the consumers spread across the +eligible producers. A producer's node accepts a consumer under either pairing, +whatever its own setting, so nodes with different settings interoperate. Set +`rendezvous` only after every node runs a router that has this option: an +older router accepts only the `first` pairing and refuses the others. See +[several producers on one node](../private-services/README.md#several-producers-on-one-node). + ## Configuration Precedence Values are resolved in the following order (highest to lowest priority): diff --git a/internal/config/router.go b/internal/config/router.go index 6620011a4..c27cb3040 100644 --- a/internal/config/router.go +++ b/internal/config/router.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net" + "slices" "strconv" "strings" "time" @@ -44,6 +45,18 @@ const ( // RouterBMPPolicies lists the accepted GALACTIC_ROUTER_BMP_POLICY values. var RouterBMPPolicies = []string{"pre-policy", "post-policy", "local-rib", "all"} +// DefaultRouterServiceSpreadPairing sends the consumers of a Spread endpoint +// whose node has no producer to the first producer by name. Every node accepts +// consumers under both pairings, so the pairing can change node by node once +// every node runs a router that does. +const DefaultRouterServiceSpreadPairing = "first" + +// RouterServiceSpreadPairings lists the accepted +// GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING values: "first" sends every such +// consumer to the first producer by name, and "rendezvous" spreads them across +// the producers. +var RouterServiceSpreadPairings = []string{DefaultRouterServiceSpreadPairing, "rendezvous"} + // --- Router environment variable keys -------------------------------------- const ( @@ -56,6 +69,10 @@ const ( EnvRouterGCNamespace = "GALACTIC_ROUTER_GC_NAMESPACE" EnvRouterGCInterval = "GALACTIC_ROUTER_GC_INTERVAL" EnvRouterServiceFrontendEnabled = "GALACTIC_ROUTER_SERVICE_FRONTEND_ENABLED" + // EnvRouterServiceSpreadPairing chooses the remote producer this node's + // consumers of a Spread ServiceEndpoint are sent to; see + // RouterServiceSpreadPairings. + EnvRouterServiceSpreadPairing = "GALACTIC_ROUTER_SERVICE_SPREAD_PAIRING" // EnvRouterTrafficPolicy runs the node's traffic policy reconciler. Off by // default, because it watches the galactic.datumapis.com CRDs, which a // cluster may not have installed. @@ -98,6 +115,8 @@ type RouterConfig struct { GCNamespace string GCInterval time.Duration ServiceFrontendEnabled bool + // ServiceSpreadPairing is one of RouterServiceSpreadPairings. + ServiceSpreadPairing string // TrafficPolicy runs the node's traffic policy reconciler. It needs the // galactic.datumapis.com CRDs, and a route reflector cannot run it. TrafficPolicy bool @@ -130,6 +149,7 @@ func NewRouterConfig() *RouterConfig { v.SetDefault("gc_namespace", DefaultRouterGCNamespace) v.SetDefault("gc_interval", DefaultRouterGCInterval.String()) v.SetDefault("service_frontend_enabled", false) + v.SetDefault("service_spread_pairing", DefaultRouterServiceSpreadPairing) v.SetDefault("traffic_policy", false) v.SetDefault("bmp_stations", "") v.SetDefault("bmp_policy", DefaultRouterBMPPolicy) @@ -160,6 +180,7 @@ func (c *RouterConfig) BindFlags(flags *pflag.FlagSet) { {"gc-namespace", "gc_namespace"}, {"gc-interval", "gc_interval"}, {"service-frontend-enabled", "service_frontend_enabled"}, + {"service-spread-pairing", "service_spread_pairing"}, {"traffic-policy", "traffic_policy"}, {"bmp-stations", "bmp_stations"}, {"bmp-policy", "bmp_policy"}, @@ -188,6 +209,7 @@ func (c *RouterConfig) readFields() { c.GCNamespace = c.v.GetString("gc_namespace") c.GCInterval = c.v.GetDuration("gc_interval") c.ServiceFrontendEnabled = c.v.GetBool("service_frontend_enabled") + c.ServiceSpreadPairing = c.v.GetString("service_spread_pairing") c.TrafficPolicy = c.v.GetBool("traffic_policy") c.BMPStations = splitCommaList(c.v.GetString("bmp_stations")) c.BMPPolicy = c.v.GetString("bmp_policy") @@ -210,6 +232,10 @@ func (c *RouterConfig) Validate() error { if c.GRPCHealthPort < 1 || c.GRPCHealthPort > 65535 { return errors.New("grpc health port must be between 1 and 65535") } + if !slices.Contains(RouterServiceSpreadPairings, c.ServiceSpreadPairing) { + return fmt.Errorf("%s must be one of %s, got %q", EnvRouterServiceSpreadPairing, + strings.Join(RouterServiceSpreadPairings, ", "), c.ServiceSpreadPairing) + } if c.TrafficPolicy && c.Reflector { return fmt.Errorf("%s needs a node with tenant interfaces, so a route reflector cannot enable it", EnvRouterTrafficPolicy) diff --git a/internal/config/router_test.go b/internal/config/router_test.go index 4fc6bc7a1..f2cb70e8d 100644 --- a/internal/config/router_test.go +++ b/internal/config/router_test.go @@ -316,3 +316,22 @@ func TestRouterConfigTrafficPolicy(t *testing.T) { t.Fatal("a route reflector accepted traffic policy") } } + +func TestRouterConfigServiceSpreadPairing(t *testing.T) { + t.Setenv(EnvRouterNodeName, "node-a") + if got := NewRouterConfig().ServiceSpreadPairing; got != DefaultRouterServiceSpreadPairing { + t.Fatalf("default Spread pairing = %q, want %q", got, DefaultRouterServiceSpreadPairing) + } + t.Setenv(EnvRouterServiceSpreadPairing, "rendezvous") + cfg := NewRouterConfig() + if cfg.ServiceSpreadPairing != "rendezvous" { + t.Fatalf("Spread pairing = %q, want rendezvous", cfg.ServiceSpreadPairing) + } + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate() = %v", err) + } + cfg.ServiceSpreadPairing = "hash" + if err := cfg.Validate(); err == nil { + t.Fatal("an unknown Spread pairing was accepted") + } +} diff --git a/internal/controller/serviceroute_access.go b/internal/controller/serviceroute_access.go index 56af353c8..dd34a4474 100644 --- a/internal/controller/serviceroute_access.go +++ b/internal/controller/serviceroute_access.go @@ -83,7 +83,7 @@ func (r *ServiceRoutePolicyReconciler) conflictingPolicies( key := types.NamespacedName{Namespace: p.Namespace, Name: p.Name} translated[key] = p.Spec.Frontend != nil for node := range nodes { - intents, err := serviceroute.CompileForConsumerVPC(p, endpoint, attachments, node, + intents, err := r.compile(p, endpoint, attachments, node, func(*cloudv1alpha1.VPCAttachment) (net.IP, error) { return net.ParseIP("fd00::1"), nil }, identity) if err == nil { desired[key] = append(desired[key], intents...) diff --git a/internal/controller/serviceroute_controller.go b/internal/controller/serviceroute_controller.go index 3bc9a2381..3b69ace03 100644 --- a/internal/controller/serviceroute_controller.go +++ b/internal/controller/serviceroute_controller.go @@ -52,14 +52,27 @@ type ServiceRoutePolicyReconciler struct { Programmer serviceroute.RouteProgrammer Metrics *serviceroute.Metrics FrontendEnabled bool - Now func() time.Time + // SpreadPairing chooses the remote producer this node's consumers of a + // Spread endpoint are sent to. Empty is serviceroute.SpreadPairingFirst. + // Producer halves are installed under every pairing regardless. + SpreadPairing serviceroute.SpreadPairing + Now func() time.Time // startupRetryWait waits between startup sync attempts and reports false // once ctx is done. Tests replace it; nil waits on a real timer. startupRetryWait func(ctx context.Context, d time.Duration) bool mu sync.Mutex - Applied map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent + Applied map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent +} + +// compile compiles policy for node with this router's options. +func (r *ServiceRoutePolicyReconciler) compile(policy *networkv1alpha1.ServiceRoutePolicy, + endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, node string, + resolveSID serviceroute.SIDResolver, vpcIdentity string, +) ([]serviceroute.RouteIntent, error) { + return serviceroute.CompileWithOptions(policy, endpoint, attachments, node, resolveSID, + serviceroute.CompileOptions{ConsumerVPCIdentity: vpcIdentity, SpreadPairing: r.SpreadPairing}) } const serviceRouteMapResyncInterval = 30 * time.Second @@ -211,7 +224,7 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R "multiple policies claim a translated consumer tuple")) return ctrl.Result{RequeueAfter: serviceRouteMapResyncInterval}, errors.Join(errs...) } - intents, err := serviceroute.CompileForConsumerVPC(policy, endpoint, all, r.NodeName, r.sidResolver(ctx), vpcIdentity) + intents, err := r.compile(policy, endpoint, all, r.NodeName, r.sidResolver(ctx), vpcIdentity) if err != nil { var dependencyErr *serviceroute.DependencyNotReadyError if errors.As(err, &dependencyErr) { @@ -455,7 +468,7 @@ func (r *ServiceRoutePolicyReconciler) syncAllPolicies(ctx context.Context) erro compiled = append(compiled, compiledPolicy{key: key}) continue } - intents, err := serviceroute.CompileForConsumerVPC( + intents, err := r.compile( policy, endpoint, allAttachments, r.NodeName, r.sidResolver(ctx), vpcIdentity) if err != nil { // Invalid policies and node-local dependencies that are not ready @@ -695,24 +708,24 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked( ) error { defer r.updateProgrammedGauge() if r.Applied == nil { - r.Applied = make(map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent) + r.Applied = make(map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent) } current := r.Applied[key] if current == nil { - current = make(map[types.NamespacedName]serviceroute.RouteIntent) + current = make(map[serviceroute.IntentSlot]serviceroute.RouteIntent) r.Applied[key] = current } - desired := make(map[types.NamespacedName]serviceroute.RouteIntent, len(intents)) + desired := make(map[serviceroute.IntentSlot]serviceroute.RouteIntent, len(intents)) for _, intent := range intents { - desired[intent.Attachment] = intent + desired[intent.Slot()] = 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] + for slot, existing := range current { + next, ok := desired[slot] if !ok || existing.Kind != serviceroute.RouteIntentLocalSet || next.Kind != serviceroute.RouteIntentLocalSet || reflect.DeepEqual(existing, next) { continue @@ -734,14 +747,14 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked( return errors.Join(&serviceRoutePolicyCleanupError{err: err}, r.Programmer.Remove(next)) } r.Metrics.ObserveOperation("remove", nil) - current[attachment] = next + current[slot] = 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. - for attachment, existing := range current { - next, ok := desired[attachment] + for slot, existing := range current { + next, ok := desired[slot] if ok && reflect.DeepEqual(existing, next) { continue } @@ -750,10 +763,10 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked( return &serviceRoutePolicyCleanupError{err: err} } r.Metrics.ObserveOperation("remove", nil) - delete(current, attachment) + delete(current, slot) } - for attachment, intent := range desired { - if existing, ok := current[attachment]; ok && reflect.DeepEqual(existing, intent) { + for slot, intent := range desired { + if existing, ok := current[slot]; ok && reflect.DeepEqual(existing, intent) { continue } if err := r.Programmer.Apply(intent); err != nil { @@ -764,7 +777,7 @@ func (r *ServiceRoutePolicyReconciler) replacePolicyLocked( return err } r.Metrics.ObserveOperation("apply", nil) - current[attachment] = intent + current[slot] = intent } if len(current) == 0 { delete(r.Applied, key) diff --git a/internal/controller/serviceroute_controller_test.go b/internal/controller/serviceroute_controller_test.go index 8e1a08c99..eeee92a4a 100644 --- a/internal/controller/serviceroute_controller_test.go +++ b/internal/controller/serviceroute_controller_test.go @@ -138,12 +138,12 @@ func TestServiceRouteRemovePolicyResumesPartialRemove(t *testing.T) { policy := types.NamespacedName{Namespace: testServiceRoutePolicyNamespace, Name: testServiceRouteName} reconciler := &ServiceRoutePolicyReconciler{ Programmer: programmer, - Applied: map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent{ + Applied: map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent{ policy: { - {Namespace: testServiceRouteTenantNamespace, Name: "a"}: { + {Attachment: types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: "a"}}: { Attachment: types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: "a"}, }, - {Namespace: testServiceRouteTenantNamespace, Name: "b"}: { + {Attachment: types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: "b"}}: { Attachment: types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: "b"}, }, }, @@ -181,9 +181,11 @@ func TestServiceRouteStartupSyncRemovesOfflineDeletedPolicyBeforeSweep(t *testin reconciler := &ServiceRoutePolicyReconciler{ Client: fake.NewClientBuilder().WithScheme(scheme).Build(), Programmer: programmer, - Applied: map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent{ + Applied: map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent{ deletedPolicy: { - {Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName}: { + {Attachment: types.NamespacedName{ + Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName, + }}: { Attachment: types.NamespacedName{ Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName, @@ -217,9 +219,11 @@ func TestServiceRouteStartupSyncRemovalFailureKeepsGateClosed(t *testing.T) { reconciler := &ServiceRoutePolicyReconciler{ Client: fake.NewClientBuilder().WithScheme(scheme).Build(), Programmer: programmer, - Applied: map[types.NamespacedName]map[types.NamespacedName]serviceroute.RouteIntent{ + Applied: map[types.NamespacedName]map[serviceroute.IntentSlot]serviceroute.RouteIntent{ deletedPolicy: { - {Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName}: { + {Attachment: types.NamespacedName{ + Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName, + }}: { Attachment: types.NamespacedName{ Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName, diff --git a/internal/controller/serviceroute_spread_test.go b/internal/controller/serviceroute_spread_test.go index f8bb83665..dd2115b1f 100644 --- a/internal/controller/serviceroute_spread_test.go +++ b/internal/controller/serviceroute_spread_test.go @@ -68,7 +68,7 @@ func TestServiceRouteReplacePolicyAppliesChangedProducerSetFirst(t *testing.T) { } } consumer := types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName} - if got := reconciler.Applied[policy][consumer].Producers[0].Device; got != "new" { + if got := reconciler.Applied[policy][serviceroute.IntentSlot{Attachment: consumer}].Producers[0].Device; got != "new" { t.Fatalf("applied intent producer = %s, want new", got) } } @@ -180,3 +180,34 @@ func TestProducerReportsOnlyRenewedForReports(t *testing.T) { t.Error("producerReportsOnlyRenewed changed its arguments") } } + +// A node holds a producer half for each producer that accepts a consumer, so +// the halves of two producers on one node for the same consumer coexist. +func TestServiceRouteReplacePolicyKeepsEveryProducerHalf(t *testing.T) { + programmer := &retryRouteProgrammer{} + reconciler := &ServiceRoutePolicyReconciler{Programmer: programmer} + policy := types.NamespacedName{Namespace: testServiceRoutePolicyNamespace, Name: testServiceRouteName} + consumer := types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: testServiceRouteConsumerName} + half := func(producer string) serviceroute.RouteIntent { + return serviceroute.RouteIntent{ + Attachment: consumer, Kind: serviceroute.RouteIntentRemoteProducer, + ProducerAttachment: types.NamespacedName{Namespace: testServiceRouteTenantNamespace, Name: producer}, + ServiceDevice: producer, + } + } + + if err := reconciler.replacePolicy(policy, []serviceroute.RouteIntent{half("a"), half("z")}); err != nil { + t.Fatal(err) + } + if got := len(reconciler.Applied[policy]); got != 2 || programmer.applyCalls != 2 { + t.Fatalf("applied %d halves with %d Apply calls, want 2 and 2", got, programmer.applyCalls) + } + if err := reconciler.replacePolicy(policy, []serviceroute.RouteIntent{half("z")}); err != nil { + t.Fatal(err) + } + if _, kept := reconciler.Applied[policy][half("z").Slot()]; !kept || len(reconciler.Applied[policy]) != 1 || + programmer.removeCalls != 1 { + t.Fatalf("after dropping a: applied %v with %d Remove calls, want only z and 1", + reconciler.Applied[policy], programmer.removeCalls) + } +} diff --git a/internal/serviceroute/planner.go b/internal/serviceroute/planner.go index d0e5b74b4..9ee779b4f 100644 --- a/internal/serviceroute/planner.go +++ b/internal/serviceroute/planner.go @@ -11,6 +11,7 @@ import ( "fmt" "hash/fnv" "net" + "slices" "sort" "time" @@ -56,6 +57,25 @@ type RouteIntent struct { Producers []ProducerTarget } +// IntentSlot identifies one intent among a node's intents for a policy. A node +// holds at most one intent for a consumer's own half, but may hold several +// producer halves for it, one per producer that accepts the consumer. +type IntentSlot struct { + Attachment types.NamespacedName + // Producer is the producer attachment of a RouteIntentRemoteProducer + // intent, and empty for every other kind. + Producer types.NamespacedName +} + +// Slot returns the slot intent occupies. +func (intent RouteIntent) Slot() IntentSlot { + slot := IntentSlot{Attachment: intent.Attachment} + if intent.Kind == RouteIntentRemoteProducer { + slot.Producer = intent.ProducerAttachment + } + return slot +} + // ProducerTarget is one member of a LocalSet intent's producer set. type ProducerTarget struct { Attachment types.NamespacedName @@ -90,6 +110,48 @@ type DependencyNotReadyError struct{ Err error } func (e *DependencyNotReadyError) Error() string { return e.Err.Error() } func (e *DependencyNotReadyError) Unwrap() error { return e.Err } +// SpreadPairing chooses the remote producer that a Spread endpoint's consumer +// is sent to when the consumer's node has no producer. +type SpreadPairing string + +const ( + // SpreadPairingFirst sends every such consumer to the first producer by + // namespace and name. + SpreadPairingFirst SpreadPairing = "first" + // SpreadPairingRendezvous spreads such consumers across the producers by + // rendezvous hashing of the consumer's and each producer's UID. + SpreadPairingRendezvous SpreadPairing = "rendezvous" +) + +// spreadPairings lists every pairing a producer's node accepts a remote +// consumer under, whichever one the consumer's node uses. +var spreadPairings = []SpreadPairing{SpreadPairingFirst, SpreadPairingRendezvous} + +// ParseSpreadPairing returns the pairing named by value. An empty value is +// SpreadPairingFirst. +func ParseSpreadPairing(value string) (SpreadPairing, error) { + switch pairing := SpreadPairing(value); pairing { + case "": + return SpreadPairingFirst, nil + case SpreadPairingFirst, SpreadPairingRendezvous: + return pairing, nil + default: + return "", fmt.Errorf("unknown Spread pairing %q, want %q or %q", + value, SpreadPairingFirst, SpreadPairingRendezvous) + } +} + +// CompileOptions carries the optional inputs of CompileWithOptions. +type CompileOptions struct { + // ConsumerVPCIdentity, when set, requires selected consumer attachments to + // carry the live provider VPC's allocated status identity. + ConsumerVPCIdentity string + // SpreadPairing is the pairing this node's consumers use. Empty means + // SpreadPairingFirst. A producer's node accepts a consumer under every + // pairing, so nodes using different pairings still interoperate. + SpreadPairing SpreadPairing +} + // 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 @@ -98,7 +160,7 @@ func (e *DependencyNotReadyError) Unwrap() error { return e.Err } func Compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, localNode string, resolveSID SIDResolver, ) ([]RouteIntent, error) { - return compile(policy, endpoint, attachments, localNode, resolveSID, "") + return CompileWithOptions(policy, endpoint, attachments, localNode, resolveSID, CompileOptions{}) } // CompileForConsumerVPC compiles a policy while requiring selected consumer @@ -106,11 +168,24 @@ func Compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alph func CompileForConsumerVPC(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, localNode string, resolveSID SIDResolver, consumerVPCIdentity string, ) ([]RouteIntent, error) { - return compile(policy, endpoint, attachments, localNode, resolveSID, consumerVPCIdentity) + return CompileWithOptions(policy, endpoint, attachments, localNode, resolveSID, + CompileOptions{ConsumerVPCIdentity: consumerVPCIdentity}) +} + +// CompileWithOptions is Compile with the optional inputs in options. +func CompileWithOptions(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, + attachments []*cloudv1alpha1.VPCAttachment, localNode string, resolveSID SIDResolver, options CompileOptions, +) ([]RouteIntent, error) { + pairing, err := ParseSpreadPairing(string(options.SpreadPairing)) + if err != nil { + return nil, err + } + return compile(policy, endpoint, attachments, localNode, resolveSID, options.ConsumerVPCIdentity, pairing) } func compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, localNode string, resolveSID SIDResolver, consumerVPCIdentity string, + pairing SpreadPairing, ) ([]RouteIntent, error) { if policy == nil || endpoint == nil { return nil, errors.New("service route policy and endpoint are required") @@ -158,7 +233,7 @@ func compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alph if !consumerMatchesVPC(policy, consumer, consumerVPCIdentity) { continue } - local, producer := selectProducers(endpoint, consumer, producers, health) + local, producer := selectProducers(endpoint, consumer, producers, health, pairing) consumerKey := types.NamespacedName{Namespace: consumer.Namespace, Name: consumer.Name} if len(local) != 0 { if consumer.Status.Node == localNode { @@ -206,26 +281,23 @@ func compile(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alph ConsumerNextHop: attachmentNextHop(consumer, service.IP), }) } - if producer.Status.Node == localNode { - consumerSID, err := resolveSID(consumer) - if err != nil { - return nil, &DependencyNotReadyError{Err: fmt.Errorf( - "resolve consumer attachment %s SID: %w", consumerKey, err)} - } - intents = append(intents, RouteIntent{ - Attachment: consumerKey, ProducerAttachment: producerKey, Kind: RouteIntentRemoteProducer, - Service: cloneIPNet(service), Frontend: cloneIPNet(frontend), ServiceDevice: producer.Status.HostInterface, - ConsumerSID: cloneIP(consumerSID), GrantID: grantID, Ports: clonePorts(ports), - ServiceNextHop: attachmentNextHop(producer, service.IP), - }) + halves, err := producerHalves(policy, endpoint, consumer, + acceptedProducers(endpoint, consumer, producers, health, producer), localNode, resolveSID, + RouteIntent{Service: service, Frontend: frontend, Ports: ports}) + if err != nil { + return nil, err } + intents = append(intents, halves...) } setIntentAuthorization(policy, intents) sort.Slice(intents, func(i, j int) bool { if intents[i].Attachment != intents[j].Attachment { return intents[i].Attachment.String() < intents[j].Attachment.String() } - return intents[i].Kind < intents[j].Kind + if intents[i].Kind != intents[j].Kind { + return intents[i].Kind < intents[j].Kind + } + return intents[i].ProducerAttachment.String() < intents[j].ProducerAttachment.String() }) return intents, nil } @@ -345,14 +417,9 @@ func spread(endpoint *networkv1alpha1.ServiceEndpoint) bool { // selectProducers returns, for a Spread endpoint, every producer on // consumer's node as local. Otherwise, or when that node has none, it returns // the one producer the consumer is sent to, or nil. A Spread endpoint's remote -// producer is chosen by rendezvous hashing of the consumer's UID with each -// candidate's UID (see rendezvousKey), among the producers whose node currently reports them -// Healthy or Unknown, or has never reported them; failing that, among those -// whose report expired, since their node may be down; failing that, among all -// of them. A producer joining or leaving a candidate set then moves only the -// consumers it gains or loses. +// producer is the one spreadRemoteProducer picks under pairing. func selectProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumer *cloudv1alpha1.VPCAttachment, - producers []*cloudv1alpha1.VPCAttachment, health map[types.UID]producerHealth, + producers []*cloudv1alpha1.VPCAttachment, health map[types.UID]producerHealth, pairing SpreadPairing, ) (local []*cloudv1alpha1.VPCAttachment, remote *cloudv1alpha1.VPCAttachment) { if spread(endpoint) { for _, producer := range producers { @@ -363,22 +430,113 @@ func selectProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumer *cloudv if len(local) != 0 { return local, nil } - if endpoint.Spec.DeliveryMode != networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal || - len(producers) == 0 { + if endpoint.Spec.DeliveryMode != networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal { return nil, nil } - for _, want := range []producerHealth{producerEligible, producerReportExpired} { - if producer := rendezvousProducer(consumer, producers, func(p *cloudv1alpha1.VPCAttachment) bool { - return health[p.UID] == want - }); producer != nil { - return nil, producer - } - } - return nil, rendezvousProducer(consumer, producers, func(*cloudv1alpha1.VPCAttachment) bool { return true }) + return nil, spreadRemoteProducer(consumer, producers, health, pairing) } return nil, chooseProducer(endpoint.Spec.DeliveryMode, consumer.Status.Node, producers) } +// spreadRemoteProducer returns the remote producer of a Spread endpoint's +// consumer, or nil when there is none. It picks among the producers whose node +// currently reports them Healthy or Unknown, or has never reported them; +// failing that, among those whose report expired, since their node may be +// down; failing that, among all of them. SpreadPairingFirst picks the first by +// namespace and name. SpreadPairingRendezvous picks by rendezvous hashing of +// the consumer's UID with each candidate's UID (see rendezvousKey), so a +// producer joining or leaving a candidate set moves only the consumers it +// gains or loses. +func spreadRemoteProducer(consumer *cloudv1alpha1.VPCAttachment, producers []*cloudv1alpha1.VPCAttachment, + health map[types.UID]producerHealth, pairing SpreadPairing, +) *cloudv1alpha1.VPCAttachment { + pick := firstProducer + if pairing == SpreadPairingRendezvous { + pick = rendezvousProducer + } + for _, want := range []producerHealth{producerEligible, producerReportExpired} { + if producer := pick(consumer, producers, func(p *cloudv1alpha1.VPCAttachment) bool { + return health[p.UID] == want + }); producer != nil { + return producer + } + } + return pick(consumer, producers, func(*cloudv1alpha1.VPCAttachment) bool { return true }) +} + +// acceptedProducers returns the producers whose node installs a producer half +// for consumer, whose own node sends it to chosen. For a Spread endpoint those +// are the producers every pairing picks, so the consumer's traffic is accepted +// while its node and the producer's node use different pairings, as during a +// rolling upgrade or a change of the pairing setting. Otherwise it is chosen +// alone. +func acceptedProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumer *cloudv1alpha1.VPCAttachment, + producers []*cloudv1alpha1.VPCAttachment, health map[types.UID]producerHealth, + chosen *cloudv1alpha1.VPCAttachment, +) []*cloudv1alpha1.VPCAttachment { + accepted := []*cloudv1alpha1.VPCAttachment{chosen} + if !spread(endpoint) { + return accepted + } + for _, pairing := range spreadPairings { + if producer := spreadRemoteProducer(consumer, producers, health, pairing); producer != nil && + !slices.Contains(accepted, producer) { + accepted = append(accepted, producer) + } + } + return accepted +} + +// producerHalves returns the RemoteProducer intents that localNode installs for +// consumer, one for each of the accepted producers on localNode. Route +// carries the service, frontend and ports of the intents. +func producerHalves(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, + consumer *cloudv1alpha1.VPCAttachment, accepted []*cloudv1alpha1.VPCAttachment, localNode string, + resolveSID SIDResolver, route RouteIntent, +) ([]RouteIntent, error) { + var halves []RouteIntent + consumerKey := types.NamespacedName{Namespace: consumer.Namespace, Name: consumer.Name} + for _, producer := range accepted { + if producer.Status.Node != localNode { + continue + } + grantID, err := serviceGrantID(policy, endpoint, consumer, producer, route.Ports) + if err != nil { + return nil, err + } + consumerSID, err := resolveSID(consumer) + if err != nil { + return nil, &DependencyNotReadyError{Err: fmt.Errorf( + "resolve consumer attachment %s SID: %w", consumerKey, err)} + } + halves = append(halves, RouteIntent{ + Attachment: consumerKey, + ProducerAttachment: types.NamespacedName{Namespace: producer.Namespace, Name: producer.Name}, + Kind: RouteIntentRemoteProducer, + Service: cloneIPNet(route.Service), + Frontend: cloneIPNet(route.Frontend), + ServiceDevice: producer.Status.HostInterface, + ConsumerSID: cloneIP(consumerSID), + GrantID: grantID, + Ports: clonePorts(route.Ports), + ServiceNextHop: attachmentNextHop(producer, route.Service.IP), + }) + } + return halves, nil +} + +// firstProducer returns the first producer accepted by include, or nil. +func firstProducer(_ *cloudv1alpha1.VPCAttachment, producers []*cloudv1alpha1.VPCAttachment, + include func(*cloudv1alpha1.VPCAttachment) bool, +) *cloudv1alpha1.VPCAttachment { + for _, producer := range producers { + if include(producer) { + return producer + } + } + return nil +} + // rendezvousProducer returns the producer accepted by include with the highest // score for consumer, or nil when include accepts none. Producers are sorted // by name, so equal scores resolve the same way on every node. diff --git a/internal/serviceroute/planner_spread_test.go b/internal/serviceroute/planner_spread_test.go index 52f782b1b..1b1fcaeee 100644 --- a/internal/serviceroute/planner_spread_test.go +++ b/internal/serviceroute/planner_spread_test.go @@ -5,6 +5,7 @@ package serviceroute import ( "fmt" + "maps" "net" "slices" "strings" @@ -148,51 +149,73 @@ func TestCompileSpreadDrainsUnhealthyProducers(t *testing.T) { } func TestCompileSpreadFallsBackToHealthyRemoteProducer(t *testing.T) { - policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal) - consumer := spreadConsumer() - first := readyAttachment(spreadProducerNamespace, firstRemoteProducer, "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 - } + for _, pairing := range spreadPairings { + t.Run(string(pairing), func(t *testing.T) { + policy, endpoint := spreadEndpoint(networkv1alpha1.ServiceEndpointDeliveryModePreferNodeLocal) + consumer := spreadConsumer() + first := readyAttachment(spreadProducerNamespace, firstRemoteProducer, "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} + options := CompileOptions{SpreadPairing: pairing} + remote := func() types.NamespacedName { + t.Helper() + got, err := CompileWithOptions(policy, endpoint, attachments, testNodeName, resolver, options) + 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 + } - chosen := remote() - other := map[string]*cloudv1alpha1.VPCAttachment{first.Name: last, last.Name: first}[chosen.Name] - if other == nil { - t.Fatalf("remote producer = %s, want a-remote or z-remote", chosen) - } - reportHealth(endpoint, map[string]*cloudv1alpha1.VPCAttachment{first.Name: first, last.Name: last}[chosen.Name], - networkv1alpha1.BackendHealthUnhealthy) - if got := remote(); got.Name != other.Name { - t.Fatalf("remote producer with %s Unhealthy = %s, want %s", chosen.Name, got, other.Name) - } - reportHealth(endpoint, other, networkv1alpha1.BackendHealthUnhealthy) - if got := remote(); got != chosen { - t.Fatalf("remote producer with both Unhealthy = %s, want %s again", got, chosen) - } + chosen := remote() + other := map[string]*cloudv1alpha1.VPCAttachment{first.Name: last, last.Name: first}[chosen.Name] + if other == nil { + t.Fatalf("remote producer = %s, want a-remote or z-remote", chosen) + } + if pairing == SpreadPairingFirst && chosen.Name != first.Name { + t.Fatalf("remote producer = %s, want the first by name", chosen) + } + reportHealth(endpoint, map[string]*cloudv1alpha1.VPCAttachment{first.Name: first, last.Name: last}[chosen.Name], + networkv1alpha1.BackendHealthUnhealthy) + if got := remote(); got.Name != other.Name { + t.Fatalf("remote producer with %s Unhealthy = %s, want %s", chosen.Name, got, other.Name) + } + reportHealth(endpoint, other, networkv1alpha1.BackendHealthUnhealthy) + if got := remote(); got != chosen { + t.Fatalf("remote producer with both Unhealthy = %s, want %s again", got, chosen) + } - // 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) - } - want := map[string]string{first.Name: "remote-a", last.Name: "remote-z"}[chosen.Name] - if len(got) != 1 || got[0].Kind != RouteIntentRemoteProducer || got[0].ServiceDevice != want { - t.Fatalf("producer node intents = %+v, want one RemoteProducer half through %s", got, want) + // The producer node installs a half for the producer each pairing + // picks, whichever one the consumer's node uses, and two producers + // on one remote node are told apart by their SIDs. + want := map[string]bool{} + for _, p := range spreadPairings { + picked := spreadRemoteProducer(consumer, []*cloudv1alpha1.VPCAttachment{first, last}, + producersHealth(endpoint, []*cloudv1alpha1.VPCAttachment{first, last}, time.Now()), p) + want[picked.Status.HostInterface] = true + } + got, err := CompileWithOptions(policy, endpoint, attachments, testRemoteNodeName, resolver, options) + if err != nil { + t.Fatalf("Compile on the producer node: %v", err) + } + devices := map[string]bool{} + for _, intent := range got { + if intent.Kind != RouteIntentRemoteProducer { + t.Fatalf("producer node intent = %+v, want RemoteProducer", intent) + } + devices[intent.ServiceDevice] = true + } + if len(got) != len(want) || !maps.Equal(devices, want) { + t.Fatalf("producer node intents = %+v, want one RemoteProducer half through each of %v", got, want) + } + }) } } @@ -407,16 +430,17 @@ func TestWithProducerReportsPrefersReportsOverStatus(t *testing.T) { } } -// remoteAssignments compiles policy on testNodeName and returns the remote -// producer each consumer there is sent to. +// remoteAssignments compiles policy on testNodeName with pairing and returns +// the remote producer each consumer there is sent to. func remoteAssignments(t *testing.T, policy *networkv1alpha1.ServiceRoutePolicy, - endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, + endpoint *networkv1alpha1.ServiceEndpoint, attachments []*cloudv1alpha1.VPCAttachment, pairing SpreadPairing, ) map[string]string { t.Helper() resolver := func(attachment *cloudv1alpha1.VPCAttachment) (net.IP, error) { return net.ParseIP("fd00::1"), nil } - intents, err := Compile(policy, endpoint, attachments, testNodeName, resolver) + intents, err := CompileWithOptions(policy, endpoint, attachments, testNodeName, resolver, + CompileOptions{SpreadPairing: pairing}) if err != nil { t.Fatalf("Compile: %v", err) } @@ -448,7 +472,7 @@ func TestCompileSpreadSpreadsConsumersAcrossRemoteProducers(t *testing.T) { testLabels(testProducerLabel, "yes"))) } all := slices.Concat(consumers, producers[:4]) - before := remoteAssignments(t, policy, endpoint, all) + before := remoteAssignments(t, policy, endpoint, all, SpreadPairingRendezvous) if len(before) != len(consumers) { t.Fatalf("assignments = %d, want %d", len(before), len(consumers)) } @@ -461,6 +485,13 @@ func TestCompileSpreadSpreadsConsumersAcrossRemoteProducers(t *testing.T) { t.Fatalf("producer %s took no consumer: %v", producer.Name, load) } } + // The default pairing sends every consumer to the first producer. + legacy := remoteAssignments(t, policy, endpoint, all, SpreadPairingFirst) + for consumer, producer := range legacy { + if producer != producers[0].Name { + t.Fatalf("first pairing sends %s to %s, want %s", consumer, producer, producers[0].Name) + } + } // moved returns the consumers whose producer changed, failing if any // moved for a reason other than allowed. @@ -480,38 +511,63 @@ func TestCompileSpreadSpreadsConsumersAcrossRemoteProducers(t *testing.T) { return n } - // Each producer's node installs the producer half of exactly the - // pairings the consumer's node chose. + // Each producer's node, whatever its own pairing, installs the producer + // half of exactly the pairings a consumer's node chooses under either + // pairing, so nodes with different pairings refuse no consumer. for _, producer := range producers[:4] { - intents, err := Compile(policy, endpoint, all, producer.Status.Node, - func(*cloudv1alpha1.VPCAttachment) (net.IP, error) { return net.ParseIP("fd00::1"), nil }) - if err != nil { - t.Fatalf("Compile on %s: %v", producer.Status.Node, err) - } - if len(intents) != load[producer.Name] { - t.Fatalf("%s has %d producer halves, want %d", producer.Name, len(intents), load[producer.Name]) + want := map[string]bool{} + for _, consumer := range consumers { + if before[consumer.Name] == producer.Name || legacy[consumer.Name] == producer.Name { + want[consumer.Name] = true + } } - for _, intent := range intents { - if intent.Kind != RouteIntentRemoteProducer || before[intent.Attachment.Name] != producer.Name { - t.Fatalf("%s installs %+v, but the consumer's node chose %s", - producer.Name, intent, before[intent.Attachment.Name]) + for _, pairing := range spreadPairings { + intents, err := CompileWithOptions(policy, endpoint, all, producer.Status.Node, + func(*cloudv1alpha1.VPCAttachment) (net.IP, error) { return net.ParseIP("fd00::1"), nil }, + CompileOptions{SpreadPairing: pairing}) + if err != nil { + t.Fatalf("Compile on %s: %v", producer.Status.Node, err) + } + got := map[string]bool{} + for _, intent := range intents { + if intent.Kind != RouteIntentRemoteProducer || intent.ProducerAttachment.Name != producer.Name { + t.Fatalf("%s installs %+v", producer.Name, intent) + } + got[intent.Attachment.Name] = true + } + if len(intents) != len(want) || !maps.Equal(got, want) { + t.Fatalf("%s with pairing %s has producer halves for %v, want %v", + producer.Name, pairing, slices.Sorted(maps.Keys(got)), slices.Sorted(maps.Keys(want))) } } } - joined := remoteAssignments(t, policy, endpoint, slices.Concat(consumers, producers)) + joined := remoteAssignments(t, policy, endpoint, slices.Concat(consumers, producers), SpreadPairingRendezvous) if moved(joined, func(_, to string) bool { return to == producers[4].Name }) == 0 { t.Fatalf("producer-4 joined but took no consumer") } - left := remoteAssignments(t, policy, endpoint, slices.Concat(consumers, producers[1:4])) + left := remoteAssignments(t, policy, endpoint, slices.Concat(consumers, producers[1:4]), SpreadPairingRendezvous) fromFirst := func(from, _ string) bool { return from == producers[0].Name } if got := moved(left, fromFirst); got != load[producers[0].Name] { t.Fatalf("producer-0 left: %d consumers moved, want its %d", got, load[producers[0].Name]) } reportHealth(endpoint, producers[1], networkv1alpha1.BackendHealthUnhealthy) - unhealthy := remoteAssignments(t, policy, endpoint, all) + unhealthy := remoteAssignments(t, policy, endpoint, all, SpreadPairingRendezvous) fromSecond := func(from, _ string) bool { return from == producers[1].Name } if got := moved(unhealthy, fromSecond); got != load[producers[1].Name] { t.Fatalf("producer-1 Unhealthy: %d consumers moved, want its %d", got, load[producers[1].Name]) } } + +func TestParseSpreadPairing(t *testing.T) { + for value, want := range map[string]SpreadPairing{ + "": SpreadPairingFirst, "first": SpreadPairingFirst, "rendezvous": SpreadPairingRendezvous, + } { + if got, err := ParseSpreadPairing(value); err != nil || got != want { + t.Fatalf("ParseSpreadPairing(%q) = %q, %v; want %q", value, got, err, want) + } + } + if _, err := ParseSpreadPairing("hash"); err == nil { + t.Fatal("ParseSpreadPairing(hash) succeeded, want an error") + } +} diff --git a/internal/serviceroute/programming.go b/internal/serviceroute/programming.go index c7e43aa4e..845411f9c 100644 --- a/internal/serviceroute/programming.go +++ b/internal/serviceroute/programming.go @@ -26,6 +26,23 @@ type ProgrammingRequirements struct { Nodes []string } +// servingProducers returns the producers whose node installs part of +// consumer's path: its node-local producer, or every remote producer that +// accepts it under any Spread pairing, whichever pairing the consumer's node +// uses. +func servingProducers(endpoint *networkv1alpha1.ServiceEndpoint, consumer *cloudv1alpha1.VPCAttachment, + producers []*cloudv1alpha1.VPCAttachment, health map[types.UID]producerHealth, +) ([]*cloudv1alpha1.VPCAttachment, error) { + local, remote := selectProducers(endpoint, consumer, producers, health, SpreadPairingFirst) + if len(local) != 0 { + return local[:1], nil + } + if remote == nil { + return nil, fmt.Errorf("consumer attachment %s/%s has no eligible producer", consumer.Namespace, consumer.Name) + } + return acceptedProducers(endpoint, consumer, producers, health, remote), nil +} + // ProgrammingPlan identifies every consumer and selected producer node required // to serve a policy. Attachment health establishes network eligibility only. func ProgrammingPlan(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *networkv1alpha1.ServiceEndpoint, @@ -81,17 +98,17 @@ func ProgrammingPlan(policy *networkv1alpha1.ServiceRoutePolicy, endpoint *netwo continue } selected++ - local, p := selectProducers(endpoint, a, producers, health) - 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) + serving, err := servingProducers(endpoint, a, producers, health) + if err != nil { + return plan, err } - if policy.Spec.Frontend != nil && (a.UID == "" || p.UID == "") { - return plan, errors.New("translated programming requires current attachment UIDs") + nodes[a.Status.Node] = true + for _, p := range serving { + if policy.Spec.Frontend != nil && (a.UID == "" || p.UID == "") { + return plan, errors.New("translated programming requires current attachment UIDs") + } + nodes[p.Status.Node] = true } - nodes[a.Status.Node], nodes[p.Status.Node] = true, true } if selected == 0 { return plan, errors.New("no eligible consumer attachments")