release: bump version to 0.78.0
This commit is contained in:
1 parent
e6aa8c539b
commit
5fc698d738
96 files changed
+10214
-747
No files matched your search
Executable
+138
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
OUTPUT_DIR="${PLANET_BACKUP_DIR:-./backups/postgres}"
|
||||
RETENTION_DAYS="${PLANET_BACKUP_RETENTION_DAYS:-14}"
|
||||
MODE="full"
|
||||
CONTAINER_NAME=""
|
||||
VERIFY_GZIP=1
|
||||
POSTGRES_USER_VALUE="${POSTGRES_USER:-postgres}"
|
||||
POSTGRES_DB_VALUE="${POSTGRES_DB:-planet_db}"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: scripts/backup_db.sh [options]
|
||||
|
||||
Create a compressed PostgreSQL backup and prune expired archives after success.
|
||||
|
||||
Options:
|
||||
--output-dir <path> Backup output directory (default: ./backups/postgres)
|
||||
--retention-days <days> Delete .sql.gz files older than N days (default: 14)
|
||||
--mode <full|core> full: complete DB dump (default)
|
||||
core: schema + core config/users/assessment tables
|
||||
(skips high-volume collected_data/logs/bgp_observations)
|
||||
--container <name> Docker Postgres container name (auto-detects running container)
|
||||
--no-verify Skip gzip integrity verification after dump
|
||||
-h, --help Show this help message
|
||||
EOF
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--output-dir)
|
||||
OUTPUT_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
--retention-days)
|
||||
RETENTION_DAYS="$2"
|
||||
shift 2
|
||||
;;
|
||||
--mode)
|
||||
MODE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--container)
|
||||
CONTAINER_NAME="$2"
|
||||
shift 2
|
||||
;;
|
||||
--no-verify)
|
||||
VERIFY_GZIP=0
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown option: %s\n' "$1" >&2
|
||||
usage >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ "$MODE" != "full" && "$MODE" != "core" ]]; then
|
||||
printf 'Invalid --mode: %s (expected full or core)\n' "$MODE" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if ! [[ "$RETENTION_DAYS" =~ ^[0-9]+$ ]]; then
|
||||
printf 'Invalid --retention-days: %s\n' "$RETENTION_DAYS" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
detect_container() {
|
||||
if [[ -n "$CONTAINER_NAME" ]]; then
|
||||
printf '%s\n' "$CONTAINER_NAME"
|
||||
return 0
|
||||
fi
|
||||
if command -v docker >/dev/null 2>&1; then
|
||||
local candidate
|
||||
for candidate in planet_deploy_postgres planet_postgres; do
|
||||
if docker ps --format '{{.Names}}' | grep -qx "$candidate"; then
|
||||
printf '%s\n' "$candidate"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
TARGET_FILE="${OUTPUT_DIR%/}/planet_${POSTGRES_DB_VALUE}_${MODE}_${STAMP}.sql.gz"
|
||||
TMP_FILE="${TARGET_FILE}.tmp"
|
||||
|
||||
cleanup_tmp() {
|
||||
rm -f "$TMP_FILE"
|
||||
}
|
||||
trap cleanup_tmp EXIT
|
||||
|
||||
PG_DUMP_ARGS=(--no-owner --no-privileges --format=plain)
|
||||
if [[ "$MODE" == "core" ]]; then
|
||||
PG_DUMP_ARGS+=(
|
||||
--exclude-table-data=collected_data
|
||||
--exclude-table-data=bgp_observations
|
||||
--exclude-table-data=ais_raw_observations
|
||||
--exclude-table-data=system_logs
|
||||
--exclude-table-data=observability_events
|
||||
--exclude-table-data=earth_data_change_events
|
||||
)
|
||||
fi
|
||||
|
||||
if ACTIVE_CONTAINER="$(detect_container)"; then
|
||||
docker exec -e PGPASSWORD="${POSTGRES_PASSWORD:-}" "$ACTIVE_CONTAINER" \
|
||||
pg_dump -U "$POSTGRES_USER_VALUE" -d "$POSTGRES_DB_VALUE" "${PG_DUMP_ARGS[@]}" \
|
||||
| gzip -c > "$TMP_FILE"
|
||||
else
|
||||
DB_URL_RAW="${DATABASE_URL:-}"
|
||||
if [[ -n "$DB_URL_RAW" ]]; then
|
||||
DB_URL_NORM="${DB_URL_RAW/postgresql+asyncpg:\/\//postgresql:\/\/}"
|
||||
pg_dump "$DB_URL_NORM" "${PG_DUMP_ARGS[@]}" | gzip -c > "$TMP_FILE"
|
||||
else
|
||||
pg_dump -U "$POSTGRES_USER_VALUE" -d "$POSTGRES_DB_VALUE" "${PG_DUMP_ARGS[@]}" \
|
||||
| gzip -c > "$TMP_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "$VERIFY_GZIP" -eq 1 ]]; then
|
||||
gzip -t "$TMP_FILE"
|
||||
fi
|
||||
|
||||
mv "$TMP_FILE" "$TARGET_FILE"
|
||||
printf 'Backup created: %s\n' "$TARGET_FILE"
|
||||
|
||||
if [[ "$RETENTION_DAYS" -gt 0 ]]; then
|
||||
find "$OUTPUT_DIR" -maxdepth 1 -type f -name 'planet_*.sql.gz' -mtime +"$RETENTION_DAYS" -delete
|
||||
fi
|
||||
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Versioned database migration CLI for Planet."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
BACKEND_DIR = REPO_ROOT / "backend"
|
||||
if str(BACKEND_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_DIR))
|
||||
|
||||
from app.db.migrations import get_migration_status, run_migrations, stamp_migrations # noqa: E402
|
||||
from app.db.session import engine # noqa: E402
|
||||
|
||||
|
||||
async def _run_command(args: argparse.Namespace) -> int:
|
||||
try:
|
||||
if args.command == "status":
|
||||
status = await get_migration_status(engine)
|
||||
print(json.dumps(status, indent=2, ensure_ascii=False))
|
||||
return 1 if status["mismatches"] else 0
|
||||
if args.command == "upgrade":
|
||||
applied = await run_migrations(engine)
|
||||
print(json.dumps({"applied": applied}, ensure_ascii=False))
|
||||
return 0
|
||||
if args.command == "stamp":
|
||||
stamped = await stamp_migrations(engine, args.version)
|
||||
print(json.dumps({"stamped": stamped}, ensure_ascii=False))
|
||||
return 0
|
||||
return 2
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Planet versioned schema migration helper")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
subparsers.add_parser("status", help="Show applied, pending, and checksum-mismatched migrations")
|
||||
subparsers.add_parser("upgrade", help="Apply all pending migrations")
|
||||
stamp_parser = subparsers.add_parser("stamp", help="Mark migrations up to VERSION as applied")
|
||||
stamp_parser.add_argument("version", help="4-digit migration version (e.g. 0001)")
|
||||
args = parser.parse_args()
|
||||
return asyncio.run(_run_command(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -17,6 +17,7 @@ main() {
|
||||
harness_run zsh -n scripts/lib/docker-proxy.zsh
|
||||
harness_run zsh -n scripts/lib/docker-mirror.zsh
|
||||
harness_run zsh -n scripts/lib/error-diagnostics.zsh
|
||||
harness_run zsh -n scripts/lib/deploy.zsh
|
||||
harness_run zsh -n scripts/windows/restart.zsh
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_bootstrap.py
|
||||
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_command.py
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
#!/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
|
||||
}
|
||||
Reference in new issue
Block a user