Files
Jyotisha/deploy/monitor/ops-check.sh
T
ClaudeandClaude Opus 5.5 caf3af6b7e fix(monitor): alerts by Feishu and email, host checks, OTP retry, off-host probe (BUG-2348)
- notify-feishu.sh: add a Resend email channel (key read from .env.production
  via a header file, never argv/stdout); both channels when configured, one
  acceptance counts; fixed Chinese labels on every alert line.
- classify_error_log.py: per-code thresholds for low-volume signals, the
  [ops-signal] marker, api access-log 429/5xx counted without query strings.
- ops-check.sh: container restarts/OOM, host memory, report queue wait, new
  feedback count (no content).
- OTP sender: retry network/429/5xx once with the same idempotency key; final
  failure logs otp_send_failed (no address).
- install-production-monitor.sh: idempotent cron install + --test-alert.
- monitor-public-health.yml: off-host probe every 5 minutes on the runner.
- Tests: tests/test_monitor_alerts_2348.py (on the quick list), OTP sender and
  ops-signal tests. Issues #350, #354.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-25 11:03:45 +08:00

199 lines
6.7 KiB
Bash

#!/usr/bin/env bash
# Host checks that logs alone cannot show (BUG-2348). Install on the production
# host, every 5 minutes:
# - a container restarted on its own, or was killed for memory
# - host available memory is low
# - the oldest report job has waited too long to start
# - new user feedback arrived (count only; no feedback text, no account)
set -euo pipefail
set +x
umask 077
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=notify-feishu.sh
source "$script_dir/notify-feishu.sh"
case "${1:-}" in
"") ;;
*)
echo "unknown argument" >&2
exit 2
;;
esac
state_dir="${JYOTISHA_MONITOR_STATE_DIR:-/var/lib/jyotisha-monitor}"
ensure_private_dir "$state_dir"
env_file="${JYOTISHA_MONITOR_ENV:-/opt/jyotisha-production/.monitor.env}"
load_monitor_env "$env_file"
project="${JYOTISHA_COMPOSE_PROJECT:-jyotisha-production}"
[[ "$project" =~ ^[a-z0-9][a-z0-9_-]*$ ]] || exit 2
queue_limit="${JYOTISHA_QUEUE_WAIT_LIMIT:-600}"
memory_limit="${JYOTISHA_MEMORY_PERCENT_LIMIT:-90}"
[[ "$queue_limit" =~ ^[1-9][0-9]{1,5}$ ]] || exit 2
[[ "$memory_limit" =~ ^[1-9][0-9]$ ]] || exit 2
# Tests replace docker and the memory file; production uses sudo -n docker
# because the monitor user is not in the docker group.
docker_cmd() {
if [ -n "${JYOTISHA_DOCKER:-}" ]; then
"$JYOTISHA_DOCKER" "$@"
else
sudo -n docker "$@"
fi
}
stamp() {
date -u +%Y-%m-%dT%H:%M:%SZ
}
state_file="$state_dir/ops-check.state"
declare -A restarts=()
memory_open=0
queue_open=0
feedback_seen=""
read_state() {
local line key value
[ -f "$state_file" ] && [ ! -L "$state_file" ] || return 0
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
restart:*=*)
key="${line%%=*}"
key="${key#restart:}"
value="${line#*=}"
[[ "$key" =~ ^[0-9a-f]{12,64}$ ]] && [[ "$value" =~ ^[0-9]+$ ]] && restarts["$key"]="$value"
;;
memory_open=[01]) memory_open="${line#memory_open=}" ;;
queue_open=[01]) queue_open="${line#queue_open=}" ;;
feedback_seen=*)
value="${line#feedback_seen=}"
[[ "$value" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$ ]] && feedback_seen="$value"
;;
esac
done <"$state_file"
}
write_state() {
local tmp key
tmp="$state_file.tmp.$$"
{
printf 'memory_open=%s\nqueue_open=%s\nfeedback_seen=%s\n' "$memory_open" "$queue_open" "$feedback_seen"
for key in "${!restarts[@]}"; do
printf 'restart:%s=%s\n' "$key" "${restarts[$key]}"
done
} >"$tmp"
if [ "$(uname -s)" = "Linux" ]; then
chmod 600 "$tmp"
fi
mv "$tmp" "$state_file"
}
alerts=""
queue_alert() {
alerts="${alerts}service=$1 route=$2 errorCode=$3 count=$4 requestId=- time=$(stamp)"$'\n'
}
check_containers() {
local ids line id name count oom service
declare -A current=()
ids="$(docker_cmd ps -q --filter "label=com.docker.compose.project=${project}")" || return 0
[ -n "$ids" ] || return 0
# shellcheck disable=SC2086
while IFS=' ' read -r id name count oom || [ -n "${id:-}" ]; do
[[ "${id:-}" =~ ^[0-9a-f]{12,64}$ ]] || continue
[[ "${count:-}" =~ ^[0-9]+$ ]] || continue
service="${name#/}"
service="${service#${project}-}"
service="${service%-[0-9]*}"
[[ "$service" =~ ^[a-z0-9_-]+$ ]] || service="container"
current["$id"]="$count"
if [ -n "${restarts[$id]:-}" ] && [ "$count" -gt "${restarts[$id]}" ]; then
if [ "$oom" = "true" ]; then
queue_alert "$service" - container_oom "$count"
else
queue_alert "$service" - container_restarted "$count"
fi
elif [ -z "${restarts[$id]:-}" ] && [ "$count" -gt 0 ]; then
queue_alert "$service" - container_restarted "$count"
fi
done < <(docker_cmd inspect --format '{{.Id}} {{.Name}} {{.RestartCount}} {{.State.OOMKilled}}' $ids)
# Containers that are gone (a deploy recreated them) drop out of the state.
restarts=()
for id in "${!current[@]}"; do
restarts["$id"]="${current[$id]}"
done
}
check_memory() {
local file total available used
file="${JYOTISHA_MEMINFO:-/proc/meminfo}"
[ -r "$file" ] || return 0
total="$(awk '$1 == "MemTotal:" {print $2}' "$file")"
available="$(awk '$1 == "MemAvailable:" {print $2}' "$file")"
[[ "$total" =~ ^[0-9]+$ ]] && [[ "$available" =~ ^[0-9]+$ ]] && [ "$total" -gt 0 ] || return 0
used=$(( (total - available) * 100 / total ))
if [ "$used" -ge "$memory_limit" ]; then
if [ "$memory_open" -eq 0 ]; then
queue_alert host - memory_high "$used"
memory_open=1
fi
elif [ "$memory_open" -eq 1 ]; then
queue_alert host - recovered 0
memory_open=0
fi
}
# One read-only query through the postgres container. The SQL is fixed text;
# its output is numbers and a timestamp only.
psql_value() {
local sql="$1"
local container="${JYOTISHA_POSTGRES_CONTAINER:-${project}-postgres-1}"
[[ "$container" =~ ^[a-z0-9][a-z0-9_.-]*$ ]] || return 1
docker_cmd exec -i "$container" sh -c 'psql -X -q -A -t -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "${POSTGRES_DB:-postgres}"' <<<"$sql"
}
check_report_queue() {
local wait
wait="$(psql_value "select coalesce(extract(epoch from now() - min(coalesce(next_attempt_at, created_at)))::bigint, 0) from public.personal_report_jobs where status in ('queued', 'retrying') and coalesce(next_attempt_at, created_at) <= now();" 2>/dev/null | tr -d '\r[:space:]')" || return 0
[[ "$wait" =~ ^[0-9]+$ ]] || return 0
if [ "$wait" -ge "$queue_limit" ]; then
if [ "$queue_open" -eq 0 ]; then
queue_alert report /api/reports report_queue_stuck "$wait"
queue_open=1
fi
elif [ "$queue_open" -eq 1 ]; then
queue_alert report /api/reports recovered 0
queue_open=0
fi
}
check_feedback() {
local row count newest since
since="${feedback_seen:-}"
if [ -z "$since" ]; then
# First run: start from now so old feedback is not announced.
row="$(psql_value "select to_char(now() at time zone 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"');" 2>/dev/null | tr -d '\r[:space:]')" || return 0
[[ "$row" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] && feedback_seen="$row"
return 0
fi
row="$(psql_value "select count(*) || '|' || coalesce(to_char(max(created_at) at time zone 'utc', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), '') from public.user_feedback where created_at > '${since}'::timestamptz;" 2>/dev/null | tr -d '\r[:space:]')" || return 0
count="${row%%|*}"
newest="${row#*|}"
[[ "$count" =~ ^[0-9]+$ ]] || return 0
if [ "$count" -gt 0 ] && [[ "$newest" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$ ]]; then
queue_alert web /admin/feedback feedback_new "$count"
feedback_seen="$newest"
fi
}
read_state
check_containers
check_memory
check_report_queue
check_feedback
if [ -n "$alerts" ]; then
post_monitor_alert "${alerts%$'\n'}"
fi
write_state