Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions cmd/galactic-nat/claims_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package main

import (
"testing"

"go.datum.net/galactic/internal/plumbing/ebpf/natprog"
)

// fakeClaims answers nat_claims lookups from fixed per-CPU counts.
type fakeClaims map[uint32][]uint64

func (f fakeClaims) Lookup(key, valueOut any) error {
*valueOut.(*[]uint64) = f[key.(uint32)]
return nil
}

func TestNatCollectorReportsClaims(t *testing.T) {
c := &natCollector{claims: fakeClaims{
natprog.ClaimSlot(natprog.TrafficFamilyNAT66, natprog.ClaimProtoTCP, 1): {4, 6},
natprog.ClaimSlot(natprog.TrafficFamilyNAT66, natprog.ClaimProtoTCP, 3): {2},
natprog.ClaimSlot(natprog.TrafficFamilyNAT64, natprog.ClaimProtoICMP, 8): {1},
}}
got := gatherAll(t, c)

creates := got["galactic_nat_session_creates_total"]
if len(creates) != 6 {
t.Errorf("session_creates_total has %d series, want 6 (2 families x 3 protocols): %v", len(creates), creates)
}
// Labels sort as family/proto.
for labels, want := range map[string]float64{"nat66/tcp": 12, "nat64/icmp": 1, "nat66/udp": 0} {
if creates[labels] != want {
t.Errorf("session_creates_total{%s} = %v, want %v", labels, creates[labels], want)
}
}

probes := got["galactic_nat_masquerade_claim_probes_total"]
if len(probes) != int(natprog.ClaimSlots) {
t.Errorf("claim_probes_total has %d series, want %d", len(probes), natprog.ClaimSlots)
}
// Labels sort as family/probes/proto.
for labels, want := range map[string]float64{
"nat66/1/tcp": 10, "nat66/3/tcp": 2, "nat64/8/icmp": 1, "nat66/2/tcp": 0,
} {
if probes[labels] != want {
t.Errorf("claim_probes_total{%s} = %v, want %v", labels, probes[labels], want)
}
}
}
68 changes: 64 additions & 4 deletions cmd/galactic-nat/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"log/slog"
"maps"
"net/netip"
"strconv"

"github.com/cilium/ebpf"
"github.com/prometheus/client_golang/prometheus"
Expand All @@ -21,11 +22,14 @@ import (
const metricsNamespace = "galactic_nat"

// labelFamily is the label carrying an address family, familyNAT66 or
// familyNAT64.
const labelFamily = "family"
// familyNAT64, and labelProto the one carrying a session protocol.
const (
labelFamily = "family"
labelProto = "proto"
)

// masqueradeLabels label the masquerade port series.
var masqueradeLabels = []string{labelFamily, "address", "proto"}
var masqueradeLabels = []string{labelFamily, "address", labelProto}

// trafficLabels label the translated-traffic series.
var trafficLabels = []string{labelFamily, "direction", "action"}
Expand All @@ -40,6 +44,7 @@ type natCollector struct {
connMaxEntries uint32
dropReasons natmap.DropReasonsReader
traffic natmap.TrafficReader
claims natmap.CounterReader

// shardConfig names the masquerade addresses whose port usage is always
// reported, zero included. Nil reports only the addresses rows hold.
Expand Down Expand Up @@ -69,6 +74,7 @@ func newNatCollector(objs *natprog.NatObjects) *natCollector {
connMaxEntries: mapMaxEntries(objs.NatConnTable),
dropReasons: objs.DropReasons,
traffic: objs.NatTraffic,
claims: objs.NatClaims,
shardConfig: natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}),
}
}
Expand All @@ -93,7 +99,7 @@ var (
prometheus.BuildFQName(metricsNamespace, "", "sessions"),
"Live sessions in this shard's nat_conn_table, by address family and protocol: sessions "+
"within their idle timeout, one per session. Expired sessions are not counted.",
[]string{labelFamily, "proto"}, nil,
[]string{labelFamily, labelProto}, nil,
)
oldestRowAgeDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "", "conn_table_oldest_row_age_seconds"),
Expand Down Expand Up @@ -143,6 +149,19 @@ var (
"Masquerade ports (or ICMP Echo Identifiers) available toward each destination address and port.",
nil, nil,
)
sessionCreatesDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "", "session_creates_total"),
"New sessions this shard opened, each one a masquerade port (or ICMP Echo Identifier) it claimed, by "+
"address family and protocol. A claim that found no free port is a *_pat_exhausted drop instead.",
[]string{labelFamily, labelProto}, nil,
)
claimProbesDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "masquerade", "claim_probes_total"),
"New sessions' masquerade port claims by how many probes each took, 1 to 8. With a share u of a "+
"destination's ports held, a claim needs more than k probes with probability of roughly u^k, so the share of "+
"claims needing more than one probe estimates how full the busiest destinations are.",
[]string{labelFamily, labelProto, "probes"}, nil,
)
dropsDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "", "drops_total"),
"Packets dropped by this shard's datapath, by reason (drop_reasons map).",
Expand All @@ -162,6 +181,8 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- portsInUseDesc
ch <- destinationPortsMaxDesc
ch <- portRangeDesc
ch <- sessionCreatesDesc
ch <- claimProbesDesc
}

