Files
ClaudeandClaude Opus 5.5 0054781bc5
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
ops: container memory limits, api init, 65% disk alert, release cleanup (BUG-2428)
- 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
2026-11-26 23:18:02 +08:00

359 lines
13 KiB
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# Shared alert sender. Source this file; do not execute it.
# 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"
mkdir -p -- "$dir"
if [ "$(uname -s)" = "Linux" ]; then
chmod 700 "$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
[ -n "$file" ] || return 0
[ -f "$file" ] && [ ! -L "$file" ] || return 0
if [ "$(uname -s)" = "Linux" ]; then
mode="$(stat -c %a "$file")"
[ "$mode" = "600" ] || {
echo "monitor env must be mode 0600" >&2
exit 1
}
fi
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
""|\#*) continue ;;
FEISHU_WEBHOOK_URL=*|FEISHU_SIGN_SECRET=*|ALERT_EMAIL_TO=*|ALERT_EMAIL_FROM=*|RESEND_API_KEY=*)
key="${line%%=*}"
value="${line#*=}"
monitor_env_value_safe "$value" || {
echo "monitor env value is unsafe" >&2
exit 1
}
printf -v "$key" '%s' "$value"
export "$key"
;;
esac
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"
local string_to_sign
string_to_sign="$(printf '%s\n%s' "$timestamp" "$secret")"
printf '' | openssl dgst -sha256 -hmac "$string_to_sign" -binary | openssl base64 -A
}
webhook_allowed() {
local url="$1"
[[ "$url" =~ ^https://open\.(feishu\.cn|larksuite\.com|larkoffice\.com)/open-apis/bot/v2/hook/[A-Za-z0-9-]+$ ]] && return 0
[[ "$url" =~ ^http://127\.0\.0\.1:[0-9]{1,5}/hook$ ]] && return 0
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$ ]]
}
# 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 '磁盘使用超过 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 看' ;;
cpu_high) printf '服务器 CPU 持续很高(约 10 分钟,数字是使用百分比),可能被挖矿' ;;
container_cpu_high) printf '某个容器 CPU 持续很高(约 10 分钟,数字是占一个核的百分比)' ;;
suspicious_process) printf '有不在白名单里的进程占用大量 CPU(数字是进程号,路径里是进程名)' ;;
miner_process) printf '发现疑似挖矿程序(数字是进程号,路径里是进程名)' ;;
mining_pool_connection) printf '有进程连到常见矿池端口(数字是进程号,路径里是进程名)' ;;
otp_send_failed) printf '验证码邮件发不出去' ;;
model_spend_alert) printf '今天的模型花费超过设定值' ;;
model_fallback_used) printf '默认模型失败,已切到备用模型' ;;
bulk_export) printf '同一账号一小时(或一天)内导出很多份报告(requestId 是账号代号,后台客户页可搜)' ;;
templated_questions) printf '同一账号把同一个问题换着很多人的星盘问(requestId 是账号代号,后台客户页可搜)' ;;
bulk_profiles) printf '同一账号一小时内新建很多个星盘档案(requestId 是账号代号,后台客户页可搜)' ;;
export_unmarked) 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
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"
}
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
}
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")"
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; charset=utf-8' \
-H 'Connection: close' \
--data-binary @"$payload_file" \
-o "$response_file" \
"$FEISHU_WEBHOOK_URL" || curl_status=$?
code=""
if [ "$curl_status" -eq 0 ]; then
code="$("$py" - "$response_file" <<'PY'
import json, sys
try:
payload = json.load(open(sys.argv[1], encoding="utf-8"))
except Exception:
payload = None
print("0" if isinstance(payload, dict) and payload.get("code") == 0 else "")
PY
)"
code="$(printf '%s' "$code" | tr -d '\r')"
fi
rm -f -- "$payload_file" "$response_file"
if [ "$curl_status" -ne 0 ] || [ "$code" != "0" ]; then
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"
}