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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
- **Per-namespace caps.** `-maxDumpBytes` (default 256 MiB) and `-maxRecordsPerNetns` (default 262144) bound one namespace's dump per poll: packets past the byte cap are drained undecoded, and records past the record cap are dropped before decode. `-maxNetns` (default 4096) bounds the namespaces tracked. At the cap, tracked namespaces keep their slots, and new ones wait for a freed slot, first come, first served. Alert on `xtcp_netns_dropped_total`. Drops are counted in `xtcp_dump_dropped_total{reason}` and `xtcp_netns_dropped_total`, with one log line per truncated dump or short reconcile. `0` turns a cap off; the matching env vars are `MAX_DUMP_BYTES`, `MAX_RECORDS_PER_NETNS` and `MAX_NETNS`. The caps are startup-only: `ConfigService.Set` keeps the running values. No healthy host should reach the defaults; a host that does now loses that namespace's excess rows, where it used to collect them all ([polling and batching](docs/polling-and-batching.md#per-namespace-caps)).
- **Socket-count gate, reconcile limits, per-owner quota.** Before each poll xtcp2 reads each namespace's sockstat (an fd opened in the namespace; `pread`, or io_uring batches with `-ioUring`) and, when the total is over `-maxRecordsPerPoll` (default 1,048,576), degrades only the namespaces over their fair share: first TIME_WAIT/SYN_RECV are not asked for, then one of K port shards is dumped per poll. `-maxNetnsPerOwner` (default 64) caps namespaces tracked per owner (the container runtime's cgroup), `-maxNetnsAddsPerReconcile` (256) the adds per reconcile, and `-reconcileTimeout` (1s) the namespace scan; a timed-out scan deletes nothing. New metrics `xtcp_poll_sockets`, `xtcp_poll_degraded_total{level}` and `xtcp_reconcile_incomplete_total{reason}`; `xtcp_netns_dropped_total` gains `reason`. `0` turns each off; all are startup-only. Each tracked namespace now holds four fds (was two: sockstat and `ip_local_port_range` are new), and xtcp2 warns at startup when `RLIMIT_NOFILE` can't cover them ([polling and batching](docs/polling-and-batching.md#socket-count-gate), [network namespaces](docs/network-namespaces.md#configuration)). The analysis behind an upstream all-namespace dump is in [docs/kernel](docs/kernel/inet-diag-all-netns.md).
- **Fuzzing every target.** `fuzz-all` (dev shell, `nix run .#fuzz-all`) finds every Go fuzz target with `go test -list` and fuzzes each in turn; `checks.test-fuzz-all` runs it sandboxed at 10 s per target, so `nix flake check` fuzzes again whenever the source changes. Two new fuzzers cover tenant-reachable paths: `FuzzDockerProjection` (a Docker inspect body to a container's name and image) and `FuzzRowFromProto` (an S3 envelope through Parquet and back). `FuzzClean` now also checks idempotence and the fast path. The first run found `/ip/vrf/show/NAME` returning 500 for a name that is no VRF; it is now a 404. Docker container list and inspect bodies are now streamed, keeping only the fields used: memory stays bounded however large a container's labels are, a container whose entry passes 4 MiB is skipped and logged (never the whole list), each request has a 10 s timeout, and an oversized `/events` line no longer stalls container-metadata refresh. Limits: [Docker API limits](docs/design-metadata-enrichment.md#docker-api-limits).
- **Golden records.** `nix run .#capture-golden-records` captures one poll of the production binary in a microVM over a fixed workload (3 containers, a named netns, the host). It commits the poll scrubbed, under `pkg/xtcp/testdata/golden/`. `xtcp2-golden diff` compares two captures and ignores run-to-run noise (timestamps, cookies, ephemeral ports, counter values, addresses). It still catches a missing attribute or a changed container name. `checks.golden-records` keeps the fixture scrubbed and consistent, and its rows seed `FuzzRowFromProto` ([Golden records](nix/README.md#golden-records)).
- **Vulnerability check.** `checks.govulncheck` runs govulncheck against a pinned snapshot of the Go vulnerability database, with no tags and with every flavor tag, and fails on a reachable finding not in its accepted list. One is accepted: GO-2026-6859 in `net/http`, fixed in go1.27.4, until the toolchain moves. `nix run .#govulncheck-fresh` checks against the live database and runs `go mod verify`; `nix build .#sbom-<binary>` writes a CycloneDX SBOM for any binary package.

## 0.2.1 (2026-11)
Expand Down
310 changes: 310 additions & 0 deletions cmd/xtcp2-golden/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
//go:build dest_s3parquet

// Command xtcp2-golden works with golden captures of xtcp2's Parquet
// records (see pkg/goldenrec and nix/README.md, "Golden records"):
//
// xtcp2-golden scrub in.parquet out.parquet
// xtcp2-golden normalize in.parquet > records.jsonl
// xtcp2-golden diff [-columns re] [-limit 50] golden.parquet candidate.parquet
// xtcp2-golden check dir
//
// diff and check exit 0 when they find nothing, 1 when they do, and 2 on an
// error.
package main

import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"slices"
"strings"

"github.com/parquet-go/parquet-go"

"github.com/randomizedcoder/xtcp2/pkg/goldenrec"
"github.com/randomizedcoder/xtcp2/pkg/xtcp"
)

const (
exitSame = 0
exitDiff = 1
exitError = 2
)

// errFound is returned when diff or check finds something.
var errFound = errors.New("differences found")

func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}

func run(args []string, stdout, stderr io.Writer) int {
err := dispatch(args, stdout, stderr)
switch {
case err == nil:
return exitSame
case errors.Is(err, errFound):
return exitDiff
default:
fmt.Fprintln(stderr, "xtcp2-golden:", err)
return exitError
}
}

const usage = "usage: xtcp2-golden scrub IN OUT | normalize IN | diff [-columns re] [-limit n] GOLDEN CANDIDATE | check DIR"

func dispatch(args []string, stdout, stderr io.Writer) error {
if len(args) == 0 {
return errors.New(usage)
}
cmd, args := args[0], args[1:]
switch cmd {
case "scrub":
if len(args) != 2 {
return errors.New(usage)
}
return scrub(args[0], args[1], stderr)
case "normalize":
if len(args) != 1 {
return errors.New(usage)
}
return normalize(args[0], stdout)
case "diff":
return diff(args, stdout, stderr)
case "check":
if len(args) != 1 {
return errors.New(usage)
}
return check(args[0], stdout)
default:
return fmt.Errorf("unknown command %q\n%s", cmd, usage)
}
}

// readFile reads name in dir through os.Root, which keeps it inside dir.
func readFile(dir, name string) ([]byte, error) {
root, err := os.OpenRoot(dir)
if err != nil {
return nil, err
}
b, err := root.ReadFile(name)
return b, errors.Join(err, root.Close())
}

func readRows(path string) ([]xtcp.ParquetRow, error) {
b, err := readFile(filepath.Dir(path), filepath.Base(path))
if err != nil {
return nil, err
}
f, err := parquet.OpenFile(bytes.NewReader(b), int64(len(b)))
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if err := sameSchema(f.Schema()); err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
rows, err := parquet.Read[xtcp.ParquetRow](bytes.NewReader(b), int64(len(b)))
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
return rows, nil
}

// sameSchema rejects a file whose columns are not ParquetRow's: a capture
// from before a schema change reads with zeros in the new columns, which
// would compare as a real difference, or hide one.
func sameSchema(s *parquet.Schema) error {
have := make([]string, 0, len(s.Columns()))
for _, p := range s.Columns() {
have = append(have, p[0])
}
wantCols := parquet.SchemaOf(xtcp.ParquetRow{}).Columns()
want := make([]string, 0, len(wantCols))
for _, p := range wantCols {
want = append(want, p[0])
}
slices.Sort(have)
slices.Sort(want)
if !slices.Equal(have, want) {
return errors.New("schema drift: the file's columns are not ParquetRow's; recapture with nix run .#capture-golden-records")
}
return nil
}

func scrub(in, out string, stderr io.Writer) error {
rows, err := readRows(in)
if err != nil {
return err
}
rep, err := goldenrec.Scrub(rows, goldenrec.Columns)
if err != nil {
return err
}
for _, s := range rep.Invalid {
fmt.Fprintln(stderr, "xtcp2-golden: left as is:", s)
}
return parquet.WriteFile(out, rows)
}

// normalizedJSONL is one JSON object per row, keys sorted.
func normalizedJSONL(rows []xtcp.ParquetRow) ([]byte, error) {
n, err := goldenrec.Normalize(rows, goldenrec.Columns)
if err != nil {
return nil, err
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
for _, r := range n {
if err := enc.Encode(r); err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}

func normalize(in string, stdout io.Writer) error {
rows, err := readRows(in)
if err != nil {
return err
}
b, err := normalizedJSONL(rows)
if err != nil {
return err
}
_, err = stdout.Write(b)
return err
}

func diff(args []string, stdout, stderr io.Writer) error {
fs := flag.NewFlagSet("diff", flag.ContinueOnError)
fs.SetOutput(stderr)
columns := fs.String("columns", "", "compare only columns matching this regular expression")
limit := fs.Int("limit", 50, "print at most this many differences")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 2 {
return errors.New(usage)
}
var sides [2][]goldenrec.Row
for i, p := range fs.Args() {
rows, err := readRows(p)
if err != nil {
return err
}
if sides[i], err = goldenrec.Normalize(rows, goldenrec.Columns); err != nil {
return fmt.Errorf("%s: %w", p, err)
}
}
diffs, err := goldenrec.Diff(sides[0], sides[1], goldenrec.Columns, goldenrec.Options{Columns: *columns})
if err != nil {
return err
}
if len(diffs) == 0 {
return nil
}
fmt.Fprint(stdout, goldenrec.Format(diffs, *limit))
return fmt.Errorf("%w: %d", errFound, len(diffs))
}

// manifest is the part of manifest.json check reads.
type manifest struct {
Rows int `json:"rows"`
}

// check verifies a fixture directory: records.jsonl is records.parquet
// normalized, records.parquet is scrubbed, and manifest.json counts its rows.
func check(dir string, stdout io.Writer) error {
rows, err := readRows(filepath.Join(dir, "records.parquet"))
if err != nil {
return err
}
var problems []string
want, err := normalizedJSONL(rows)
if err != nil {
return err
}
got, err := readFile(dir, "records.jsonl")
if err != nil {
return err
}
if !bytes.Equal(got, want) {
problems = append(problems, "records.jsonl is not records.parquet normalized: "+firstDiffLine(got, want))
}
bad, err := goldenrec.CheckScrubbed(rows, goldenrec.Columns)
if err != nil {
return err
}
problems = append(problems, bad...)
mb, err := readFile(dir, "manifest.json")
if err != nil {
return err
}
var m manifest
if err := json.Unmarshal(mb, &m); err != nil {
return fmt.Errorf("manifest.json: %w", err)
}
if m.Rows != len(rows) {
problems = append(problems, fmt.Sprintf("manifest.json says %d rows, records.parquet has %d", m.Rows, len(rows)))
}
if len(problems) == 0 {
return nil
}
for _, p := range problems {
fmt.Fprintln(stdout, p)
}
return fmt.Errorf("%w: %d", errFound, len(problems))
}

// firstDiffLine names the first line where got and want differ.
func firstDiffLine(got, want []byte) string {
g, w := bytes.Split(got, []byte("\n")), bytes.Split(want, []byte("\n"))
for i := range max(len(g), len(w)) {
var gl, wl []byte
if i < len(g) {
gl = g[i]
}
if i < len(w) {
wl = w[i]
}
if !bytes.Equal(gl, wl) {
return fmt.Sprintf("line %d:%s", i+1, lineDiff(gl, wl))
}
}
return "no differing line"
}

// lineDiff names the fields two normalized rows differ in, or shows both
// lines whole when either is not a row.
func lineDiff(got, want []byte) string {
var g, w map[string]string
if json.Unmarshal(got, &g) != nil || json.Unmarshal(want, &w) != nil {
return fmt.Sprintf("\n committed %s\n normalized %s", got, want)
}
keys := slices.Sorted(maps.Keys(g))
for k := range w {
if _, ok := g[k]; !ok {
keys = append(keys, k)
}
}
var b strings.Builder
for _, k := range keys {
gv, gok := g[k]
wv, wok := w[k]
switch {
case !gok:
fmt.Fprintf(&b, "\n %s: missing, normalized %q", k, wv)
case !wok:
fmt.Fprintf(&b, "\n %s: committed %q, not a column", k, gv)
case gv != wv:
fmt.Fprintf(&b, "\n %s: committed %q, normalized %q", k, gv, wv)
}
}
return b.String()
}
Loading