refactor: 重构部署脚本为 dev/build_docker/remote/build 四脚本并统一单域名容器模型

This commit is contained in:
Nixevol
2026-07-09 09:42:21 +08:00
parent b498a49a9b
commit 1e0e1d6eb8
19 changed files with 1040 additions and 1514 deletions
+208
View File
@@ -0,0 +1,208 @@
"""SSH 自动部署到远程 Docker 主机。
复用 scripts/build_docker.py 构建完整离线部署包,再通过 SSH 上传到服务器并
执行包内 up.sh 完成部署。服务器只需具备 Docker、Docker Compose 和 SSH 访问。
架构为单域名单端口(Nginx 反代到 API 容器),HTTPS 与域名由外层 1Panel/宝塔反代。
用法:python scripts/remote.py
"""
from __future__ import annotations
import os
import shlex
import shutil
import sys
import time
from dataclasses import dataclass
from pathlib import Path
import build_docker
from build_docker import (
DockerConfig,
ask,
ask_config,
ask_required_secret,
ask_yes_no,
build_bundle,
log,
)
DEFAULT_REMOTE_DIR = "/opt/artveris"
@dataclass
class RemoteTarget:
remote_dir: str
clean_remote: bool
ssh_host: str
ssh_port: int
ssh_username: str
ssh_password: str
def ask_remote_target() -> RemoteTarget:
remote_dir = ask("服务器部署目录", DEFAULT_REMOTE_DIR)
clean_remote = ask_yes_no(
"是否先清理线上 Artveris 旧容器/卷/网络/API镜像后重新部署(会删除 Artveris 数据)",
False,
)
log("请填写 SSH 信息,用于上传并启动远程 Docker。")
ssh_host = ask("服务器 SSH IP/域名")
ssh_port = int(ask("服务器 SSH 端口", "22"))
ssh_username = ask("服务器 SSH 账号", "root")
ssh_password = ask_required_secret("服务器 SSH 密码")
return RemoteTarget(
remote_dir=remote_dir,
clean_remote=clean_remote,
ssh_host=ssh_host,
ssh_port=ssh_port,
ssh_username=ssh_username,
ssh_password=ssh_password,
)
def import_paramiko():
try:
import paramiko # type: ignore
return paramiko
except ImportError:
log("缺少 paramiko。请先执行:python -m pip install -r scripts/requirements.txt")
sys.exit(1)
def ssh_connect(target: RemoteTarget):
paramiko = import_paramiko()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
log(f"连接 SSH:{target.ssh_username}@{target.ssh_host}:{target.ssh_port}")
client.connect(
hostname=target.ssh_host,
port=target.ssh_port,
username=target.ssh_username,
password=target.ssh_password,
timeout=20,
banner_timeout=20,
auth_timeout=20,
)
return client
def remote_exec(ssh, command: str) -> None:
log(f"[remote] $ {command}")
_stdin, stdout, _stderr = ssh.exec_command(command, get_pty=True)
channel = stdout.channel
while not channel.exit_status_ready():
if channel.recv_ready():
print(channel.recv(4096).decode("utf-8", errors="replace"), end="")
if channel.recv_stderr_ready():
print(channel.recv_stderr(4096).decode("utf-8", errors="replace"), end="")
time.sleep(0.1)
while channel.recv_ready():
print(channel.recv(4096).decode("utf-8", errors="replace"), end="")
while channel.recv_stderr_ready():
print(channel.recv_stderr(4096).decode("utf-8", errors="replace"), end="")
code = channel.recv_exit_status()
if code != 0:
raise RuntimeError(f"远程命令失败(退出码 {code}):{command}")
def upload_file(ssh, local_path: Path, remote_path: str) -> None:
sftp = ssh.open_sftp()
try:
total = local_path.stat().st_size
last_percent = -1
def progress(sent: int, _total: int) -> None:
nonlocal last_percent
percent = int(sent * 100 / max(total, 1))
if percent != last_percent and percent % 5 == 0:
last_percent = percent
print(f"\r[artveris-remote] 上传进度:{percent:3d}%", end="")
sftp.put(str(local_path), remote_path, callback=progress)
print()
finally:
sftp.close()
BUNDLE_FILES = "images docker-compose.yml nginx.conf mysql-init.sql .env manifest.json load.sh up.sh README.txt"
def remote_clean_command(remote_dir: str) -> str:
script = f"""
set -eu
if [ -f docker-compose.yml ]; then
docker compose --env-file .env -f docker-compose.yml down -v --remove-orphans || true
fi
containers="$(docker ps -aq --filter label=com.docker.compose.project=artveris || true)"
if [ -n "$containers" ]; then docker rm -f $containers || true; fi
volumes="$(docker volume ls -q --filter label=com.docker.compose.project=artveris || true)"
if [ -n "$volumes" ]; then docker volume rm -f $volumes || true; fi
networks="$(docker network ls -q --filter label=com.docker.compose.project=artveris || true)"
if [ -n "$networks" ]; then docker network rm $networks || true; fi
images="$(docker images --format '{{{{.Repository}}}}:{{{{.Tag}}}}' | grep '^{build_docker.API_IMAGE_REPO}:' || true)"
if [ -n "$images" ]; then docker rmi -f $images || true; fi
rm -rf {BUNDLE_FILES}
"""
return f"cd {shlex.quote(remote_dir)} && sh -c {shlex.quote(script)}"
def deploy(target: RemoteTarget, archive_path: Path, api_image: str, cfg: DockerConfig) -> None:
ssh = ssh_connect(target)
remote_archive = f"/tmp/{archive_path.name}"
remote_dir_q = shlex.quote(target.remote_dir)
remote_archive_q = shlex.quote(remote_archive)
try:
remote_exec(ssh, "command -v docker >/dev/null && docker compose version >/dev/null")
remote_exec(ssh, "uname -m")
remote_exec(ssh, f"mkdir -p {remote_dir_q}")
if target.clean_remote:
log("按用户选择清理线上 Artveris 旧容器/卷/网络/API镜像。")
remote_exec(ssh, remote_clean_command(target.remote_dir))
log(f"上传部署包到 {remote_archive}")
upload_file(ssh, archive_path, remote_archive)
remote_exec(
ssh,
" && ".join(
[
f"cd {remote_dir_q}",
f"rm -rf {BUNDLE_FILES}",
f"tar -xzf {remote_archive_q} -C {remote_dir_q} --strip-components=1",
f"rm -f {remote_archive_q}",
"sh up.sh",
]
),
)
finally:
ssh.close()
log("远程部署完成。")
log(f"已加载 API 镜像:{api_image}")
log("请在外层 1Panel/宝塔配置 HTTPS 反向代理:")
log(f" {cfg.base_url} -> http://{cfg.bind_host}:{cfg.http_port}")
log("如果是重复部署且更换过 MySQL/Redis 密码,旧 Docker 卷不会自动改密码,需保持原密码或手动迁移数据。")
def main() -> None:
if os.name != "nt":
log("当前脚本按 Windows 本机构建流程设计;Linux/macOS 也可尝试运行,但未作为主要路径。")
cfg = ask_config()
target = ask_remote_target()
bundle_dir, archive_path, api_image = build_bundle(cfg)
# 本地只需上传压缩包,构建目录可先删除以节省磁盘
shutil.rmtree(bundle_dir, ignore_errors=True)
try:
deploy(target, archive_path, api_image, cfg)
finally:
archive_path.unlink(missing_ok=True)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print()
log("已取消部署。")
sys.exit(130)