ops: container memory limits, api init, 65% disk alert, release cleanup (BUG-2428)
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m34s
Independent Staging Quality Gate / validate-python (push) Successful in 8m34s
Independent Staging Quality Gate / publish (push) Successful in 3m57s

- postgres 1g + oom_score_adj -500; api 1536m + init; web 768m; caddy 128m
  (BUG-2416 hardening kept; web keeps its own SIGTERM handling)
- disk alert 80% -> 65%, below the 70% backup stop line
- ops-check: container_memory_high at 85% of the container's own limit
- after a verified production deploy: keep newest 5 pre-release recovery
  points (+ baseline) and current/previous app images; dry-run supported

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
2026-11-26 23:18:02 +08:00
co-authored by Claude Opus 5.5
parent ba14cdf3b6
commit 0054781bc5
13 changed files with 532 additions and 14 deletions
+10 -4
View File
@@ -506,6 +506,10 @@ report list / detail / create smoke”): `GET /api/reports` 200, owned
- 工作流:`.gitea/workflows/backup-production-daily.yml`。北京时间每天 04:00,也可手动触发。只从 `main` 运行,调用 `deploy/run-production-recovery.sh`,不另写一套导出。
- 每日文件前缀是 `production-daily-`。手动恢复点仍是 `production-pre-migration-`。清理脚本 `deploy/prune-production-daily-backups.sh` 只删超过 7 天的每日文件和对应的校验文件,不会删 `production-pre-migration-` 手动恢复点。清理排在新备份之前,所以磁盘到 70% 时过期的每日文件仍会被清掉。
- 每日备份只做存档和还原核对,不是发布用的恢复点。它不改 `/opt/jyotisha-production/.state/recovery-baseline.env`。核对结果另写在同目录的 `daily-backup-latest.env`,只有文件名、sha256、核对时间和格式版本,没有数据和密钥。发布、迁移、回退都不读这个文件。上线前仍要手动点 Create production recovery。
- 发版后清理(BUG-2428,`deploy/prune-production-release.sh`,由 `run-production-deploy.sh` 在新版本核对通过之后调用;清理失败不让发版失败):
- 本机 `backups/` 里的 `production-pre-migration-` 恢复点只留最新 5 个和 `.state/recovery-baseline.env` 指向的那个,对应的校验文件一起删。每日备份和 OSS 里的副本都不动。
- 应用镜像(发布仓库里的 api/web 镜像)只留现在运行的和上一版(回滚用),以及任何容器(包括停止的)还在用的;postgres、caddy 等其它镜像不动。第一次部署或同一镜像重新部署时不清镜像。
- 每删一个都打一行 `release_cleanup removed ...`;`RELEASE_CLEANUP_DRY_RUN=1` 只打 `would_remove`,不删。
- Gitea 产物默认保留 14 天。手动恢复点工作流仍是 30 天,没有改。
- 还原步骤:`docs/operations/production-restore-drill-20261014.md`。
@@ -522,10 +526,10 @@ sudo bash /opt/jyotisha-production/deploy/monitor/install-production-monitor.sh
| 频率 | 脚本 | 看什么 |
|---|---|---|
| 每分钟 | `healthcheck-alert.sh --mode all` | 本机看到的 `/api/health`(连续 3 次失败告警、恢复发一次);磁盘 ≥80%;每日备份超过 36 小时没核对成功 |
| 每分钟 | `healthcheck-alert.sh --mode all` | 本机看到的 `/api/health`(连续 3 次失败告警、恢复发一次);磁盘 ≥65%(BUG-2428:备份在 70% 停,告警要先到);每日备份超过 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 分钟没开始;有新的用户反馈(只发条数) |
| 每 5 分钟 | `ops-check.sh` | 容器自己重启或被 OOM 杀;主机可用内存 ≥90% 已用;某个容器用到自己内存上限的 ≥85%(BUG-2428,`container_memory_high`,不算可回收的文件缓存);报告排队最久的任务超过 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 里能看到运行记录断了。
@@ -597,17 +601,19 @@ deploy/find-request-log.sh <requestId> --since 24h
- 命令行里出现常见挖矿程序名或 `stratum+tcp`:`miner_process`。
- 有进程连到常见矿池端口(3333、4444、5555、7777、9999、14444 等):`mining_pool_connection`。我们自己的 22/80/443/3000/5200/5432 入站连接不算。
- 告警只带进程名和进程号,不发命令行和环境变量。同一个进程只报一次。
- 阈值可用 `JYOTISHA_CPU_PERCENT_LIMIT`、`JYOTISHA_CONTAINER_CPU_LIMIT`、`JYOTISHA_PROCESS_CPU_LIMIT`、`JYOTISHA_CPU_SUSTAIN_RUNS` 调。
- 阈值可用 `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`,测试和生产共用)**
- `api` 以 uid 10001、`web` 以 uid 1000 运行,不再是 root。
- 两者都是只读镜像(`read_only`),去掉全部 Linux 权限(`cap_drop: ALL`),不许提权(`no-new-privileges`),限制进程数和内存(api 2 GB,web 1 GB)。
- 两者都是只读镜像(`read_only`),去掉全部 Linux 权限(`cap_drop: ALL`),不许提权(`no-new-privileges`),限制进程数和内存。
- 可写的地方只有这些:
- api:`/app/scratch/local`(原来的命名卷:星盘缓存、任务记录)和 `/tmp`(内存盘 512 MB:报告产物、临时文件)。
- web:`/tmp`(内存盘 256 MB:在线技能的运行副本)和 `/app/frontend/.next/cache`(内存盘 256 MB:图片缓存)。
- `api-scratch-owner` 是一次性小容器:每次启动 api 前,把 scratch 卷里不属于 10001 的文件改给 10001。它没有网络,只有改文件属主的权限,跑完就退出。
- caddy 镜像按 digest 固定;caddy 只保留绑定 80/443 的权限。postgres 不动(它的启动脚本需要切换用户)。
- 内存上限(BUG-2428,按 `docs/operations/capacity-2026-11.md`,原值 api 2 GB / web 1 GB / caddy 256 MB / postgres 无):postgres 1 GB 且 `oom_score_adj: -500`(主机内存不足时最后才杀它),api 1.5 GB,web 768 MB,caddy 128 MB。内存盘 `/tmp` 也算在容器内存里。超过上限只杀那一个容器,然后自动重启;到上限 85% 先告警。
- api 加了 `init: true`:Python 做 1 号进程时不理 SIGTERM,每次停容器都要等满 10 秒被强杀。web 不加,它自己处理 SIGTERM(BUG-2352,`stop_grace_period: 40s` 不变)。
- **回退**:容器设置只在 compose 文件里,镜像没变。出问题时把 `deploy/docker-compose.server.yml` 回到上一个版本再部署即可;回到 root 运行后,属于 10001 的 scratch 文件 root 照样能读写。
**主机只读核查**
+4
View File
@@ -8,6 +8,10 @@ services:
max-size: "20m"
max-file: "10"
shm_size: 128mb
# BUG-2428: 1 GB (peak 202 MB; the rest is cache). When the host runs out of
# memory the kernel kills the database last.
mem_limit: 1g
oom_score_adj: -500
env_file:
- ${DATABASE_ENV_FILE:-../.env.staging.database}
command:
+11 -3
View File
@@ -39,7 +39,13 @@ services:
cap_drop:
- ALL
pids_limit: 512
mem_limit: 2g
# BUG-2428: 1.5 GB (owner-approved, docs/operations/capacity-2026-11.md). Peak
# 971 MB without report generation; /tmp above is memory-backed and counts too.
# ops-check.sh alerts at 85 % of this limit.
mem_limit: 1536m
# BUG-2428: Python as PID 1 ignored SIGTERM, so every stop waited the full 10 s
# before SIGKILL. Docker's init forwards the signal and reaps children.
init: true
logging:
driver: json-file
options:
@@ -96,7 +102,8 @@ services:
cap_drop:
- ALL
pids_limit: 512
mem_limit: 1g
# BUG-2428: 768 MB (peak 407 MB). No init: node handles SIGTERM itself (BUG-2352).
mem_limit: 768m
logging:
driver: json-file
options:
@@ -133,7 +140,8 @@ services:
cap_add:
- NET_BIND_SERVICE
pids_limit: 256
mem_limit: 256m
# BUG-2428: 128 MB (peak 30 MB).
mem_limit: 128m
logging:
driver: json-file
options:
+3 -1
View File
@@ -219,7 +219,9 @@ check_disk() {
echo "disk usage is unreadable" >&2
exit 1
}
if [ "$percent" -ge 80 ]; then
# BUG-2428: 65 %, so the alert fires before run-production-recovery.sh stops
# making backups at 70 % (was 80 %, after backups had already stopped).
if [ "$percent" -ge 65 ]; then
if [ "$disk_alert_open" -eq 0 ]; then
send_alert host - disk_high "$percent" -
disk_alert_open=1
+1 -1
View File
@@ -6,7 +6,7 @@
# 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 minute healthcheck-alert.sh --mode all site health (local view), disk 65%, 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
+2 -1
View File
@@ -126,10 +126,11 @@ alert_label() {
health_down) printf '网站打不开(连续探活失败)' ;;
recovered) printf '已恢复' ;;
commit_changed) printf '线上版本变了(不在发版窗口内)' ;;
disk_high) printf '磁盘使用超过 80%%' ;;
disk_high) printf '磁盘使用超过 65%%(到 70%% 备份会停)' ;;
backup_stale) printf '每日备份超过 36 小时没有核对成功' ;;
container_restarted) printf '容器自己重启了' ;;
container_oom) printf '容器因内存不够被杀' ;;
container_memory_high) printf '某个容器内存用到上限的 85%% 以上(数字是占上限的百分比)' ;;
memory_high) printf '服务器可用内存不足(数字是已用百分比)' ;;
report_queue_stuck) printf '报告排队太久没开始(数字是等待秒数)' ;;
feedback_new) printf '有新的用户反馈,去 /admin/feedback 看' ;;
+54 -1
View File
@@ -3,6 +3,7 @@
# host, every 5 minutes:
# - a container restarted on its own, or was killed for memory
# - host available memory is low
# - BUG-2428: one container uses 85 % or more of its own memory limit
# - the oldest report job has waited too long to start
# - new user feedback arrived (count only; no feedback text, no account)
# - BUG-2416: host CPU or one container's CPU stays high across two runs
@@ -45,6 +46,8 @@ process_cpu_limit="${JYOTISHA_PROCESS_CPU_LIMIT:-50}"
[[ "$container_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2
[[ "$sustain_runs" =~ ^[1-9]$ ]] || exit 2
[[ "$process_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2
container_memory_limit="${JYOTISHA_CONTAINER_MEMORY_PERCENT_LIMIT:-85}"
[[ "$container_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.
@@ -84,7 +87,7 @@ feedback_seen=""
cpu_prev=""
cpu_hot=0
cpu_open=0
declare -A ccpu_prev=() ccpu_hot=() ccpu_open=() suspects=() suspects_now=()
declare -A ccpu_prev=() ccpu_hot=() ccpu_open=() cmem_open=() suspects=() suspects_now=()
container_ids=""
read_state() {
@@ -120,6 +123,11 @@ read_state() {
ccpu_hot["$key"]="${BASH_REMATCH[3]}"
ccpu_open["$key"]="${BASH_REMATCH[4]}"
;;
cmem:*=1)
key="${line%%=*}"
key="${key#cmem:}"
[[ "$key" =~ ^[0-9a-f]{64}$ ]] && cmem_open["$key"]=1
;;
suspect:*)
key="${line#suspect:}"
[[ "$key" =~ ^[0-9]+/[A-Za-z0-9_.-]+$ ]] && suspects["$key"]=1
@@ -140,6 +148,9 @@ write_state() {
for key in "${!ccpu_prev[@]}"; do
printf 'ccpu:%s=%s:%s:%s\n' "$key" "${ccpu_prev[$key]}" "${ccpu_hot[$key]:-0}" "${ccpu_open[$key]:-0}"
done
for key in "${!cmem_open[@]}"; do
printf 'cmem:%s=1\n' "$key"
done
for key in "${!suspects[@]}"; do
printf 'suspect:%s\n' "$key"
done
@@ -331,6 +342,47 @@ check_container_cpu() {
done
}
# BUG-2428: per-container memory against its own compose limit (cgroup v2).
# Used memory = memory.current minus inactive_file, the same figure docker stats
# shows, so reclaimable page cache (postgres reads) does not count. Containers
# without a limit (memory.max = max) are skipped. Alert once, recover once.
check_container_memory() {
local root entry id service dir current max inactive used pct
declare -A seen=()
root="${JYOTISHA_CGROUP_ROOT:-/sys/fs/cgroup}"
while IFS= read -r entry; do
[ -n "$entry" ] || continue
id="${entry%%:*}"
service="${entry#*:}"
[[ "$id" =~ ^[0-9a-f]{64}$ ]] || continue
dir="$root/system.slice/docker-$id.scope"
[ -r "$dir/memory.current" ] && [ -r "$dir/memory.max" ] || continue
current="$(tr -d '[:space:]' <"$dir/memory.current")"
max="$(tr -d '[:space:]' <"$dir/memory.max")"
[[ "$current" =~ ^[0-9]+$ ]] && [[ "$max" =~ ^[1-9][0-9]*$ ]] || continue
inactive=0
if [ -r "$dir/memory.stat" ]; then
inactive="$(awk '$1 == "inactive_file" {print $2; exit}' "$dir/memory.stat")"
[[ "$inactive" =~ ^[0-9]+$ ]] || inactive=0
fi
used=$((current > inactive ? current - inactive : 0))
pct=$((used * 100 / max))
seen["$id"]=1
if [ "$pct" -ge "$container_memory_limit" ]; then
if [ -z "${cmem_open[$id]:-}" ]; then
queue_alert "$service" - container_memory_high "$pct"
cmem_open["$id"]=1
fi
elif [ -n "${cmem_open[$id]:-}" ]; then
queue_alert "$service" - recovered 0
unset "cmem_open[$id]"
fi
done <<<"$container_ids"
for id in "${!cmem_open[@]}"; do
[ -n "${seen[$id]:-}" ] || unset "cmem_open[$id]"
done
}
# Process names that may legitimately use a lot of CPU on this host.
allowed_process() {
case "$1" in
@@ -422,6 +474,7 @@ check_containers
check_memory
check_host_cpu
check_container_cpu
check_container_memory
check_processes
check_egress
prune_suspects
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
# BUG-2428: release cleanup that runs after a verified production deploy.
# - keep only the newest pre-release recovery points (production-pre-migration-*)
# in the local backups directory; the one named by .state/recovery-baseline.env
# is always kept. Daily backups and the OSS copies are never touched here.
# - remove old application images of the release repository, keeping the
# images that are running now and the previous release's images for rollback.
# Every removal prints one "release_cleanup ..." line. RELEASE_CLEANUP_DRY_RUN=1
# prints "would_remove" lines and deletes nothing.
set -euo pipefail
release_cleanup_log() {
printf 'release_cleanup %s\n' "$*"
}
release_cleanup_dry_run() {
[ "${RELEASE_CLEANUP_DRY_RUN:-0}" = "1" ]
}
# prune_recovery_points BACKUP_DIRECTORY KEEP [BASELINE_FILE]
prune_recovery_points() {
local directory="$1"
local keep="$2"
local baseline="${3:-}"
local protected="" reference name base verify index=0
local -a points=()
[ -n "$directory" ] && [ -d "$directory" ] && [ ! -L "$directory" ] || {
echo "backup directory is unsafe" >&2
return 1
}
[[ "$keep" =~ ^[1-9][0-9]?$ ]] || {
echo "recovery point count must be a positive integer" >&2
return 1
}
if [ -n "$baseline" ] && [ -f "$baseline" ] && [ ! -L "$baseline" ]; then
reference="$(awk -F= '$1 == "RECOVERY_REFERENCE" { print $2; exit }' "$baseline")"
protected="${reference##*/}"
fi
# Names carry a UTC timestamp, so a reverse name sort is newest first.
mapfile -t points < <(
find "$directory" -maxdepth 1 -type f -name 'production-pre-migration-*.dump.enc' -printf '%f\n' 2>/dev/null |
grep -E '^production-pre-migration-[0-9]{8}T[0-9]{6}Z\.dump\.enc$' | LC_ALL=C sort -r || true
)
for name in "${points[@]}"; do
index=$((index + 1))
if (( index <= keep )) || [ "$name" = "$protected" ]; then
continue
fi
base="${name%.dump.enc}"
verify="$directory/${base}-restore-verify.json"
if release_cleanup_dry_run; then
release_cleanup_log "would_remove recovery_point=$name"
continue
fi
rm -f -- "$directory/$name"
if [ -f "$verify" ] && [ ! -L "$verify" ]; then
rm -f -- "$verify"
fi
release_cleanup_log "removed recovery_point=$name"
done
release_cleanup_log "recovery_points_kept=$(( ${#points[@]} < keep ? ${#points[@]} : keep ))${protected:+ baseline=$protected}"
}
release_cleanup_docker() {
if declare -p docker_command >/dev/null 2>&1; then
"${docker_command[@]}" "$@"
else
docker "$@"
fi
}
# prune_release_images REPOSITORY KEEP_REF...
# KEEP_REF is an image id (sha256:...) or a digest reference. Images used by any
# container, running or stopped, are kept as well. Removal is by id without
# force, so Docker itself refuses anything still in use.
prune_release_images() {
local repository="$1"
shift
local ref id refs line container_image short
declare -A keep_ids=()
local -a ids=()
[[ "$repository" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[1-9][0-9]{0,4})?(/[a-z0-9]+([._-][a-z0-9]+)*)+$ ]] || {
echo "release image repository is unsafe" >&2
return 1
}
for ref in "$@"; do
[ -n "$ref" ] || continue
id="$(release_cleanup_docker image inspect --format '{{.Id}}' "$ref" 2>/dev/null || true)"
[[ "$id" =~ ^sha256:[0-9a-f]{64}$ ]] || {
echo "release image to keep is not on the host; skipping image cleanup" >&2
return 0
}
keep_ids["$id"]=1
done
while IFS= read -r line; do
[ -n "$line" ] || continue
container_image="$(release_cleanup_docker inspect --format '{{.Image}}' "$line" 2>/dev/null || true)"
[[ "$container_image" =~ ^sha256:[0-9a-f]{64}$ ]] && keep_ids["$container_image"]=1
done < <(release_cleanup_docker ps -aq --no-trunc 2>/dev/null || true)
mapfile -t ids < <(release_cleanup_docker image ls -q --no-trunc 2>/dev/null | LC_ALL=C sort -u || true)
for id in "${ids[@]}"; do
[[ "$id" =~ ^sha256:[0-9a-f]{64}$ ]] || continue
[ -z "${keep_ids[$id]:-}" ] || continue
refs="$(release_cleanup_docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}{{range .RepoTags}}{{println .}}{{end}}' "$id" 2>/dev/null || true)"
# Only images of the release repository; postgres, caddy and anything else stay.
grep -Eq "^${repository//./\\.}[@:]" <<<"$refs" || continue
short="${id#sha256:}"
short="${short:0:12}"
if release_cleanup_dry_run; then
release_cleanup_log "would_remove image=$short"
continue
fi
if release_cleanup_docker image rm "$id" >/dev/null 2>&1; then
release_cleanup_log "removed image=$short"
else
release_cleanup_log "image_remove_failed image=$short"
fi
done
release_cleanup_log "images_kept=${#keep_ids[@]}"
}
+22
View File
@@ -343,6 +343,28 @@ chmod 600 "$revision_file"
mv -f "$revision_file" "$state_directory/deployed-revision"
trap - ERR
# BUG-2428: release cleanup, only after the new release is verified. A cleanup
# failure never fails the deploy. Recovery points: newest 5 plus the baseline.
# Images: current + previous release; skipped on a first or same-image deploy so
# a rollback target always stays on the host.
# shellcheck source=prune-production-release.sh
source deploy/prune-production-release.sh
if [ -d "$DEPLOY_PATH/backups" ]; then
prune_recovery_points "$DEPLOY_PATH/backups" 5 "$state_directory/recovery-baseline.env" ||
echo "release_cleanup recovery_points_failed" >&2
fi
current_api_id="$("${docker_command[@]}" image inspect --format '{{.Id}}' "$API_IMAGE" 2>/dev/null || true)"
if [ -n "$previous_api_target" ] && [ -n "$previous_web_target" ] &&
[ -n "$current_api_id" ] && [ "$previous_api_id" != "$current_api_id" ]; then
for cleanup_repository in $(printf '%s\n' "$api_repository" "$web_repository" | sort -u); do
prune_release_images "$cleanup_repository" "$API_IMAGE" "$WEB_IMAGE" \
"$previous_api_target" "$previous_web_target" ||
echo "release_cleanup images_failed" >&2
done
else
release_cleanup_log "images_skipped=no_distinct_previous_release"
fi
printf 'previous_sha=%s\nprevious_api_image=%s\nprevious_api_id=%s\n' \
"$current_sha" "${previous_api_image:-not-deployed}" "${previous_api_id:-not-deployed}"
printf 'previous_web_image=%s\nprevious_web_id=%s\nverified_sha=%s\n' \
+18
View File
@@ -33145,3 +33145,21 @@
- 防复发:文档写明何时重量(库过 2 GB 或磁盘过 50%)。
- 关联记录:#345(压测)、#348(拆分计算服务)、BUG-2425。
- 修复版本:`bug-2425-backup`(文档,未推送)。
## BUG-2428 | 容器内存上限、计算服务停止慢、磁盘告警晚于备份停止线、恢复点和旧镜像从不清理(按 BUG-2426 容量结论落实)
- 状态:implemented, not deployed(compose 和部署脚本改动要随下一次生产发版生效;未推送)。
- 现象:Gitea #355 后续。BUG-2426 实测:postgres 无内存上限、`oom_score_adj` 0,主机内存不足时可能先杀数据库;api 停止要等满 10 秒被强杀;磁盘告警 80% 比 `run-production-recovery.sh` 的 70% 停备份线还高;`production-pre-migration-*` 恢复点和旧应用镜像(约 2.5 GB)从不清理。
- 触发条件:主机内存吃紧、每次发版、磁盘增长。
- 根因:上线时没有容量数据;BUG-2416 加的上限(api 2 GB / web 1 GB / caddy 256 MB)是安全加固估值,没覆盖 postgres;Python 作为 1 号进程不处理 SIGTERM;磁盘阈值沿用旧值;部署脚本只拉镜像、不清理。
- 修复(负责人 11-26 批准 `docs/operations/capacity-2026-11.md` 的建议):
- `deploy/docker-compose.postgres.yml`:postgres `mem_limit: 1g`、`oom_score_adj: -500`。`deploy/docker-compose.server.yml`:api 1536m(含 512 MB 内存盘 `/tmp`)、web 768m、caddy 128m;BUG-2416 的只读、去权限、pids 等全部保留。
- api `init: true`;web 自己处理 SIGTERM(BUG-2352),不加,`stop_grace_period: 40s` 不变。
- `deploy/monitor/healthcheck-alert.sh` 磁盘告警 80% → 65%(告警文字、安装脚本注释、README 同步)。
- `deploy/monitor/ops-check.sh` 新增 `container_memory_high`:容器用到自己上限 ≥85%(cgroup v2 `memory.current` 减 `inactive_file`,不算可回收缓存;无上限的容器跳过),开一次、恢复一次。因为报告生成时 api 的峰值要等 #345 压测,先用告警兜底。
- 新增 `deploy/prune-production-release.sh`,`run-production-deploy.sh` 在新版本核对通过、写入 `deployed-revision` 之后调用,失败不影响发版:恢复点只留最新 5 个加 `recovery-baseline.env` 指向的那个(校验文件一起删;每日备份和 OSS 不碰);发布仓库里的应用镜像只留当前、上一版和任何容器在用的,按 id 不加 force 删除,postgres/caddy 等其它镜像不动;首次部署或同镜像重部署跳过镜像清理;每删一项打一行 `release_cleanup removed ...`,`RELEASE_CLEANUP_DRY_RUN=1` 只打 `would_remove`。
- 验证:新增 `tests/test_release_capacity_2428.py`(9 项:四个内存上限和 postgres OOM 优先级、api init / web 不加 init 且 40 s 宽限、65% < 70% 停备份线、容器内存告警开一次恢复一次且 postgres 缓存不误报、恢复点保留 5 + 基线并可 dry-run、坏输入拒绝、镜像保留当前/上一版/在用且只删发布仓库、缺保留目标时整体跳过、清理排在核对之后、bash -n);`tests/test_beta_safety_net.py` 磁盘用例改为 64 不报 / 65 报(原值 81,原因见用例注释);`test_monitor_alerts_2348`、`test_railway_deployment`、`test_monitor_scrape_alerts_2417`、`test_production_config_backup_2425` 通过。本机没有 docker/rsync,`docker compose config` 类前端用例要在 CI 上跑。
- 防复发:测试钉住内存上限、init、告警阈值低于停备份线、清理只在核对之后。
- 已知风险:api 内存盘 `/tmp` 写满 512 MB 时与常驻约 1 GB 合计接近 1.5 GB 上限;超了只重启 api(85% 先告警),#345 压测后再定是否调整。
- 关联记录:BUG-2426(容量实测)、BUG-2416(容器加固)、BUG-2352(web 平滑停止)、BUG-2348(告警)、BUG-2425。
- 修复版本:`bug-2428-capacity`(未推送)。
+7
View File
@@ -108,3 +108,10 @@ BUG-2426,Gitea #355。服务器 83.229.126.99:2 核、3.9 GB 内存、4 GB
4. 用户报告和聊天是用户的内容,不建议自动删。库超过 2 GB 时再选:扩磁盘(最省事),或把 30 天前报告的长附录挪到 OSS、库里只留索引。
5. 可以定期删的:过期会话、验证码限流和验证记录(`identity.sessions`/`otp_rate_limits`/`verifications` 30 天以前的),失败的报告任务。量很小,主要是保持整洁。
6. 库过 2 GB 或磁盘过 50% 时重新量一次本表。
## 已落实(BUG-2428,11-26 产品批准,下一次发版生效)
- 内存上限按上表:postgres 1 GB + `oom_score_adj: -500`,api 1.5 GB,web 768 MB,caddy 128 MB(BUG-2416 加的只读、去权限等设置都保留)。api 的内存盘 `/tmp`(最多 512 MB)也算在 1.5 GB 里;生成报告时的峰值要等 #345 压测,所以 `ops-check.sh` 在容器用到自己上限 85% 时先告警(`container_memory_high`)。
- api 加 `init: true`,停容器不再干等 10 秒。web 自己处理 SIGTERM,不加。
- 磁盘告警 80% → 65%。
- 发版核对通过后自动清理:发版前恢复点只留最新 5 个(加上 `recovery-baseline.env` 指向的那个),应用镜像只留当前和上一版。见 `deploy/README.md`“备份”一节。
+9 -3
View File
@@ -603,15 +603,21 @@ def test_disk_alerts_once_and_no_webhook_stays_local(tmp_path: Path) -> None:
"JYOTISHA_MONITOR_ENV": bash_path(tmp_path / "missing.env"),
"JYOTISHA_DAILY_BACKUP_RECORD": bash_path(record),
"JYOTISHA_NOW": "2026-10-15T01:00:00Z",
"FAKE_DISK_PERCENT": "81",
# 原值: 81(阈值 80%)。新值: 64 不告警、65 告警。原因: BUG-2428,备份在 70% 就停,
# 告警要在停备份之前到。
"FAKE_DISK_PERCENT": "64",
}
env.pop("FEISHU_WEBHOOK_URL", None)
env.pop("FEISHU_SIGN_SECRET", None)
below = run_disk_mode(bin_dir, env)
assert below.returncode == 0, below.stderr
assert alert_lines(state) == []
env["FAKE_DISK_PERCENT"] = "65"
completed = run_disk_mode(bin_dir, env)
assert completed.returncode == 0, completed.stderr
assert "errorCode=disk_high" in alert_lines(state)[0]
assert "count=81" in alert_lines(state)[0]
env["FAKE_DISK_PERCENT"] = "81"
assert "count=65" in alert_lines(state)[0]
env["FAKE_DISK_PERCENT"] = "66"
again = run_disk_mode(bin_dir, env)
assert again.returncode == 0, again.stderr
assert len(alert_lines(state)) == 1
+267
View File
@@ -0,0 +1,267 @@
"""BUG-2428: container memory limits, api init, disk alert before the backup stop line,
container memory alert, and release cleanup (recovery points + old app images).
Fixtures are fictional; nothing here touches a real host or Docker."""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
import yaml
from tests.test_beta_safety_net import BASH, ROOT, alert_lines, bash_path, write_text
from tests.test_monitor_alerts_2348 import run_ops
DEPLOY = ROOT / "deploy"
PRUNE = DEPLOY / "prune-production-release.sh"
DEPLOY_SCRIPT = DEPLOY / "run-production-deploy.sh"
def load(name: str) -> dict:
return yaml.safe_load((DEPLOY / name).read_text(encoding="utf-8"))
def test_memory_limits_match_the_owner_approved_capacity_note() -> None:
# 原值: api 2g / web 1g / caddy 256m(BUG-2416),postgres 无上限、oom_score_adj 0。
# 新值: api 1536m / web 768m / caddy 128m / postgres 1g + oom_score_adj -500。
# 原因: BUG-2428,产品 11-26 批准 docs/operations/capacity-2026-11.md 的建议;合计 3.4 GB < 3.9 GB。
server = load("docker-compose.server.yml")["services"]
postgres = load("docker-compose.postgres.yml")["services"]["postgres"]
assert server["api"]["mem_limit"] == "1536m"
assert server["web"]["mem_limit"] == "768m"
assert server["caddy"]["mem_limit"] == "128m"
assert postgres["mem_limit"] == "1g"
assert postgres["oom_score_adj"] < 0 and postgres["oom_score_adj"] == -500
for name in ("api", "web", "caddy"):
assert "oom_score_adj" not in server[name] # only the database is protected
def test_api_gets_init_and_web_keeps_its_own_sigterm_handling() -> None:
# 原值: api 无 init(Python 做 1 号进程不理 SIGTERM,停容器等满 10 秒)。新值: init: true。
services = load("docker-compose.server.yml")["services"]
assert services["api"]["init"] is True
# web handles SIGTERM itself (BUG-2352) and must keep its 40 s grace period.
assert "init" not in services["web"]
assert services["web"]["stop_grace_period"] == "40s"
assert services["web"]["environment"]["NEXT_MANUAL_SIG_HANDLE"] == "true"
# BUG-2416 hardening is unchanged.
for name in ("api", "web"):
assert services[name]["read_only"] is True
assert services[name]["cap_drop"] == ["ALL"]
def test_disk_alert_threshold_is_below_the_backup_stop_line() -> None:
alert = (DEPLOY / "monitor" / "healthcheck-alert.sh").read_text(encoding="utf-8")
recovery = (DEPLOY / "run-production-recovery.sh").read_text(encoding="utf-8")
alert_at = int(re.search(r'if \[ "\$percent" -ge (\d+) \]', alert).group(1))
stop_at = int(re.search(r"\(\( usage_percent < (\d+) \)\)", recovery).group(1))
assert alert_at == 65 and stop_at == 70 and alert_at < stop_at
assert "65%%" in (DEPLOY / "monitor" / "notify-feishu.sh").read_text(encoding="utf-8")
def test_container_memory_alert_opens_once_and_recovers(tmp_path: Path) -> None:
state = tmp_path / "state"
api = "d" * 64
pg = "e" * 64
base = {
"fake_ids": f"{api[:12]}\n{pg[:12]}",
"fake_inspect": f"{api} /jyotisha-production-api-1 0 false\n{pg} /jyotisha-production-postgres-1 0 false",
}
limit = 1536 * 1024 * 1024
api_dir = tmp_path / "cgroup" / "system.slice" / f"docker-{api}.scope"
pg_dir = tmp_path / "cgroup" / "system.slice" / f"docker-{pg}.scope"
api_dir.mkdir(parents=True)
pg_dir.mkdir(parents=True)
# postgres: page cache fills the limit, but it is inactive_file, so no alert.
write_text(pg_dir / "memory.current", f"{1024 ** 3}\n")
write_text(pg_dir / "memory.max", f"{1024 ** 3}\n")
write_text(pg_dir / "memory.stat", f"anon 200000000\ninactive_file {700 * 1024 ** 2}\n")
def run(used: int):
write_text(api_dir / "memory.current", f"{used + 50 * 1024 ** 2}\n")
write_text(api_dir / "memory.max", f"{limit}\n")
write_text(api_dir / "memory.stat", f"anon {used}\ninactive_file {50 * 1024 ** 2}\n")
return run_ops(tmp_path, state, **base)
assert run(1000 * 1024 ** 2).returncode == 0 # 65 %: quiet
assert [line for line in alert_lines(state) if "memory" in line] == []
assert run(limit * 9 // 10 + 1024).returncode == 0
lines = [line for line in alert_lines(state) if "container_memory_high" in line]
assert len(lines) == 1 and "service=api" in lines[0] and "count=90" in lines[0]
assert run(int(limit * 0.95)).returncode == 0
assert len([line for line in alert_lines(state) if "container_memory_high" in line]) == 1
assert run(700 * 1024 ** 2).returncode == 0
assert "service=api" in alert_lines(state)[-1] and "errorCode=recovered" in alert_lines(state)[-1]
assert not any("service=postgres" in line for line in alert_lines(state))
def run_prune(script: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[BASH, "-c", f'source "{bash_path(PRUNE)}"\n{script}'],
capture_output=True, text=True, encoding="utf-8",
env={"PATH": "/usr/bin:/bin", **(env or {})},
)
def point(directory: Path, stamp: str, verify: bool = True) -> str:
name = f"production-pre-migration-{stamp}.dump.enc"
write_text(directory / name, "x")
if verify:
write_text(directory / f"production-pre-migration-{stamp}-restore-verify.json", "{}")
return name
def test_recovery_points_keep_newest_five_plus_baseline(tmp_path: Path) -> None:
backups = tmp_path / "backups"
backups.mkdir()
stamps = [f"202611{day:02d}T030000Z" for day in range(1, 9)] # 8 points, oldest first
names = [point(backups, stamp) for stamp in stamps]
daily = backups / "production-daily-20261101T040000Z.dump.enc"
write_text(daily, "d")
other = backups / "production-pre-migration-notes.txt"
write_text(other, "keep")
baseline = tmp_path / "recovery-baseline.env"
write_text(baseline, f"RECOVERY_REFERENCE=gitea-actions-run-1/{names[0]}\nRECOVERY_FORMAT=2\n")
dry = run_prune(f'prune_recovery_points "{bash_path(backups)}" 5 "{bash_path(baseline)}"',
{"RELEASE_CLEANUP_DRY_RUN": "1"})
assert dry.returncode == 0, dry.stderr
assert dry.stdout.count("would_remove recovery_point=") == 2
assert all((backups / name).exists() for name in names)
done = run_prune(f'prune_recovery_points "{bash_path(backups)}" 5 "{bash_path(baseline)}"')
assert done.returncode == 0, done.stderr
removed = re.findall(r"removed recovery_point=(\S+)", done.stdout)
assert removed == [names[2], names[1]] # oldest two outside the newest five; baseline kept
remaining = sorted(path.name for path in backups.glob("production-pre-migration-*.dump.enc"))
assert remaining == sorted([names[0], *names[3:]])
assert not (backups / f"production-pre-migration-{stamps[1]}-restore-verify.json").exists()
assert (backups / f"production-pre-migration-{stamps[0]}-restore-verify.json").exists()
assert daily.exists() and other.exists()
assert "recovery_points_kept=5 baseline=" in done.stdout
again = run_prune(f'prune_recovery_points "{bash_path(backups)}" 5 "{bash_path(baseline)}"')
assert "removed" not in again.stdout
def test_recovery_points_refuse_unsafe_input(tmp_path: Path) -> None:
target = tmp_path / "real"
target.mkdir()
link = tmp_path / "link"
link.symlink_to(target)
assert run_prune(f'prune_recovery_points "{bash_path(link)}" 5').returncode != 0
assert run_prune(f'prune_recovery_points "{bash_path(target)}" 0').returncode != 0
assert run_prune('prune_recovery_points "" 5').returncode != 0
FAKE_DOCKER = r'''#!PYTHON
import json, sys
cfg_path = sys.argv[0] + ".json"
cfg = json.load(open(cfg_path))
args = sys.argv[1:]
def out(lines):
for line in lines:
print(line)
if args[:2] == ["image", "inspect"]:
fmt, ref = args[3], args[4]
image = cfg["refs"].get(ref, ref)
if image not in cfg["images"]:
sys.exit(1)
if fmt == "{{.Id}}":
out([image])
else:
out(cfg["images"][image])
elif args[:2] == ["image", "ls"]:
out(list(cfg["images"]))
elif args[:2] == ["image", "rm"]:
image = args[2]
if image in cfg.get("busy", []):
sys.exit(1)
del cfg["images"][image]
cfg.setdefault("removed", []).append(image)
json.dump(cfg, open(cfg_path, "w"))
elif args[:1] == ["ps"]:
out(list(cfg["containers"]))
elif args[:1] == ["inspect"]:
out([cfg["containers"][args[3]]])
else:
sys.exit(2)
'''
def image_id(char: str) -> str:
return "sha256:" + char * 64
def test_release_images_keep_current_previous_and_in_use(tmp_path: Path) -> None:
repo = "registry.example:5000/root/jyotisha"
cur_api, cur_web, prev_api, prev_web = image_id("1"), image_id("2"), image_id("3"), image_id("4")
old_api, old_web, stopped, busy = image_id("5"), image_id("6"), image_id("7"), image_id("8")
postgres, caddy = image_id("a"), image_id("b")
cur_api_ref = f"{repo}@sha256:{'1' * 64}"
images = {
cur_api: [cur_api_ref],
cur_web: [f"{repo}@sha256:{'2' * 64}"],
prev_api: [f"{repo}@sha256:{'3' * 64}"],
prev_web: [f"{repo}@sha256:{'4' * 64}"],
old_api: [f"{repo}@sha256:{'5' * 64}"],
old_web: [f"{repo}:web-old"],
stopped: [f"{repo}@sha256:{'7' * 64}"],
busy: [f"{repo}@sha256:{'8' * 64}"],
postgres: ["postgres@sha256:" + "a" * 64, "postgres:17-alpine"],
caddy: ["caddy@sha256:" + "b" * 64],
}
cfg = {
"refs": {cur_api_ref: cur_api, f"{repo}@sha256:{'2' * 64}": cur_web},
"images": images,
"containers": {"c1": cur_api, "c2": cur_web, "c3": postgres, "c4": stopped},
"busy": [busy],
}
docker = tmp_path / "docker"
write_text(docker, FAKE_DOCKER.replace("#!PYTHON", f"#!{sys.executable}"))
docker.chmod(0o755)
(tmp_path / "docker.json").write_text(json.dumps(cfg), encoding="utf-8")
env = {"PATH": f"{bash_path(tmp_path)}:/usr/bin:/bin"}
call = (f'prune_release_images "{repo}" "{cur_api_ref}" "{repo}@sha256:{"2" * 64}" '
f'"{prev_api}" "{prev_web}"')
dry = run_prune(call, {**env, "RELEASE_CLEANUP_DRY_RUN": "1"})
assert dry.returncode == 0, dry.stderr
assert dry.stdout.count("would_remove image=") == 3
assert "removed" not in json.loads((tmp_path / "docker.json").read_text())
done = run_prune(call, env)
assert done.returncode == 0, done.stderr
state = json.loads((tmp_path / "docker.json").read_text())
assert sorted(state["removed"]) == sorted([old_api, old_web])
assert f"image_remove_failed image={'8' * 12}" in done.stdout
for kept in (cur_api, cur_web, prev_api, prev_web, stopped, busy, postgres, caddy):
assert kept in state["images"]
# A keep target missing on the host: nothing is removed at all.
missing = run_prune(f'prune_release_images "{repo}" "{image_id("f")}"', env)
assert missing.returncode == 0 and "removed" not in missing.stdout
assert run_prune('prune_release_images "bad repo" x', env).returncode != 0
def test_deploy_runs_cleanup_only_after_verification() -> None:
text = DEPLOY_SCRIPT.read_text(encoding="utf-8")
cleanup = text.index("source deploy/prune-production-release.sh")
assert text.index('mv -f "$revision_file" "$state_directory/deployed-revision"') < cleanup
assert text.index("trap - ERR") < cleanup
assert 'prune_recovery_points "$DEPLOY_PATH/backups" 5 "$state_directory/recovery-baseline.env" ||' in text
assert '"$previous_api_target" "$previous_web_target" ||' in text
assert "images_skipped=no_distinct_previous_release" in text
prune = PRUNE.read_text(encoding="utf-8")
assert "image rm -f" not in prune and "--force" not in prune and "system prune" not in prune
assert "production-daily" not in prune.split("set -euo pipefail", 1)[1]
assert "oss" not in prune.lower().split("set -euo pipefail", 1)[1]
def test_release_scripts_pass_bash_n() -> None:
for script in (PRUNE, DEPLOY_SCRIPT, DEPLOY / "monitor" / "ops-check.sh", DEPLOY / "monitor" / "healthcheck-alert.sh"):
completed = subprocess.run([BASH, "-n", str(script)], capture_output=True, text=True)
assert completed.returncode == 0, completed.stderr