Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
340 lines
11 KiB
Go
340 lines
11 KiB
Go
package node
|
|
|
|
// Kernel shaping is confined to an otherwise network-none qualification
|
|
// container. The Core/Node addresses are test loopback aliases, not host routes.
|
|
// UDP datagrams represent encrypted video packet demand; no encoder/decoder or
|
|
// WebRTC/DERP implementation is claimed by this fixture.
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"os/exec"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type contentionProfile struct {
|
|
name string
|
|
down, up, oneWay int
|
|
loss string
|
|
jitter int
|
|
}
|
|
|
|
func tc(t *testing.T, args ...string) []byte {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
out, err := exec.CommandContext(ctx, "tc", args...).CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("tc %v: %v %s", args, err, out)
|
|
}
|
|
return out
|
|
}
|
|
func shape(t *testing.T, p contentionProfile) {
|
|
t.Helper()
|
|
if os.Getenv("MISSION_CORE_ISOLATED_NETEM") != "1" {
|
|
t.Fatal("Only the declared network-none Worker container may run netem")
|
|
}
|
|
if _, err := os.Stat("/.dockerenv"); err != nil {
|
|
t.Fatal("Docker isolation marker missing")
|
|
}
|
|
interfaces, err := net.Interfaces()
|
|
if err != nil || len(interfaces) != 1 || interfaces[0].Name != "lo" {
|
|
t.Fatal("Only a loopback-only isolated namespace is admitted")
|
|
}
|
|
// No host interface, namespace creation, sysctl or routing change is used.
|
|
tc(t, "qdisc", "add", "dev", "lo", "root", "handle", "1:", "prio", "bands", "3")
|
|
t.Cleanup(func() { tc(t, "qdisc", "del", "dev", "lo", "root") })
|
|
for _, d := range []struct {
|
|
band, rate int
|
|
dst string
|
|
}{{1, p.up, "127.0.0.2/32"}, {2, p.down, "127.0.0.3/32"}} {
|
|
args := []string{"qdisc", "add", "dev", "lo", "parent", fmt.Sprintf("1:%d", d.band), "handle", fmt.Sprintf("%d0:", d.band), "netem", "limit", "64", "delay", fmt.Sprintf("%dms", p.oneWay)}
|
|
if p.jitter > 0 {
|
|
args = append(args, fmt.Sprintf("%dms", p.jitter))
|
|
}
|
|
args = append(args, "rate", fmt.Sprintf("%dkbit", d.rate))
|
|
tc(t, args...)
|
|
tc(t, "filter", "add", "dev", "lo", "protocol", "ip", "parent", "1:", "prio", fmt.Sprint(d.band), "u32", "match", "ip", "dst", d.dst, "flowid", fmt.Sprintf("1:%d", d.band))
|
|
}
|
|
}
|
|
func percentile(values []float64, p float64) float64 {
|
|
if len(values) == 0 {
|
|
return 0
|
|
}
|
|
x := append([]float64{}, values...)
|
|
sort.Float64s(x)
|
|
return x[int(float64(len(x)-1)*p)]
|
|
}
|
|
func TestWorkerContentionMatrix(t *testing.T) {
|
|
profiles := []contentionProfile{{"5M-5M-rtt40", 5000, 5000, 20, "", 0}, {"1M-256K-rtt100", 1000, 256, 50, "", 0}, {"256K-128K-rtt150", 256, 128, 75, "", 0}, {"256K-128K-rtt150-loss1", 256, 128, 75, "1%", 0}}
|
|
for _, profile := range profiles {
|
|
for _, mode := range []string{"none", "gated", "unregulated"} {
|
|
t.Run(profile.name+"/"+mode, func(t *testing.T) { runContention(t, profile, mode, 8) })
|
|
}
|
|
}
|
|
}
|
|
func TestWorkerContentionSoak(t *testing.T) {
|
|
runContention(t, contentionProfile{"1M-256K-rtt100", 1000, 256, 50, "", 0}, "gated", 60)
|
|
}
|
|
func TestWorkerDatagramContentionMatrix(t *testing.T) {
|
|
profiles := []contentionProfile{{"5M-5M-rtt40", 5000, 5000, 20, "", 0}, {"1M-256K-rtt100", 1000, 256, 50, "", 0}, {"256K-128K-rtt150", 256, 128, 75, "", 0}, {"256K-128K-rtt150-loss1", 256, 128, 75, "1%", 0}}
|
|
for _, p := range profiles {
|
|
for _, mode := range []string{"none", "gated"} {
|
|
t.Run(p.name+"/"+mode, func(t *testing.T) { runContention(t, p, mode, 8, true) })
|
|
}
|
|
}
|
|
}
|
|
func TestWorkerDatagramJitter(t *testing.T) {
|
|
runContention(t, contentionProfile{"5M-5M-rtt40-jitter40", 5000, 5000, 20, "", 40}, "gated", 8, true)
|
|
}
|
|
|
|
func TestWorkerDatagramCompareTCP(t *testing.T) {
|
|
p := contentionProfile{"1M-256K-rtt100", 1000, 256, 50, "", 0}
|
|
for _, datagram := range []bool{false, true} {
|
|
t.Run(fmt.Sprintf("datagram-%t", datagram), func(t *testing.T) { runContention(t, p, "gated", 8, datagram) })
|
|
}
|
|
}
|
|
func runContention(t *testing.T, p contentionProfile, mode string, seconds int, datagram ...bool) {
|
|
shape(t, p)
|
|
useDatagram := len(datagram) > 0 && datagram[0]
|
|
// UDP's loopback route selects .1; include it in exactly the same downlink
|
|
// queue as TCP's .3. Otherwise the UDP comparison would bypass shaping.
|
|
if useDatagram {
|
|
tc(t, "filter", "add", "dev", "lo", "protocol", "ip", "parent", "1:", "prio", "3", "u32", "match", "ip", "dst", "127.0.0.1/32", "flowid", "1:2")
|
|
}
|
|
f := newTransportRig(t, func(f *transportRig) {
|
|
f.networkFixture = true
|
|
f.timeout = time.Duration(seconds+20) * time.Second
|
|
if useDatagram {
|
|
f.datagram = &datagramRig{}
|
|
}
|
|
})
|
|
var mu sync.Mutex
|
|
var rows []map[string]any
|
|
var overflow bool
|
|
// The diagnostic collector is local to the fixture and never crosses qdisc.
|
|
f.workers.Add(1)
|
|
go func() {
|
|
defer f.workers.Done()
|
|
tick := time.NewTicker(20 * time.Millisecond)
|
|
defer tick.Stop()
|
|
for {
|
|
select {
|
|
case <-f.ctx.Done():
|
|
return
|
|
case <-tick.C:
|
|
f.state.mu.Lock()
|
|
batch := f.state.devEvents
|
|
f.state.devEvents = nil
|
|
f.state.mu.Unlock()
|
|
mu.Lock()
|
|
if len(batch) >= 64 {
|
|
overflow = true
|
|
}
|
|
rows = append(rows, batch...)
|
|
mu.Unlock()
|
|
}
|
|
}
|
|
}()
|
|
// Fixed 20 Hz Core generation, original clock/expiry. No new identity is
|
|
// fabricated after a stop. TCP writes may backpressure; the ticker coalesces.
|
|
f.workers.Add(1)
|
|
go func() {
|
|
defer f.workers.Done()
|
|
tick := time.NewTicker(50 * time.Millisecond)
|
|
defer tick.Stop()
|
|
seq := 0
|
|
for {
|
|
select {
|
|
case <-f.ctx.Done():
|
|
return
|
|
case <-tick.C:
|
|
seq++
|
|
if useDatagram {
|
|
f.datagram.write(f.frame(transportSession, seq))
|
|
continue
|
|
}
|
|
job := transportWrite{data: f.frame(transportSession, seq), done: make(chan error, 1)}
|
|
select {
|
|
case f.wire <- job:
|
|
case <-f.ctx.Done():
|
|
return
|
|
}
|
|
select {
|
|
case <-job.done:
|
|
case <-f.ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
f.pause(2 * time.Second)
|
|
f.mu.Lock()
|
|
activeStart := float64(time.Since(f.origin).Microseconds()) / 1000
|
|
telemetryBefore := f.telemetry
|
|
f.mu.Unlock()
|
|
if p.loss != "" {
|
|
for _, d := range []struct{ band, rate int }{{1, p.up}, {2, p.down}} {
|
|
tc(t, "qdisc", "change", "dev", "lo", "parent", fmt.Sprintf("1:%d", d.band), "handle", fmt.Sprintf("%d0:", d.band), "netem", "limit", "64", "delay", fmt.Sprintf("%dms", p.oneWay), "rate", fmt.Sprintf("%dkbit", d.rate), "loss", "random", p.loss)
|
|
}
|
|
}
|
|
receiver, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sender, err := net.DialUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.3")}, receiver.LocalAddr().(*net.UDPAddr))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { sender.Close(); receiver.Close() })
|
|
var sent, received, denied atomic.Uint64
|
|
var producerErrors atomic.Uint64
|
|
f.workers.Add(1)
|
|
go func() {
|
|
defer f.workers.Done()
|
|
buf := make([]byte, 1200)
|
|
for f.ctx.Err() == nil {
|
|
receiver.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
|
n, _, e := receiver.ReadFromUDP(buf)
|
|
if e == nil {
|
|
received.Add(uint64(n))
|
|
}
|
|
}
|
|
}()
|
|
if mode != "none" {
|
|
handler := f.state.budget.Handler()
|
|
f.workers.Add(1)
|
|
go func() {
|
|
defer f.workers.Done()
|
|
tick := time.NewTicker(2200 * time.Microsecond)
|
|
defer tick.Stop()
|
|
renew := time.Time{}
|
|
packet := make([]byte, 1100)
|
|
for {
|
|
select {
|
|
case <-f.ctx.Done():
|
|
return
|
|
case now := <-tick.C:
|
|
if mode == "gated" {
|
|
if now.Sub(renew) >= time.Second {
|
|
rr := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", "/producer", bytes.NewBufferString(`{"id":"ffffffffffffffffffffffffffffffff","class":"video","active":true,"demand_bps":4000000,"primary":true}`))
|
|
handler.ServeHTTP(rr, req)
|
|
renew = now
|
|
if rr.Code != http.StatusOK {
|
|
return
|
|
}
|
|
}
|
|
rr := httptest.NewRecorder()
|
|
req := httptest.NewRequest("POST", "/permit", bytes.NewBufferString(`{"producer_id":"ffffffffffffffffffffffffffffffff","class":"video","bytes":1100}`))
|
|
handler.ServeHTTP(rr, req)
|
|
var permit struct {
|
|
Granted bool `json:"granted"`
|
|
}
|
|
if err := json.Unmarshal(rr.Body.Bytes(), &permit); err != nil || rr.Code != http.StatusOK {
|
|
producerErrors.Add(1)
|
|
return
|
|
}
|
|
if !permit.Granted {
|
|
denied.Add(1)
|
|
continue
|
|
}
|
|
}
|
|
if n, e := sender.Write(packet); e == nil {
|
|
sent.Add(uint64(n))
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
var budgets []map[string]any
|
|
for i := 0; i < seconds; i++ {
|
|
f.pause(time.Second)
|
|
budgets = append(budgets, f.state.budget.Snapshot())
|
|
}
|
|
activeEnd := float64(time.Since(f.origin).Microseconds()) / 1000
|
|
qdisc := tc(t, "-s", "-j", "qdisc", "show", "dev", "lo")
|
|
mu.Lock()
|
|
events := append([]map[string]any{}, rows...)
|
|
dropped := overflow
|
|
mu.Unlock()
|
|
if dropped {
|
|
t.Error("local diagnostic ring overflowed")
|
|
}
|
|
var gaps, ages, telemetryElapsed []float64
|
|
lastReceipt := activeStart
|
|
maxSilence := 0.0
|
|
var telemetryErrors, streamErrors int
|
|
var tails []map[string]any
|
|
for _, row := range events {
|
|
at, _ := row["monotonic_ms"].(float64)
|
|
if at < activeStart || at > activeEnd {
|
|
continue
|
|
}
|
|
switch row["event"] {
|
|
case "stream_frame_received":
|
|
at, _ := row["monotonic_ms"].(float64)
|
|
maxSilence = max(maxSilence, at-lastReceipt)
|
|
lastReceipt = at
|
|
g, _ := row["gap_ms"].(float64)
|
|
a, _ := row["age_upper_ms"].(float64)
|
|
gaps = append(gaps, g)
|
|
ages = append(ages, a)
|
|
if g >= 150 || a >= 250 {
|
|
tails = append(tails, row)
|
|
}
|
|
case "telemetry":
|
|
if elapsed, ok := row["elapsed_ms"].(int64); ok {
|
|
telemetryElapsed = append(telemetryElapsed, float64(elapsed))
|
|
}
|
|
if row["error_stage"] != "" {
|
|
telemetryErrors++
|
|
}
|
|
case "stream_disconnected":
|
|
streamErrors++
|
|
}
|
|
}
|
|
maxSilence = max(maxSilence, activeEnd-lastReceipt)
|
|
if len(tails) > 12 {
|
|
tails = tails[:12]
|
|
}
|
|
f.mu.Lock()
|
|
telemetryOK := f.telemetry - telemetryBefore
|
|
var stops []transportSample
|
|
for _, s := range f.samples {
|
|
if s.Mode == "stop" && s.AtMS >= activeStart && s.AtMS <= activeEnd {
|
|
stops = append(stops, s)
|
|
}
|
|
}
|
|
f.mu.Unlock()
|
|
if useDatagram && mode != "unregulated" && len(stops) > 0 {
|
|
t.Error("gated datagram profile stopped", stops)
|
|
}
|
|
if useDatagram && mode == "gated" && p.jitter > 0 && float64(received.Load())*8/(activeEnd-activeStart) < 384 {
|
|
t.Error("healthy-capacity jitter profile starved optional media")
|
|
}
|
|
if producerErrors.Load() != 0 {
|
|
t.Error("video producer/permit failed", producerErrors.Load())
|
|
}
|
|
if len(gaps) == 0 {
|
|
t.Error("no production stream receipts measured")
|
|
}
|
|
if (mode == "none" || seconds >= 60) && p.loss == "" && p.up >= 256 && len(stops) > 0 {
|
|
t.Error("critical-only admissible profile stopped")
|
|
}
|
|
result := map[string]any{"case": t.Name(), "started_utc": f.origin.UTC().Format(time.RFC3339Nano), "active_start_ms": activeStart, "active_end_ms": activeEnd, "profile": p.name, "mode": mode, "datagram": useDatagram,
|
|
"telemetry_elapsed_p95_ms": percentile(telemetryElapsed, .95), "telemetry_elapsed_max_ms": percentile(telemetryElapsed, 1), "max_receipt_silence_ms": maxSilence, "receipts": len(gaps), "gap_p95_ms": percentile(gaps, .95), "gap_max_ms": percentile(gaps, 1), "age_p95_ms": percentile(ages, .95), "age_max_ms": percentile(ages, 1), "stream_errors": streamErrors, "telemetry_ok": telemetryOK, "telemetry_errors": telemetryErrors,
|
|
"video_sent_bytes": sent.Load(), "video_received_bytes": received.Load(), "video_deferrals": denied.Load(), "stops": stops, "budget_samples": budgets, "qdisc": json.RawMessage(qdisc), "tails": tails, "local_trace_overflow": dropped, "actuator_output": false}
|
|
raw, _ := json.Marshal(result)
|
|
t.Log("CONTENTION_EVIDENCE " + string(raw))
|
|
}
|