douyinWEB/scripts/linux/api_health_watch.sh
eric ba946d5a9a Fix dy.live API hang and sticky OAuth false failures.
Keep Shorts/yt_long/tiktok/x_clips SQLite off the asyncio thread, fall back past proxy Bad Request on token refresh, and avoid marking oauth_ok=0 for transient egress errors.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 06:01:19 -05:00

84 lines
2.4 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env bash
# Restart douyinweb-api when local /api/health stays down.
# Includes start grace — uvicorn often needs 1–2 minutes before listen.
set +e
INTERVAL="${DY_API_WATCH_INTERVAL:-20}"
FAILS_NEED="${DY_API_WATCH_FAILS:-4}"
COOLDOWN="${DY_API_WATCH_COOLDOWN:-180}"
GRACE="${DY_API_WATCH_START_GRACE:-180}"
HEALTH_URL="${DY_API_WATCH_URL:-http://127.0.0.1:8014/api/health}"
UNIT="${DY_API_WATCH_UNIT:-douyinweb-api.service}"
RECVQ_LIMIT="${DY_API_WATCH_RECVQ_LIMIT:-200}"
HEALTH_TIMEOUT="${DY_API_WATCH_HEALTH_TIMEOUT:-4}"
log() { printf '[api-watch] %s\n' "$*"; }
fails=0
last_restart=0
recvq_too_high() {
# Listen socket Recv-Q climbing means accept/event-loop wedged even if TCP connects.
local q
q=$(ss -ltn sport = :8014 2>/dev/null | awk 'NR==2 {print $2}')
case "$q" in ''|*[!0-9]*) return 1 ;; esac
[ "$q" -ge "$RECVQ_LIMIT" ]
}
while true; do
st=$(systemctl is-active "$UNIT" 2>/dev/null || true)
if [ "$st" != "active" ]; then
log "unit=$st skip"
fails=0
sleep "$INTERVAL"
continue
fi
started=$(systemctl show -p ActiveEnterTimestamp --value "$UNIT" 2>/dev/null)
if [ -n "$started" ] && [ "$started" != "n/a" ]; then
start_epoch=$(date -d "$started" +%s 2>/dev/null || echo 0)
now_epoch=$(date +%s)
if [ "$start_epoch" -gt 0 ]; then
up=$((now_epoch - start_epoch))
if [ "$up" -lt "$GRACE" ]; then
log "grace ${up}/${GRACE}s"
fails=0
sleep "$INTERVAL"
continue
fi
fi
fi
code=$(curl -sS -m "$HEALTH_TIMEOUT" -o /dev/null -w '%{http_code}' "$HEALTH_URL" 2>/dev/null)
[ -n "$code" ] || code=000
now=$(date +%s)
if [ "$code" = "200" ]; then
if recvq_too_high; then
fails=$((fails + 1))
log "health=200 but Recv-Q high fails=$fails/$FAILS_NEED"
else
fails=0
fi
else
fails=$((fails + 1))
log "health=$code fails=$fails/$FAILS_NEED"
fi
if [ "$fails" -ge "$FAILS_NEED" ]; then
elapsed=$((now - last_restart))
if [ "$elapsed" -ge "$COOLDOWN" ]; then
log "restarting $UNIT"
systemctl kill -s SIGKILL "$UNIT" >/dev/null 2>&1
pkill -9 -f 'uvicorn app.main:app' >/dev/null 2>&1
sleep 2
systemctl reset-failed "$UNIT" >/dev/null 2>&1
systemctl start "$UNIT" >/dev/null 2>&1
last_restart=$now
fails=0
else
log "cooldown ${elapsed}/${COOLDOWN}s"
fi
fi
sleep "$INTERVAL"
done