Rework nightly-storeall.sh for cron-driven scheduling, add maintenance_log

nightly-storeall.sh no longer sleeps/retries internally - it's meant to
be invoked every 30 min from 21:00-06:00 by cron and does a single
check-and-maybe-act per run, so a missed/killed run just gets picked up
at the next tick instead of losing all progress. No forced fallback if
still busy at the 06:00 cutoff - that's handled manually for now.

Add maintenance_log() to upgrade-funs.sh: drops a MaintenanceLog XML file
per event into WEB-INF/storage/maintenance-log/ (atomic temp+rename) for
the webapp to pick up and route to sms/email/etc via its own machinery.
Fire-and-forget, matching the shape of MaintenanceLog.java.

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 14:11:11 +00:00
parent 2478310f55
commit 177a8d3702
No known key found for this signature in database
2 changed files with 168 additions and 31 deletions

View file

@ -2,15 +2,29 @@
# #
# nightly-storeall.sh # nightly-storeall.sh
# #
# Waits for a safe moment to flush in-memory state via the app's storeall # Flushes in-memory state via the app's storeall command during a quiet
# command, so the nightly long-lived backup's freeze doesn't land on top # moment overnight, so the nightly backup's freeze doesn't land on top of
# of live race/production traffic. Falls back to running unconditionally # live race/production traffic.
# once the retry budget runs out.
# #
# This script is traffic-driven only and meant to run once a night. The # Cron-driven: meant to be invoked every 30 minutes from 21:00 through
# separate, independent safety valve for JVM heap pressure - which needs # 06:00 (see crontab.example below). Each invocation is a single
# to run much more often, on its own schedule, regardless of traffic - # check-and-maybe-act - this script no longer sleeps/loops internally,
# lives in emergency-storeall.sh. # cron itself provides the retry cadence. That also means a missed or
# killed run just gets picked up again at the next scheduled tick instead
# of losing all progress the way a single long-lived process would.
#
# There is no "force it anyway" fallback. If 06:00 arrives and the server
# is still busy every time we checked, this script gives up for the
# night rather than running storeall against live traffic - that's a
# deliberate choice, done manually for now if it comes to that. See
# emergency-storeall.sh for the separate, independent heap-pressure
# safety valve that DOES act regardless of traffic, on its own schedule.
#
# Every meaningful outcome (deferred because busy, ran successfully, ran
# and failed, gave up for the night) is recorded as a MaintenanceLog XML
# entry via maintenance_log (see upgrade-funs.sh) for the webapp to pick
# up and act on - fire-and-forget, no execution-status handshake back to
# this script.
# #
# Busy signal: any of these handlers appearing in Tomcat's stdout log # Busy signal: any of these handlers appearing in Tomcat's stdout log
# within the trailing window means real work is happening right now - # within the trailing window means real work is happening right now -
@ -38,11 +52,10 @@
# grep -oE approach below, which finds the timestamp+handler substring # grep -oE approach below, which finds the timestamp+handler substring
# anywhere in the line instead. # anywhere in the line instead.
# #
# Validated against a real two-day event's log (Cykelvasan, Aug 2026): # Validated against real production logs spanning several multi-day
# these six handlers sit at exactly zero for the entire overnight lull # events (2023 and 2026): these six handlers sit at exactly zero for the
# on both nights, and never dip below several hundred matches in any # entire overnight lull on every quiet night checked, and never dip below
# 10-minute window during live racing - see the excerpt-based tests run # several hundred matches in any 10-minute window during live racing.
# alongside this script's development for the numbers.
# #
# Scope: this script only decides *when* to call storeall and calls it. # Scope: this script only decides *when* to call storeall and calls it.
# It does not take the actual pg_dump/webapp backup - that's a separate # It does not take the actual pg_dump/webapp backup - that's a separate
@ -60,11 +73,13 @@ TOMCAT_LOG="${TOMCAT_LOG:-/path/to/tomcat/stdout.log}"
TAIL_LINES=20000 # comfortably covers CHECK_WINDOW_MIN even at peak traffic (~800 req/min observed) TAIL_LINES=20000 # comfortably covers CHECK_WINDOW_MIN even at peak traffic (~800 req/min observed)
CHECK_WINDOW_MIN=10 # trailing window used to decide "busy right now" - validated against real data CHECK_WINDOW_MIN=10 # trailing window used to decide "busy right now" - validated against real data
RETRY_INTERVAL_SEC=300 # wait 5 min between retries while busy STOP_TRYING_HOUR=6 # 24h clock - give up for the night at/after this hour if still busy
MAX_RETRIES=24 # ~2 hours of retrying before forcing the run anyway STATE_DIR="${STATE_DIR:-$(dirname "$0")/state}"
BUSY_PATTERN='ProductionCommand\.get_clipcast_screenplay|ProductionCommand\.start_production|ProductionCommand\.update_production|ProductionCommand\.finish_production|ProductionCommand\.append_stream_batch|ESTPushServlet\.null' BUSY_PATTERN='ProductionCommand\.get_clipcast_screenplay|ProductionCommand\.start_production|ProductionCommand\.update_production|ProductionCommand\.finish_production|ProductionCommand\.append_stream_batch|ESTPushServlet\.null'
mkdir -p "$STATE_DIR"
log() { log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') nightly-storeall: $*" echo "$(date '+%Y-%m-%d %H:%M:%S') nightly-storeall: $*"
} }
@ -104,33 +119,94 @@ is_busy() {
[ "$age" -ge 0 ] && [ "$age" -le "$window_sec" ] [ "$age" -ge 0 ] && [ "$age" -le "$window_sec" ]
} }
# ---- main ---- # Sums the TOTAL(n) values out of the most recent "----- SUCCESS -----"
# block in TOMCAT_LOG - i.e. how many objects the storeall that just ran
# actually flushed. Best-effort and purely for the log entry: prints 0
# rather than erroring if nothing is found.
#
# NOTE: unconfirmed whether this duplicates data already available some
# other way (e.g. directly in the status file runcmd reads) - in every
# real log checked so far the object breakdown only ever showed up on
# Tomcat's stdout, never in anything runcmd itself sees, but worth
# double-checking against the actual status file content before relying
# on this as the only source.
last_storeall_object_count() {
tail -n "$TAIL_LINES" "$TOMCAT_LOG" | awk '
/----- SUCCESS -----/ { sum=0; in_block=1; next }
/----- FAILURE -----/ { in_block=0 }
in_block {
n = split($0, parts, "TOTAL(")
if (n > 1) {
split(parts[2], parts2, ")")
sum += parts2[1] + 0
}
}
END { print sum+0 }
'
}
attempt=0 # ---- night-window bookkeeping ----
forced_reason=""
while is_busy; do current_hour=$((10#$(date +%H)))
attempt=$((attempt + 1))
if [ "$attempt" -ge "$MAX_RETRIES" ]; then
forced_reason="retry budget exhausted (${MAX_RETRIES} attempts)"
break
fi
log "server busy, waiting ${RETRY_INTERVAL_SEC}s before retry ${attempt}/${MAX_RETRIES}"
sleep "$RETRY_INTERVAL_SEC"
done
if [ -n "$forced_reason" ]; then # The marker represents "did tonight's window already succeed (or give
log "proceeding with storeall - forced (${forced_reason})" # up)". The window spans midnight (21:00-06:00), so a run at 21:30 and a
# run at 01:00 the next calendar day both need to agree on which night
# they belong to - runs in the small hours belong to the *previous*
# calendar date's night.
if [ "$current_hour" -ge 21 ]; then
night_date=$(date +%Y%m%d)
cutoff_reached=false
else else
log "proceeding with storeall - server is quiet" night_date=$(date -d "yesterday" +%Y%m%d)
if [ "$current_hour" -ge "$STOP_TRYING_HOUR" ]; then
cutoff_reached=true
else
cutoff_reached=false
fi
fi fi
MARKER="$STATE_DIR/nightly-storeall.$night_date"
# Already handled tonight (succeeded, or already gave up past the
# cutoff) - nothing new to report, stay quiet rather than re-logging
# every 30 minutes until 21:00.
if [ -f "$MARKER" ]; then
exit 0
fi
# ---- main ----
if is_busy; then
if [ "$cutoff_reached" = true ]; then
log "reached ${STOP_TRYING_HOUR}:00 with no quiet window found - giving up for tonight"
maintenance_log warning nightly_storeall nop no_quiet_window \
"Reached ${STOP_TRYING_HOUR}:00 cutoff without a quiet window; storeall was not run."
touch "$MARKER"
exit 0
else
log "server busy, will retry at the next scheduled check"
maintenance_log info nightly_storeall nop busy \
"Server busy - deferring storeall to the next scheduled check."
exit 0
fi
fi
log "server is quiet - running storeall"
pid=$$ pid=$$
runcmd result storeall runcmd result storeall
if [ "x$result" == "xsuccess" ]; then if [ "x$result" == "xsuccess" ]; then
log "storeall completed successfully" count=$(last_storeall_object_count)
log "storeall completed successfully (${count} objects stored)"
maintenance_log info nightly_storeall storeall quiet \
"storeall completed successfully." \
" <objectsStored>${count}</objectsStored>"
touch "$MARKER"
exit 0 exit 0
else else
log "storeall reported '${result}' (not 'success') - check the server log for details" log "storeall reported '${result}' (not 'success') - check the server log for details"
maintenance_log error nightly_storeall storeall quiet \
"storeall failed: result was '${result}'."
exit 1 exit 1
fi fi

View file

@ -43,3 +43,64 @@ function runcmd {
fi fi
done done
} }
# maintenance_log drops one XML file per event into the maintenance-log
# folder for the sportrum webapp to pick up, deserialize into a
# MaintenanceLog object, and act on (trigger sms/email/etc through its
# own machinery - see MaintenanceLog.java). Fire-and-forget: this
# function doesn't wait for anything to process the file, and there's no
# execution-status handshake back to the caller - it just needs to land a
# well-formed file.
#
# Usage: maintenance_log <severity> <operation> <action> <reason> <message> [extra_xml]
# maintenance_log info nightly_storeall storeall quiet "storeall completed."
#
# severity/operation/action/reason are free-form lowercase tokens (e.g.
# severity: info|warning|error, action: nop|storeall, reason:
# busy|quiet|no_quiet_window) - adjust the exact vocabulary to match
# whatever the webapp's Severity/MaintenanceType lookups actually expect.
#
# <extra_xml>, if given, is inserted verbatim as additional children
# inside <details> (e.g. "<objectsStored>42</objectsStored>") - caller is
# responsible for passing well-formed XML there.
#
# Written via a temp file + atomic rename so whatever's watching the
# directory never sees a partially-written file.
function maintenance_log {
local severity=$1
local operation=$2
local action=$3
local reason=$4
local message=$5
local extra_xml="${6:-}"
local logdir="/home/sportrum/webapp/sportrum/WEB-INF/storage/maintenance-log"
mkdir -p "$logdir"
local esc_message
esc_message=$(printf '%s' "$message" | sed -e 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g')
local ts_utc
ts_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
local fname
fname="$(date -u +%Y%m%dT%H%M%S).$$.${severity}"
local tmpfile="${logdir}/.${fname}.tmp"
local finalfile="${logdir}/${fname}.xml"
cat > "$tmpfile" <<EOF
<MaintenanceLog>
<creationTime>${ts_utc}</creationTime>
<severity>${severity}</severity>
<operation>${operation}</operation>
<action>${action}</action>
<reason>${reason}</reason>
<details>
<script>$(basename "$0")</script>
<host>$(hostname)</host>
<message>${esc_message}</message>
${extra_xml}
</details>
</MaintenanceLog>
EOF
mv "$tmpfile" "$finalfile"
}