diff --git a/nightly-storeall.sh b/nightly-storeall.sh
index 4a3ff8d..d5c3989 100755
--- a/nightly-storeall.sh
+++ b/nightly-storeall.sh
@@ -2,15 +2,29 @@
#
# nightly-storeall.sh
#
-# Waits for a safe moment to flush in-memory state via the app's storeall
-# command, so the nightly long-lived backup's freeze doesn't land on top
-# of live race/production traffic. Falls back to running unconditionally
-# once the retry budget runs out.
+# Flushes in-memory state via the app's storeall command during a quiet
+# moment overnight, so the nightly backup's freeze doesn't land on top of
+# live race/production traffic.
#
-# This script is traffic-driven only and meant to run once a night. The
-# separate, independent safety valve for JVM heap pressure - which needs
-# to run much more often, on its own schedule, regardless of traffic -
-# lives in emergency-storeall.sh.
+# Cron-driven: meant to be invoked every 30 minutes from 21:00 through
+# 06:00 (see crontab.example below). Each invocation is a single
+# check-and-maybe-act - this script no longer sleeps/loops internally,
+# 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
# 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
# anywhere in the line instead.
#
-# Validated against a real two-day event's log (Cykelvasan, Aug 2026):
-# these six handlers sit at exactly zero for the entire overnight lull
-# on both nights, and never dip below several hundred matches in any
-# 10-minute window during live racing - see the excerpt-based tests run
-# alongside this script's development for the numbers.
+# Validated against real production logs spanning several multi-day
+# events (2023 and 2026): these six handlers sit at exactly zero for the
+# entire overnight lull on every quiet night checked, and never dip below
+# several hundred matches in any 10-minute window during live racing.
#
# 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
@@ -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)
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
-MAX_RETRIES=24 # ~2 hours of retrying before forcing the run anyway
+STOP_TRYING_HOUR=6 # 24h clock - give up for the night at/after this hour if still busy
+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'
+mkdir -p "$STATE_DIR"
+
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') nightly-storeall: $*"
}
@@ -104,33 +119,94 @@ is_busy() {
[ "$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
-forced_reason=""
+# ---- night-window bookkeeping ----
-while is_busy; do
- 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
+current_hour=$((10#$(date +%H)))
-if [ -n "$forced_reason" ]; then
- log "proceeding with storeall - forced (${forced_reason})"
+# The marker represents "did tonight's window already succeed (or give
+# 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
- 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
+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=$$
runcmd result storeall
+
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." \
+ " ${count}"
+ touch "$MARKER"
exit 0
else
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
fi
diff --git a/upgrade-funs.sh b/upgrade-funs.sh
index 8dfe8da..81eac5f 100644
--- a/upgrade-funs.sh
+++ b/upgrade-funs.sh
@@ -43,3 +43,64 @@ function runcmd {
fi
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 [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.
+#
+# , if given, is inserted verbatim as additional children
+# inside (e.g. "42") - 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/&/\&/g; s/\</g; s/>/\>/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" <
+ ${ts_utc}
+ ${severity}
+ ${operation}
+ ${action}
+ ${reason}
+
+
+ $(hostname)
+ ${esc_message}
+${extra_xml}
+
+
+EOF
+ mv "$tmpfile" "$finalfile"
+}