// Collect implements prometheus.Collector.
Expand All @@ -170,6 +191,7 @@ func (c *natCollector) Collect(ch chan<- prometheus.Metric) {
c.collectConnTableMaxEntries(ch)
c.collectDrops(ch)
c.collectTraffic(ch)
c.collectClaims(ch)
}

// Family label values, one per address family a shard translates.
Expand Down Expand Up @@ -341,3 +363,41 @@ func (c *natCollector) collectTraffic(ch chan<- prometheus.Metric) {
}
}
}

// collectClaims reports new sessions by family and protocol, and their claims
// by probe count, every combination zero included.
func (c *natCollector) collectClaims(ch chan<- prometheus.Metric) {
if c.claims == nil {
return
}
totals, err := natmap.ClaimTotals(c.claims)
if err != nil {
slog.Warn("cannot read nat_claims; skipping session creation metrics", "err", err)
return
}
families := []struct {
id uint32
label string
}{{natprog.TrafficFamilyNAT66, familyNAT66}, {natprog.TrafficFamilyNAT64, familyNAT64}}
protos := []struct {
id uint32
label string
}{
{natprog.ClaimProtoTCP, natmap.SessionProtoTCP},
{natprog.ClaimProtoUDP, natmap.SessionProtoUDP},
{natprog.ClaimProtoICMP, natmap.SessionProtoICMP},
}
for _, f := range families {
for _, p := range protos {
var creates uint64
for probes := 1; probes <= natprog.PATProbeLimit; probes++ {
n := totals[natprog.ClaimSlot(f.id, p.id, probes)]
creates += n
ch <- prometheus.MustNewConstMetric(claimProbesDesc, prometheus.CounterValue, float64(n),
f.label, p.label, strconv.Itoa(probes))
}
ch <- prometheus.MustNewConstMetric(sessionCreatesDesc, prometheus.CounterValue, float64(creates),
f.label, p.label)
}
}
}
19 changes: 19 additions & 0 deletions cmd/galactic-nat/nat.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ type natDatapath struct {
// nat64 is whether the programmed identity serves NAT64, which an uplink
// found later needs IPv4 forwarding for, as Program gives the rest.
nat64 bool

// resolveErrors counts watchUplinks' failed re-resolutions, which keep
// the previous coverage. Nil counts nothing.
resolveErrors prometheus.Counter
}

// Attached reports whether startup completed its load and attach pass. It is
Expand Down Expand Up @@ -361,6 +365,18 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig,

registerUplinkQueueStats(metricsReg, d)

