diff --git a/docs/netlink/events-export-status.md b/docs/netlink/events-export-status.md index 605d5fb8f..75a8607a7 100644 --- a/docs/netlink/events-export-status.md +++ b/docs/netlink/events-export-status.md @@ -40,7 +40,7 @@ - States are `not started`, `in progress`, `blocked`, `done` or `deferred`. There are no percentages. - A task is `done` only when its gates have passed and the evidence is in the [ledger](#verification-ledger). -- Evidence IDs (`V###` for code and VM runs, `DOC###` for docs) are immutable and append-only. The next free ID is V406; the next free DOC is DOC040 (DOC039 is the gobridge write arc's 26B; DOC038 is the gobridge monitor arc's 25B, renumbered from its landed DOC035 — a collision with the events plan's DOC035 — by the events export arc's index-row fix). +- Evidence IDs (`V###` for code and VM runs, `DOC###` for docs) are immutable and append-only. The next free ID is V407; the next free DOC is DOC040 (DOC039 is the gobridge write arc's 26B; DOC038 is the gobridge monitor arc's 25B, renumbered from its landed DOC035 — a collision with the events plan's DOC035 — by the events export arc's index-row fix). - Task IDs (`EXM`, `EXP`, `EXD`, `EXC`, `EXU` with `-Tmm` suffixes) are never renumbered. ## Phase states @@ -49,7 +49,7 @@ |---|---|---|---|---| | [Tier EXM](events-export.md#tier-exm-the-policy-measured) | the constants, measured from the corpora | EXM-T02 | done | V403 | | [Tier EXP](events-export.md#tier-exp-the-proto) | the messages, the generation, the conversion | EXP-T02 | done | V404 | -| [Tier EXD](events-export.md#tier-exd-the-destination) | the producer, the config, the self-test gate | EXD-T03 | in progress (T01/T02 done, V405) | V405 | +| [Tier EXD](events-export.md#tier-exd-the-destination) | the producer, the config, the self-test gate | EXD-T03 | done | V405, V406 | | [Tier EXC](events-export.md#tier-exc-clickhouse) | the table, the topic, the flavor | EXC-T03 | not started | — | | [Tier EXU](events-export.md#tier-exu-the-close) | §14 resolved, the deferrals unwound | EXU-T01 | not started | — | @@ -63,7 +63,7 @@ | [x] | [EXP-T02](events-export.md#exp-t02-generation-and-conversion) | generation and conversion | done | V404 | | [x] | [EXD-T01](events-export.md#exd-t01-the-producer) | the producer | done | V405 | | [x] | [EXD-T02](events-export.md#exd-t02-the-config-and-the-flag) | the config and the flag | done | V405 | -| [ ] | [EXD-T03](events-export.md#exd-t03-the-gate) | the self-test gate | not started | — | +| [x] | [EXD-T03](events-export.md#exd-t03-the-gate) | the self-test gate | done | V406 | | [ ] | [EXC-T01](events-export.md#exc-t01-the-table) | the table | not started | — | | [ ] | [EXC-T02](events-export.md#exc-t02-the-epoch-and-the-topic) | the epoch and the topic | not started | — | | [ ] | [EXC-T03](events-export.md#exc-t03-the-gate) | the flavor | not started | — | @@ -73,12 +73,22 @@ | ID | Task | Evidence | |---|---|---| +| V406 | EXD-T03 | **The gate, live.** The interface-naming flavor's daemon runs `-eventsEnable -eventsDest file:/var/log/xtcp2-events.bin` beside `-localityEvents` (the both-on composition), and the new EVENTS_EXPORT check (`nix/microvms/self-test.nix`, the `EVENTS_EXPORT` sentinel) drives a link add/up/addr/del sequence (`evtcheck0`, 198.51.100.77/32 — unique, so the file's other events cannot satisfy the greps) in the daemon's own namespace, reads the export back with **events-probe** (`tools/events-probe`, riding xtcp2AllPackage like rtnlmon-probe: the ProtobufList read-back via `recordfmt.NextDelimited` + `UnmarshalVT`, printing rtnlmon-probe's own line grammar plus the per-row netns), and asserts the four steps in order, the root listener's `netns=default`, and the interval flush counter. **The live run** (`nix build .#test-microvm-lifecycle-x86_64-interface-naming`, booted and driven here): `EVENTS_EXPORT_PASS (add=35 addr=40 del=50; rows=50; interval flushes=25)` and `OVERALL_PASS`. **Two root causes the gate caught, both now unit-pinned:** (1) the interval chain was armed only inside flushLocked — an exporter whose namespaces produce no startup events (a quiet boot; the veth topology must happen to churn) never arms one, and the 1s bound is dead from the start; the chain now arms at construction (`newEventsExport`), and `TestEventsExportIntervalFromConstruction` pins the fix. (2) the empty interval flush did not count (the return came before the counter), so the flush counter proved nothing on a quiet file; the counter now fires on every trigger, an empty envelope included — the empty cadence is the proof the timer lives. The gate's own lessons: the metrics' labels print sorted (function, type, variable — a `variable=…type=…` grep order never matches; the locality check's greps never place type= after variable= for this reason), the self-test's echo lines never reach the journal (the diagnostics ride the XTCP2_SELF_TEST_* sentinel line itself), and the check does not demand the whole file be `netns=default` — the rows from the flavor's other namespace are the per-namespace listener's, the both-on second in-namespace thread's events, and are the composition working, not a label bug (the run shows 8 of 52 on the non-root namespace). Gates: both full suites, vet both modes, gofmt, lint-baseline, nix-fmt, test-goip-docs, netlink-audit, test-goip-monitorfile, nix-fmt over the flavor edits, and the VM gate itself. | | V405 | EXD-T01/T02 | **The producer** (`pkg/xtcp/events_export.go`): one `rtnlmon` listener per monitored namespace feeds a shared `eventsExport` — every namespace appends to one envelope (EXM: one notification per datagram, so the flush policy is the batching and low volume shares it), which flushes on the rows cap, the bytes cap, the interval and shutdown, writing the ProtobufList wire (`recordfmt.AppendDelimited`, the generic twin of the record path's `AppendEnvelopeProtobufList`, plus `NextDelimited` the read-back reader). **The header-carrying dispatch:** `rtnlmon.HandlerHdr` (`EventHdr(hdr, ev)`) — `run` detects it once and hands the handler the `nlmsghdr` it already holds at the dispatch point; the plain `Handler` is dispatched unchanged, and the handler's unreachable `Event` fails loudly. **The rule groups** (`GroupIPv4Rule`/`GroupIPv6Rule`) are valid but contribute no snapshot dump — nothing folds rules; the events' handler no-ops `Snapshot` entirely (the startup drain-then-dump is resync state; the non-start reasons count, so an overrun's dropped notifications are visible, never silent). **The epoch guard:** each flush schedules the next interval timer, and a stale callback (a timer that fired while a cap flush held the mutex) no-ops on its epoch — without it a second timer stacks behind the live one and doubles the cadence forever (`TestEventsExportStaleTimerNoOp`). **The both-on composition:** `-localityEvents` keeps the namespace's own wait thread (unchanged) and the export gets a second in-namespace thread through a `Dup` of the ns fd (setns in, run, restore; a failed restore keeps the thread locked so the runtime terminates it — netNamespaceInstance's own documented lesson). The both-off and events-only cases: `listenNamespace` is the one wait-thread dispatcher. **The config:** `events_enable`/`events_dest`/`events_flush_{interval_ms,threshold_rows,threshold_bytes}` at 260-264 (0 = the EXM constants), the five `-events*` flags, env fallbacks, goldens updated (`mainFlagsFieldCountCst` 146→151, `printflags-golden`, `defineflags-golden`). The `min_len: 6` first cut on `events_dest` rejected the empty default and was caught by `TestRunMain_debugWritersNotCompiledIn` — the field validates max-len only, and enable-without-dest is the startup error. **The gate tests:** `TestRunHandlerHdr` (header fidelity through the dispatch, pinned from a corpus datagram retagged with a distinctive echo — `NLM_F_ECHO`, not `NLM_F_MULTI`, which `WalkNotifications` filters), `TestPlanDumpsRuleGroups`, `TestEventsExportFlush{RowsCap,BytesCap,Interval,Shutdown}`, `TestEventsExportStaleTimerNoOp`, `TestEventsExportHandler` (the glue: header fields, nsid lookup, the unreachable Event), `TestEventsNetnsLabel`, `TestEventsExportWaitDispatch`, `TestDelimitedRoundTrip`/`TestNextDelimitedErrors`. Gates: both full suites, vet both modes, gofmt, `lint-baseline`, `test-goip-docs`, `netlink-audit`, `nix-fmt`, `buf lint`. The file sink is v1's own (the factories are single-dest); the factory generalization is EXC's measured need. | | V404 | EXP | **The proto:** `proto/xtcp_netlink_events/v1/xtcp_netlink_events.proto` — the five family messages in the record proto's own style (the header cites the allocation plan: 2100 ifinfomsg, 2200 ifaddrmsg, 2300 rtmsg, 2400 ndmsg, 2500 fib_rule_hdr; the blocks sit above 2047, so every payload field costs a 3-byte tag — §14 assigns the numbers, and EXM's measured low volume is what makes the cost immaterial). Every field carries a kernel-source comment with the attribute number read from `~/Downloads/linux/include/uapi/linux/{if_link,if_addr,rtnetlink,neighbour,fib_rules}.h` (IFLA_OPERSTATE 16, NDA_FDB_EXT_ATTRS 14, FRA_DSCP_MASK 30, …). Presence is a `has_`-prefixed bool beside the value — the structs' own Has* pairs, load-bearing for the events' render semantics. **The v1 surface:** the header structs and the scalar attributes; the nested payloads (the forty per-kind link nests, RTA_MULTIPATH, RTA_METRICS, the stats blocks) are presence bits, each a later block, never an epoch bump — the file header's scope note names the rule. `NetlinkEvent` carries the nlmsghdr, the timestamp, the netns provenance (the record's own netns/netns_inode/nsid/nsid_assigned contract), the derived action enum, and the oneof. `XtcpNetlinkEventsSchemaVersion = 1` lands in `pkg/xtcp/schema_version.go` beside the record's. **Generated** by `nix run .#regen-protos` (the regen re-resolves the protovalidate dep in `buf.lock` to a newer commit; the events proto imports nothing, so the outputs are lock-independent and the lock is reverted — the drift is the regen path's own behavior, noted for the next arc that regenerates). **The conversion** (`pkg/xtcp/events_export_convert.go`): a pure function per family plus the `ConvertNetlinkEvent` wrapper (any other payload is an error, never a silent drop). **The gate:** `TestEventsExportConvertRoundTrip` walks the 71 event pcaps and the 15 crafted `.nl` files — parse, convert, marshal, unmarshal, `proto.Equal` — **458 link, 165 addr, 303 route, 107 neigh, 10 rule**, the totals pinned; `TestEventsExportConvertSpotPins` compares the struct's own values against the converted fields for one corpus event per family (the round trip alone cannot catch a swapped mapping — both directions would carry the same wrong field). **The wire-contract finding, groundwork for EXC:** the committed `clickhouse_protolist` artifacts pin the ProtobufList framing — `insert4294967295.proto.bin` is `[varint][Record bytes]` (one length-delimited row per row) while `insert1_and_4294967295.bin` is `[varint][Envelope]` (rows wrapped) — and the record's kafka table names the ROW type with the comment "ClickHouse's ProtobufList handles the envelope framing internally". Which schema name the events' engine table names, and how the oneof's payloads map to columns, is EXC-T01's container probe. Gates: both full suites, vet both modes, gofmt, `lint-baseline`, `test-goip-docs`, `netlink-audit`, `nix-fmt`, `buf lint` (STANDARD, clean). | | V403 | EXM | **Measured:** `TestEventsExportPolicyInputs` (`pkg/xtcpnl/xtcpnl_events_export_policy_test.go`) walks the committed event corpora — the five 7.1.4 oneshot pcaps (a 41-second boot window; the base pcap the union of the four family splits, 355 = 66+125+44+120) and the 66 ev rows at both iproute2 versions — and pins the measured shape: events, datagrams, the per-event body sizes, the peak 100 ms and 1 s windows, the quiet gaps. **The finding that reshaped the tier:** one notification per datagram, every corpus, both kernel eras, every family (max events per datagram = 1, asserted over all 71 pcaps) — the plan's premise that the kernel batches notifications into one recvmsg is falsified; the flush policy is the batching. **The numbers:** the boot flood peaks at 56 events in 100 ms (60 in the worst second); a churn row's whole window peaks at 17; the quiet gaps run to 16.69 s (steady state); the event bodies run 40 bytes (the smallest route/nsid event) to 1548 (a full link event), median 40-116. **The constants** (`pkg/xtcp/events_export_policy.go`): `EventsFlushIntervalCst` = 1 s (the locality consumer's own chosen latency, the §13 close's "within a 1s debounce"; a lone event waits at most this), `EventsFlushThresholdRowsCst` = 64 (above the 56-per-100 ms boot peak, ~4× the churn rows' worst window), `EventsFlushThresholdBytesCst` = 64 KiB (~41 of the widest 1548-byte rows; the record path's rows-primary/bytes-secondary pair). The queue needs no events-specific depth: the destination's default (16 envelopes) holds over 1.5 s of the measured worst flood, and drop-oldest is the record path's answer. The test's walk treats a zero nlmsghdr as end-of-datagram padding (the 7.1.4 oneshot zero-pads its records — measured at base-pcap record 515) and is manual, not `WalkNlMsgsHdr`, because the latter's seq filter drops exactly the userspace-caused notifications (`IsRtnetlinkNotification`'s own documented trap). The crafted monitor files carry no timestamps, so they are EXP's round-trip inputs, not this measurement's. Gates: `go test ./pkg/xtcpnl/ -run TestEventsExportPolicyInputs`, both full suites, vet both modes, gofmt, `lint-baseline`, `test-goip-docs`, `netlink-audit`, `nix-fmt`. | ## Decision log +- **2026-12-05: the gate run caught the producer's zero-start (V406).** The + EXD-T03 gate's first live run exported nothing on a quiet boot — the + interval chain was armed only at a flush, so an exporter with no startup + events never armed a timer, and the 1s bound was dead from the start + (the run's binary at the second boot happened to see the veth topology + churn, reached the rows cap, and worked — the non-determinism is the + quiet boot's, which is exactly what the gate exists to catch). The fix: + arm at construction; the empty interval flushes now count, and + `TestEventsExportIntervalFromConstruction` pins it. - **2026-12-04: EXD designed against three measured constraints (V404's groundwork).** (1) `rtnlmon`'s `Handler.Event(ev any)` carries no nlmsghdr — the wrapper's nlmsg_seq/nlmsg_pid (the originating process's diff --git a/events-probe b/events-probe new file mode 100755 index 000000000..479a613f4 Binary files /dev/null and b/events-probe differ diff --git a/nix/binaries.nix b/nix/binaries.nix index a56157687..07c8e1dbb 100644 --- a/nix/binaries.nix +++ b/nix/binaries.nix @@ -266,6 +266,11 @@ let # snapshots and events. Rides xtcp2AllPackage into every lifecycle microvm, # where the self-test runs it as the RTNL_EVENTS check. "rtnlmon-probe" + # events-probe: reads the events-export destination file (-eventsEnable + # producer output) back and prints one line per row. Rides xtcp2AllPackage + # into the interface-naming microvm, where the self-test runs it as the + # EVENTS_EXPORT check (events-export.md, EXD-T03). + "events-probe" # sockfill: holds N loopback TCP pairs (or a never-accepting listener) # open in its namespace. Rides xtcp2AllPackage into the socket-scale # microvm, which builds 100k-500k socket tables with it. @@ -418,6 +423,7 @@ defaultBinaries tcp_client discovery-bench rtnlmon-probe + events-probe sockfill ipfeed-fixture slowloris diff --git a/nix/microvms/default.nix b/nix/microvms/default.nix index 2d5042532..2802c6f71 100644 --- a/nix/microvms/default.nix +++ b/nix/microvms/default.nix @@ -837,6 +837,7 @@ let "IFNAME" "ASN" "LOCALITY_EVENTS" + "EVENTS_EXPORT" ]; # Checks 5f/5g each poll for up to 2 min (x waitScale). That fits inside # the default stall watchdog, and the old 600 s absolute cap is now below diff --git a/nix/microvms/mkVm.nix b/nix/microvms/mkVm.nix index 599e8aa7c..3d4c49d65 100644 --- a/nix/microvms/mkVm.nix +++ b/nix/microvms/mkVm.nix @@ -598,6 +598,12 @@ let # LOCALITY_SELF through the -localityEvents listener. runLocalityEventsCheck = isInterfaceNaming; localityEventsIf = ifnEgrIf; + # interface-naming flavor only (EXD-T03): the daemon runs -eventsEnable + # beside -localityEvents, and the EVENTS_EXPORT check drives a link + # add/up/addr/del sequence in the daemon's own namespace and reads the + # export back from -eventsDest. + runEventsExportCheck = isInterfaceNaming; + eventsExportPath = eventsExportPath; inherit asnDbPath asnCachePath @@ -2436,6 +2442,12 @@ let # the self-test run as root, so a 0600 file under /var/log is readable. fileOutputPath = "/var/log/xtcp2.jsonl"; + # Where the events export writes when the flavor turns it on: the + # -eventsDest file: path (EXD's v1 sink, beside the record file dest — + # both root-owned 0600 under /var/log, readable by the self-test). The + # interface-naming flavor's EVENTS_EXPORT check reads it back. + eventsExportPath = "/var/log/xtcp2-events.bin"; + # socket-sink flavors: stream jsonl records over the raw socket destination # (tcp/udp/unix/unixgram) to the in-VM ncat receiver. For inet dests, # `localhost` (dual-stack) resolves to 127.0.0.1 AND ::1 and the sink listens @@ -3289,6 +3301,9 @@ in "-localityEvents" "-localityRefreshInterval" "10m" + "-eventsEnable" + "-eventsDest" + "file:${eventsExportPath}" "-enrichAsn" "-asnDbPath" asnDbPath diff --git a/nix/microvms/self-test.nix b/nix/microvms/self-test.nix index 28c28daf2..e98ff75cd 100644 --- a/nix/microvms/self-test.nix +++ b/nix/microvms/self-test.nix @@ -119,6 +119,14 @@ # address added after start makes # its socket LOCALITY_SELF via the # -localityEvents listener +# XTCP2_SELF_TEST_EVENTS_EXPORT_{PASS,FAIL} (interface-naming only) the +# -eventsEnable producer: a link +# add/up/addr/del sequence driven +# in the daemon's own namespace +# is read back from the +# -eventsDest file, decoded, and +# compared with what the check +# drove (events-export.md EXD-T03) # XTCP2_SELF_TEST_IPMETA_BOOTSTRAP_{PASS,FAIL} bootstrap lookup artifact # enriches records before live data # XTCP2_SELF_TEST_IPMETA_RECOVERY_{PASS,FAIL} delayed in-VM HTTP source @@ -269,6 +277,13 @@ # rtnetlink listener can explain, not the timed re-dump. runLocalityEventsCheck ? false, localityEventsIf ? "", + # When true (interface-naming flavor, whose daemon runs -eventsEnable + # -eventsDest file:…), the EVENTS_EXPORT check drives a distinctive link + # add/up/addr/del sequence in the daemon's own namespace and reads the + # export back: every step in order, the netns label the root listener + # stamps, and the interval flush counter. + runEventsExportCheck ? false, + eventsExportPath ? "", # When true (ipmeta-bootstrap flavor), validates the cold-start bootstrap # lookup, delayed in-VM HTTP source recovery, cache rotation, and rejection of # a later empty/bad update while xtcp2 keeps enriching from the last good @@ -1127,6 +1142,65 @@ pkgs.writeShellApplication { if [ "$checkLe" -ne 0 ]; then overall_ok=0; fi ''} + # ─── Check 5g: events export read-back (EXD-T03) ──────────────────── + # The daemon runs -eventsEnable -eventsDest file:… beside -localityEvents + # (the both-on composition). This check drives a distinctive sequence in + # the daemon's own namespace — dummy link add, up, address add, link del — + # then reads the export back with events-probe: every step must appear, + # in order, with the root listener's netns label, and the interval flush + # counter must have moved. The sequence is deliberately unique (evtcheck0, + # 198.51.100.77/32) so the file's other events — earlier checks' address + # churn included — cannot satisfy the grep. + ${lib.optionalString runEventsExportCheck '' + echo "--- check: events export (${eventsExportPath}) ---" + checkEv=1 + ev_metrics() { curl -sf "''${prom_auth[@]}" "http://127.0.0.1:${toString promPort}/metrics" 2>/dev/null || true; } + ev_iprc=0 + { ip link add evtcheck0 type dummy || ev_iprc=$? + ip link set evtcheck0 up + ip addr add 198.51.100.77/32 dev evtcheck0 + ip link del evtcheck0 + } 2>/tmp/xtcp2-ev-ip.log || true + ev_ip1=$(head -1 /tmp/xtcp2-ev-ip.log 2>/dev/null || true) + evOk=0 + for _ in $(seq 1 "$(scaled 30)"); do + events-probe -file "${eventsExportPath}" >/tmp/xtcp2-ev.log 2>&1 || true + evFirst() { grep -n -m1 -E "$1" /tmp/xtcp2-ev.log | cut -d: -f1; } + e_add=$(evFirst '^EVENTS_EVENT link add .* ifname=evtcheck0 up netns=') + e_addr=$(evFirst '^EVENTS_EVENT addr add .* addr=198\.51\.100\.77/32 netns=') + e_del=$(evFirst '^EVENTS_EVENT link del .* ifname=evtcheck0 ') + if [ -n "$e_add" ] && [ -n "$e_addr" ] && [ -n "$e_del" ] \ + && [ "$e_add" -lt "$e_addr" ] && [ "$e_addr" -lt "$e_del" ]; then + evOk=1 + break + fi + sleep 1 + done + # The netns label: the root listener stamps "default" on every row it + # exports; the event lines the check drove all demand it by their + # greps. The OTHER rows (rows total vs default rows) are the per- + # namespace listener's - the both-on composition, the second + # in-namespace thread's events - so the check demands its own rows + # carry the default label, not that the whole file does. + ev_netns=$(grep -c 'netns=default$' /tmp/xtcp2-ev.log 2>/dev/null || true) + ev_other=$(grep -c '^EVENTS_EVENT .*netns=' /tmp/xtcp2-ev.log 2>/dev/null || true) + ev_flush=$(ev_metrics | grep -E '^xtcp_counts\{[^}]*function="eventsExport"[^}]*type="interval"[^}]*variable="flush"[^}]*\} ' | awk '{print $2}' | head -1) + ev_probe=$(tail -1 /tmp/xtcp2-ev.log 2>/dev/null || true) + ev_srv=$(systemctl is-active xtcp2.service 2>/dev/null || true) + ev_evtx=$(ev_metrics | grep -c 'eventsExport' || true) + if [ "$evOk" -eq 1 ] && [ "$ev_netns" -ge 3 ] \ + && [ -n "$ev_flush" ] && [ "''${ev_flush%%.*}" -ge 1 ] 2>/dev/null; then + echo "XTCP2_SELF_TEST_EVENTS_EXPORT_PASS (add=$e_add addr=$e_addr del=$e_del; rows=$ev_other netns=default; interval flushes=''${ev_flush%%.*})" + checkEv=0 + else + # The diagnostics ride the sentinel line: the echo lines above do not + # reach the journal (the service's console path drops them), but the + # XTCP2_SELF_TEST_* line always does. + echo "XTCP2_SELF_TEST_EVENTS_EXPORT_FAIL (seen=$evOk netns_rows=$ev_netns of $ev_other interval_flushes=''${ev_flush:-absent} add=$e_add addr=$e_addr del=$e_del; ip-add rc=$ev_iprc [ ''${ev_ip1} ]; probe: $ev_probe; srv=$ev_srv evtx=$ev_evtx)" + fi + if [ "$checkEv" -ne 0 ]; then overall_ok=0; fi + ''} + # ─── Check 5f: raw socket destination → in-VM ncat sink ─────────────── # ─── Check 5h: IP metadata bootstrap / recovery / bad update ────────── ${lib.optionalString runIpmetaBootstrapCheck '' diff --git a/pkg/xtcp/events_export.go b/pkg/xtcp/events_export.go index 88d7cd9fa..a441629f6 100644 --- a/pkg/xtcp/events_export.go +++ b/pkg/xtcp/events_export.go @@ -128,20 +128,32 @@ func newEventsExport(x *XTCP) (*eventsExport, error) { if bytes <= 0 { bytes = EventsFlushThresholdBytesCst } - return &eventsExport{ + ex := &eventsExport{ x: x, f: f, env: &xtcp_netlink_events.Envelope{}, interval: interval, thresholdRows: rows, thresholdBytes: bytes, - }, nil + } + // The interval chain starts HERE, not at the first flush: the timer is + // armed inside flushLocked, so an exporter whose namespace never + // produces events (quiet, or the caps never reached) would never arm + // one - the 1s bound would be dead from the start. Arming at + // construction makes "a lone event waits at most the interval" true for + // the very first event, and the empty cadence is visible in the + // flush counter from the first second. + ex.arm() + return ex, nil } // initEventsExport constructs the exporter when events_enable is set; a bad // -eventsDest is a startup error, not a silent no-op — the operator asked // for the export. func (x *XTCP) initEventsExport() { + if x.debugLevel > 10 { + log.Printf("eventsExport: init: enable=%t dest=%q", x.config.GetEventsEnable(), x.config.GetEventsDest()) + } if !x.config.GetEventsEnable() { return } @@ -222,6 +234,13 @@ func (ex *eventsExport) flush(reason string) { // — varint(size) || Envelope bytes), the record path's own envelope form. func (ex *eventsExport) flushLocked(reason string) { defer ex.arm() + x := ex.x + // The flush counter fires on every trigger, an empty envelope included: + // the interval is EXM's "a lone event waits at most 1s" bound, and the + // count on the empty cadence is the proof the timer chain lives (the + // record path's own flushEnvelope counter tracks its triggers the same + // way). The rows counter is the data. + x.pC.WithLabelValues("eventsExport", "flush", reason).Inc() if len(ex.env.Row) == 0 { return } @@ -229,8 +248,6 @@ func (ex *eventsExport) flushLocked(reason string) { if err == nil { _, err = ex.f.Write(buf) } - x := ex.x - x.pC.WithLabelValues("eventsExport", "flush", reason).Inc() x.pC.WithLabelValues("eventsExport", "rows", "count").Add(float64(len(ex.env.Row))) if err != nil { x.pC.WithLabelValues("eventsExport", "flush", "error").Inc() diff --git a/pkg/xtcp/events_export_test.go b/pkg/xtcp/events_export_test.go index c2914d52e..563f5c474 100644 --- a/pkg/xtcp/events_export_test.go +++ b/pkg/xtcp/events_export_test.go @@ -20,6 +20,7 @@ import ( "github.com/randomizedcoder/xtcp2/gen/go/xtcp_config" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/randomizedcoder/xtcp2/gen/go/xtcp_netlink_events" "github.com/randomizedcoder/xtcp2/pkg/recordfmt" @@ -289,6 +290,43 @@ func TestEventsExportHandler(t *testing.T) { } } +// TestEventsExportIntervalFromConstruction pins the load-bearing fix the +// EXD-T03 gate caught (the interface-naming run that exported nothing on a +// quiet boot): the interval chain is armed at CONSTRUCTION, not at the +// first flush — flushLocked arms the next timer, so an exporter whose +// namespaces produce no events would otherwise never arm one, and the 1s +// bound would be dead from the start. The observable: the flush counter +// ticks on the empty cadence, with no events at all. +func TestEventsExportIntervalFromConstruction(t *testing.T) { + f := filepath.Join(t.TempDir(), "events.bin") + x := &XTCP{ + pC: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "test"}, []string{"function", "variable", "type"}), + config: &xtcp_config.XtcpConfig{ + EventsEnable: true, + EventsDest: "file:" + f, + EventsFlushIntervalMs: 50, + }, + } + ex, err := newEventsExport(x) + if err != nil { + t.Fatalf("newEventsExport: %v", err) + } + defer func() { _ = ex.f.Close() }() + // No events, no caps: with the timer never armed this exporter would + // stay silent forever. The construction arm must have the cadence + // running within a few intervals. + deadline := time.Now().Add(2 * time.Second) + for { + if testutil.ToFloat64(x.pC.WithLabelValues("eventsExport", "flush", "interval")) >= 2 { + return + } + if time.Now().After(deadline) { + t.Fatalf("the interval never fired without a first flush: 0 intervals after 2s") + } + time.Sleep(20 * time.Millisecond) + } +} + func TestEventsNetnsLabel(t *testing.T) { for _, row := range []struct { description string diff --git a/tools/events-probe/main.go b/tools/events-probe/main.go new file mode 100644 index 000000000..42ea18f9a --- /dev/null +++ b/tools/events-probe/main.go @@ -0,0 +1,143 @@ +// Command events-probe reads an events-export destination file — the +// varint-framed Envelope messages the daemon's -eventsEnable producer +// flushes (the ProtobufList wire, pkg/recordfmt's delimited pair) — and +// prints one line per row, for the microVM self-test's EVENTS_EXPORT check: +// +// EVENTS_EVENT link ifindex=N ifname=X netns=S +// EVENTS_EVENT addr ifindex=N addr=A/P netns=S +// EVENTS_EVENT route table=T dst=A/L oif=N netns=S +// EVENTS_EVENT neigh ifindex=N dst=A netns=S +// EVENTS_EVENT rule table=T prio=P netns=S +// EVENTS_EOF envelopes=N rows=N +// +// A torn tail frame (the daemon mid-Write when this read a snapshot of the +// file) prints EVENTS_TRUNC instead of failing: the check polls, so a later +// read sees the complete frame. Any other decode error fails the run. +package main + +import ( + "flag" + "fmt" + "io" + "net/netip" + "os" + + "golang.org/x/sys/unix" + + "github.com/randomizedcoder/xtcp2/gen/go/xtcp_netlink_events" + "github.com/randomizedcoder/xtcp2/pkg/recordfmt" +) + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +func run(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("events-probe", flag.ContinueOnError) + fs.SetOutput(stderr) + file := fs.String("file", "", "the events destination file the daemon's -eventsEnable producer flushes") + if err := fs.Parse(args); err != nil || *file == "" { + if err == nil { + err = fmt.Errorf("-file is required") + } + fmt.Fprintf(stderr, "events-probe: %v\n", err) + return 1 + } + bs, err := os.ReadFile(*file) + if err != nil { + fmt.Fprintf(stderr, "events-probe: %v\n", err) + return 1 + } + envelopes, rows := 0, 0 + for len(bs) > 0 { + msg, rest, err := recordfmt.NextDelimited(bs) + if err != nil { + // Only a torn tail frame is tolerated: a short prefix (the + // varint present, the body cut mid-Write) with nothing after it. + fmt.Fprintf(stdout, "EVENTS_TRUNC envelopes=%d rows=%d\n", envelopes, rows) + return 0 + } + e := &xtcp_netlink_events.Envelope{} + if err := e.UnmarshalVT(msg); err != nil { + fmt.Fprintf(stderr, "events-probe: envelope %d: %v\n", envelopes, err) + return 1 + } + envelopes++ + for _, r := range e.Row { + fmt.Fprintln(stdout, "EVENTS_EVENT "+eventString(r)) + rows++ + } + bs = rest + } + fmt.Fprintf(stdout, "EVENTS_EOF envelopes=%d rows=%d\n", envelopes, rows) + return 0 +} + +// eventString renders one row the rtnlmon-probe way (tools/rtnlmon-probe's +// own print grammar, plus the netns label the export stamps per row), so +// the check's greps read the same shape in both probes. +func eventString(r *xtcp_netlink_events.NetlinkEvent) string { + netns := " netns=" + r.GetNetns() + switch p := r.GetPayload().(type) { + case *xtcp_netlink_events.NetlinkEvent_Link: + l := p.Link + state := "down" + if l.GetIfiFlags()&unix.IFF_UP != 0 { + state = "up" + } + return fmt.Sprintf("link %s ifindex=%d ifname=%s %s%s", + actionString(r.GetAction()), l.GetIfiIndex(), l.GetIflaIfname(), state, netns) + case *xtcp_netlink_events.NetlinkEvent_Addr: + a := p.Addr + raw := a.GetIfaLocal() + if len(raw) == 0 { + raw = a.GetIfaAddress() + } + return fmt.Sprintf("addr %s ifindex=%d addr=%s%s", + actionString(r.GetAction()), a.GetIfaIndex(), addrString(raw, a.GetIfaFamily(), a.GetIfaPrefixlen()), netns) + case *xtcp_netlink_events.NetlinkEvent_Route: + ro := p.Route + return fmt.Sprintf("route %s table=%d dst=%s/%d oif=%d%s", + actionString(r.GetAction()), ro.GetRtmTable(), + ipString(ro.GetRtaDst(), ro.GetRtmFamily()), ro.GetRtmDstLen(), ro.GetRtaOif(), netns) + case *xtcp_netlink_events.NetlinkEvent_Neigh: + n := p.Neigh + return fmt.Sprintf("neigh %s ifindex=%d dst=%s%s", + actionString(r.GetAction()), n.GetNdmIfindex(), ipString(n.GetNdaDst(), n.GetNdmFamily()), netns) + case *xtcp_netlink_events.NetlinkEvent_Rule: + ru := p.Rule + return fmt.Sprintf("rule %s table=%d prio=%d%s", + actionString(r.GetAction()), ru.GetTable(), ru.GetFraPriority(), netns) + default: + return fmt.Sprintf("unknown %T%s", r.GetPayload(), netns) + } +} + +func actionString(a xtcp_netlink_events.NetlinkEvent_EventAction) string { + if a == xtcp_netlink_events.NetlinkEvent_EVENT_ACTION_DEL { + return "del" + } + return "add" +} + +// addrString is IFA_LOCAL when present, as `ip` prints it, else IFA_ADDRESS +// — rtnlmon-probe's own rule. +func addrString(raw []byte, family uint32, prefixlen uint32) string { + return fmt.Sprintf("%s/%d", ipString(raw, family), prefixlen) +} + +// ipString prints raw as an address; an absent destination (a default +// route) is the family's zero address. The family field is the proto's +// uint32 (the kernel's __u8 widened). +func ipString(raw []byte, family uint32) string { + if len(raw) == 0 { + if family == unix.AF_INET6 { + return "::" + } + return "0.0.0.0" + } + if ip, ok := netip.AddrFromSlice(raw); ok { + return ip.String() + } + return fmt.Sprintf("%x", raw) +}