From 54ead3d6fcc9a0e2a118e29636c9d406450420b7 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 5 Oct 2026 11:13:37 -0400 Subject: [PATCH 1/2] fix(nat): Report live sessions apart from expired rows galactic_nat_conns counted every row in nat_conn_table. Since sessions began expiring lazily (#726), expired rows stay until the LRU evicts them or a new claim reuses their port, so any busy shard reads close to full and an alert on table fill never clears. The collector now walks the table once and reports: - galactic_nat_sessions{family,proto}: reverse rows still within their idle timeout, one per live session. Liveness mirrors the datapath's session_timeout and session_expired, read against CLOCK_MONOTONIC in whole seconds truncated to 32 bits, the clock bpf_ktime_get_ns stamps last_seen with. Forward rows are skipped because their last_seen records when they were written and is never refreshed. - galactic_nat_conn_table_oldest_row_age_seconds: the age of the least recently seen reverse row, expired ones included. Expired rows are rarely touched again, so on a full table this approximates how long an idle row survives before eviction. A table above 90% full whose oldest row is younger than 7440 s, the established TCP timeout, is evicting idle live sessions. - galactic_nat_conns keeps its name and value, so dashboards and the lab check still work. Its help text now says it counts rows, expired sessions included, two per session. natmap.ConnTable.CountSessions replaces CountByFamily, its only caller being the collector. The metrics and NAT configuration docs drop the #731 caveat, say a full table is normal under lazy expiry, and replace the table-fill alert with the eviction-horizon one. A counter of rows evicted while live was considered and rejected: BPF LRU maps have no eviction hook, so it would need datapath changes and per-packet cost. The alert itself is left out of config/monitoring/ until the gauges have been seen on a lab shard. Fixes #731 Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-nat/metrics.go | 91 ++++++++-- cmd/galactic-nat/metrics_test.go | 138 ++++++++++++++- docs/metrics.md | 40 +++-- docs/nat/configuration.md | 34 +++- internal/plumbing/ebpf/natmap/conntable.go | 100 ++++++++++- .../plumbing/ebpf/natmap/conntable_test.go | 162 ++++++++++++++++-- 6 files changed, 504 insertions(+), 61 deletions(-) diff --git a/cmd/galactic-nat/metrics.go b/cmd/galactic-nat/metrics.go index 3f94fd124..246b35618 100644 --- a/cmd/galactic-nat/metrics.go +++ b/cmd/galactic-nat/metrics.go @@ -10,6 +10,7 @@ import ( "github.com/cilium/ebpf" "github.com/prometheus/client_golang/prometheus" + "golang.org/x/sys/unix" "go.datum.net/galactic/internal/plumbing/ebpf/natmap" "go.datum.net/galactic/internal/plumbing/ebpf/natprog" @@ -18,13 +19,29 @@ import ( const metricsNamespace = "galactic_nat" // natCollector reads this shard's live map state at every scrape: drops by -// reason and connection-table occupancy by address family. It is a pull-based collector like the other datapaths', +// reason, connection-table rows by address family, and live sessions by family +// and protocol. It is a pull-based collector like the other datapaths', // scoped to what the map layer exposes read access to, the connection table // being entirely datapath-owned and so observability-only. type natCollector struct { connTable *natmap.ConnTable connMaxEntries uint32 dropReasons natmap.DropReasonsReader + + // now reads the clock the datapath stamps last_seen with. Nil means + // datapathNow. + now func() uint32 +} + +// datapathNow reads the datapath's session clock: bpf_ktime_get_ns is +// CLOCK_MONOTONIC, which the datapath keeps in whole seconds truncated to 32 +// bits (now_sec in nat.c). +func datapathNow() uint32 { + var ts unix.Timespec + if err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts); err != nil { + return 0 + } + return uint32(ts.Sec) } // newNatCollector builds a collector reading directly from a loaded object @@ -48,11 +65,25 @@ func mapMaxEntries(m *ebpf.Map) uint32 { var ( connsDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "conns"), - "Current number of flows in this shard's nat_conn_table, by address family -- a point-in-time "+ - "snapshot; the table is a self-evicting LRU, so this can fluctuate independently of actual "+ - "live traffic under memory pressure.", + "Rows in this shard's nat_conn_table, by address family, expired sessions included: "+ + "a session holds two rows, and an expired one keeps them until the LRU evicts them or a "+ + "new claim reuses its port. See galactic_nat_sessions for live sessions.", []string{"family"}, nil, ) + sessionsDesc = prometheus.NewDesc( + 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{"family", "proto"}, nil, + ) + oldestRowAgeDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "conn_table_oldest_row_age_seconds"), + "Seconds since the least recently seen session in nat_conn_table last translated a packet, "+ + "expired sessions included. On a full table this approximates how long an idle session "+ + "survives before the LRU evicts it; below the longest session timeout, idle live sessions "+ + "are being evicted.", + nil, nil, + ) connTableMaxEntriesDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "conn_table_max_entries"), "Capacity of nat_conn_table in rows.", @@ -68,6 +99,8 @@ var ( // Describe implements prometheus.Collector. func (c *natCollector) Describe(ch chan<- *prometheus.Desc) { ch <- connsDesc + ch <- sessionsDesc + ch <- oldestRowAgeDesc ch <- connTableMaxEntriesDesc ch <- dropsDesc } @@ -79,35 +112,65 @@ func (c *natCollector) Collect(ch chan<- prometheus.Metric) { c.collectDrops(ch) } +// Family label values, one per address family a shard translates. +const ( + familyNAT66 = "nat66" + familyNAT64 = "nat64" +) + func familyLabel(family uint8) string { switch family { case natprog.FamilyIPv4: - return "nat64" + return familyNAT64 case natprog.FamilyIPv6: - return "nat66" + return familyNAT66 default: return "unknown" } } func (c *natCollector) collectConns(ch chan<- prometheus.Metric) { + if c.connTable == nil { + return + } + now := c.now + if now == nil { + now = datapathNow + } // A walk the datapath's own inserts and evictions disturbed still reports // what it counted: an error metric here fails the whole scrape, drops // included. - counts, err := c.connTable.CountByFamily() + counts, err := c.connTable.CountSessions(now()) if err != nil { slog.Debug("nat_conn_table walk incomplete; reporting an approximate count", "err", err) } - // Both families are always reported, zero included: a family that - // disappears from the output entirely reads as "not scraped" rather than - // "no flows", which is the difference that matters at 3am. - byFamily := map[string]int{"nat66": 0, "nat64": 0} - for family, count := range counts { - byFamily[familyLabel(family)] += count + // Every family and protocol is always reported, zero included: a series + // that disappears from the output entirely reads as "not scraped" rather + // than "no flows", which is the difference that matters at 3am. + rows := map[string]int{familyNAT66: 0, familyNAT64: 0} + for family, count := range counts.Rows { + rows[familyLabel(family)] += count } - for family, count := range byFamily { + for family, count := range rows { ch <- prometheus.MustNewConstMetric(connsDesc, prometheus.GaugeValue, float64(count), family) } + + live := map[[2]string]int{} + for _, family := range []string{familyNAT66, familyNAT64} { + for _, proto := range []string{natmap.SessionProtoTCP, natmap.SessionProtoUDP, natmap.SessionProtoICMP} { + live[[2]string{family, proto}] = 0 + } + } + for key, count := range counts.Live { + live[[2]string{familyLabel(key.Family), key.Proto}] += count + } + for key, count := range live { + ch <- prometheus.MustNewConstMetric(sessionsDesc, prometheus.GaugeValue, float64(count), key[0], key[1]) + } + + if counts.HasReverse { + ch <- prometheus.MustNewConstMetric(oldestRowAgeDesc, prometheus.GaugeValue, float64(counts.OldestAge)) + } } func (c *natCollector) collectConnTableMaxEntries(ch chan<- prometheus.Metric) { diff --git a/cmd/galactic-nat/metrics_test.go b/cmd/galactic-nat/metrics_test.go index 166bb50df..b1dff701c 100644 --- a/cmd/galactic-nat/metrics_test.go +++ b/cmd/galactic-nat/metrics_test.go @@ -7,6 +7,7 @@ package main import ( "errors" "os" + "reflect" "strings" "testing" @@ -15,10 +16,145 @@ import ( "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" + "go.datum.net/galactic/internal/plumbing/ebpf/natmap" "go.datum.net/galactic/internal/plumbing/ebpf/natprog" ) -const connTableMaxEntriesName = "galactic_nat_conn_table_max_entries" +const ( + connTableMaxEntriesName = "galactic_nat_conn_table_max_entries" + connsName = "galactic_nat_conns" + sessionsName = "galactic_nat_sessions" + oldestRowAgeName = "galactic_nat_conn_table_oldest_row_age_seconds" +) + +// connRows is a read-only natmap.Table over a fixed list of wire rows, enough +// for the collector's walk. +type connRows struct { + keys []natprog.NatConnKey + values []natprog.NatConnValue +} + +func (r *connRows) add(key natprog.NatConnKey, value natprog.NatConnValue) { + r.keys = append(r.keys, key) + r.values = append(r.values, value) +} + +func (*connRows) Put(_, _ any) error { return errors.New("read-only") } +func (*connRows) Lookup(_, _ any) error { return ebpf.ErrKeyNotExist } +func (*connRows) Delete(_ any) error { return ebpf.ErrKeyNotExist } +func (r *connRows) Iterate() natmap.Iterator { + return &connRowsIterator{rows: r, idx: -1} +} + +type connRowsIterator struct { + rows *connRows + idx int +} + +func (it *connRowsIterator) Next(keyOut, valueOut any) bool { + it.idx++ + if it.idx >= len(it.rows.keys) { + return false + } + reflect.ValueOf(keyOut).Elem().Set(reflect.ValueOf(it.rows.keys[it.idx])) + reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(it.rows.values[it.idx])) + return true +} + +func (*connRowsIterator) Err() error { return nil } + +// reverseRow is a reverse row's wire key and value: no encapsulation source. +// destPort is in host order. +func reverseRow( + family, proto uint8, shardPort, destPort uint16, lastSeen uint32, +) (natprog.NatConnKey, natprog.NatConnValue) { + return natprog.NatConnKey{Family: family, Proto: proto, Dport: shardPort}, + natprog.NatConnValue{Proto: proto, DestPort: destPort<<8 | destPort>>8, LastSeen: lastSeen} +} + +// gatherGauges registers c and returns every gauge by metric name, each keyed +// by its label values joined with "/". +func gatherGauges(t *testing.T, c prometheus.Collector) (map[string]map[string]float64, map[string]string) { + t.Helper() + reg := prometheus.NewPedanticRegistry() + if err := reg.Register(c); err != nil { + t.Fatalf("register: %v", err) + } + families, err := reg.Gather() + if err != nil { + t.Fatalf("gather: %v", err) + } + gauges := map[string]map[string]float64{} + help := map[string]string{} + for _, mf := range families { + if mf.GetType() != dto.MetricType_GAUGE { + continue + } + help[mf.GetName()] = mf.GetHelp() + series := map[string]float64{} + for _, m := range mf.GetMetric() { + labels := make([]string, 0, len(m.GetLabel())) + for _, lp := range m.GetLabel() { + labels = append(labels, lp.GetValue()) + } + series[strings.Join(labels, "/")] = m.GetGauge().GetValue() + } + gauges[mf.GetName()] = series + } + return gauges, help +} + +func TestNatCollectorCountsLiveSessions(t *testing.T) { + const now uint32 = 50_000 + rows := &connRows{} + // nat66: one live DNS session and two expired ones. + rows.add(reverseRow(natprog.FamilyIPv6, 17, 35000, 53, now-10)) + rows.add(reverseRow(natprog.FamilyIPv6, 17, 35001, 53, now-31)) + rows.add(reverseRow(natprog.FamilyIPv6, 17, 35002, 53, now-900)) + // nat64: one live ICMP Echo session, tenant protocol ICMPv6. + rows.add(reverseRow(natprog.FamilyIPv4, 58, 35003, 0, now-20)) + // A forward row: counted as a row, never as a session. + rows.add(natprog.NatConnKey{Family: natprog.FamilyIPv6, Proto: 17, EncapSrc: [16]byte{0xfc}}, + natprog.NatConnValue{Proto: 17, LastSeen: 1}) + + c := &natCollector{connTable: natmap.NewConnTable(rows), now: func() uint32 { return now }} + gauges, help := gatherGauges(t, c) + + wantConns := map[string]float64{familyNAT66: 4, familyNAT64: 1} + if !reflect.DeepEqual(gauges[connsName], wantConns) { + t.Errorf("%s = %v, want %v", connsName, gauges[connsName], wantConns) + } + wantSessions := map[string]float64{ + "nat66/tcp": 0, "nat66/udp": 1, "nat66/icmp": 0, + "nat64/tcp": 0, "nat64/udp": 0, "nat64/icmp": 1, + } + if !reflect.DeepEqual(gauges[sessionsName], wantSessions) { + t.Errorf("%s = %v, want %v", sessionsName, gauges[sessionsName], wantSessions) + } + if got := gauges[oldestRowAgeName][""]; got != 900 { + t.Errorf("%s = %v, want 900", oldestRowAgeName, got) + } + + if !strings.Contains(help[connsName], "expired sessions included") { + t.Errorf("%s help does not say it counts expired rows: %q", connsName, help[connsName]) + } + if !strings.Contains(help[sessionsName], "Expired sessions are not counted") { + t.Errorf("%s help does not say it counts live sessions only: %q", sessionsName, help[sessionsName]) + } +} + +func TestNatCollectorEmptyConnTable(t *testing.T) { + c := &natCollector{connTable: natmap.NewConnTable(&connRows{}), now: func() uint32 { return 1 }} + gauges, _ := gatherGauges(t, c) + + if len(gauges[connsName]) != 2 || len(gauges[sessionsName]) != 6 { + t.Errorf("empty table: %s = %v, %s = %v; want every series at zero", + connsName, gauges[connsName], sessionsName, gauges[sessionsName]) + } + if _, ok := gauges[oldestRowAgeName]; ok { + t.Errorf("%s reported for a table with no reverse rows", oldestRowAgeName) + } +} func TestNatCollectorDescribesConnTableMaxEntries(t *testing.T) { ch := make(chan *prometheus.Desc, 16) diff --git a/docs/metrics.md b/docs/metrics.md index cdc03c33c..db70cfeee 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -225,20 +225,23 @@ sum by (controller) (rate(controller_runtime_reconcile_errors_total{job=~"galact One `galactic-nat` pod per egress shard; every value is per shard. -| Metric | Type | Labels | Meaning | -|---------------------------------------|---------|-----------------------------|-------------------------------------------------------------------------------------| -| `galactic_nat_conns` | gauge | `family` (`nat66`, `nat64`) | Flows in the connection table. Both families are always emitted, at zero when empty | -| `galactic_nat_conn_table_max_entries` | gauge | none | Table capacity in rows, shared by both families | -| `galactic_nat_drops_total` | counter | `reason` | Packets dropped by the NAT datapath | - -Caveats for `galactic_nat_conns`: - -- The table is a self-evicting LRU, so under memory pressure the count can - move without traffic changing. -- It also counts expired sessions - ([#731](https://github.com/datum-cloud/galactic/issues/731)), so a healthy - shard can look nearly full. Until that is fixed, don't alert on occupancy - alone; pair it with a port-exhaustion drop rate. +| Metric | Type | Labels | Meaning | +|--------------------------------------------------|---------|------------------------------------------|------------------------------------------------------------------------------------------------| +| `galactic_nat_conns` | gauge | `family` (`nat66`, `nat64`) | Rows in the connection table, expired sessions included. A session holds two rows | +| `galactic_nat_sessions` | gauge | `family`, `proto` (`tcp`, `udp`, `icmp`) | Live sessions: one per session within its idle timeout | +| `galactic_nat_conn_table_oldest_row_age_seconds` | gauge | none | Seconds since the least recently seen session, expired ones included, last translated a packet | +| `galactic_nat_conn_table_max_entries` | gauge | none | Table capacity in rows, shared by both families | +| `galactic_nat_drops_total` | counter | `reason` | Packets dropped by the NAT datapath | + +Caveats for the session table: + +- Expired sessions keep their rows until the LRU evicts them or a new claim + reuses their port, so `galactic_nat_conns` sits near capacity on any busy + shard. That is normal. Use `galactic_nat_sessions` for live sessions. +- Live sessions are at risk only when the table is full and its oldest row is + younger than the longest session timeout, 7440 s for established TCP. +- The table is a self-evicting LRU, so the counts can move without traffic + changing. | Reason group | Values | Meaning | |---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------| @@ -251,11 +254,12 @@ Caveats for `galactic_nat_conns`: | Rate limit | `icmp_rate_limited` | ICMP errors suppressed by the rate limiter | ```promql -# Occupancy (inflated by #731 until it is fixed) -sum by (node) (galactic_nat_conns) / on (node) galactic_nat_conn_table_max_entries +# Live sessions per family +sum by (node, family) (galactic_nat_sessions) -# Sessions per family -sum by (node, family) (galactic_nat_conns) +# Idle live sessions being evicted: table full, oldest row younger than the TCP timeout +sum by (node) (galactic_nat_conns) / on (node) galactic_nat_conn_table_max_entries > 0.9 + and on (node) galactic_nat_conn_table_oldest_row_age_seconds < 7440 # Port exhaustion or no shard sum by (node, reason) (rate(galactic_nat_drops_total{reason=~".*_pat_exhausted|nat64_shard_unavailable"}[5m])) > 0 diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 043e55b36..f88410641 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -414,7 +414,13 @@ gone idle for its protocol's timeout, compile-time constants in `nat.c`: session drops as `no_return_conn`, the tenant's next packet claims a fresh port, and a port claim that collides with an expired session releases both its rows and takes the port. Expired rows hold table capacity until then, - so `galactic_nat_conns` counts them. + so `galactic_nat_conns` counts them and `galactic_nat_sessions` does not. +- **A full table is normal.** On any steadily used shard, expired rows fill + `nat_conn_table` toward its capacity and stay there, because nothing + removes them early. Only evicting a live session is harmful, and the LRU + does that only once rows turn over faster than the longest timeout, + 2 h 4 min. `galactic_nat_conn_table_oldest_row_age_seconds` shows how + fast rows turn over; see the alert under [Verifying](#verifying). - **Split sessions.** The LRU evicts rows one at a time. A forward row whose reverse row is gone is replaced on its next packet; a reverse row whose forward row is gone keeps translating replies, and the flow's next packet @@ -432,11 +438,22 @@ kubectl get bgpadvertisement -n galactic-system | grep nat66 Metrics, exposed on `GALACTIC_NAT_METRICS_PORT` (`9182` by default): -| Metric | Type | Labels | Meaning | -| ------------------------------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `galactic_nat_conns` | Gauge | — | Current row count in this shard's `nat_conn_table` — a point-in-time snapshot of an LRU, so it can fluctuate independently of actual live traffic under memory pressure. | -| `galactic_nat_conn_table_max_entries` | Gauge | — | Capacity of `nat_conn_table`, read from the loaded map. Alert when `sum(galactic_nat_conns) / galactic_nat_conn_table_max_entries` stays above about 0.9: past that, new sessions evict live ones. | -| `galactic_nat_drops_total` | Counter | `reason` | Packets dropped by the `nat_ingress` program, by reason. Cumulative for the life of the *node*, not the process: the counters live in a map pinned under `natattach.PinDir`, which a restarting shard reuses as-is. Always read it as a delta — an absolute value includes every transient the node has ever seen, and zeroing it takes `bpftool map update` against the pin directly. | +| Metric | Type | Labels | Meaning | +| ------------------------------------------------ | ------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_nat_conns` | Gauge | `family` | Rows in this shard's `nat_conn_table`, expired sessions included. A session holds two rows. Expect it near capacity on a busy shard; see [Session table](#session-table). | +| `galactic_nat_sessions` | Gauge | `family`, `proto` | Live sessions, one per session within its idle timeout. `proto` is `tcp`, `udp` or `icmp`. Every series is reported, at zero when empty. | +| `galactic_nat_conn_table_oldest_row_age_seconds` | Gauge | — | Seconds since the least recently seen session in the table, expired ones included, last translated a packet. On a full table this is roughly how long an idle session lasts before the LRU evicts it. Absent while the table holds no sessions. | +| `galactic_nat_conn_table_max_entries` | Gauge | — | Capacity of `nat_conn_table` in rows, read from the loaded map. | +| `galactic_nat_drops_total` | Counter | `reason` | Packets dropped by the `nat_ingress` program, by reason. Cumulative for the life of the *node*, not the process: the counters live in a map pinned under `natattach.PinDir`, which a restarting shard reuses as-is. Always read it as a delta — an absolute value includes every transient the node has ever seen, and zeroing it takes `bpftool map update` against the pin directly. | + +A full table alone is not a problem. Alert when the table is full and its +oldest row is younger than the longest session timeout, 7440 s: idle +established TCP sessions are then evicted before they expire. + +```promql +sum by (node) (galactic_nat_conns) / on (node) galactic_nat_conn_table_max_entries > 0.9 + and on (node) galactic_nat_conn_table_oldest_row_age_seconds < 7440 +``` Drop reasons currently defined (`internal/plumbing/ebpf/natprog/dropreason.go`): @@ -552,8 +569,9 @@ knowing before you rely on this component in production: burst of tenant pings to many destinations can evict live TCP and UDP sessions. Eviction looks like `nat66_no_return_conn` or `nat64_no_return_conn` rising in step with ICMP traffic rather than with - any routing change — check `galactic_nat_conns` against the table's - capacity when that happens. The table is shared deliberately, not by + any routing change — check + `galactic_nat_conn_table_oldest_row_age_seconds` against the 7440 s TCP + timeout when that happens. The table is shared deliberately, not by omission; the datapath's `nat_conn_table` comment gives the reasoning. - **The ICMP rate limit is per CPU, not per shard or per peer.** Every reply the echo responder sends, and every Packet Too Big or Fragmentation diff --git a/internal/plumbing/ebpf/natmap/conntable.go b/internal/plumbing/ebpf/natmap/conntable.go index 463945013..8dd448dff 100644 --- a/internal/plumbing/ebpf/natmap/conntable.go +++ b/internal/plumbing/ebpf/natmap/conntable.go @@ -237,21 +237,111 @@ func (t *ConnTable) List() ([]ConnEntry, error) { return entries, nil } -// CountByFamily counts rows by their key's family. It reads no value field, so -// it does not depend on the value layout. +// Session protocols as CountSessions reports them. A row of any protocol other +// than TCP or UDP is an ICMP Echo session, matching the datapath's +// session_timeout, which gives every such row the ICMP timeout. +const ( + SessionProtoTCP = "tcp" + SessionProtoUDP = "udp" + SessionProtoICMP = "icmp" +) + +const ( + ipprotoTCP = 6 + ipprotoUDP = 17 + dnsPort = 53 +) + +// SessionKey groups live sessions by their key's family and their protocol. +type SessionKey struct { + Family uint8 + Proto string +} + +// SessionCounts is one walk of nat_conn_table. +type SessionCounts struct { + // Rows counts every row by its key's family, expired sessions included. + // A whole session holds two rows. + Rows map[uint8]int + + // Live counts reverse rows whose session has not expired, one per live + // session. + Live map[SessionKey]int + + // OldestAge is the largest age in seconds, now minus last_seen, of any + // reverse row, expired ones included. Expired rows stay until the LRU + // evicts them or a claim reuses their port, so on a full table this is + // roughly how long an idle row survives before eviction. HasReverse is + // false, and OldestAge zero, when the walk found no reverse row. + OldestAge uint32 + HasReverse bool +} + +// sessionProto names a row's protocol as SessionKey reports it. +func sessionProto(proto uint8) string { + switch proto { + case ipprotoTCP: + return SessionProtoTCP + case ipprotoUDP: + return SessionProtoUDP + default: + return SessionProtoICMP + } +} + +// sessionTimeout mirrors the datapath's session_timeout, in seconds. +func sessionTimeout(value *natprog.NatConnValue) uint32 { + switch value.Proto { + case ipprotoTCP: + if value.State&(natprog.SessionTCPEstablished|natprog.SessionTCPClosing) == natprog.SessionTCPEstablished { + return natprog.TimeoutTCPEstablished + } + return natprog.TimeoutTCPTransitory + case ipprotoUDP: + if beU16(value.DestPort) == dnsPort { + return natprog.TimeoutUDPDNS + } + return natprog.TimeoutUDP + default: + return natprog.TimeoutICMP + } +} + +// sessionExpired mirrors the datapath's session_expired. now is the datapath's +// clock: CLOCK_MONOTONIC in whole seconds, truncated to 32 bits. The +// subtraction wraps the same way, so a stamp from before the last wrap still +// reads as its true age. +func sessionExpired(value *natprog.NatConnValue, now uint32) bool { + return now-value.LastSeen > sessionTimeout(value) +} + +// CountSessions counts rows by family, and live sessions by family and +// protocol, as of now (see sessionExpired for its clock). Only a reverse row, +// whose key carries no encapsulation source, is checked for liveness: a forward +// row's last_seen records when it was written and is never refreshed. // // The datapath inserts and evicts rows during the walk, which can restart it // or cut it short. The counts gathered so far are returned alongside any error, // and are approximate either way. -func (t *ConnTable) CountByFamily() (map[uint8]int, error) { +func (t *ConnTable) CountSessions(now uint32) (SessionCounts, error) { var ( - counts = map[uint8]int{} + counts = SessionCounts{Rows: map[uint8]int{}, Live: map[SessionKey]int{}} rawKey natprog.NatConnKey value natprog.NatConnValue ) it := t.table.Iterate() for it.Next(&rawKey, &value) { - counts[rawKey.Family]++ + counts.Rows[rawKey.Family]++ + if rawKey.EncapSrc != ([16]byte{}) { + continue + } + if age := now - value.LastSeen; !counts.HasReverse || age > counts.OldestAge { + counts.OldestAge = age + } + counts.HasReverse = true + if !sessionExpired(&value, now) { + counts.Live[SessionKey{Family: rawKey.Family, Proto: sessionProto(value.Proto)}]++ + } } if err := it.Err(); err != nil { return counts, fmt.Errorf("natmap: nat_conn_table: count: %w", err) diff --git a/internal/plumbing/ebpf/natmap/conntable_test.go b/internal/plumbing/ebpf/natmap/conntable_test.go index bf3fa5f27..d8495d0ad 100644 --- a/internal/plumbing/ebpf/natmap/conntable_test.go +++ b/internal/plumbing/ebpf/natmap/conntable_test.go @@ -165,28 +165,160 @@ type abortingIterator struct{ Iterator } func (*abortingIterator) Err() error { return ebpf.ErrIterationAborted } -func TestConnTable_CountByFamily(t *testing.T) { - fake := newFakeTable() - for i, family := range []uint8{natprog.FamilyIPv6, natprog.FamilyIPv6, natprog.FamilyIPv4} { - e := testConnEntry() - e.Family = family - e.Sport = uint16(1000 + i) - putEntry(t, fake, e) +// sessionRow builds a reverse row: no encapsulation source, as the datapath +// writes one. destPort, state and lastSeen are the fields liveness reads. +func sessionRow(family, proto uint8, shardPort, destPort uint16, state uint8, lastSeen uint32) ConnEntry { + e := testConnEntry() + e.Family = family + e.Proto = proto + e.ConnKey.Proto = proto + e.TenantArg = 0 + e.Sport = 0 + e.Dport = shardPort + e.DestPort = destPort + e.State = state + e.LastSeen = lastSeen + return e +} + +func TestConnTable_CountSessions(t *testing.T) { + const now uint32 = 100_000 + est := natprog.SessionTCPEstablished + closing := natprog.SessionTCPEstablished | natprog.SessionTCPClosing + + tests := []struct { + name string + proto uint8 + destPort uint16 + state uint8 + age uint32 + live bool + }{ + {"udp live", 17, 443, 0, natprog.TimeoutUDP, true}, + {"udp expired", 17, 443, 0, natprog.TimeoutUDP + 1, false}, + {"udp dns live", 17, 53, 0, natprog.TimeoutUDPDNS, true}, + {"udp dns expired", 17, 53, 0, natprog.TimeoutUDPDNS + 1, false}, + {"tcp established live", 6, 443, est, natprog.TimeoutTCPEstablished, true}, + {"tcp established expired", 6, 443, est, natprog.TimeoutTCPEstablished + 1, false}, + {"tcp transitory live", 6, 443, 0, natprog.TimeoutTCPTransitory, true}, + {"tcp transitory expired", 6, 443, 0, natprog.TimeoutTCPTransitory + 1, false}, + {"tcp closing expired", 6, 443, closing, natprog.TimeoutTCPTransitory + 1, false}, + {"icmp live", 58, 0, 0, natprog.TimeoutICMP, true}, + {"icmp expired", 58, 0, 0, natprog.TimeoutICMP + 1, false}, + } + + for _, family := range []uint8{natprog.FamilyIPv6, natprog.FamilyIPv4} { + for _, tt := range tests { + t.Run(familyName(family)+"/"+tt.name, func(t *testing.T) { + fake := newFakeTable() + putEntry(t, fake, sessionRow(family, tt.proto, 35000, tt.destPort, tt.state, now-tt.age)) + + counts, err := NewConnTable(fake).CountSessions(now) + if err != nil { + t.Fatalf("CountSessions: %v", err) + } + want := 0 + if tt.live { + want = 1 + } + key := SessionKey{Family: family, Proto: sessionProto(tt.proto)} + if got := counts.Live[key]; got != want { + t.Errorf("Live[%v] = %d, want %d", key, got, want) + } + if counts.Rows[family] != 1 { + t.Errorf("Rows[%d] = %d, want 1 whether or not the session expired", family, counts.Rows[family]) + } + if !counts.HasReverse || counts.OldestAge != tt.age { + t.Errorf("OldestAge = %d (HasReverse %t), want %d", counts.OldestAge, counts.HasReverse, tt.age) + } + }) + } + } +} + +func familyName(family uint8) string { + if family == natprog.FamilyIPv4 { + return "nat64" } + return "nat66" +} + +func TestConnTable_CountSessionsMixedTable(t *testing.T) { + const now uint32 = 100_000 + fake := newFakeTable() + + // Two live sessions and three expired ones, as a busy DNS client leaves + // the table. + putEntry(t, fake, sessionRow(natprog.FamilyIPv6, 17, 35000, 53, 0, now-5)) + putEntry(t, fake, sessionRow(natprog.FamilyIPv6, 17, 35001, 53, 0, now-3600)) + putEntry(t, fake, sessionRow(natprog.FamilyIPv6, 17, 35002, 53, 0, now-600)) + putEntry(t, fake, sessionRow(natprog.FamilyIPv4, 6, 35003, 443, natprog.SessionTCPEstablished, now-7000)) + putEntry(t, fake, sessionRow(natprog.FamilyIPv4, 1, 35004, 0, 0, now-61)) - counts, err := NewConnTable(fake).CountByFamily() + // A forward row, keyed by its encapsulation source, whose last_seen is + // from when it was written: never live, never the oldest. + fwd := testConnEntry() + fwd.Family = natprog.FamilyIPv6 + fwd.EncapSrc = netip.MustParseAddr("fc00:3:4::1") + fwd.LastSeen = 1 + putEntry(t, fake, fwd) + + counts, err := NewConnTable(fake).CountSessions(now) if err != nil { - t.Fatalf("CountByFamily: %v", err) + t.Fatalf("CountSessions: %v", err) + } + wantLive := map[SessionKey]int{ + {Family: natprog.FamilyIPv6, Proto: SessionProtoUDP}: 1, + {Family: natprog.FamilyIPv4, Proto: SessionProtoTCP}: 1, } - if counts[natprog.FamilyIPv6] != 2 || counts[natprog.FamilyIPv4] != 1 { - t.Errorf("counts = %v, want 2 IPv6 and 1 IPv4", counts) + if len(counts.Live) != len(wantLive) { + t.Errorf("Live = %v, want %v", counts.Live, wantLive) + } + for k, v := range wantLive { + if counts.Live[k] != v { + t.Errorf("Live[%v] = %d, want %d", k, counts.Live[k], v) + } + } + if counts.Rows[natprog.FamilyIPv6] != 4 || counts.Rows[natprog.FamilyIPv4] != 2 { + t.Errorf("Rows = %v, want 4 IPv6 and 2 IPv4", counts.Rows) + } + if counts.OldestAge != 7000 { + t.Errorf("OldestAge = %d, want 7000 from the reverse rows alone", counts.OldestAge) } - counts, err = NewConnTable(abortingTable{fake}).CountByFamily() + counts, err = NewConnTable(abortingTable{fake}).CountSessions(now) if !errors.Is(err, ebpf.ErrIterationAborted) { - t.Fatalf("CountByFamily on an aborted walk: err = %v, want ErrIterationAborted", err) + t.Fatalf("CountSessions on an aborted walk: err = %v, want ErrIterationAborted", err) + } + if counts.Rows[natprog.FamilyIPv6] != 4 || counts.Rows[natprog.FamilyIPv4] != 2 { + t.Errorf("rows from an aborted walk = %v, want the rows seen before it ended", counts.Rows) + } +} + +func TestConnTable_CountSessionsClockWrap(t *testing.T) { + // The clock wrapped 10 s ago; the row was stamped 20 s before the wrap. + const now uint32 = 10 + fake := newFakeTable() + putEntry(t, fake, sessionRow(natprog.FamilyIPv6, 17, 35000, 53, 0, ^uint32(0)-19)) + + counts, err := NewConnTable(fake).CountSessions(now) + if err != nil { + t.Fatalf("CountSessions: %v", err) + } + if counts.OldestAge != 30 { + t.Errorf("OldestAge = %d, want 30 across the wrap", counts.OldestAge) + } + if got := counts.Live[SessionKey{Family: natprog.FamilyIPv6, Proto: SessionProtoUDP}]; got != 1 { + t.Errorf("a 30 s old DNS session across the wrap: live = %d, want 1", got) + } +} + +func TestConnTable_CountSessionsEmpty(t *testing.T) { + counts, err := NewConnTable(newFakeTable()).CountSessions(1) + if err != nil { + t.Fatalf("CountSessions: %v", err) } - if counts[natprog.FamilyIPv6] != 2 || counts[natprog.FamilyIPv4] != 1 { - t.Errorf("counts from an aborted walk = %v, want the rows seen before it ended", counts) + if counts.HasReverse || len(counts.Rows) != 0 || len(counts.Live) != 0 { + t.Errorf("counts on an empty table = %+v, want nothing", counts) } } From ea813c5e1c7b2772700ef66d3e3ee77b67cac661 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 5 Oct 2026 13:47:36 -0400 Subject: [PATCH 2/2] fix(nat): Count sessions refreshed during a scrape as live The scrape reads the session clock once and then walks up to 65536 rows while the datapath keeps refreshing last_seen on other CPUs. A row refreshed in the same second or later wrapped now - last_seen to about 2^32, so the busiest sessions read as expired and galactic_nat_conn_table_oldest_row_age_seconds jumped to about 4.29e9, which kept the eviction alert from firing on exactly the shards it is for. - An age whose wrapped difference is negative now reads as zero. Stamps from before a clock wrap still read as their true age, as in the datapath. - A failed clock read skips the session table series for that scrape instead of reporting every row as wrapped. The drop counters are still reported. - A collector without a session table reports none of its series, matching the capacity gauge, and a test pins that. - The oldest-row help text and docs say the age is an estimate, meaningful only on a near-full table. - Comments note that a forward row from an outer source of "::" would be counted as a session, and the NAT64 Echo test rows now carry ICMP in the key as the datapath writes it. Related to #731 Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-nat/metrics.go | 34 +++++++---- cmd/galactic-nat/metrics_test.go | 60 +++++++++++++++++-- docs/metrics.md | 17 +++--- docs/nat/configuration.md | 2 +- internal/plumbing/ebpf/natmap/conntable.go | 35 ++++++++--- .../plumbing/ebpf/natmap/conntable_test.go | 23 +++++++ 6 files changed, 138 insertions(+), 33 deletions(-) diff --git a/cmd/galactic-nat/metrics.go b/cmd/galactic-nat/metrics.go index 246b35618..a1938e080 100644 --- a/cmd/galactic-nat/metrics.go +++ b/cmd/galactic-nat/metrics.go @@ -30,18 +30,18 @@ type natCollector struct { // now reads the clock the datapath stamps last_seen with. Nil means // datapathNow. - now func() uint32 + now func() (uint32, error) } // datapathNow reads the datapath's session clock: bpf_ktime_get_ns is // CLOCK_MONOTONIC, which the datapath keeps in whole seconds truncated to 32 // bits (now_sec in nat.c). -func datapathNow() uint32 { +func datapathNow() (uint32, error) { var ts unix.Timespec if err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts); err != nil { - return 0 + return 0, fmt.Errorf("read CLOCK_MONOTONIC: %w", err) } - return uint32(ts.Sec) + return uint32(ts.Sec), nil //nolint:gosec // truncated to 32 bits, as the datapath's now_sec does } // newNatCollector builds a collector reading directly from a loaded object @@ -79,9 +79,10 @@ var ( oldestRowAgeDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "conn_table_oldest_row_age_seconds"), "Seconds since the least recently seen session in nat_conn_table last translated a packet, "+ - "expired sessions included. On a full table this approximates how long an idle session "+ - "survives before the LRU evicts it; below the longest session timeout, idle live sessions "+ - "are being evicted.", + "expired sessions included. Meaningful only while the table is near full: then it "+ + "approximates how long an idle session survives before the LRU evicts it, and a value "+ + "below the longest session timeout means idle live sessions are being evicted. On a "+ + "table with room it only grows.", nil, nil, ) connTableMaxEntriesDesc = prometheus.NewDesc( @@ -129,18 +130,29 @@ func familyLabel(family uint8) string { } } +// collectConns reports the session table's rows, live sessions and oldest row. +// A collector with no table, like one with no capacity, reports none of them; +// newNatCollector always sets one, so that happens only in tests. func (c *natCollector) collectConns(ch chan<- prometheus.Metric) { if c.connTable == nil { return } - now := c.now - if now == nil { - now = datapathNow + clock := c.now + if clock == nil { + clock = datapathNow + } + // Without the datapath's clock every row's age is meaningless, so the + // scrape skips these series rather than report wrong ones; the drop + // counters are still reported. + now, err := clock() + if err != nil { + slog.Warn("cannot read the session clock; skipping session table metrics", "err", err) + return } // A walk the datapath's own inserts and evictions disturbed still reports // what it counted: an error metric here fails the whole scrape, drops // included. - counts, err := c.connTable.CountSessions(now()) + counts, err := c.connTable.CountSessions(now) if err != nil { slog.Debug("nat_conn_table walk incomplete; reporting an approximate count", "err", err) } diff --git a/cmd/galactic-nat/metrics_test.go b/cmd/galactic-nat/metrics_test.go index b1dff701c..6223a88e2 100644 --- a/cmd/galactic-nat/metrics_test.go +++ b/cmd/galactic-nat/metrics_test.go @@ -64,14 +64,24 @@ func (it *connRowsIterator) Next(keyOut, valueOut any) bool { func (*connRowsIterator) Err() error { return nil } // reverseRow is a reverse row's wire key and value: no encapsulation source. -// destPort is in host order. +// proto is the tenant's protocol, which the value carries; a NAT64 Echo +// session's key holds ICMP instead, as the datapath writes it. destPort is in +// host order. func reverseRow( family, proto uint8, shardPort, destPort uint16, lastSeen uint32, ) (natprog.NatConnKey, natprog.NatConnValue) { - return natprog.NatConnKey{Family: family, Proto: proto, Dport: shardPort}, + keyProto := proto + if family == natprog.FamilyIPv4 && proto == 58 { + keyProto = 1 + } + return natprog.NatConnKey{Family: family, Proto: keyProto, Dport: shardPort}, natprog.NatConnValue{Proto: proto, DestPort: destPort<<8 | destPort>>8, LastSeen: lastSeen} } +func fixedClock(now uint32) func() (uint32, error) { + return func() (uint32, error) { return now, nil } +} + // gatherGauges registers c and returns every gauge by metric name, each keyed // by its label values joined with "/". func gatherGauges(t *testing.T, c prometheus.Collector) (map[string]map[string]float64, map[string]string) { @@ -117,7 +127,7 @@ func TestNatCollectorCountsLiveSessions(t *testing.T) { rows.add(natprog.NatConnKey{Family: natprog.FamilyIPv6, Proto: 17, EncapSrc: [16]byte{0xfc}}, natprog.NatConnValue{Proto: 17, LastSeen: 1}) - c := &natCollector{connTable: natmap.NewConnTable(rows), now: func() uint32 { return now }} + c := &natCollector{connTable: natmap.NewConnTable(rows), now: fixedClock(now)} gauges, help := gatherGauges(t, c) wantConns := map[string]float64{familyNAT66: 4, familyNAT64: 1} @@ -144,7 +154,7 @@ func TestNatCollectorCountsLiveSessions(t *testing.T) { } func TestNatCollectorEmptyConnTable(t *testing.T) { - c := &natCollector{connTable: natmap.NewConnTable(&connRows{}), now: func() uint32 { return 1 }} + c := &natCollector{connTable: natmap.NewConnTable(&connRows{}), now: fixedClock(1)} gauges, _ := gatherGauges(t, c) if len(gauges[connsName]) != 2 || len(gauges[sessionsName]) != 6 { @@ -203,6 +213,48 @@ func TestNatCollectorReportsMaxEntriesAsGauge(t *testing.T) { } } +func TestNatCollectorSessionRefreshedMidWalk(t *testing.T) { + // The datapath refreshed this session after the scrape read its clock. + const now uint32 = 50_000 + rows := &connRows{} + rows.add(reverseRow(natprog.FamilyIPv6, 6, 35000, 443, now+1)) + + c := &natCollector{connTable: natmap.NewConnTable(rows), now: fixedClock(now)} + gauges, _ := gatherGauges(t, c) + + if got := gauges[sessionsName]["nat66/tcp"]; got != 1 { + t.Errorf("session refreshed mid-walk: %s{nat66,tcp} = %v, want 1", sessionsName, got) + } + if got := gauges[oldestRowAgeName][""]; got != 0 { + t.Errorf("session refreshed mid-walk: %s = %v, want 0", oldestRowAgeName, got) + } +} + +func TestNatCollectorSkipsSessionsWithoutClock(t *testing.T) { + rows := &connRows{} + rows.add(reverseRow(natprog.FamilyIPv6, 17, 35000, 53, 1)) + c := &natCollector{ + connTable: natmap.NewConnTable(rows), + now: func() (uint32, error) { return 0, errors.New("no clock") }, + } + gauges, _ := gatherGauges(t, c) + + for _, name := range []string{connsName, sessionsName, oldestRowAgeName} { + if _, ok := gauges[name]; ok { + t.Errorf("%s reported without the session clock", name) + } + } +} + +func TestNatCollectorOmitsSessionsWithoutTable(t *testing.T) { + ch := make(chan prometheus.Metric, 16) + (&natCollector{}).collectConns(ch) + close(ch) + for m := range ch { + t.Errorf("unexpected metric without a session table: %s", m.Desc()) + } +} + func requireRoot(t *testing.T) { t.Helper() if os.Geteuid() != 0 { diff --git a/docs/metrics.md b/docs/metrics.md index db70cfeee..a01d33462 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -225,13 +225,13 @@ sum by (controller) (rate(controller_runtime_reconcile_errors_total{job=~"galact One `galactic-nat` pod per egress shard; every value is per shard. -| Metric | Type | Labels | Meaning | -|--------------------------------------------------|---------|------------------------------------------|------------------------------------------------------------------------------------------------| -| `galactic_nat_conns` | gauge | `family` (`nat66`, `nat64`) | Rows in the connection table, expired sessions included. A session holds two rows | -| `galactic_nat_sessions` | gauge | `family`, `proto` (`tcp`, `udp`, `icmp`) | Live sessions: one per session within its idle timeout | -| `galactic_nat_conn_table_oldest_row_age_seconds` | gauge | none | Seconds since the least recently seen session, expired ones included, last translated a packet | -| `galactic_nat_conn_table_max_entries` | gauge | none | Table capacity in rows, shared by both families | -| `galactic_nat_drops_total` | counter | `reason` | Packets dropped by the NAT datapath | +| Metric | Type | Labels | Meaning | +|--------------------------------------------------|---------|------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------| +| `galactic_nat_conns` | gauge | `family` (`nat66`, `nat64`) | Rows in the connection table, expired sessions included. A session holds two rows | +| `galactic_nat_sessions` | gauge | `family`, `proto` (`tcp`, `udp`, `icmp`) | Live sessions: one per session within its idle timeout | +| `galactic_nat_conn_table_oldest_row_age_seconds` | gauge | none | Seconds since the least recently seen session, expired ones included, last translated a packet. Meaningful only on a near-full table | +| `galactic_nat_conn_table_max_entries` | gauge | none | Table capacity in rows, shared by both families | +| `galactic_nat_drops_total` | counter | `reason` | Packets dropped by the NAT datapath | Caveats for the session table: @@ -239,7 +239,8 @@ Caveats for the session table: reuses their port, so `galactic_nat_conns` sits near capacity on any busy shard. That is normal. Use `galactic_nat_sessions` for live sessions. - Live sessions are at risk only when the table is full and its oldest row is - younger than the longest session timeout, 7440 s for established TCP. + younger than the longest session timeout, 7440 s for established TCP. The + table's LRU evicts in approximate order, so the age is an estimate. - The table is a self-evicting LRU, so the counts can move without traffic changing. diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index f88410641..3f8e69d3c 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -442,7 +442,7 @@ Metrics, exposed on `GALACTIC_NAT_METRICS_PORT` (`9182` by default): | ------------------------------------------------ | ------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `galactic_nat_conns` | Gauge | `family` | Rows in this shard's `nat_conn_table`, expired sessions included. A session holds two rows. Expect it near capacity on a busy shard; see [Session table](#session-table). | | `galactic_nat_sessions` | Gauge | `family`, `proto` | Live sessions, one per session within its idle timeout. `proto` is `tcp`, `udp` or `icmp`. Every series is reported, at zero when empty. | -| `galactic_nat_conn_table_oldest_row_age_seconds` | Gauge | — | Seconds since the least recently seen session in the table, expired ones included, last translated a packet. On a full table this is roughly how long an idle session lasts before the LRU evicts it. Absent while the table holds no sessions. | +| `galactic_nat_conn_table_oldest_row_age_seconds` | Gauge | — | Seconds since the least recently seen session in the table, expired ones included, last translated a packet. On a near-full table it approximates how long an idle session lasts before the LRU evicts it; on a table with room it only grows. Absent while the table holds no sessions. | | `galactic_nat_conn_table_max_entries` | Gauge | — | Capacity of `nat_conn_table` in rows, read from the loaded map. | | `galactic_nat_drops_total` | Counter | `reason` | Packets dropped by the `nat_ingress` program, by reason. Cumulative for the life of the *node*, not the process: the counters live in a map pinned under `natattach.PinDir`, which a restarting shard reuses as-is. Always read it as a delta — an absolute value includes every transient the node has ever seen, and zeroing it takes `bpftool map update` against the pin directly. | diff --git a/internal/plumbing/ebpf/natmap/conntable.go b/internal/plumbing/ebpf/natmap/conntable.go index 8dd448dff..c7cfc95db 100644 --- a/internal/plumbing/ebpf/natmap/conntable.go +++ b/internal/plumbing/ebpf/natmap/conntable.go @@ -307,18 +307,35 @@ func sessionTimeout(value *natprog.NatConnValue) uint32 { } } -// sessionExpired mirrors the datapath's session_expired. now is the datapath's -// clock: CLOCK_MONOTONIC in whole seconds, truncated to 32 bits. The -// subtraction wraps the same way, so a stamp from before the last wrap still -// reads as its true age. +// rowAge is how many seconds before now a row was last seen. now is the +// datapath's clock: CLOCK_MONOTONIC in whole seconds, truncated to 32 bits. The +// subtraction wraps as the datapath's does, so a stamp from before the last +// wrap still reads as its true age. +// +// Unlike the datapath, a stamp after now reads as age zero. The walk reads now +// once and then takes a while, and the datapath keeps refreshing rows on other +// CPUs meanwhile; without the clamp, a session refreshed mid-walk would wrap to +// an age of about 2^32 seconds and read as long expired. +func rowAge(lastSeen, now uint32) uint32 { + age := now - lastSeen + if int32(age) < 0 { //nolint:gosec // reinterpreting the wrapped difference is the point + return 0 + } + return age +} + +// sessionExpired mirrors the datapath's session_expired, with rowAge's clamp. func sessionExpired(value *natprog.NatConnValue, now uint32) bool { - return now-value.LastSeen > sessionTimeout(value) + return rowAge(value.LastSeen, now) > sessionTimeout(value) } // CountSessions counts rows by family, and live sessions by family and -// protocol, as of now (see sessionExpired for its clock). Only a reverse row, -// whose key carries no encapsulation source, is checked for liveness: a forward -// row's last_seen records when it was written and is never refreshed. +// protocol, as of now (see rowAge for its clock). Only a reverse row, whose key +// carries no encapsulation source, is checked for liveness: a forward row's +// last_seen records when it was written and is never refreshed. The datapath +// copies a forward row's encapsulation source from the packet's outer header, +// so a packet sent from "::" would leave a forward row that is counted here as a +// session; no legitimate fabric node sends from that address. // // The datapath inserts and evicts rows during the walk, which can restart it // or cut it short. The counts gathered so far are returned alongside any error, @@ -335,7 +352,7 @@ func (t *ConnTable) CountSessions(now uint32) (SessionCounts, error) { if rawKey.EncapSrc != ([16]byte{}) { continue } - if age := now - value.LastSeen; !counts.HasReverse || age > counts.OldestAge { + if age := rowAge(value.LastSeen, now); !counts.HasReverse || age > counts.OldestAge { counts.OldestAge = age } counts.HasReverse = true diff --git a/internal/plumbing/ebpf/natmap/conntable_test.go b/internal/plumbing/ebpf/natmap/conntable_test.go index d8495d0ad..a89a9d2a9 100644 --- a/internal/plumbing/ebpf/natmap/conntable_test.go +++ b/internal/plumbing/ebpf/natmap/conntable_test.go @@ -172,6 +172,11 @@ func sessionRow(family, proto uint8, shardPort, destPort uint16, state uint8, la e.Family = family e.Proto = proto e.ConnKey.Proto = proto + // A NAT64 Echo session's value holds the tenant's ICMPv6, its reverse key + // the peer's ICMP. + if family == natprog.FamilyIPv4 && proto == 58 { + e.ConnKey.Proto = 1 + } e.TenantArg = 0 e.Sport = 0 e.Dport = shardPort @@ -313,6 +318,24 @@ func TestConnTable_CountSessionsClockWrap(t *testing.T) { } } +func TestConnTable_CountSessionsRefreshedMidWalk(t *testing.T) { + // The datapath refreshed the session after the walk read now. + const now uint32 = 100_000 + fake := newFakeTable() + putEntry(t, fake, sessionRow(natprog.FamilyIPv6, 6, 35000, 443, 0, now+1)) + + counts, err := NewConnTable(fake).CountSessions(now) + if err != nil { + t.Fatalf("CountSessions: %v", err) + } + if got := counts.Live[SessionKey{Family: natprog.FamilyIPv6, Proto: SessionProtoTCP}]; got != 1 { + t.Errorf("session stamped after now: live = %d, want 1", got) + } + if counts.OldestAge != 0 { + t.Errorf("session stamped after now: OldestAge = %d, want 0", counts.OldestAge) + } +} + func TestConnTable_CountSessionsEmpty(t *testing.T) { counts, err := NewConnTable(newFakeTable()).CountSessions(1) if err != nil {