qs-stats: single writer, fix @STAT pipe race

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
rope 2026-07-28 20:47:39 +01:00
parent fb0a724d7e
commit a7976205a8

View file

@ -31,28 +31,33 @@
# one @STAT line per tick (hottest coretemp across both sockets, WAN # one @STAT line per tick (hottest coretemp across both sockets, WAN
# byte rates from eno1). Everything rides one SSH connection. # byte rates from eno1). Everything rides one SSH connection.
(pkgs.writeShellScriptBin "qs-stats" '' (pkgs.writeShellScriptBin "qs-stats" ''
# Single writer: the loop re-emits top's lines itself and injects a
# @STAT line at each frame header. top writing the pipe directly in
# parallel raced the injected lines (pipe writes aren't line-atomic)
# and spliced @STAT mid-frame, where the client parser never saw it.
C=${pkgs.coreutils}/bin C=${pkgs.coreutils}/bin
export LC_ALL=C export LC_ALL=C
${pkgs.procps}/bin/top -b -d 2 -w 512 &
trap 'kill $! 2>/dev/null' EXIT
prev_rx="" prev_rx=""
while :; do ${pkgs.procps}/bin/top -b -d 2 -w 512 | while IFS= read -r line; do
t=0 printf '%s\n' "$line"
for h in /sys/class/hwmon/*; do case $line in
if [ "$($C/cat "$h/name" 2>/dev/null)" = coretemp ]; then "top - "*)
for f in "$h"/temp*_input; do t=0
v=$($C/cat "$f" 2>/dev/null || echo 0) for h in /sys/class/hwmon/*; do
[ "$v" -gt "$t" ] && t=$v [ "$($C/cat "$h/name" 2>/dev/null)" = coretemp ] || continue
for f in "$h"/temp*_input; do
v=$($C/cat "$f" 2>/dev/null || echo 0)
[ "$v" -gt "$t" ] && t=$v
done
done done
fi read -r rx tx < <(${pkgs.gawk}/bin/awk '$1 == "eno1:" {print $2, $10}' /proc/net/dev)
done if [ -n "$prev_rx" ]; then
read -r rx tx < <(${pkgs.gawk}/bin/awk '$1 == "eno1:" {print $2, $10}' /proc/net/dev) printf '@STAT temp=%s rxbps=%s txbps=%s\n' "$((t / 1000))" "$(( (rx - prev_rx) / 2 ))" "$(( (tx - prev_tx) / 2 ))"
if [ -n "$prev_rx" ]; then fi
echo "@STAT temp=$((t / 1000)) rxbps=$(( (rx - prev_rx) / 2 )) txbps=$(( (tx - prev_tx) / 2 ))" prev_rx=$rx
fi prev_tx=$tx
prev_rx=$rx ;;
prev_tx=$tx esac
$C/sleep 2
done done
'') '')
]; ];