#!/bin/bash # # nightly-storeall.sh # # 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. # # 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 - # video production nodes actively producing, the live-stream ingest # pipeline actively receiving chunks, or the timing system actively # receiving live race data: # ProductionCommand.get_clipcast_screenplay # ProductionCommand.start_production # ProductionCommand.update_production # ProductionCommand.finish_production # ProductionCommand.append_stream_batch # ESTPushServlet.null # Deliberately excludes ProductionCommand.peek_productions_queue_new, # ProductionCommand.request_batch and ProductionCommand.producer_log - # those fire continuously from idle nodes kept warm during an event and # don't indicate real work happening. # # IMPORTANT: match against the log without anchoring at the start of the # line. Some handlers (append_stream_batch in particular) print an # unterminated progress fragment ("- processed N chunks") immediately # before the request-completion log line with no newline in between, so # the two get glued onto one physical line and "sportrum:" doesn't start # at column 1. An anchored regex missed 99.9% of append_stream_batch's # occurrences in testing (and ~2-4% of the other handlers') - see the # grep -oE approach below, which finds the timestamp+handler substring # anywhere in the line instead. # # 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 # step to chain after a successful run. set -u cd "$(dirname "$0")" . ./upgrade-funs.sh # ---- configuration - tune for your environment ---- # TODO: fill in the real path once you've found where supervisord writes # Tomcat's stdout (its stdout_logfile setting for the tomcat program). 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 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: $*" } # Prints the epoch of the most recent busy-pattern line seen in the # trailing $TAIL_LINES lines of the log. Returns 1 (prints nothing) if # none found in that tail at all. # # Uses grep -oE to pull out just the "day mon HH:MM:SS <-> Handler" # substring wherever it occurs on the line, rather than anchoring at the # start of the line - see the note above BUSY_PATTERN for why an anchored # match silently misses most append_stream_batch lines. last_busy_epoch() { local last day mon t last=$(tail -n "$TAIL_LINES" "$TOMCAT_LOG" \ | grep -oE "[0-9]+ [a-z]+ [0-9]{2}:[0-9]{2}:[0-9]{2} <-> (${BUSY_PATTERN})" \ | tail -n 1) [ -z "$last" ] && return 1 day=$(awk '{print $1}' <<< "$last") mon=$(awk '{print $2}' <<< "$last") t=$(awk '{print $3}' <<< "$last") # NOTE: log lines carry no year, and the month name is locale-dependent # (this JVM logs in Swedish locale - "maj"/"okt" would not parse here, # though every month actually exercised so far happens to be spelled # the same in Swedish and English). Revisit if a false parse ever shows # up around May or October. date -d "$day $mon $(date +%Y) $t" +%s 2>/dev/null } # Exit 0 = busy (real work within the trailing window), 1 = quiet. is_busy() { local last_epoch now age window_sec last_epoch=$(last_busy_epoch) || return 1 now=$(date +%s) age=$(( now - last_epoch )) window_sec=$(( CHECK_WINDOW_MIN * 60 )) [ "$age" -ge 0 ] && [ "$age" -le "$window_sec" ] } # 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 } ' } # ---- night-window bookkeeping ---- current_hour=$((10#$(date +%H))) # 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 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 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