Add self-throttling schedule and request throughput to emergency-storeall.sh

Check interval now adapts to the last observed condition instead of a
fixed cron cadence: every 30 min while normal, every 10 once elevated
or critical, so cron only needs one entry at the fastest interval this
ever needs. Also bundles recent request count/rate/avg duration from
Tomcat's stdout log into the same check and MaintenanceLog entry, to
give the heap numbers traffic context rather than running as a
separate job.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tj4SF2BGFxgoRYrCAzNpDb
This commit is contained in:
Claude 2026-09-30 16:17:08 +00:00
parent be650ea16c
commit aef964fc4d
No known key found for this signature in database

View file

@ -2,24 +2,29 @@
# #
# emergency-storeall.sh # emergency-storeall.sh
# #
# JVM heap-pressure watcher. Meant to be run frequently (e.g. every 10-15 # JVM heap-pressure watcher. Self-throttling: cron calls this every
# minutes) on its own cron schedule, independent of and much more often # CHECK_INTERVAL_ELEVATED_MIN minutes (the fastest cadence it ever needs),
# than nightly-storeall.sh. # and the script itself decides whether a check is actually due yet based
# on the condition it saw last time - full checks (which shell out to
# sudo jstat and tail the Tomcat log) only happen every
# CHECK_INTERVAL_NORMAL_MIN minutes while things look normal, stepping up
# to every CHECK_INTERVAL_ELEVATED_MIN minutes once condition is elevated
# or critical. That keeps the steady-state cost low without needing two
# separate cron entries or an internal sleep loop - cron still provides
# all the actual timing, same as nightly-storeall.sh.
# #
# Cron-driven, same shape as nightly-storeall.sh: a single check-and-log # crontab: */10 * * * * /path/to/emergency-storeall.sh
# per invocation, no internal sleep/loop - cron provides the cadence, and
# a missed or killed run just gets picked up again at the next tick.
# #
# IMPORTANT: this script currently only WATCHES and LOGS heap pressure - # IMPORTANT: this script only WATCHES and LOGS heap pressure - it does NOT
# it does NOT force storeall. That decision is still made manually for # force storeall. That decision is still made manually for now (see the
# now (see the "GC death-spiral vs. a normal single Full GC" discussion # "GC death-spiral vs. a normal single Full GC" discussion this was
# this was parked on - a real historical example of a run bad enough to # parked on - a real historical example of a run bad enough to justify
# justify forcing it has never actually been found yet). Every run writes # forcing it has never actually been found yet). Every check that actually
# a MaintenanceLog entry with the current heap/GC numbers regardless of # runs writes a MaintenanceLog entry with the current heap/GC/throughput
# condition, so this quietly builds exactly the historical dataset that # numbers regardless of condition, so this quietly builds exactly the
# was missing last time - once there's real incident data to calibrate # historical dataset that was missing last time - once there's real
# against, the forcing logic can be added on top of this without changing # incident data to calibrate against, forcing logic can be added on top
# anything about how the numbers are gathered. # of this without changing how the numbers are gathered.
# #
# Condition label is deliberately based on old-gen occupancy ALONE - the # Condition label is deliberately based on old-gen occupancy ALONE - the
# one signal already validated against real production GC logs (see # one signal already validated against real production GC logs (see
@ -35,10 +40,24 @@
# elevated old-gen at/above HEAP_ELEVATED_THRESHOLD_PCT, below CRITICAL # elevated old-gen at/above HEAP_ELEVATED_THRESHOLD_PCT, below CRITICAL
# critical old-gen at/above HEAP_CRITICAL_THRESHOLD_PCT # critical old-gen at/above HEAP_CRITICAL_THRESHOLD_PCT
# #
# Exits 0 on every completed check, whatever the condition - this script # Request throughput/timing (recent request count, rate, average duration
# only observes. Exits 1 only if the heap check itself couldn't be # from Tomcat's stdout log) is bundled into the same check and the same
# performed (jstat missing, pid not found, etc.), so a broken monitor is # MaintenanceLog entry rather than a separate job. The reason it's here
# still visible to cron/whatever watches this script's exit code. # and not standalone: the whole point of adding it is to give the heap
# numbers context - "old-gen is climbing, but is that because of a
# traffic spike, or is it climbing with nothing happening?" - and that
# only works if both numbers come from the same moment and land in the
# same log row. It also means throughput sampling naturally follows the
# same self-throttling cadence as the heap check. If a continuous traffic
# history independent of heap condition ever turns out to be useful too
# (e.g. for capacity planning rather than heap diagnosis), that would be
# a better fit as its own separate job on its own fixed schedule.
#
# Exits 0 whenever a check is skipped (not due yet) or completes,
# whatever the condition - this script only observes. Exits 1 only if a
# check that WAS due couldn't actually be performed (jstat missing, pid
# not found, etc.), so a broken monitor is still visible to cron/whatever
# watches this script's exit code.
set -u set -u
cd "$(dirname "$0")" cd "$(dirname "$0")"
@ -55,6 +74,23 @@ cd "$(dirname "$0")"
HEAP_ELEVATED_THRESHOLD_PCT="${HEAP_ELEVATED_THRESHOLD_PCT:-75}" HEAP_ELEVATED_THRESHOLD_PCT="${HEAP_ELEVATED_THRESHOLD_PCT:-75}"
HEAP_CRITICAL_THRESHOLD_PCT="${HEAP_CRITICAL_THRESHOLD_PCT:-85}" HEAP_CRITICAL_THRESHOLD_PCT="${HEAP_CRITICAL_THRESHOLD_PCT:-85}"
# How often a full check actually runs, in minutes. "Elevated" applies to
# both the elevated and critical conditions - critical doesn't get an
# even shorter interval of its own, since cron itself isn't calling this
# script more often than CHECK_INTERVAL_ELEVATED_MIN in the first place.
# Lower both cron's own interval and this value together if critical
# should be watched even more tightly than elevated.
CHECK_INTERVAL_NORMAL_MIN="${CHECK_INTERVAL_NORMAL_MIN:-30}"
CHECK_INTERVAL_ELEVATED_MIN="${CHECK_INTERVAL_ELEVATED_MIN:-10}"
# TODO: same placeholder as nightly-storeall.sh - fill in the real path
# once you've found supervisord's stdout_logfile setting for the tomcat
# program. Needed here for the throughput measurement, not the heap
# check itself.
TOMCAT_LOG="${TOMCAT_LOG:-/path/to/tomcat/stdout.log}"
TAIL_LINES="${TAIL_LINES:-20000}" # see nightly-storeall.sh's note on peak traffic volume
THROUGHPUT_WINDOW_MIN="${THROUGHPUT_WINDOW_MIN:-10}" # matches nightly-storeall.sh's validated CHECK_WINDOW_MIN
STATE_DIR="${STATE_DIR:-$(dirname "$0")/state}" STATE_DIR="${STATE_DIR:-$(dirname "$0")/state}"
STATE_FILE="$STATE_DIR/emergency-storeall.state" STATE_FILE="$STATE_DIR/emergency-storeall.state"
mkdir -p "$STATE_DIR" mkdir -p "$STATE_DIR"
@ -121,6 +157,107 @@ read_heap_stats() {
echo "$o $fgc $fgct $ygc $ygct" echo "$o $fgc $fgct $ygc $ygct"
} }
# Prints two space-separated numbers: how many Tomcat request-completion
# lines appeared in the trailing THROUGHPUT_WINDOW_MIN minutes, and the
# sum of their durations in ms (caller derives rate and average). Prints
# "0 0" (and logs why) if TOMCAT_LOG can't be read or nothing matches.
#
# Deliberately matches ANY handler's completion line (unlike
# nightly-storeall.sh's is_busy(), which only matches the six handlers
# that indicate real production/streaming work) - this is a general
# traffic/timing measure, not a busy/quiet signal, so it should reflect
# total load including routine polling traffic.
#
# Performance note: resolves each distinct minute (day+month+HH:MM) seen
# in the matched lines to an epoch ONCE via date(1), rather than once per
# line - a 10-30 minute window has at most a few dozen distinct minutes,
# versus potentially thousands of log lines at peak traffic, and date(1)
# is the expensive part. Duration is parsed with sub()/awk string
# manipulation rather than a 3-arg awk match() - see
# nightly-storeall.sh's last_storeall_object_count() for why (mawk/
# busybox awk don't support the gawk-only 3-arg form).
#
# Precision note: because minutes are resolved without seconds, a line
# within ~59s of the window edge can fall on the wrong side of it -
# confirmed against a synthetic log during testing. Harmless for a
# rate/average over a 10+ minute window; worth knowing if you ever reuse
# this for something that needs second-level precision.
request_stats() {
if [ ! -r "$TOMCAT_LOG" ]; then
log "cannot read TOMCAT_LOG (${TOMCAT_LOG}) - skipping throughput measurement"
echo "0 0"
return 1
fi
local matches
matches=$(tail -n "$TAIL_LINES" "$TOMCAT_LOG" \
| grep -oE "[0-9]+ [a-z]+ [0-9]{2}:[0-9]{2}:[0-9]{2} <-> [A-Za-z0-9_]+\.[A-Za-z0-9_]+ \([0-9]+ms\)")
if [ -z "$matches" ]; then
echo "0 0"
return 0
fi
local now cutoff minute_map
now=$(date +%s)
cutoff=$(( now - THROUGHPUT_WINDOW_MIN * 60 ))
minute_map=$(awk '{print $1, $2, substr($3,1,5)}' <<< "$matches" | sort -u | \
while read -r day mon hhmm; do
epoch=$(date -d "$day $mon $(date +%Y) $hhmm" +%s 2>/dev/null)
[ -n "$epoch" ] && echo "${day}|${mon}|${hhmm}|${epoch}"
done)
awk -v cutoff="$cutoff" -v minute_map="$minute_map" '
BEGIN {
n = split(minute_map, lines, "\n")
for (i = 1; i <= n; i++) {
split(lines[i], f, "|")
epoch_of[f[1] "|" f[2] "|" f[3]] = f[4]
}
}
{
key = $1 "|" $2 "|" substr($3,1,5)
e = epoch_of[key]
if (e != "" && e >= cutoff) {
count++
s = $0
sub(/^.*\(/, "", s)
sub(/ms\).*$/, "", s)
dur_sum += (s + 0)
}
}
END { print count+0, dur_sum+0 }
' <<< "$matches"
}
# ---- self-throttling: is a full check actually due? ----
now_epoch=$(date +%s)
# Defaults used when there's no previous state (first run, or state dir
# reset) - always run the first check rather than guessing an interval.
LAST_CHECK_EPOCH=""
LAST_CONDITION="normal"
if [ -f "$STATE_FILE" ]; then
. "$STATE_FILE"
fi
LAST_CHECK_EPOCH="${LAST_CHECK_EPOCH:-}"
LAST_CONDITION="${LAST_CONDITION:-normal}"
FGC_COUNT="${FGC_COUNT:-0}"
FGC_TIME_S="${FGC_TIME_S:-0}"
required_interval_min=$CHECK_INTERVAL_NORMAL_MIN
[ "$LAST_CONDITION" != "normal" ] && required_interval_min=$CHECK_INTERVAL_ELEVATED_MIN
if [ -n "$LAST_CHECK_EPOCH" ]; then
elapsed_min=$(( (now_epoch - LAST_CHECK_EPOCH) / 60 ))
if [ "$elapsed_min" -lt "$required_interval_min" ]; then
log "next check not due for $(( required_interval_min - elapsed_min ))m (last condition: ${LAST_CONDITION}, interval ${required_interval_min}m) - skipping"
exit 0
fi
fi
# ---- main ---- # ---- main ----
stats=$(read_heap_stats) || exit 1 stats=$(read_heap_stats) || exit 1
@ -130,25 +267,13 @@ read -r old_gen_pct fgc_count fgc_time_s ygc_count ygc_time_s <<< "$stats"
# (see the condition-label note above for why these don't drive the label # (see the condition-label note above for why these don't drive the label
# itself yet), but this is the shape a future frequency-based signal would # itself yet), but this is the shape a future frequency-based signal would
# need, so it's captured now rather than only the point-in-time totals. # need, so it's captured now rather than only the point-in-time totals.
have_prev=false if [ -n "$LAST_CHECK_EPOCH" ]; then
prev_fgc_count=0 new_fgc_count=$(( fgc_count - FGC_COUNT ))
prev_fgc_time_s=0
if [ -f "$STATE_FILE" ]; then
have_prev=true
read -r prev_fgc_count prev_fgc_time_s < "$STATE_FILE"
fi
prev_fgc_count="${prev_fgc_count:-0}"
prev_fgc_time_s="${prev_fgc_time_s:-0}"
echo "$fgc_count $fgc_time_s" > "$STATE_FILE"
if [ "$have_prev" = true ]; then
new_fgc_count=$(( fgc_count - prev_fgc_count ))
# Negative means Tomcat restarted (counters reset) since the last check, # Negative means Tomcat restarted (counters reset) since the last check,
# not that GCs somehow went backwards - treat as "no new data" rather # not that GCs somehow went backwards - treat as "no new data" rather
# than a nonsense negative number. # than a nonsense negative number.
[ "$new_fgc_count" -lt 0 ] && new_fgc_count=0 [ "$new_fgc_count" -lt 0 ] && new_fgc_count=0
new_fgc_time_s=$(awk -v a="$fgc_time_s" -v b="$prev_fgc_time_s" \ new_fgc_time_s=$(awk -v a="$fgc_time_s" -v b="$FGC_TIME_S" \
'BEGIN { d = a - b; if (d < 0) d = 0; printf "%.3f", d }') 'BEGIN { d = a - b; if (d < 0) d = 0; printf "%.3f", d }')
else else
new_fgc_count=0 new_fgc_count=0
@ -156,6 +281,11 @@ else
log "no previous reading found (first run, or state file missing/reset) - since-last-check numbers start from this run" log "no previous reading found (first run, or state file missing/reset) - since-last-check numbers start from this run"
fi fi
read -r req_count req_dur_sum <<< "$(request_stats)"
req_rate=$(awk -v c="$req_count" -v w="$THROUGHPUT_WINDOW_MIN" 'BEGIN { printf "%.1f", c / w }')
req_avg_dur=0
[ "$req_count" -gt 0 ] && req_avg_dur=$(( req_dur_sum / req_count ))
# ---- condition ---- # ---- condition ----
if [ "$old_gen_pct" -ge "$HEAP_CRITICAL_THRESHOLD_PCT" ]; then if [ "$old_gen_pct" -ge "$HEAP_CRITICAL_THRESHOLD_PCT" ]; then
@ -169,7 +299,7 @@ else
severity="info" severity="info"
fi fi
log "old-gen ${old_gen_pct}% - condition: ${condition} (+${new_fgc_count} full GC(s) since last check, +${new_fgc_time_s}s; ${fgc_count} full GC(s) total, ${fgc_time_s}s total)" log "old-gen ${old_gen_pct}% - condition: ${condition} (+${new_fgc_count} full GC(s) since last check, +${new_fgc_time_s}s; ${fgc_count} full GC(s) total, ${fgc_time_s}s total); throughput: ${req_count} requests / ${req_rate} per min, avg ${req_avg_dur}ms over last ${THROUGHPUT_WINDOW_MIN}m"
maintenance_log "$severity" emergency_storeall nop "$condition" \ maintenance_log "$severity" emergency_storeall nop "$condition" \
"Heap check: old-gen ${old_gen_pct}%, condition ${condition}." \ "Heap check: old-gen ${old_gen_pct}%, condition ${condition}." \
@ -179,6 +309,17 @@ maintenance_log "$severity" emergency_storeall nop "$condition" \
<fullGcCountTotal>${fgc_count}</fullGcCountTotal> <fullGcCountTotal>${fgc_count}</fullGcCountTotal>
<fullGcTimeTotalSec>${fgc_time_s}</fullGcTimeTotalSec> <fullGcTimeTotalSec>${fgc_time_s}</fullGcTimeTotalSec>
<youngGcCountTotal>${ygc_count}</youngGcCountTotal> <youngGcCountTotal>${ygc_count}</youngGcCountTotal>
<youngGcTimeTotalSec>${ygc_time_s}</youngGcTimeTotalSec>" <youngGcTimeTotalSec>${ygc_time_s}</youngGcTimeTotalSec>
<throughputWindowMin>${THROUGHPUT_WINDOW_MIN}</throughputWindowMin>
<recentRequestCount>${req_count}</recentRequestCount>
<recentRequestRatePerMin>${req_rate}</recentRequestRatePerMin>
<recentAvgDurationMs>${req_avg_dur}</recentAvgDurationMs>"
cat > "$STATE_FILE" <<EOF
FGC_COUNT=$fgc_count
FGC_TIME_S=$fgc_time_s
LAST_CHECK_EPOCH=$now_epoch
LAST_CONDITION=$condition
EOF
exit 0 exit 0