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
69 changes: 66 additions & 3 deletions cmd/galactic-nat/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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.
Expand All @@ -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,
}
}

Expand All @@ -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"),
Expand All @@ -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).",
Expand All @@ -104,13 +127,16 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- oldestRowAgeDesc
ch <- connTableMaxEntriesDesc
ch <- dropsDesc
ch <- packetsDesc
ch <- bytesDesc
}

// Collect implements prometheus.Collector.
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.
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
}
}
}
}
23 changes: 18 additions & 5 deletions cmd/galactic-nat/nat.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions cmd/galactic-nat/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
133 changes: 133 additions & 0 deletions cmd/galactic-nat/state.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading