diff --git a/cmd/galactic-gateway/dispatch_test.go b/cmd/galactic-gateway/dispatch_test.go index 5448cf665..6907a2a01 100644 --- a/cmd/galactic-gateway/dispatch_test.go +++ b/cmd/galactic-gateway/dispatch_test.go @@ -94,7 +94,7 @@ type gatewayProcess struct { func startGateway(t *testing.T, d pinDirs) gatewayProcess { t.Helper() ctx, cancel := context.WithCancel(context.Background()) - objs, dispatcher, public, _, leaseDone, err := joinDispatcher(ctx, d.dispatch, d.edge, false) + objs, dispatcher, public, _, leaseDone, err := joinDispatcher(ctx, d.dispatch, d.edge, false, nil) if err != nil { cancel() t.Fatalf("gateway joinDispatcher: %v", err) diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 211667bda..d85b64f0b 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -145,8 +145,13 @@ func setupGatewayDatapath( if attachMode == config.GatewayXDPAttachDispatch { leaseCtx, stopLeases := context.WithCancel(ctx) var leaseDone <-chan struct{} + lease := xdpdispatch.NewLeaseMetrics(edgemetrics.Namespace) + if err := lease.Register(metricsReg); err != nil { + stopLeases() + return nil, fmt.Errorf("register dispatcher lease metrics: %w", err) + } objs, dispatcher, publicSet, returnSet, leaseDone, err = joinDispatcher(leaseCtx, xdpdispatch.PinDir, - edgeattach.PinDir, len(returnTargets) > 0) + edgeattach.PinDir, len(returnTargets) > 0, lease) if err != nil { stopLeases() return nil, err @@ -273,7 +278,9 @@ func attachDirect(ctx context.Context, dispatchDir, edgeDir string, targets, ret // the returned sets put the dispatcher on the targets and read coverage back. // The returned channel closes once both lease loops have stopped, which a // caller waits on before closing the dispatcher. -func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn bool) ( +func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn bool, + lease *xdpdispatch.LeaseMetrics, +) ( *edgeprog.EdgedsrObjects, *xdpdispatch.Dispatcher, targetSet, targetSet, <-chan struct{}, error, ) { dispatcher, err := xdpdispatch.Open(ctx, dispatchDir) @@ -326,10 +333,10 @@ func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn var leases sync.WaitGroup for _, slot := range []xdpdispatch.Slot{xdpdispatch.SlotGatewayLB, xdpdispatch.SlotGatewayReturn} { leases.Go(func() { - dispatcher.Lease(ctx, slot, func(err error) { + dispatcher.Lease(ctx, slot, lease.Observe(slot, func(err error) { slog.Error("Cannot renew an edge gateway slot's lease in the XDP dispatcher; "+ "the dispatcher skips the slot once it lapses", "slot", slot, "err", err) - }) + })) }) } leaseDone := make(chan struct{}) diff --git a/cmd/galactic-nat/dispatch_test.go b/cmd/galactic-nat/dispatch_test.go index 5fa358211..d2c0a2bec 100644 --- a/cmd/galactic-nat/dispatch_test.go +++ b/cmd/galactic-nat/dispatch_test.go @@ -94,7 +94,7 @@ func joinForTest(t *testing.T, dispatchDir string, program *ebpf.Program) (*xdpd ) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) - d, set, leaseDone, err := joinDispatcher(ctx, dispatchDir, program) + d, set, leaseDone, err := joinDispatcher(ctx, dispatchDir, program, nil) if err != nil { cancel() t.Fatalf("joinDispatcher: %v", err) diff --git a/cmd/galactic-nat/metrics.go b/cmd/galactic-nat/metrics.go index 030c44904..547127cff 100644 --- a/cmd/galactic-nat/metrics.go +++ b/cmd/galactic-nat/metrics.go @@ -7,6 +7,8 @@ package main import ( "fmt" "log/slog" + "maps" + "net/netip" "github.com/cilium/ebpf" "github.com/prometheus/client_golang/prometheus" @@ -22,6 +24,9 @@ const metricsNamespace = "galactic_nat" // familyNAT64. const labelFamily = "family" +// masqueradeLabels label the masquerade port series. +var masqueradeLabels = []string{labelFamily, "address", "proto"} + // trafficLabels label the translated-traffic series. var trafficLabels = []string{labelFamily, "direction", "action"} @@ -36,6 +41,10 @@ type natCollector struct { dropReasons natmap.DropReasonsReader traffic natmap.TrafficReader + // shardConfig names the masquerade addresses whose port usage is always + // reported, zero included. Nil reports only the addresses rows hold. + shardConfig *natmap.ShardConfigTable + // now reads the clock the datapath stamps last_seen with. Nil means // datapathNow. now func() (uint32, error) @@ -60,6 +69,7 @@ func newNatCollector(objs *natprog.NatObjects) *natCollector { connMaxEntries: mapMaxEntries(objs.NatConnTable), dropReasons: objs.DropReasons, traffic: objs.NatTraffic, + shardConfig: natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}), } } @@ -113,6 +123,26 @@ var ( "without the Ethernet header or the SRv6 outer header a return packet carries.", trafficLabels, nil, ) + portsInUseDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "masquerade", "ports_in_use"), + "Distinct masquerade ports live sessions hold on this masquerade address and protocol, toward any "+ + "destination. A port is claimed per destination address and port, so this can sit near "+ + "galactic_nat_masquerade_port_range on a healthy shard; see "+ + "galactic_nat_masquerade_destination_ports_max for exhaustion.", + masqueradeLabels, nil, + ) + destinationPortsMaxDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "masquerade", "destination_ports_max"), + "The most masquerade ports live sessions hold toward any single destination address and port, on this "+ + "masquerade address and protocol. New flows to that destination start failing as it approaches "+ + "galactic_nat_masquerade_port_range.", + masqueradeLabels, nil, + ) + portRangeDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "masquerade", "port_range"), + "Masquerade ports (or ICMP Echo Identifiers) available toward each destination address and port.", + nil, nil, + ) dropsDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "drops_total"), "Packets dropped by this shard's datapath, by reason (drop_reasons map).", @@ -129,6 +159,9 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) { ch <- dropsDesc ch <- packetsDesc ch <- bytesDesc + ch <- portsInUseDesc + ch <- destinationPortsMaxDesc + ch <- portRangeDesc } // Collect implements prometheus.Collector. @@ -173,6 +206,7 @@ func (c *natCollector) collectConns(ch chan<- prometheus.Metric) { now, err := clock() if err != nil { slog.Warn("cannot read the session clock; skipping session table metrics", "err", err) + ch <- prometheus.MustNewConstMetric(portRangeDesc, prometheus.GaugeValue, float64(natprog.PATPortRange)) return } // A walk the datapath's own inserts and evictions disturbed still reports @@ -209,6 +243,41 @@ func (c *natCollector) collectConns(ch chan<- prometheus.Metric) { if counts.HasReverse { ch <- prometheus.MustNewConstMetric(oldestRowAgeDesc, prometheus.GaugeValue, float64(counts.OldestAge)) } + + c.collectPorts(ch, counts.Ports) +} + +// collectPorts reports port usage for every masquerade address and protocol +// the programmed identity serves, zero included, and for any other address +// live rows still hold, such as one a re-programmed identity replaced. +func (c *natCollector) collectPorts(ch chan<- prometheus.Metric, usage map[natmap.MasqueradeKey]natmap.PortUsage) { + ch <- prometheus.MustNewConstMetric(portRangeDesc, prometheus.GaugeValue, float64(natprog.PATPortRange)) + + all := map[natmap.MasqueradeKey]natmap.PortUsage{} + if c.shardConfig != nil { + if cfg, ok, err := c.shardConfig.Get(); err != nil { + slog.Debug("cannot read shard_config_table; reporting port usage only for held addresses", "err", err) + } else if ok { + for _, served := range []struct { + family uint8 + addr netip.Addr + }{{natprog.FamilyIPv6, cfg.ShardPubAddr6}, {natprog.FamilyIPv4, cfg.ShardPubAddr4}} { + if !served.addr.IsValid() { + continue + } + for _, proto := range []string{natmap.SessionProtoTCP, natmap.SessionProtoUDP, natmap.SessionProtoICMP} { + all[natmap.MasqueradeKey{Family: served.family, Address: served.addr, Proto: proto}] = natmap.PortUsage{} + } + } + } + } + maps.Copy(all, usage) + for key, u := range all { + labels := []string{familyLabel(key.Family), key.Address.String(), key.Proto} + ch <- prometheus.MustNewConstMetric(portsInUseDesc, prometheus.GaugeValue, float64(u.InUse), labels...) + ch <- prometheus.MustNewConstMetric(destinationPortsMaxDesc, prometheus.GaugeValue, + float64(u.MaxPerDestination), labels...) + } } func (c *natCollector) collectConnTableMaxEntries(ch chan<- prometheus.Metric) { diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 62c051f53..0ba2b0559 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -325,7 +325,12 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, case config.NATXDPAttachDispatch: // The lease runs for the life of the process, so its done channel // is not needed here. - if dispatcher, dispatchSet, _, err = joinDispatcher(ctx, xdpdispatch.PinDir, objs.NatIngress); err != nil { + lease := xdpdispatch.NewLeaseMetrics(metricsNamespace) + if err := lease.Register(metricsReg); err != nil { + _ = objs.Close() + return nil, fmt.Errorf("register dispatcher lease metrics: %w", err) + } + if dispatcher, dispatchSet, _, err = joinDispatcher(ctx, xdpdispatch.PinDir, objs.NatIngress, lease); err != nil { _ = objs.Close() return nil, err } @@ -389,11 +394,12 @@ func registerUplinkQueueStats(metricsReg prometheus.Registerer, d *natDatapath) } // joinDispatcher opens the node's XDP dispatcher, fills this shard's slot with -// program, and starts renewing the slot's lease for the life of ctx. It +// program, and starts renewing the slot's lease for the life of ctx, recording +// each renewal in lease, which may be nil. It // returns the set that keeps the dispatcher on the uplinks, and a channel // closed once the lease loop has stopped, which a caller waits on before // closing the dispatcher. -func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program) ( +func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program, lease *xdpdispatch.LeaseMetrics) ( *xdpdispatch.Dispatcher, *xdpattach.DispatchSet, <-chan struct{}, error, ) { dispatcher, err := xdpdispatch.Open(ctx, pinDir) @@ -422,10 +428,10 @@ func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program) ( leaseDone := make(chan struct{}) go func() { defer close(leaseDone) - dispatcher.Lease(ctx, xdpdispatch.SlotNAT, func(err error) { + dispatcher.Lease(ctx, xdpdispatch.SlotNAT, lease.Observe(xdpdispatch.SlotNAT, func(err error) { slog.Error("Cannot renew the egress translation slot's lease in the XDP dispatcher; "+ "the dispatcher skips the slot once it lapses", "err", err) - }) + })) }() slog.Info("Egress translation datapath installed in the XDP dispatcher", "pinDir", pinDir) return dispatcher, set, leaseDone, nil diff --git a/cmd/galactic-nat/ports_test.go b/cmd/galactic-nat/ports_test.go new file mode 100644 index 000000000..6fc678826 --- /dev/null +++ b/cmd/galactic-nat/ports_test.go @@ -0,0 +1,107 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "errors" + "net/netip" + "reflect" + "testing" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/natmap" + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" +) + +// memTable is an in-memory natmap.Table keyed by any comparable key. +type memTable map[any]any + +func (m memTable) Put(key, value any) error { m[key] = value; return nil } +func (m memTable) Lookup(key, valueOut any) error { + v, ok := m[key] + if !ok { + return ebpf.ErrKeyNotExist + } + reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(v)) + return nil +} +func (m memTable) Delete(key any) error { delete(m, key); return nil } +func (memTable) Iterate() natmap.Iterator { return &connRowsIterator{rows: &connRows{}, idx: -1} } + +func TestNatCollectorReportsMasqueradePorts(t *testing.T) { + const now uint32 = 100_000 + shardConfig := natmap.NewShardConfigTable(memTable{}) + if err := shardConfig.Set(natmap.ShardConfig{ + ShardSID: netip.MustParseAddr("fc00:1:2::1"), + ShardPubAddr6: netip.MustParseAddr("2001:db8:9966::1"), + }); err != nil { + t.Fatalf("Set: %v", err) + } + + var rows connRows + peerPort := uint16(443) + for _, port := range []uint16{35000, 35001} { + key, value := reverseRow(natprog.FamilyIPv6, 17, port, 443, now) + key.Daddr = netip.MustParseAddr("2001:db8:9966::1").As16() + key.Saddr = netip.MustParseAddr("2001:db8:1::1").As16() + key.Sport = peerPort<<8 | peerPort>>8 + rows.add(key, value) + } + + c := &natCollector{ + connTable: natmap.NewConnTable(&rows), + now: fixedClock(now), + shardConfig: shardConfig, + } + got := gatherAll(t, c) + + if v := got["galactic_nat_masquerade_port_range"][""]; v != float64(natprog.PATPortRange) { + t.Errorf("port range = %v, want %d", v, natprog.PATPortRange) + } + inUse := got["galactic_nat_masquerade_ports_in_use"] + maxDest := got["galactic_nat_masquerade_destination_ports_max"] + // Labels sort as address/family/proto. The served IPv6 address is reported + // for every protocol, zero included; the unserved IPv4 family not at all. + want := map[string]float64{ + "2001:db8:9966::1/nat66/udp": 2, + "2001:db8:9966::1/nat66/tcp": 0, + "2001:db8:9966::1/nat66/icmp": 0, + } + if !reflect.DeepEqual(inUse, want) { + t.Errorf("ports_in_use = %v, want %v", inUse, want) + } + if !reflect.DeepEqual(maxDest, want) { + t.Errorf("destination_ports_max = %v, want %v", maxDest, want) + } +} + +// Without the session clock no row's liveness is known, so the per-address +// port series are left out rather than reported as zeros an idle shard would +// show. The range, which needs no clock, is still reported. +func TestNatCollectorPortsWithoutClock(t *testing.T) { + shardConfig := natmap.NewShardConfigTable(memTable{}) + if err := shardConfig.Set(natmap.ShardConfig{ + ShardSID: netip.MustParseAddr("fc00:1:2::1"), + ShardPubAddr6: netip.MustParseAddr("2001:db8:9966::1"), + }); err != nil { + t.Fatalf("Set: %v", err) + } + c := &natCollector{ + connTable: natmap.NewConnTable(&connRows{}), + now: func() (uint32, error) { return 0, errors.New("no clock") }, + shardConfig: shardConfig, + } + got := gatherAll(t, c) + if _, ok := got["galactic_nat_masquerade_ports_in_use"]; ok { + t.Error("reported ports_in_use without a clock; zeros would read as an idle shard") + } + if _, ok := got["galactic_nat_masquerade_destination_ports_max"]; ok { + t.Error("reported destination_ports_max without a clock") + } + if got["galactic_nat_masquerade_port_range"][""] != float64(natprog.PATPortRange) { + t.Error("port range missing without a clock") + } +} diff --git a/config/monitoring/prometheusrule.yaml b/config/monitoring/prometheusrule.yaml index a6dbdff51..1a4509310 100644 --- a/config/monitoring/prometheusrule.yaml +++ b/config/monitoring/prometheusrule.yaml @@ -439,6 +439,66 @@ spec: Compute nodes have encapsulated tenant traffic toward {{ $labels.shard_sid }} for 10 minutes, but the shard on {{ $labels.node }} translated none of it outbound. Check galactic_nat_uplink_covered, galactic_nat_datapath_attached and the shard's XDP attachment. + # A claim needs a free port toward one destination address and port, + # and probes 8 of the range's candidates. With a share u of that + # destination's ports held, a new flow fails with probability about + # u^8: 0.4% at half full, 1.7% at 60%, 17% at 80%. Half full is the + # last point before GalacticNatPortExhausted's drops become routine, + # so this warns while new flows still almost always succeed. + - alert: GalacticNatPortsNearExhaustion + expr: >- + max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max{job="galactic-nat"}) + / on (node) group_left () max by (node) (galactic_nat_masquerade_port_range{job="galactic-nat"}) > 0.5 + for: 10m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "Masquerade {{ $labels.proto }} ports on {{ $labels.address }} are {{ $value | humanizePercentage }} used toward one destination" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatportsnearexhaustion" + description: >- + The egress shard on {{ $labels.node }} holds {{ $value | humanizePercentage }} of the {{ $labels.proto }} + ports on {{ $labels.address }} toward a single destination for 10 minutes. New flows to that destination + start failing as this approaches 100%, with GalacticNatPortExhausted. + # The lease is renewed every 10s for 120s, so it survives 11 failed + # renewals in a row. More than two failures in every 5-minute window + # means renewals keep failing, well before the lease is at risk. + - alert: GalacticNatDispatchLeaseFailing + expr: >- + increase(galactic_nat_dispatch_lease_renewals_total{job="galactic-nat", result="error"}[5m]) > 2 + for: 5m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "The egress shard on {{ $labels.node }} cannot renew its XDP dispatcher lease" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatdispatchleasefailing" + description: >- + galactic-nat on {{ $labels.node }} has failed to renew its {{ $labels.slot }} slot's lease in the XDP + dispatcher more than twice in every 5-minute window for 5 minutes. Once the lease expires the + dispatcher skips the slot and tenant traffic leaves untranslated. The shard's log names the error. + # No successful renewal in two minutes means the 120s lease has lapsed + # or is about to. Read from the renewal counter rather than the expiry + # timestamp, which would compare the node's clock with the evaluator's + # and page on skew alone; a two-minute window holds four samples at + # the 30s scrape, so jitter cannot empty it. + - alert: GalacticNatDispatchLeaseExpiring + expr: >- + changes(galactic_nat_dispatch_lease_renewals_total{job="galactic-nat", result="success"}[2m]) == 0 + for: 0s + labels: + severity: critical + service: galactic + team: connect + annotations: + summary: "The egress shard's XDP dispatcher lease on {{ $labels.node }} has lapsed or is about to" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatdispatchleaseexpiring" + description: >- + galactic-nat on {{ $labels.node }} has not renewed its {{ $labels.slot }} slot lease for two minutes, + so the 120-second lease has lapsed or is about to. The dispatcher skips a lapsed slot, so the shard's + uplinks pass tenant traffic untranslated. - alert: GalacticNatMetricsDown expr: up{job="galactic-nat"} == 0 for: 5m diff --git a/config/monitoring/tests/rules-test.yaml b/config/monitoring/tests/rules-test.yaml index ae98c1efb..0213d4195 100644 --- a/config/monitoring/tests/rules-test.yaml +++ b/config/monitoring/tests/rules-test.yaml @@ -1304,3 +1304,90 @@ tests: Compute nodes have encapsulated tenant traffic toward fc00:1:2:: for 10 minutes, but the shard on dfw-worker2 translated none of it outbound. Check galactic_nat_uplink_covered, galactic_nat_datapath_attached and the shard's XDP attachment. + + # dfw-worker2's busiest destination holds 15400 of 28000 UDP ports (55%) + # for 10m and fires. sjc-worker2's holds 40% and does not. + - interval: 30s + input_series: + - series: 'galactic_nat_masquerade_destination_ports_max{job="galactic-nat",node="dfw-worker2",family="nat66",address="2001:db8:9966::1",proto="udp"}' + values: "15400x30" + - series: 'galactic_nat_masquerade_port_range{job="galactic-nat",node="dfw-worker2"}' + values: "28000x30" + - series: 'galactic_nat_masquerade_destination_ports_max{job="galactic-nat",node="sjc-worker2",family="nat66",address="2001:db8:9967::1",proto="udp"}' + values: "11200x30" + - series: 'galactic_nat_masquerade_port_range{job="galactic-nat",node="sjc-worker2"}' + values: "28000x30" + alert_rule_test: + - eval_time: 12m + alertname: GalacticNatPortsNearExhaustion + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + node: dfw-worker2 + family: nat66 + address: "2001:db8:9966::1" + proto: udp + exp_annotations: + summary: "Masquerade udp ports on 2001:db8:9966::1 are 55% used toward one destination" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatportsnearexhaustion" + description: >- + The egress shard on dfw-worker2 holds 55% of the udp + ports on 2001:db8:9966::1 toward a single destination for 10 minutes. New flows to that destination + start failing as this approaches 100%, with GalacticNatPortExhausted. + + # dfw-worker2 renews every 10s until 5m, then every renewal fails, 3 errors + # per 30s. Expiring fires once no renewal has succeeded for 2m; failing + # fires after 5m of more than two errors per window. sjc-worker2 keeps + # renewing and has one transient error, which fires neither. + - interval: 30s + input_series: + - series: 'galactic_nat_dispatch_lease_renewals_total{job="galactic-nat",node="dfw-worker2",slot="nat",result="error"}' + values: "0x10 0+3x20" + - series: 'galactic_nat_dispatch_lease_renewals_total{job="galactic-nat",node="dfw-worker2",slot="nat",result="success"}' + values: "0+3x10 30x20" + - series: 'galactic_nat_dispatch_lease_renewals_total{job="galactic-nat",node="sjc-worker2",slot="nat",result="error"}' + values: "0x10 1x20" + - series: 'galactic_nat_dispatch_lease_renewals_total{job="galactic-nat",node="sjc-worker2",slot="nat",result="success"}' + values: "0+3x30" + alert_rule_test: + - eval_time: 6m + alertname: GalacticNatDispatchLeaseExpiring + exp_alerts: [] + - eval_time: 8m + alertname: GalacticNatDispatchLeaseExpiring + exp_alerts: + - exp_labels: + severity: critical + service: galactic + team: connect + job: galactic-nat + node: dfw-worker2 + slot: nat + result: success + exp_annotations: + summary: "The egress shard's XDP dispatcher lease on dfw-worker2 has lapsed or is about to" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatdispatchleaseexpiring" + description: >- + galactic-nat on dfw-worker2 has not renewed its nat slot lease for two minutes, + so the 120-second lease has lapsed or is about to. The dispatcher skips a lapsed slot, so the shard's + uplinks pass tenant traffic untranslated. + - eval_time: 12m + alertname: GalacticNatDispatchLeaseFailing + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + job: galactic-nat + node: dfw-worker2 + slot: nat + result: error + exp_annotations: + summary: "The egress shard on dfw-worker2 cannot renew its XDP dispatcher lease" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatdispatchleasefailing" + description: >- + galactic-nat on dfw-worker2 has failed to renew its nat slot's lease in the XDP + dispatcher more than twice in every 5-minute window for 5 minutes. Once the lease expires the + dispatcher skips the slot and tenant traffic leaves untranslated. The shard's log names the error. diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 9f902bcb9..754867596 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -711,7 +711,11 @@ Relevant series: `galactic_edge_rule_packets_total`, `galactic_edge_drops_total` (labeled by `reason`), and `galactic_edge_control_plane_drops_total` (rule applications rejected before ever reaching the datapath, e.g. quota -denials). A rule with zero `rule_packets_total` and a client actually +denials). In dispatch mode, `galactic_edge_dispatch_lease_renewals_total` +(labeled by `slot` and `result`) and +`galactic_edge_dispatch_lease_expiry_timestamp_seconds` (labeled by `slot`) +show each XDP dispatcher slot's lease: the dispatcher skips a slot once its +lease expires, so a slot whose renewals keep failing stops serving its VIPs. A rule with zero `rule_packets_total` and a client actually sending traffic points at an upstream problem (BGP not carrying the route, underlay reachability) rather than this node's own datapath; nonzero `dropped_packets_total` for a rule with `rule_backends` at `0` means the diff --git a/docs/metrics.md b/docs/metrics.md index 504862fbe..d7c526af2 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -269,25 +269,30 @@ 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. 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 | -| `galactic_nat_packets_total` | counter | `family`, `direction` (`outbound`, `return`), `action` (`redirect`, `tx`) | Packets the shard translated and queued for transmit. Every combination is reported, zero included | -| `galactic_nat_bytes_total` | counter | same | Bytes of those packets: the translated IP packet, without Ethernet or the SRv6 outer header | -| `galactic_nat_datapath_enabled` | gauge | none | 1 when the datapath is turned on by configuration, 0 when it is turned off | -| `galactic_nat_datapath_attached` | gauge | none | 1 once the datapath has loaded and attached, 0 before that or while turned off | -| `galactic_nat_programmed` | gauge | none | 1 while the datapath holds an EgressShard identity, 0 while it claims no packet | -| `galactic_nat_uplink_covered` | gauge | `interface` | 1 for each resolved uplink the datapath translates on, 0 for one it misses. Absent while turned off | -| `galactic_nat_family_enabled` | gauge | `family` | 1 when the programmed identity has a masquerade address for the family | -| `galactic_nat_info` | gauge | `shard_sid`, `nat64_prefix`, `xdp_attach`, `version` | Always 1. Empty `shard_sid` and `nat64_prefix` while unprogrammed; `xdp_attach="off"` while turned off | -| `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 | -| `galactic_nat_uplink_info` | gauge | `interface`, `driver`, `driver_version`, `firmware_version`, `kernel` | Always 1. Names each uplink's driver and NIC firmware versions and the node's kernel release | +| 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 | +| `galactic_nat_packets_total` | counter | `family`, `direction` (`outbound`, `return`), `action` (`redirect`, `tx`) | Packets the shard translated and queued for transmit. Every combination is reported, zero included | +| `galactic_nat_bytes_total` | counter | same | Bytes of those packets: the translated IP packet, without Ethernet or the SRv6 outer header | +| `galactic_nat_datapath_enabled` | gauge | none | 1 when the datapath is turned on by configuration, 0 when it is turned off | +| `galactic_nat_datapath_attached` | gauge | none | 1 once the datapath has loaded and attached, 0 before that or while turned off | +| `galactic_nat_programmed` | gauge | none | 1 while the datapath holds an EgressShard identity, 0 while it claims no packet | +| `galactic_nat_uplink_covered` | gauge | `interface` | 1 for each resolved uplink the datapath translates on, 0 for one it misses. Absent while turned off | +| `galactic_nat_family_enabled` | gauge | `family` | 1 when the programmed identity has a masquerade address for the family | +| `galactic_nat_info` | gauge | `shard_sid`, `nat64_prefix`, `xdp_attach`, `version` | Always 1. Empty `shard_sid` and `nat64_prefix` while unprogrammed; `xdp_attach="off"` while turned off | +| `galactic_nat_masquerade_ports_in_use` | gauge | `family`, `address`, `proto` | Distinct masquerade ports live sessions hold on the address, toward any destination | +| `galactic_nat_masquerade_destination_ports_max` | gauge | `family`, `address`, `proto` | The most ports live sessions hold toward any single destination address and port. New flows to it fail as this nears the range | +| `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_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 | +| `galactic_nat_uplink_info` | gauge | `interface`, `driver`, `driver_version`, `firmware_version`, `kernel` | Always 1. Names each uplink's driver and NIC firmware versions and the node's kernel release | Caveats for the translated traffic and state series: @@ -308,6 +313,28 @@ Caveats for the translated traffic and state series: - Cardinality: 8 series each for packets and bytes, one `uplink_covered` series per uplink, and one `info` series per shard. +Caveats for the masquerade port series: + +- A port is claimed per destination address and port, not per masquerade + address, so the same port can serve many destinations at once. + `galactic_nat_masquerade_ports_in_use` can sit near the range on a healthy + shard that talks to many destinations; + `galactic_nat_masquerade_destination_ports_max` is what predicts exhaustion. +- A claim probes 8 of the range's ports, so a destination fails new flows well + before it is full: about 0.4% of new flows at half full, 17% at 80% + (`GalacticNatPortsNearExhaustion` warns at half full). +- Every protocol of every address the programmed identity serves is reported, + zero included, except when the session clock cannot be read: then only the + range is reported, rather than zeros that would read as an idle shard. An + address a re-programmed identity replaced is reported while live sessions + still hold its ports. +- Both are read from the session table walk at scrape time, like + `galactic_nat_sessions`, so they are approximate on a churning table. + +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. + Caveats for the session table: - Expired sessions keep their rows until the LRU evicts them or a new claim @@ -366,6 +393,16 @@ sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|n / (sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|nat(66|64)_malformed_forward|redirect_failed|no_egress_ifindex|adjust_head_failed"}[10m])) + sum by (node) (rate(galactic_nat_packets_total[10m]))) +# Busiest destination per masquerade address, as a share of the range (GalacticNatPortsNearExhaustion) +max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max) + / on (node) group_left () max by (node) (galactic_nat_masquerade_port_range) + +# Seconds left on the dispatcher lease, by the node's clock +galactic_nat_dispatch_lease_expiry_timestamp_seconds - time() + +# No successful lease renewal in two minutes (GalacticNatDispatchLeaseExpiring) +changes(galactic_nat_dispatch_lease_renewals_total{result="success"}[2m]) == 0 + # Shards turned on but not programmed, and uplinks not covered galactic_nat_datapath_enabled == 1 and on (node) galactic_nat_programmed == 0 galactic_nat_uplink_covered == 0 @@ -408,4 +445,7 @@ carries `service: galactic`, `team: connect` and a `runbook_url`. | GalacticNatUplinkUncovered | `galactic_nat_uplink_covered == 0` | 10m | critical | | GalacticNatForwardDropRatio | owned-traffic drops over 1% of translated, over 10 packets/s | 15m | warning | | GalacticNatNotTranslating | compute nodes send to the shard's SID, it translates none outbound | 10m | critical | +| GalacticNatPortsNearExhaustion | busiest destination holds over half its port range | 10m | warning | +| GalacticNatDispatchLeaseFailing | more than two lease renewal errors in every 5-minute window | 5m | warning | +| GalacticNatDispatchLeaseExpiring | no successful lease renewal in 2 minutes | 0 | critical | | GalacticNatMetricsDown | `galactic-nat` scrape down | 5m | warning | diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 7e01e69ae..e5a2363a3 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -702,23 +702,28 @@ 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 | `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 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. | -| `galactic_nat_packets_total` | Counter | `family`, `direction`, `action` | Packets the shard translated and queued for transmit. `direction` is `outbound` (tenant to internet) or `return` (internet to tenant), `action` is `tx` (out the uplink it arrived on) or `redirect` (out another). Messages the shard sends on its own behalf (Packet Too Big, Fragmentation Needed, echo replies) are not translations and are not counted. Every combination is reported, at zero when unused. Cumulative for the life of the node, like `galactic_nat_drops_total`. | -| `galactic_nat_bytes_total` | Counter | `family`, `direction`, `action` | Bytes of the packets in `galactic_nat_packets_total`: the translated IP packet, without the Ethernet header or the SRv6 outer header a return packet carries. | -| `galactic_nat_datapath_enabled` | Gauge | — | 1 when `GALACTIC_NAT_DATAPATH_ENABLED` turns the datapath on, 0 when it is off. | -| `galactic_nat_datapath_attached` | Gauge | — | 1 once startup has loaded the program and attached it to the uplinks or the XDP dispatcher. 0 before that, and while the datapath is turned off. | -| `galactic_nat_programmed` | Gauge | — | 1 while `shard_config_table` holds an EgressShard identity, 0 while the shard claims no packet. | -| `galactic_nat_uplink_covered` | Gauge | `interface` | 1 for each resolved uplink the datapath translates on, 0 for one it misses, whose traffic leaves untranslated. Absent while the datapath is turned off. | -| `galactic_nat_family_enabled` | Gauge | `family` | 1 when the programmed identity has a masquerade address for that family (`shardAddressIPv6` for `nat66`, `shardAddressIPv4` for `nat64`). | -| `galactic_nat_info` | Gauge | `shard_sid`, `nat64_prefix`, `xdp_attach`, `version` | Always 1. `shard_sid` and `nat64_prefix` are empty while unprogrammed, and `xdp_attach` is `off` while the datapath is turned off. | -| `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. | +| 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 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. | +| `galactic_nat_packets_total` | Counter | `family`, `direction`, `action` | Packets the shard translated and queued for transmit. `direction` is `outbound` (tenant to internet) or `return` (internet to tenant), `action` is `tx` (out the uplink it arrived on) or `redirect` (out another). Messages the shard sends on its own behalf (Packet Too Big, Fragmentation Needed, echo replies) are not translations and are not counted. Every combination is reported, at zero when unused. Cumulative for the life of the node, like `galactic_nat_drops_total`. | +| `galactic_nat_bytes_total` | Counter | `family`, `direction`, `action` | Bytes of the packets in `galactic_nat_packets_total`: the translated IP packet, without the Ethernet header or the SRv6 outer header a return packet carries. | +| `galactic_nat_datapath_enabled` | Gauge | — | 1 when `GALACTIC_NAT_DATAPATH_ENABLED` turns the datapath on, 0 when it is off. | +| `galactic_nat_datapath_attached` | Gauge | — | 1 once startup has loaded the program and attached it to the uplinks or the XDP dispatcher. 0 before that, and while the datapath is turned off. | +| `galactic_nat_programmed` | Gauge | — | 1 while `shard_config_table` holds an EgressShard identity, 0 while the shard claims no packet. | +| `galactic_nat_uplink_covered` | Gauge | `interface` | 1 for each resolved uplink the datapath translates on, 0 for one it misses, whose traffic leaves untranslated. Absent while the datapath is turned off. | +| `galactic_nat_family_enabled` | Gauge | `family` | 1 when the programmed identity has a masquerade address for that family (`shardAddressIPv6` for `nat66`, `shardAddressIPv4` for `nat64`). | +| `galactic_nat_info` | Gauge | `shard_sid`, `nat64_prefix`, `xdp_attach`, `version` | Always 1. `shard_sid` and `nat64_prefix` are empty while unprogrammed, and `xdp_attach` is `off` while the datapath is turned off. | +| `galactic_nat_masquerade_ports_in_use` | Gauge | `family`, `address`, `proto` | Distinct masquerade ports (or ICMP Echo Identifiers) live sessions hold on the address, toward any destination. A port is claimed per destination address and port, so this can approach the range on a healthy shard; see the next series for exhaustion. Every protocol of every served address is reported, zero included. | +| `galactic_nat_masquerade_destination_ports_max` | Gauge | `family`, `address`, `proto` | The most ports live sessions hold toward one destination address and port. A claim probes 8 of the range's candidates, so new flows to that destination fail with probability about (this / range)^8: 0.4% at half full. | +| `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_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. | `config/monitoring/podmonitor-galactic-nat.yaml` scrapes every shard as `job="galactic-nat"` with a `node` label. diff --git a/internal/plumbing/ebpf/edgemetrics/collector.go b/internal/plumbing/ebpf/edgemetrics/collector.go index fa53d9057..7d92127a9 100644 --- a/internal/plumbing/ebpf/edgemetrics/collector.go +++ b/internal/plumbing/ebpf/edgemetrics/collector.go @@ -15,7 +15,10 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" ) -const namespace = "galactic_edge" +// Namespace is the gateway's metric prefix, shared by every gateway series. +const Namespace = "galactic_edge" + +const namespace = Namespace // DropReasonsReader narrows the drop-reason map, a per-CPU array keyed by // reason index, to the one operation Collector needs, so tests can substitute an diff --git a/internal/plumbing/ebpf/natmap/conntable.go b/internal/plumbing/ebpf/natmap/conntable.go index c7cfc95db..edef6d7a2 100644 --- a/internal/plumbing/ebpf/natmap/conntable.go +++ b/internal/plumbing/ebpf/natmap/conntable.go @@ -275,6 +275,35 @@ type SessionCounts struct { // false, and OldestAge zero, when the walk found no reverse row. OldestAge uint32 HasReverse bool + + // Ports describes the masquerade ports live sessions hold, by family, + // masquerade address and protocol. + Ports map[MasqueradeKey]PortUsage +} + +// MasqueradeKey groups live sessions by the shard address and protocol their +// masquerade port belongs to. Address is the IPv4 address itself for NAT64. +type MasqueradeKey struct { + Family uint8 + Address netip.Addr + Proto string +} + +// PortUsage is how much of a masquerade address's port space live sessions +// hold. A claim needs a free port toward one destination address and port, so +// MaxPerDestination, the most ports held toward any single destination, is what +// approaches exhaustion; InUse, the distinct ports held toward any destination, +// can sit near the whole range on a healthy shard talking to many destinations. +type PortUsage struct { + InUse int + MaxPerDestination int +} + +// portDestination is one destination address and port behind a masquerade key. +type portDestination struct { + MasqueradeKey + peer [16]byte + peerPort uint16 } // sessionProto names a row's protocol as SessionKey reports it. @@ -342,9 +371,13 @@ func sessionExpired(value *natprog.NatConnValue, now uint32) bool { // and are approximate either way. func (t *ConnTable) CountSessions(now uint32) (SessionCounts, error) { var ( - counts = SessionCounts{Rows: map[uint8]int{}, Live: map[SessionKey]int{}} - rawKey natprog.NatConnKey - value natprog.NatConnValue + counts = SessionCounts{ + Rows: map[uint8]int{}, Live: map[SessionKey]int{}, Ports: map[MasqueradeKey]PortUsage{}, + } + rawKey natprog.NatConnKey + value natprog.NatConnValue + ports = map[MasqueradeKey]map[uint16]struct{}{} + perDest = map[portDestination]map[uint16]struct{}{} ) it := t.table.Iterate() for it.Next(&rawKey, &value) { @@ -358,10 +391,43 @@ func (t *ConnTable) CountSessions(now uint32) (SessionCounts, error) { counts.HasReverse = true if !sessionExpired(&value, now) { counts.Live[SessionKey{Family: rawKey.Family, Proto: sessionProto(value.Proto)}]++ + countPort(ports, perDest, &rawKey, &value) } } + for key, held := range ports { + counts.Ports[key] = PortUsage{InUse: len(held)} + } + for dest, held := range perDest { + usage := counts.Ports[dest.MasqueradeKey] + usage.MaxPerDestination = max(usage.MaxPerDestination, len(held)) + counts.Ports[dest.MasqueradeKey] = usage + } if err := it.Err(); err != nil { return counts, fmt.Errorf("natmap: nat_conn_table: count: %w", err) } return counts, nil } + +// countPort records the masquerade port a live reverse row holds. The row's +// key is the reply as it arrives: the destination as source, and the +// masquerade address and port as destination. Ports are kept as sets, so a +// row a restarted walk visits twice is still counted once. +func countPort(ports map[MasqueradeKey]map[uint16]struct{}, perDest map[portDestination]map[uint16]struct{}, + rawKey *natprog.NatConnKey, value *natprog.NatConnValue, +) { + key := MasqueradeKey{ + Family: rawKey.Family, + Address: netip.AddrFrom16(rawKey.Daddr).Unmap(), + Proto: sessionProto(value.Proto), + } + if ports[key] == nil { + ports[key] = map[uint16]struct{}{} + } + port := beU16(rawKey.Dport) + ports[key][port] = struct{}{} + dest := portDestination{MasqueradeKey: key, peer: rawKey.Saddr, peerPort: rawKey.Sport} + if perDest[dest] == nil { + perDest[dest] = map[uint16]struct{}{} + } + perDest[dest][port] = struct{}{} +} diff --git a/internal/plumbing/ebpf/natmap/conntable_test.go b/internal/plumbing/ebpf/natmap/conntable_test.go index a89a9d2a9..71e7a4823 100644 --- a/internal/plumbing/ebpf/natmap/conntable_test.go +++ b/internal/plumbing/ebpf/natmap/conntable_test.go @@ -345,3 +345,103 @@ func TestConnTable_CountSessionsEmpty(t *testing.T) { t.Errorf("counts on an empty table = %+v, want nothing", counts) } } + +// portRow is a live reverse UDP row holding shardPort on masq toward +// peer:peerPort, the shape a reply's key takes. +func portRow(family uint8, masq, peer string, peerPort, shardPort uint16, lastSeen uint32) ConnEntry { + e := sessionRow(family, 17, shardPort, peerPort, 0, lastSeen) + e.Saddr = netip.MustParseAddr(peer) + e.Sport = peerPort + e.Daddr = netip.MustParseAddr(masq) + return e +} + +func TestConnTable_CountSessionsPorts(t *testing.T) { + const now uint32 = 100_000 + masq6 := "2001:db8:9966::1" + masq4 := "::ffff:192.0.2.10" + + fake := newFakeTable() + for _, e := range []ConnEntry{ + // Three ports toward one destination, two toward another, one of + // them a port the first destination also holds. + portRow(natprog.FamilyIPv6, masq6, "2001:db8:1::1", 443, 35000, now), + portRow(natprog.FamilyIPv6, masq6, "2001:db8:1::1", 443, 35001, now), + portRow(natprog.FamilyIPv6, masq6, "2001:db8:1::1", 443, 35002, now), + portRow(natprog.FamilyIPv6, masq6, "2001:db8:1::1", 80, 35000, now), + portRow(natprog.FamilyIPv6, masq6, "2001:db8:2::1", 443, 35003, now), + // An expired session holds nothing. + portRow(natprog.FamilyIPv6, masq6, "2001:db8:1::1", 443, 35004, now-natprog.TimeoutUDP-1), + // NAT64 rows carry the masquerade address IPv4-mapped. + portRow(natprog.FamilyIPv4, masq4, "::ffff:198.51.100.7", 53, 40000, now), + } { + putEntry(t, fake, e) + } + + counts, err := NewConnTable(fake).CountSessions(now) + if err != nil { + t.Fatalf("CountSessions: %v", err) + } + want := map[MasqueradeKey]PortUsage{ + {Family: natprog.FamilyIPv6, Address: netip.MustParseAddr(masq6), Proto: SessionProtoUDP}: { + InUse: 4, MaxPerDestination: 3, + }, + {Family: natprog.FamilyIPv4, Address: netip.MustParseAddr("192.0.2.10"), Proto: SessionProtoUDP}: { + InUse: 1, MaxPerDestination: 1, + }, + } + if len(counts.Ports) != len(want) { + t.Errorf("Ports = %v, want %v", counts.Ports, want) + } + for key, w := range want { + if got := counts.Ports[key]; got != w { + t.Errorf("Ports[%v] = %+v, want %+v", key, got, w) + } + } +} + +// repeatingTable walks its rows twice, the way a walk the datapath's evictions +// restart revisits rows it already returned. +type repeatingTable struct{ *fakeTable } + +func (r repeatingTable) Iterate() Iterator { + return &repeatingIterator{table: r.fakeTable, current: r.fakeTable.Iterate()} +} + +type repeatingIterator struct { + table *fakeTable + current Iterator + second bool +} + +func (it *repeatingIterator) Next(keyOut, valueOut any) bool { + if it.current.Next(keyOut, valueOut) { + return true + } + if it.second { + return false + } + it.second = true + it.current = it.table.Iterate() + return it.current.Next(keyOut, valueOut) +} + +func (it *repeatingIterator) Err() error { return it.current.Err() } + +func TestConnTable_CountSessionsPortsSurviveRestartedWalk(t *testing.T) { + const now uint32 = 100_000 + fake := newFakeTable() + for _, port := range []uint16{35000, 35001} { + putEntry(t, fake, portRow(natprog.FamilyIPv6, "2001:db8:9966::1", "2001:db8:1::1", 443, port, now)) + } + counts, err := NewConnTable(repeatingTable{fake}).CountSessions(now) + if err != nil { + t.Fatalf("CountSessions: %v", err) + } + key := MasqueradeKey{ + Family: natprog.FamilyIPv6, Address: netip.MustParseAddr("2001:db8:9966::1"), Proto: SessionProtoUDP, + } + if got, want := counts.Ports[key], (PortUsage{InUse: 2, MaxPerDestination: 2}); got != want { + t.Errorf("Ports after a walk that revisited every row = %+v, want %+v", got, want) + } +} diff --git a/internal/plumbing/ebpf/natprog/traffic.go b/internal/plumbing/ebpf/natprog/traffic.go index ba11de7f2..be39aae52 100644 --- a/internal/plumbing/ebpf/natprog/traffic.go +++ b/internal/plumbing/ebpf/natprog/traffic.go @@ -27,3 +27,13 @@ const ( func TrafficSlot(family, direction, action uint32) uint32 { return family*4 + direction*2 + action } + +// Masquerade port allocation, mirroring the datapath's NAT_PAT_* constants: +// a claim probes up to PATProbeLimit candidates within PATPortRange ports +// starting at PATPortBase. The range is per destination address and port, not +// per masquerade address. +const ( + PATPortBase uint16 = 32768 + PATPortRange uint16 = 28000 + PATProbeLimit int = 8 +) diff --git a/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go b/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go new file mode 100644 index 000000000..a49d14951 --- /dev/null +++ b/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go @@ -0,0 +1,103 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpdispatch + +import ( + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +// String names slot as its metrics label: "gateway_lb", "gateway_return", +// "nat", or "slot_" for any other. +func (s Slot) String() string { + switch s { + case SlotGatewayLB: + return "gateway_lb" + case SlotGatewayReturn: + return "gateway_return" + case SlotNAT: + return "nat" + default: + return "slot_" + strconv.FormatUint(uint64(s), 10) + } +} + +// Lease renewal results, as the renewals counter labels them. +const ( + leaseResultSuccess = "success" + leaseResultError = "error" +) + +// LeaseMetrics records each renewal of a slot's dispatcher lease: how many +// succeeded and failed, and when the lease last renewed expires. A slot whose +// renewals fail stops claiming packets once that time passes. +type LeaseMetrics struct { + renewals *prometheus.CounterVec + expiry *prometheus.GaugeVec + now func() time.Time +} + +// NewLeaseMetrics builds the lease series under namespace, the caller's own +// metric prefix: _dispatch_lease_renewals_total{slot, result} and +// _dispatch_lease_expiry_timestamp_seconds{slot}. +func NewLeaseMetrics(namespace string) *LeaseMetrics { + return &LeaseMetrics{ + renewals: prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: namespace, + Subsystem: "dispatch_lease", + Name: "renewals_total", + Help: "Renewals of this process's XDP dispatcher slot leases, by slot and result. A slot whose " + + "renewals keep failing is skipped by the dispatcher once its lease expires.", + }, []string{"slot", "result"}), + expiry: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: namespace, + Subsystem: "dispatch_lease", + Name: "expiry_timestamp_seconds", + Help: "Unix time at which the slot's lease, as last renewed, expires: the time of the last " + + "successful renewal plus the lease TTL.", + }, []string{"slot"}), + now: time.Now, + } +} + +// Register registers m's series with reg. +func (m *LeaseMetrics) Register(reg prometheus.Registerer) error { + if err := reg.Register(m.renewals); err != nil { + return err + } + return reg.Register(m.expiry) +} + +// Observe returns the onRenew callback for Lease on slot: it records each +// renewal's result and then calls onError, which may be nil, with a failed +// renewal's error. Both of slot's result series exist from this call on, at +// zero until a renewal lands in them. A nil m records nothing and only passes +// failures on. +func (m *LeaseMetrics) Observe(slot Slot, onError func(error)) func(error) { + if m == nil { + return func(err error) { + if err != nil && onError != nil { + onError(err) + } + } + } + label := slot.String() + success := m.renewals.WithLabelValues(label, leaseResultSuccess) + failure := m.renewals.WithLabelValues(label, leaseResultError) + expiry := m.expiry.WithLabelValues(label) + return func(err error) { + if err != nil { + failure.Inc() + if onError != nil { + onError(err) + } + return + } + success.Inc() + expiry.Set(float64(m.now().Add(LeaseTTL).UnixNano()) / 1e9) + } +} diff --git a/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go b/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go new file mode 100644 index 000000000..9c45936d8 --- /dev/null +++ b/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go @@ -0,0 +1,71 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpdispatch + +import ( + "errors" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" +) + +func TestLeaseMetricsObserve(t *testing.T) { + m := NewLeaseMetrics("test") + reg := prometheus.NewPedanticRegistry() + if err := m.Register(reg); err != nil { + t.Fatalf("Register: %v", err) + } + renewedAt := time.Unix(1_000_000, 0) + m.now = func() time.Time { return renewedAt } + + var passed []error + onRenew := m.Observe(SlotNAT, func(err error) { passed = append(passed, err) }) + + if got := testutil.ToFloat64(m.renewals.WithLabelValues("nat", leaseResultError)); got != 0 { + t.Errorf("error renewals before any renewal = %v, want a zero series", got) + } + + onRenew(nil) + onRenew(nil) + boom := errors.New("map write failed") + onRenew(boom) + + if got := testutil.ToFloat64(m.renewals.WithLabelValues("nat", leaseResultSuccess)); got != 2 { + t.Errorf("success renewals = %v, want 2", got) + } + if got := testutil.ToFloat64(m.renewals.WithLabelValues("nat", leaseResultError)); got != 1 { + t.Errorf("error renewals = %v, want 1", got) + } + wantExpiry := float64(renewedAt.Add(LeaseTTL).Unix()) + if got := testutil.ToFloat64(m.expiry.WithLabelValues("nat")); got != wantExpiry { + t.Errorf("expiry = %v, want %v: a failed renewal must leave the last expiry in place", got, wantExpiry) + } + if len(passed) != 1 || !errors.Is(passed[0], boom) { + t.Errorf("onError got %v, want only the failure", passed) + } +} + +func TestLeaseMetricsNilPassesFailuresOn(t *testing.T) { + var m *LeaseMetrics + var passed []error + onRenew := m.Observe(SlotGatewayLB, func(err error) { passed = append(passed, err) }) + onRenew(nil) + onRenew(errors.New("boom")) + if len(passed) != 1 { + t.Errorf("onError called %d times, want once for the failure", len(passed)) + } +} + +func TestSlotString(t *testing.T) { + for slot, want := range map[Slot]string{ + SlotGatewayLB: "gateway_lb", SlotGatewayReturn: "gateway_return", SlotNAT: "nat", Slot(9): "slot_9", + } { + if got := slot.String(); got != want { + t.Errorf("Slot(%d).String() = %q, want %q", slot, got, want) + } + } +} diff --git a/internal/plumbing/ebpf/xdpdispatch/lock.go b/internal/plumbing/ebpf/xdpdispatch/lock.go index 633f22f5f..37b8ff2ab 100644 --- a/internal/plumbing/ebpf/xdpdispatch/lock.go +++ b/internal/plumbing/ebpf/xdpdispatch/lock.go @@ -46,12 +46,13 @@ func lockDir(ctx context.Context, dir string) (func(), error) { // Lease renews slot's lease every LeaseRenewal until ctx is done, starting // now. It leaves the lease in place when it stops, so a restart within -// LeaseTTL never lets the slot lapse. A failed renewal is reported to onError, -// which may be nil. -func (d *Dispatcher) Lease(ctx context.Context, slot Slot, onError func(error)) { +// LeaseTTL never lets the slot lapse. Every renewal's result, nil on success, +// is reported to onRenew, which may be nil. +func (d *Dispatcher) Lease(ctx context.Context, slot Slot, onRenew func(error)) { renew := func() { - if err := d.Renew(slot); err != nil && onError != nil { - onError(err) + err := d.Renew(slot) + if onRenew != nil { + onRenew(err) } } renew()