From 74cc7eed2e36bb7a3ca1a3ed9828dd2998d004fc Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 12 Oct 2026 14:50:34 -0400 Subject: [PATCH] feat(nat): Count session creation and claim probes Port pressure showed only as the busiest destination's share once sessions had piled up, and a shard whose uplinks failed to re-resolve after a link change logged it and kept stale coverage with no metric. nat_claims, a per-CPU array of 48 slots (family x protocol x probes), counts every new session's masquerade port claim by how many of its 8 candidates it probed, at one increment per new session and nothing per packet. A claim that adopts a live session's lost port opens no session and is not counted. galactic_nat_session_creates_total sums it per family and protocol, and galactic_nat_masquerade_claim_probes_total keeps the distribution: with a share u of a destination's ports held, a claim needs more than k probes with probability u^k, so the share above one probe estimates fill before any destination nears exhaustion. galactic_nat_uplink_resolve_errors_total counts failed uplink re-resolutions. The EgressShard reconciler's controller-runtime metrics were already served on the same port; the docs now say so. Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-nat/claims_test.go | 52 ++++++++++++ cmd/galactic-nat/metrics.go | 68 +++++++++++++++- cmd/galactic-nat/nat.go | 19 +++++ docs/metrics.md | 26 ++++++ docs/nat/configuration.md | 8 ++ internal/plumbing/ebpf/natmap/dropreasons.go | 22 +++++ internal/plumbing/ebpf/natprog/claims_test.go | 81 +++++++++++++++++++ internal/plumbing/ebpf/natprog/nat.c | 35 +++++++- internal/plumbing/ebpf/natprog/traffic.go | 20 +++++ 9 files changed, 325 insertions(+), 6 deletions(-) create mode 100644 cmd/galactic-nat/claims_test.go create mode 100644 internal/plumbing/ebpf/natprog/claims_test.go diff --git a/cmd/galactic-nat/claims_test.go b/cmd/galactic-nat/claims_test.go new file mode 100644 index 000000000..156ca5f15 --- /dev/null +++ b/cmd/galactic-nat/claims_test.go @@ -0,0 +1,52 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "testing" + + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" +) + +// fakeClaims answers nat_claims lookups from fixed per-CPU counts. +type fakeClaims map[uint32][]uint64 + +func (f fakeClaims) Lookup(key, valueOut any) error { + *valueOut.(*[]uint64) = f[key.(uint32)] + return nil +} + +func TestNatCollectorReportsClaims(t *testing.T) { + c := &natCollector{claims: fakeClaims{ + natprog.ClaimSlot(natprog.TrafficFamilyNAT66, natprog.ClaimProtoTCP, 1): {4, 6}, + natprog.ClaimSlot(natprog.TrafficFamilyNAT66, natprog.ClaimProtoTCP, 3): {2}, + natprog.ClaimSlot(natprog.TrafficFamilyNAT64, natprog.ClaimProtoICMP, 8): {1}, + }} + got := gatherAll(t, c) + + creates := got["galactic_nat_session_creates_total"] + if len(creates) != 6 { + t.Errorf("session_creates_total has %d series, want 6 (2 families x 3 protocols): %v", len(creates), creates) + } + // Labels sort as family/proto. + for labels, want := range map[string]float64{"nat66/tcp": 12, "nat64/icmp": 1, "nat66/udp": 0} { + if creates[labels] != want { + t.Errorf("session_creates_total{%s} = %v, want %v", labels, creates[labels], want) + } + } + + probes := got["galactic_nat_masquerade_claim_probes_total"] + if len(probes) != int(natprog.ClaimSlots) { + t.Errorf("claim_probes_total has %d series, want %d", len(probes), natprog.ClaimSlots) + } + // Labels sort as family/probes/proto. + for labels, want := range map[string]float64{ + "nat66/1/tcp": 10, "nat66/3/tcp": 2, "nat64/8/icmp": 1, "nat66/2/tcp": 0, + } { + if probes[labels] != want { + t.Errorf("claim_probes_total{%s} = %v, want %v", labels, probes[labels], want) + } + } +} diff --git a/cmd/galactic-nat/metrics.go b/cmd/galactic-nat/metrics.go index 547127cff..cdee0d594 100644 --- a/cmd/galactic-nat/metrics.go +++ b/cmd/galactic-nat/metrics.go @@ -9,6 +9,7 @@ import ( "log/slog" "maps" "net/netip" + "strconv" "github.com/cilium/ebpf" "github.com/prometheus/client_golang/prometheus" @@ -21,11 +22,14 @@ import ( const metricsNamespace = "galactic_nat" // labelFamily is the label carrying an address family, familyNAT66 or -// familyNAT64. -const labelFamily = "family" +// familyNAT64, and labelProto the one carrying a session protocol. +const ( + labelFamily = "family" + labelProto = "proto" +) // masqueradeLabels label the masquerade port series. -var masqueradeLabels = []string{labelFamily, "address", "proto"} +var masqueradeLabels = []string{labelFamily, "address", labelProto} // trafficLabels label the translated-traffic series. var trafficLabels = []string{labelFamily, "direction", "action"} @@ -40,6 +44,7 @@ type natCollector struct { connMaxEntries uint32 dropReasons natmap.DropReasonsReader traffic natmap.TrafficReader + claims natmap.CounterReader // shardConfig names the masquerade addresses whose port usage is always // reported, zero included. Nil reports only the addresses rows hold. @@ -69,6 +74,7 @@ func newNatCollector(objs *natprog.NatObjects) *natCollector { connMaxEntries: mapMaxEntries(objs.NatConnTable), dropReasons: objs.DropReasons, traffic: objs.NatTraffic, + claims: objs.NatClaims, shardConfig: natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}), } } @@ -93,7 +99,7 @@ var ( prometheus.BuildFQName(metricsNamespace, "", "sessions"), "Live sessions in this shard's nat_conn_table, by address family and protocol: sessions "+ "within their idle timeout, one per session. Expired sessions are not counted.", - []string{labelFamily, "proto"}, nil, + []string{labelFamily, labelProto}, nil, ) oldestRowAgeDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "conn_table_oldest_row_age_seconds"), @@ -143,6 +149,19 @@ var ( "Masquerade ports (or ICMP Echo Identifiers) available toward each destination address and port.", nil, nil, ) + sessionCreatesDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "session_creates_total"), + "New sessions this shard opened, each one a masquerade port (or ICMP Echo Identifier) it claimed, by "+ + "address family and protocol. A claim that found no free port is a *_pat_exhausted drop instead.", + []string{labelFamily, labelProto}, nil, + ) + claimProbesDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "masquerade", "claim_probes_total"), + "New sessions' masquerade port claims by how many probes each took, 1 to 8. With a share u of a "+ + "destination's ports held, a claim needs more than k probes with probability of roughly u^k, so the share of "+ + "claims needing more than one probe estimates how full the busiest destinations are.", + []string{labelFamily, labelProto, "probes"}, nil, + ) dropsDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "drops_total"), "Packets dropped by this shard's datapath, by reason (drop_reasons map).", @@ -162,6 +181,8 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) { ch <- portsInUseDesc ch <- destinationPortsMaxDesc ch <- portRangeDesc + ch <- sessionCreatesDesc + ch <- claimProbesDesc } // Collect implements prometheus.Collector. @@ -170,6 +191,7 @@ func (c *natCollector) Collect(ch chan<- prometheus.Metric) { c.collectConnTableMaxEntries(ch) c.collectDrops(ch) c.collectTraffic(ch) + c.collectClaims(ch) } // Family label values, one per address family a shard translates. @@ -341,3 +363,41 @@ func (c *natCollector) collectTraffic(ch chan<- prometheus.Metric) { } } } + +// collectClaims reports new sessions by family and protocol, and their claims +// by probe count, every combination zero included. +func (c *natCollector) collectClaims(ch chan<- prometheus.Metric) { + if c.claims == nil { + return + } + totals, err := natmap.ClaimTotals(c.claims) + if err != nil { + slog.Warn("cannot read nat_claims; skipping session creation metrics", "err", err) + return + } + families := []struct { + id uint32 + label string + }{{natprog.TrafficFamilyNAT66, familyNAT66}, {natprog.TrafficFamilyNAT64, familyNAT64}} + protos := []struct { + id uint32 + label string + }{ + {natprog.ClaimProtoTCP, natmap.SessionProtoTCP}, + {natprog.ClaimProtoUDP, natmap.SessionProtoUDP}, + {natprog.ClaimProtoICMP, natmap.SessionProtoICMP}, + } + for _, f := range families { + for _, p := range protos { + var creates uint64 + for probes := 1; probes <= natprog.PATProbeLimit; probes++ { + n := totals[natprog.ClaimSlot(f.id, p.id, probes)] + creates += n + ch <- prometheus.MustNewConstMetric(claimProbesDesc, prometheus.CounterValue, float64(n), + f.label, p.label, strconv.Itoa(probes)) + } + ch <- prometheus.MustNewConstMetric(sessionCreatesDesc, prometheus.CounterValue, float64(creates), + f.label, p.label) + } + } +} diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 0ba2b0559..90a2cefd9 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -72,6 +72,10 @@ type natDatapath struct { // nat64 is whether the programmed identity serves NAT64, which an uplink // found later needs IPv4 forwarding for, as Program gives the rest. nat64 bool + + // resolveErrors counts watchUplinks' failed re-resolutions, which keep + // the previous coverage. Nil counts nothing. + resolveErrors prometheus.Counter } // Attached reports whether startup completed its load and attach pass. It is @@ -361,6 +365,18 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, registerUplinkQueueStats(metricsReg, d) + d.resolveErrors = prometheus.NewCounter(prometheus.CounterOpts{ + Namespace: metricsNamespace, + Name: "uplink_resolve_errors_total", + Help: "Times re-resolving this node's uplinks after a link or route change failed. The shard keeps " + + "its previous coverage, so a steady rise means uplinks that appeared since are not covered.", + }) + if err := metricsReg.Register(d.resolveErrors); err != nil { + closeAll(xdpLinks) + _ = objs.Close() + return nil, fmt.Errorf("register uplink resolve error metric: %w", err) + } + natDatapathKeepAlive.objs = objs natDatapathKeepAlive.set = set natDatapathKeepAlive.dispatch = dispatcher @@ -504,6 +520,9 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover uplinks, err := natattach.ResolveUplinks(override) if err != nil { slog.Warn("Re-resolve uplink interfaces failed; keeping current coverage", "err", err) + if d.resolveErrors != nil { + d.resolveErrors.Inc() + } return } ready := d.adoptUplinks(uplinks) diff --git a/docs/metrics.md b/docs/metrics.md index d7c526af2..f8f30e836 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -289,6 +289,9 @@ One `galactic-nat` pod per egress shard; every value is per shard. | `galactic_nat_masquerade_port_range` | gauge | none | Ports (or ICMP Echo Identifiers) available toward each destination: 28000 | | `galactic_nat_dispatch_lease_renewals_total` | counter | `slot`, `result` (`success`, `error`) | Renewals of the shard's XDP dispatcher slot lease. Dispatch mode only | | `galactic_nat_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time the lease, as last renewed, expires. Dispatch mode only | +| `galactic_nat_session_creates_total` | counter | `family`, `proto` | New sessions the shard opened, one masquerade port claim each | +| `galactic_nat_masquerade_claim_probes_total` | counter | `family`, `proto`, `probes` (`1`..`8`) | Those claims by how many probes each took. Rising multi-probe shares mean busy destinations are filling | +| `galactic_nat_uplink_resolve_errors_total` | counter | none | Failed re-resolutions of the uplinks after a link or route change; the shard keeps its previous coverage | | `galactic_nat_uplink_rx_queue_packets_total` | counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink received, from `ethtool -S`. Exported for `bnxt_en`, `ixgbe`, `ice`, `i40e`, `mlx5_core` | | `galactic_nat_uplink_rx_queue_discards_total` | counter | `interface`, `driver`, `queue` | Packets one receive queue discarded before the datapath saw them. Reported only by drivers that count per queue: `bnxt_en` today | | `galactic_nat_uplink_queue_driver_stat_total` | counter | `interface`, `driver`, `queue`, `stat` | One of a queue's other driver counters, under its `ethtool -S` name. `bnxt_en` only, see below | @@ -331,6 +334,25 @@ Caveats for the masquerade port series: - Both are read from the session table walk at scrape time, like `galactic_nat_sessions`, so they are approximate on a churning table. +Caveats for session creation: + +- `galactic_nat_session_creates_total` is the sum of + `galactic_nat_masquerade_claim_probes_total` over `probes`. A claim that + finds no port is a `*_pat_exhausted` drop, and a claim that adopts a live + session's lost port opens no new session; neither is counted. +- With a share u of a destination's ports held, a claim needs more than k + probes with probability of roughly u^k (the probes walk consecutive ports, + and held ports cluster, so it is an estimate). The share of claims needing more than one + probe therefore estimates how full the destinations taking new flows are, + before `galactic_nat_masquerade_destination_ports_max` names the worst one + and long before `*_pat_exhausted` drops start. +- Cardinality: 6 creates series and 48 probe series per shard. + +The `EgressShard` reconciler's controller-runtime metrics +(`controller_runtime_reconcile_total{controller="egressshard"}`, +`controller_runtime_reconcile_errors_total`, `workqueue_*`) are served on the +same port, from the same registry. + The dispatcher lease series are registered in dispatch mode only. The edge gateway exports the same pair as `galactic_edge_dispatch_lease_*` for its two slots; no shipped alert reads the gateway's yet. @@ -397,6 +419,10 @@ sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|n max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max) / on (node) group_left () max by (node) (galactic_nat_masquerade_port_range) +# Share of new sessions whose port claim needed more than one probe +sum by (node, family) (rate(galactic_nat_masquerade_claim_probes_total{probes!="1"}[10m])) + / sum by (node, family) (rate(galactic_nat_session_creates_total[10m])) + # Seconds left on the dispatcher lease, by the node's clock galactic_nat_dispatch_lease_expiry_timestamp_seconds - time() diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index e5a2363a3..855db1d56 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -722,9 +722,17 @@ Metrics, exposed on `GALACTIC_NAT_METRICS_PORT` (`9182` by default): | `galactic_nat_masquerade_port_range` | Gauge | — | Ports available toward each destination, `NAT_PAT_PORT_RANGE` (28000). | | `galactic_nat_dispatch_lease_renewals_total` | Counter | `slot`, `result` | Renewals of the shard's XDP dispatcher slot lease, `success` or `error`. Present in dispatch mode only. | | `galactic_nat_dispatch_lease_expiry_timestamp_seconds` | Gauge | `slot` | Unix time the slot's lease, as last renewed, expires. The dispatcher skips the slot once it passes. Present in dispatch mode only. | +| `galactic_nat_session_creates_total` | Counter | `family`, `proto` | New sessions opened, each a masquerade port (or ICMP Echo Identifier) the shard claimed. A claim that found no port is a `*_pat_exhausted` drop instead, and one that adopted a live session's lost port is not counted. Every combination is reported, zero included. | +| `galactic_nat_masquerade_claim_probes_total` | Counter | `family`, `proto`, `probes` | Those claims by how many of the 8 candidates each probed. With a share u of a destination's ports held, a claim needs more than k probes with probability of roughly u^k, so a rising share above `probes="1"` is the earliest sign destinations are filling. | +| `galactic_nat_uplink_resolve_errors_total` | Counter | — | Times re-resolving the uplinks after a link or route change failed. The shard keeps its previous coverage, so uplinks that appeared since stay uncovered until a later resolution succeeds. | | `galactic_nat_uplink_rx_queue_packets_total` | Counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink received, from the driver's `ethtool -S` statistics. Exported for `bnxt_en`, `ixgbe`, `ice`, `i40e` and `mlx5_core`; any other driver exports nothing. | | `galactic_nat_uplink_rx_queue_discards_total` | Counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink discarded before the datapath saw them, so `galactic_nat_drops_total` never counts them. Only drivers that count discards per queue report it: `bnxt_en` today. | +The same port also serves the `EgressShard` reconciler's controller-runtime +metrics (`controller_runtime_reconcile_total{controller="egressshard"}`, +`controller_runtime_reconcile_errors_total`, `workqueue_*`), registered in the +same registry as the series above. + `config/monitoring/podmonitor-galactic-nat.yaml` scrapes every shard as `job="galactic-nat"` with a `node` label. diff --git a/internal/plumbing/ebpf/natmap/dropreasons.go b/internal/plumbing/ebpf/natmap/dropreasons.go index 28ad23769..e25983ad4 100644 --- a/internal/plumbing/ebpf/natmap/dropreasons.go +++ b/internal/plumbing/ebpf/natmap/dropreasons.go @@ -69,3 +69,25 @@ func TrafficTotals(reader TrafficReader) ([natprog.TrafficSlots]natprog.NatNatTr } return totals, nil } + +// CounterReader narrows a per-CPU array of uint64 counters, such as +// nat_claims, to the one operation its readers need. +type CounterReader interface { + Lookup(key, valueOut any) error +} + +// ClaimTotals reads every nat_claims slot and returns its count summed across +// CPUs, indexed by natprog.ClaimSlot. +func ClaimTotals(reader CounterReader) ([natprog.ClaimSlots]uint64, error) { + var totals [natprog.ClaimSlots]uint64 + for slot := range natprog.ClaimSlots { + var perCPU []uint64 + if err := reader.Lookup(slot, &perCPU); err != nil { + return totals, fmt.Errorf("natmap: nat_claims: lookup[%d]: %w", slot, err) + } + for _, v := range perCPU { + totals[slot] += v + } + } + return totals, nil +} diff --git a/internal/plumbing/ebpf/natprog/claims_test.go b/internal/plumbing/ebpf/natprog/claims_test.go new file mode 100644 index 000000000..aa626068d --- /dev/null +++ b/internal/plumbing/ebpf/natprog/claims_test.go @@ -0,0 +1,81 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natprog + +import "testing" + +func claimCount(t *testing.T, objs *NatObjects, slot uint32) uint64 { + t.Helper() + var perCPU []uint64 + if err := objs.NatClaims.Lookup(slot, &perCPU); err != nil { + t.Fatalf("lookup nat_claims[%d]: %v", slot, err) + } + var total uint64 + for _, v := range perCPU { + total += v + } + return total +} + +// TestNatClaims_CountsNewSessionsOnce checks that a new session counts one +// claim in its family and protocol's single-probe slot, and that the same +// session's later packets, which reuse its port, count nothing. +func TestNatClaims_CountsNewSessionsOnce(t *testing.T) { + f := newNAT66Fixture(t) + udp1 := ClaimSlot(TrafficFamilyNAT66, ClaimProtoUDP, 1) + + f.sendUDP(t) + if got := claimCount(t, f.objs, udp1); got != 1 { + t.Fatalf("nat_claims[nat66/udp/1] after a new session = %d, want 1", got) + } + f.sendUDP(t) + f.sendUDP(t) + if got := claimCount(t, f.objs, udp1); got != 1 { + t.Errorf("nat_claims[nat66/udp/1] after the same session's later packets = %d, want still 1", got) + } + for slot := range ClaimSlots { + if slot == udp1 { + continue + } + if got := claimCount(t, f.objs, slot); got != 0 { + t.Errorf("nat_claims[%d] = %d, want 0", slot, got) + } + } +} + +func TestClaimSlot(t *testing.T) { + seen := map[uint32]bool{} + for _, family := range []uint32{TrafficFamilyNAT66, TrafficFamilyNAT64} { + for _, proto := range []uint32{ClaimProtoTCP, ClaimProtoUDP, ClaimProtoICMP} { + for probes := 1; probes <= PATProbeLimit; probes++ { + slot := ClaimSlot(family, proto, probes) + if slot >= ClaimSlots || seen[slot] { + t.Fatalf("ClaimSlot(%d, %d, %d) = %d, out of range or reused", family, proto, probes, slot) + } + seen[slot] = true + } + } + } + if uint32(len(seen)) != ClaimSlots { + t.Errorf("slots used = %d, want all %d", len(seen), ClaimSlots) + } +} + +// TestClaimSlots_MatchesTheMap keeps the Go slot count in step with the +// datapath's nat_claims size, which the C side derives from its own probe +// limit. +func TestClaimSlots_MatchesTheMap(t *testing.T) { + spec, err := LoadNat() + if err != nil { + t.Fatalf("LoadNat: %v", err) + } + m := spec.Maps["nat_claims"] + if m == nil { + t.Fatal("nat_claims missing from the compiled spec") + } + if m.MaxEntries != ClaimSlots { + t.Errorf("nat_claims has %d entries, natprog.ClaimSlots is %d", m.MaxEntries, ClaimSlots) + } +} diff --git a/internal/plumbing/ebpf/natprog/nat.c b/internal/plumbing/ebpf/natprog/nat.c index 20b49ba87..7f79d5920 100644 --- a/internal/plumbing/ebpf/natprog/nat.c +++ b/internal/plumbing/ebpf/natprog/nat.c @@ -630,6 +630,21 @@ struct { __type(value, struct nat_traffic_counter); } nat_traffic SEC(".maps"); +// nat_claims counts every new session's masquerade port claim by how many +// probes it took, per CPU: slot family * 24 + protocol * 8 + (probes - 1), +// family 0 for NAT66 and 1 for NAT64, protocol 0 TCP, 1 UDP, 2 ICMP Echo. +// Mirrored in Go by natprog.ClaimSlot. A claim that finds no port within +// NAT_PAT_PROBE_LIMIT probes is a pat_exhausted drop instead, and a claim that +// adopts a live session's port opens no new session, so neither is counted. +#define NAT_CLAIM_SLOTS (2 * 3 * NAT_PAT_PROBE_LIMIT) + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, NAT_CLAIM_SLOTS); + __type(key, __u32); + __type(value, __u64); +} nat_claims SEC(".maps"); + // struct icmp_bucket is one CPU's token bucket, held as nanoseconds of credit // rather than whole tokens so a refill is an addition, with no division on the // packet path: each message costs NAT_ICMP_COST_NS, and credit accrues one @@ -1380,6 +1395,18 @@ static NAT_ALWAYS_INLINE void release_session(struct conn_key *rev_key, const st bpf_map_delete_elem(&nat_conn_table, rev_key); } +// count_claim records a new session's claim that took probes probes. +static NAT_ALWAYS_INLINE void count_claim(const struct conn_key *rev_key, int probes) +{ + __u32 family = rev_key->family == NAT_FAMILY_V4 ? 1 : 0; + __u32 proto = rev_key->proto == NAT_IPPROTO_TCP ? 0 : rev_key->proto == NAT_IPPROTO_UDP ? 1 : 2; + __u32 slot = family * 3 * NAT_PAT_PROBE_LIMIT + proto * NAT_PAT_PROBE_LIMIT + (__u32) (probes - 1); + __u64 *count = bpf_map_lookup_elem(&nat_claims, &slot); + + if (count) + *count += 1; +} + // claim_masquerade_port probes for a free (shard address, port) pair for a new // flow and installs the reverse row under it, returning the claimed port in // network order or 0 when every probe collided with a live session. @@ -1409,8 +1436,10 @@ static NAT_ALWAYS_INLINE __be16 claim_masquerade_port(struct session_scratch *ss rev_key->dport = port; cv->shard_port = port; - if (bpf_map_update_elem(&nat_conn_table, rev_key, cv, BPF_NOEXIST) == 0) + if (bpf_map_update_elem(&nat_conn_table, rev_key, cv, BPF_NOEXIST) == 0) { + count_claim(rev_key, i + 1); return port; + } struct conn_value *held = bpf_map_lookup_elem(&nat_conn_table, rev_key); if (!held) @@ -1423,8 +1452,10 @@ static NAT_ALWAYS_INLINE __be16 claim_masquerade_port(struct session_scratch *ss return port; } release_session(rev_key, held, &ss->victim); - if (bpf_map_update_elem(&nat_conn_table, rev_key, cv, BPF_NOEXIST) == 0) + if (bpf_map_update_elem(&nat_conn_table, rev_key, cv, BPF_NOEXIST) == 0) { + count_claim(rev_key, i + 1); return port; + } } return 0; } diff --git a/internal/plumbing/ebpf/natprog/traffic.go b/internal/plumbing/ebpf/natprog/traffic.go index be39aae52..0e74ba1f7 100644 --- a/internal/plumbing/ebpf/natprog/traffic.go +++ b/internal/plumbing/ebpf/natprog/traffic.go @@ -37,3 +37,23 @@ const ( PATPortRange uint16 = 28000 PATProbeLimit int = 8 ) + +// Claim protocol indices of the nat_claims map, mirroring the datapath's +// count_claim: TCP, UDP, and ICMP Echo. +const ( + ClaimProtoTCP uint32 = 0 + ClaimProtoUDP uint32 = 1 + ClaimProtoICMP uint32 = 2 + + // ClaimSlots is the nat_claims map's entry count: two families, three + // protocols, and one slot per probe count up to PATProbeLimit. + ClaimSlots uint32 = 2 * 3 * uint32(PATProbeLimit) +) + +// ClaimSlot returns the nat_claims index for a claim of protocol proto in +// family (TrafficFamilyNAT66 or TrafficFamilyNAT64) that took probes probes, +// from 1 to PATProbeLimit. +func ClaimSlot(family, proto uint32, probes int) uint32 { + limit := uint32(PATProbeLimit) + return family*3*limit + proto*limit + uint32(probes-1) //nolint:gosec // probes is 1..PATProbeLimit +}