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
3 changes: 3 additions & 0 deletions cmd/xtcp2/testdata/defineflags-golden.txt
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ s3SpillMaxBytes 1073741824 s3parquet: bytes -s3SpillDir may hold; past it the ol
s3UploadBackoffCap 0s s3parquet: cap on a single upload retry's backoff window (full jitter draws in [0,window]). 0 = derive as clamp(-frequency/10, 1s, 1h).
s3UploadMaxAttempts 10 s3parquet: max upload attempts (original + retries) before dropping the object. Retries use full-jitter exponential backoff.
tag label applied to the protobuf
tcpMaxBufferedBytes 0 tcp dest: marshaled envelope bytes the queue may hold. Past it the oldest envelope is dropped (reason="buffered_bytes"); the newest is always kept. 0 = no byte bound. Falls back to TCP_MAX_BUFFERED_BYTES env.
tcpQueueDepth 16 tcp dest: envelopes queued between the poller and the write worker (max 4096). Past it the oldest is dropped and counted in xtcp_tcp_dropped_total{reason="queue_depth"}, so a wedged sink never blocks polling. 0 = 16. Falls back to TCP_QUEUE_DEPTH env.
tcpWriteTimeout 30s tcp dest: deadline on a single write (and the dial), bounding a wedged route to the timeout instead of the TCP retransmit window (~15.4 min at prod tcp_retries2). Past it the conn is closed, the next attempt re-dials under full-jitter backoff, and after 3 failed attempts the envelope is dropped (xtcp_tcp_dropped_total{reason="attempts"}). 0 = 30s. Falls back to TCP_WRITE_TIMEOUT env.
timeout 5s Poll timeout per name space
topic xtcp Kafka or NSQ topic
treatmentAttribution optional journal directory of a standalone xtcp2-treatment-agent (its config's directory, default /var/lib/xtcp2/routes); this daemon only reads the snapshot and stamps treatment provenance onto records. Mutually exclusive with -treatmentConfig
Expand Down
37 changes: 37 additions & 0 deletions cmd/xtcp2/xtcp2.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ const (
s3MaxBufferedBytesCst uint64 = 64 * 1024 * 1024
s3SpillMaxBytesCst uint64 = 1024 * 1024 * 1024

// tcp destination delivery bounds (#345/#339): the write deadline,
// queue depth and byte bound handed to the tcp worker.
tcpWriteTimeoutCst = 30 * time.Second
tcpQueueDepthCst uint = 16
tcpMaxBufferedBytesCst uint64 = 0 // 0 = no byte bound (depth alone)

// Namespace-reconcile cadence defaults (Method B /proc-scan discovery).
// reconcileBeforePoll ties discovery to poll cadence (reconcile before each
// poll) and is the real discovery mechanism. The background reconcile is now
Expand Down Expand Up @@ -317,6 +323,10 @@ type mainFlags struct {
s3SpillDir *string
s3SpillMaxBytes *uint64

tcpWriteTimeout *time.Duration
tcpQueueDepth *uint
tcpMaxBufferedBytes *uint64

reconcileFrequency *time.Duration
reconcileBeforePoll *bool

Expand Down Expand Up @@ -514,6 +524,9 @@ func defineFlags() *mainFlags {
f.xtcpProtoFile = flag.String("xtcpProtoFile", xtcpProtoFileCst, "xtcpProtoFile for registering with the schema registry")
f.kafkaSchemaUrl = flag.String("kafkaSchemaUrl", kafkaSchemaUrlCst, "kafka schema registry URL")
f.produceTimeout = flag.Duration("produceTimeout", kafkaProduceTimeoutCst, "Kafka produce timeout (context.WithTimeout)")
f.tcpWriteTimeout = flag.Duration("tcpWriteTimeout", tcpWriteTimeoutCst, "tcp dest: deadline on a single write (and the dial), bounding a wedged route to the timeout instead of the TCP retransmit window (~15.4 min at prod tcp_retries2). Past it the conn is closed, the next attempt re-dials under full-jitter backoff, and after 3 failed attempts the envelope is dropped (xtcp_tcp_dropped_total{reason=\"attempts\"}). 0 = 30s. Falls back to TCP_WRITE_TIMEOUT env.")
f.tcpQueueDepth = flag.Uint("tcpQueueDepth", tcpQueueDepthCst, "tcp dest: envelopes queued between the poller and the write worker (max 4096). Past it the oldest is dropped and counted in xtcp_tcp_dropped_total{reason=\"queue_depth\"}, so a wedged sink never blocks polling. 0 = 16. Falls back to TCP_QUEUE_DEPTH env.")
f.tcpMaxBufferedBytes = flag.Uint64("tcpMaxBufferedBytes", tcpMaxBufferedBytesCst, "tcp dest: marshaled envelope bytes the queue may hold. Past it the oldest envelope is dropped (reason=\"buffered_bytes\"); the newest is always kept. 0 = no byte bound. Falls back to TCP_MAX_BUFFERED_BYTES env.")
f.label = flag.String("label", labelCst, "label applied to the protobuf")
f.tag = flag.String("tag", tagCst, "label applied to the protobuf")
f.location = flag.String("location", locationCst, "deployment grouping/facility this daemon runs in (data center, PoP, region, site, …); stamped on every record's `location`. Falls back to LOCATION env.")
Expand Down Expand Up @@ -890,6 +903,9 @@ func buildConfig(f *mainFlags, des *xtcp_config.EnabledDeserializers) *xtcp_conf
S3MaxBufferedBytes: *f.s3MaxBufferedBytes,
S3SpillDir: *f.s3SpillDir,
S3SpillMaxBytes: *f.s3SpillMaxBytes,
TcpWriteTimeout: durationpb.New(*f.tcpWriteTimeout),
TcpQueueDepth: uint32(*f.tcpQueueDepth),
TcpMaxBufferedBytes: *f.tcpMaxBufferedBytes,
ReconcileFrequency: durationpb.New(*f.reconcileFrequency),
ReconcileBeforePoll: *f.reconcileBeforePoll,
MaxDumpBytes: *f.maxDumpBytes,
Expand Down Expand Up @@ -1671,6 +1687,7 @@ func environmentOverrideConfig(c *xtcp_config.XtcpConfig, debugLevel uint) {
envOverrideMarshalAndDest(c, debugLevel)
envOverrideCaps(c, debugLevel)
envOverrideS3Queue(c, debugLevel)
envOverrideTCPQueue(c, debugLevel)
envOverrideKafka(c, debugLevel)
envOverrideLabeling(c, debugLevel)
envOverrideEnrichment(c, debugLevel)
Expand Down Expand Up @@ -2398,6 +2415,23 @@ func checkNoPositional(args []string) error {
return fmt.Errorf("unexpected argument %q: flags take -name value, and an empty value must be quoted (-name \"\" or -name=)", args[0])
}

// envOverrideTCPQueue applies TCP_WRITE_TIMEOUT, TCP_QUEUE_DEPTH and
// TCP_MAX_BUFFERED_BYTES, the tcp destination's delivery bounds.
func envOverrideTCPQueue(c *xtcp_config.XtcpConfig, debugLevel uint) {
if v, ok := envDuration("TCP_WRITE_TIMEOUT"); ok {
c.TcpWriteTimeout = durationpb.New(v)
logEnv("TCP_WRITE_TIMEOUT", fmt.Sprintf("c.TcpWriteTimeout:%s", v), debugLevel)
}
if v, ok := envUint32("TCP_QUEUE_DEPTH"); ok {
c.TcpQueueDepth = v
logEnv("TCP_QUEUE_DEPTH", fmt.Sprintf("c.TcpQueueDepth:%d", v), debugLevel)
}
if v, ok := envUint64("TCP_MAX_BUFFERED_BYTES"); ok {
c.TcpMaxBufferedBytes = v
logEnv("TCP_MAX_BUFFERED_BYTES", fmt.Sprintf("c.TcpMaxBufferedBytes:%d", v), debugLevel)
}
}

// envOverrideS3Queue applies S3_QUEUE_DEPTH, S3_MAX_BUFFERED_BYTES,
// S3_SPILL_DIR and S3_SPILL_MAX_BYTES, the s3parquet upload queue's bounds
// and its spill directory.
Expand Down Expand Up @@ -2479,6 +2513,9 @@ func printConfigCaps(c *xtcp_config.XtcpConfig) {
fmt.Println("c.MaxNetnsPerOwner:", c.MaxNetnsPerOwner)
fmt.Println("c.MaxNetnsAddsPerReconcile:", c.MaxNetnsAddsPerReconcile)
fmt.Println("c.S3QueueDepth:", c.S3QueueDepth)
fmt.Println("c.TcpWriteTimeout:", c.TcpWriteTimeout)
fmt.Println("c.TcpQueueDepth:", c.TcpQueueDepth)
fmt.Println("c.TcpMaxBufferedBytes:", c.TcpMaxBufferedBytes)
fmt.Println("c.S3MaxBufferedBytes:", c.S3MaxBufferedBytes)
fmt.Println("c.S3SpillDir:", c.S3SpillDir)
fmt.Println("c.S3SpillMaxBytes:", c.S3SpillMaxBytes)
Expand Down
6 changes: 5 additions & 1 deletion cmd/xtcp2/xtcp2_flags_helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const (
// mainFlags field must be a registered flag and every registered flag must
// have a field. A flag added without a field, or a field that stops being
// registered, is the drift this file exists to notice.
mainFlagsFieldCountCst = 143 // + treatmentConfig (embedded agent) and treatmentAttribution (journal reader)
mainFlagsFieldCountCst = 146 // + treatmentConfig (embedded agent) and treatmentAttribution (journal reader)

printFlagsGoldenCst = "testdata/printflags-golden.txt"
defineFlagsGoldenCst = "testdata/defineflags-golden.txt"
Expand Down Expand Up @@ -195,6 +195,10 @@ func populatedMainFlags() *mainFlags {
s3SpillDir: s("s3SpillDir-v"),
s3SpillMaxBytes: u64(1193),

tcpWriteTimeout: ms(1194),
tcpQueueDepth: u(1195),
tcpMaxBufferedBytes: u64(1196),

reconcileFrequency: ms(120),
reconcileBeforePoll: b(false),

Expand Down
6 changes: 6 additions & 0 deletions cmd/xtcp2/xtcp2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,9 @@ func TestPrintFlags(t *testing.T) {
f.s3MaxBufferedBytes = &n64
f.s3SpillDir = &s
f.s3SpillMaxBytes = &n64
f.tcpWriteTimeout = &d
f.tcpQueueDepth = &n
f.tcpMaxBufferedBytes = &n64
f.reconcileFrequency = &d
f.reconcileBeforePoll = &b
f.maxDumpBytes = &n64
Expand Down Expand Up @@ -1299,6 +1302,9 @@ func TestBuildConfig(t *testing.T) {
s3MaxBufferedBytes: &nl,
s3SpillDir: &ssd,
s3SpillMaxBytes: &ssmb,
tcpWriteTimeout: &rf,
tcpQueueDepth: &wf,
tcpMaxBufferedBytes: &nl,
reconcileFrequency: &rf,
reconcileBeforePoll: &rbp,
maxDumpBytes: &nl,
Expand Down
20 changes: 18 additions & 2 deletions docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,12 @@ All are in `xtcp_counts`.
| `destNATS` | `FlushOnClose` | error | the final flush at shutdown failed |
| `destHTTP` | `posts`, `postBytes` | count | POSTs and their bytes |
| `destHTTP` | `newRequest`, `do`, `status` | error | building or sending the POST failed, or a non-2xx status |
| `destTCP`, `destUnix`, `destUnixGram` | `Writes`, `WriteBytes` | count | writes and their bytes |
| `destTCP`, `destUnix`, `destUnixGram` | `Write` | error | a write failed |
| `destTCP` | `Writes`, `WriteBytes` | count | the worker's writes and their bytes |
| `destTCP` | `Write` | error | a write failed (the conn is closed; the next attempt re-dials) |
| `destTCP` | `Dial` | error | a (re)connect dial failed |
| `destTCP` | `Reconnect` | count | a dial succeeded after a failed write/dial — delivery healed without a restart |
| `destTCP` | `queueFull` | error | an envelope was dropped from the queue, past `-tcpQueueDepth` or `-tcpMaxBufferedBytes` |
| `destTCP` | `dropped` | error | the worker dropped an envelope (attempt budget exhausted, or shutdown) |
| `Inetdiager` | `udpWrites`, `udpWriteBytes` / `udpConn.Write` | count / error | the UDP destination's writes |
| `destUDPIoUring`, `destUnixIoUring`, `destUnixGramIoUring` | `Writes`, `WriteBytes` / `Write` | count / error | io_uring destination writes, from their completions |
| `destUDPIoUring`, `destUnixGramIoUring` / `destUnixIoUring` | `EnqueueSend` / `EnqueueWritev` | error | a write couldn't be queued on the ring |
Expand All @@ -227,6 +231,18 @@ The s3parquet upload queue has its own series. Past either bound it drops the ol
| `xtcp_s3_spill_total` | `result="written"\|"uploaded"\|"evicted"\|"too_large"\|"error"` | Parquet objects through `-s3SpillDir`: spilled after a failed upload, uploaded from the spill, deleted past `-s3SpillMaxBytes`, refused as larger than the bound, or a write failure or corrupt file |
| `xtcp_s3_spill_objects`, `xtcp_s3_spill_bytes` | | objects and bytes waiting in the spill directory |

The tcp destination has the same queue shape (a bounded FIFO between the
poller and one write worker): `Send` never blocks, every write and dial
carries `-tcpWriteTimeout`, a failed write reconnects under full-jitter
backoff, and past 3 attempts per envelope the envelope is dropped and
counted — a wedged or unreachable sink stalls delivery, never polling.

| metric | labels | meaning |
|---|---|---|
| `xtcp_tcp_dropped_total` | `reason="queue_depth"\|"buffered_bytes"\|"attempts"\|"shutdown"` | envelopes dropped: past `-tcpQueueDepth`/`-tcpMaxBufferedBytes` (oldest first), after the write-attempt budget exhausted (the sink was unreachable for `-tcpWriteTimeout` × attempts), or still queued at close |
| `xtcp_tcp_dropped_bytes_total` | `reason` | their marshaled bytes |
| `xtcp_tcp_buffered_bytes` | `stage="queue"` | bytes held: envelopes awaiting the worker |

### Enrichment

`enrich*.go`. Updates per refresh or per event, not per record.
Expand Down
2 changes: 1 addition & 1 deletion docs/redteam-harness.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ definition behind `REDTEAM_ROUTER=1`):
attacker↔victim vantage — distinct from libvirt's default net so the DoD
"no networks beyond the defined ones" assertion is `virsh net-list`-checkable;
- `victim` provisioning: `common.sh` → upload `.gen/*.tar.gz` → `victim.sh
<MODE> <AUTH> <CAPS> <ATTACKER> <DEST> <ENRICH> <NOFILE> <CPUS> <PPROF> <MAX_RECORDS> <SINK_IP>` (matrix as
<MODE> <AUTH> <CAPS> <ATTACKER> <DEST> <ENRICH> <NOFILE> <CPUS> <PPROF> <MAX_RECORDS> <SINK_IP> <TCP_WRITE_TIMEOUT>` (matrix as
argv, validated by `lib/matrix.sh` — env → argv translation happens in the
Vagrantfile so `vagrant provision` alone re-applies a matrix change). The
Phase 4 axes: `XTCP2_NOFILE` (`default` = docker's own 524287 on
Expand Down
1 change: 1 addition & 0 deletions docs/redteam-implementation.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ completing the RT-4 suite and RT-11 tiers 1–2.
- [x] Phase 4 part 1 complete: rt-4-1 **BLOCKED** (8/8 — the ladder + the amplifier finding), rt-11-2 **BLOCKED** (11/11 — the crossover refuted at a pinned budget, the RT-11 ops answer), rt-4-2 **BLOCKED** (11/11 — the 5 s absolute ReadHeaderTimeout makes the slowloris premise unreachable; 26 KiB/conn while alive), rt-4-5 **BLOCKED** (9/9 — the in-flight cap engages on the slow paths, 10x 503 on `/metrics-all`; the fast path self-throttles). New tools: sockfill `-remote` (the ladder), slowloris (the drip), grpcidle (the gRPC pin) — all static, in the attacker tools tar; two new deploy axes `XTCP2_NOFILE`/`XTCP2_CPUS`.
- [x] Phase 4 part 2 complete (the stream/gRPC suite): rt-4-3 **BLOCKED** (11/11 — read-cred oversize answered PermissionDenied at the method ACL before the 4 MB cap is even reachable; admin-cred oversize answered ResourceExhausted; a 10×20 reading storm cost a linear 299 goroutines, 1.1 M records, no leak 71→299→71), rt-11-3 **CONFIRMED** (11/11 — **the strongest RT-11 crossover**: ONE never-reading authenticated stream took the catcher 1993 → 0 lines/6 s; `flatRecordServiceSend`'s blocking per-client Send runs per record on the decode hot path, so one stalled stream backpressures the whole fleet; API stayed 200 — the tier-2 split; recovery ≤6 s, no leak), rt-4-4 **BLOCKED** (11/11 — RSS slope −17 KiB/s under 4 paced readers, and the backpressure finding: the catcher collapsed 1494 → 0 lines/6 s with EXACTLY 32 records in 240 s — the paced wedge, same root cause as rt-11-3), rt-2-9 **CONFIRMED** (7/7 — stream-expiry carry-over: 2158/2200 records flowed ~50 s past the skew-0 window; file-don't-fix, ops note: key rotation does not break held-open streams). New tool: grpcstorm (storm/oversize/wedge/paced/HMAC shapes, static, in the attacker tools tar); new deploy axis `XTCP2_PPROF` (a loopback, token-gated debug listener for goroutine-count asserts — an observability axis, not a surface change); rt-2-2's Phase-4 deferral landed as row rt-2-9. Full matrix regression: **30 scenarios, 29 PASS + 1 harness race fixed + re-verified solo** — rt-2-2's in-minute replay minted at :44 and the tcpdump window pushed the replay past the boundary (correct 401 under skew 0; the assert raced, not the product): the guard now lands the mint at 05..18 and re-mints once if a slow provision still crosses.
- [x] Phase 4 part 3 complete (the delivery-outage suite): rt-4-7 **BLOCKED** (15/15, the split verdict — the s3 queue sink: RSS slope 70 KiB/s, the outage counted (`destS3Parquet/upload/error`, `s3_dropped_total=8`), recovery on endpoint return (objects 1270→2375); the tcp half: the permanent blind measured — counters light immediately, polling continues, the catcher restart changes nothing, only a daemon restart re-dials), rt-11-4 **BLOCKED** (14/14 — 300,008 thief sockets, victim coverage lag 0 s (parallel per-netns dumps + the 1 s poll-timeout valve), PollTimeout firing every cycle, RSS 29→31 MiB, and the amplifier at scale: 211,244 lines/6 s ≈ 100× baseline; the walkable budget engaged `xtcp_poll_degraded_total{level="sample"}` with victims still at 0 s lag), rt-11-5 **CONFIRMED** (16/16 — the L2 freeze: a CAP_NET_RAW sibling ARP-blackholes the sink via a 200 ms gratuitous-reply loop; the poller FREEZES in the blocked Write (no deadline, sync on the poll goroutine) for the whole retransmit window (~15.4 min at the prod default) with zero error counters and scrape 200; de-poison mid-window = full catch-up with no loss; the window closed = counters light + delivery permanently dead). New tool: arppoison (static, in the attacker tools tar); new deploy axes `XTCP2_MAX_RECORDS` (rt-11-4's walkable budget) and `XTCP2_SINK_IP` (rt-11-5's dedicated sink alias — poisoning the gateway takes the docker-proxy replies down with it, measured); the freeze finding filed as #345. Full matrix regression: **33 scenarios, 32 PASS + 1 tool race fixed + re-verified solo** — rt-4-3's oversize probe (leg B) raced the transport's arrival-based recv-limit kill against a fanned-out record beating the 8 MB frame on a fresh slow-start conn (measured OK 3/3 in the matrix, ResourceExhausted 12/12 by hand): the probe now drains Recv to the terminal verdict.
- [x] **Product fixes #345 + #339 landed with the expectation flips in the same change** (the S2 pair the delivery-outage suite surfaced): the tcp destination is now a bounded queue + worker — `Send` never blocks (the poller can never freeze on the sink), every write AND dial carries `tcp_write_timeout` (config field 120, validate-gted/lte'd to [1s, 1h], Go belt `resolveTCPWriteTimeout`, default 30 s, CLI `-tcpWriteTimeout`/`TCP_WRITE_TIMEOUT` env), the queue is `envelopeQueue` shared with s3 (moved untagged to destinations_queue.go — tcp is in every flavor including stdlib-only), and a failed write reconnects under full-jitter backoff (the `backoffWindow` cap derived like s3's: clamp(poll_frequency/10, 1s, 1h)) with 3 attempts per envelope, then drop-and-count. New counters: `xtcp_tcp_dropped_total{reason}` / `_bytes_total` / `xtcp_tcp_buffered_bytes{stage}` + `destTCP` Dial/Reconnect/queueFull/dropped. Verified by the same attacks that pinned the bugs: **rt-11-5 MITIGATED 18/18** (polls keep issuing through the stall 25→47/32 s — the freeze gone; Write/error=9, Dial/error=8, drops=3 while dark; de-poison heals with NO restart, reconnects=1; second cycle repeats — a REACHABLE neighbor entry ignores gratuitous ARP until STALE ~30 s, the flip is now a bounded wait) and **rt-4-7 BLOCKED 15/15** (the catcher restart heals delivery, reconnects=1, 2482 lines/6 s — no daemon restart). Harness: deploy axis `XTCP2_TCP_WRITE_TIMEOUT` (Vagrantfile arg 12). Harness lesson: `promLabels` order is function, VARIABLE, type — `WithLabelValues("destTCP","Write","error")` emits `type="error",variable="Write"`; grep the emitted order or the assert reads empty.
- [ ] 24 h churn variant runs clean overnight once (logged evidence), or its blocker filed. (Phase 4 part 4)
- [ ] rt-11-5 shows delivery metrics lighting up during the L2 kill (assert specific series non-zero), or files the observability gap.
- [ ] rt-11-7 either survives or produces a crashing fixture committed under the repo's fixture path and a linked parser issue.
Expand Down
Loading