503 lines
16 KiB
Bash
503 lines
16 KiB
Bash
#!/usr/bin/env zsh
|
||
|
||
# Production deployment, backup, and migration helpers sourced by planet.sh.
|
||
|
||
deploy_resolve_python() {
|
||
local venv_python="${SCRIPT_DIR:-.}/.venv/bin/python"
|
||
if [ -x "$venv_python" ]; then
|
||
printf "%s\n" "$venv_python"
|
||
return 0
|
||
fi
|
||
if command -v python3 >/dev/null 2>&1; then
|
||
command -v python3
|
||
return 0
|
||
fi
|
||
return 1
|
||
}
|
||
|
||
deploy_usage() {
|
||
cat <<'EOF'
|
||
用法: ./planet.sh deploy [up|down|restart|status|logs|init-env] [选项]
|
||
|
||
选项:
|
||
--split 启用 API + Worker 拆分高可用模式 (backend API-only + worker 调度实例)
|
||
--no-build 使用本地已有镜像启动,不重新构建
|
||
--env-file <path> 指定部署环境变量文件 (默认: ./.env.deploy)
|
||
--force 与 init-env 配合使用,允许覆盖已有环境文件
|
||
-h, --help 显示此帮助信息
|
||
EOF
|
||
}
|
||
|
||
backup_usage() {
|
||
"$SCRIPT_DIR/scripts/backup_db.sh" --help
|
||
}
|
||
|
||
migrate_usage() {
|
||
cat <<'EOF'
|
||
用法: ./planet.sh migrate {status|upgrade|stamp <version>} [--container [容器名]]
|
||
|
||
说明:
|
||
status 查看已应用、待应用与校验和异常的数据库迁移
|
||
upgrade 按顺序执行所有待应用迁移 (带 PostgreSQL Advisory Lock)
|
||
stamp <version> 将指定版本及之前迁移标记为已应用(不执行 SQL)
|
||
--container [name] 在运行中的后端容器内执行 (默认: planet_deploy_backend)
|
||
EOF
|
||
}
|
||
|
||
deploy_parse_env_file_value() {
|
||
local env_file="$1"
|
||
local target_key="$2"
|
||
local default_val="${3:-}"
|
||
local py_bin=""
|
||
|
||
py_bin="$(deploy_resolve_python || true)"
|
||
[ -n "$py_bin" ] && [ -f "$env_file" ] || {
|
||
printf "%s\n" "$default_val"
|
||
return 0
|
||
}
|
||
|
||
"$py_bin" - "$env_file" "$target_key" "$default_val" <<'PY'
|
||
from pathlib import Path
|
||
import sys
|
||
|
||
env_path, key, default_val = Path(sys.argv[1]), sys.argv[2], sys.argv[3]
|
||
found = default_val
|
||
for raw in env_path.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||
line = raw.strip()
|
||
if not line or line.startswith("#") or "=" not in line:
|
||
continue
|
||
k, v = line.split("=", 1)
|
||
k = k.strip()
|
||
if k.startswith("export "):
|
||
k = k[len("export "):].strip()
|
||
if k == key:
|
||
v = v.strip()
|
||
if len(v) >= 2 and v[0] == v[-1] and v[0] in ("'", '"'):
|
||
v = v[1:-1]
|
||
found = v
|
||
print(found)
|
||
PY
|
||
}
|
||
|
||
deploy_init_env() {
|
||
local env_file="$1"
|
||
local force="${2:-0}"
|
||
local py_bin=""
|
||
|
||
if [ -f "$env_file" ] && [ "$force" -ne 1 ]; then
|
||
log_error "部署环境文件已存在: ${env_file}(如需覆盖请追加 --force)"
|
||
return 1
|
||
fi
|
||
|
||
py_bin="$(deploy_resolve_python || true)"
|
||
if [ -z "$py_bin" ]; then
|
||
log_error "未找到 Python 运行时,无法生成高强度随机密钥"
|
||
return 1
|
||
fi
|
||
|
||
local admin_user="${INITIAL_ADMIN_USERNAME:-}"
|
||
local admin_email="${INITIAL_ADMIN_EMAIL:-}"
|
||
local admin_password="${INITIAL_ADMIN_PASSWORD:-}"
|
||
local generated_password=0
|
||
|
||
if [ -z "$admin_user" ]; then
|
||
if [ -t 0 ]; then
|
||
printf "初始超级管理员用户名 [admin_prod]: " >&2
|
||
read -r admin_user || true
|
||
fi
|
||
admin_user="${admin_user:-admin_prod}"
|
||
fi
|
||
|
||
if [ -z "$admin_email" ]; then
|
||
local default_email="${admin_user}@planet.local"
|
||
if [ -t 0 ]; then
|
||
printf "初始超级管理员邮箱 [%s]: " "$default_email" >&2
|
||
read -r admin_email || true
|
||
fi
|
||
admin_email="${admin_email:-$default_email}"
|
||
fi
|
||
|
||
if [ -z "$admin_password" ]; then
|
||
if [ -t 0 ]; then
|
||
local password_confirm=""
|
||
while true; do
|
||
printf "初始超级管理员密码 (至少8位): " >&2
|
||
read -rs admin_password || true
|
||
printf "\n" >&2
|
||
if [ "${#admin_password}" -lt 8 ]; then
|
||
log_warn "密码长度不能少于 8 位,请重新输入"
|
||
continue
|
||
fi
|
||
printf "确认密码: " >&2
|
||
read -rs password_confirm || true
|
||
printf "\n" >&2
|
||
if [ "$admin_password" != "$password_confirm" ]; then
|
||
log_warn "两次输入密码不一致,请重新输入"
|
||
continue
|
||
fi
|
||
break
|
||
done
|
||
else
|
||
admin_password="$("$py_bin" -c 'import secrets; print(secrets.token_urlsafe(14))')"
|
||
generated_password=1
|
||
fi
|
||
fi
|
||
|
||
mkdir -p "$(dirname "$env_file")"
|
||
DEPLOY_ENV_TARGET="$env_file" \
|
||
DEPLOY_ADMIN_USER="$admin_user" \
|
||
DEPLOY_ADMIN_EMAIL="$admin_email" \
|
||
DEPLOY_ADMIN_PASSWORD="$admin_password" \
|
||
DEPLOY_CORS_ORIGINS="${CORS_ORIGINS:-[]}" \
|
||
DEPLOY_ADMIN_PORT="${PLANET_ADMIN_PORT:-3000}" \
|
||
DEPLOY_FRONTEND_TARGET="${PLANET_FRONTEND_TARGET:-full}" \
|
||
"$py_bin" - <<'PY'
|
||
import base64
|
||
import os
|
||
from pathlib import Path
|
||
import secrets
|
||
|
||
target = Path(os.environ["DEPLOY_ENV_TARGET"])
|
||
secret_key = secrets.token_urlsafe(40)
|
||
service_token = secrets.token_urlsafe(32)
|
||
encryption_key = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode("ascii")
|
||
pg_password = secrets.token_urlsafe(20)
|
||
redis_password = secrets.token_urlsafe(20)
|
||
|
||
content = "\n".join(
|
||
[
|
||
"# Planet production deployment environment (generated by ./planet.sh deploy init-env)",
|
||
"APP_ENV=production",
|
||
"PLANET_ROLE=all",
|
||
f"PLANET_FRONTEND_TARGET={os.environ['DEPLOY_FRONTEND_TARGET']}",
|
||
f"PLANET_ADMIN_PORT={os.environ['DEPLOY_ADMIN_PORT']}",
|
||
f"CORS_ORIGINS={os.environ['DEPLOY_CORS_ORIGINS']}",
|
||
"",
|
||
"# Cryptographic keys and internal service tokens",
|
||
f"SECRET_KEY={secret_key}",
|
||
"ACCESS_TOKEN_EXPIRE_MINUTES=60",
|
||
"REFRESH_TOKEN_EXPIRE_DAYS=7",
|
||
f"AI_PROVIDER_SERVICE_TOKEN={service_token}",
|
||
f"SETTINGS_ENCRYPTION_KEY={encryption_key}",
|
||
"",
|
||
"# Database & Redis",
|
||
"POSTGRES_USER=postgres",
|
||
f"POSTGRES_PASSWORD={pg_password}",
|
||
"POSTGRES_DB=planet_db",
|
||
f"REDIS_PASSWORD={redis_password}",
|
||
"",
|
||
"# Initial super_admin (used when bootstrapping an empty/production DB)",
|
||
f"INITIAL_ADMIN_USERNAME={os.environ['DEPLOY_ADMIN_USER']}",
|
||
f"INITIAL_ADMIN_EMAIL={os.environ['DEPLOY_ADMIN_EMAIL']}",
|
||
f"INITIAL_ADMIN_PASSWORD={os.environ['DEPLOY_ADMIN_PASSWORD']}",
|
||
"",
|
||
"# Collector concurrency guardrails",
|
||
"COLLECTOR_MAX_CONCURRENCY=2",
|
||
"COLLECTOR_HEAVY_CONCURRENCY=1",
|
||
"",
|
||
]
|
||
)
|
||
target.write_text(content, encoding="utf-8")
|
||
os.chmod(target, 0o600)
|
||
PY
|
||
|
||
log_success "已生成生产部署环境文件: ${env_file} (权限 0600)"
|
||
if [ "$generated_password" -eq 1 ]; then
|
||
log_note "已为非交互环境自动生成初始超级管理员密码,请在 ${env_file} 中查看 INITIAL_ADMIN_PASSWORD"
|
||
fi
|
||
}
|
||
|
||
deploy_validate_env_file() {
|
||
local env_file="$1"
|
||
local py_bin=""
|
||
|
||
if [ ! -f "$env_file" ]; then
|
||
log_error "缺少部署环境文件: ${env_file}"
|
||
return 1
|
||
fi
|
||
|
||
py_bin="$(deploy_resolve_python || true)"
|
||
if [ -z "$py_bin" ]; then
|
||
log_error "未找到 Python 运行时,无法校验生产环境配置"
|
||
return 1
|
||
fi
|
||
|
||
"$py_bin" - "$env_file" <<'PY'
|
||
import json
|
||
from pathlib import Path
|
||
import sys
|
||
|
||
env_path = Path(sys.argv[1])
|
||
values: dict[str, str] = {}
|
||
for raw in env_path.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||
line = raw.strip()
|
||
if not line or line.startswith("#") or "=" not in line:
|
||
continue
|
||
k, v = line.split("=", 1)
|
||
k = k.strip()
|
||
if k.startswith("export "):
|
||
k = k[len("export "):].strip()
|
||
v = v.strip()
|
||
if len(v) >= 2 and v[0] == v[-1] and v[0] in ("'", '"'):
|
||
v = v[1:-1]
|
||
values[k] = v
|
||
|
||
weak_secrets = {
|
||
"",
|
||
"change-me",
|
||
"change_me",
|
||
"change_me_to_a_random_secret",
|
||
"change_me_to_a_random_32_plus_char_secret",
|
||
"your-secret-key-change-in-production",
|
||
"replace-with-strong-32-char-random-secret",
|
||
}
|
||
weak_tokens = {"", "change-me", "change_me", "replace-with-internal-token"}
|
||
errors: list[str] = []
|
||
|
||
app_env = values.get("APP_ENV", "production").strip().lower()
|
||
if app_env != "production":
|
||
errors.append(f"APP_ENV 应为 production(当前: {app_env!r})")
|
||
|
||
secret_key = values.get("SECRET_KEY", "").strip()
|
||
if secret_key in weak_secrets or len(secret_key) < 32:
|
||
errors.append("SECRET_KEY 必须为至少 32 字符的随机字符串且不能使用占位符")
|
||
|
||
try:
|
||
if int(values.get("ACCESS_TOKEN_EXPIRE_MINUTES", "60")) <= 0:
|
||
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES 必须大于 0")
|
||
except ValueError:
|
||
errors.append("ACCESS_TOKEN_EXPIRE_MINUTES 必须为整数")
|
||
|
||
try:
|
||
if int(values.get("REFRESH_TOKEN_EXPIRE_DAYS", "7")) <= 0:
|
||
errors.append("REFRESH_TOKEN_EXPIRE_DAYS 必须大于 0")
|
||
except ValueError:
|
||
errors.append("REFRESH_TOKEN_EXPIRE_DAYS 必须为整数")
|
||
|
||
service_token = values.get("AI_PROVIDER_SERVICE_TOKEN", "").strip()
|
||
if service_token in weak_tokens:
|
||
errors.append("AI_PROVIDER_SERVICE_TOKEN 不能为空或占位符")
|
||
|
||
cors_raw = values.get("CORS_ORIGINS", "[]").strip()
|
||
try:
|
||
cors_list = json.loads(cors_raw) if cors_raw else []
|
||
if not isinstance(cors_list, list):
|
||
errors.append("CORS_ORIGINS 必须为 JSON 数组")
|
||
elif "*" in cors_list:
|
||
errors.append("生产环境 CORS_ORIGINS 禁止包含 '*'")
|
||
except json.JSONDecodeError:
|
||
errors.append("CORS_ORIGINS 必须为合法 JSON 数组(例如 [] 或 [\"https://planet.example.com\"])")
|
||
|
||
if errors:
|
||
for err in errors:
|
||
sys.stderr.write(f"配置校验失败: {err}\n")
|
||
raise SystemExit(1)
|
||
PY
|
||
}
|
||
|
||
deploy_compose_exec() {
|
||
local env_file="$1"
|
||
local split_mode="$2"
|
||
shift 2
|
||
|
||
local -a prefix=()
|
||
local -a profile_args=()
|
||
if [ "$split_mode" -eq 1 ]; then
|
||
prefix=(env PLANET_ROLE=api)
|
||
profile_args=(--profile split)
|
||
fi
|
||
|
||
if (( $+functions[compose_available] )) && compose_available; then
|
||
"${prefix[@]}" docker compose --env-file "$env_file" -f "$SCRIPT_DIR/docker-compose.deploy.yml" "${profile_args[@]}" "$@"
|
||
return $?
|
||
fi
|
||
if command -v docker-compose >/dev/null 2>&1; then
|
||
"${prefix[@]}" docker-compose --env-file "$env_file" -f "$SCRIPT_DIR/docker-compose.deploy.yml" "${profile_args[@]}" "$@"
|
||
return $?
|
||
fi
|
||
|
||
log_error "未找到 Docker Compose,请先安装或启动 Docker"
|
||
return 1
|
||
}
|
||
|
||
deploy_command() {
|
||
local action="up"
|
||
local split_mode=0
|
||
local no_build=0
|
||
local force_init=0
|
||
local env_file="$SCRIPT_DIR/.env.deploy"
|
||
local -a passthrough=()
|
||
|
||
if [ "$#" -gt 0 ]; then
|
||
case "$1" in
|
||
up|down|restart|status|logs|init-env)
|
||
action="$1"
|
||
shift
|
||
;;
|
||
-h|--help|help)
|
||
deploy_usage
|
||
return 0
|
||
;;
|
||
esac
|
||
fi
|
||
|
||
while [ "$#" -gt 0 ]; do
|
||
case "$1" in
|
||
--split)
|
||
split_mode=1
|
||
shift
|
||
;;
|
||
--no-build)
|
||
no_build=1
|
||
shift
|
||
;;
|
||
--force)
|
||
force_init=1
|
||
shift
|
||
;;
|
||
--env-file)
|
||
if [ "$#" -lt 2 ]; then
|
||
log_error "--env-file 需要提供路径参数"
|
||
return 1
|
||
fi
|
||
env_file="$2"
|
||
shift 2
|
||
;;
|
||
--env-file=*)
|
||
env_file="${1#--env-file=}"
|
||
shift
|
||
;;
|
||
-h|--help|help)
|
||
deploy_usage
|
||
return 0
|
||
;;
|
||
*)
|
||
passthrough+=("$1")
|
||
shift
|
||
;;
|
||
esac
|
||
done
|
||
|
||
case "$action" in
|
||
init-env)
|
||
deploy_init_env "$env_file" "$force_init"
|
||
return $?
|
||
;;
|
||
up)
|
||
if (( $+functions[ensure_docker_runtime] )); then
|
||
ensure_docker_runtime "${PLANET_COMMAND_ARGS[@]}" || return 1
|
||
fi
|
||
if [ ! -f "$env_file" ]; then
|
||
log_step "未发现 ${env_file},正在生成生产环境配置"
|
||
deploy_init_env "$env_file" 0 || return 1
|
||
fi
|
||
deploy_validate_env_file "$env_file" || return 1
|
||
local -a up_args=(up -d)
|
||
if [ "$no_build" -eq 0 ]; then
|
||
up_args+=(--build)
|
||
fi
|
||
[ "$split_mode" -eq 1 ] && log_step "启动生产环境 (API + Worker 拆分模式)" || log_step "启动生产环境 (单节点模式)"
|
||
deploy_compose_exec "$env_file" "$split_mode" "${up_args[@]}" "${passthrough[@]}" || return 1
|
||
local admin_port=""
|
||
admin_port="$(deploy_parse_env_file_value "$env_file" "PLANET_ADMIN_PORT" "3000")"
|
||
log_success "生产环境容器已启动: http://127.0.0.1:${admin_port}/"
|
||
if command -v curl >/dev/null 2>&1; then
|
||
if curl -fsS --max-time 3 "http://127.0.0.1:${admin_port}/api/health/ready" >/dev/null 2>&1; then
|
||
log_success "后端就绪探针 (/api/health/ready) 已通过"
|
||
else
|
||
log_note "服务仍在初始化,稍后可执行 ./planet.sh deploy status 查看就绪状态"
|
||
fi
|
||
fi
|
||
;;
|
||
down)
|
||
deploy_compose_exec "$env_file" "$split_mode" down "${passthrough[@]}"
|
||
;;
|
||
restart)
|
||
deploy_validate_env_file "$env_file" || return 1
|
||
deploy_compose_exec "$env_file" "$split_mode" restart "${passthrough[@]}"
|
||
;;
|
||
status)
|
||
deploy_compose_exec "$env_file" "$split_mode" ps
|
||
local admin_port=""
|
||
admin_port="$(deploy_parse_env_file_value "$env_file" "PLANET_ADMIN_PORT" "3000")"
|
||
if (( $+functions[print_http_health_status] )); then
|
||
print_http_health_status "生产入口存活" "http://127.0.0.1:${admin_port}/api/health/live"
|
||
print_http_health_status "生产入口就绪" "http://127.0.0.1:${admin_port}/api/health/ready"
|
||
fi
|
||
;;
|
||
logs)
|
||
if [ "${#passthrough[@]}" -gt 0 ]; then
|
||
deploy_compose_exec "$env_file" "$split_mode" logs -f "${passthrough[@]}"
|
||
else
|
||
deploy_compose_exec "$env_file" "$split_mode" logs --tail 80 -f
|
||
fi
|
||
;;
|
||
esac
|
||
}
|
||
|
||
backup_command() {
|
||
for arg in "$@"; do
|
||
case "$arg" in
|
||
-h|--help|help)
|
||
backup_usage
|
||
return 0
|
||
;;
|
||
esac
|
||
done
|
||
"$SCRIPT_DIR/scripts/backup_db.sh" "$@"
|
||
}
|
||
|
||
migrate_command() {
|
||
local use_container=0
|
||
local container_name="planet_deploy_backend"
|
||
local -a migrate_args=()
|
||
|
||
while [ "$#" -gt 0 ]; do
|
||
case "$1" in
|
||
-h|--help|help)
|
||
migrate_usage
|
||
return 0
|
||
;;
|
||
--container)
|
||
use_container=1
|
||
if [ "$#" -ge 2 ] && [[ "$2" != -* ]] && [ "$2" != "status" ] && [ "$2" != "upgrade" ] && [ "$2" != "stamp" ]; then
|
||
container_name="$2"
|
||
shift 2
|
||
else
|
||
shift
|
||
fi
|
||
;;
|
||
--container=*)
|
||
use_container=1
|
||
container_name="${1#--container=}"
|
||
shift
|
||
;;
|
||
*)
|
||
migrate_args+=("$1")
|
||
shift
|
||
;;
|
||
esac
|
||
done
|
||
|
||
if [ "${#migrate_args[@]}" -eq 0 ]; then
|
||
migrate_usage
|
||
return 2
|
||
fi
|
||
|
||
if [ "$use_container" -eq 1 ]; then
|
||
docker exec "$container_name" uv run --frozen --no-dev --project /app python /app/scripts/db_migrate.py "${migrate_args[@]}"
|
||
return $?
|
||
fi
|
||
|
||
local py_bin=""
|
||
py_bin="$(deploy_resolve_python || true)"
|
||
if command -v uv >/dev/null 2>&1; then
|
||
uv run --frozen --project "$SCRIPT_DIR" python "$SCRIPT_DIR/scripts/db_migrate.py" "${migrate_args[@]}"
|
||
elif [ -n "$py_bin" ]; then
|
||
PYTHONPATH="$SCRIPT_DIR/backend" "$py_bin" "$SCRIPT_DIR/scripts/db_migrate.py" "${migrate_args[@]}"
|
||
else
|
||
log_error "未找到 uv 或 Python 运行时"
|
||
return 1
|
||
fi
|
||
}
|