diff --git a/.gitea/workflows/monitor-public-health.yml b/.gitea/workflows/monitor-public-health.yml new file mode 100644 index 000000000..2c0db0f3a --- /dev/null +++ b/.gitea/workflows/monitor-public-health.yml @@ -0,0 +1,70 @@ +name: Monitor Public Health + +# BUG-2348: availability probe from outside the production server. Every 5 +# minutes the runner opens the public health URL three times, 20 seconds apart. +# Three failures in a row send one alert (Feishu and/or email); the first good +# probe afterwards sends one recovery. State lives under the runner user's home +# so an outage alerts once, not every run. +# +# Secrets (repository → Actions → Secrets): MONITOR_FEISHU_WEBHOOK_URL, +# MONITOR_FEISHU_SIGN_SECRET (optional), MONITOR_ALERT_EMAIL_TO, +# MONITOR_ALERT_EMAIL_FROM, MONITOR_RESEND_API_KEY. Any channel left empty is +# skipped; with none set the alert stays in the runner's local alerts.log. + +on: + schedule: + - cron: "*/5 * * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: monitor-public-health + cancel-in-progress: false + +jobs: + probe: + if: gitea.ref == 'refs/heads/main' + runs-on: xiaoxin + timeout-minutes: 5 + env: + GITEA_SHA: ${{ gitea.sha }} + GITEA_REF: ${{ gitea.ref }} + steps: + - name: Probe https://jyotisha.chat/api/health + env: + MONITOR_FEISHU_WEBHOOK_URL: ${{ secrets.MONITOR_FEISHU_WEBHOOK_URL }} + MONITOR_FEISHU_SIGN_SECRET: ${{ secrets.MONITOR_FEISHU_SIGN_SECRET }} + MONITOR_ALERT_EMAIL_TO: ${{ secrets.MONITOR_ALERT_EMAIL_TO }} + MONITOR_ALERT_EMAIL_FROM: ${{ secrets.MONITOR_ALERT_EMAIL_FROM }} + MONITOR_RESEND_API_KEY: ${{ secrets.MONITOR_RESEND_API_KEY }} + run: | + set -euo pipefail + set +x + [[ "$GITEA_REF" == "refs/heads/main" ]] + [[ "$GITEA_SHA" =~ ^[0-9a-f]{40}$ ]] + git init -q . + git remote remove origin 2>/dev/null || true + git remote add origin https://git.copse.top/root/Jyotisha.git + git fetch -q --no-tags --depth 1 origin "$GITEA_SHA" + git checkout -q --detach --force "$GITEA_SHA" + work="${RUNNER_TEMP}/monitor-public-health" + install -m 700 -d "$work" + env_file="$work/monitor.env" + : >"$env_file" + chmod 600 "$env_file" + [ -z "$MONITOR_FEISHU_WEBHOOK_URL" ] || printf 'FEISHU_WEBHOOK_URL=%s\n' "$MONITOR_FEISHU_WEBHOOK_URL" >>"$env_file" + [ -z "$MONITOR_FEISHU_SIGN_SECRET" ] || printf 'FEISHU_SIGN_SECRET=%s\n' "$MONITOR_FEISHU_SIGN_SECRET" >>"$env_file" + [ -z "$MONITOR_ALERT_EMAIL_TO" ] || printf 'ALERT_EMAIL_TO=%s\n' "$MONITOR_ALERT_EMAIL_TO" >>"$env_file" + [ -z "$MONITOR_ALERT_EMAIL_FROM" ] || printf 'ALERT_EMAIL_FROM=%s\n' "$MONITOR_ALERT_EMAIL_FROM" >>"$env_file" + [ -z "$MONITOR_RESEND_API_KEY" ] || printf 'RESEND_API_KEY=%s\n' "$MONITOR_RESEND_API_KEY" >>"$env_file" + trap 'rm -rf -- "$work"' EXIT + export JYOTISHA_MONITOR_ENV="$env_file" + export JYOTISHA_APP_ENV_FILE="$work/no-app-env" + export JYOTISHA_COMMIT_ALERT=off + export JYOTISHA_MONITOR_STATE_DIR="${HOME}/.jyotisha-monitor/public-health" + for attempt in 1 2 3; do + bash deploy/monitor/healthcheck-alert.sh --mode health + [ "$attempt" -eq 3 ] || sleep 20 + done diff --git a/deploy/README.md b/deploy/README.md index 594be4263..4b2c5af3f 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -493,20 +493,46 @@ report list / detail / create smoke”): `GET /api/reports` 200, owned - Gitea 产物默认保留 14 天。手动恢复点工作流仍是 30 天,没有改。 - 还原步骤:`docs/operations/production-restore-drill-20261014.md`。 -### 告警装在哪 +### 告警装在哪(BUG-2348) -- 探活不要装在生产主机上。装在 Gitea runner 上,每分钟跑 `deploy/monitor/healthcheck-alert.sh --mode health`。它访问公网 `https://jyotisha.chat/api/health`,超时 10 秒。连续 3 次失败才告警,恢复只发一次。 -- 发布窗口:在 runner 上执行 `touch /var/lib/jyotisha-monitor/release-window`。45 分钟内,版本号变化不告警。 -- 磁盘检查装在生产主机上,每分钟跑同一个脚本的 `--mode disk`。使用率达到 80% 告警一次,降下来再发一次已恢复。同一轮还会读 `/opt/jyotisha-production/.state/daily-backup-latest.env` 的 `VERIFIED_AT`。这份记录缺失,或比当前时间早超过 36 小时,会再告警一次。重新核对成功后发一次已恢复。探活模式不读这份文件。 -- 错误汇总装在生产主机上。每 5 分钟 `deploy/monitor/error-digest.sh --window`。每天北京时间 09:00(UTC 01:00)跑 `--daily`,汇总前一天。同类错误 5 分钟内至少 10 次,或 5xx 至少 20 次,才发窗口告警。同一服务、同一路由、同一错误码在 30 分钟内不重复发。消息里最多 5 个 requestId。含邮箱、第二个日期或非 ASCII 文本的日志行整行丢掉。飞书没有返回成功时,这条不会被记成已发送。 -- Webhook 写在模式 `0600` 的环境文件里,建议路径 `/opt/jyotisha-production/.monitor.env`(runner 上用 `JYOTISHA_MONITOR_ENV` 指向自己的文件)。只放这两行,不要提交: +一条命令装好主机上的全部监控,可以重复运行: + +```bash +sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh +sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh --test-alert +``` + +它写 `/etc/cron.d/jyotisha-production-monitor`(root 运行,输出进 syslog,标签 `jyotisha-monitor`): + +| 频率 | 脚本 | 看什么 | +|---|---|---| +| 每分钟 | `healthcheck-alert.sh --mode all` | 本机看到的 `/api/health`(连续 3 次失败告警、恢复发一次);磁盘 ≥80%;每日备份超过 36 小时没核对成功 | +| 每 5 分钟 | `error-digest.sh --window` | web/api 日志里的错误码和 5xx;计算服务 429;`[ops-signal]` 信号(验证码发信失败、模型花费超标、切到备用模型) | +| 北京时间 09:00 | `error-digest.sh --daily` | 前一天的汇总 | +| 每 5 分钟 | `ops-check.sh` | 容器自己重启或被 OOM 杀;主机可用内存 ≥90% 已用;报告排队最久的任务超过 10 分钟没开始;有新的用户反馈(只发条数) | + +服务器整台不可达时本机发不出告警,所以另有一个**服务器之外的探活**:Gitea 工作流 `.gitea/workflows/monitor-public-health.yml`,在 runner 上每 5 分钟访问三次 `https://jyotisha.chat/api/health`,连续三次失败告警一次,恢复发一次。它用仓库 Actions 密钥:`MONITOR_FEISHU_WEBHOOK_URL`、`MONITOR_FEISHU_SIGN_SECRET`(可空)、`MONITOR_ALERT_EMAIL_TO`、`MONITOR_ALERT_EMAIL_FROM`、`MONITOR_RESEND_API_KEY`。runner 关机时这一路也停,Gitea 里能看到运行记录断了。 + +发布窗口:版本号变化在本机和 runner 上都不再告警(`JYOTISHA_COMMIT_ALERT=off`),发版本身由部署工作流记录。 + +**阈值(5 分钟窗口)**:一般错误码 10 次、5xx 20 次;验证码发信失败 3 次;花费超标 1 次;备用模型 3 次;供应商错误 3 次;超时、空回答 5 次;计算服务 429 合计 10 次。同一服务、路由、错误码 30 分钟内只发一次。容器、内存、排队、探活、磁盘、备份这几类是“开一次、恢复一次”。 + +**通道**写在 `/opt/jyotisha-production/.monitor.env`(模式 `0600`,不提交): ```text FEISHU_WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/ FEISHU_SIGN_SECRET=<只有开了签名校验才填> +ALERT_EMAIL_TO=<收告警的邮箱,最多 5 个,用逗号隔开> ``` -没配 Webhook 时只写本机 `alerts.log`,不外发。飞书消息是 `msg_type: text`。配了签名就带 `timestamp` 和 `sign`。 +邮件用 `.env.production` 里已有的 `RESEND_API_KEY` 和 `RESEND_FROM_EMAIL` 发(只读这两行,不打印)。想换发件人可在 `.monitor.env` 里加 `ALERT_EMAIL_FROM=`。两个通道都配时两边都发;只要有一个接收成功就算发出,都失败时不记成已发送,下一轮再试。一个都没配时只写本机 `/var/lib/jyotisha-monitor/alerts.log`。 + +告警正文:第一行「Jyotisha 生产告警」,每条先是一句固定的中文说明(来自 `notify-feishu.sh` 里的对照表),再是 `service=… route=… errorCode=… count=… requestId=… time=…` 这一行。日志里的文字不会进告警。 + +**应用里的信号**:`frontend/src/lib/ops-signal.ts` 打一行 `[ops-signal] {"errorCode":"…","route":"…","upstream":"…"}`。只允许固定的错误码(`otp_send_failed`、`model_spend_alert`、`model_fallback_used`),没有邮箱、用户、正文或供应商原文。验证码发信遇到网络错误、429 或 5xx 会用同一个幂等键重试一次,仍失败才打 `otp_send_failed`。 + +**验证码邮件的发信域名**:在 Resend 后台 Domains 里确认发件域名的 SPF、DKIM 是 Verified,DNS 里有一条 DMARC 记录(`_dmarc.<域名>` TXT,至少 `v=DMARC1; p=none`)。上线后用一个新邮箱实收一封验证码,看是否进了垃圾箱。 + ### 日志轮转 diff --git a/deploy/monitor/classify_error_log.py b/deploy/monitor/classify_error_log.py index 5de32ef88..3805571ab 100644 --- a/deploy/monitor/classify_error_log.py +++ b/deploy/monitor/classify_error_log.py @@ -28,8 +28,26 @@ DOCKER = re.compile( r"^(?Pweb|api)-\d+\s+\|\s+" r"(?P\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z) (?P.*)$" ) +ACCESS = re.compile( + r'"(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) (?P/[^ ?"]*)(?:\?[^ "]*)? HTTP/[0-9.]+" (?P\d{3})\b' +) CST = timezone(timedelta(hours=8)) +# Codes that matter at low volume (BUG-2348). A window row is sent once a code +# reaches its own threshold; other codes keep the general error threshold. +# `[ops-signal]` lines carry these codes from the app: one JSON object with +# `errorCode` and optional `route`, never user text. +CODE_THRESHOLDS = { + "otp_send_failed": 3, + "model_spend_alert": 1, + "model_fallback_used": 3, + "provider_error": 3, + "timeout": 5, + "empty_answer": 5, + "http_429": 10, +} +SIGNAL_MARKERS = ("[agent-observability]", "[ops-signal]") + def unsafe(line: str) -> bool: if any(ord(char) > 126 for char in line): @@ -40,6 +58,26 @@ def unsafe(line: str) -> bool: return len(DATE.findall(line)) >= 2 +def access_log_row(line: str) -> tuple[str, str, str] | None: + """An api access-log line counted before the privacy filter. + + Only the path (query dropped) and the status leave the line, and only for + 429 and 5xx, so a birth date in a query string never reaches an alert. + """ + match = FIXTURE.match(line) or DOCKER.match(line) + if not match or match.group("svc") != "api": + return None + access = ACCESS.search(match.group("rest")) + if not access: + return None + status = int(access.group("status")) + if status != 429 and not 500 <= status <= 599: + return None + path = access.group("path") + route = path if ROUTE.match(path) and not DATE.search(path) and not EMAIL.search(path) else "-" + return match.group("ts"), route, str(status) + + def parse_line(line: str) -> tuple[str, str, str] | None: match = FIXTURE.match(line) or DOCKER.match(line) if not match: @@ -60,8 +98,8 @@ def extract_fields(rest: str) -> tuple[str, str, str, int | None]: error_code = "" request_id = "" status: int | None = None - marker = "[agent-observability]" - if marker in rest: + marker = next((item for item in SIGNAL_MARKERS if item in rest), None) + if marker is not None: raw = rest.split(marker, 1)[1].strip() try: payload = json.loads(raw) @@ -99,7 +137,21 @@ def classify(lines: list[str], mode: str, now_text: str, error_threshold: int, f for raw in lines: line = raw.rstrip("\r\n") - if not line or unsafe(line): + if not line: + continue + access = access_log_row(line) + if access is not None: + timestamp, _route, status_text = access + if mode == "daily" and timestamp_cst_date(timestamp) != yesterday: + continue + if status_text == "429": + # Summed across routes: a chart page fans out over many paths. + add(("api", "-", "http_429"), "") + else: + fivexx_counts["api"] = fivexx_counts.get("api", 0) + 1 + fivexx_ids.setdefault("api", []) + continue + if unsafe(line): continue parsed = parse_line(line) if parsed is None: @@ -128,7 +180,8 @@ def classify(lines: list[str], mode: str, now_text: str, error_threshold: int, f # An `alert.` code is already a decision made by the app (BUG-2347 daily # model spend): it is sent on its first occurrence, not after a burst. immediate = key[2].startswith("alert.") - if mode == "window" and count < error_threshold and not immediate: + threshold = CODE_THRESHOLDS.get(key[2], error_threshold) + if mode == "window" and count < threshold and not immediate: continue if count <= 0: continue diff --git a/deploy/monitor/healthcheck-alert.sh b/deploy/monitor/healthcheck-alert.sh index 1d995f47c..c5f4d65b1 100644 --- a/deploy/monitor/healthcheck-alert.sh +++ b/deploy/monitor/healthcheck-alert.sh @@ -189,7 +189,9 @@ PY fi consecutive_failures=0 if [[ "$commit" =~ ^[0-9a-f]{40}$ ]]; then - if [ -n "$last_commit" ] && [ "$commit" != "$last_commit" ] && [ "$commit_alerted" != "$commit" ]; then + # The off-host probe sets JYOTISHA_COMMIT_ALERT=off: every release would + # otherwise alert there, since its runner has no release-window marker. + if [ "${JYOTISHA_COMMIT_ALERT:-on}" != "off" ] && [ -n "$last_commit" ] && [ "$commit" != "$last_commit" ] && [ "$commit_alerted" != "$commit" ]; then if ! release_window_open; then send_alert site /api/health commit_changed 1 - commit_alerted="$commit" diff --git a/deploy/monitor/install-production-monitor.sh b/deploy/monitor/install-production-monitor.sh new file mode 100644 index 000000000..729ad8dbe --- /dev/null +++ b/deploy/monitor/install-production-monitor.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# Install (or re-install) the production host monitors (BUG-2348). Idempotent: +# running it again rewrites the same cron file and leaves .monitor.env alone. +# +# sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh +# sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh --test-alert +# +# What it installs (/etc/cron.d/jyotisha-production-monitor, as root): +# every minute healthcheck-alert.sh --mode all site health (local view), disk 80%, daily backup age +# every 5 min error-digest.sh --window error codes, 5xx, 429, OTP and model signals +# 09:00 Beijing error-digest.sh --daily yesterday's summary +# every 5 min ops-check.sh container restarts/OOM, memory, report queue, new feedback +# The off-host probe is the Gitea workflow monitor-public-health.yml. +# +# Alert channels live in /opt/jyotisha-production/.monitor.env (mode 0600): +# FEISHU_WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/ +# FEISHU_SIGN_SECRET= +# ALERT_EMAIL_TO=[,] +# Email goes through the Resend key and sender already in .env.production. +set -euo pipefail +set +x +umask 077 + +base="${JYOTISHA_PRODUCTION_PATH:-/opt/jyotisha-production}" +cron_file="${JYOTISHA_MONITOR_CRON_FILE:-/etc/cron.d/jyotisha-production-monitor}" +state_dir="${JYOTISHA_MONITOR_STATE_DIR:-/var/lib/jyotisha-monitor}" +monitor_dir="$base/deploy/monitor" +env_file="$base/.monitor.env" + +mode="install" +case "${1:-}" in + "") ;; + --test-alert) mode="test" ;; + *) + echo "usage: install-production-monitor.sh [--test-alert]" >&2 + exit 2 + ;; +esac + +if [ "${JYOTISHA_MONITOR_INSTALL_ALLOW_NONROOT:-0}" != "1" ] && [ "$(id -u)" -ne 0 ]; then + echo "run as root (sudo)" >&2 + exit 1 +fi + +for script in healthcheck-alert.sh error-digest.sh ops-check.sh notify-feishu.sh classify_error_log.py; do + [ -f "$monitor_dir/$script" ] || { + echo "missing $monitor_dir/$script — deploy this release first" >&2 + exit 1 + } +done + +install -d -m 700 "$state_dir" +if [ ! -e "$env_file" ]; then + install -m 600 /dev/null "$env_file" + echo "created empty $env_file (alerts stay in $state_dir/alerts.log until channels are filled in)" +fi +chmod 600 "$env_file" + +if [ "$mode" = "test" ]; then + export JYOTISHA_MONITOR_STATE_DIR="$state_dir" + export JYOTISHA_APP_ENV_FILE="$base/.env.production" + # shellcheck source=notify-feishu.sh + source "$monitor_dir/notify-feishu.sh" + load_monitor_env "$env_file" + channels="" + [ -n "${FEISHU_WEBHOOK_URL:-}" ] && channels="${channels} feishu" + [ -n "${ALERT_EMAIL_TO:-}" ] && channels="${channels} email" + if post_monitor_alert "service=monitor route=- errorCode=monitor_test count=1 requestId=- time=$(date -u +%Y-%m-%dT%H:%M:%SZ)"; then + if [ -n "$channels" ]; then + echo "test alert accepted by:${channels} (a channel that failed printed its own line above)" + else + echo "no channel configured; test alert written to $state_dir/alerts.log only" + fi + else + echo "test alert was not accepted by any channel" >&2 + exit 1 + fi + exit 0 +fi + +command -v sudo >/dev/null 2>&1 || { + echo "sudo is required (the monitors call sudo -n docker)" >&2 + exit 1 +} + +# Cron reads host local time. Put the daily summary at 09:00 Beijing. +offset="$(date +%z)" +sign="${offset:0:1}" +hours=$((10#${offset:1:2})) +[ "$sign" = "-" ] && hours=$((-hours)) +# 09:00 Beijing is 01:00 UTC; local hour = 1 + UTC offset. +daily_hour=$(( (1 + hours + 48) % 24 )) +[ "$((10#${offset:3:2}))" -eq 0 ] || echo "host timezone has a non-hour offset; daily summary runs at the nearest hour" + +tmp="$cron_file.tmp.$$" +cat >"$tmp" <&1 | logger -t jyotisha-monitor +*/5 * * * * root bash $monitor_dir/error-digest.sh --window 2>&1 | logger -t jyotisha-monitor +0 $daily_hour * * * root bash $monitor_dir/error-digest.sh --daily 2>&1 | logger -t jyotisha-monitor +2-59/5 * * * * root bash $monitor_dir/ops-check.sh 2>&1 | logger -t jyotisha-monitor +EOF +chmod 644 "$tmp" +mv "$tmp" "$cron_file" +echo "installed $cron_file (daily summary at host hour $daily_hour = 09:00 Beijing)" +echo "state: $state_dir channels: $env_file" +echo "next: fill in $env_file, then run this script with --test-alert" diff --git a/deploy/monitor/notify-feishu.sh b/deploy/monitor/notify-feishu.sh index 882c684f7..c129119c9 100644 --- a/deploy/monitor/notify-feishu.sh +++ b/deploy/monitor/notify-feishu.sh @@ -1,6 +1,9 @@ #!/usr/bin/env bash # Shared alert sender. Source this file; do not execute it. -# Outbound text is limited to service, route, errorCode, count, requestId, time. +# Alert lines carry only service, route, errorCode, count, requestId, time. +# Delivery: Feishu group bot and/or email through Resend (BUG-2348). Every +# accepted alert is also kept in the local alerts.log. With no channel +# configured the alert stays local. ensure_private_dir() { local dir="$1" @@ -10,6 +13,13 @@ ensure_private_dir() { fi } +monitor_env_value_safe() { + case "$1" in + *[$'\n\r`$"\\']*) return 1 ;; + esac + return 0 +} + load_monitor_env() { local file="$1" local line key value mode @@ -25,15 +35,13 @@ load_monitor_env() { while IFS= read -r line || [ -n "$line" ]; do case "$line" in ""|\#*) continue ;; - FEISHU_WEBHOOK_URL=*|FEISHU_SIGN_SECRET=*) + FEISHU_WEBHOOK_URL=*|FEISHU_SIGN_SECRET=*|ALERT_EMAIL_TO=*|ALERT_EMAIL_FROM=*|RESEND_API_KEY=*) key="${line%%=*}" value="${line#*=}" - case "$value" in - *[$'\n\r`$']*) - echo "monitor env value is unsafe" >&2 - exit 1 - ;; - esac + monitor_env_value_safe "$value" || { + echo "monitor env value is unsafe" >&2 + exit 1 + } printf -v "$key" '%s' "$value" export "$key" ;; @@ -41,6 +49,35 @@ load_monitor_env() { done <"$file" } +# Read only the Resend key and sender from the application env file, never +# printing them. Values already set by the monitor env win. +load_resend_from_app_env() { + local file="${JYOTISHA_APP_ENV_FILE:-/opt/jyotisha-production/.env.production}" + local line key value + [ -f "$file" ] && [ ! -L "$file" ] && [ -r "$file" ] || return 0 + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in + RESEND_API_KEY=*|RESEND_FROM_EMAIL=*) + key="${line%%=*}" + value="${line#*=}" + value="${value%$'\r'}" + case "$value" in + \"*\") value="${value#\"}"; value="${value%\"}" ;; + \'*\') value="${value#\'}"; value="${value%\'}" ;; + esac + monitor_env_value_safe "$value" || continue + if [ "$key" = "RESEND_API_KEY" ] && [ -z "${RESEND_API_KEY:-}" ]; then + RESEND_API_KEY="$value" + export RESEND_API_KEY + elif [ "$key" = "RESEND_FROM_EMAIL" ] && [ -z "${ALERT_EMAIL_FROM:-}" ]; then + ALERT_EMAIL_FROM="$value" + export ALERT_EMAIL_FROM + fi + ;; + esac + done <"$file" +} + feishu_sign() { local timestamp="$1" local secret="$2" @@ -56,60 +93,119 @@ webhook_allowed() { return 1 } +resend_url() { + local url="${JYOTISHA_RESEND_URL:-https://api.resend.com/emails}" + if [[ "$url" == "https://api.resend.com/emails" || "$url" =~ ^http://127\.0\.0\.1:[0-9]{1,5}/emails$ ]]; then + printf '%s' "$url" + return 0 + fi + return 1 +} + +email_recipients_valid() { + local list="$1" + local item count=0 + local IFS=',' + [ -n "$list" ] || return 1 + for item in $list; do + [[ "$item" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || return 1 + count=$((count + 1)) + done + [ "$count" -ge 1 ] && [ "$count" -le 5 ] +} + alert_line_allowed() { local line="$1" [[ "$line" =~ ^service=[a-z0-9_-]+[[:space:]]route=(/|/[A-Za-z0-9/_.-]+|-)[[:space:]]errorCode=[a-z][a-z0-9._-]*[[:space:]]count=[0-9]+[[:space:]]requestId=(-|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(,[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}){0,4})[[:space:]]time=[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$ ]] } -post_monitor_alert() { - local text="$1" - local state_dir line timestamp sign payload_file response_file pending py curl_status code - state_dir="${JYOTISHA_MONITOR_STATE_DIR:-/var/lib/jyotisha-monitor}" - ensure_private_dir "$state_dir" - pending="" +# Fixed Chinese labels so an alert reads on a phone. The label comes from this +# table only; no log text reaches it. +alert_label() { + case "$1" in + health_down) printf '网站打不开(连续探活失败)' ;; + recovered) printf '已恢复' ;; + commit_changed) printf '线上版本变了(不在发版窗口内)' ;; + disk_high) printf '磁盘使用超过 80%%' ;; + backup_stale) printf '每日备份超过 36 小时没有核对成功' ;; + container_restarted) printf '容器自己重启了' ;; + container_oom) printf '容器因内存不够被杀' ;; + memory_high) printf '服务器可用内存不足(数字是已用百分比)' ;; + report_queue_stuck) printf '报告排队太久没开始(数字是等待秒数)' ;; + feedback_new) printf '有新的用户反馈,去 /admin/feedback 看' ;; + otp_send_failed) printf '验证码邮件发不出去' ;; + model_spend_alert) printf '今天的模型花费超过设定值' ;; + model_fallback_used) printf '默认模型失败,已切到备用模型' ;; + provider_error) printf '模型供应商调用失败' ;; + timeout) printf '回答超时' ;; + empty_answer) printf '模型回答为空' ;; + http_429) printf '计算服务限流(429)' ;; + http_5xx) printf '服务器 5xx 错误' ;; + daily_summary) printf '昨日错误汇总' ;; + monitor_test) printf '测试告警,收到说明这个通道正常' ;; + *) printf '异常' ;; + esac +} + +render_alert_text() { + local pending="$1" + local line code out + out="Jyotisha 生产告警" while IFS= read -r line || [ -n "$line" ]; do [ -n "$line" ] || continue - alert_line_allowed "$line" || { - echo "alert text has a field that is not allowed" >&2 - exit 1 - } - pending="${pending}${line}"$'\n' - done <<<"$text" - [ -n "$pending" ] || return 0 - pending="${pending%$'\n'}" + code="" + if [[ "$line" =~ errorCode=([a-z][a-z0-9._-]*) ]]; then + code="${BASH_REMATCH[1]}" + fi + out="${out}"$'\n'"- $(alert_label "$code")"$'\n'" ${line}" + done <<<"$pending" + printf '%s' "$out" +} - if [ -z "${FEISHU_WEBHOOK_URL:-}" ]; then - printf '%s\n' "$pending" >>"$state_dir/alerts.log" - return 0 +monitor_python() { + if [ -n "${JYOTISHA_PYTHON:-}" ]; then + printf '%s' "$JYOTISHA_PYTHON" + elif command -v python3 >/dev/null 2>&1; then + printf 'python3' + else + printf 'python' fi - webhook_allowed "$FEISHU_WEBHOOK_URL" || { - printf '%s\n' "service=monitor route=- errorCode=webhook_rejected count=1 requestId=- time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >>"$state_dir/alerts.log" - return 0 - } +} +send_feishu_alert() { + local text="$1" + local payload_file response_file timestamp sign py curl_status code mode + webhook_allowed "$FEISHU_WEBHOOK_URL" || { + echo "feishu webhook url is not allowed" >&2 + return 1 + } + py="$(monitor_python)" payload_file="$(mktemp)" response_file="$(mktemp)" if [ "$(uname -s)" = "Linux" ]; then chmod 600 "$payload_file" "$response_file" fi + mode="plain" + timestamp="" + sign="" if [ -n "${FEISHU_SIGN_SECRET:-}" ]; then + mode="signed" timestamp="$(date +%s)" sign="$(feishu_sign "$timestamp" "$FEISHU_SIGN_SECRET")" - FEISHU_ALERT_TEXT="$text" FEISHU_ALERT_TIMESTAMP="$timestamp" FEISHU_ALERT_SIGN="$sign" \ - python_write_payload "$payload_file" signed - else - FEISHU_ALERT_TEXT="$text" python_write_payload "$payload_file" plain - fi - if [ -n "${JYOTISHA_PYTHON:-}" ]; then - py="$JYOTISHA_PYTHON" - elif command -v python3 >/dev/null 2>&1; then - py="python3" - else - py="python" fi + FEISHU_ALERT_TEXT="$text" FEISHU_ALERT_TIMESTAMP="$timestamp" FEISHU_ALERT_SIGN="$sign" \ + "$py" - "$payload_file" "$mode" <<'PY' +import json, os, sys +payload = {"msg_type": "text", "content": {"text": os.environ["FEISHU_ALERT_TEXT"]}} +if sys.argv[2] == "signed": + payload["timestamp"] = os.environ["FEISHU_ALERT_TIMESTAMP"] + payload["sign"] = os.environ["FEISHU_ALERT_SIGN"] +with open(sys.argv[1], "w", encoding="utf-8", newline="\n") as handle: + json.dump(payload, handle, ensure_ascii=False, separators=(",", ":")) +PY curl_status=0 curl --silent --show-error --fail --connect-timeout 10 --max-time 10 \ - -H 'Content-Type: application/json' \ + -H 'Content-Type: application/json; charset=utf-8' \ -H 'Connection: close' \ --data-binary @"$payload_file" \ -o "$response_file" \ @@ -117,18 +213,12 @@ post_monitor_alert() { code="" if [ "$curl_status" -eq 0 ]; then code="$("$py" - "$response_file" <<'PY' -import json -import sys - +import json, sys try: payload = json.load(open(sys.argv[1], encoding="utf-8")) except Exception: - print("") - raise SystemExit(0) -if isinstance(payload, dict) and payload.get("code") == 0: - print("0") -else: - print("") + payload = None +print("0" if isinstance(payload, dict) and payload.get("code") == 0 else "") PY )" code="$(printf '%s' "$code" | tr -d '\r')" @@ -138,33 +228,121 @@ PY echo "feishu webhook was not accepted" >&2 return 1 fi + return 0 +} + +send_email_alert() { + local text="$1" + local subject="$2" + local url payload_file response_file header_file py curl_status http_code ok + url="$(resend_url)" || { + echo "resend url is not allowed" >&2 + return 1 + } + email_recipients_valid "$ALERT_EMAIL_TO" || { + echo "alert email recipients are invalid" >&2 + return 1 + } + [ -n "${RESEND_API_KEY:-}" ] && [ -n "${ALERT_EMAIL_FROM:-}" ] || { + echo "resend key or sender is missing" >&2 + return 1 + } + py="$(monitor_python)" + payload_file="$(mktemp)" + response_file="$(mktemp)" + header_file="$(mktemp)" + if [ "$(uname -s)" = "Linux" ]; then + chmod 600 "$payload_file" "$response_file" "$header_file" + fi + ALERT_TEXT="$text" ALERT_SUBJECT="$subject" "$py" - "$payload_file" <<'PY' +import json, os, sys +payload = { + "from": os.environ["ALERT_EMAIL_FROM"], + "to": [item for item in os.environ["ALERT_EMAIL_TO"].split(",") if item], + "subject": os.environ["ALERT_SUBJECT"], + "text": os.environ["ALERT_TEXT"], +} +with open(sys.argv[1], "w", encoding="utf-8", newline="\n") as handle: + json.dump(payload, handle, ensure_ascii=False, separators=(",", ":")) +PY + # The key goes through a header file so it never shows in the process list. + printf 'Authorization: Bearer %s\n' "$RESEND_API_KEY" >"$header_file" + curl_status=0 + http_code="$(curl --silent --show-error --connect-timeout 10 --max-time 15 \ + -H 'Content-Type: application/json; charset=utf-8' \ + -H @"$header_file" \ + --data-binary @"$payload_file" \ + -o "$response_file" -w '%{http_code}' \ + "$url")" || curl_status=$? + ok="" + if [ "$curl_status" -eq 0 ] && [[ "$http_code" =~ ^2[0-9][0-9]$ ]]; then + ok="$("$py" - "$response_file" <<'PY' +import json, sys +try: + payload = json.load(open(sys.argv[1], encoding="utf-8")) +except Exception: + payload = None +print("1" if isinstance(payload, dict) and isinstance(payload.get("id"), str) and payload["id"] else "") +PY +)" + ok="$(printf '%s' "$ok" | tr -d '\r')" + fi + rm -f -- "$payload_file" "$response_file" "$header_file" + if [ "$ok" != "1" ]; then + echo "alert email was not accepted" >&2 + return 1 + fi + return 0 +} + +post_monitor_alert() { + local text="$1" + local state_dir line pending human first_code subject total feishu_on email_on delivered + state_dir="${JYOTISHA_MONITOR_STATE_DIR:-/var/lib/jyotisha-monitor}" + ensure_private_dir "$state_dir" + pending="" + total=0 + first_code="" + while IFS= read -r line || [ -n "$line" ]; do + [ -n "$line" ] || continue + alert_line_allowed "$line" || { + echo "alert text has a field that is not allowed" >&2 + exit 1 + } + if [ -z "$first_code" ] && [[ "$line" =~ errorCode=([a-z][a-z0-9._-]*) ]]; then + first_code="${BASH_REMATCH[1]}" + fi + total=$((total + 1)) + pending="${pending}${line}"$'\n' + done <<<"$text" + [ -n "$pending" ] || return 0 + pending="${pending%$'\n'}" + + load_resend_from_app_env + feishu_on=0 + email_on=0 + [ -n "${FEISHU_WEBHOOK_URL:-}" ] && feishu_on=1 + [ -n "${ALERT_EMAIL_TO:-}" ] && email_on=1 + if [ "$feishu_on" -eq 0 ] && [ "$email_on" -eq 0 ]; then + printf '%s\n' "$pending" >>"$state_dir/alerts.log" + return 0 + fi + + human="$(render_alert_text "$pending")" + subject="Jyotisha 告警:$(alert_label "$first_code")" + if [ "$total" -gt 1 ]; then + subject="${subject} 等 ${total} 条" + fi + delivered=0 + if [ "$feishu_on" -eq 1 ] && send_feishu_alert "$human"; then + delivered=1 + fi + if [ "$email_on" -eq 1 ] && send_email_alert "$human" "$subject"; then + delivered=1 + fi + if [ "$delivered" -eq 0 ]; then + echo "no alert channel accepted the alert" >&2 + return 1 + fi printf '%s\n' "$pending" >>"$state_dir/alerts.log" } - -python_write_payload() { - local destination="$1" - local mode="$2" - local py - export FEISHU_ALERT_TEXT FEISHU_ALERT_TIMESTAMP FEISHU_ALERT_SIGN - if [ -n "${JYOTISHA_PYTHON:-}" ]; then - py="$JYOTISHA_PYTHON" - elif command -v python3 >/dev/null 2>&1; then - py="python3" - else - py="python" - fi - "$py" - "$destination" "$mode" <<'PY' -import json -import os -import sys - -destination, mode = sys.argv[1], sys.argv[2] -text = os.environ["FEISHU_ALERT_TEXT"] -payload = {"msg_type": "text", "content": {"text": text}} -if mode == "signed": - payload["timestamp"] = os.environ["FEISHU_ALERT_TIMESTAMP"] - payload["sign"] = os.environ["FEISHU_ALERT_SIGN"] -with open(destination, "w", encoding="utf-8", newline="\n") as handle: - json.dump(payload, handle, ensure_ascii=True, separators=(",", ":")) -PY -} diff --git a/deploy/monitor/ops-check.sh b/deploy/monitor/ops-check.sh new file mode 100644 index 000000000..19b885dd1 --- /dev/null +++ b/deploy/monitor/ops-check.sh @@ -0,0 +1,198 @@ +#!/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 diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index c89025078..855d12c2d 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -32011,3 +32011,25 @@ - 负责人要做的(后台):在「模型」里发布一个其他供应商的模型,并把默认模型的「回退模型」填成它;每个供应商至少放两把密钥;在各供应商自己的后台设花费上限;需要时在服务器 `.env.production` 设 `MODEL_DAILY_SPEND_ALERT_USD`;飞书告警要等监控装好(#350)。 - 关联记录:#352、#350(监控与飞书)、BUG-1922(多密钥)、BUG-2345。 - 修复版本:分支 `claude/model-fallback-2347`(本地提交,未推送)。 + +## BUG-2348 | 生产出事没人知道:探活、容器重启、内存、报告排队、验证码发信失败、模型花费、新反馈都没有告警,告警也只能发飞书(#350、#354) + +- 状态:fixed-pending-verify(本地提交,未推送;要发版后在主机上运行安装脚本、填好告警通道、发一条测试告警才算完成)。 +- 现象:工单 #350、#354 只读核对:仓库里有 `healthcheck-alert.sh`、`error-digest.sh`,但主机上没有统一的安装办法;服务器整台不可达、容器自己重启或被 OOM 杀、主机内存不足、报告排队卡住、验证码邮件大面积发不出、模型调用失败、计算服务 429、用户提交反馈,这些都不会告警。告警只能发飞书,负责人要求飞书和邮件都要(2026-11-25)。 +- 触发条件:任何上面列的故障;访问量小时错误次数也到不了通用阈值。 +- 根因:监控脚本只覆盖了磁盘、备份、日志里的通用错误码,没有低频关键信号的单独阈值;验证码发信失败只抛错、没有可被汇总的日志;发信不重试;告警通道只有飞书;没有安装脚本,也没有服务器之外的探活。 +- 修复: + - `deploy/monitor/notify-feishu.sh`:加邮件通道(Resend HTTP API;密钥只从 `.env.production` 读 `RESEND_API_KEY` 和 `RESEND_FROM_EMAIL` 两行,经临时头文件传给 curl,不进命令行也不打印);飞书和邮件都配时两边都发,任一接收成功就算发出,都失败不记成已发送;正文加固定中文说明(对照表里的固定文字,日志文字不进告警)。 + - `deploy/monitor/classify_error_log.py`:按错误码单独定阈值(验证码发信失败 3、花费超标 1、切备用模型 3、供应商错误 3、超时和空回答 5、429 合计 10);认 `[ops-signal]` 行;从计算服务的访问日志数 429 和 5xx,只取路径和状态码,查询串丢掉,生日日期和邮箱进不了告警。 + - 新 `deploy/monitor/ops-check.sh`(主机每 5 分钟):容器重启次数增加或被 OOM 杀;主机内存已用 ≥90%;报告排队最久的任务等待 ≥10 分钟(`personal_report_jobs`,所有报告类型共用);新的用户反馈(只发条数,不带内容和账号)。这几类“开一次、恢复一次”。 + - 新 `frontend/src/lib/ops-signal.ts`:`[ops-signal] {"errorCode":…,"route":…,"upstream":…}`,错误码是封闭列表(`otp_send_failed`、`model_spend_alert`、`model_fallback_used`)。 + - 验证码发信(`resend-email-otp-sender.ts`):网络错误、429、5xx 用同一个幂等键重试一次(不会发两封);4xx 不重试;最终失败打一行 `otp_send_failed`,不带邮箱和供应商原文。 + - `healthcheck-alert.sh`:`JYOTISHA_COMMIT_ALERT=off` 时版本变化不告警(主机和 runner 上都关,否则每次发版都报)。 + - 新 `deploy/monitor/install-production-monitor.sh`:可重复运行,写 `/etc/cron.d/jyotisha-production-monitor`(每分钟本机探活 + 磁盘 + 备份;每 5 分钟错误汇总和主机检查;北京时间 09:00 日报,按主机时区换算),不覆盖已有的 `.monitor.env`;`--test-alert` 发一条测试告警。 + - 新 `.gitea/workflows/monitor-public-health.yml`:runner 上每 5 分钟访问三次公网 `/api/health`,服务器之外的探活;通道走仓库 Actions 密钥。 + - `deploy/README.md`「告警装在哪」整节改写,含 SPF / DKIM / DMARC 的核对办法。 +- 验证:新增 `tests/test_monitor_alerts_2348.py`(9 条,已加入快检列表):邮件通道的请求内容和中文标题、密钥不出现在正文和输出里;飞书失败邮件成功仍算发出、两边都失败不记录;低频信号阈值;429/5xx 访问日志计数且不带查询串;主机检查四类告警的开和恢复;安装脚本可重复、日报时间按时区换算、测试告警;探活工作流。`frontend/tests/identity-email-sender.test.ts` 加 3 条(5xx 重试一次同一个幂等键、4xx 不重试并发信号、两次网络失败只发一次信号),新 `frontend/tests/ops-signal-2348.test.ts`(4 条)。`tests/test_beta_safety_net.py` 原有 20 条照常通过。tsc 无错,ESLint 0 错误。 +- 防复发:上面的测试;通道和阈值都写在 README 一处。 +- 未完成 / 需要人做:发版后在生产主机运行安装脚本;负责人提供飞书群机器人 webhook 和收告警的邮箱;runner 的 Actions 密钥;在 Resend 后台确认发件域名的 SPF / DKIM 和 DMARC;BUG-2347 的花费告警要用 `logOpsSignal({ errorCode: "model_spend_alert" })` 打这一行才会被汇总。 +- 关联记录:BUG-1361(站点打不开或磁盘过满时没有告警)、BUG-2131(异地备份告警走同一个发送器)、BUG-2345(连接数)、BUG-2347(模型备用与花费)、#350、#354、#357。 +- 修复版本:分支 `claude/monitor-2348`(本地提交,未推送)。 diff --git a/frontend/src/lib/ops-signal.ts b/frontend/src/lib/ops-signal.ts new file mode 100644 index 000000000..7e8a146ab --- /dev/null +++ b/frontend/src/lib/ops-signal.ts @@ -0,0 +1,68 @@ +/** + * Operational signals for the host monitor (BUG-2348). + * + * One line per event: `[ops-signal] {"errorCode":"…","route":"…"}`. The + * monitor (`deploy/monitor/classify_error_log.py`) counts these per 5-minute + * window and alerts when a code reaches its own threshold. Fields are closed: + * a machine code, an optional route, an optional upstream class. Never an + * email address, user id, message text or provider error text. + */ + +export const OPS_SIGNAL_MARKER = "[ops-signal]"; + +export const opsSignalCodes = [ + "otp_send_failed", + "model_spend_alert", + "model_fallback_used", +] as const; + +export type OpsSignalCode = (typeof opsSignalCodes)[number]; + +export type OpsSignalUpstream = "network" | "http_4xx" | "http_429" | "http_5xx"; + +export type OpsSignal = Readonly<{ + errorCode: OpsSignalCode; + route?: string; + upstream?: OpsSignalUpstream; +}>; + +const routePattern = /^\/[A-Za-z0-9/_.-]{0,120}$/; +const knownCodes = new Set(opsSignalCodes); +const knownUpstreams = new Set(["network", "http_4xx", "http_429", "http_5xx"]); + +export function formatOpsSignal(signal: OpsSignal): string | null { + if (!knownCodes.has(signal.errorCode)) return null; + const payload: Record = { errorCode: signal.errorCode }; + if (signal.route !== undefined) { + if (!routePattern.test(signal.route)) return null; + payload.route = signal.route; + } + if (signal.upstream !== undefined) { + if (!knownUpstreams.has(signal.upstream)) return null; + payload.upstream = signal.upstream; + } + return `${OPS_SIGNAL_MARKER} ${JSON.stringify(payload)}`; +} + +export type OpsSignalSink = (line: string) => void; + +const consoleSink: OpsSignalSink = (line) => { + console.warn(line); +}; + +export function logOpsSignal(signal: OpsSignal, sink: OpsSignalSink = consoleSink): void { + const line = formatOpsSignal(signal); + if (line === null) return; + try { + sink(line); + } catch { + // Logging must never change the business response. + } +} + +/** Upstream class from an HTTP status, for `upstream`. */ +export function upstreamFromStatus(status: number): OpsSignalUpstream { + if (status === 429) return "http_429"; + if (status >= 500) return "http_5xx"; + return "http_4xx"; +} diff --git a/frontend/src/modules/identity/email/resend-email-otp-sender.ts b/frontend/src/modules/identity/email/resend-email-otp-sender.ts index c3a27b404..ccd28eef2 100644 --- a/frontend/src/modules/identity/email/resend-email-otp-sender.ts +++ b/frontend/src/modules/identity/email/resend-email-otp-sender.ts @@ -4,6 +4,12 @@ import type { } from "../contracts.ts"; import { legalEntityValue } from "../../../lib/legal-entity.ts"; import { buildOtpEmail } from "./otp-email-template.ts"; +import { + logOpsSignal, + upstreamFromStatus, + type OpsSignal, + type OpsSignalUpstream, +} from "../../../lib/ops-signal.ts"; const resendEndpoint = "https://api.resend.com/emails"; const safeDeliveryError = "OTP email delivery failed"; @@ -12,17 +18,30 @@ export interface ResendEmailOtpSenderOptions { apiKey: string; from: string; fetchImpl?: typeof fetch; + /** Wait before the single retry; tests pass 0. */ + retryDelayMs?: number; + /** Where the failure signal goes; defaults to the console line the host monitor reads. */ + signal?: (signal: OpsSignal) => void; } +// BUG-2348: a network error, 429 or 5xx is retried once with the same +// idempotency key, so Resend never sends two codes. A final failure writes one +// `otp_send_failed` signal (no address, no provider text) for the monitor. +const retryable = (upstream: OpsSignalUpstream) => upstream !== "http_4xx"; + export class ResendEmailOtpSender implements EmailOtpSender { private readonly apiKey: string; private readonly from: string; private readonly fetchImpl: typeof fetch; + private readonly retryDelayMs: number; + private readonly signal: (signal: OpsSignal) => void; constructor(options: ResendEmailOtpSenderOptions) { this.apiKey = options.apiKey; this.from = options.from; this.fetchImpl = options.fetchImpl ?? fetch; + this.retryDelayMs = Math.max(0, options.retryDelayMs ?? 800); + this.signal = options.signal ?? ((signal) => logOpsSignal(signal)); } async send(message: EmailOtpMessage): Promise { @@ -33,27 +52,37 @@ export class ResendEmailOtpSender implements EmailOtpSender { legalEntityValue("contactEmail"), ); - try { - const response = await this.fetchImpl(resendEndpoint, { - method: "POST", - headers: { - Authorization: `Bearer ${this.apiKey}`, - "Content-Type": "application/json", - "Idempotency-Key": message.idempotencyKey, - "User-Agent": "jyotisha-identity/1.0", - }, - body: JSON.stringify({ - from: this.from, - to: [message.email], - subject, - text, - html, - }), - }); - - if (!response.ok) throw new Error(safeDeliveryError); - } catch { - throw new Error(safeDeliveryError); + const body = JSON.stringify({ + from: this.from, + to: [message.email], + subject, + text, + html, + }); + let upstream: OpsSignalUpstream = "network"; + for (let attempt = 0; attempt < 2; attempt += 1) { + if (attempt > 0 && this.retryDelayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, this.retryDelayMs)); + } + try { + const response = await this.fetchImpl(resendEndpoint, { + method: "POST", + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + "Idempotency-Key": message.idempotencyKey, + "User-Agent": "jyotisha-identity/1.0", + }, + body, + }); + if (response.ok) return; + upstream = upstreamFromStatus(response.status); + } catch { + upstream = "network"; + } + if (!retryable(upstream)) break; } + this.signal({ errorCode: "otp_send_failed", route: "/api/auth/email-otp", upstream }); + throw new Error(safeDeliveryError); } } diff --git a/frontend/tests/identity-email-sender.test.ts b/frontend/tests/identity-email-sender.test.ts index b09cd2a2c..edb7afe76 100644 --- a/frontend/tests/identity-email-sender.test.ts +++ b/frontend/tests/identity-email-sender.test.ts @@ -204,3 +204,66 @@ test("BUG-2271: the email's 5 minutes matches the OTP lifetime", () => { const options = createEmailOtpOptions(new FakeEmailOtpSender(), "secret", true); assert.equal(options.expiresIn, OTP_EMAIL_VALID_MINUTES * 60); }); + +// BUG-2348: one retry with the same idempotency key, then one closed signal. +test("Resend OTP sender retries a 5xx once with the same idempotency key", async () => { + const keys: Array = []; + const signals: unknown[] = []; + let calls = 0; + const sender = new ResendEmailOtpSender({ + apiKey: "re_test_secret_value", + from: "Jyotisha ", + retryDelayMs: 0, + signal: (signal) => signals.push(signal), + fetchImpl: async (_input, init) => { + calls += 1; + keys.push(new Headers(init?.headers).get("idempotency-key")); + return calls === 1 ? new Response("down", { status: 503 }) : Response.json({ id: "email_123" }); + }, + }); + + await sender.send(message); + + assert.equal(calls, 2); + assert.deepEqual(keys, [message.idempotencyKey, message.idempotencyKey]); + assert.deepEqual(signals, []); +}); + +test("Resend OTP sender does not retry a 4xx and signals the failure without the address", async () => { + const signals: unknown[] = []; + let calls = 0; + const sender = new ResendEmailOtpSender({ + apiKey: "re_test_secret_value", + from: "Jyotisha ", + retryDelayMs: 0, + signal: (signal) => signals.push(signal), + fetchImpl: async () => { + calls += 1; + return new Response("invalid", { status: 422 }); + }, + }); + + await assert.rejects(sender.send(message), new Error("OTP email delivery failed")); + assert.equal(calls, 1); + assert.deepEqual(signals, [{ errorCode: "otp_send_failed", route: "/api/auth/email-otp", upstream: "http_4xx" }]); + assert.doesNotMatch(JSON.stringify(signals), /example\.com|123456/); +}); + +test("Resend OTP sender signals once after two network failures", async () => { + const signals: unknown[] = []; + let calls = 0; + const sender = new ResendEmailOtpSender({ + apiKey: "re_test_secret_value", + from: "Jyotisha ", + retryDelayMs: 0, + signal: (signal) => signals.push(signal), + fetchImpl: async () => { + calls += 1; + throw new Error("socket includes recipient person@example.com"); + }, + }); + + await assert.rejects(sender.send(message), new Error("OTP email delivery failed")); + assert.equal(calls, 2); + assert.deepEqual(signals, [{ errorCode: "otp_send_failed", route: "/api/auth/email-otp", upstream: "network" }]); +}); diff --git a/frontend/tests/ops-signal-2348.test.ts b/frontend/tests/ops-signal-2348.test.ts new file mode 100644 index 000000000..7d430ffb2 --- /dev/null +++ b/frontend/tests/ops-signal-2348.test.ts @@ -0,0 +1,31 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { formatOpsSignal, logOpsSignal, upstreamFromStatus } from "../src/lib/ops-signal.ts"; + +// BUG-2348: the host monitor parses `[ops-signal] {json}`; the fields are closed. +test("ops signal line is the marker plus a closed JSON object", () => { + assert.equal( + formatOpsSignal({ errorCode: "otp_send_failed", route: "/api/auth/email-otp", upstream: "http_5xx" }), + '[ops-signal] {"errorCode":"otp_send_failed","route":"/api/auth/email-otp","upstream":"http_5xx"}', + ); + assert.equal(formatOpsSignal({ errorCode: "model_spend_alert" }), '[ops-signal] {"errorCode":"model_spend_alert"}'); +}); + +test("ops signal refuses unknown codes and unsafe routes", () => { + assert.equal(formatOpsSignal({ errorCode: "anything" as never }), null); + assert.equal(formatOpsSignal({ errorCode: "otp_send_failed", route: "/x?email=a@b.co" }), null); + const lines: string[] = []; + logOpsSignal({ errorCode: "otp_send_failed", route: "not a route" }, (line) => lines.push(line)); + assert.deepEqual(lines, []); +}); + +test("ops signal never throws when the sink fails", () => { + assert.doesNotThrow(() => logOpsSignal({ errorCode: "otp_send_failed" }, () => { throw new Error("sink"); })); +}); + +test("upstream class from status", () => { + assert.equal(upstreamFromStatus(429), "http_429"); + assert.equal(upstreamFromStatus(503), "http_5xx"); + assert.equal(upstreamFromStatus(422), "http_4xx"); +}); diff --git a/scripts/run_quality_gate.py b/scripts/run_quality_gate.py index f67b10988..cb4233c6c 100644 --- a/scripts/run_quality_gate.py +++ b/scripts/run_quality_gate.py @@ -168,6 +168,7 @@ CORE_PYTEST_TARGETS = [ # Closed-beta safety net. The Linux 0600 monitor-env check only fails in # release-quality-gate unless this file is on the staging quick list. "tests/test_beta_safety_net.py", + "tests/test_monitor_alerts_2348.py", # Summary lines by default; failure keeps the last 200 lines and a full log (BUG-1230). "tests/test_run_quality_gate_output.py", "tests/test_upstream_git_import_b9a0ef8f.py", diff --git a/tests/test_monitor_alerts_2348.py b/tests/test_monitor_alerts_2348.py new file mode 100644 index 000000000..9f5f87c6f --- /dev/null +++ b/tests/test_monitor_alerts_2348.py @@ -0,0 +1,350 @@ +"""BUG-2348: alert channels, low-volume signals, host checks, installer. Fixtures are fictional.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from http.server import BaseHTTPRequestHandler +from pathlib import Path + +from tests.test_beta_safety_net import ( + BASH, + DIGEST_SCRIPT, + HEALTH_SCRIPT, + ROOT, + HealthHandler, + HookHandler, + alert_lines, + bash_path, + run_bash, + serve, + uuid, + write_text, +) + +MONITOR = ROOT / "deploy" / "monitor" +OPS_SCRIPT = MONITOR / "ops-check.sh" +INSTALL_SCRIPT = MONITOR / "install-production-monitor.sh" +PROBE_WORKFLOW = ROOT / ".gitea" / "workflows" / "monitor-public-health.yml" +FAKE_KEY = "re_fixture_key_should_not_leak" + + +class ResendHandler(BaseHTTPRequestHandler): + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length", "0")) + body = self.rfile.read(length) + self.server.requests.append((self.path, dict(self.headers), body)) + status = int(getattr(self.server, "status", 200)) + reply = json.dumps({"id": "email_fixture"} if status == 200 else {"message": "no"}).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(reply))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(reply) + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 + return + + +def monitor_env(tmp_path: Path, lines: list[str]) -> Path: + env_file = tmp_path / "monitor.env" + write_text(env_file, "".join(f"{line}\n" for line in lines)) + os.chmod(env_file, 0o600) + return env_file + + +def app_env(tmp_path: Path) -> Path: + path = tmp_path / "app.env" + write_text(path, f'RESEND_API_KEY="{FAKE_KEY}"\nRESEND_FROM_EMAIL=Jyotisha \nOTHER_SECRET=nope\n') + return path + + +def three_health_failures(env: dict[str, str]) -> subprocess.CompletedProcess[str]: + result = None + for _ in range(3): + result = run_bash(HEALTH_SCRIPT, env, ["--mode", "health"]) + assert result is not None + return result + + +def test_email_channel_sends_readable_chinese_alert_without_leaking_the_key(tmp_path: Path) -> None: + resend, _thread = serve(ResendHandler) + resend.requests = [] + health, _thread = serve(HealthHandler) + health.kind = "500" + state = tmp_path / "state" + env_file = monitor_env(tmp_path, ["ALERT_EMAIL_TO=owner@example.test"]) + env = { + "JYOTISHA_MONITOR_STATE_DIR": bash_path(state), + "JYOTISHA_MONITOR_ENV": bash_path(env_file), + "JYOTISHA_APP_ENV_FILE": bash_path(app_env(tmp_path)), + "JYOTISHA_RESEND_URL": f"http://127.0.0.1:{resend.server_address[1]}/emails", + "JYOTISHA_HEALTH_URL": f"http://127.0.0.1:{health.server_address[1]}/health", + "JYOTISHA_HEALTH_TIMEOUT": "2", + } + try: + completed = three_health_failures(env) + assert completed.returncode == 0, completed.stderr + assert len(resend.requests) == 1 + path, headers, body = resend.requests[0] + assert path == "/emails" + lowered = {key.lower(): value for key, value in headers.items()} + assert lowered["authorization"] == f"Bearer {FAKE_KEY}" + payload = json.loads(body.decode("utf-8")) + assert set(payload) == {"from", "to", "subject", "text"} + assert payload["to"] == ["owner@example.test"] + assert payload["from"] == "Jyotisha " + assert payload["subject"] == "Jyotisha 告警:网站打不开(连续探活失败)" + assert "errorCode=health_down" in payload["text"] + assert FAKE_KEY not in payload["text"] + assert FAKE_KEY not in completed.stdout + completed.stderr + assert len(alert_lines(state)) == 1 + finally: + resend.shutdown() + health.shutdown() + + +def test_one_accepting_channel_is_enough_and_both_receive_the_alert(tmp_path: Path) -> None: + resend, _thread = serve(ResendHandler) + resend.requests = [] + hook, _thread = serve(HookHandler) + hook.bodies = [] + hook.feishu_code = 19001 + health, _thread = serve(HealthHandler) + health.kind = "500" + state = tmp_path / "state" + env_file = monitor_env( + tmp_path, + [f"FEISHU_WEBHOOK_URL=http://127.0.0.1:{hook.server_address[1]}/hook", "ALERT_EMAIL_TO=owner@example.test"], + ) + env = { + "JYOTISHA_MONITOR_STATE_DIR": bash_path(state), + "JYOTISHA_MONITOR_ENV": bash_path(env_file), + "JYOTISHA_APP_ENV_FILE": bash_path(app_env(tmp_path)), + "JYOTISHA_RESEND_URL": f"http://127.0.0.1:{resend.server_address[1]}/emails", + "JYOTISHA_HEALTH_URL": f"http://127.0.0.1:{health.server_address[1]}/health", + "JYOTISHA_HEALTH_TIMEOUT": "2", + } + try: + completed = three_health_failures(env) + assert completed.returncode == 0, completed.stderr + assert len(hook.bodies) == 1 + feishu_text = json.loads(hook.bodies[0].decode("utf-8"))["content"]["text"] + assert feishu_text.startswith("Jyotisha 生产告警") + assert "网站打不开" in feishu_text + assert len(resend.requests) == 1 + assert len(alert_lines(state)) == 1 + + resend.status = 500 + state_b = tmp_path / "state-b" + rejected = three_health_failures({**env, "JYOTISHA_MONITOR_STATE_DIR": bash_path(state_b)}) + assert rejected.returncode != 0 + assert alert_lines(state_b) == [] + finally: + resend.shutdown() + hook.shutdown() + health.shutdown() + + +def run_digest(tmp_path: Path, name: str, lines: list[str]) -> list[str]: + fixture = tmp_path / f"{name}.txt" + write_text(fixture, "\n".join(lines) + "\n") + state = tmp_path / f"state-{name}" + completed = run_bash( + DIGEST_SCRIPT, + { + "JYOTISHA_MONITOR_STATE_DIR": bash_path(state), + "JYOTISHA_MONITOR_ENV": bash_path(tmp_path / "missing.env"), + "JYOTISHA_LOG_FIXTURE": bash_path(fixture), + "JYOTISHA_NOW": "2026-10-15T01:00:00Z", + }, + ["--window"], + ) + assert completed.returncode == 0, completed.stderr + return alert_lines(state) + + +def signal(index: int, code: str, route: str = "/api/auth/email-otp") -> str: + return f"2026-10-15T00:00:{index:02d}Z web [ops-signal] {json.dumps({'errorCode': code, 'route': route, 'upstream': 'http_5xx'})}" + + +def test_low_volume_signals_have_their_own_thresholds(tmp_path: Path) -> None: + assert run_digest(tmp_path, "otp2", [signal(i, "otp_send_failed") for i in range(2)]) == [] + rows = run_digest(tmp_path, "otp3", [signal(i, "otp_send_failed") for i in range(3)]) + assert len(rows) == 1 + assert "errorCode=otp_send_failed" in rows[0] + assert "route=/api/auth/email-otp" in rows[0] + assert "count=3" in rows[0] + spend = run_digest(tmp_path, "spend", [f"2026-10-15T00:00:01Z web [ops-signal] {json.dumps({'errorCode': 'model_spend_alert'})}"]) + assert len(spend) == 1 and "errorCode=model_spend_alert" in spend[0] + provider = run_digest( + tmp_path, + "provider", + [f"2026-10-15T00:00:{i:02d}Z web [agent-observability] {json.dumps({'requestId': uuid(i), 'errorCode': 'provider_error'})}" for i in range(1, 4)], + ) + assert len(provider) == 1 and "errorCode=provider_error" in provider[0] + + +def test_api_access_log_429_and_5xx_are_counted_without_the_query(tmp_path: Path) -> None: + limited = [ + f'api-1 | 2026-10-15T00:00:{i:02d}.123Z 172.18.0.3 - - [15/Oct/2026 00:00:{i:02d}] "POST /api/chart{i % 3} HTTP/1.1" 429 -' + for i in range(10) + ] + rows = run_digest(tmp_path, "429", limited) + assert len(rows) == 1 + assert "errorCode=http_429" in rows[0] + assert "route=- " in rows[0] + assert "count=10" in rows[0] + assert run_digest(tmp_path, "429-few", limited[:9]) == [] + failing = [ + f'api-1 | 2026-10-15T00:01:{i:02d}Z 172.18.0.3 - - [15/Oct/2026 00:01:{i:02d}] "GET /api/chart?birth=1990-01-02&email=a@example.test HTTP/1.1" 500 -' + for i in range(20) + ] + rows = run_digest(tmp_path, "500", failing) + joined = "\n".join(rows) + assert "errorCode=http_5xx" in joined and "count=20" in joined + assert "1990-01-02" not in joined and "example.test" not in joined + ok_lines = [f'api-1 | 2026-10-15T00:02:{i:02d}Z x - - [d] "GET /api/health HTTP/1.1" 200 -' for i in range(30)] + assert run_digest(tmp_path, "200", ok_lines) == [] + + +FAKE_DOCKER = r"""#!/usr/bin/env bash +case "$1" in + ps) printf '%s\n' "${FAKE_IDS:-}" ;; + inspect) printf '%s\n' "${FAKE_INSPECT:-}" ;; + exec) + sql="$(cat)" + case "$sql" in + *personal_report_jobs*) printf '%s\n' "${FAKE_QUEUE_WAIT:-0}" ;; + *"count(*)"*) printf '%s\n' "${FAKE_FEEDBACK_ROW:-0|}" ;; + *"now()"*) printf '%s\n' "${FAKE_NOW:-2026-10-15T01:00:00Z}" ;; + esac + ;; +esac +""" + + +def run_ops(tmp_path: Path, state: Path, **fake: str) -> subprocess.CompletedProcess[str]: + docker = tmp_path / "fake-docker" + if not docker.exists(): + write_text(docker, FAKE_DOCKER) + os.chmod(docker, 0o755) + meminfo = tmp_path / "meminfo" + available = fake.pop("available_kb", "3000000") + write_text(meminfo, f"MemTotal: 4000000 kB\nMemAvailable: {available} kB\n") + env = { + "JYOTISHA_MONITOR_STATE_DIR": bash_path(state), + "JYOTISHA_MONITOR_ENV": bash_path(tmp_path / "missing.env"), + "JYOTISHA_DOCKER": bash_path(docker), + "JYOTISHA_MEMINFO": bash_path(meminfo), + **{key.upper(): value for key, value in fake.items()}, + } + return run_bash(OPS_SCRIPT, env) + + +def test_ops_check_container_restarts_memory_queue_and_feedback(tmp_path: Path) -> None: + state = tmp_path / "state" + web = "a" * 64 + api = "b" * 64 + base = { + "fake_ids": f"{web[:12]}\n{api[:12]}", + "fake_inspect": f"{web} /jyotisha-production-web-1 0 false\n{api} /jyotisha-production-api-1 0 false", + } + first = run_ops(tmp_path, state, **base) + assert first.returncode == 0, first.stderr + assert alert_lines(state) == [] # first run only sets the feedback baseline + + restarted = {**base, "fake_inspect": f"{web} /jyotisha-production-web-1 0 false\n{api} /jyotisha-production-api-1 2 true"} + assert run_ops(tmp_path, state, **restarted).returncode == 0 + lines = alert_lines(state) + assert len(lines) == 1 + assert "service=api" in lines[0] and "errorCode=container_oom" in lines[0] and "count=2" in lines[0] + assert run_ops(tmp_path, state, **restarted).returncode == 0 + assert len(alert_lines(state)) == 1 + + assert run_ops(tmp_path, state, **restarted, fake_queue_wait="900", available_kb="200000").returncode == 0 + joined = "\n".join(alert_lines(state)) + assert "errorCode=report_queue_stuck" in joined and "count=900" in joined + assert "errorCode=memory_high" in joined and "count=95" in joined + count_before = len(alert_lines(state)) + assert run_ops(tmp_path, state, **restarted, fake_queue_wait="900", available_kb="200000").returncode == 0 + assert len(alert_lines(state)) == count_before + assert run_ops(tmp_path, state, **restarted, fake_queue_wait="5").returncode == 0 + recovered = alert_lines(state)[count_before:] + assert sum("errorCode=recovered" in line for line in recovered) == 2 + + feedback = {**restarted, "fake_feedback_row": "2|2026-10-15T01:03:00.000000Z"} + assert run_ops(tmp_path, state, **feedback).returncode == 0 + last = alert_lines(state)[-1] + assert "errorCode=feedback_new" in last and "count=2" in last and "route=/admin/feedback" in last + assert "feedback_seen=2026-10-15T01:03:00.000000Z" in (state / "ops-check.state").read_text(encoding="utf-8") + + +def run_install(tmp_path: Path, args: list[str], tz: str = "Asia/Shanghai") -> subprocess.CompletedProcess[str]: + base = tmp_path / "opt" + (base / "deploy").mkdir(parents=True, exist_ok=True) + target = base / "deploy" / "monitor" + if not target.exists(): + target.symlink_to(MONITOR) + env = { + **os.environ, + "TZ": tz, + "JYOTISHA_MONITOR_INSTALL_ALLOW_NONROOT": "1", + "JYOTISHA_PRODUCTION_PATH": str(base), + "JYOTISHA_MONITOR_CRON_FILE": str(tmp_path / "cron.d-monitor"), + "JYOTISHA_MONITOR_STATE_DIR": str(tmp_path / "state"), + "JYOTISHA_PYTHON": sys.executable, + } + env.pop("FEISHU_WEBHOOK_URL", None) + env.pop("ALERT_EMAIL_TO", None) + return subprocess.run([BASH, str(INSTALL_SCRIPT), *args], env=env, capture_output=True, text=True, encoding="utf-8") + + +def test_installer_is_idempotent_and_places_the_daily_summary_at_beijing_nine(tmp_path: Path) -> None: + first = run_install(tmp_path, []) + assert first.returncode == 0, first.stderr + cron = (tmp_path / "cron.d-monitor").read_text(encoding="utf-8") + assert "* * * * * root bash" in cron and "healthcheck-alert.sh --mode all" in cron + assert "error-digest.sh --window" in cron and "ops-check.sh" in cron + assert "0 9 * * * root bash" in cron + assert "JYOTISHA_COMMIT_ALERT=off" in cron + env_file = tmp_path / "opt" / ".monitor.env" + assert env_file.exists() and (env_file.stat().st_mode & 0o777) == 0o600 + write_text(env_file, "# kept\n") + os.chmod(env_file, 0o600) + again = run_install(tmp_path, []) + assert again.returncode == 0, again.stderr + assert (tmp_path / "cron.d-monitor").read_text(encoding="utf-8") == cron + assert env_file.read_text(encoding="utf-8") == "# kept\n" + utc = run_install(tmp_path, [], tz="UTC") + assert utc.returncode == 0, utc.stderr + assert "0 1 * * * root bash" in (tmp_path / "cron.d-monitor").read_text(encoding="utf-8") + + +def test_installer_test_alert_without_channels_stays_local(tmp_path: Path) -> None: + assert run_install(tmp_path, []).returncode == 0 + test = run_install(tmp_path, ["--test-alert"]) + assert test.returncode == 0, test.stderr + lines = alert_lines(tmp_path / "state") + assert len(lines) == 1 and "errorCode=monitor_test" in lines[0] + + +def test_off_host_probe_workflow_runs_every_five_minutes_from_main() -> None: + text = PROBE_WORKFLOW.read_text(encoding="utf-8") + assert 'cron: "*/5 * * * *"' in text + assert "if: gitea.ref == 'refs/heads/main'" in text + assert "runs-on: xiaoxin" in text + assert "JYOTISHA_COMMIT_ALERT=off" in text + assert "deploy/monitor/healthcheck-alert.sh --mode health" in text + for name in ("MONITOR_FEISHU_WEBHOOK_URL", "MONITOR_ALERT_EMAIL_TO", "MONITOR_RESEND_API_KEY"): + assert f"secrets.{name}" in text + assert "hook/" not in text.split("on:", 1)[1].replace("hook/", "") + + +def test_monitor_scripts_pass_bash_n() -> None: + for script in (OPS_SCRIPT, INSTALL_SCRIPT, MONITOR / "notify-feishu.sh"): + completed = subprocess.run([BASH, "-n", str(script)], capture_output=True, text=True) + assert completed.returncode == 0, completed.stderr