diff --git a/api/network/v1alpha1/networkservice_types.go b/api/network/v1alpha1/networkservice_types.go index 18209e77d..cefadcd20 100644 --- a/api/network/v1alpha1/networkservice_types.go +++ b/api/network/v1alpha1/networkservice_types.go @@ -39,6 +39,33 @@ const ( NetworkServiceProtocolICMP NetworkServiceProtocol = "icmp" ) +// NetworkServiceSessionAffinity selects which parts of a flow a gateway hashes +// to pick its backend. Every gateway node hashes a service the same way, so a +// flow keeps its backend when it moves between nodes. Affinity is stateless: +// it holds only while the backend set is unchanged, and each change to that +// set moves about 1/N of clients, N being the number of backends. +// +// +kubebuilder:validation:Enum=None;ClientIP;ClientIPAndProtocol +type NetworkServiceSessionAffinity string + +const ( + // NetworkServiceSessionAffinityNone hashes the client's address and source + // port, so each connection is balanced on its own. + NetworkServiceSessionAffinityNone NetworkServiceSessionAffinity = "None" + + // NetworkServiceSessionAffinityClientIP hashes the client's address only, + // so every connection from one address reaches the same backend, whatever + // its port, protocol or service among the services sharing that backend + // set. + NetworkServiceSessionAffinityClientIP NetworkServiceSessionAffinity = "ClientIP" + + // NetworkServiceSessionAffinityClientIPAndProtocol hashes the client's + // address and the IP protocol, so every connection from one address over + // one protocol reaches the same backend, among the services sharing that + // backend set. + NetworkServiceSessionAffinityClientIPAndProtocol NetworkServiceSessionAffinity = "ClientIPAndProtocol" +) + // Ownership reasons for the Accepted condition on NetworkService and // NetworkEgressPolicy, reserved for an admission check that verifies the // requester is authorized for the VPC resources the object references. No such @@ -196,6 +223,18 @@ type NetworkServiceSpec struct { // +kubebuilder:validation:Minimum=1 // +kubebuilder:validation:Maximum=65535 BackendPort int32 `json:"backendPort,omitempty"` + + // SessionAffinity selects which connections from one client share a + // backend: None, the default, balances each connection on its own; + // ClientIP pins a client address to one backend; ClientIPAndProtocol pins + // a client address and protocol to one. Two services pin a client to the + // same backend only if both set the same affinity and select the same + // backend addresses. A change takes effect on every gateway node without a + // restart, and rehashes every connection of the service, so most open + // connections reach a different backend afterwards. + // +optional + // +kubebuilder:default=None + SessionAffinity NetworkServiceSessionAffinity `json:"sessionAffinity,omitempty"` } // NetworkServiceStatus defines the observed state of a NetworkService. diff --git a/config/crd/galactic.datumapis.com_networkservices.yaml b/config/crd/galactic.datumapis.com_networkservices.yaml index 4f3773be1..ce7352d99 100644 --- a/config/crd/galactic.datumapis.com_networkservices.yaml +++ b/config/crd/galactic.datumapis.com_networkservices.yaml @@ -185,6 +185,22 @@ spec: - message: 'protocol is not served yet: the gateway datapath serves tcp and udp only' rule: self in ['tcp', 'udp'] + sessionAffinity: + default: None + description: |- + SessionAffinity selects which connections from one client share a + backend: None, the default, balances each connection on its own; + ClientIP pins a client address to one backend; ClientIPAndProtocol pins + a client address and protocol to one. Two services pin a client to the + same backend only if both set the same affinity and select the same + backend addresses. A change takes effect on every gateway node without a + restart, and rehashes every connection of the service, so most open + connections reach a different backend afterwards. + enum: + - None + - ClientIP + - ClientIPAndProtocol + type: string vipAddresses: description: |- VIPAddresses is the list of ingress VIP addresses this service provisions diff --git a/docs/agents/ARCHITECTURE-GATEWAY.md b/docs/agents/ARCHITECTURE-GATEWAY.md index 513b2b493..a771e66b3 100644 --- a/docs/agents/ARCHITECTURE-GATEWAY.md +++ b/docs/agents/ARCHITECTURE-GATEWAY.md @@ -425,15 +425,24 @@ forward half, so it has exactly one branch, not two. Replies are `vip_stats_table`'s hit counters (packets/bytes/last-seen), lazily creating the row on first match. An empty backend list drops (`DROP_REASON_EMPTY_BACKEND_LIST`). -4. **Maglev lookup.** Hash the client's own `(address, port)` and look up - the precomputed Maglev table (`vip_table`'s own `maglev_table` field, - populated by the Go control plane's `internal/maglev.Table` — see - `edgemap`'s doc comment) to get a backend index, deterministically and - statelessly: every gateway node computes the identical index for the - identical flow from the identical `(VIP, backend list)` input, which is - what makes this design safe under anycast/ECMP — a flow's packets - landing on a different gateway node mid-connection still resolve to the - same backend. +4. **Maglev lookup.** Hash the client's address with what the entry's + `affinity` byte selects (`EDGE_AFFINITY_*`, from + `NetworkService.spec.sessionAffinity`): its source port under `None`, + nothing more under `ClientIP`, its L4 protocol under + `ClientIPAndProtocol`. Look up the precomputed Maglev table + (`vip_table`'s own `maglev_table` field, populated by the Go control + plane's `internal/maglev.Table` — see `edgemap`'s doc comment) to get a + backend index, deterministically and statelessly: every gateway node + computes the identical index for the identical flow from the identical + `(VIP, backend list)` input, which is what makes this design safe under + anycast/ECMP — a flow's packets landing on a different gateway node + mid-connection still resolve to the same backend. Under either client-IP + affinity `KernelDatapath` keys the table by backend address alone rather + than address and port, so services over the same backend addresses on + different backend ports build the same table and pin a client to the + same backend. `affinity` occupies padding before `generation`, so it adds + nothing to `vip_value`'s size, and a zero byte reads as `None`. See + [configuration.md](../gateway/configuration.md#session-affinity). 5. **Push** a fresh 40-byte outer IPv6 header addressed to the chosen backend's own worker-node SRv6 uSID (`vip_table`'s per-backend field, resolved by the Go control plane the same way any other cross-node SRv6 diff --git a/docs/api/network-gateway.md b/docs/api/network-gateway.md index 24664b157..7933ebafc 100644 --- a/docs/api/network-gateway.md +++ b/docs/api/network-gateway.md @@ -435,6 +435,29 @@ _Appears in:_ | `icmp` | NetworkServiceProtocolICMP matches ICMP traffic: ICMPv6 (IP protocol 58)
on an IPv6 VIP and ICMP (IP protocol 1) on an IPv4 VIP. It has no ports.
It is declared but not served yet.
| +#### NetworkServiceSessionAffinity + +_Underlying type:_ _string_ + +NetworkServiceSessionAffinity selects which parts of a flow a gateway hashes +to pick its backend. Every gateway node hashes a service the same way, so a +flow keeps its backend when it moves between nodes. Affinity is stateless: +it holds only while the backend set is unchanged, and each change to that +set moves about 1/N of clients, N being the number of backends. + +_Validation:_ +- Enum: [None ClientIP ClientIPAndProtocol] + +_Appears in:_ +- [NetworkServiceSpec](#networkservicespec) + +| Field | Description | +| --- | --- | +| `None` | NetworkServiceSessionAffinityNone hashes the client's address and source
port, so each connection is balanced on its own.
| +| `ClientIP` | NetworkServiceSessionAffinityClientIP hashes the client's address only,
so every connection from one address reaches the same backend, whatever
its port, protocol or service among the services sharing that backend
set.
| +| `ClientIPAndProtocol` | NetworkServiceSessionAffinityClientIPAndProtocol hashes the client's
address and the IP protocol, so every connection from one address over
one protocol reaches the same backend, among the services sharing that
backend set.
| + + #### NetworkServiceSpec @@ -455,6 +478,7 @@ _Appears in:_ | `port` _integer_ | Port is the ingress port on VIPAddresses that this service load-balances,
1-65535. It is required for a protocol with ports (tcp, udp and sctp)
and must be unset for one without (esp, gre and icmp). Zero means unset
and is omitted when encoding, and an explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| | `backendSelector` _[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v/#labelselector-v1-meta)_ | BackendSelector selects the VPCAttachments (galactic.datumapis.com/v1alpha1,
in any namespace) that serve this service, matched against each
VPCAttachment object's own labels. Only attachments whose status.vpc
equals VPCRef are candidates, whatever their labels, so a selector cannot
reach into another tenant's VPC. Each selected attachment contributes the
IPv6 addresses in its spec.interface.addresses as backends, on
BackendPort, for both VIPs: its node translates the IPv4 VIP's flows to
and from IPv6, and its IPv4 addresses are never backends. An attachment
with no status.node, or no IPv6 address, is not a backend until it has
both. An empty selector is rejected rather than read as "every
attachment in the VPC". | | Required: \{\}
| | `backendPort` _integer_ | BackendPort is the destination port on every selected backend, 1-65535.
Like Port, it is required for tcp, udp and sctp and must be unset for
esp, gre and icmp. Zero means unset and is omitted when encoding, and an
explicit 0 is refused. | | Maximum: 65535
Minimum: 1
| +| `sessionAffinity` _[NetworkServiceSessionAffinity](#networkservicesessionaffinity)_ | SessionAffinity selects which connections from one client share a
backend: None, the default, balances each connection on its own;
ClientIP pins a client address to one backend; ClientIPAndProtocol pins
a client address and protocol to one. Two services pin a client to the
same backend only if both set the same affinity and select the same
backend addresses. A change takes effect on every gateway node without a
restart, and rehashes every connection of the service, so most open
connections reach a different backend afterwards. | None | Enum: [None ClientIP ClientIPAndProtocol]
| #### NetworkServiceStatus diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 5c566d65a..24b6b7420 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -520,6 +520,7 @@ gateway node, named after that node (see the worked example above). | `spec.port` | tcp, udp | `int32` (1–65535) | Ingress port on `vipAddresses` this rule load-balances. Required for a protocol with ports, refused for one without. | | `spec.backendSelector` | Yes | `metav1.LabelSelector` | Selects the `VPCAttachment`s (`galactic.datumapis.com`, any namespace) that serve the rule. Each contributes its IPv6 interface addresses as backends of both VIPs; its IPv4 addresses are never backends. Must not be empty. | | `spec.backendPort` | tcp, udp | `int32` (1–65535) | Destination port on every selected backend. Required for a protocol with ports, refused for one without. | +| `spec.sessionAffinity` | No | `string` enum | `None` (default), `ClientIP` or `ClientIPAndProtocol`: which connections from one client share a backend. See [Session affinity](#session-affinity). | | `status.conditions` | — | — | `Accepted` (set `True` once gateway nodes exist in the namespace; not an ownership check, see below); the rule-wide `Programmed`, `Advertised`, `BackendsReady`, `Ready` and, with an IPv4 VIP, `IPv4Served` (see [Reading a rule's status](#reading-a-rules-status)); `/Programmed` and `/Advertised` per gateway node, `/IPv4Served` per gateway node for a rule with an IPv4 VIP, and `/BackendsBound` per node hosting a backend. | Example, the TCP rule from `deploy/containerlab/resources/galactic-gateway/iad/networkservices.yaml`: @@ -632,6 +633,38 @@ cannot keep the backend nodes' IPv4 bindings alive. A node missing from the gate uncached read of the API server first, so a new gateway node's conditions are never removed while the cache has yet to see its `NetworkGateway`. +#### Session affinity + +`spec.sessionAffinity` selects what a gateway hashes, besides the client's +address, to pick a backend: + +| Value | Hashed | Connections from one client that share a backend | +| --------------------- | --------------------------- | ------------------------------------------------------- | +| `None` (default) | Address and source port | None: each connection is balanced on its own | +| `ClientIP` | Address | All, whatever their port, protocol or service | +| `ClientIPAndProtocol` | Address and the IP protocol | Those over one protocol, whatever their port or service | + +Affinity keeps no state. Every gateway node hashes the same inputs over the +same Maglev table, so a client's flows reach the same backend whichever node +receives them. Under `ClientIP` and `ClientIPAndProtocol` the table depends +only on the backends' addresses, so services that set the same affinity and +select the same backend addresses pin a client to the same backend, even with +different `port`s and `backendPort`s. A rule's IPv4 and IPv6 VIPs are +separate tables over each family's backends, and a client's IPv4 and IPv6 +addresses are different clients. + +Affinity holds only while the backend set is unchanged. Adding or removing a +backend moves about 1 in N clients to another backend, N being the number of +backends, and each moved TCP connection is reset by its new backend. Clients +behind one NAT address share a backend under either client-IP mode. + +A change to `sessionAffinity` takes effect on every gateway node at the next +reconcile, with no restart. It rehashes every connection of the service, so a +connection reaches a different backend afterwards with odds of (N-1)/N; change +it when the service can take that. Set it only once every gateway node runs a +release that serves it: a gateway without affinity support ignores the field +and balances by source port, so nodes would disagree on a client's backend. + #### Reading a rule's status Rule-wide conditions say whether a rule serves, without reading diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index 9074648bf..1687d1dd1 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -1484,6 +1484,7 @@ func buildDesiredRule( VIPAddresses: vips, Protocol: string(rule.Spec.Protocol), Port: port, + Affinity: string(rule.Spec.SessionAffinity), Backends: v6Backends, IPv4Backends: v4Backends, }, unresolved, ipv4, nil diff --git a/internal/controller/networkgateway_controller_test.go b/internal/controller/networkgateway_controller_test.go index a589e75fa..988b58716 100644 --- a/internal/controller/networkgateway_controller_test.go +++ b/internal/controller/networkgateway_controller_test.go @@ -1984,3 +1984,33 @@ func TestNetworkGatewayReconciler_KeepsAdvertisementForRuleMissingFromCache(t *t t.Errorf("BGPAdvertisement %s for a live rule was removed: %v", own.Name, err) } } + +// TestBuildDesiredRule_CarriesSessionAffinity: the service's sessionAffinity +// reaches the engine as written, an unset one as empty, which the datapath +// treats as None. +func TestBuildDesiredRule_CarriesSessionAffinity(t *testing.T) { + backendRouter, backendAdv, backendVRF := newBackendFixtures("vpc-1") + idx := &backendSIDIndex{ + routers: map[string]*bgpv1alpha1.BGPRouter{backendRouter.Name: backendRouter}, + advs: []*bgpv1alpha1.BGPAdvertisement{backendAdv}, + vrfInstances: map[string]*bgpv1alpha1.BGPVRFInstance{backendVRF.Name: backendVRF}, + } + attachments := []*cloudv1alpha1.VPCAttachment{newBackendAttachment("vpc-1")} + + for _, affinity := range []bgpv1alpha1.NetworkServiceSessionAffinity{ + "", + bgpv1alpha1.NetworkServiceSessionAffinityNone, + bgpv1alpha1.NetworkServiceSessionAffinityClientIP, + bgpv1alpha1.NetworkServiceSessionAffinityClientIPAndProtocol, + } { + rule := newTestRule(testRuleName, "vpc-1", testVIP) + rule.Spec.SessionAffinity = affinity + dr, _, _, err := buildDesiredRule(rule, attachments, idx, nil, false, nil) + if err != nil { + t.Fatalf("affinity %q: %v", affinity, err) + } + if dr.Affinity != string(affinity) { + t.Errorf("affinity %q: DesiredRule.Affinity = %q", affinity, dr.Affinity) + } + } +} diff --git a/internal/gateway/affinity_test.go b/internal/gateway/affinity_test.go new file mode 100644 index 000000000..1125ef745 --- /dev/null +++ b/internal/gateway/affinity_test.go @@ -0,0 +1,290 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "fmt" + "math/rand/v2" + "net/netip" + "testing" + + "go.datum.net/galactic/internal/plumbing/ebpf/edgemap" + "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" +) + +// affinityTestBackends returns n backends sharing port, each on its own +// worker uSID. +func affinityTestBackends(n int, port uint16) []DesiredBackend { + out := make([]DesiredBackend, n) + for i := range out { + out[i] = DesiredBackend{ + Address: netip.MustParseAddr(fmt.Sprintf("fd00:10:1::%x", i+0x20)), + Port: port, + USID: netip.MustParseAddr(fmt.Sprintf("2001:db8:2::%x", i+1)), + } + } + return out +} + +// affinityTestRules returns three services over the same eight backend +// addresses, as the API has a tenant spread them: TCP 443 to backend port +// 8443, TCP 80 to backend port 8080 on another VIP, and UDP 443 to backend +// port 8443 on a third. +func affinityTestRules(affinity string) []DesiredRule { + return []DesiredRule{ + { + Key: "ns/https", Protocol: protocolTCP, Port: 443, Affinity: affinity, + VIPAddresses: []netip.Addr{netip.MustParseAddr("2001:db8:1::10")}, + Backends: affinityTestBackends(8, 8443), + }, + { + Key: "ns/http", Protocol: protocolTCP, Port: 80, Affinity: affinity, + VIPAddresses: []netip.Addr{netip.MustParseAddr("2001:db8:1::11")}, + Backends: affinityTestBackends(8, 8080), + }, + { + Key: "ns/quic", Protocol: protocolUDP, Port: 443, Affinity: affinity, + VIPAddresses: []netip.Addr{netip.MustParseAddr("2001:db8:1::12")}, + Backends: affinityTestBackends(8, 8443), + }, + } +} + +// gatewayNode is one gateway node's programmed vip_table, for predicting the +// backend its datapath picks. +type gatewayNode struct { + t *testing.T + d *KernelDatapath +} + +// newGatewayNode applies rules to a fresh datapath, as each gateway node does +// independently from the same NetworkServices. +func newGatewayNode(t *testing.T, rules []DesiredRule) gatewayNode { + t.Helper() + d := newTestKernelDatapath() + for _, rule := range rules { + if err := d.ApplyRule(context.Background(), rule); err != nil { + t.Fatalf("ApplyRule %s: %v", rule.Key, err) + } + } + return gatewayNode{t: t, d: d} +} + +// pick returns the backend address this node's datapath sends a flow from +// client:sport to, reading the entry's own affinity and Maglev table and +// hashing as edge_lb does. +func (n gatewayNode) pick(rule DesiredRule, client netip.Addr, sport uint16) netip.Addr { + n.t.Helper() + proto, err := protoNumber(rule.Protocol) + if err != nil { + n.t.Fatal(err) + } + key := edgemap.VIPKey{Proto: proto, VPort: rule.Port, VIP: rule.VIPAddresses[0]} + entry, ok, err := n.d.vipTable.Get(key) + if err != nil || !ok { + n.t.Fatalf("Get %+v: ok=%v err=%v", key, ok, err) + } + slot := edgeprog.FlowHash(client.As16(), entry.Affinity, proto, sport) % edgemap.MaglevTableSize + return entry.Backends[entry.MaglevTable[slot]].Addr +} + +// TestAffinity_PinsClientsAsEachModeSays checks each mode's contract over +// 500 clients, IPv6 and IPv4, each opening connections from four random source +// ports to each of three services over one backend set, as seen by two gateway +// nodes that programmed the same services on their own: +// +// - every mode: both nodes pick the same backend for the same flow +// - None: a client's connections spread over backends +// - ClientIP: every connection from one client reaches one backend, across +// ports, services and protocols +// - ClientIPAndProtocol: every connection from one client over one protocol +// reaches one backend, across ports and services +func TestAffinity_PinsClientsAsEachModeSays(t *testing.T) { + const ( + clients = 500 + ports = 4 + ) + for _, mode := range []string{affinityNone, affinityClientIP, affinityClientIPAndProtocol} { + t.Run(mode, func(t *testing.T) { + rules := affinityTestRules(mode) + nodeA, nodeB := newGatewayNode(t, rules), newGatewayNode(t, rules) + r := rand.New(rand.NewPCG(733, 1)) + + var spread int + for c := range clients { + client := randomAddr(r, c%2 == 0) + byProto := map[string]netip.Addr{} + seen := map[netip.Addr]struct{}{} + for _, rule := range rules { + for range ports { + sport := uint16(1024 + r.IntN(65536-1024)) + got := nodeA.pick(rule, client, sport) + if other := nodeB.pick(rule, client, sport); other != got { + t.Fatalf("%s from %s:%d: node A picks %s, node B %s", rule.Key, client, sport, got, other) + } + seen[got] = struct{}{} + + // The connections a mode pins together: all of a + // client's under ClientIP, one protocol's under + // ClientIPAndProtocol. + pin := rule.Protocol + if mode == affinityClientIP { + pin = "" + } + pinned, ok := byProto[pin] + switch { + case mode == affinityNone: + case !ok: + byProto[pin] = got + case got != pinned: + t.Fatalf("%s from %s:%d reaches %s, want %s, the backend its other %s connections reach", + rule.Key, client, sport, got, pinned, mode) + } + } + } + if len(seen) > 1 { + spread++ + } + } + + if mode == affinityNone && spread < clients/2 { + t.Errorf("None: %d of %d clients reached more than one backend over %d connections, want most", + spread, clients, len(rules)*ports) + } + if mode == affinityClientIP && spread != 0 { + t.Errorf("ClientIP: %d clients reached more than one backend, want none", spread) + } + }) + } +} + +// TestAffinity_ClientIPModesKeyTheTableByAddress checks that a client-IP mode +// builds the same Maglev table for services whose backends share addresses but +// not ports, and that None keeps keying by address and port, so the tables of +// rules already running under None do not move. +func TestAffinity_ClientIPModesKeyTheTableByAddress(t *testing.T) { + for _, tt := range []struct { + mode string + same bool + }{ + {affinityNone, false}, + {affinityClientIP, true}, + {affinityClientIPAndProtocol, true}, + } { + t.Run(tt.mode, func(t *testing.T) { + rules := affinityTestRules(tt.mode) + _, https, err := buildMaglevTable(rules[0], rules[0].Backends) + if err != nil { + t.Fatal(err) + } + _, http, err := buildMaglevTable(rules[1], rules[1].Backends) + if err != nil { + t.Fatal(err) + } + if same := https == http; same != tt.same { + t.Errorf("tables over backend ports 8443 and 8080 identical = %v, want %v", same, tt.same) + } + }) + } + + // An unset affinity and None both key the table by address and port, so + // they build the same table. + rule := affinityTestRules("")[0] + _, unset, err := buildMaglevTable(rule, rule.Backends) + if err != nil { + t.Fatal(err) + } + rule.Affinity = affinityNone + _, none, err := buildMaglevTable(rule, rule.Backends) + if err != nil { + t.Fatal(err) + } + if unset != none { + t.Error("an unset affinity and None build different tables") + } +} + +func TestKernelDatapath_ApplyRuleStoresAffinity(t *testing.T) { + for mode, want := range map[string]uint8{ + "": edgeprog.AffinityNone, + affinityNone: edgeprog.AffinityNone, + affinityClientIP: edgeprog.AffinityClientIP, + affinityClientIPAndProtocol: edgeprog.AffinityClientIPAndProtocol, + } { + d := newTestKernelDatapath() + rule := testDesiredRule(t, testKeyA, "2001:db8:1::10") + rule.Affinity = mode + if err := d.ApplyRule(context.Background(), rule); err != nil { + t.Fatalf("ApplyRule(affinity %q): %v", mode, err) + } + entry, ok, err := d.vipTable.Get(edgemap.VIPKey{Proto: 6, VPort: 443, VIP: rule.VIPAddresses[0]}) + if err != nil || !ok { + t.Fatalf("Get: ok=%v err=%v", ok, err) + } + if entry.Affinity != want { + t.Errorf("affinity %q: stored %d, want %d", mode, entry.Affinity, want) + } + } +} + +func TestKernelDatapath_ApplyRuleRejectsUnknownAffinity(t *testing.T) { + d := newTestKernelDatapath() + rule := testDesiredRule(t, testKeyA, "2001:db8:1::10") + rule.Affinity = "ClientIPAndPort" + if err := d.ApplyRule(context.Background(), rule); err == nil { + t.Error("ApplyRule with an unknown affinity: want an error, got nil") + } + if entries, err := d.vipTable.List(); err != nil || len(entries) != 0 { + t.Errorf("vip_table after a refused rule: %d entries, err %v, want none", len(entries), err) + } +} + +// TestKernelDatapath_ApplyRuleRejectsSharedBackendAddressUnderClientIP: a +// client-IP mode keys backends by address, so two backends on one address +// would be one Maglev candidate. The rule is refused rather than merged. +func TestKernelDatapath_ApplyRuleRejectsSharedBackendAddressUnderClientIP(t *testing.T) { + d := newTestKernelDatapath() + rule := testDesiredRule(t, testKeyA, "2001:db8:1::10") + rule.Affinity = affinityClientIP + second := rule.Backends[0] + second.Port++ + rule.Backends = append(rule.Backends, second) + if err := d.ApplyRule(context.Background(), rule); err == nil { + t.Error("ApplyRule with two backends on one address under ClientIP: want an error, got nil") + } +} + +// TestEngine_AffinityChangeReprogramsTheRule: editing only a running rule's +// affinity reprograms its entry on the next reconcile, which every gateway +// node runs on the NetworkService's update, without a restart. +func TestEngine_AffinityChangeReprogramsTheRule(t *testing.T) { + d := newTestKernelDatapath() + e := NewEngine(d, &fakeQuota{}, &fakeTelemetry{}) + ctx := context.Background() + rule := affinityTestRules(affinityNone)[0] + + for _, step := range []struct { + affinity string + want uint8 + }{ + {affinityNone, edgeprog.AffinityNone}, + {affinityClientIP, edgeprog.AffinityClientIP}, + {affinityClientIPAndProtocol, edgeprog.AffinityClientIPAndProtocol}, + {affinityNone, edgeprog.AffinityNone}, + } { + rule.Affinity = step.affinity + if _, err := e.Reconcile(ctx, EngineState{Rules: map[string]DesiredRule{rule.Key: rule}}); err != nil { + t.Fatalf("Reconcile(affinity %q): %v", step.affinity, err) + } + entry, ok, err := d.vipTable.Get(edgemap.VIPKey{Proto: 6, VPort: rule.Port, VIP: rule.VIPAddresses[0]}) + if err != nil || !ok { + t.Fatalf("Get: ok=%v err=%v", ok, err) + } + if entry.Affinity != step.want { + t.Errorf("after setting %q: programmed affinity %d, want %d", step.affinity, entry.Affinity, step.want) + } + } +} diff --git a/internal/gateway/diff.go b/internal/gateway/diff.go index bf9c4e3a9..998ece799 100644 --- a/internal/gateway/diff.go +++ b/internal/gateway/diff.go @@ -44,6 +44,7 @@ func rulesEqual(a, b DesiredRule) bool { a.VPCRef == b.VPCRef && a.Protocol == b.Protocol && a.Port == b.Port && + a.Affinity == b.Affinity && slices.Equal(a.VIPAddresses, b.VIPAddresses) && slices.Equal(a.Backends, b.Backends) && slices.Equal(a.IPv4Backends, b.IPv4Backends) diff --git a/internal/gateway/diff_test.go b/internal/gateway/diff_test.go index 2dab4bf4a..551684ab1 100644 --- a/internal/gateway/diff_test.go +++ b/internal/gateway/diff_test.go @@ -100,6 +100,7 @@ func TestRulesEqual(t *testing.T) { {"port changed", clone(func(r *DesiredRule) { r.Port = 443 }), false}, {"protocol changed", clone(func(r *DesiredRule) { r.Protocol = "" }), false}, {"VPC changed", clone(func(r *DesiredRule) { r.VPCRef = "other" }), false}, + {"affinity changed", clone(func(r *DesiredRule) { r.Affinity = affinityClientIP }), false}, {"IPv4 VIP backend added", clone(func(r *DesiredRule) { r.IPv4Backends = []DesiredBackend{{Address: netip.MustParseAddr("fd20:60::5"), Port: 8080, USID: usidA}} }), false}, diff --git a/internal/gateway/flowhash_test.go b/internal/gateway/flowhash_test.go index d19aa95c6..858353a24 100644 --- a/internal/gateway/flowhash_test.go +++ b/internal/gateway/flowhash_test.go @@ -33,7 +33,7 @@ func TestFlowHash_ConsecutivePortsSpreadAcrossBackends(t *testing.T) { r := rand.New(rand.NewPCG(958, 1)) pick := func(table *[edgemap.MaglevTableSize]byte, addr [16]byte, port uint16) byte { - return table[edgeprog.FlowHash(addr, port)%edgemap.MaglevTableSize] + return table[edgeprog.FlowHash(addr, edgeprog.AffinityNone, 0, port)%edgemap.MaglevTableSize] } oneBackend := func(table *[edgemap.MaglevTableSize]byte, addr [16]byte, port func(int) uint16) bool { first := pick(table, addr, port(0)) diff --git a/internal/gateway/kerneldatapath.go b/internal/gateway/kerneldatapath.go index cdd2e8e69..137571e87 100644 --- a/internal/gateway/kerneldatapath.go +++ b/internal/gateway/kerneldatapath.go @@ -22,15 +22,43 @@ import ( // and this is the one place the two representations meet. func protoNumber(protocol string) (uint8, error) { switch protocol { - case "tcp": + case protocolTCP: return 6, nil - case "udp": + case protocolUDP: return 17, nil default: return 0, fmt.Errorf("kerneldatapath: unsupported protocol %q (want \"tcp\" or \"udp\")", protocol) } } +// affinityNumber maps a rule's affinity string to the edgeprog Affinity value +// vip_table stores, an empty string meaning "None", and rejects anything else. +func affinityNumber(affinity string) (uint8, error) { + switch affinity { + case "", affinityNone: + return edgeprog.AffinityNone, nil + case affinityClientIP: + return edgeprog.AffinityClientIP, nil + case affinityClientIPAndProtocol: + return edgeprog.AffinityClientIPAndProtocol, nil + default: + return 0, fmt.Errorf( + "kerneldatapath: unsupported affinity %q (want \"None\", \"ClientIP\" or \"ClientIPAndProtocol\")", affinity) + } +} + +// addressKeyed is a DesiredBackend whose Maglev key is its address alone. A +// rule with a client-IP affinity builds its table from these, so its table +// depends only on its backends' addresses, and another rule over the same +// addresses, whatever their ports, gets the same table and so pins a client to +// the same backend. +type addressKeyed struct{ DesiredBackend } + +// Key implements maglev.Backend. +func (b addressKeyed) Key() string { + return b.Address.String() +} + // vipKeysForRule returns the vip_table keys ApplyRule registers for rule, one // per VIP address, the map being keyed by protocol, port, and address with the // backend list and Maglev table identical across every VIP of one family a @@ -54,7 +82,9 @@ func vipKeysForRule(rule DesiredRule) ([]edgemap.VIPKey, error) { // 1. Reject up front when the backend count exceeds the cap. The CRD already // bounds it, but a silently truncated array is worse than a clear error. // 2. Build a Maglev table over the backends, each of which supplies its own -// key. +// key: its address and port, or under a client-IP affinity its address +// alone (see addressKeyed). The latter refuses two backends sharing an +// address. // 3. The table returns its backend set sorted by key, and that order becomes // each backend's index into the returned slice, and so into the map value's // fixed-size array. @@ -69,9 +99,17 @@ func buildMaglevTable(rule DesiredRule, in []DesiredBackend) ([]edgemap.Backend, rule.Key, len(in), edgemap.MaxBackends) } + affinity, err := affinityNumber(rule.Affinity) + if err != nil { + return nil, maglevTable, fmt.Errorf("kerneldatapath: rule %s: %w", rule.Key, err) + } candidates := make([]maglev.Backend, len(in)) for i, b := range in { - candidates[i] = b + if affinity == edgeprog.AffinityNone { + candidates[i] = b + } else { + candidates[i] = addressKeyed{b} + } } table, err := maglev.New(candidates, edgemap.MaglevTableSize) @@ -83,7 +121,13 @@ func buildMaglevTable(rule DesiredRule, in []DesiredBackend) ([]edgemap.Backend, backends := make([]edgemap.Backend, len(sorted)) indexByKey := make(map[string]int, len(sorted)) for i, b := range sorted { - db := b.(DesiredBackend) // every candidate above was built from a DesiredBackend + var db DesiredBackend + switch c := b.(type) { // every candidate above is one of these + case DesiredBackend: + db = c + case addressKeyed: + db = c.DesiredBackend + } backends[i] = edgemap.Backend{Addr: db.Address, Port: db.Port, USID: db.USID} indexByKey[b.Key()] = i } @@ -156,6 +200,10 @@ func (d *KernelDatapath) ApplyRule(_ context.Context, rule DesiredRule) error { if err != nil { return err } + affinity, err := affinityNumber(rule.Affinity) + if err != nil { + return fmt.Errorf("kerneldatapath: rule %s: %w", rule.Key, err) + } type family struct { backends []edgemap.Backend @@ -182,7 +230,7 @@ func (d *KernelDatapath) ApplyRule(_ context.Context, rule DesiredRule) error { for i, key := range keys { f := families[key.VIP.Is4()] - if err := d.vipTable.Register(key, f.backends, f.table); err != nil { + if err := d.vipTable.Register(key, affinity, f.backends, f.table); err != nil { // Record the keys that did land, alongside the ones this rule // already owned, the prune below not having run yet, so // RemoveRule can still find every live entry. diff --git a/internal/gateway/types.go b/internal/gateway/types.go index 89273ac7d..fb4f159a2 100644 --- a/internal/gateway/types.go +++ b/internal/gateway/types.go @@ -9,6 +9,17 @@ import ( "net/netip" ) +// DesiredRule.Protocol and DesiredRule.Affinity values, the CRD's enum +// strings. +const ( + protocolTCP = "tcp" + protocolUDP = "udp" + + affinityNone = "None" + affinityClientIP = "ClientIP" + affinityClientIPAndProtocol = "ClientIPAndProtocol" +) + // DesiredBackend is one backend endpoint a rule load-balances to. It mirrors // the CRD's backend plus one field the CRD does not carry: the SRv6 uSID of the // worker node the backend is reachable through. The controller resolves that @@ -52,6 +63,14 @@ type DesiredRule struct { Protocol string Port uint16 + // Affinity is "None", "ClientIP" or "ClientIPAndProtocol", matching + // galactic.datumapis.com/v1alpha1's NetworkServiceSessionAffinity enum + // values; empty means "None". It selects what the datapath hashes besides + // the client's address, and under either client-IP mode keys the Maglev + // table by backend address alone, so services over the same backend + // addresses pin a client to the same one. + Affinity string + // Backends serve the rule's IPv6 VIPs and IPv4Backends its IPv4 VIPs. Both // are IPv6 backends, the IPv4 VIPs' reached by translation on their nodes, // and usually the same ones; they differ only where another rule owns a diff --git a/internal/plumbing/ebpf/edgeattach/attach_test.go b/internal/plumbing/ebpf/edgeattach/attach_test.go index c165bac4d..f96ec39a9 100644 --- a/internal/plumbing/ebpf/edgeattach/attach_test.go +++ b/internal/plumbing/ebpf/edgeattach/attach_test.go @@ -591,3 +591,55 @@ func TestLoad_UpgradeReplacesOnlyTheGrownDropReasons(t *testing.T) { t.Errorf("vip_table row after the upgrade = %+v, %v; want it kept", got, err) } } + +// TestLoad_KeepsPinnedVipTableWithZeroedAffinity: vip_value's affinity byte +// sits in the alignment gap before generation, so a pinned vip_table of +// 3216-byte values with that gap zeroed stays compatible. Load keeps it and +// every row, which reads as AffinityNone. +func TestLoad_KeepsPinnedVipTableWithZeroedAffinity(t *testing.T) { + requireRoot(t) + const previousValueSize = 3216 + pinDir := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-edge-test-affinity-%d", os.Getpid())) + if err := os.MkdirAll(pinDir, 0o755); err != nil { + t.Skipf("bpffs not writable at /sys/fs/bpf: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + + spec, err := edgeprog.LoadEdgedsr() + if err != nil { + t.Fatalf("LoadEdgedsr: %v", err) + } + oldSpec := spec.Maps["vip_table"].Copy() + oldSpec.ValueSize = previousValueSize + oldSpec.Key, oldSpec.Value = nil, nil + oldSpec.Pinning = ebpf.PinNone + old, err := ebpf.NewMap(oldSpec) + if err != nil { + t.Fatalf("create previous vip_table: %v", err) + } + key := edgeprog.EdgedsrVipKey{Proto: 6, Port: 0xbb01, Vip: netip.MustParseAddr("2001:db8::100").As16()} + row := make([]byte, previousValueSize) + row[0] = 1 // backend_count, little-endian + row[previousValueSize-8] = 9 // generation, little-endian + if err := old.Put(key, row); err != nil { + t.Fatalf("write previous vip_table row: %v", err) + } + if err := old.Pin(filepath.Join(pinDir, "vip_table")); err != nil { + t.Fatalf("pin previous vip_table: %v", err) + } + _ = old.Close() + + objs, err := Load(pinDir, nil) + if err != nil { + t.Fatalf("Load over the previous vip_table: %v", err) + } + t.Cleanup(func() { _ = objs.Close() }) + var got edgeprog.EdgedsrVipValue + if err := objs.VipTable.Lookup(key, &got); err != nil { + t.Fatalf("vip_table row after the upgrade: %v; want it kept", err) + } + if got.BackendCount != 1 || got.Generation != 9 || got.Affinity != edgeprog.AffinityNone { + t.Errorf("vip_table row after the upgrade = count %d, generation %d, affinity %d; want 1, 9, %d", + got.BackendCount, got.Generation, got.Affinity, edgeprog.AffinityNone) + } +} diff --git a/internal/plumbing/ebpf/edgemap/viptable.go b/internal/plumbing/ebpf/edgemap/viptable.go index cb3a0bed8..cfc516876 100644 --- a/internal/plumbing/ebpf/edgemap/viptable.go +++ b/internal/plumbing/ebpf/edgemap/viptable.go @@ -71,6 +71,9 @@ type VIPEntry struct { // builder returns them. A caller reading it back must not mutate it. MaglevTable [MaglevTableSize]byte + // Affinity is the edgeprog Affinity value this entry was registered with. + Affinity uint8 + // Generation is this table's monotonic-clock reading when Register last // wrote this entry. See the package doc comment. Generation uint64 @@ -197,15 +200,21 @@ func toWireBackends(backends []Backend) ([MaxBackends]edgeprog.EdgedsrBackend, e } // Register writes, or overwrites, the vip_table entry for key, mapping it to -// backends and maglevTable and stamping it with the current generation. Each -// slot of maglevTable must be an index into backends, in the same order. -// Rejects an empty or over-capacity backend list before writing. +// backends and maglevTable under affinity, one of edgeprog's Affinity values, +// and stamping it with the current generation. Each slot of maglevTable must be +// an index into backends, in the same order. Rejects an unknown affinity and an +// empty or over-capacity backend list before writing. // // A blind overwrite rather than a read-modify-write, because it never touches // the statistics map and so has nothing to race against the datapath's // per-packet increments. Keeping the counters in a map this method has no // reason to read closes that race rather than narrowing it. -func (t *VIPTable) Register(key VIPKey, backends []Backend, maglevTable [MaglevTableSize]byte) error { +func (t *VIPTable) Register(key VIPKey, affinity uint8, backends []Backend, maglevTable [MaglevTableSize]byte) error { + switch affinity { + case edgeprog.AffinityNone, edgeprog.AffinityClientIP, edgeprog.AffinityClientIPAndProtocol: + default: + return fmt.Errorf("edgemap: vip_table: register %+v: unknown affinity %d", key, affinity) + } if len(backends) == 0 { return fmt.Errorf("edgemap: vip_table: register %+v: at least one backend is required", key) } @@ -227,6 +236,7 @@ func (t *VIPTable) Register(key VIPKey, backends []Backend, maglevTable [MaglevT BackendCount: uint32(len(backends)), Backends: wireBackends, MaglevTable: maglevTable, + Affinity: affinity, Generation: t.clock(), } if err := t.table.Put(wireKey, value); err != nil { @@ -428,6 +438,7 @@ func fromWireValue(key VIPKey, value edgeprog.EdgedsrVipValue, stats edgeprog.Ed VIPKey: key, Backends: backends, MaglevTable: value.MaglevTable, + Affinity: value.Affinity, Generation: value.Generation, Packets: stats.Packets, Bytes: stats.Bytes, diff --git a/internal/plumbing/ebpf/edgemap/viptable_test.go b/internal/plumbing/ebpf/edgemap/viptable_test.go index df01c33a4..18792cc11 100644 --- a/internal/plumbing/ebpf/edgemap/viptable_test.go +++ b/internal/plumbing/ebpf/edgemap/viptable_test.go @@ -139,7 +139,7 @@ func TestVIPTable_RegisterGetRoundTrip(t *testing.T) { vt := newTestVIPTable() key, backend := testKey(t), testBackend(t) - if err := vt.Register(key, []Backend{backend}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{backend}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -163,7 +163,7 @@ func TestVIPTable_RegisterStoresMaglevTable(t *testing.T) { maglevTable[0] = 5 maglevTable[1020] = 9 - if err := vt.Register(key, []Backend{backend}, maglevTable); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{backend}, maglevTable); err != nil { t.Fatalf("Register: %v", err) } @@ -176,9 +176,38 @@ func TestVIPTable_RegisterStoresMaglevTable(t *testing.T) { } } +func TestVIPTable_RegisterStoresAffinity(t *testing.T) { + vt := newTestVIPTable() + key, backend := testKey(t), testBackend(t) + + affinities := []uint8{edgeprog.AffinityClientIP, edgeprog.AffinityClientIPAndProtocol, edgeprog.AffinityNone} + for _, affinity := range affinities { + if err := vt.Register(key, affinity, []Backend{backend}, [MaglevTableSize]byte{}); err != nil { + t.Fatalf("Register(affinity %d): %v", affinity, err) + } + got, ok, err := vt.Get(key) + if err != nil || !ok { + t.Fatalf("Get: ok=%v err=%v", ok, err) + } + if got.Affinity != affinity { + t.Errorf("Get: Affinity = %d, want %d", got.Affinity, affinity) + } + } +} + +func TestVIPTable_RegisterRejectsUnknownAffinity(t *testing.T) { + vt := newTestVIPTable() + if err := vt.Register(testKey(t), 3, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err == nil { + t.Error("Register with affinity 3: want error, got nil") + } + if _, ok, err := vt.Get(testKey(t)); err != nil || ok { + t.Errorf("Get after a refused Register: ok=%v err=%v, want no entry", ok, err) + } +} + func TestVIPTable_RegisterRejectsEmptyBackends(t *testing.T) { vt := newTestVIPTable() - if err := vt.Register(testKey(t), nil, [MaglevTableSize]byte{}); err == nil { + if err := vt.Register(testKey(t), edgeprog.AffinityNone, nil, [MaglevTableSize]byte{}); err == nil { t.Error("Register with no backends: want error, got nil") } } @@ -189,7 +218,7 @@ func TestVIPTable_RegisterRejectsTooManyBackends(t *testing.T) { for i := range backends { backends[i] = testBackend(t) } - if err := vt.Register(testKey(t), backends, [MaglevTableSize]byte{}); err == nil { + if err := vt.Register(testKey(t), edgeprog.AffinityNone, backends, [MaglevTableSize]byte{}); err == nil { t.Error("Register with MaxBackends+1 backends: want error, got nil") } } @@ -200,12 +229,12 @@ func TestVIPTable_RegisterRejectsIPv4MappedAddresses(t *testing.T) { backend := testBackend(t) backend.Addr = mapped - if err := vt.Register(testKey(t), []Backend{backend}, [MaglevTableSize]byte{}); err == nil { + if err := vt.Register(testKey(t), edgeprog.AffinityNone, []Backend{backend}, [MaglevTableSize]byte{}); err == nil { t.Error("Register with an IPv4-mapped backend address: want error, got nil") } key := testKey(t) key.VIP = mapped - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err == nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err == nil { t.Error("Register with an IPv4-mapped VIP: want error, got nil") } } @@ -220,7 +249,7 @@ func TestVIPTable_IPv4RoundTrip(t *testing.T) { backend := testBackend(t) backend.Addr = mustAddr(t, "10.60.0.5") - if err := vt.Register(key, []Backend{backend}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{backend}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -252,7 +281,7 @@ func TestVIPTable_IPv4AndIPv6RowsDoNotCollide(t *testing.T) { vt := newTestVIPTable() v6, v4 := testKey(t), VIPKey{Proto: 6, VPort: 443, VIP: mustAddr(t, "192.0.2.10")} for _, k := range []VIPKey{v6, v4} { - if err := vt.Register(k, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(k, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register %s: %v", k.VIP, err) } } @@ -278,7 +307,7 @@ func TestVIPTable_UnregisterIsIdempotent(t *testing.T) { if err := vt.Unregister(key); err != nil { t.Fatalf("Unregister on an absent key: %v, want nil", err) } - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } if err := vt.Unregister(key); err != nil { @@ -308,10 +337,10 @@ func TestVIPTable_List(t *testing.T) { key1 := testKey(t) key2 := VIPKey{Proto: 17, VPort: 53, VIP: mustAddr(t, "2001:db8:1::11")} - if err := vt.Register(key1, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key1, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register key1: %v", err) } - if err := vt.Register(key2, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key2, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register key2: %v", err) } @@ -333,10 +362,11 @@ func TestVIPTable_ReconcileRemovesStaleNotLive(t *testing.T) { staleKey := VIPKey{Proto: 17, VPort: 53, VIP: mustAddr(t, "2001:db8:1::11")} fakeClock = 100 - if err := vt.Register(liveKey, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(liveKey, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register liveKey: %v", err) } - if err := vt.Register(staleKey, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(staleKey, edgeprog.AffinityNone, + []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register staleKey: %v", err) } @@ -378,7 +408,8 @@ func TestVIPTable_ReconcileSparesRecentGeneration(t *testing.T) { fakeClock = 50 // written AFTER the cutoff snapshot was taken recentKey := testKey(t) - if err := vt.Register(recentKey, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(recentKey, edgeprog.AffinityNone, + []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -400,10 +431,10 @@ func TestVIPTable_RegisterOverwritesExistingKey(t *testing.T) { b1 := testBackend(t) b2 := Backend{Addr: mustAddr(t, "fd00:10:1::99"), Port: 9999, USID: mustAddr(t, "2001:db8:2::2")} - if err := vt.Register(key, []Backend{b1}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{b1}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("first Register: %v", err) } - if err := vt.Register(key, []Backend{b2}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{b2}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("second Register: %v", err) } @@ -428,7 +459,7 @@ func TestVIPTable_RegisterPreservesHitCounters(t *testing.T) { vt := NewVIPTable(newFakeTable(), statsTable, newFakeAddrTable(), newFakeReturnStatsTable()) key := testKey(t) - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("first Register: %v", err) } @@ -450,7 +481,7 @@ func TestVIPTable_RegisterPreservesHitCounters(t *testing.T) { // Re-register with a different backend, exactly as a later // convergence pass would (e.g. a backend Pod rescheduled). b2 := Backend{Addr: mustAddr(t, "fd00:10:1::99"), Port: 9999, USID: mustAddr(t, "2001:db8:2::2")} - if err := vt.Register(key, []Backend{b2}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{b2}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("second Register: %v", err) } @@ -487,11 +518,11 @@ func TestVIPTable_RegisterNeverTouchesStatsTable(t *testing.T) { vt := NewVIPTable(newFakeTable(), statsTable, newFakeAddrTable(), newFakeReturnStatsTable()) key := testKey(t) - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("first Register: %v", err) } b2 := Backend{Addr: mustAddr(t, "fd00:10:1::99"), Port: 9999, USID: mustAddr(t, "2001:db8:2::2")} - if err := vt.Register(key, []Backend{b2}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{b2}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("second Register (re-registration): %v", err) } @@ -513,7 +544,7 @@ func TestVIPTable_UnregisterDeletesStatsRow(t *testing.T) { vt := NewVIPTable(newFakeTable(), statsTable, newFakeAddrTable(), newFakeReturnStatsTable()) key := testKey(t) - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } wireKey, err := toWireKey(key) @@ -540,7 +571,7 @@ func TestVIPTable_RegisterOnFreshKeyStartsCountersAtZero(t *testing.T) { vt := newTestVIPTable() key := testKey(t) - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -579,7 +610,7 @@ func TestVIPTable_RegisterClaimsTheVIPAddress(t *testing.T) { vt := NewVIPTable(newFakeTable(), newFakeStatsTable(), addrs, newFakeReturnStatsTable()) key := testKey(t) - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -608,7 +639,7 @@ func TestVIPTable_UnregisterKeepsAnAddressAnotherRuleStillUses(t *testing.T) { https := VIPKey{Proto: 6, VPort: 443, VIP: vip} http := VIPKey{Proto: 6, VPort: 80, VIP: vip} for _, key := range []VIPKey{https, http} { - if err := vt.Register(key, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register %+v: %v", key, err) } } @@ -699,7 +730,8 @@ func TestVIPTable_ReplaceReturnAddrs(t *testing.T) { vt := NewVIPTable(newFakeTable(), stats, addrs, returnStats) served := testKey(t) - if err := vt.Register(served, []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { + if err := vt.Register(served, edgeprog.AffinityNone, + []Backend{testBackend(t)}, [MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } wireKey, err := toWireKey(served) diff --git a/internal/plumbing/ebpf/edgemetrics/collector_test.go b/internal/plumbing/ebpf/edgemetrics/collector_test.go index bb15723fc..0a874537a 100644 --- a/internal/plumbing/ebpf/edgemetrics/collector_test.go +++ b/internal/plumbing/ebpf/edgemetrics/collector_test.go @@ -327,7 +327,8 @@ func TestCollector_CollectsRuleCounters(t *testing.T) { Port: 8443, USID: mustAddr(t, "2001:db8:2::1"), } - if err := vt.Register(key, []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, + []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -385,7 +386,7 @@ func TestCollector_OmitsSecondsSinceLastPacketWhenNeverSeen(t *testing.T) { table := newFakeVIPTable() vt := edgemap.NewVIPTable(table, newFakeStatsTable(), newFakeAddrTable(), newFakeReturnStatsTable()) key := edgemap.VIPKey{Proto: 6, VPort: 443, VIP: mustAddr(t, "2001:db8:1::10")} - if err := vt.Register(key, []edgemap.Backend{{ + if err := vt.Register(key, edgeprog.AffinityNone, []edgemap.Backend{{ Addr: mustAddr(t, "fd00:10:1::20"), Port: 8443, USID: mustAddr(t, "2001:db8:2::1"), }}, [edgemap.MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) @@ -453,7 +454,8 @@ func TestCollector_CollectsReturnCounters(t *testing.T) { Port: 80, USID: mustAddr(t, "2001:db8:ff01:1:e003::"), } - if err := vt.Register(key, []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, + []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } @@ -515,7 +517,8 @@ func TestCollector_LabelsSeriesWithOwningVPC(t *testing.T) { Addr: mustAddr(t, "fd00:10:1::20"), Port: 8443, USID: mustAddr(t, "2001:db8:2::1"), } for _, key := range []edgemap.VIPKey{owned, unowned} { - if err := vt.Register(key, []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, + []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { t.Fatalf("Register(%+v): %v", key, err) } } @@ -563,7 +566,8 @@ func TestCollector_SharedAddressKeepsRuleVPCs(t *testing.T) { Addr: mustAddr(t, "fd00:10:1::20"), Port: 8443, USID: mustAddr(t, "2001:db8:2::1"), } for _, key := range []edgemap.VIPKey{https, dns} { - if err := vt.Register(key, []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, + []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { t.Fatalf("Register(%+v): %v", key, err) } } @@ -592,7 +596,8 @@ func TestCollector_LabelsIPv4VIPsPlainly(t *testing.T) { vt := edgemap.NewVIPTable(table, newFakeStatsTable(), newFakeAddrTable(), newFakeReturnStatsTable()) key := edgemap.VIPKey{Proto: 17, VPort: 53, VIP: mustAddr(t, "192.0.2.10")} backend := edgemap.Backend{Addr: mustAddr(t, "10.60.0.5"), Port: 5353, USID: mustAddr(t, "2001:db8:2::1")} - if err := vt.Register(key, []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { + if err := vt.Register(key, edgeprog.AffinityNone, + []edgemap.Backend{backend}, [edgemap.MaglevTableSize]byte{}); err != nil { t.Fatalf("Register: %v", err) } diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr.c b/internal/plumbing/ebpf/edgeprog/edgedsr.c index bdf41c332..f0b9de689 100644 --- a/internal/plumbing/ebpf/edgeprog/edgedsr.c +++ b/internal/plumbing/ebpf/edgeprog/edgedsr.c @@ -45,7 +45,8 @@ // row on first match. Stats live in their own map so a control-plane // read-modify-write can never race these per-packet increments. // 5. An empty backend list is a counted drop. Otherwise hash the client's -// address and port and index the precomputed Maglev table to get a backend. +// address, with its port or protocol as the rule's affinity selects, and +// index the precomputed Maglev table to get a backend. // Every gateway node computes the same index for the same flow from the // same inputs, which is what makes this safe under anycast: a flow landing // on a different node mid-connection still resolves to the same backend. @@ -168,6 +169,13 @@ static long (*bpf_redirect)(__u32 ifindex, __u64 flags) = (void *) BPF_FUNC_redi // a deployment's measured disruption on backend-set changes needs tighter. #define EDGE_MAGLEV_TABLE_SIZE 1021 +// EDGE_AFFINITY_* are vip_value.affinity's values, selecting what flow_hash +// hashes besides the client's address. Zero is the default, so a value whose +// affinity byte the control plane left zero hashes by address and port. +#define EDGE_AFFINITY_NONE 0 // address and source port +#define EDGE_AFFINITY_CLIENT_IP 1 // address only +#define EDGE_AFFINITY_CLIENT_IP_PROTO 2 // address and L4 protocol + // --------------------------------------------------------------------- // Minimal, self-contained header structs, byte-exact to the wire formats, with // one external header dependency. @@ -235,7 +243,11 @@ struct vip_key { // struct vip_value is vip_table's value: the backend set for one VIP, port, and // protocol, plus a precomputed Maglev table mapping each slot to an index into -// backends. generation is a monotonic reading stamped by the control plane on +// backends, and the session affinity that selects flow_hash's inputs (one of +// EDGE_AFFINITY_*). affinity sits in the alignment gap before generation and +// adds nothing to the value's size. Keep it there: a size change makes every +// pinned vip_table incompatible, and edgeattach recreates it empty. +// generation is a monotonic reading stamped by the control plane on // every registration, backing the crash-safe reconcile cutoff, and is never // read here. // @@ -245,6 +257,7 @@ struct vip_value { __u32 backend_count; struct backend backends[EDGE_MAX_BACKENDS]; __u8 maglev_table[EDGE_MAGLEV_TABLE_SIZE]; + __u8 affinity; __u64 generation; }; @@ -477,25 +490,34 @@ static EDGE_ALWAYS_INLINE void count_match(struct vip_stats_value *stats, __u64 // backend count, which is what makes a backend-set change reassign roughly one // flow in N instead of nearly all of them. // -// It is 32-bit FNV-1a over the 16 address bytes and the port's two bytes in -// wire order, so bpfel and bpfeb builds agree, then murmur3's fmix32 -// finalizer. +// It is 32-bit FNV-1a over the 16 address bytes, then, by affinity, the port's +// two bytes in wire order (EDGE_AFFINITY_NONE), nothing (CLIENT_IP) or the L4 +// protocol number (CLIENT_IP_PROTO), then murmur3's fmix32 finalizer. Wire +// order keeps bpfel and bpfeb builds in agreement. An affinity value this +// program does not know hashes as EDGE_AFFINITY_NONE; the control plane never +// writes one. // // Every gateway node must run this same hash: a flow that changes gateway // keeps its backend only if both nodes hash it alike. FlowHash in flowhash.go // mirrors it and must change with it. -static EDGE_ALWAYS_INLINE __u32 flow_hash(const __u8 addr[16], __be16 port) +static EDGE_ALWAYS_INLINE __u32 flow_hash(const __u8 addr[16], __u8 affinity, __u8 proto, + __be16 port) { __u32 h = 2166136261u; for (int i = 0; i < 16; i++) { h ^= addr[i]; h *= 16777619u; } - const __u8 *p = (const __u8 *) &port; - h ^= p[0]; - h *= 16777619u; - h ^= p[1]; - h *= 16777619u; + if (affinity == EDGE_AFFINITY_CLIENT_IP_PROTO) { + h ^= proto; + h *= 16777619u; + } else if (affinity != EDGE_AFFINITY_CLIENT_IP) { + const __u8 *p = (const __u8 *) &port; + h ^= p[0]; + h *= 16777619u; + h ^= p[1]; + h *= 16777619u; + } h ^= h >> 16; h *= 0x85ebca6bu; @@ -881,8 +903,8 @@ static EDGE_ALWAYS_INLINE int send_frag_needed4(struct xdp_md *ctx, __u32 mtu) // the packet for size, for the caller to answer. static EDGE_ALWAYS_INLINE int lb_forward(struct xdp_md *ctx, struct vip_value *rule, struct vip_stats_value *stats, const __u8 client[16], - __be16 sport, __be16 outer_payload_len, __u8 nexthdr, - __u16 *frag_mtu) + __u8 proto, __be16 sport, __be16 outer_payload_len, + __u8 nexthdr, __u16 *frag_mtu) { if (rule->backend_count == 0) { count_claimed_drop(DROP_REASON_EMPTY_BACKEND_LIST, stats); @@ -896,7 +918,7 @@ static EDGE_ALWAYS_INLINE int lb_forward(struct xdp_md *ctx, struct vip_value *r // rejected as unbounded without help. The same barrier-then-clamp technique // the backend index needs is applied here, as an explicit range clamp // rather than a mask, since no bitmask bounds a prime. - __u32 slot = flow_hash(client, sport) % EDGE_MAGLEV_TABLE_SIZE; + __u32 slot = flow_hash(client, rule->affinity, proto, sport) % EDGE_MAGLEV_TABLE_SIZE; EDGE_BARRIER_VAR(slot); if (slot >= EDGE_MAGLEV_TABLE_SIZE) slot = EDGE_MAGLEV_TABLE_SIZE - 1; @@ -970,7 +992,7 @@ static EDGE_ALWAYS_INLINE int edge_lb_v6(struct xdp_md *ctx, struct edge_ethhdr __builtin_bswap16((__u16) sizeof(struct edge_ip6hdr) + __builtin_bswap16(ip6->payload_len)); __u16 frag_mtu = 0; - int verdict = lb_forward(ctx, rule, stats, ip6->saddr, ports->source, outer_payload_len, + int verdict = lb_forward(ctx, rule, stats, ip6->saddr, vk.proto, ports->source, outer_payload_len, EDGE_IPPROTO_IPV6, &frag_mtu); if (verdict >= 0) return verdict; @@ -1061,7 +1083,7 @@ static EDGE_ALWAYS_INLINE int edge_lb_v4(struct xdp_md *ctx, struct edge_ethhdr } __u16 frag_mtu = 0; - int verdict = lb_forward(ctx, rule, stats, client, sport, __builtin_bswap16((__u16) tot_len), + int verdict = lb_forward(ctx, rule, stats, client, vk.proto, sport, __builtin_bswap16((__u16) tot_len), EDGE_IPPROTO_IPIP, &frag_mtu); if (verdict >= 0) return verdict; diff --git a/internal/plumbing/ebpf/edgeprog/flowhash.go b/internal/plumbing/ebpf/edgeprog/flowhash.go index 54f6207dd..495a57f4e 100644 --- a/internal/plumbing/ebpf/edgeprog/flowhash.go +++ b/internal/plumbing/ebpf/edgeprog/flowhash.go @@ -4,15 +4,31 @@ package edgeprog +// Affinity values mirror the datapath's EDGE_AFFINITY_* defines, hand-kept in +// sync since a C define has no BTF representation to generate a constant +// from. They are vip_value's affinity byte, and select what FlowHash hashes +// besides the client's address. +const ( + // AffinityNone hashes the client's address and source port. + AffinityNone uint8 = 0 + // AffinityClientIP hashes the client's address only. + AffinityClientIP uint8 = 1 + // AffinityClientIPAndProtocol hashes the client's address and L4 protocol. + AffinityClientIPAndProtocol uint8 = 2 +) + // FlowHash mirrors the datapath's flow_hash, hand-kept in sync with the C // source: the hash edge_lb takes modulo the Maglev table size to pick a // client's slot. addr is the client's address in its 16-byte form, an IPv4 -// address IPv4-mapped, and port is the client's source port. It exists so a -// test or tool can predict the backend a gateway picks for a flow. +// address IPv4-mapped, affinity is the rule's Affinity value, proto the L4 +// protocol number and port the client's source port. Only the inputs affinity +// selects are hashed; an unknown affinity hashes as AffinityNone. It exists so +// a test or tool can predict the backend a gateway picks for a flow. // -// It is 32-bit FNV-1a over addr and port in network byte order, then -// murmur3's fmix32 finalizer. -func FlowHash(addr [16]byte, port uint16) uint32 { +// It is 32-bit FNV-1a over addr, then the port in network byte order +// (AffinityNone), nothing (AffinityClientIP) or proto +// (AffinityClientIPAndProtocol), then murmur3's fmix32 finalizer. +func FlowHash(addr [16]byte, affinity, proto uint8, port uint16) uint32 { const ( fnvOffset = 2166136261 fnvPrime = 16777619 @@ -22,10 +38,17 @@ func FlowHash(addr [16]byte, port uint16) uint32 { h ^= uint32(b) h *= fnvPrime } - h ^= uint32(port >> 8) - h *= fnvPrime - h ^= uint32(port & 0xff) - h *= fnvPrime + switch affinity { + case AffinityClientIP: + case AffinityClientIPAndProtocol: + h ^= uint32(proto) + h *= fnvPrime + default: + h ^= uint32(port >> 8) + h *= fnvPrime + h ^= uint32(port & 0xff) + h *= fnvPrime + } h ^= h >> 16 h *= 0x85ebca6b diff --git a/internal/plumbing/ebpf/edgeprog/flowhash_test.go b/internal/plumbing/ebpf/edgeprog/flowhash_test.go index 894d37dae..39a361185 100644 --- a/internal/plumbing/ebpf/edgeprog/flowhash_test.go +++ b/internal/plumbing/ebpf/edgeprog/flowhash_test.go @@ -10,25 +10,45 @@ import ( "testing" ) -// TestFlowHash_KnownValues pins FlowHash to fixed outputs, so a change to the -// hash on either side fails without root. TestEdgeLB_PicksTheSlotFlowHashPredicts -// ties these values to the loaded program, and they were also checked against -// an independent implementation of FNV-1a and fmix32. +// TestFlowHash_KnownValues pins FlowHash to fixed outputs for each affinity, +// so a change to the hash on either side fails without root. +// TestEdgeLB_PicksTheSlotFlowHashPredicts ties these values to the loaded +// program, and they were also checked against an independent implementation of +// FNV-1a and fmix32. Under AffinityClientIP the protocol and port change +// nothing, and under AffinityClientIPAndProtocol the port changes nothing. func TestFlowHash_KnownValues(t *testing.T) { + const ( + client6 = "2001:db8:ffff::1" + client4 = "::ffff:198.51.100.7" + ) tests := []struct { - addr string - port uint16 - want uint32 + addr string + affinity uint8 + proto uint8 + port uint16 + want uint32 }{ - {"::", 0, 0x3c2b6e16}, - {"2001:db8:ffff::1", 40000, 0xf88dae54}, - {"2001:db8:ffff::1", 40001, 0xca4d8f14}, - {"::ffff:198.51.100.7", 40000, 0x5e88eb3a}, - {"::ffff:198.51.100.7", 65535, 0x4711f2c7}, + {"::", AffinityNone, 0, 0, 0x3c2b6e16}, + {client6, AffinityNone, ipprotoTCP, 40000, 0xf88dae54}, + {client6, AffinityNone, ipprotoUDP, 40000, 0xf88dae54}, + {client6, AffinityNone, ipprotoTCP, 40001, 0xca4d8f14}, + {client4, AffinityNone, ipprotoTCP, 40000, 0x5e88eb3a}, + {client4, AffinityNone, ipprotoTCP, 65535, 0x4711f2c7}, + {client6, AffinityClientIP, ipprotoTCP, 40000, 0x546a4eb1}, + {client6, AffinityClientIP, ipprotoUDP, 1, 0x546a4eb1}, + {client4, AffinityClientIP, ipprotoTCP, 40000, 0xd6aa8729}, + {client6, AffinityClientIPAndProtocol, ipprotoTCP, 40000, 0xf4e8b80c}, + {client6, AffinityClientIPAndProtocol, ipprotoTCP, 1, 0xf4e8b80c}, + {client6, AffinityClientIPAndProtocol, ipprotoUDP, 40000, 0x440e8af6}, + {client4, AffinityClientIPAndProtocol, ipprotoTCP, 1, 0xc5c414dc}, + // An affinity the datapath does not know hashes as AffinityNone. + {client6, 7, ipprotoTCP, 40000, 0xf88dae54}, } for _, tt := range tests { - if got := FlowHash(netip.MustParseAddr(tt.addr).As16(), tt.port); got != tt.want { - t.Errorf("FlowHash(%s, %d) = %#08x, want %#08x", tt.addr, tt.port, got, tt.want) + got := FlowHash(netip.MustParseAddr(tt.addr).As16(), tt.affinity, tt.proto, tt.port) + if got != tt.want { + t.Errorf("FlowHash(%s, affinity %d, proto %d, port %d) = %#08x, want %#08x", + tt.addr, tt.affinity, tt.proto, tt.port, got, tt.want) } } } @@ -37,8 +57,8 @@ func TestFlowHash_KnownValues(t *testing.T) { // program. The VIP holds the most backends a rule can, and slot i of its table // names backend i mod that count, so the backend edge_lb encapsulates toward // gives away the slot it picked modulo that count. Every flow must match -// FlowHash's prediction, for an IPv6 and an IPv4 client over 64 consecutive -// source ports. +// FlowHash's prediction under each affinity, for an IPv6 and an IPv4 client +// over TCP and UDP and 64 consecutive source ports. func TestEdgeLB_PicksTheSlotFlowHashPredicts(t *testing.T) { requireRoot(t) objs := loadObjects(t) @@ -52,38 +72,57 @@ func TestEdgeLB_PicksTheSlotFlowHashPredicts(t *testing.T) { usids[i] = netip.MustParseAddr(fmt.Sprintf("fc00:1:%x::1", i+1)) } vip6 := netip.MustParseAddr("2001:db8::100") - putIPv4VIP(t, objs, ipprotoTCP, 443, vip6, usids...) - putIPv4VIP(t, objs, ipprotoTCP, 443, testVIP4, usids...) + keys := []EdgedsrVipKey{ + putIPv4VIP(t, objs, ipprotoTCP, 443, vip6, usids...), + putIPv4VIP(t, objs, ipprotoTCP, 443, testVIP4, usids...), + putIPv4VIP(t, objs, ipprotoUDP, 443, vip6, usids...), + putIPv4VIP(t, objs, ipprotoUDP, 443, testVIP4, usids...), + } tests := []struct { name string + proto uint8 vip netip.Addr client netip.Addr }{ - {"IPv6 client", vip6, netip.MustParseAddr("2001:db8:ffff::1")}, - {"IPv4 client", testVIP4, testClient4}, + {"IPv6 TCP client", ipprotoTCP, vip6, netip.MustParseAddr("2001:db8:ffff::1")}, + {"IPv4 TCP client", ipprotoTCP, testVIP4, testClient4}, + {"IPv6 UDP client", ipprotoUDP, vip6, netip.MustParseAddr("2001:db8:ffff::1")}, + {"IPv4 UDP client", ipprotoUDP, testVIP4, testClient4}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - for sport := uint16(40000); sport < 40064; sport++ { - var pkt []byte - if tt.client.Is4() { - pkt = buildIPv4Packet(t, ipprotoTCP, tt.vip, tt.client, sport, 443, nil, ip4Opts{}) - } else { - pkt = buildL4Packet(t, ipprotoTCP, tt.vip, tt.client, sport, 443, nil) - } - _, out := runLB(t, objs, pkt) - if len(out) < ethLen+40 { - t.Fatalf("source port %d: output %d bytes, want an outer header", sport, len(out)) - } + for _, affinity := range []uint8{AffinityNone, AffinityClientIP, AffinityClientIPAndProtocol} { + for _, key := range keys { + var value EdgedsrVipValue + if err := objs.VipTable.Lookup(key, &value); err != nil { + t.Fatalf("read vip_table: %v", err) + } + value.Affinity = affinity + if err := objs.VipTable.Put(key, value); err != nil { + t.Fatalf("set affinity %d: %v", affinity, err) + } + } + for _, tt := range tests { + t.Run(fmt.Sprintf("%s/affinity %d", tt.name, affinity), func(t *testing.T) { + for sport := uint16(40000); sport < 40064; sport++ { + var pkt []byte + if tt.client.Is4() { + pkt = buildIPv4Packet(t, tt.proto, tt.vip, tt.client, sport, 443, nil, ip4Opts{}) + } else { + pkt = buildL4Packet(t, tt.proto, tt.vip, tt.client, sport, 443, nil) + } + _, out := runLB(t, objs, pkt) + if len(out) < ethLen+40 { + t.Fatalf("source port %d: output %d bytes, want an outer header", sport, len(out)) + } - // An IPv4 client is hashed in its IPv4-mapped form, as As16 gives it. - slot := FlowHash(tt.client.As16(), sport) % tableSize - want := usids[slot%maxBackends] - if got := addrAt(out[ethLen:], 24); got != want { - t.Errorf("source port %d: encapsulated toward %v, want %v (slot %d)", sport, got, want, slot) + // An IPv4 client is hashed in its IPv4-mapped form, as As16 gives it. + slot := FlowHash(tt.client.As16(), affinity, tt.proto, sport) % tableSize + want := usids[slot%maxBackends] + if got := addrAt(out[ethLen:], 24); got != want { + t.Errorf("source port %d: encapsulated toward %v, want %v (slot %d)", sport, got, want, slot) + } } - } - }) + }) + } } }