From 89efc3a7cf6ece80aa5fdb7706e11b8c290ff63e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:21:40 +0800 Subject: [PATCH] fix(ops): process alert ignores seconds-old processes; release flow reads production's real revision and says why it stops (BUG-2437, BUG-2438) - ops-check reads etimes; only processes alive >= 120 s count as CPU-hot; ps/ss/next-server allowlisted. Miner-name and pool-port checks unchanged. - migrate/deploy-production print why they stop when the web container has no GITHUB_SHA. - ship-release compares migrations against production's running SHA (unknown = migrate), so a rerun after a failed migration no longer skips it. README: manual container recreate must carry GITHUB_SHA. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8 --- .gitea/workflows/deploy-production.yml | 6 +++- .../workflows/migrate-production-database.yml | 7 ++++- .gitea/workflows/ship-release.yml | 11 +++++-- deploy/README.md | 3 ++ deploy/monitor/ops-check.sh | 16 +++++++--- docs/BUG_HISTORY.md | 31 +++++++++++++++++++ frontend/tests/branch-flow-2415.test.ts | 6 +++- tests/test_monitor_alerts_2348.py | 14 ++++++--- 8 files changed, 80 insertions(+), 14 deletions(-) diff --git a/.gitea/workflows/deploy-production.yml b/.gitea/workflows/deploy-production.yml index e4df2ecd0..45555f289 100644 --- a/.gitea/workflows/deploy-production.yml +++ b/.gitea/workflows/deploy-production.yml @@ -398,7 +398,11 @@ jobs: scp -i "$key_path" -P "$DEPLOY_PORT" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known_hosts_path" artifacts/controller/controller.tar "$remote:$incoming/controller.tar" ssh "${ssh_options[@]}" "$remote" "tar -xf '$incoming/controller.tar' -C '$incoming' && rm -f -- '$incoming/controller.tar'" previous_sha="$(ssh "${ssh_options[@]}" "$remote" "state='$DEPLOY_PATH/.state/deployed-revision'; id=\$(sudo -n docker ps -aq --filter 'label=com.docker.compose.project=jyotisha-production' --filter 'label=com.docker.compose.service=web' | head -n 1); if [ -n \"\$id\" ]; then sudo -n docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \"\$id\" | sed -n 's/^GITHUB_SHA=//p' | head -n 1; elif [ -e \"\$state\" ]; then printf state-present-without-container; else printf not-deployed; fi")" - [[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || exit 1 + [[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || { + # BUG-2438: this used to exit silently (see migrate-production-database.yml). + echo "cannot read the deployed revision from the production web container (got '${previous_sha:0:60}'); its GITHUB_SHA env is missing or malformed" >&2 + exit 1 + } forward_verified=false if [[ "$previous_sha" != not-deployed && "$previous_sha" != "$DEPLOY_SHA" && "$ALLOW_ROLLBACK" != true ]]; then comparison="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \ diff --git a/.gitea/workflows/migrate-production-database.yml b/.gitea/workflows/migrate-production-database.yml index 0e27fe8c3..d99b0411c 100644 --- a/.gitea/workflows/migrate-production-database.yml +++ b/.gitea/workflows/migrate-production-database.yml @@ -319,7 +319,12 @@ jobs: scp -i "$key_path" -P "$DEPLOY_PORT" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known_hosts_path" artifacts/staging-image/controller.tar "$remote:$incoming/controller.tar" ssh "${ssh_options[@]}" "$remote" "tar -xf '$incoming/controller.tar' -C '$incoming' && rm -f -- '$incoming/controller.tar'" previous_sha="$(ssh "${ssh_options[@]}" "$remote" "state='$DEPLOY_PATH/.state/deployed-revision'; id=\$(sudo -n docker ps -aq --filter 'label=com.docker.compose.project=jyotisha-production' --filter 'label=com.docker.compose.service=web' | head -n 1); if [ -n \"\$id\" ]; then sudo -n docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \"\$id\" | sed -n 's/^GITHUB_SHA=//p' | head -n 1; elif [ -e \"\$state\" ]; then printf state-present-without-container; else printf not-deployed; fi")" - [[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || exit 1 + [[ "$previous_sha" == not-deployed || "$previous_sha" =~ ^[0-9a-f]{40}$ ]] || { + # BUG-2438: this used to exit silently. An empty value means the running web container has no + # GITHUB_SHA (for example it was recreated by hand without it); recreate it with GITHUB_SHA set. + echo "cannot read the deployed revision from the production web container (got '${previous_sha:0:60}'); its GITHUB_SHA env is missing or malformed" >&2 + exit 1 + } forward_verified=false if [[ "$previous_sha" != not-deployed && "$previous_sha" != "$DEPLOY_SHA" ]]; then comparison="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \ diff --git a/.gitea/workflows/ship-release.yml b/.gitea/workflows/ship-release.yml index fea5ed32f..c24251fca 100644 --- a/.gitea/workflows/ship-release.yml +++ b/.gitea/workflows/ship-release.yml @@ -38,6 +38,7 @@ jobs: RELEASE_PUSH_TOKEN: ${{ secrets.RELEASE_PUSH_TOKEN }} VERSION: ${{ inputs.version }} STAGING_URL: ${{ vars.STAGING_URL }} + PRODUCTION_URL: ${{ vars.PRODUCTION_URL }} steps: - name: Ship run: | @@ -74,7 +75,13 @@ jobs: git push origin "$sha:refs/heads/main" echo "main → $sha" - if bash "$flow" migrations-changed "$main_before" "$sha"; then + # BUG-2438: compare against what production actually runs, not main before the push. A + # rerun after a failed migration has main == sha already, and main_before..sha is empty, + # which used to skip the migration that never ran. Unknown production SHA = migrate. + production_sha="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \ + "${PRODUCTION_URL:-https://jyotisha.chat}/api/health" | jq -r '.deployment.gitCommit // ""' || true)" + echo "production runs ${production_sha:-unknown}" + if [[ ! "$production_sha" =~ ^[0-9a-f]{40}$ ]] || bash "$flow" migrations-changed "$production_sha" "$sha"; then run="$(bash "$flow" dispatch create-production-recovery.yml refs/heads/main "$(jq -cn --arg s "$sha" '{deploy_sha:$s}')")" echo "recovery point run $run" bash "$flow" wait-run "$run" 45 @@ -91,7 +98,7 @@ jobs: echo "production migration run $run" bash "$flow" wait-run "$run" 45 else - echo "no migration changes since $main_before; skipping recovery point and migration" + echo "no migration changes since production ($production_sha); skipping recovery point and migration" fi run="$(bash "$flow" dispatch deploy-production.yml refs/heads/main "$(jq -cn --arg s "$sha" \ diff --git a/deploy/README.md b/deploy/README.md index 23ac18278..77d31cf31 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -598,6 +598,9 @@ deploy/find-request-log.sh --since 24h - 命令行里出现常见挖矿程序名或 `stratum+tcp`:`miner_process`。 - 有进程连到常见矿池端口(3333、4444、5555、7777、9999、14444 等):`mining_pool_connection`。我们自己的 22/80/443/3000/5200/5432 入站连接不算。 - 告警只带进程名和进程号,不发命令行和环境变量。同一个进程只报一次。 +- `suspicious_process` 只看已经运行满 2 分钟(`JYOTISHA_PROCESS_MIN_AGE`,默认 120 秒)的进程:`ps` 的 CPU 百分比是整个生命期的平均,刚启动几秒的进程(`ps` 自己、部署时的解压、网站刚启动)会显示接近 100%(BUG-2437)。`ps`、`ss` 和网站进程 `next-server (v…)` 在白名单里。 + +**手动重建生产容器(BUG-2438)**:手动 `docker compose up -d` 重建 web 或 api 时,必须同时带上 `WEB_IMAGE`、`API_IMAGE`(读当前容器的镜像摘要)和 `GITHUB_SHA`(当前容器 env 里的值),`--env-file /opt/jyotisha-production/.env.production`。漏了 `GITHUB_SHA`,健康检查的 `gitCommit` 变空,下一次生产迁移和部署会因为读不到「当前版本」而停下。 - 阈值可用 `JYOTISHA_CONTAINER_MEMORY_PERCENT_LIMIT`、`JYOTISHA_CPU_PERCENT_LIMIT`、`JYOTISHA_CONTAINER_CPU_LIMIT`、`JYOTISHA_PROCESS_CPU_LIMIT`、`JYOTISHA_CPU_SUSTAIN_RUNS` 调。 **容器(`docker-compose.server.yml`,测试和生产共用)** diff --git a/deploy/monitor/ops-check.sh b/deploy/monitor/ops-check.sh index a0a47303b..a0c7e8fe5 100644 --- a/deploy/monitor/ops-check.sh +++ b/deploy/monitor/ops-check.sh @@ -42,6 +42,7 @@ cpu_limit="${JYOTISHA_CPU_PERCENT_LIMIT:-85}" container_cpu_limit="${JYOTISHA_CONTAINER_CPU_LIMIT:-90}" sustain_runs="${JYOTISHA_CPU_SUSTAIN_RUNS:-2}" process_cpu_limit="${JYOTISHA_PROCESS_CPU_LIMIT:-50}" +process_min_age="${JYOTISHA_PROCESS_MIN_AGE:-120}" # BUG-2437: seconds [[ "$cpu_limit" =~ ^[1-9][0-9]$ ]] || exit 2 [[ "$container_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2 [[ "$sustain_runs" =~ ^[1-9]$ ]] || exit 2 @@ -386,10 +387,10 @@ check_container_memory() { # Process names that may legitimately use a lot of CPU on this host. allowed_process() { case "$1" in - node|python|python3|python3.*|uvicorn|gunicorn|postgres|postmaster|pg_dump|pg_restore|psql) return 0 ;; + node|next-server*|python|python3|python3.*|uvicorn|gunicorn|postgres|postmaster|pg_dump|pg_restore|psql) return 0 ;; caddy|dockerd|containerd|containerd-shim*|runc|docker|docker-proxy|docker-compose) return 0 ;; sshd|cron|systemd|systemd-*|journald|rsyslogd|unattended-upgr*|apt|apt-get|dpkg|http|https|gpgv) return 0 ;; - bash|sh|awk|gzip|zstd|xz|tar|sort|ossutil*|kworker*|ksoftirqd*|kswapd*) return 0 ;; + bash|sh|awk|gzip|zstd|xz|tar|sort|ps|ss|ossutil*|kworker*|ksoftirqd*|kswapd*) return 0 ;; esac return 1 } @@ -422,20 +423,25 @@ prune_suspects() { done } +# BUG-2437: ps reports %CPU as CPU time over lifetime, so a process seconds old (ps itself, a +# deploy step, a server warming up) reads near 100 %. Only a process running at least +# process_min_age seconds counts as hot; a miner keeps running and is still caught, and the +# name / pool checks ignore age. check_processes() { - local pid pcpu comm args pct - while read -r pid pcpu comm args || [ -n "${pid:-}" ]; do + local pid etimes pcpu comm args pct + while read -r pid etimes pcpu comm args || [ -n "${pid:-}" ]; do [[ "${pid:-}" =~ ^[0-9]+$ ]] || continue if miner_text "$comm $args"; then report_suspect "$pid" "$comm" miner_process continue fi + [[ "${etimes:-}" =~ ^[0-9]+$ ]] && [ "$etimes" -ge "$process_min_age" ] || continue pct="${pcpu%%.*}" [[ "$pct" =~ ^[0-9]+$ ]] || continue if [ "$pct" -ge "$process_cpu_limit" ] && ! allowed_process "$comm"; then report_suspect "$pid" "$comm" suspicious_process fi - done < <(ps_cmd -eo pid=,pcpu=,comm=,args= 2>/dev/null || true) + done < <(ps_cmd -eo pid=,etimes=,pcpu=,comm=,args= 2>/dev/null || true) } # Established outbound connections to common mining-pool ports. diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 41fe35a18..d9fd3c7af 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -33309,3 +33309,34 @@ - 防复发:群文案和弹窗用同一组字段,不再各写一份。 - 关联记录:#331(更新说明)、BUG-1935(admin_runtime 策略)、负责人「结果用 toast」规则。 - 修复版本:`next`(1.7)。 + +## BUG-2437 | 生产告警「有不在白名单里的进程占用大量 CPU」误报:报的是监控自己的 `ps` + +- 状态:fixed-pending-verify(推到 `next`,随 1.7 上生产)。 +- 首次发现 / 最近更新:2026-11-27(负责人收到飞书告警,1.6 部署期间)。 +- 现象:告警 `service=host route=/proc/ps errorCode=suspicious_process`,时间正好在 1.6 生产部署(网站容器刚重建)那一分钟;上机查看时进程早已结束,负载 0.26,没有可疑进程。 +- 触发条件:ops-check 每 5 分钟用 `ps -eo pcpu` 看进程;部署或其它短命令刚启动时跑到这一刻。 +- 根因:`ps` 的 `%CPU` 是「CPU 时间 / 存活时间」,刚启动几秒的进程(`ps` 自己、部署时的解压、刚启动的网站)读数接近 100%;检查不看存活时间,白名单里也没有 `ps`。另外 Next.js 的进程名是 `next-server (v…)`(`comm` 带空格),不在白名单的 `node` 里,网站启动那一下同样会被报。 +- 修复:`deploy/monitor/ops-check.sh` 的 `check_processes` 多读一列 `etimes`,只有存活满 `JYOTISHA_PROCESS_MIN_AGE`(默认 120 秒)的进程才按 CPU 判可疑;白名单加 `ps`、`ss`、`next-server*`。按挖矿程序名 / `stratum` 和矿池端口的两条检查不看存活时间,照旧。 +- 验证:`tests/test_monitor_alerts_2348.py` 加三条假进程(刚启动的 `ps` 100%、5 秒的 `unpigz` 97%、长期运行的 `next-server (v16.0.0)` 60%)都不报;存活 30 秒的 `kdevtmpfsi` 仍按名字报 `miner_process`;原有用例照过。 +- 防复发:监控按百分比判断时必须同时看存活时间;新增常驻服务时把它的 `comm` 名加进白名单。 +- 关联记录:BUG-2416(防入侵告警)、BUG-2348(监控安装)。 +- 修复版本:`next`(本条提交)。 + +## BUG-2438 | 发 1.6 时生产迁移无提示失败:网站容器缺 `GITHUB_SHA`;发版流程重跑会跳过没跑成的迁移 + +- 状态:fixed-pending-verify(生产已手动补好并完成 1.6 发布;流程修复推到 `next`,随 1.7 生效)。 +- 首次发现 / 最近更新:2026-11-27(协调窗口,发 1.6 的 ship-release 8869 / 迁移 8871)。 +- 现象:「发版」流程把 main 快进到 4155b9d22、恢复点 8870 成功后,生产迁移 8871 在「Migrate」一步以 exit 1 结束,日志里没有任何错误说明;生产健康检查的 `gitCommit` 是空字符串。 +- 触发条件:1.5 上线时为加 Turnstile 密钥手动 `docker compose up -d --no-deps web`,只带了 `WEB_IMAGE` / `API_IMAGE`,没带 `GITHUB_SHA`,网站容器的 `GITHUB_SHA=` 变成空值。 +- 根因: + 1. 迁移和部署都从网站容器的 env 读「当前生产版本」,读到空值时 `[[ … ]] || exit 1` 直接退出,不打印原因(`migrate-production-database.yml`、`deploy-production.yml`)。 + 2. 运维文档没写手动重建容器必须带 `GITHUB_SHA`。 + 3. `ship-release.yml` 用「推送前的 main」和发版 SHA 比较迁移有没有变化;迁移失败后 main 已经等于 SHA,重跑「发版」时这段比较为空,会跳过从没跑成的迁移直接部署。 +- 修复: + - 负责人同意后用原镜像摘要、原 env 文件带上 `GITHUB_SHA=87677ca9…` 重建网站容器(几秒中断),重跑迁移 8871 成功,手动派发部署 8873 成功,v1.6 自动打标签。 + - 代码:两处读取失败改为打印「读不到生产网站容器的版本(GITHUB_SHA 缺失或格式不对)」再退出;`ship-release.yml` 改为和生产健康检查报告的实际运行版本比较,读不到就照样做恢复点和迁移;`deploy/README.md` 写明手动重建容器要带 `WEB_IMAGE`、`API_IMAGE`、`GITHUB_SHA` 和 env 文件。 +- 验证:生产 `/api/health` = 1.6 / 4155b9d22,`/login` 200,未登录 `/api/account` 401,内部 API 健康 `swisseph_available = true`,Turnstile 两个 key 和 `.monitor.env` 仍在。`frontend/tests/branch-flow-2415.test.ts` 改为钉住新的比较方式(原值 / 新值 / 原因已注明)并通过;三个工作流 YAML 解析通过。 +- 防复发:任何读生产状态的检查失败时必须打印原因;发版判断「要不要迁移」只以生产实际运行版本为准。 +- 关联记录:BUG-2402(Turnstile)、BUG-2415(分支发版流程)、BUG-2425(同步删掉 `.monitor.env`,同属手动运维与发版流程的交界)。 +- 修复版本:`next`(本条提交)。 diff --git a/frontend/tests/branch-flow-2415.test.ts b/frontend/tests/branch-flow-2415.test.ts index 2fd7829ad..a6abaaf13 100644 --- a/frontend/tests/branch-flow-2415.test.ts +++ b/frontend/tests/branch-flow-2415.test.ts @@ -56,7 +56,11 @@ test("发版 ships only a tested head: staging live on it, release checks passed const migrate = wf.indexOf("migrate-production-database.yml"); const deploy = wf.indexOf("deploy-production.yml"); assert.ok(recovery > 0 && recovery < migrate && migrate < deploy); - assert.match(wf, /if bash "\$flow" migrations-changed "\$main_before" "\$sha"; then/); + // 原值:migrations-changed "$main_before" "$sha";新值:比较生产实际运行的版本,读不到就照样迁移; + // 原因:BUG-2438 迁移失败后重跑时 main 已经等于 sha,main_before..sha 为空会跳过从没跑成的迁移。 + assert.match(wf, /production_sha="\$\(curl [^\n]*\\\n\s*"\$\{PRODUCTION_URL:-https:\/\/jyotisha\.chat\}\/api\/health"/); + assert.match(wf, /if \[\[ ! "\$production_sha" =~ \^\[0-9a-f\]\{40\}\$ \]\] \|\| bash "\$flow" migrations-changed "\$production_sha" "\$sha"; then/); + assert.doesNotMatch(wf, /migrations-changed "\$main_before"/); // Its own queue: the production workflows it starts hold production-mutation themselves. assert.match(wf, /group: release-flow/); assert.doesNotMatch(wf, /group: production-mutation/); diff --git a/tests/test_monitor_alerts_2348.py b/tests/test_monitor_alerts_2348.py index be6dd0047..f1de2dbcf 100644 --- a/tests/test_monitor_alerts_2348.py +++ b/tests/test_monitor_alerts_2348.py @@ -419,10 +419,15 @@ def test_ops_check_cpu_miners_and_pool_connections_2416(tmp_path: Path) -> None: # Miner by name, an unknown hot process, a pool connection; allowlisted node stays quiet. ps_out = "\n".join([ - " 101 99.0 node node server.js", - " 202 80.0 kdevtmpfsi /tmp/kdevtmpfsi", - " 303 75.0 sysupdate /var/tmp/.x/sysupdate -o pool.example:443", - " 404 1.0 worker ./worker --url stratum+tcp://pool.example:3333 --user SECRETWALLET", + " 101 9000 99.0 node node server.js", + " 202 30 80.0 kdevtmpfsi /tmp/kdevtmpfsi", + " 303 9000 75.0 sysupdate /var/tmp/.x/sysupdate -o pool.example:443", + " 404 9000 1.0 worker ./worker --url stratum+tcp://pool.example:3333 --user SECRETWALLET", + # BUG-2437: the monitor's own ps and a fresh deploy step read ~100 % in their first seconds; + # Next.js names its process 「next-server (v…)」. + " 505 0 100.0 ps ps -eo pid=,etimes=,pcpu=,comm=,args=", + " 606 5 97.0 unpigz unpigz -d -c", + " 707 9000 60.0 next-server (v16.0.0) next-server (v16.0.0)", ]) ss_out = "\n".join([ "0 0 10.0.0.5:51234 203.0.113.9:4444 users:((\"sysupdate\",pid=303,fd=7))", @@ -437,6 +442,7 @@ def test_ops_check_cpu_miners_and_pool_connections_2416(tmp_path: Path) -> None: assert "route=/proc/sysupdate errorCode=suspicious_process count=303" in joined assert "route=/proc/sysupdate errorCode=mining_pool_connection" not in joined # same pid already reported assert "/proc/node" not in joined and "docker-proxy" not in joined # allowlisted / inbound + assert "/proc/ps " not in joined and "/proc/unpigz" not in joined and "/proc/next-server" not in joined # BUG-2437 assert "SECRETWALLET" not in joined and "stratum" not in joined and "pool.example" not in joined # Still running next time: not announced again. before = len(alert_lines(state))