d.resolveErrors = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: metricsNamespace,
Name: "uplink_resolve_errors_total",
Help: "Times re-resolving this node's uplinks after a link or route change failed. The shard keeps " +
"its previous coverage, so a steady rise means uplinks that appeared since are not covered.",
})
if err := metricsReg.Register(d.resolveErrors); err != nil {
closeAll(xdpLinks)
_ = objs.Close()
return nil, fmt.Errorf("register uplink resolve error metric: %w", err)
}

natDatapathKeepAlive.objs = objs
natDatapathKeepAlive.set = set
natDatapathKeepAlive.dispatch = dispatcher
Expand Down Expand Up @@ -504,6 +520,9 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover
uplinks, err := natattach.ResolveUplinks(override)
if err != nil {
slog.Warn("Re-resolve uplink interfaces failed; keeping current coverage", "err", err)
if d.resolveErrors != nil {
d.resolveErrors.Inc()
}
return
}
ready := d.adoptUplinks(uplinks)
Expand Down
26 changes: 26 additions & 0 deletions docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,9 @@ One `galactic-nat` pod per egress shard; every value is per shard.
| `galactic_nat_masquerade_port_range` | gauge | none | Ports (or ICMP Echo Identifiers) available toward each destination: 28000 |
| `galactic_nat_dispatch_lease_renewals_total` | counter | `slot`, `result` (`success`, `error`) | Renewals of the shard's XDP dispatcher slot lease. Dispatch mode only |
| `galactic_nat_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time the lease, as last renewed, expires. Dispatch mode only |
| `galactic_nat_session_creates_total` | counter | `family`, `proto` | New sessions the shard opened, one masquerade port claim each |
| `galactic_nat_masquerade_claim_probes_total` | counter | `family`, `proto`, `probes` (`1`..`8`) | Those claims by how many probes each took. Rising multi-probe shares mean busy destinations are filling |
| `galactic_nat_uplink_resolve_errors_total` | counter | none | Failed re-resolutions of the uplinks after a link or route change; the shard keeps its previous coverage |
| `galactic_nat_uplink_rx_queue_packets_total` | counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink received, from `ethtool -S`. Exported for `bnxt_en`, `ixgbe`, `ice`, `i40e`, `mlx5_core` |
| `galactic_nat_uplink_rx_queue_discards_total` | counter | `interface`, `driver`, `queue` | Packets one receive queue discarded before the datapath saw them. Reported only by drivers that count per queue: `bnxt_en` today |
| `galactic_nat_uplink_queue_driver_stat_total` | counter | `interface`, `driver`, `queue`, `stat` | One of a queue's other driver counters, under its `ethtool -S` name. `bnxt_en` only, see below |
Expand Down Expand Up @@ -331,6 +334,25 @@ Caveats for the masquerade port series:
- Both are read from the session table walk at scrape time, like
`galactic_nat_sessions`, so they are approximate on a churning table.

Caveats for session creation:

- `galactic_nat_session_creates_total` is the sum of
`galactic_nat_masquerade_claim_probes_total` over `probes`. A claim that
finds no port is a `*_pat_exhausted` drop, and a claim that adopts a live
session's lost port opens no new session; neither is counted.
- With a share u of a destination's ports held, a claim needs more than k
probes with probability of roughly u^k (the probes walk consecutive ports,
and held ports cluster, so it is an estimate). The share of claims needing more than one
probe therefore estimates how full the destinations taking new flows are,
before `galactic_nat_masquerade_destination_ports_max` names the worst one
and long before `*_pat_exhausted` drops start.
- Cardinality: 6 creates series and 48 probe series per shard.

The `EgressShard` reconciler's controller-runtime metrics
(`controller_runtime_reconcile_total{controller="egressshard"}`,
`controller_runtime_reconcile_errors_total`, `workqueue_*`) are served on the
same port, from the same registry.

The dispatcher lease series are registered in dispatch mode only. The
edge gateway exports the same pair as `galactic_edge_dispatch_lease_*` for
its two slots; no shipped alert reads the gateway's yet.
Expand Down Expand Up @@ -397,6 +419,10 @@ sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|n
max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max)
/ on (node) group_left () max by (node) (galactic_nat_masquerade_port_range)

# Share of new sessions whose port claim needed more than one probe
sum by (node, family) (rate(galactic_nat_masquerade_claim_probes_total{probes!="1"}[10m]))
/ sum by (node, family) (rate(galactic_nat_session_creates_total[10m]))

# Seconds left on the dispatcher lease, by the node's clock
galactic_nat_dispatch_lease_expiry_timestamp_seconds - time()

Expand Down
8 changes: 8 additions & 0 deletions docs/nat/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -722,9 +722,17 @@ Metrics, exposed on `GALACTIC_NAT_METRICS_PORT` (`9182` by default):
| `galactic_nat_masquerade_port_range` | Gauge | — | Ports available toward each destination, `NAT_PAT_PORT_RANGE` (28000). |
| `galactic_nat_dispatch_lease_renewals_total` | Counter | `slot`, `result` | Renewals of the shard's XDP dispatcher slot lease, `success` or `error`. Present in dispatch mode only. |
| `galactic_nat_dispatch_lease_expiry_timestamp_seconds` | Gauge | `slot` | Unix time the slot's lease, as last renewed, expires. The dispatcher skips the slot once it passes. Present in dispatch mode only. |
| `galactic_nat_session_creates_total` | Counter | `family`, `proto` | New sessions opened, each a masquerade port (or ICMP Echo Identifier) the shard claimed. A claim that found no port is a `*_pat_exhausted` drop instead, and one that adopted a live session's lost port is not counted. Every combination is reported, zero included. |
| `galactic_nat_masquerade_claim_probes_total` | Counter | `family`, `proto`, `probes` | Those claims by how many of the 8 candidates each probed. With a share u of a destination's ports held, a claim needs more than k probes with probability of roughly u^k, so a rising share above `probes="1"` is the earliest sign destinations are filling. |
| `galactic_nat_uplink_resolve_errors_total` | Counter | — | Times re-resolving the uplinks after a link or route change failed. The shard keeps its previous coverage, so uplinks that appeared since stay uncovered until a later resolution succeeds. |
| `galactic_nat_uplink_rx_queue_packets_total` | Counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink received, from the driver's `ethtool -S` statistics. Exported for `bnxt_en`, `ixgbe`, `ice`, `i40e` and `mlx5_core`; any other driver exports nothing. |
| `galactic_nat_uplink_rx_queue_discards_total` | Counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink discarded before the datapath saw them, so `galactic_nat_drops_total` never counts them. Only drivers that count discards per queue report it: `bnxt_en` today. |

The same port also serves the `EgressShard` reconciler's controller-runtime
metrics (`controller_runtime_reconcile_total{controller="egressshard"}`,
`controller_runtime_reconcile_errors_total`, `workqueue_*`), registered in the
same registry as the series above.

`config/monitoring/podmonitor-galactic-nat.yaml` scrapes every shard as
`job="galactic-nat"` with a `node` label.

Expand Down
22 changes: 22 additions & 0 deletions internal/plumbing/ebpf/natmap/dropreasons.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,25 @@ func TrafficTotals(reader TrafficReader) ([natprog.TrafficSlots]natprog.NatNatTr
}
return totals, nil
}

// CounterReader narrows a per-CPU array of uint64 counters, such as
// nat_claims, to the one operation its readers need.
type CounterReader interface {
Lookup(key, valueOut any) error
}

// ClaimTotals reads every nat_claims slot and returns its count summed across
// CPUs, indexed by natprog.ClaimSlot.
func ClaimTotals(reader CounterReader) ([natprog.ClaimSlots]uint64, error) {
var totals [natprog.ClaimSlots]uint64
for slot := range natprog.ClaimSlots {
var perCPU []uint64
if err := reader.Lookup(slot, &perCPU); err != nil {
return totals, fmt.Errorf("natmap: nat_claims: lookup[%d]: %w", slot, err)
}
for _, v := range perCPU {
totals[slot] += v
}
}
return totals, nil
}
Loading
Loading