sportrum-deploy/emergency-storeall.sh

86 lines
2.9 KiB
Bash
Raw Normal View History

#!/bin/bash
#
# emergency-storeall.sh
#
# JVM heap-pressure safety valve. Meant to be run frequently (e.g. every
# 10-15 minutes) on its own cron schedule, independent of and much more
# often than nightly-storeall.sh.
#
# storeall is the only thing that flushes in-memory dirty state to
# Postgres, and it's also the only thing that lets the JVM
# garbage-collect anything currently marked dirty (the registry's
# WeakHashMap eviction is blocked for anything a Modified/Copy record
# still points to). That means old-gen occupancy can only climb, never
# fall, for as long as storeall is deferred - so unlike
# nightly-storeall.sh, this script does not wait for a quiet moment. If
# heap pressure is critical it forces storeall immediately, traffic or
# no traffic, because the alternative is an OOM that loses whatever
# in-memory state was never flushed.
#
# Exits 0 with nothing done when heap pressure isn't critical, so it's
# cheap and safe to run this on a tight schedule.
set -u
cd "$(dirname "$0")"
. ./upgrade-funs.sh
# TODO: this is a starting guess, not yet validated against a real jstat
# reading from production - tune once you've observed normal vs. tight
# old-gen occupancy on the actual server.
HEAP_FORCE_THRESHOLD_PCT="${HEAP_FORCE_THRESHOLD_PCT:-85}"
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') emergency-storeall: $*"
}
# NOTE: untested against a real JVM in this session - the "O" (old gen)
# column is located dynamically from jstat's own header rather than
# hardcoded by position, but the whole function is worth a dry run
# against production before trusting it to force a live storeall.
heap_pressure_critical() {
local tomcat_pid out header data col util
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
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
header=$(head -n 1 <<< "$out")
data=$(tail -n 1 <<< "$out")
col=$(awk '{for (i=1;i<=NF;i++) if ($i=="O") print i}' <<< "$header")
if [ -z "$col" ]; then
log "could not find old-gen (O) column in jstat output, skipping heap check"
return 1
fi
util=$(awk -v c="$col" '{print $c}' <<< "$data" | cut -d. -f1)
if [ -z "$util" ]; then
log "could not read old-gen utilization from jstat output, skipping heap check"
return 1
fi
if [ "$util" -ge "$HEAP_FORCE_THRESHOLD_PCT" ]; then
log "old-gen at ${util}% (>= ${HEAP_FORCE_THRESHOLD_PCT}%) - forcing storeall regardless of traffic"
return 0
fi
return 1
}
# ---- main ----
if ! heap_pressure_critical; then
exit 0
fi
pid=$$
runcmd result storeall
if [ "x$result" == "xsuccess" ]; then
log "storeall completed successfully"
exit 0
else
log "storeall reported '${result}' (not 'success') - check the server log for details"
exit 1
fi