#!/bin/sh # hubble-flow-collector — long-lived, filtered, bounded capture of Hubble flows. # # Why a long-lived consumer: the Cilium agent's Hubble ring buffer holds ~4096 # events per type. At the measured ~150 flows/s that is ~28 s of history, so any # polling design (cron + `hubble observe --last N`) loses almost everything # between runs. This process stays attached to the flow API instead. # # What is written (see filter.awk): drop / policy-verdict / l7 events, plus # trace events whose peer is outside the cluster CIDRs (to-world = the # beacon/exfil signal). Intra-cluster trace ACK chatter is discarded. # # Bounds (hard, enforced here and not by a follow-up card): # * the file being appended right now is plain `flows--.jsonl`, so a # reader always has exactly one file to tail; # * on rotation the just-closed file is gzip'd to `flows--.jsonl.gz` # (temp name + atomic rename, so a reader never sees a half-written archive); # * <= MAX_FILES *plain* flows-*.jsonl (live file + any leftover from a restart); # * <= MAX_TOTAL_BYTES for the WHOLE directory, archives and in-flight .tmp # included; oldest deleted first. # Measured 2026-11-27 on siriussec: 3.1-4.3 MB/min (4.5-6.2 GB/day) of JSONL # compression at 18.5x (level 9, whole closed files), so the 960 MiB byte bound # holds 72-100 h of flows (72.6 h at the 6.2 GB/day CI-burst rate, 92-100 h at # the sustained rate). The byte bound is the binding one: MAX_FILES must NOT be # applied to the archives, or retention collapses back to a few hours. # # Only /data (hostPath /var/log/netsec) is ever written. Logs go to stdout so # they land in the container log, never on the node's disk. set -u DATA_DIR="${DATA_DIR:-/data}" SOCK="${SOCK:-/var/run/cilium/hubble.sock}" FILTER_AWK="${FILTER_AWK:-/scripts/filter.awk}" MAX_FILE_BYTES="${MAX_FILE_BYTES:-157286400}" # 150 MiB MAX_FILES="${MAX_FILES:-6}" # plain .jsonl only MAX_TOTAL_BYTES="${MAX_TOTAL_BYTES:-1006632960}" # 960 MiB (spec cap is 1 GiB) GZIP_LEVEL="${GZIP_LEVEL:-9}" # 18.5x on live data (17.9x at 6); ~1 s per 150 MiB, off the read path # Never compress a file appended to this recently: a restart must not gzip a # file another writer still owns. COMPRESS_MIN_AGE="${COMPRESS_MIN_AGE:-60}" RETRY_SECONDS="${RETRY_SECONDS:-5}" CHECK_EVERY_LINES="${CHECK_EVERY_LINES:-200}" log() { printf '%s collector: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*"; } mkdir -p "$DATA_DIR" || { log "cannot create $DATA_DIR"; exit 1; } fsize() { stat -c %s "$1" 2>/dev/null || echo 0; } mtime() { stat -c %Y "$1" 2>/dev/null || date -u +%s; } # Is $1 the file the writer is appending to right now? `cur` is unset outside # the write loop (the startup sweep runs before it is assigned). is_current() { [ -n "${cur:-}" ] && [ "$1" = "$cur" ]; } # Is a gzip for $1 currently running? The temp file is created *before* the # compressor forks, so a prune that runs immediately after compress() sees it # and leaves that file alone — deleting it mid-gzip would discard the archive # and lose the whole file's flows. in_flight() { for t in "$1".gz.tmp*; do [ -e "$t" ] && return 0 done return 1 } # Compress one closed .jsonl in the BACKGROUND so the flow reader is never # blocked (blocking it would stall `hubble observe` and make the agent drop # events for this client). Order: gzip to a temp name, rename into place, then # drop the plain file. A reader that globs *.jsonl therefore sees either the # whole plain file or no plain file at all — never a partial .gz. compress() { f=$1 force=${2:-0} # 1 = we just closed it ourselves; skip the age guard is_current "$f" && return 0 [ -e "$f" ] || return 0 [ -e "$f.gz" ] && return 0 in_flight "$f" && return 0 if [ "$force" -eq 0 ]; then age=$(( $(date -u +%s) - $(mtime "$f") )) [ "$age" -ge "$COMPRESS_MIN_AGE" ] || return 0 fi if [ ! -s "$f" ]; then rm -f "$f" # closed with nothing in it: nothing to keep log "removed empty $f" return 0 fi tmp="$f.gz.tmp.$$" : > "$tmp" 2>/dev/null || return 0 # marker: prune must not reap $f now ( if gzip -"$GZIP_LEVEL" -c "$f" > "$tmp" 2>/dev/null && [ -s "$tmp" ]; then # Preserve the source mtime so the pruner still sees true chronology. touch -r "$f" "$tmp" 2>/dev/null if [ -e "$f" ] && mv -f "$tmp" "$f.gz"; then rm -f "$f" log "compressed $(basename "$f") -> $(basename "$f.gz") $(fsize "$f.gz")B" else rm -f "$tmp" # pruner took the plain file meanwhile fi else rm -f "$tmp" log "compress failed (left plain): $f" fi ) & } # Delete oldest files until the directory is inside both bounds. # `ls -1t` is newest-first, so walking it and deleting from the first overflow # onward removes the oldest data first. Filenames are generated by this script # and contain no spaces, so plain word splitting is safe. (Do not `set -f` here: # GNU ls does not glob the pattern itself, so noglob would make this match # nothing.) prune() { files=$(ls -1t "$DATA_DIR"/flows-* 2>/dev/null) [ -n "$files" ] || return 0 total=0 under=1 for f in $files; do case "$f" in *.gz.tmp*) # compression in flight: counts toward the cap, never deleted total=$((total + $(fsize "$f"))) continue ;; esac sz=$(fsize "$f") total=$((total + sz)) is_current "$f" && continue in_flight "$f" && continue # gzip running: this file is about to shrink case "$f" in *.jsonl|*.jsonl.gz) ;; *) continue ;; # unknown junk: counted, left alone esac if [ "$under" -eq 0 ] || [ "$total" -gt "$MAX_TOTAL_BYTES" ]; then under=0 rm -f "$f" && total=$((total - sz)) && log "pruned $f (dir over ${MAX_TOTAL_BYTES}B)" fi done # Plain-file bound, independent of the byte bound (the live file counts). n=0 for f in $(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null); do n=$((n + 1)) [ "$n" -le "$MAX_FILES" ] && continue is_current "$f" && continue in_flight "$f" && continue rm -f "$f" && log "pruned plain $f (over MAX_FILES=$MAX_FILES)" done return 0 } # A compressor killed mid-flight (pod stop) leaves flows-*.gz.tmp* behind. for t in "$DATA_DIR"/flows-*.gz.tmp*; do [ -e "$t" ] || continue rm -f "$t" && log "removed stale temp $t" done prune # Anything plain left by a previous writer is archived on startup, so a restart # does not leave uncompressed history lying ahead of the byte bound. for f in $(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null); do compress "$f" done log "starting: dir=$DATA_DIR sock=$SOCK max_file=${MAX_FILE_BYTES}B max_files=$MAX_FILES max_total=${MAX_TOTAL_BYTES}B gzip=-$GZIP_LEVEL" attempt=0 while :; do attempt=$((attempt + 1)) stamp=$(date -u +%Y%m%dT%H%M%SZ) seq=$attempt cur="$DATA_DIR/flows-$stamp-$seq.jsonl" log "attach attempt=$attempt file=$cur" # --type is repeatable; filtering server-side keeps the 148/s trace bulk # (all subtypes) off the wire. We only ask for trace:to-network, which is # the packet-level "left the node toward a peer" half of the to-world test. # stderr is left unredirected on purpose: it lands in the container log. hubble observe \ --server "unix://$SOCK" \ --follow \ --output json \ --type drop \ --type policy-verdict \ --type l7 \ --type trace:to-network \ | awk -f "$FILTER_AWK" \ | { lines=0 while IFS= read -r line; do # Only JSON flows reach the file; anything else is printed to the # container log instead of corrupting the JSONL. case "$line" in "{"*) ;; *) printf '%s\n' "$line"; continue ;; esac printf '%s\n' "$line" >> "$cur" lines=$((lines + 1)) if [ "$lines" -ge "$CHECK_EVERY_LINES" ]; then lines=0 size=$(fsize "$cur") if [ "$size" -ge "$MAX_FILE_BYTES" ]; then prev="$cur" seq=$((seq + 1)) cur="$DATA_DIR/flows-$(date -u +%Y%m%dT%H%M%SZ)-$seq.jsonl" log "rotated: $cur (closed $prev at $(fsize "$prev")B)" # Archive what we just closed (we own it, so no age guard), # then re-check the bounds. The sweep also archives any # orphan a previous writer left behind. compress "$prev" 1 for f in $(ls -1t "$DATA_DIR"/flows-*.jsonl 2>/dev/null); do compress "$f" done prune fi fi done log "stream ended ($cur)" } prune log "reattaching in ${RETRY_SECONDS}s" sleep "$RETRY_SECONDS" done