diff --git a/cmd/galactic-nat/metrics.go b/cmd/galactic-nat/metrics.go index a1938e080..030c44904 100644 --- a/cmd/galactic-nat/metrics.go +++ b/cmd/galactic-nat/metrics.go @@ -18,6 +18,13 @@ import ( const metricsNamespace = "galactic_nat" +// labelFamily is the label carrying an address family, familyNAT66 or +// familyNAT64. +const labelFamily = "family" + +// trafficLabels label the translated-traffic series. +var trafficLabels = []string{labelFamily, "direction", "action"} + // natCollector reads this shard's live map state at every scrape: drops by // reason, connection-table rows by address family, and live sessions by family // and protocol. It is a pull-based collector like the other datapaths', @@ -27,6 +34,7 @@ type natCollector struct { connTable *natmap.ConnTable connMaxEntries uint32 dropReasons natmap.DropReasonsReader + traffic natmap.TrafficReader // now reads the clock the datapath stamps last_seen with. Nil means // datapathNow. @@ -51,6 +59,7 @@ func newNatCollector(objs *natprog.NatObjects) *natCollector { connTable: natmap.NewConnTable(natmap.KernelTable{Map: objs.NatConnTable}), connMaxEntries: mapMaxEntries(objs.NatConnTable), dropReasons: objs.DropReasons, + traffic: objs.NatTraffic, } } @@ -68,13 +77,13 @@ var ( "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, + []string{labelFamily}, 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, + []string{labelFamily, "proto"}, nil, ) oldestRowAgeDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "conn_table_oldest_row_age_seconds"), @@ -90,6 +99,20 @@ var ( "Capacity of nat_conn_table in rows.", nil, nil, ) + packetsDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "packets_total"), + "Packets this shard translated and queued for transmit, by address family, direction (outbound: tenant "+ + "to internet, return: internet to tenant) and action (redirect: out another interface, tx: out the "+ + "interface it arrived on). Packets the shard generates itself, such as Packet Too Big, and packets it "+ + "passes on unclaimed are not counted.", + trafficLabels, nil, + ) + bytesDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "bytes_total"), + "Bytes of the packets in galactic_nat_packets_total: the translated packet's IP header and payload, "+ + "without the Ethernet header or the SRv6 outer header a return packet carries.", + trafficLabels, nil, + ) dropsDesc = prometheus.NewDesc( prometheus.BuildFQName(metricsNamespace, "", "drops_total"), "Packets dropped by this shard's datapath, by reason (drop_reasons map).", @@ -104,6 +127,8 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) { ch <- oldestRowAgeDesc ch <- connTableMaxEntriesDesc ch <- dropsDesc + ch <- packetsDesc + ch <- bytesDesc } // Collect implements prometheus.Collector. @@ -111,6 +136,7 @@ func (c *natCollector) Collect(ch chan<- prometheus.Metric) { c.collectConns(ch) c.collectConnTableMaxEntries(ch) c.collectDrops(ch) + c.collectTraffic(ch) } // Family label values, one per address family a shard translates. @@ -198,7 +224,7 @@ func (c *natCollector) collectDrops(ch chan<- prometheus.Metric) { } totals, err := natmap.DropReasonTotals(c.dropReasons) if err != nil { - ch <- prometheus.NewInvalidMetric(dropsDesc, fmt.Errorf("read drop_reasons: %w", err)) + slog.Warn("cannot read drop_reasons; skipping drop metrics", "err", err) return } for i, total := range totals { @@ -209,3 +235,40 @@ func (c *natCollector) collectDrops(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric(dropsDesc, prometheus.CounterValue, float64(total), name) } } + +// collectTraffic reports every family, direction and action, zero included. +func (c *natCollector) collectTraffic(ch chan<- prometheus.Metric) { + if c.traffic == nil { + return + } + // Skipped rather than reported as an invalid metric, which the metrics + // server turns into a failed scrape of every other series. + totals, err := natmap.TrafficTotals(c.traffic) + if err != nil { + slog.Warn("cannot read nat_traffic; skipping translated traffic metrics", "err", err) + return + } + families := []struct { + id uint32 + label string + }{{natprog.TrafficFamilyNAT66, familyNAT66}, {natprog.TrafficFamilyNAT64, familyNAT64}} + directions := []struct { + id uint32 + label string + }{{natprog.TrafficDirectionOutbound, "outbound"}, {natprog.TrafficDirectionReturn, "return"}} + actions := []struct { + id uint32 + label string + }{{natprog.TrafficActionRedirect, "redirect"}, {natprog.TrafficActionTX, "tx"}} + for _, f := range families { + for _, d := range directions { + for _, a := range actions { + t := totals[natprog.TrafficSlot(f.id, d.id, a.id)] + ch <- prometheus.MustNewConstMetric(packetsDesc, prometheus.CounterValue, float64(t.Packets), + f.label, d.label, a.label) + ch <- prometheus.MustNewConstMetric(bytesDesc, prometheus.CounterValue, float64(t.Bytes), + f.label, d.label, a.label) + } + } + } +} diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index e11553174..62c051f53 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -65,8 +65,10 @@ type natDatapath struct { // ones whose forwarding sysctls have been applied. uplinks []string configured map[string]bool - // missing is the resolved uplinks the datapath does not cover. - missing []string + // missing is the resolved uplinks the datapath does not cover, and + // coverageUplinks the uplink set missing was computed against. + missing []string + coverageUplinks []string // nat64 is whether the programmed identity serves NAT64, which an uplink // found later needs IPv4 forwarding for, as Program gives the rest. nat64 bool @@ -96,10 +98,20 @@ func (d *natDatapath) Uplinks() []string { return slices.Clone(d.uplinks) } -// setMissing records missing, reporting whether it changed. -func (d *natDatapath) setMissing(missing []string) bool { +// Coverage reports the uplinks the latest coverage pass checked and the ones +// among them the datapath misses, read together so the two always agree. +func (d *natDatapath) Coverage() (uplinks, missing []string) { d.mu.Lock() defer d.mu.Unlock() + return slices.Clone(d.coverageUplinks), slices.Clone(d.missing) +} + +// setCoverage records missing as the uplinks the datapath misses among +// uplinks, reporting whether missing changed. +func (d *natDatapath) setCoverage(uplinks, missing []string) bool { + d.mu.Lock() + defer d.mu.Unlock() + d.coverageUplinks = slices.Clone(uplinks) if slices.Equal(d.missing, missing) { return false } @@ -283,6 +295,7 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, d.configured[iface] = true } d.uplinks = uplinks + d.coverageUplinks = uplinks objs, err := natattach.Load(natattach.PinDir) if err != nil { @@ -491,7 +504,7 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover missing := uncovered(uplinks, cover(ready)) - if !d.setMissing(missing) { + if !d.setCoverage(uplinks, missing) { return } switch { diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index 9a32368ec..7769803f6 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -143,6 +143,10 @@ func runCmd(cfg *config.NATConfig) error { if err != nil { return fmt.Errorf("setup egress translation eBPF datapath: %w", err) } + if err := ctrlmetrics.Registry.Register( + newShardStateCollector(datapath, cfg.DatapathEnabled, cfg.XDPAttach)); err != nil { + return fmt.Errorf("register egress shard state metrics: %w", err) + } coverageEvents := make(chan event.GenericEvent, 1) go followCoverage(ctx, datapath, healthSrv, coverageChanged, coverageEvents) diff --git a/cmd/galactic-nat/state.go b/cmd/galactic-nat/state.go new file mode 100644 index 000000000..7aa8e99f9 --- /dev/null +++ b/cmd/galactic-nat/state.go @@ -0,0 +1,133 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "github.com/prometheus/client_golang/prometheus" + + "go.datum.net/galactic/internal/controller" + "go.datum.net/galactic/internal/metadata" +) + +// coverageReporter is the part of a datapath that knows which uplinks it +// checked and which of them it misses, read together. A datapath without it, +// like a turned-off one, has no uplinks to report. +type coverageReporter interface { + Coverage() (uplinks, missing []string) +} + +// shardStateCollector reports, at every scrape, whether this shard is turned +// on, attached and programmed, which uplinks it covers, which families it +// serves, and an info series naming its identity and build. A shard that is +// attached but unprogrammed, or misses an uplink, passes traffic through +// untranslated, and these series are how that shows outside the logs. +type shardStateCollector struct { + datapath controller.EgressDatapath + enabled bool + xdpAttach string + version string +} + +// newShardStateCollector builds a collector over datapath. enabled is whether +// the datapath is turned on by configuration, and xdpAttach the attach mode +// it was configured with. +func newShardStateCollector(datapath controller.EgressDatapath, enabled bool, xdpAttach string) *shardStateCollector { + return &shardStateCollector{datapath: datapath, enabled: enabled, xdpAttach: xdpAttach, version: metadata.Version} +} + +var ( + datapathEnabledDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "datapath_enabled"), + "1 when this shard's datapath is turned on by configuration, 0 when it is turned off and translates "+ + "nothing by design.", + nil, nil, + ) + datapathAttachedDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "datapath_attached"), + "1 once this shard's datapath has loaded and attached to its uplinks or the XDP dispatcher, 0 before "+ + "that or when the datapath is turned off.", + nil, nil, + ) + programmedDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "programmed"), + "1 when the datapath holds an EgressShard identity to translate with, 0 when it claims no packet.", + nil, nil, + ) + uplinkCoveredDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "uplink_covered"), + "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.", + []string{"interface"}, nil, + ) + familyEnabledDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "family_enabled"), + "1 when the programmed identity has a masquerade address for this family, so the shard translates it.", + []string{labelFamily}, nil, + ) + shardInfoDesc = prometheus.NewDesc( + prometheus.BuildFQName(metricsNamespace, "", "info"), + "Always 1. Labels carry the programmed shard SID and NAT64 prefix, empty while unprogrammed, the XDP "+ + "attach mode (off when the datapath is turned off) and the build version.", + []string{"shard_sid", "nat64_prefix", "xdp_attach", "version"}, nil, + ) +) + +// Describe implements prometheus.Collector. +func (c *shardStateCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- datapathEnabledDesc + ch <- datapathAttachedDesc + ch <- programmedDesc + ch <- uplinkCoveredDesc + ch <- familyEnabledDesc + ch <- shardInfoDesc +} + +// Collect implements prometheus.Collector. +func (c *shardStateCollector) Collect(ch chan<- prometheus.Metric) { + identity, programmed := c.datapath.Programmed() + + ch <- prometheus.MustNewConstMetric(datapathEnabledDesc, prometheus.GaugeValue, boolValue(c.enabled)) + ch <- prometheus.MustNewConstMetric(datapathAttachedDesc, prometheus.GaugeValue, boolValue(c.datapath.Attached())) + ch <- prometheus.MustNewConstMetric(programmedDesc, prometheus.GaugeValue, boolValue(programmed)) + + if reporter, ok := c.datapath.(coverageReporter); ok { + uplinks, missingList := reporter.Coverage() + missing := map[string]bool{} + for _, iface := range missingList { + missing[iface] = true + } + for _, iface := range uplinks { + ch <- prometheus.MustNewConstMetric(uplinkCoveredDesc, prometheus.GaugeValue, boolValue(!missing[iface]), iface) + } + } + + ch <- prometheus.MustNewConstMetric(familyEnabledDesc, prometheus.GaugeValue, + boolValue(programmed && identity.ShardAddressIPv6.IsValid()), familyNAT66) + ch <- prometheus.MustNewConstMetric(familyEnabledDesc, prometheus.GaugeValue, + boolValue(programmed && identity.ShardAddressIPv4.IsValid()), familyNAT64) + + var shardSID, nat64Prefix string + if programmed { + if identity.ShardSID.IsValid() { + shardSID = identity.ShardSID.String() + } + if identity.NAT64Prefix.IsValid() { + nat64Prefix = identity.NAT64Prefix.String() + } + } + xdpAttach := c.xdpAttach + if !c.enabled { + xdpAttach = "off" + } + ch <- prometheus.MustNewConstMetric(shardInfoDesc, prometheus.GaugeValue, 1, + shardSID, nat64Prefix, xdpAttach, c.version) +} + +func boolValue(b bool) float64 { + if b { + return 1 + } + return 0 +} diff --git a/cmd/galactic-nat/state_test.go b/cmd/galactic-nat/state_test.go new file mode 100644 index 000000000..2a56c10dd --- /dev/null +++ b/cmd/galactic-nat/state_test.go @@ -0,0 +1,233 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "errors" + "net/netip" + "strings" + "testing" + + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + + "go.datum.net/galactic/internal/controller" + "go.datum.net/galactic/internal/plumbing/ebpf/natprog" +) + +const ( + testUplink0 = "up0" + testUplink1 = "up1" + + metricDatapathEnabled = "galactic_nat_datapath_enabled" + metricDatapathAttached = "galactic_nat_datapath_attached" + metricProgrammed = "galactic_nat_programmed" + metricUplinkCovered = "galactic_nat_uplink_covered" + metricFamilyEnabled = "galactic_nat_family_enabled" + metricInfo = "galactic_nat_info" + metricPacketsTotal = "galactic_nat_packets_total" + metricBytesTotal = "galactic_nat_bytes_total" +) + +// gatherAll collects c through a registry and returns every series by metric +// name and its label values joined with "/", counters and gauges alike. +func gatherAll(t *testing.T, c prometheus.Collector) map[string]map[string]float64 { + 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) + } + out := map[string]map[string]float64{} + for _, mf := range families { + 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()) + } + value := m.GetGauge().GetValue() + if mf.GetType() == dto.MetricType_COUNTER { + value = m.GetCounter().GetValue() + } + series[strings.Join(labels, "/")] = value + } + out[mf.GetName()] = series + } + return out +} + +// fakeTraffic is a natmap.TrafficReader over fixed per-CPU slot values. +type fakeTraffic struct { + perCPU map[uint32][]natprog.NatNatTrafficCounter + err error +} + +func (f fakeTraffic) Lookup(key, valueOut any) error { + if f.err != nil { + return f.err + } + *valueOut.(*[]natprog.NatNatTrafficCounter) = f.perCPU[key.(uint32)] + return nil +} + +func TestNatCollectorReportsTranslatedTraffic(t *testing.T) { + outboundRedirect := natprog.TrafficSlot(natprog.TrafficFamilyNAT66, natprog.TrafficDirectionOutbound, + natprog.TrafficActionRedirect) + returnTX := natprog.TrafficSlot(natprog.TrafficFamilyNAT64, natprog.TrafficDirectionReturn, + natprog.TrafficActionTX) + c := &natCollector{traffic: fakeTraffic{perCPU: map[uint32][]natprog.NatNatTrafficCounter{ + outboundRedirect: {{Packets: 2, Bytes: 200}, {Packets: 3, Bytes: 300}}, + returnTX: {{Packets: 1, Bytes: 60}}, + }}} + + got := gatherAll(t, c) + for _, name := range []string{metricPacketsTotal, metricBytesTotal} { + if n := len(got[name]); n != 8 { + t.Errorf("%s has %d series, want all 8 family/direction/action combinations: %v", name, n, got[name]) + } + } + checks := []struct { + name, labels string + want float64 + }{ + {metricPacketsTotal, "redirect/outbound/nat66", 5}, + {metricBytesTotal, "redirect/outbound/nat66", 500}, + {metricPacketsTotal, "tx/return/nat64", 1}, + {metricBytesTotal, "tx/return/nat64", 60}, + {metricPacketsTotal, "tx/outbound/nat66", 0}, + } + for _, c := range checks { + if v, ok := got[c.name][c.labels]; !ok || v != c.want { + t.Errorf("%s{%s} = %v (present %v), want %v", c.name, c.labels, v, ok, c.want) + } + } +} + +func TestNatCollectorTrafficReadErrorKeepsOtherSeries(t *testing.T) { + c := &natCollector{ + traffic: fakeTraffic{err: errors.New("lookup failed")}, + dropReasons: fakeDropReasons{}, + } + got := gatherAll(t, c) + if _, ok := got[metricPacketsTotal]; ok { + t.Errorf("reported %s after a failed nat_traffic read", metricPacketsTotal) + } + if len(got["galactic_nat_drops_total"]) == 0 { + t.Error("a failed nat_traffic read suppressed the drop counters") + } +} + +// fakeDropReasons answers every drop_reasons lookup with one CPU's zero. +type fakeDropReasons struct{} + +func (fakeDropReasons) Lookup(_, valueOut any) error { + *valueOut.(*[]uint64) = []uint64{0} + return nil +} + +// fakeShard is a controller.EgressDatapath with a fixed state, and the uplinks +// and coverage a natDatapath reports. +type fakeShard struct { + attached bool + uplinks []string + missing []string + identity controller.EgressShardIdentity + programmed bool +} + +func (f fakeShard) Attached() bool { return f.attached } +func (f fakeShard) MissingUplinks() []string { return f.missing } +func (f fakeShard) Coverage() ([]string, []string) { return f.uplinks, f.missing } +func (fakeShard) Program(controller.EgressShardIdentity) error { return nil } +func (fakeShard) Clear() error { return nil } +func (f fakeShard) Programmed() (controller.EgressShardIdentity, bool) { + return f.identity, f.programmed +} + +func TestShardStateCollector(t *testing.T) { + sid := netip.MustParseAddr("fc00:1:2::") + tests := []struct { + name string + datapath controller.EgressDatapath + enabled bool + want map[string]map[string]float64 + }{ + { + name: "ProgrammedNAT66MissingOneUplink", + datapath: fakeShard{ + attached: true, uplinks: []string{testUplink0, testUplink1}, missing: []string{testUplink1}, programmed: true, + identity: controller.EgressShardIdentity{ + ShardSID: sid, ShardAddressIPv6: netip.MustParseAddr("2001:db8::1"), + }, + }, + enabled: true, + want: map[string]map[string]float64{ + metricDatapathEnabled: {"": 1}, + metricDatapathAttached: {"": 1}, + metricProgrammed: {"": 1}, + metricUplinkCovered: {testUplink0: 1, testUplink1: 0}, + metricFamilyEnabled: {familyNAT66: 1, familyNAT64: 0}, + metricInfo: {"/fc00:1:2::/test/dispatch": 1}, + }, + }, + { + name: "AttachedUnprogrammed", + datapath: fakeShard{attached: true, uplinks: []string{testUplink0}}, + enabled: true, + want: map[string]map[string]float64{ + metricDatapathEnabled: {"": 1}, + metricDatapathAttached: {"": 1}, + metricProgrammed: {"": 0}, + metricUplinkCovered: {testUplink0: 1}, + metricFamilyEnabled: {familyNAT66: 0, familyNAT64: 0}, + metricInfo: {"//test/dispatch": 1}, + }, + }, + { + name: "TurnedOff", + datapath: disabledDatapath{}, + enabled: false, + want: map[string]map[string]float64{ + metricDatapathEnabled: {"": 0}, + metricDatapathAttached: {"": 0}, + metricProgrammed: {"": 0}, + metricFamilyEnabled: {familyNAT66: 0, familyNAT64: 0}, + metricInfo: {"//test/off": 1}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := newShardStateCollector(tt.datapath, tt.enabled, "dispatch") + c.version = "test" + got := gatherAll(t, c) + if len(got) != len(tt.want) { + t.Errorf("got metrics %v, want exactly %v", keys(got), keys(tt.want)) + } + for name, series := range tt.want { + for labels, want := range series { + if v, ok := got[name][labels]; !ok || v != want { + t.Errorf("%s{%s} = %v (present %v), want %v; all: %v", name, labels, v, ok, want, got[name]) + } + } + if len(got[name]) != len(series) { + t.Errorf("%s has series %v, want %v", name, got[name], series) + } + } + }) + } +} + +func keys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +} diff --git a/config/monitoring/prometheusrule.yaml b/config/monitoring/prometheusrule.yaml index 05cb59373..a6dbdff51 100644 --- a/config/monitoring/prometheusrule.yaml +++ b/config/monitoring/prometheusrule.yaml @@ -341,6 +341,104 @@ spec: {{ $value | humanizePercentage }} of its packets for 10 minutes while no more than half of the interface's queues have. Flows hashed to that queue fail on every retry. Bouncing the interface clears it, once its bond partner is confirmed up. + # A shard that is turned on but holds no EgressShard identity claims no + # packet: tenants routed to it get no egress. Ten minutes covers a + # restart and the first reconcile. + - alert: GalacticNatNotProgrammed + expr: >- + galactic_nat_datapath_enabled{job="galactic-nat"} == 1 + and on (node) + galactic_nat_programmed{job="galactic-nat"} == 0 + for: 10m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "The egress shard on {{ $labels.node }} is running but not programmed" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatnotprogrammed" + description: >- + galactic-nat on {{ $labels.node }} has been turned on for 10 minutes without an EgressShard identity + to translate with, so it claims no packet. Check that an EgressShard targets the node and what its + status conditions say. + # Traffic arriving on an uplink the datapath does not cover leaves + # untranslated: tenants whose flows hash onto that link have no egress. + - alert: GalacticNatUplinkUncovered + expr: galactic_nat_uplink_covered{job="galactic-nat"} == 0 + for: 10m + labels: + severity: critical + service: galactic + team: connect + annotations: + summary: "The egress shard on {{ $labels.node }} does not translate on uplink {{ $labels.interface }}" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatuplinkuncovered" + description: >- + galactic-nat on {{ $labels.node }} has not covered uplink {{ $labels.interface }} for 10 minutes, so + packets arriving on it leave untranslated. The shard's log names why it cannot attach there. + # Drops of traffic the shard owned, as a share of what it translated. + # The no-session return reasons are left out: they are mostly + # unsolicited internet traffic and scans, which no tenant sent. Three + # of the reasons kept (redirect_failed, no_egress_ifindex, + # adjust_head_failed) fire on either leg, so the denominator is every + # translated packet, both directions. A healthy shard drops almost none, so 1% over + # 15 minutes is a real fault (exhausted ports, malformed encapsulation, + # an egress link it cannot send on) rather than a burst, and is already + # enough loss to cut a TCP flow's throughput sharply. The volume floor + # keeps a few drops on a nearly idle shard from firing it. + - alert: GalacticNatForwardDropRatio + expr: | + ( + sum by (node) (rate(galactic_nat_drops_total{job="galactic-nat", 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_drops_total{job="galactic-nat", 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{job="galactic-nat"}[10m])) + ) + ) > 0.01 + and on (node) + ( + sum by (node) (rate(galactic_nat_drops_total{job="galactic-nat", 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{job="galactic-nat"}[10m])) + ) > 10 + for: 15m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "The egress shard on {{ $labels.node }} drops {{ $value | humanizePercentage }} of its traffic" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatforwarddropratio" + description: >- + galactic-nat on {{ $labels.node }} has dropped {{ $value | humanizePercentage }} of the packets it + owned, tenant traffic and replies to it, for 15 minutes. galactic_nat_drops_total by reason shows + which check refuses them. + # Compute nodes keep sending tenant traffic to this shard's SID, but the + # shard translates none of it outbound: the packets die between the + # fabric and the datapath (an uncovered uplink, a detached program, a + # dispatcher slot whose lease lapsed). Only hashed egress publishes the + # per-shard series this joins on. + - alert: GalacticNatNotTranslating + expr: | + max by (node, shard_sid) (galactic_nat_info{job="galactic-nat", shard_sid!=""}) + and on (node) + sum by (node) (rate(galactic_nat_packets_total{job="galactic-nat", direction="outbound"}[5m])) == 0 + and on (shard_sid) + sum by (shard_sid) (rate(galactic_cni_egress_shard_packets_total{job="galactic-cni"}[5m])) > 0.1 + for: 10m + labels: + severity: critical + service: galactic + team: connect + annotations: + summary: "The egress shard on {{ $labels.node }} translates nothing while tenants send to it" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatnottranslating" + description: >- + 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. - alert: GalacticNatMetricsDown expr: up{job="galactic-nat"} == 0 for: 5m @@ -352,9 +450,8 @@ spec: summary: "galactic-nat metrics on {{ $labels.node }} cannot be scraped" runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatmetricsdown" description: >- - Prometheus cannot reach galactic-nat's metrics port on {{ $labels.node }} (9182), so - GalacticNatSessionTableEvictingLive, GalacticNatPortExhausted and GalacticNatUplinkRxQueueStalled - cannot fire for it. + Prometheus cannot reach galactic-nat's metrics port on {{ $labels.node }} (9182), so no other + galactic-nat alert can fire for it. # From galactic-cni (job galactic-cni, port 9180): its egress shard groups, # one per translation class (nat66, or nat64:), and its own # control loop. A node in ordered mode with no group left publishes no diff --git a/config/monitoring/tests/rules-test.yaml b/config/monitoring/tests/rules-test.yaml index 85f177ca3..ae98c1efb 100644 --- a/config/monitoring/tests/rules-test.yaml +++ b/config/monitoring/tests/rules-test.yaml @@ -670,9 +670,8 @@ tests: summary: "galactic-nat metrics on dfw-worker2 cannot be scraped" runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatmetricsdown" description: >- - Prometheus cannot reach galactic-nat's metrics port on dfw-worker2 (9182), so - GalacticNatSessionTableEvictingLive, GalacticNatPortExhausted and GalacticNatUplinkRxQueueStalled - cannot fire for it. + Prometheus cannot reach galactic-nat's metrics port on dfw-worker2 (9182), so no other + galactic-nat alert can fire for it. # Hashed egress, NAT66 class: the node's only shard becomes unreachable at # 5m. GalacticEgressPoolEmpty fires after 2m, BelowMinimum after 10m. The @@ -1170,3 +1169,138 @@ tests: The fabric-api sidecar on dfw-worker holds routes but has not been in sync with bgpd's Loc-RIB for 15 minutes, so its AS-path and community searches are refused. bgpd's BMP session to the sidecar (bmp targets fabric-api, 127.0.0.1:9348) is down or has not completed its initial table. + + # Turned on and unprogrammed for 10m fires. A turned-off shard and a + # programmed one do not. + - interval: 30s + input_series: + - series: 'galactic_nat_datapath_enabled{job="galactic-nat",node="dfw-worker2"}' + values: "1x30" + - series: 'galactic_nat_programmed{job="galactic-nat",node="dfw-worker2"}' + values: "0x30" + - series: 'galactic_nat_datapath_enabled{job="galactic-nat",node="dfw-worker3"}' + values: "0x30" + - series: 'galactic_nat_programmed{job="galactic-nat",node="dfw-worker3"}' + values: "0x30" + - series: 'galactic_nat_datapath_enabled{job="galactic-nat",node="sjc-worker2"}' + values: "1x30" + - series: 'galactic_nat_programmed{job="galactic-nat",node="sjc-worker2"}' + values: "1x30" + alert_rule_test: + - eval_time: 8m + alertname: GalacticNatNotProgrammed + exp_alerts: [] + - eval_time: 12m + alertname: GalacticNatNotProgrammed + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + job: galactic-nat + node: dfw-worker2 + exp_annotations: + summary: "The egress shard on dfw-worker2 is running but not programmed" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatnotprogrammed" + description: >- + galactic-nat on dfw-worker2 has been turned on for 10 minutes without an EgressShard identity + to translate with, so it claims no packet. Check that an EgressShard targets the node and what its + status conditions say. + + # One uplink uncovered for 10m fires; the covered one does not. + - interval: 30s + input_series: + - series: 'galactic_nat_uplink_covered{job="galactic-nat",node="dfw-worker2",interface="eth1"}' + values: "1x30" + - series: 'galactic_nat_uplink_covered{job="galactic-nat",node="dfw-worker2",interface="eth2"}' + values: "0x30" + alert_rule_test: + - eval_time: 12m + alertname: GalacticNatUplinkUncovered + exp_alerts: + - exp_labels: + severity: critical + service: galactic + team: connect + job: galactic-nat + node: dfw-worker2 + interface: eth2 + exp_annotations: + summary: "The egress shard on dfw-worker2 does not translate on uplink eth2" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatuplinkuncovered" + description: >- + galactic-nat on dfw-worker2 has not covered uplink eth2 for 10 minutes, so + packets arriving on it leave untranslated. The shard's log names why it cannot attach there. + + # dfw-worker2 drops 2 packets a second against 100 translated, about 2%, + # and fires after 15m. sjc-worker2 drops half of a trickle, under the + # volume floor. iad-worker2 drops many unsolicited return packets, which are + # not tenant traffic, and fires nothing. + - interval: 30s + input_series: + - series: 'galactic_nat_packets_total{job="galactic-nat",node="dfw-worker2",family="nat66",direction="outbound",action="redirect"}' + values: "0+3000x60" + - series: 'galactic_nat_drops_total{job="galactic-nat",node="dfw-worker2",reason="nat66_pat_exhausted"}' + values: "0+60x60" + - series: 'galactic_nat_packets_total{job="galactic-nat",node="sjc-worker2",family="nat66",direction="outbound",action="redirect"}' + values: "0+30x60" + - series: 'galactic_nat_drops_total{job="galactic-nat",node="sjc-worker2",reason="nat66_malformed_forward"}' + values: "0+30x60" + - series: 'galactic_nat_packets_total{job="galactic-nat",node="iad-worker2",family="nat66",direction="outbound",action="redirect"}' + values: "0+3000x60" + - series: 'galactic_nat_drops_total{job="galactic-nat",node="iad-worker2",reason="nat66_no_return_conn"}' + values: "0+3000x60" + alert_rule_test: + - eval_time: 12m + alertname: GalacticNatForwardDropRatio + exp_alerts: [] + - eval_time: 27m + alertname: GalacticNatForwardDropRatio + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + node: dfw-worker2 + exp_annotations: + summary: "The egress shard on dfw-worker2 drops 1.961% of its traffic" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatforwarddropratio" + description: >- + galactic-nat on dfw-worker2 has dropped 1.961% of the packets it + owned, tenant traffic and replies to it, for 15 minutes. galactic_nat_drops_total by reason shows + which check refuses them. + + # Compute nodes send to dfw-worker2's shard SID throughout, but it translates + # nothing outbound, and fires after 10m. sjc-worker2's shard translates what + # it is sent. + - interval: 30s + input_series: + - series: 'galactic_nat_info{job="galactic-nat",node="dfw-worker2",shard_sid="fc00:1:2::",nat64_prefix="",xdp_attach="dispatch",version="v1"}' + values: "1x50" + - series: 'galactic_nat_packets_total{job="galactic-nat",node="dfw-worker2",family="nat66",direction="outbound",action="redirect"}' + values: "0x50" + - series: 'galactic_cni_egress_shard_packets_total{job="galactic-cni",node="dfw-worker",shard_sid="fc00:1:2::",class="nat66"}' + values: "0+300x50" + - series: 'galactic_nat_info{job="galactic-nat",node="sjc-worker2",shard_sid="fc00:2:2::",nat64_prefix="",xdp_attach="dispatch",version="v1"}' + values: "1x50" + - series: 'galactic_nat_packets_total{job="galactic-nat",node="sjc-worker2",family="nat66",direction="outbound",action="redirect"}' + values: "0+300x50" + - series: 'galactic_cni_egress_shard_packets_total{job="galactic-cni",node="sjc-worker",shard_sid="fc00:2:2::",class="nat66"}' + values: "0+300x50" + alert_rule_test: + - eval_time: 22m + alertname: GalacticNatNotTranslating + exp_alerts: + - exp_labels: + severity: critical + service: galactic + team: connect + node: dfw-worker2 + shard_sid: "fc00:1:2::" + exp_annotations: + summary: "The egress shard on dfw-worker2 translates nothing while tenants send to it" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatnottranslating" + description: >- + 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. diff --git a/docs/metrics.md b/docs/metrics.md index 3a9bb1e73..504862fbe 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -269,17 +269,44 @@ 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_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_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: + +- `outbound` is tenant traffic the shard decapsulated and translated toward + the internet; `return` is a reply translated back and encapsulated toward + the tenant. `tx` means the packet left over the uplink it arrived on, + `redirect` over another one. +- Messages the shard sends on its own behalf (Packet Too Big, Fragmentation + Needed, echo replies to its own address) and packets it passes on + unclaimed are not translations and are not counted. +- The counters live in a pinned map, so they outlive a pod restart, like + `galactic_nat_drops_total`. +- A shard can be attached and programmed and still translate nothing, when + its uplinks never hand it the traffic. Compare + `galactic_nat_packets_total{direction="outbound"}` with the compute nodes' + `galactic_cni_egress_shard_packets_total` for its `shard_sid` + (`GalacticNatNotTranslating`). +- Cardinality: 8 series each for packets and bytes, one `uplink_covered` + series per uplink, and one `info` series per shard. Caveats for the session table: @@ -331,6 +358,18 @@ sum by (node, reason) (increase(galactic_nat_drops_total{reason=~"nat(66|64)_pat # Drop rate by reason sum by (node, reason) (rate(galactic_nat_drops_total[5m])) > 0 +# Translated packets per shard and direction +sum by (node, direction) (rate(galactic_nat_packets_total[5m])) + +# Share of the shard's own traffic it dropped (GalacticNatForwardDropRatio) +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_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]))) + +# 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 + # Discard share per uplink receive queue (#673) rate(galactic_nat_uplink_rx_queue_discards_total[5m]) / (rate(galactic_nat_uplink_rx_queue_discards_total[5m]) + rate(galactic_nat_uplink_rx_queue_packets_total[5m])) @@ -345,24 +384,28 @@ sum by (node, interface, queue) ( `config/monitoring/prometheusrule.yaml` (the `galactic-bgp` PrometheusRule, unit-tested with `task test:alerts`) covers routing, the NAT session table -and ports, and the egress shards' uplinks. Every alert +and ports, the egress shards' state, drop ratio and uplinks. Every alert carries `service: galactic`, `team: connect` and a `runbook_url`. -| Alert | Fires when | For | Severity | -|--------------------------------------|---------------------------------------------------------|-----|----------| -| FabricBGPSessionDown | `frr_bgp_peer_state == 0` | 5m | critical | -| FabricBGPSessionAdminDown | `frr_bgp_peer_state == 2` | 1h | warning | -| FabricBGPSessionFlapping | `resets(frr_bgp_peer_uptime_seconds[30m]) >= 3` | 0 | warning | -| FabricBGPPrefixesDropped | received prefixes under half of an hour ago, session up | 15m | warning | -| FabricRouterExporterCollectorFailing | `frr_collector_up == 0` | 10m | warning | -| FabricRouterMetricsDown | `fabric-router` scrape down | 5m | warning | -| FabricBGPMappedNextHop | `fabric_router_bgp_mapped_nexthop == 1` | 15m | critical | -| FabricBGPRoutesNotInstalled | `fabric_router_bgp_uninstalled_routes > 0` | 10m | warning | -| FabricConfigAgentMetricsDown | `fabric-config-agent` scrape down | 5m | warning | -| GalacticRouterBMPStationDown | `galactic_router_bmp_station_up == 0` | 10m | warning | -| GalacticRouterRoutesNotInstalled | `galactic_router_route_install_failing > 0` | 10m | warning | -| GalacticRouterMetricsDown | `galactic-router` or `galactic-router-rr` scrape down | 5m | warning | -| GalacticNatSessionTableEvictingLive | table over 90% full, oldest row under 7440 s | 15m | warning | -| GalacticNatPortExhausted | `*_pat_exhausted` drops in every 10-minute window | 15m | warning | -| GalacticNatUplinkRxQueueStalled | one uplink rx queue discards >1%, most siblings do not | 10m | critical | -| GalacticNatMetricsDown | `galactic-nat` scrape down | 5m | warning | +| Alert | Fires when | For | Severity | +|--------------------------------------|--------------------------------------------------------------------|-----|----------| +| FabricBGPSessionDown | `frr_bgp_peer_state == 0` | 5m | critical | +| FabricBGPSessionAdminDown | `frr_bgp_peer_state == 2` | 1h | warning | +| FabricBGPSessionFlapping | `resets(frr_bgp_peer_uptime_seconds[30m]) >= 3` | 0 | warning | +| FabricBGPPrefixesDropped | received prefixes under half of an hour ago, session up | 15m | warning | +| FabricRouterExporterCollectorFailing | `frr_collector_up == 0` | 10m | warning | +| FabricRouterMetricsDown | `fabric-router` scrape down | 5m | warning | +| FabricBGPMappedNextHop | `fabric_router_bgp_mapped_nexthop == 1` | 15m | critical | +| FabricBGPRoutesNotInstalled | `fabric_router_bgp_uninstalled_routes > 0` | 10m | warning | +| FabricConfigAgentMetricsDown | `fabric-config-agent` scrape down | 5m | warning | +| GalacticRouterBMPStationDown | `galactic_router_bmp_station_up == 0` | 10m | warning | +| GalacticRouterRoutesNotInstalled | `galactic_router_route_install_failing > 0` | 10m | warning | +| GalacticRouterMetricsDown | `galactic-router` or `galactic-router-rr` scrape down | 5m | warning | +| GalacticNatSessionTableEvictingLive | table over 90% full, oldest row under 7440 s | 15m | warning | +| GalacticNatPortExhausted | `*_pat_exhausted` drops in every 10-minute window | 15m | warning | +| GalacticNatUplinkRxQueueStalled | one uplink rx queue discards >1%, most siblings do not | 10m | critical | +| GalacticNatNotProgrammed | turned on, no EgressShard identity | 10m | warning | +| 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 | +| GalacticNatMetricsDown | `galactic-nat` scrape down | 5m | warning | diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 2a1e9de2e..7e01e69ae 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -702,15 +702,23 @@ 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_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_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/natmap/dropreasons.go b/internal/plumbing/ebpf/natmap/dropreasons.go index 7113b61b8..28ad23769 100644 --- a/internal/plumbing/ebpf/natmap/dropreasons.go +++ b/internal/plumbing/ebpf/natmap/dropreasons.go @@ -46,3 +46,26 @@ func DropReasonTotals(reader DropReasonsReader) (map[uint32]uint64, error) { } return totals, nil } + +// TrafficReader narrows the nat_traffic map, a per-CPU array keyed by +// natprog.TrafficSlot, to the one operation TrafficTotals needs. +type TrafficReader interface { + Lookup(key, valueOut any) error +} + +// TrafficTotals reads every nat_traffic slot and returns its packets and bytes +// summed across CPUs, indexed by natprog.TrafficSlot. +func TrafficTotals(reader TrafficReader) ([natprog.TrafficSlots]natprog.NatNatTrafficCounter, error) { + var totals [natprog.TrafficSlots]natprog.NatNatTrafficCounter + for slot := range natprog.TrafficSlots { + var perCPU []natprog.NatNatTrafficCounter + if err := reader.Lookup(slot, &perCPU); err != nil { + return totals, fmt.Errorf("natmap: nat_traffic: lookup[%d]: %w", slot, err) + } + for _, v := range perCPU { + totals[slot].Packets += v.Packets + totals[slot].Bytes += v.Bytes + } + } + return totals, nil +} diff --git a/internal/plumbing/ebpf/natprog/doc.go b/internal/plumbing/ebpf/natprog/doc.go index a17afd2a5..7992b85c9 100644 --- a/internal/plumbing/ebpf/natprog/doc.go +++ b/internal/plumbing/ebpf/natprog/doc.go @@ -86,4 +86,4 @@ const ( // within their packed structs, so they are genuinely 2-byte aligned despite the // packed attribute. // -//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -Wno-address-of-packed-member -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type conn_key -type conn_value -type shard_config Nat nat.c +//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -Wno-address-of-packed-member -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type conn_key -type conn_value -type shard_config -type nat_traffic_counter Nat nat.c diff --git a/internal/plumbing/ebpf/natprog/icmpgen_test.go b/internal/plumbing/ebpf/natprog/icmpgen_test.go index b52ae4c88..cc5792e05 100644 --- a/internal/plumbing/ebpf/natprog/icmpgen_test.go +++ b/internal/plumbing/ebpf/natprog/icmpgen_test.go @@ -151,15 +151,22 @@ func TestPacketTooBig_ReplyTooBigForTheFabric(t *testing.T) { masqPort := binary.BigEndian.Uint16(out[ethLen+ip6Len:]) small := buildUDPPacket(t, f.shardPub, f.peer, encappedDstPort, masqPort, []byte("small")) - if ret, _ := f.run(t, small); ret != xdpRedirect { + before := trafficSnapshot(t, f.objs) + ret, smallOut := f.run(t, small) + if ret != xdpRedirect { t.Fatalf("small reply verdict = %d, want XDP_REDIRECT (%d) over the fabric link", ret, xdpRedirect) } + assertTranslatedDelta(t, f.objs, before, TrafficFamilyNAT66, TrafficDirectionReturn, ret, smallOut) + // The Packet Too Big the shard sends in place of the big reply is its + // own message, not a translation. big := buildUDPPacket(t, f.shardPub, f.peer, encappedDstPort, masqPort, make([]byte, bigPayload)) - ret, out := f.run(t, big) + before = trafficSnapshot(t, f.objs) + ret, out = f.run(t, big) if ret != xdpRedirect { t.Fatalf("verdict = %d, want XDP_REDIRECT (%d): the Packet Too Big routed to its sender", ret, xdpRedirect) } + assertNoTranslatedDelta(t, f.objs, before) if got := sumPerCPU(t, f.objs.DropReasons, DropReasonNatFibFragNeeded); got != 1 { t.Errorf("drop_reasons[fib_frag_needed] = %d, want 1 -- the reply is still dropped", got) } diff --git a/internal/plumbing/ebpf/natprog/nat.c b/internal/plumbing/ebpf/natprog/nat.c index eaac79c29..20b49ba87 100644 --- a/internal/plumbing/ebpf/natprog/nat.c +++ b/internal/plumbing/ebpf/natprog/nat.c @@ -590,6 +590,46 @@ struct { __type(value, __u64); } drop_reasons SEC(".maps"); +// Translated traffic, by address family, direction and how the packet left. +// The slot is family * 4 + direction * 2 + action, mirrored in Go by +// natprog.TrafficSlot. +enum nat_traffic_family { + NAT_TRAFFIC_NAT66 = 0, + NAT_TRAFFIC_NAT64 = 1, +}; + +enum nat_traffic_direction { + NAT_TRAFFIC_OUTBOUND = 0, // tenant to internet, decapsulated and translated + NAT_TRAFFIC_RETURN = 1, // internet to tenant, translated and encapsulated +}; + +enum nat_traffic_action { + NAT_TRAFFIC_REDIRECT = 0, // left over another interface + NAT_TRAFFIC_TX = 1, // left over the interface it arrived on +}; + +#define NAT_TRAFFIC_SLOTS 8 + +// struct nat_traffic_counter is one slot's translated packets and bytes, per +// CPU. bytes is the translated packet's IP header and payload, without the +// Ethernet header or the SRv6 outer header a return packet carries, so the +// two directions measure the same thing. +struct nat_traffic_counter { + __u64 packets; + __u64 bytes; +}; + +// nat_traffic counts every packet a leg translated and queued for transmit. +// Packets the shard generates itself (Packet Too Big, Fragmentation Needed, +// echo replies) and packets it passes on unclaimed are not translations and +// are not counted here. +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, NAT_TRAFFIC_SLOTS); + __type(key, __u32); + __type(value, struct nat_traffic_counter); +} nat_traffic SEC(".maps"); + // struct icmp_bucket is one CPU's token bucket, held as nanoseconds of credit // rather than whole tokens so a refill is an addition, with no division on the // packet path: each message costs NAT_ICMP_COST_NS, and credit accrues one @@ -1143,6 +1183,30 @@ static NAT_ALWAYS_INLINE int leave_via(struct xdp_md *ctx, __u32 egress_ifindex) return XDP_REDIRECT; } +// leave_translated is leave_via for a packet a leg translated, counting it in +// nat_traffic once it is queued for transmit: one per-CPU slot update, packets +// and bytes together. A return packet carries the SRv6 outer header, which is +// left out of its bytes. +static NAT_ALWAYS_INLINE int leave_translated(struct xdp_md *ctx, __u32 egress_ifindex, __u32 family, + __u32 direction) +{ + __u64 len = ctx->data_end - ctx->data; + __u64 headers = sizeof(struct nat_ethhdr) + (direction == NAT_TRAFFIC_RETURN ? NAT_IP6HDR_LEN : 0); + int rc = leave_via(ctx, egress_ifindex); + + if (rc != XDP_TX && rc != XDP_REDIRECT) + return rc; + + __u32 slot = family * 4 + direction * 2 + (rc == XDP_TX ? NAT_TRAFFIC_TX : NAT_TRAFFIC_REDIRECT); + struct nat_traffic_counter *c = bpf_map_lookup_elem(&nat_traffic, &slot); + + if (c) { + c->packets += 1; + c->bytes += len > headers ? len - headers : 0; + } + return rc; +} + // push_outer_header uses the same mechanism as the other datapath programs' // function of the same name. Copied rather than shared, since each program // defines its own surrounding header structs. @@ -1566,7 +1630,7 @@ static NAT_ALWAYS_INLINE int nat66_forward_leg(struct xdp_md *ctx, const int icm return XDP_DROP; } - return leave_via(ctx, egress_ifindex); + return leave_translated(ctx, egress_ifindex, NAT_TRAFFIC_NAT66, NAT_TRAFFIC_OUTBOUND); } SEC("xdp") @@ -1753,7 +1817,7 @@ static NAT_ALWAYS_INLINE int send_frag_needed4(struct xdp_md *ctx, struct shard_ // a translated ICMP error is never answered with another. static NAT_ALWAYS_INLINE int reencap_to_tenant(struct xdp_md *ctx, struct shard_config *cfg, struct nat_ip6hdr *ip6, const __u8 usid[16], - const __be32 *quote) + const __be32 *quote, __u32 family) { // Must include the inner IPv6 header's own 40 bytes, not just its payload. // Passing the inner payload length alone undercounts the outer header's @@ -1778,7 +1842,7 @@ static NAT_ALWAYS_INLINE int reencap_to_tenant(struct xdp_md *ctx, struct shard_ return XDP_DROP; } - return leave_via(ctx, egress_ifindex); + return leave_translated(ctx, egress_ifindex, family, NAT_TRAFFIC_RETURN); } // nat66_return_leg un-SNATs a reply whose transport view the caller has already @@ -1819,7 +1883,7 @@ static NAT_ALWAYS_INLINE int nat66_return_leg(struct xdp_md *ctx, struct shard_c __builtin_memcpy(ip6->daddr, cv->backend_addr, 16); *l4v->dport_ptr = cv->backend_port; - return reencap_to_tenant(ctx, cfg, ip6, cv->backend_usid, quote); + return reencap_to_tenant(ctx, cfg, ip6, cv->backend_usid, quote, NAT_TRAFFIC_NAT66); } // nat66_return: a reply from the IPv6 internet, addressed to this shard's own @@ -1922,7 +1986,7 @@ static NAT_ALWAYS_INLINE int nat66_icmp_error(struct xdp_md *ctx, struct shard_c __builtin_memcpy(quoted->saddr, cv->backend_addr, 16); *q.masq_ptr = cv->backend_port; - return reencap_to_tenant(ctx, cfg, ip6, cv->backend_usid, 0); + return reencap_to_tenant(ctx, cfg, ip6, cv->backend_usid, 0, NAT_TRAFFIC_NAT66); } // echo_respond6 is echo_respond4 for shard_pub_addr6. Swapping the addresses @@ -2256,7 +2320,7 @@ static NAT_ALWAYS_INLINE int nat64_forward_leg(struct xdp_md *ctx, const int icm return XDP_DROP; } - return leave_via(ctx, egress_ifindex); + return leave_translated(ctx, egress_ifindex, NAT_TRAFFIC_NAT64, NAT_TRAFFIC_OUTBOUND); } SEC("xdp") @@ -2427,7 +2491,7 @@ static NAT_ALWAYS_INLINE int nat64_return_leg(struct xdp_md *ctx, struct shard_c return XDP_DROP; } - return leave_via(ctx, egress_ifindex); + return leave_translated(ctx, egress_ifindex, NAT_TRAFFIC_NAT64, NAT_TRAFFIC_RETURN); } // nat64_return: a TCP or UDP reply from the IPv4 internet, addressed to this @@ -2823,7 +2887,7 @@ int nat64_icmp_error(struct xdp_md *ctx) __builtin_memcpy(ip6->daddr, dst6, 16); __builtin_memcpy((void *) (ip6 + 1), msg, sizeof(msg)); - return reencap_to_tenant(ctx, cfg, ip6, usid, 0); + return reencap_to_tenant(ctx, cfg, ip6, usid, 0, NAT_TRAFFIC_NAT64); } // echo_respond4 answers an Echo Request addressed to shard_pub_addr4, when the diff --git a/internal/plumbing/ebpf/natprog/nat64_test.go b/internal/plumbing/ebpf/natprog/nat64_test.go index f077f0858..ebdeeec5b 100644 --- a/internal/plumbing/ebpf/natprog/nat64_test.go +++ b/internal/plumbing/ebpf/natprog/nat64_test.go @@ -158,11 +158,13 @@ func TestNat64Forward_TranslatesIPv6ToIPv4(t *testing.T) { pkt := buildEncappedUDPPacket(t, sidWithArgument(shardSID, 0x123), backendUSID, backendAddr, destAddr, payload) + before := trafficSnapshot(t, objs) ret, out, err := objs.NatIngress.Test(pkt) if err != nil { t.Fatalf("program test-run: %v", err) } assertLeftFromDatapath(t, ret) + assertTranslatedDelta(t, objs, before, TrafficFamilyNAT64, TrafficDirectionOutbound, ret, out) if got := binary.BigEndian.Uint16(out[12:14]); got != 0x0800 { t.Fatalf("ethertype = %#04x, want 0x0800 -- an IPv4 packet behind an IPv6 EtherType is "+ @@ -263,10 +265,12 @@ func TestNat64Return_TranslatesIPv4BackAndReencapsulates(t *testing.T) { replyPkt := buildIPv4UDPPacket(t, shardPub4, peer4, encappedDstPort, masqPort, []byte("reply")) + before := trafficSnapshot(t, objs) ret, out, err := objs.NatIngress.Test(replyPkt) if err != nil { t.Fatalf("return program test-run: %v", err) } + assertTranslatedDelta(t, objs, before, TrafficFamilyNAT64, TrafficDirectionReturn, ret, out) // Same as the NAT66 return leg: push_outer_header's FIB lookup against a // synthetic backend uSID cannot resolve on a test host, so the packet is // fully translated and then dropped at the last step. diff --git a/internal/plumbing/ebpf/natprog/nat_test.go b/internal/plumbing/ebpf/natprog/nat_test.go index d9de46339..20e90d04f 100644 --- a/internal/plumbing/ebpf/natprog/nat_test.go +++ b/internal/plumbing/ebpf/natprog/nat_test.go @@ -328,11 +328,13 @@ func TestNatIngress_ForwardSNATsAndPreservesChecksum(t *testing.T) { pkt := buildEncappedUDPPacket(t, netip.AddrFrom16(shardSIDWithArg), backendUSID, backendAddr, destAddr, payload) + before := trafficSnapshot(t, objs) ret, out, err := objs.NatIngress.Test(pkt) if err != nil { t.Fatalf("program test-run: %v", err) } assertLeftFromDatapath(t, ret) + assertTranslatedDelta(t, objs, before, TrafficFamilyNAT66, TrafficDirectionOutbound, ret, out) // The decapsulated frame must still carry a real link header. Widening the // head past it and reclaiming 14 bytes exposes the old packet's bytes at @@ -561,10 +563,12 @@ func TestNatIngress_ReturnUnNATsAndReencapsulates(t *testing.T) { // Now the reply: from destAddr:destPort, to shardPub:masqPort. replyPkt := buildUDPPacket(t, shardPub, destAddr, destPort, masqPort, []byte("reply")) + before := trafficSnapshot(t, objs) ret, out, err := objs.NatIngress.Test(replyPkt) if err != nil { t.Fatalf("return program test-run: %v", err) } + assertTranslatedDelta(t, objs, before, TrafficFamilyNAT66, TrafficDirectionReturn, ret, out) if ret != xdpDrop { t.Fatalf("verdict = %d, want XDP_DROP (%d) (FIB lookup against a synthetic backend uSID must "+ "fail, not succeed, on this test host)", ret, xdpDrop) diff --git a/internal/plumbing/ebpf/natprog/traffic.go b/internal/plumbing/ebpf/natprog/traffic.go new file mode 100644 index 000000000..ba11de7f2 --- /dev/null +++ b/internal/plumbing/ebpf/natprog/traffic.go @@ -0,0 +1,29 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natprog + +// Translated-traffic slot layout of the nat_traffic map, mirroring the +// datapath's enums. Hand-kept in sync with the C source, like the drop +// reasons, because the generator produces no Go type for an enum used only +// as a literal constant. +const ( + TrafficFamilyNAT66 uint32 = 0 + TrafficFamilyNAT64 uint32 = 1 + + TrafficDirectionOutbound uint32 = 0 + TrafficDirectionReturn uint32 = 1 + + TrafficActionRedirect uint32 = 0 + TrafficActionTX uint32 = 1 + + // TrafficSlots is the nat_traffic map's entry count, one per family, + // direction and action. + TrafficSlots uint32 = 8 +) + +// TrafficSlot returns the nat_traffic index for family, direction and action. +func TrafficSlot(family, direction, action uint32) uint32 { + return family*4 + direction*2 + action +} diff --git a/internal/plumbing/ebpf/natprog/traffic_test.go b/internal/plumbing/ebpf/natprog/traffic_test.go new file mode 100644 index 000000000..551d5c98b --- /dev/null +++ b/internal/plumbing/ebpf/natprog/traffic_test.go @@ -0,0 +1,121 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natprog + +import ( + "encoding/binary" + "testing" +) + +// trafficSnapshot reads every nat_traffic slot summed across CPUs. +func trafficSnapshot(t *testing.T, objs *NatObjects) [TrafficSlots]NatNatTrafficCounter { + t.Helper() + var totals [TrafficSlots]NatNatTrafficCounter + for slot := range TrafficSlots { + var perCPU []NatNatTrafficCounter + if err := objs.NatTraffic.Lookup(slot, &perCPU); err != nil { + t.Fatalf("lookup nat_traffic[%d]: %v", slot, err) + } + for _, v := range perCPU { + totals[slot].Packets += v.Packets + totals[slot].Bytes += v.Bytes + } + } + return totals +} + +// assertTranslatedDelta checks that one program run, which returned ret and +// left out on the wire, moved nat_traffic by exactly what that verdict means: +// one packet of the translated packet's length in the family and direction's +// slot for the action ret names, and nothing anywhere else. A dropped packet +// moves nothing. A return packet carries the SRv6 outer header, which the +// counter leaves out. +func assertTranslatedDelta(t *testing.T, objs *NatObjects, before [TrafficSlots]NatNatTrafficCounter, + family, direction, ret uint32, out []byte, +) { + t.Helper() + want := before + switch ret { + case xdpTx, xdpRedirect: + action := TrafficActionRedirect + if ret == xdpTx { + action = TrafficActionTX + } + headers := ethLen + if direction == TrafficDirectionReturn { + headers += ip6Len + } + slot := TrafficSlot(family, direction, action) + want[slot].Packets++ + want[slot].Bytes += uint64(len(out) - headers) //nolint:gosec // a frame is far smaller than 2^63 + } + if got := trafficSnapshot(t, objs); got != want { + t.Errorf("nat_traffic after verdict %d = %+v, want %+v", ret, got, want) + } +} + +// assertNoTranslatedDelta checks a run counted nothing as translated. +func assertNoTranslatedDelta(t *testing.T, objs *NatObjects, before [TrafficSlots]NatNatTrafficCounter) { + t.Helper() + if got := trafficSnapshot(t, objs); got != before { + t.Errorf("nat_traffic = %+v, want unchanged %+v", got, before) + } +} + +// TestNatTraffic_CountsEachLegOnce drives a session through both legs of each +// family over routes the FIB lookup resolves, so every translated packet leaves +// the datapath: each leg counts one packet of its translated length in its own +// slot, and a reply too big for the fabric, answered by the shard's own error +// instead, counts nothing. +func TestNatTraffic_CountsEachLegOnce(t *testing.T) { + t.Run("nat66", func(t *testing.T) { + f := newNAT66Fixture(t) + narrowFabric(t, f.backendUSID, f.peer) + + before := trafficSnapshot(t, f.objs) + ret, out := f.run(t, buildEncappedUDPPacket(t, sidWithArgument(f.shardSID, 0x123), f.backendUSID, + f.backend, f.peer, []byte("out"))) + requireLeft(t, ret) + assertTranslatedDelta(t, f.objs, before, TrafficFamilyNAT66, TrafficDirectionOutbound, ret, out) + masqPort := binary.BigEndian.Uint16(out[ethLen+ip6Len:]) + + before = trafficSnapshot(t, f.objs) + ret, out = f.run(t, buildUDPPacket(t, f.shardPub, f.peer, encappedDstPort, masqPort, []byte("reply"))) + requireLeft(t, ret) + assertTranslatedDelta(t, f.objs, before, TrafficFamilyNAT66, TrafficDirectionReturn, ret, out) + + before = trafficSnapshot(t, f.objs) + f.run(t, buildUDPPacket(t, f.shardPub, f.peer, encappedDstPort, masqPort, make([]byte, bigPayload))) + assertNoTranslatedDelta(t, f.objs, before) + }) + t.Run("nat64", func(t *testing.T) { + f := newNAT64Fixture(t, 0) + narrowFabric(t, f.backendUSID, f.peer4) + + before := trafficSnapshot(t, f.objs) + ret, out := f.run(t, buildEncappedUDPPacket(t, sidWithArgument(f.shardSID, 0x123), f.backendUSID, + f.backend, f.synth, []byte("out"))) + requireLeft(t, ret) + assertTranslatedDelta(t, f.objs, before, TrafficFamilyNAT64, TrafficDirectionOutbound, ret, out) + masqPort := binary.BigEndian.Uint16(out[ethLen+ip4Len:]) + + before = trafficSnapshot(t, f.objs) + ret, out = f.run(t, buildIPv4UDPPacket(t, f.shardPub4, f.peer4, encappedDstPort, masqPort, []byte("reply"))) + requireLeft(t, ret) + assertTranslatedDelta(t, f.objs, before, TrafficFamilyNAT64, TrafficDirectionReturn, ret, out) + + before = trafficSnapshot(t, f.objs) + f.run(t, buildIPv4UDPPacket(t, f.shardPub4, f.peer4, encappedDstPort, masqPort, make([]byte, bigPayload))) + assertNoTranslatedDelta(t, f.objs, before) + }) +} + +// requireLeft fails unless ret hands the packet to the wire. +func requireLeft(t *testing.T, ret uint32) { + t.Helper() + if ret != xdpTx && ret != xdpRedirect { + t.Fatalf("verdict = %d, want XDP_TX (%d) or XDP_REDIRECT (%d) over the test's routes", ret, xdpTx, xdpRedirect) + } +}