strawberry/scripts/strawberry-reduce.sh
trvon 1ee208fb4b
Stage 7e: scheduled stop->reduce->start telemetry-reduction maintenance (opt-in)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-11 13:21:13 -07:00

64 lines
2.4 KiB
Bash
Executable file

#!/usr/bin/env bash
# Scheduled telemetry reduction: stop strawberry.service -> `store reduce` -> start.
# Run by strawberry-reduce.service (timer is opt-in). `store reduce` needs exclusive
# store access, so the daemon is stopped for the duration (a monitoring GAP).
#
# SAFETY-CRITICAL: the daemon MUST come back on every exit path (reduce failure,
# signal, unbound variable). That is the EXIT trap below. No `set -e` on purpose,
# so a failing step can never skip the restart. Only SIGKILL of this script itself
# bypasses the trap (residual risk; documented in docs/store-reduction.md).
set -uo pipefail
BIN="${STRAWBERRY_BIN:-/usr/local/bin/strawberry}"
CONF="${STRAWBERRY_CONF:-/etc/strawberry/strawberry.conf}"
UNIT=strawberry.service
# Gate: single source of truth. A fired timer no-ops unless explicitly enabled.
if ! grep -Eqs '^[[:space:]]*store_reduce_enabled[[:space:]]*=[[:space:]]*(true|1)[[:space:]]*$' "$CONF"; then
echo "strawberry-reduce: disabled (store_reduce_enabled)"
exit 0
fi
restart_daemon() {
# Idempotent; runs on every exit path once armed.
systemctl start "$UNIT" || echo "strawberry-reduce: ERROR: could not restart $UNIT" >&2
}
stopped=0
if systemctl is-active --quiet "$UNIT"; then
# Arm the restart BEFORE stopping, so nothing between stop and start can leave
# the daemon down. Signals become a normal exit, which fires the EXIT trap.
trap restart_daemon EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
trap 'exit 129' HUP
stopped=1
if ! systemctl stop "$UNIT"; then
echo "strawberry-reduce: could not stop $UNIT; aborting (trap restarts it)" >&2
exit 1
fi
fi
rc=1
out=""
for attempt in 1 2 3 4 5; do
out=$(nice -n 19 "$BIN" store reduce --yes --config "$CONF" --json 2>&1)
rc=$?
# Defensive: stop is synchronous, but retry if the flock is still held.
if [ "$rc" -ne 0 ] && printf '%s' "$out" | grep -qi 'locked'; then
sleep 2
continue
fi
break
done
printf '%s\n' "$out"
before=$(printf '%s\n' "$out" | sed -n 's/.*"records_before": *\([0-9]*\).*/\1/p' | head -1)
after=$(printf '%s\n' "$out" | sed -n 's/.*"records_after": *\([0-9]*\).*/\1/p' | head -1)
echo "strawberry-reduce: rc=$rc records ${before:-?} -> ${after:-?} (daemon_was_active=$stopped)"
# Restart now (the EXIT trap also covers this and every earlier exit path).
if [ "$stopped" -eq 1 ]; then
restart_daemon
fi
exit "$rc"