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
2 changes: 1 addition & 1 deletion cmd/galactic-gateway/dispatch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ type gatewayProcess struct {
func startGateway(t *testing.T, d pinDirs) gatewayProcess {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
objs, dispatcher, public, _, leaseDone, err := joinDispatcher(ctx, d.dispatch, d.edge, false)
objs, dispatcher, public, _, leaseDone, err := joinDispatcher(ctx, d.dispatch, d.edge, false, nil)
if err != nil {
cancel()
t.Fatalf("gateway joinDispatcher: %v", err)
Expand Down
15 changes: 11 additions & 4 deletions cmd/galactic-gateway/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,13 @@ func setupGatewayDatapath(
if attachMode == config.GatewayXDPAttachDispatch {
leaseCtx, stopLeases := context.WithCancel(ctx)
var leaseDone <-chan struct{}
lease := xdpdispatch.NewLeaseMetrics(edgemetrics.Namespace)
if err := lease.Register(metricsReg); err != nil {
stopLeases()
return nil, fmt.Errorf("register dispatcher lease metrics: %w", err)
}
objs, dispatcher, publicSet, returnSet, leaseDone, err = joinDispatcher(leaseCtx, xdpdispatch.PinDir,
edgeattach.PinDir, len(returnTargets) > 0)
edgeattach.PinDir, len(returnTargets) > 0, lease)
if err != nil {
stopLeases()
return nil, err
Expand Down Expand Up @@ -273,7 +278,9 @@ func attachDirect(ctx context.Context, dispatchDir, edgeDir string, targets, ret
// the returned sets put the dispatcher on the targets and read coverage back.
// The returned channel closes once both lease loops have stopped, which a
// caller waits on before closing the dispatcher.
func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn bool) (
func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn bool,
lease *xdpdispatch.LeaseMetrics,
) (
*edgeprog.EdgedsrObjects, *xdpdispatch.Dispatcher, targetSet, targetSet, <-chan struct{}, error,
) {
dispatcher, err := xdpdispatch.Open(ctx, dispatchDir)
Expand Down Expand Up @@ -326,10 +333,10 @@ func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn
var leases sync.WaitGroup
for _, slot := range []xdpdispatch.Slot{xdpdispatch.SlotGatewayLB, xdpdispatch.SlotGatewayReturn} {
leases.Go(func() {
dispatcher.Lease(ctx, slot, func(err error) {
dispatcher.Lease(ctx, slot, lease.Observe(slot, func(err error) {
slog.Error("Cannot renew an edge gateway slot's lease in the XDP dispatcher; "+
"the dispatcher skips the slot once it lapses", "slot", slot, "err", err)
})
}))
})
}
leaseDone := make(chan struct{})
Expand Down
2 changes: 1 addition & 1 deletion cmd/galactic-nat/dispatch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func joinForTest(t *testing.T, dispatchDir string, program *ebpf.Program) (*xdpd
) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
d, set, leaseDone, err := joinDispatcher(ctx, dispatchDir, program)
d, set, leaseDone, err := joinDispatcher(ctx, dispatchDir, program, nil)
if err != nil {
cancel()
t.Fatalf("joinDispatcher: %v", err)
Expand Down
69 changes: 69 additions & 0 deletions cmd/galactic-nat/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ package main
import (
"fmt"
"log/slog"
"maps"
"net/netip"

"github.com/cilium/ebpf"
"github.com/prometheus/client_golang/prometheus"
Expand All @@ -22,6 +24,9 @@ const metricsNamespace = "galactic_nat"
// familyNAT64.
const labelFamily = "family"

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

// trafficLabels label the translated-traffic series.
var trafficLabels = []string{labelFamily, "direction", "action"}

Expand All @@ -36,6 +41,10 @@ type natCollector struct {
dropReasons natmap.DropReasonsReader
traffic natmap.TrafficReader

// shardConfig names the masquerade addresses whose port usage is always
// reported, zero included. Nil reports only the addresses rows hold.
shardConfig *natmap.ShardConfigTable

// now reads the clock the datapath stamps last_seen with. Nil means
// datapathNow.
now func() (uint32, error)
Expand All @@ -60,6 +69,7 @@ func newNatCollector(objs *natprog.NatObjects) *natCollector {
connMaxEntries: mapMaxEntries(objs.NatConnTable),
dropReasons: objs.DropReasons,
traffic: objs.NatTraffic,
shardConfig: natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}),
}
}

Expand Down Expand Up @@ -113,6 +123,26 @@ var (
"without the Ethernet header or the SRv6 outer header a return packet carries.",
trafficLabels, nil,
)
portsInUseDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "masquerade", "ports_in_use"),
"Distinct masquerade ports live sessions hold on this masquerade address and protocol, toward any "+
"destination. A port is claimed per destination address and port, so this can sit near "+
"galactic_nat_masquerade_port_range on a healthy shard; see "+
"galactic_nat_masquerade_destination_ports_max for exhaustion.",
masqueradeLabels, nil,
)
destinationPortsMaxDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "masquerade", "destination_ports_max"),
"The most masquerade ports live sessions hold toward any single destination address and port, on this "+
"masquerade address and protocol. New flows to that destination start failing as it approaches "+
"galactic_nat_masquerade_port_range.",
masqueradeLabels, nil,
)
portRangeDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "masquerade", "port_range"),
"Masquerade ports (or ICMP Echo Identifiers) available toward each destination address and port.",
nil, nil,
)
dropsDesc = prometheus.NewDesc(
prometheus.BuildFQName(metricsNamespace, "", "drops_total"),
"Packets dropped by this shard's datapath, by reason (drop_reasons map).",
Expand All @@ -129,6 +159,9 @@ func (c *natCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- dropsDesc
ch <- packetsDesc
ch <- bytesDesc
ch <- portsInUseDesc
ch <- destinationPortsMaxDesc
ch <- portRangeDesc
}

// Collect implements prometheus.Collector.
Expand Down Expand Up @@ -173,6 +206,7 @@ func (c *natCollector) collectConns(ch chan<- prometheus.Metric) {
now, err := clock()
if err != nil {
slog.Warn("cannot read the session clock; skipping session table metrics", "err", err)
ch <- prometheus.MustNewConstMetric(portRangeDesc, prometheus.GaugeValue, float64(natprog.PATPortRange))
return
}
// A walk the datapath's own inserts and evictions disturbed still reports
Expand Down Expand Up @@ -209,6 +243,41 @@ func (c *natCollector) collectConns(ch chan<- prometheus.Metric) {
if counts.HasReverse {
ch <- prometheus.MustNewConstMetric(oldestRowAgeDesc, prometheus.GaugeValue, float64(counts.OldestAge))
}

c.collectPorts(ch, counts.Ports)
}

// collectPorts reports port usage for every masquerade address and protocol
// the programmed identity serves, zero included, and for any other address
// live rows still hold, such as one a re-programmed identity replaced.
func (c *natCollector) collectPorts(ch chan<- prometheus.Metric, usage map[natmap.MasqueradeKey]natmap.PortUsage) {
ch <- prometheus.MustNewConstMetric(portRangeDesc, prometheus.GaugeValue, float64(natprog.PATPortRange))

all := map[natmap.MasqueradeKey]natmap.PortUsage{}
if c.shardConfig != nil {
if cfg, ok, err := c.shardConfig.Get(); err != nil {
slog.Debug("cannot read shard_config_table; reporting port usage only for held addresses", "err", err)
} else if ok {
for _, served := range []struct {
family uint8
addr netip.Addr
}{{natprog.FamilyIPv6, cfg.ShardPubAddr6}, {natprog.FamilyIPv4, cfg.ShardPubAddr4}} {
if !served.addr.IsValid() {
continue
}
for _, proto := range []string{natmap.SessionProtoTCP, natmap.SessionProtoUDP, natmap.SessionProtoICMP} {
all[natmap.MasqueradeKey{Family: served.family, Address: served.addr, Proto: proto}] = natmap.PortUsage{}
}
}
}
}
maps.Copy(all, usage)
for key, u := range all {
labels := []string{familyLabel(key.Family), key.Address.String(), key.Proto}
ch <- prometheus.MustNewConstMetric(portsInUseDesc, prometheus.GaugeValue, float64(u.InUse), labels...)
ch <- prometheus.MustNewConstMetric(destinationPortsMaxDesc, prometheus.GaugeValue,
float64(u.MaxPerDestination), labels...)
}
}

func (c *natCollector) collectConnTableMaxEntries(ch chan<- prometheus.Metric) {
Expand Down
16 changes: 11 additions & 5 deletions cmd/galactic-nat/nat.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,12 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig,
case config.NATXDPAttachDispatch:
// The lease runs for the life of the process, so its done channel
// is not needed here.
if dispatcher, dispatchSet, _, err = joinDispatcher(ctx, xdpdispatch.PinDir, objs.NatIngress); err != nil {
lease := xdpdispatch.NewLeaseMetrics(metricsNamespace)
if err := lease.Register(metricsReg); err != nil {
_ = objs.Close()
return nil, fmt.Errorf("register dispatcher lease metrics: %w", err)
}
if dispatcher, dispatchSet, _, err = joinDispatcher(ctx, xdpdispatch.PinDir, objs.NatIngress, lease); err != nil {
_ = objs.Close()
return nil, err
}
Expand Down Expand Up @@ -389,11 +394,12 @@ func registerUplinkQueueStats(metricsReg prometheus.Registerer, d *natDatapath)
}

// joinDispatcher opens the node's XDP dispatcher, fills this shard's slot with
// program, and starts renewing the slot's lease for the life of ctx. It
// program, and starts renewing the slot's lease for the life of ctx, recording
// each renewal in lease, which may be nil. It
// returns the set that keeps the dispatcher on the uplinks, and a channel
// closed once the lease loop has stopped, which a caller waits on before
// closing the dispatcher.
func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program) (
func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program, lease *xdpdispatch.LeaseMetrics) (
*xdpdispatch.Dispatcher, *xdpattach.DispatchSet, <-chan struct{}, error,
) {
dispatcher, err := xdpdispatch.Open(ctx, pinDir)
Expand Down Expand Up @@ -422,10 +428,10 @@ func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program) (
leaseDone := make(chan struct{})
go func() {
defer close(leaseDone)
dispatcher.Lease(ctx, xdpdispatch.SlotNAT, func(err error) {
dispatcher.Lease(ctx, xdpdispatch.SlotNAT, lease.Observe(xdpdispatch.SlotNAT, func(err error) {
slog.Error("Cannot renew the egress translation slot's lease in the XDP dispatcher; "+
"the dispatcher skips the slot once it lapses", "err", err)
})
}))
}()
slog.Info("Egress translation datapath installed in the XDP dispatcher", "pinDir", pinDir)
return dispatcher, set, leaseDone, nil
Expand Down
107 changes: 107 additions & 0 deletions cmd/galactic-nat/ports_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package main

import (
"errors"
"net/netip"
"reflect"
"testing"

"github.com/cilium/ebpf"

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

// memTable is an in-memory natmap.Table keyed by any comparable key.
type memTable map[any]any

func (m memTable) Put(key, value any) error { m[key] = value; return nil }
func (m memTable) Lookup(key, valueOut any) error {
v, ok := m[key]
if !ok {
return ebpf.ErrKeyNotExist
}
reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(v))
return nil
}
func (m memTable) Delete(key any) error { delete(m, key); return nil }
func (memTable) Iterate() natmap.Iterator { return &connRowsIterator{rows: &connRows{}, idx: -1} }

func TestNatCollectorReportsMasqueradePorts(t *testing.T) {
const now uint32 = 100_000
shardConfig := natmap.NewShardConfigTable(memTable{})
if err := shardConfig.Set(natmap.ShardConfig{
ShardSID: netip.MustParseAddr("fc00:1:2::1"),
ShardPubAddr6: netip.MustParseAddr("2001:db8:9966::1"),
}); err != nil {
t.Fatalf("Set: %v", err)
}

var rows connRows
peerPort := uint16(443)
for _, port := range []uint16{35000, 35001} {
key, value := reverseRow(natprog.FamilyIPv6, 17, port, 443, now)
key.Daddr = netip.MustParseAddr("2001:db8:9966::1").As16()
key.Saddr = netip.MustParseAddr("2001:db8:1::1").As16()
key.Sport = peerPort<<8 | peerPort>>8
rows.add(key, value)
}

c := &natCollector{
connTable: natmap.NewConnTable(&rows),
now: fixedClock(now),
shardConfig: shardConfig,
}
got := gatherAll(t, c)

if v := got["galactic_nat_masquerade_port_range"][""]; v != float64(natprog.PATPortRange) {
t.Errorf("port range = %v, want %d", v, natprog.PATPortRange)
}
inUse := got["galactic_nat_masquerade_ports_in_use"]
maxDest := got["galactic_nat_masquerade_destination_ports_max"]
// Labels sort as address/family/proto. The served IPv6 address is reported
// for every protocol, zero included; the unserved IPv4 family not at all.
want := map[string]float64{
"2001:db8:9966::1/nat66/udp": 2,
"2001:db8:9966::1/nat66/tcp": 0,
"2001:db8:9966::1/nat66/icmp": 0,
}
if !reflect.DeepEqual(inUse, want) {
t.Errorf("ports_in_use = %v, want %v", inUse, want)
}
if !reflect.DeepEqual(maxDest, want) {
t.Errorf("destination_ports_max = %v, want %v", maxDest, want)
}
}

// Without the session clock no row's liveness is known, so the per-address
// port series are left out rather than reported as zeros an idle shard would
// show. The range, which needs no clock, is still reported.
func TestNatCollectorPortsWithoutClock(t *testing.T) {
shardConfig := natmap.NewShardConfigTable(memTable{})
if err := shardConfig.Set(natmap.ShardConfig{
ShardSID: netip.MustParseAddr("fc00:1:2::1"),
ShardPubAddr6: netip.MustParseAddr("2001:db8:9966::1"),
}); err != nil {
t.Fatalf("Set: %v", err)
}
c := &natCollector{
connTable: natmap.NewConnTable(&connRows{}),
now: func() (uint32, error) { return 0, errors.New("no clock") },
shardConfig: shardConfig,
}
got := gatherAll(t, c)
if _, ok := got["galactic_nat_masquerade_ports_in_use"]; ok {
t.Error("reported ports_in_use without a clock; zeros would read as an idle shard")
}
if _, ok := got["galactic_nat_masquerade_destination_ports_max"]; ok {
t.Error("reported destination_ports_max without a clock")
}
if got["galactic_nat_masquerade_port_range"][""] != float64(natprog.PATPortRange) {
t.Error("port range missing without a clock")
}
}
60 changes: 60 additions & 0 deletions config/monitoring/prometheusrule.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,66 @@ spec:
Compute nodes have encapsulated tenant traffic toward {{ $labels.shard_sid }} for 10 minutes, but the
shard on {{ $labels.node }} translated none of it outbound. Check galactic_nat_uplink_covered,
galactic_nat_datapath_attached and the shard's XDP attachment.
# A claim needs a free port toward one destination address and port,
# and probes 8 of the range's candidates. With a share u of that
# destination's ports held, a new flow fails with probability about
# u^8: 0.4% at half full, 1.7% at 60%, 17% at 80%. Half full is the
# last point before GalacticNatPortExhausted's drops become routine,
# so this warns while new flows still almost always succeed.
- alert: GalacticNatPortsNearExhaustion
expr: >-
max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max{job="galactic-nat"})
/ on (node) group_left () max by (node) (galactic_nat_masquerade_port_range{job="galactic-nat"}) > 0.5
for: 10m
labels:
severity: warning
service: galactic
team: connect
annotations:
summary: "Masquerade {{ $labels.proto }} ports on {{ $labels.address }} are {{ $value | humanizePercentage }} used toward one destination"
runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatportsnearexhaustion"
description: >-
The egress shard on {{ $labels.node }} holds {{ $value | humanizePercentage }} of the {{ $labels.proto }}
ports on {{ $labels.address }} toward a single destination for 10 minutes. New flows to that destination
start failing as this approaches 100%, with GalacticNatPortExhausted.
# The lease is renewed every 10s for 120s, so it survives 11 failed
# renewals in a row. More than two failures in every 5-minute window
# means renewals keep failing, well before the lease is at risk.
- alert: GalacticNatDispatchLeaseFailing
expr: >-
increase(galactic_nat_dispatch_lease_renewals_total{job="galactic-nat", result="error"}[5m]) > 2
for: 5m
labels:
severity: warning
service: galactic
team: connect
annotations:
summary: "The egress shard on {{ $labels.node }} cannot renew its XDP dispatcher lease"
runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatdispatchleasefailing"
description: >-
galactic-nat on {{ $labels.node }} has failed to renew its {{ $labels.slot }} slot's lease in the XDP
dispatcher more than twice in every 5-minute window for 5 minutes. Once the lease expires the
dispatcher skips the slot and tenant traffic leaves untranslated. The shard's log names the error.
# No successful renewal in two minutes means the 120s lease has lapsed
# or is about to. Read from the renewal counter rather than the expiry
# timestamp, which would compare the node's clock with the evaluator's
# and page on skew alone; a two-minute window holds four samples at
# the 30s scrape, so jitter cannot empty it.
- alert: GalacticNatDispatchLeaseExpiring
expr: >-
changes(galactic_nat_dispatch_lease_renewals_total{job="galactic-nat", result="success"}[2m]) == 0
for: 0s
labels:
severity: critical
service: galactic
team: connect
annotations:
summary: "The egress shard's XDP dispatcher lease on {{ $labels.node }} has lapsed or is about to"
runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#galacticnatdispatchleaseexpiring"
description: >-
galactic-nat on {{ $labels.node }} has not renewed its {{ $labels.slot }} slot lease for two minutes,
so the 120-second lease has lapsed or is about to. The dispatcher skips a lapsed slot, so the shard's
uplinks pass tenant traffic untranslated.
- alert: GalacticNatMetricsDown
expr: up{job="galactic-nat"} == 0
for: 5m
Expand Down
Loading
Loading