219 lines
8.0 KiB
Python
219 lines
8.0 KiB
Python
"""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,
|
||
build_bundle,
|
||
log,
|
||
)
|
||
|
||
DEFAULT_REMOTE_DIR = "/opt/artveris"
|
||
|
||
|
||
@dataclass
|
||
class RemoteTarget:
|
||
remote_dir: str
|
||
mode: str # upgrade | fresh | clean
|
||
ssh_host: str
|
||
ssh_port: int
|
||
ssh_username: str
|
||
ssh_password: str
|
||
|
||
|
||
def ask_deploy_mode() -> str:
|
||
print("[artveris-remote] 部署模式:")
|
||
print(" 1) 升级(推荐):保留服务器已有 .env 与 data 目录,只更新镜像与容器")
|
||
print(" 2) 全新:从本次配置重写 .env,保留 data 目录(首次部署选这个)")
|
||
print(" 3) 清理重装:删除该项目容器/卷/网络与 data 目录后全新部署(会删除数据,慎用)")
|
||
choice = ask("请输入 1 / 2 / 3", "1")
|
||
return {"1": "upgrade", "2": "fresh", "3": "clean"}.get(choice.strip(), "upgrade")
|
||
|
||
|
||
def ask_remote_target() -> RemoteTarget:
|
||
remote_dir = ask("服务器部署目录", DEFAULT_REMOTE_DIR)
|
||
mode = ask_deploy_mode()
|
||
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,
|
||
mode=mode,
|
||
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()
|
||
|
||
|
||
# 每次部署都可安全清理并被新包覆盖的“代码/编排”文件(不含 .env 与 data/)。
|
||
CODE_FILES = "images docker-compose.yml nginx.conf mysql-init.sql manifest.json load.sh up.sh README.txt .env.sample"
|
||
|
||
|
||
def remote_clean_command(remote_dir: str) -> str:
|
||
# 清理重装:拆除本项目容器/卷/网络、删除 artveris-api 镜像与 data 目录及全部部署文件(含 .env)。
|
||
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 {CODE_FILES} .env data
|
||
"""
|
||
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)
|
||
# 清理重装会删除 .env 与 data,之后按全新走;升级/全新保留 data(升级还保留 .env)
|
||
up_mode = "fresh" if target.mode == "clean" else target.mode
|
||
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.mode == "clean":
|
||
log("清理重装:拆除线上 Artveris 容器/卷/网络/API镜像并删除 data 目录。")
|
||
remote_exec(ssh, remote_clean_command(target.remote_dir))
|
||
log(f"上传部署包到 {remote_archive}")
|
||
upload_file(ssh, archive_path, remote_archive)
|
||
# 仅清理可被覆盖的代码/编排文件,绝不动服务器已有的 .env 与 data/
|
||
remote_exec(
|
||
ssh,
|
||
" && ".join(
|
||
[
|
||
f"cd {remote_dir_q}",
|
||
f"rm -rf {CODE_FILES}",
|
||
f"tar -xzf {remote_archive_q} -C {remote_dir_q} --strip-components=1",
|
||
f"rm -f {remote_archive_q}",
|
||
f"sh up.sh {up_mode}",
|
||
]
|
||
),
|
||
)
|
||
finally:
|
||
ssh.close()
|
||
|
||
log(f"远程部署完成(模式:{target.mode})。")
|
||
log(f"已加载 API 镜像:{api_image}")
|
||
log("请在外层 1Panel/宝塔配置 HTTPS 反向代理:")
|
||
log(f" {cfg.base_url} -> http://{cfg.bind_host}:{cfg.http_port}")
|
||
log("升级模式不会覆盖服务器已有 .env 与 data/;清理重装会清空数据,正式环境慎用。")
|
||
|
||
|
||
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)
|