aien-architecture-mv
Canonical architecture for the AIEN ecosystem: flows, boundaries, ADRs, and the map from design to implementation repositories.
Brought by drakestapleton
aien-architecture-mv / tools / ops / disk-alarm
| 1 | #!/usr/bin/env bash |
| 2 | # disk-alarm: one loud ALARM line on ~/handoffs/BOARD.md, and a comment on the standing Linear issue, when the |
| 3 | # root filesystem is short of space or filling fast. Never deletes anything. Change-driven, not clock-driven: |
| 4 | # every landing on a ~/git store repository runs it (the store hook tools/ops/store-post-update, detached, after |
| 5 | # spark-cleanup --landed), aien-bays finish runs it each time a bay finishes, and any lander or gate runner may |
| 6 | # run it at start (`disk-alarm --quiet`). Nothing else runs it: while no landing, bay finish or manual run |
| 7 | # happens, the disk is not checked at all, so a quiet board is not proof that the disk is fine. |
| 8 | # |
| 9 | # Linear: the first ALARM, each further 25 GB fall, and the "cleared" line are also posted as a comment on |
| 10 | # DISK_ALARM_LINEAR_ISSUE (default DRA-521, "Free space on the Spark disk"), by one direct commentCreate call |
| 11 | # to Linear's API (`disk-alarm --linear-comment ISSUE TEXT`, below; the key comes from atlas-vault for that |
| 12 | # process only). A post counts only when Linear returns the new comment's id ($STATE/linear.log). A failed |
| 13 | # post is kept in $STATE/linear-pending, said once on the board as an ALARM, and sent again at the next check. |
| 14 | # Repeats held back on the board are not posted. DISK_ALARM_LINEAR_CMD replaces the route (tests): it is run |
| 15 | # as `CMD ISSUE TEXT` and must print the comment id; set it to `echo off` to turn the Linear route off. |
| 16 | # Process names and directories in the text are cut to a fixed character set and length. |
| 17 | # |
| 18 | # What it measures (the whole filesystem, never a list of directories): |
| 19 | # free = df free bytes of the filesystem holding DISK_ALARM_FS (default /) |
| 20 | # rate = fall of free between this check and the newest earlier check at least DISK_ALARM_WINDOW_S |
| 21 | # old (default 600 s; checks older than 3 h are dropped), in GB/h (GB = 10^9 bytes) |
| 22 | # consumers = which processes wrote the most since that earlier check, from every process's |
| 23 | # /proc/<pid>/io write_bytes (reaped children are counted in their parent), summed per real |
| 24 | # working directory (readlink of /proc/<pid>/cwd: symlinks resolved, any name), plus bytes held by |
| 25 | # deleted-but-open files. A writer is named wherever it runs; no path list can hide it. |
| 26 | # Alarm when free < DISK_ALARM_MIN_GB (default 300, the free-space target set for this disk on DRA-702, so the |
| 27 | # alarm comes well before the disk is full) or rate > DISK_ALARM_MAX_RATE_GBH (default 20). |
| 28 | # A repeat ALARM waits DISK_ALARM_REPEAT_S (default 1800 s) unless free fell another 25 GB; one |
| 29 | # "cleared" line is written when the condition ends. |
| 30 | # Cost when quiet: one df and one grep over /proc/*/io (well under a second). |
| 31 | # |
| 32 | # Test hooks: DISK_ALARM_DF (command that prints free bytes), DISK_ALARM_NOW (epoch), DISK_ALARM_PROC |
| 33 | # (a fake /proc tree with <pid>/io, <pid>/comm, <pid>/cwd), DISK_ALARM_BOARD, DISK_ALARM_STATE. |
| 34 | # Usage: disk-alarm [--quiet] exit 0 quiet, 3 alarm (written or held back), 2 cannot measure. |
| 35 | set -u |
| 36 | H=$HOME |
| 37 | FS=${DISK_ALARM_FS:-/} |
| 38 | MIN_GB=${DISK_ALARM_MIN_GB:-300} |
| 39 | MAX_RATE=${DISK_ALARM_MAX_RATE_GBH:-20} |
| 40 | WINDOW=${DISK_ALARM_WINDOW_S:-600} |
| 41 | REPEAT=${DISK_ALARM_REPEAT_S:-1800} |
| 42 | BOARD=${DISK_ALARM_BOARD:-$H/handoffs/BOARD.md} |
| 43 | STATE=${DISK_ALARM_STATE:-$H/.local/state/disk-alarm} |
| 44 | PROC=${DISK_ALARM_PROC:-/proc} |
| 45 | # other users' /proc/<pid>/io (root services, containers) is readable only through sudo; without it those |
| 46 | # writers are counted as unreadable, never as "wrote nothing" |
| 47 | SUDO=''; [ -z "${DISK_ALARM_PROC:-}" ] && sudo -n true 2>/dev/null && SUDO='sudo -n' |
| 48 | LINEAR_ISSUE=${DISK_ALARM_LINEAR_ISSUE:-DRA-521} |
| 49 | QUIET=0; [ "${1:-}" = --quiet ] && QUIET=1 |
| 50 | LINEAR_CMD=${DISK_ALARM_LINEAR_CMD:-$(readlink -f "$0") --linear-comment} |
| 51 | mkdir -p "$STATE/io" || exit 2 |
| 52 | |
| 53 | # --linear-comment ISSUE TEXT: the default Linear route. One commentCreate call; prints the new comment's id |
| 54 | # and exits 0, or says why on stderr and exits 1. The key is read from atlas-vault into this process only, |
| 55 | # never into argv or a file. Host binaries: curl (Omega has no TLS client yet), jq, atlas-vault. |
| 56 | if [ "${1:-}" = --linear-comment ]; then |
| 57 | [ $# = 3 ] || { echo "usage: disk-alarm --linear-comment ISSUE TEXT" >&2; exit 2; } |
| 58 | if [ -z "${LINEAR_API_KEY:-}" ]; then |
| 59 | [ -z "${DISK_ALARM_VAULTED:-}" ] || { echo "atlas-vault gave no LINEAR_API_KEY" >&2; exit 1; } |
| 60 | command -v atlas-vault >/dev/null || { echo "atlas-vault not found" >&2; exit 1; } |
| 61 | export DISK_ALARM_VAULTED=1 |
| 62 | exec atlas-vault run LINEAR_API_KEY -- "$(readlink -f "$0")" "$@" |
| 63 | fi |
| 64 | out=$(jq -nc --arg i "$2" --arg b "$3" \ |
| 65 | '{query:"mutation($i:String!,$b:String!){commentCreate(input:{issueId:$i,body:$b}){success comment{id}}}",variables:{i:$i,b:$b}}' | |
| 66 | curl -q -sS --noproxy '*' --max-time 60 -H 'Content-Type: application/json' \ |
| 67 | -H @<(printf 'Authorization: %s\n' "$LINEAR_API_KEY") --data-binary @- https://api.linear.app/graphql 2>&1) || |
| 68 | { echo "curl: $out" >&2; exit 1; } |
| 69 | id=$(jq -r 'if .data.commentCreate.success == true then .data.commentCreate.comment.id // empty else empty end' <<<"$out" 2>/dev/null) |
| 70 | [ -n "$id" ] || { echo "Linear refused: $(jq -c '.errors // .' <<<"$out" 2>/dev/null | cut -c1-300)" >&2; exit 1; } |
| 71 | echo "$id"; exit 0 |
| 72 | fi |
| 73 | exec 9>"$STATE/run.lock" |
| 74 | flock -n 9 || exit 0 # another check is running at this moment; its result stands |
| 75 | |
| 76 | now=${DISK_ALARM_NOW:-$(date +%s)} |
| 77 | if [ -n "${DISK_ALARM_DF:-}" ]; then free=$(eval "$DISK_ALARM_DF"); else free=$(df -B1 --output=avail "$FS" | tail -n 1 | tr -d ' '); fi |
| 78 | [[ "$free" =~ ^[0-9]+$ ]] || { echo "disk-alarm: cannot read free space (${free:-nothing})" >&2; exit 2; } |
| 79 | |
| 80 | # sample: free bytes, and every process's cumulative write_bytes (pid<TAB>bytes) |
| 81 | S="$STATE/samples.tsv"; touch "$S" |
| 82 | printf '%s\t%s\n' "$now" "$free" >> "$S" |
| 83 | $SUDO grep -sH '^write_bytes' "$PROC"/[0-9]*/io | sed -E "s#^$PROC/([0-9]+)/io:write_bytes:[[:space:]]*#\1\t#" > "$STATE/io/$now.tsv" |
| 84 | unread=$(( $(printf '%s\n' "$PROC"/[0-9]* | grep -c '/[0-9][0-9]*$') - $(wc -l < "$STATE/io/$now.tsv") )); [ "$unread" -lt 0 ] && unread=0 |
| 85 | # keep 3 hours of samples and their io snapshots |
| 86 | awk -F'\t' -v c=$((now - 10800)) '$1 >= c' "$S" > "$S.tmp" && mv "$S.tmp" "$S" |
| 87 | for f in "$STATE"/io/*.tsv; do t=${f##*/}; t=${t%.tsv}; [ "$t" -lt $((now - 10800)) ] && rm -f "$f"; done |
| 88 | |
| 89 | # rate against the newest earlier sample at least WINDOW old |
| 90 | read -r t0 f0 < <(awk -F'\t' -v c=$((now - WINDOW)) '$1 <= c {t=$1; f=$2} END{if (t) print t, f}' "$S") |
| 91 | rate='' |
| 92 | [ -n "${t0:-}" ] && [ "$now" -gt "$t0" ] && rate=$(awk -v a="$f0" -v b="$free" -v dt=$((now - t0)) 'BEGIN{printf "%.1f", (a-b)/1e9*3600/dt}') |
| 93 | gb=$(awk -v b="$free" 'BEGIN{printf "%.1f", b/1e9}') |
| 94 | |
| 95 | why='' |
| 96 | awk -v g="$gb" -v m="$MIN_GB" 'BEGIN{exit !(g < m)}' && why="free ${gb} GB < ${MIN_GB} GB" |
| 97 | if [ -n "$rate" ] && awk -v r="$rate" -v m="$MAX_RATE" 'BEGIN{exit !(r > m)}'; then |
| 98 | why="${why:+$why; }falling ${rate} GB/h > ${MAX_RATE} GB/h" |
| 99 | fi |
| 100 | |
| 101 | board_line() { ( flock -w 30 8 || exit 1; printf '%s\n' "$1" >> "$BOARD" ) 8>>"$BOARD.lock"; } |
| 102 | stamp() { date -u -d "@$1" +%FT%TZ; } |
| 103 | # Linear: a post counts only when the route prints the new comment's id. Success records it (alarm: time and |
| 104 | # free in last-linear; cleared: last-linear dropped) and drops any pending post. Failure keeps the post in |
| 105 | # linear-pending for the next check and says so once on the board. Never changes the exit status. |
| 106 | L="$STATE/last-linear"; P="$STATE/linear-pending" |
| 107 | linear_send() { # $1 alarm|cleared, $2 text |
| 108 | local id err |
| 109 | if id=$(timeout 180 $LINEAR_CMD "$LINEAR_ISSUE" "$2" 2>"$STATE/linear.err" </dev/null) && [[ "$id" =~ ^[A-Za-z0-9-]+$ ]]; then |
| 110 | printf '%s %s posted on %s, comment %s\n' "$(stamp "$now")" "$1" "$LINEAR_ISSUE" "$id" >> "$STATE/linear.log" |
| 111 | if [ "$1" = alarm ]; then printf '%s %s\n' "$now" "$free" > "$L"; else rm -f "$L"; fi |
| 112 | rm -f "$P"; return 0 |
| 113 | fi |
| 114 | err=$(tr '\n' ' ' < "$STATE/linear.err" | tr -c 'A-Za-z0-9 ._:/=()-' ' ' | head -c 200 | sed 's/ *$//') |
| 115 | printf '%s %s FAILED on %s: %s\n' "$(stamp "$now")" "$1" "$LINEAR_ISSUE" "${err:-no comment id}" >> "$STATE/linear.log" |
| 116 | [ -f "$P" ] || board_line "- $(stamp "$now") **ALARM disk-alarm**: the Linear comment on $LINEAR_ISSUE failed (${err:-no comment id}); kept in $P and sent again at the next check" |
| 117 | printf '%s\n%s\n' "$1" "$2" > "$P" |
| 118 | return 1 |
| 119 | } |
| 120 | # a post that failed at an earlier check goes first |
| 121 | if [ -f "$P" ]; then pk=$(head -n 1 "$P"); linear_send "$pk" "$(tail -n +2 "$P")"; fi |
| 122 | |
| 123 | A="$STATE/last-alarm" |
| 124 | if [ -z "$why" ]; then |
| 125 | if [ -f "$A" ]; then |
| 126 | line="- $(stamp "$now") disk-alarm: cleared, / free ${gb} GB, falling ${rate:-unmeasured} GB/h (thresholds ${MIN_GB} GB, ${MAX_RATE} GB/h)" |
| 127 | board_line "$line" |
| 128 | { [ -f "$L" ] || [ -f "$P" ]; } && linear_send cleared "${line#- }" |
| 129 | rm -f "$A" |
| 130 | fi |
| 131 | [ "$QUIET" = 1 ] || echo "disk-alarm: quiet, free ${gb} GB, falling ${rate:-unmeasured} GB/h" |
| 132 | exit 0 |
| 133 | fi |
| 134 | if [ -f "$A" ]; then |
| 135 | read -r lt lf < "$A" |
| 136 | if [ $((now - lt)) -lt "$REPEAT" ] && [ $((lf - free)) -lt 25000000000 ]; then |
| 137 | [ "$QUIET" = 1 ] || echo "disk-alarm: alarm held (posted $((now - lt)) s ago): $why" |
| 138 | exit 3 |
| 139 | fi |
| 140 | fi |
| 141 | |
| 142 | # consumers: write_bytes since the baseline snapshot, summed per real cwd |
| 143 | base="$STATE/io/${t0:-x}.tsv" |
| 144 | if [ ! -f "$base" ]; then # no snapshot at t0: the newest one older than this check |
| 145 | bt=$(for f in "$STATE"/io/*.tsv; do t=${f##*/}; echo "${t%.tsv}"; done | awk -v n="$now" '$1 ~ /^[0-9]+$/ && $1 < n' | sort -n | tail -n 1) |
| 146 | base="$STATE/io/$bt.tsv" |
| 147 | fi |
| 148 | top='' |
| 149 | if [ -n "$base" ] && [ -f "$base" ]; then |
| 150 | since=${base##*/}; since=${since%.tsv} |
| 151 | top=$(awk -F'\t' 'NR==FNR {a[$1]=$2; next} ($1 in a) && $2 > a[$1] {print $1 "\t" $2 - a[$1]}' "$base" "$STATE/io/$now.tsv" | |
| 152 | sort -t$'\t' -k2,2nr | head -n 200 | |
| 153 | while IFS=$'\t' read -r pid d; do |
| 154 | cwd=$($SUDO readlink -f "$PROC/$pid/cwd" 2>/dev/null | tr -d '\n' | tr -c 'A-Za-z0-9._/+-' '?' | cut -c1-160) |
| 155 | printf '%s\t%s\t%s\n' "${cwd:-exited}" "$d" "$(tr -d '\n' < "$PROC/$pid/comm" 2>/dev/null | tr -c 'A-Za-z0-9._+-' '?' | cut -c1-32)" |
| 156 | done | |
| 157 | awk -F'\t' '{s[$1]+=$2; if (!($1 in c) || $2 > m[$1]) {c[$1]=$3; m[$1]=$2}} END {for (k in s) printf "%d\t%s\t%s\n", s[k], k, c[k]}' | |
| 158 | sort -t$'\t' -k1,1nr | head -n 3 | |
| 159 | awk -F'\t' -v h="$H" '{p=$2; if (index(p, h "/") == 1) p="~" substr(p, length(h)+1); printf "%s%s +%.1f GB written (%s)", (NR>1 ? "; " : ""), p, $1/1e9, $3}') |
| 160 | [ "$unread" -gt 0 ] && top="${top:+$top; }$unread process(es) whose writes could not be read" |
| 161 | top="${top:-no readable process wrote} (since $(stamp "$since"))" |
| 162 | fi |
| 163 | # bytes held by deleted-but-open files (space df counts as used that no directory shows) |
| 164 | held=$(find "$PROC"/[0-9]*/fd -maxdepth 1 -type l -lname '*(deleted)' -printf '%p\n' 2>/dev/null | |
| 165 | while read -r f; do stat -Lc %s "$f" 2>/dev/null; done | awk '{s+=$1} END{printf "%.1f", s/1e9}') |
| 166 | |
| 167 | line="$(stamp "$now") ALARM disk: / free ${gb} GB, falling ${rate:-unmeasured} GB/h ($why). Top writers by real directory: ${top:-no baseline yet}. Deleted-but-open: ${held:-0} GB. Nothing deleted; see ~/.local/bin/disk-alarm; regenerable bay output: bay-clean; reviewed reclaim: spark-cleanup (dry run first)." |
| 168 | board_line "- ${line/ALARM disk:/**ALARM disk**}" |
| 169 | printf '%s %s\n' "$now" "$free" > "$A" |
| 170 | # Linear: the first alarm of an episode, then each further 25 GB fall |
| 171 | lf=''; [ -f "$L" ] && read -r _ lf < "$L" |
| 172 | [ -z "$lf" ] || [ $((lf - free)) -ge 25000000000 ] && linear_send alarm "$line" |
| 173 | [ "$QUIET" = 1 ] || echo "disk-alarm: ALARM written to $BOARD: $why" |
| 174 | exit 3 |