2026-09-30 11:46:00 +00:00
#!/bin/bash
#
# emergency-storeall.sh
#
2026-09-30 16:17:08 +00:00
# JVM heap-pressure watcher. Self-throttling: cron calls this every
# CHECK_INTERVAL_ELEVATED_MIN minutes (the fastest cadence it ever needs),
# 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.
2026-09-30 11:46:00 +00:00
#
2026-09-30 16:17:08 +00:00
# crontab: */10 * * * * /path/to/emergency-storeall.sh
2026-09-30 11:46:00 +00:00
#
2026-09-30 16:17:08 +00:00
# IMPORTANT: this script only WATCHES and LOGS heap pressure - it does NOT
# force storeall. That decision is still made manually for now (see the
# "GC death-spiral vs. a normal single Full GC" discussion this was
# parked on - a real historical example of a run bad enough to justify
# forcing it has never actually been found yet). Every check that actually
# runs writes a MaintenanceLog entry with the current heap/GC/throughput
# numbers regardless of condition, so this quietly builds exactly the
# historical dataset that was missing last time - once there's real
# incident data to calibrate against, forcing logic can be added on top
# of this without changing how the numbers are gathered.
2026-09-30 16:09:16 +00:00
#
# Condition label is deliberately based on old-gen occupancy ALONE - the
# one signal already validated against real production GC logs (see
# sportrum-ansible's group_vars/production.yml for the 14-event history
# behind the 3072MB heap sizing). Full GC count/time are surfaced in the
# log purely as data, not fed into the condition label: a single Full GC
# at high occupancy is normal operation, not a warning sign by itself,
# and there isn't yet a validated way to tell a normal Full GC apart from
# the start of a death spiral just from GC frequency alone. Once the
# older incident logs are recovered, that can change.
#
# normal old-gen below HEAP_ELEVATED_THRESHOLD_PCT
# elevated old-gen at/above HEAP_ELEVATED_THRESHOLD_PCT, below CRITICAL
# critical old-gen at/above HEAP_CRITICAL_THRESHOLD_PCT
#
2026-09-30 16:17:08 +00:00
# Request throughput/timing (recent request count, rate, average duration
# from Tomcat's stdout log) is bundled into the same check and the same
# MaintenanceLog entry rather than a separate job. The reason it's here
# 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.
2026-09-30 11:46:00 +00:00
set -u
cd " $( dirname " $0 " ) "
. ./upgrade-funs.sh
2026-09-30 16:09:16 +00:00
# ---- configuration - tune for your environment ----
# TODO: both still starting guesses, not yet validated against real
# jstat readings from production. HEAP_CRITICAL_THRESHOLD_PCT carries
# over the same 85% guess used before this script stopped forcing
# anything; HEAP_ELEVATED_THRESHOLD_PCT is new and even less validated -
# tune both once you've observed normal vs. tight old-gen occupancy on
# the actual server.
HEAP_ELEVATED_THRESHOLD_PCT = " ${ HEAP_ELEVATED_THRESHOLD_PCT :- 75 } "
HEAP_CRITICAL_THRESHOLD_PCT = " ${ HEAP_CRITICAL_THRESHOLD_PCT :- 85 } "
2026-09-30 16:17:08 +00:00
# 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
2026-09-30 16:09:16 +00:00
STATE_DIR = " ${ STATE_DIR :- $( dirname " $0 " ) /state } "
STATE_FILE = " $STATE_DIR /emergency-storeall.state "
mkdir -p " $STATE_DIR "
2026-09-30 11:46:00 +00:00
log( ) {
echo " $( date '+%Y-%m-%d %H:%M:%S' ) emergency-storeall: $* "
}
2026-09-30 16:09:16 +00:00
# Reads jstat -gcutil for the running Tomcat and prints five
# space-separated numbers: old-gen occupancy pct, full GC count (total
# since JVM start), full GC total time in seconds, young GC count, young
# GC total time in seconds. Prints nothing and returns 1 on any failure -
# every failure reason is logged so a silent/broken cron run is still
# diagnosable from its own log line.
#
# NOTE: same caveat as before this rewrite - untested against a real JVM
# in this session. Columns are located dynamically from jstat's own
# header rather than hardcoded by position, worth a dry run against
# production before trusting the numbers it produces.
read_heap_stats( ) {
local tomcat_pid out header data
local col_o col_fgc col_fgct col_ygc col_ygct
local o fgc fgct ygc ygct
2026-09-30 11:46:00 +00:00
tomcat_pid = $( sudo supervisorctl pid tomcat 2>/dev/null)
if [ -z " $tomcat_pid " ] ; then
log "could not resolve tomcat pid via supervisorctl, skipping heap check"
return 1
fi
2026-09-30 16:09:16 +00:00
2026-09-30 11:46:00 +00:00
out = $( sudo jstat -gcutil " $tomcat_pid " 2>/dev/null)
if [ -z " $out " ] ; then
log " jstat returned nothing for pid $tomcat_pid , skipping heap check "
return 1
fi
2026-09-30 16:09:16 +00:00
2026-09-30 11:46:00 +00:00
header = $( head -n 1 <<< " $out " )
data = $( tail -n 1 <<< " $out " )
2026-09-30 16:09:16 +00:00
col_o = $( awk '{for (i=1;i<=NF;i++) if ($i=="O") print i}' <<< " $header " )
col_fgc = $( awk '{for (i=1;i<=NF;i++) if ($i=="FGC") print i}' <<< " $header " )
col_fgct = $( awk '{for (i=1;i<=NF;i++) if ($i=="FGCT") print i}' <<< " $header " )
col_ygc = $( awk '{for (i=1;i<=NF;i++) if ($i=="YGC") print i}' <<< " $header " )
col_ygct = $( awk '{for (i=1;i<=NF;i++) if ($i=="YGCT") print i}' <<< " $header " )
if [ -z " $col_o " ] || [ -z " $col_fgc " ] || [ -z " $col_fgct " ] \
|| [ -z " $col_ygc " ] || [ -z " $col_ygct " ]
then
log "could not find all expected columns (O/FGC/FGCT/YGC/YGCT) in jstat output"
2026-09-30 11:46:00 +00:00
return 1
fi
2026-09-30 16:09:16 +00:00
o = $( awk -v c = " $col_o " '{print $c}' <<< " $data " | cut -d. -f1)
fgc = $( awk -v c = " $col_fgc " '{print $c}' <<< " $data " | cut -d. -f1)
fgct = $( awk -v c = " $col_fgct " '{print $c}' <<< " $data " )
ygc = $( awk -v c = " $col_ygc " '{print $c}' <<< " $data " | cut -d. -f1)
ygct = $( awk -v c = " $col_ygct " '{print $c}' <<< " $data " )
if [ -z " $o " ] || [ -z " $fgc " ] || [ -z " $fgct " ] || [ -z " $ygc " ] || [ -z " $ygct " ] ; then
log "could not parse one or more numbers out of jstat output"
2026-09-30 11:46:00 +00:00
return 1
fi
2026-09-30 16:09:16 +00:00
echo " $o $fgc $fgct $ygc $ygct "
2026-09-30 11:46:00 +00:00
}
2026-09-30 16:17:08 +00:00
# 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
2026-09-30 11:46:00 +00:00
# ---- main ----
2026-09-30 16:09:16 +00:00
stats = $( read_heap_stats) || exit 1
read -r old_gen_pct fgc_count fgc_time_s ygc_count ygc_time_s <<< " $stats "
# "Since last check" deltas for the Full GC numbers - purely informational
# (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
# need, so it's captured now rather than only the point-in-time totals.
2026-09-30 16:17:08 +00:00
if [ -n " $LAST_CHECK_EPOCH " ] ; then
new_fgc_count = $(( fgc_count - FGC_COUNT ))
2026-09-30 16:09:16 +00:00
# Negative means Tomcat restarted (counters reset) since the last check,
# not that GCs somehow went backwards - treat as "no new data" rather
# than a nonsense negative number.
[ " $new_fgc_count " -lt 0 ] && new_fgc_count = 0
2026-09-30 16:17:08 +00:00
new_fgc_time_s = $( awk -v a = " $fgc_time_s " -v b = " $FGC_TIME_S " \
2026-09-30 16:09:16 +00:00
'BEGIN { d = a - b; if (d < 0) d = 0; printf "%.3f", d }' )
else
new_fgc_count = 0
new_fgc_time_s = "0.000"
log "no previous reading found (first run, or state file missing/reset) - since-last-check numbers start from this run"
2026-09-30 11:46:00 +00:00
fi
2026-09-30 16:17:08 +00:00
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 ))
2026-09-30 16:09:16 +00:00
# ---- condition ----
if [ " $old_gen_pct " -ge " $HEAP_CRITICAL_THRESHOLD_PCT " ] ; then
condition = "critical"
severity = "error"
elif [ " $old_gen_pct " -ge " $HEAP_ELEVATED_THRESHOLD_PCT " ] ; then
condition = "elevated"
severity = "warning"
2026-09-30 11:46:00 +00:00
else
2026-09-30 16:09:16 +00:00
condition = "normal"
severity = "info"
2026-09-30 11:46:00 +00:00
fi
2026-09-30 16:09:16 +00:00
2026-09-30 16:17:08 +00:00
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 "
2026-09-30 16:09:16 +00:00
maintenance_log " $severity " emergency_storeall nop " $condition " \
" Heap check: old-gen ${ old_gen_pct } %, condition ${ condition } . " \
" <oldGenPct> ${ old_gen_pct } </oldGenPct>
<fullGcCountSinceLastCheck>${ new_fgc_count } </fullGcCountSinceLastCheck>
<fullGcTimeSinceLastCheckSec>${ new_fgc_time_s } </fullGcTimeSinceLastCheckSec>
<fullGcCountTotal>${ fgc_count } </fullGcCountTotal>
<fullGcTimeTotalSec>${ fgc_time_s } </fullGcTimeTotalSec>
<youngGcCountTotal>${ ygc_count } </youngGcCountTotal>
2026-09-30 16:17:08 +00:00
<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
2026-09-30 16:09:16 +00:00
exit 0