feat: 添加远程一键部署脚本
This commit is contained in:
@@ -0,0 +1,646 @@
|
||||
"""Build a local Artveris release bundle and deploy it to a remote Docker host.
|
||||
|
||||
The script is intentionally self-contained: the remote server only needs Docker,
|
||||
Docker Compose and SSH access. Frontend assets and the API image are built on the
|
||||
local machine, then uploaded as one archive.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import posixpath
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from _lib import ROOT, ensure_pnpm
|
||||
|
||||
|
||||
DEPLOY_ROOT = ROOT / ".deploy"
|
||||
DEFAULT_ADMIN_URL = "https://art.asio.asia"
|
||||
DEFAULT_CLIENT_URL = "https://artveris.asio.asia"
|
||||
DEFAULT_REMOTE_DIR = "/opt/artveris"
|
||||
API_IMAGE_REPO = "artveris-api"
|
||||
BASE_IMAGES = ("mysql:8.0", "redis:7-alpine", "nginx:alpine")
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeployConfig:
|
||||
admin_url: str
|
||||
client_url: str
|
||||
remote_dir: str
|
||||
bind_host: str
|
||||
admin_http_port: str
|
||||
client_http_port: str
|
||||
mysql_root_password: str
|
||||
mysql_database: str
|
||||
mysql_user: str
|
||||
mysql_password: str
|
||||
redis_password: str
|
||||
jwt_secret: str
|
||||
seed_admin_username: str
|
||||
seed_admin_password: str
|
||||
seed_admin_name: str
|
||||
storage_driver: str
|
||||
oss_endpoint: str
|
||||
oss_region: str
|
||||
oss_bucket: str
|
||||
oss_access_key_id: str
|
||||
oss_access_key_secret: str
|
||||
cdn_base_url: str
|
||||
include_base_images: bool
|
||||
ssh_host: str
|
||||
ssh_port: int
|
||||
ssh_username: str
|
||||
ssh_password: str
|
||||
|
||||
|
||||
def log(message: str) -> None:
|
||||
print(f"[artveris-deploy] {message}")
|
||||
|
||||
|
||||
def ask(prompt: str, default: str = "") -> str:
|
||||
suffix = f"(默认 {default})" if default else "(可留空)"
|
||||
value = input(f"{prompt}{suffix}: ").strip()
|
||||
return value or default
|
||||
|
||||
|
||||
def ask_secret(prompt: str, default: str = "") -> str:
|
||||
suffix = "(留空自动生成)" if not default else "(留空使用默认值)"
|
||||
value = getpass.getpass(f"{prompt}{suffix}: ").strip()
|
||||
return value or default
|
||||
|
||||
|
||||
def ask_yes_no(prompt: str, default: bool = True) -> bool:
|
||||
hint = "Y/n" if default else "y/N"
|
||||
value = input(f"{prompt}({hint}): ").strip().lower()
|
||||
if not value:
|
||||
return default
|
||||
return value in {"y", "yes", "1", "是", "yes."}
|
||||
|
||||
|
||||
def random_secret(length: int = 48) -> str:
|
||||
return secrets.token_urlsafe(length)
|
||||
|
||||
|
||||
def normalize_url(value: str) -> str:
|
||||
return value.rstrip("/")
|
||||
|
||||
|
||||
def ask_config() -> DeployConfig:
|
||||
log("请填写生产部署配置。密码输入时不会回显。")
|
||||
admin_url = normalize_url(ask("后台/API 域名", DEFAULT_ADMIN_URL))
|
||||
client_url = normalize_url(ask("客户端域名", DEFAULT_CLIENT_URL))
|
||||
remote_dir = ask("服务器部署目录", DEFAULT_REMOTE_DIR)
|
||||
bind_host = ask("容器端口绑定地址", "127.0.0.1")
|
||||
admin_http_port = ask("后台/API 本机 HTTP 端口(给 1Panel 反代)", "18080")
|
||||
client_http_port = ask("客户端本机 HTTP 端口(给 1Panel 反代)", "18081")
|
||||
|
||||
mysql_root_password = ask_secret("MySQL root 密码", random_secret(24))
|
||||
mysql_database = ask("MySQL 业务库名", "artveris")
|
||||
mysql_user = ask("MySQL 业务用户名", "artveris")
|
||||
mysql_password = ask_secret("MySQL 业务用户密码", random_secret(24))
|
||||
redis_password = ask_secret("Redis 密码", random_secret(24))
|
||||
jwt_secret = ask_secret("JWT_SECRET", random_secret(48))
|
||||
|
||||
seed_admin_username = ask("初始超级管理员账号", "admin")
|
||||
seed_admin_password = ask_secret("初始超级管理员密码", "Admin@12345")
|
||||
seed_admin_name = ask("初始超级管理员名称", "超级管理员")
|
||||
|
||||
storage_driver = ask("存储方式:local 或 oss", "local").lower()
|
||||
if storage_driver not in {"local", "oss"}:
|
||||
log("存储方式只能是 local 或 oss,已回退为 local。")
|
||||
storage_driver = "local"
|
||||
|
||||
oss_endpoint = oss_region = oss_bucket = oss_access_key_id = oss_access_key_secret = ""
|
||||
if storage_driver == "oss":
|
||||
oss_endpoint = ask("OSS Endpoint")
|
||||
oss_region = ask("OSS Region")
|
||||
oss_bucket = ask("OSS Bucket")
|
||||
oss_access_key_id = ask("OSS AccessKey ID")
|
||||
oss_access_key_secret = ask_secret("OSS AccessKey Secret")
|
||||
|
||||
cdn_base_url = ""
|
||||
if ask_yes_no("是否启用 CDN 基础地址", False):
|
||||
cdn_base_url = normalize_url(ask("CDN_BASE_URL"))
|
||||
|
||||
include_base_images = ask_yes_no(
|
||||
"是否同时打包 MySQL/Redis/Nginx 基础镜像(服务器拉取 Docker Hub 不稳定时建议开启)",
|
||||
True,
|
||||
)
|
||||
|
||||
log("请填写 SSH 信息,用于上传并启动远程 Docker。")
|
||||
ssh_host = ask("服务器 SSH IP/域名")
|
||||
ssh_port = int(ask("服务器 SSH 端口", "22"))
|
||||
ssh_username = ask("服务器 SSH 账号", "root")
|
||||
ssh_password = ask_secret("服务器 SSH 密码")
|
||||
|
||||
return DeployConfig(
|
||||
admin_url=admin_url,
|
||||
client_url=client_url,
|
||||
remote_dir=remote_dir,
|
||||
bind_host=bind_host,
|
||||
admin_http_port=admin_http_port,
|
||||
client_http_port=client_http_port,
|
||||
mysql_root_password=mysql_root_password,
|
||||
mysql_database=mysql_database,
|
||||
mysql_user=mysql_user,
|
||||
mysql_password=mysql_password,
|
||||
redis_password=redis_password,
|
||||
jwt_secret=jwt_secret,
|
||||
seed_admin_username=seed_admin_username,
|
||||
seed_admin_password=seed_admin_password,
|
||||
seed_admin_name=seed_admin_name,
|
||||
storage_driver=storage_driver,
|
||||
oss_endpoint=oss_endpoint,
|
||||
oss_region=oss_region,
|
||||
oss_bucket=oss_bucket,
|
||||
oss_access_key_id=oss_access_key_id,
|
||||
oss_access_key_secret=oss_access_key_secret,
|
||||
cdn_base_url=cdn_base_url,
|
||||
include_base_images=include_base_images,
|
||||
ssh_host=ssh_host,
|
||||
ssh_port=ssh_port,
|
||||
ssh_username=ssh_username,
|
||||
ssh_password=ssh_password,
|
||||
)
|
||||
|
||||
|
||||
def run_cmd(args: list[str], cwd: Path | None = None) -> None:
|
||||
log("$ " + " ".join(shlex.quote(str(item)) for item in args))
|
||||
subprocess.run(args, cwd=str(cwd or ROOT), check=True)
|
||||
|
||||
|
||||
def remove_dir(path: Path) -> None:
|
||||
if path.exists():
|
||||
shutil.rmtree(path)
|
||||
|
||||
|
||||
def copy_tree(src: Path, dst: Path) -> None:
|
||||
remove_dir(dst)
|
||||
shutil.copytree(src, dst)
|
||||
|
||||
|
||||
def env_value(value: str) -> str:
|
||||
if value == "":
|
||||
return ""
|
||||
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
|
||||
return f'"{escaped}"'
|
||||
|
||||
|
||||
def write_env_file(path: Path, cfg: DeployConfig, image_tag: str) -> None:
|
||||
database_url = (
|
||||
"mysql://"
|
||||
f"{quote(cfg.mysql_user, safe='')}:{quote(cfg.mysql_password, safe='')}"
|
||||
f"@mysql:3306/{quote(cfg.mysql_database, safe='')}"
|
||||
)
|
||||
env = {
|
||||
"APP_NAME": "艺术品溯源平台",
|
||||
"NODE_ENV": "production",
|
||||
"API_PORT": "3000",
|
||||
"BASE_URL": cfg.admin_url,
|
||||
"PUBLIC_TRACE_PATH": "/t",
|
||||
"ADMIN_ORIGIN": cfg.admin_url,
|
||||
"CLIENT_ORIGIN": cfg.client_url,
|
||||
"TRACE_URL_TEMPLATE": f"{cfg.client_url}/#/trace/{{code}}",
|
||||
"DATABASE_URL": database_url,
|
||||
"MYSQL_ROOT_PASSWORD": cfg.mysql_root_password,
|
||||
"MYSQL_DATABASE": cfg.mysql_database,
|
||||
"MYSQL_USER": cfg.mysql_user,
|
||||
"MYSQL_PASSWORD": cfg.mysql_password,
|
||||
"REDIS_HOST": "redis",
|
||||
"REDIS_PORT": "6379",
|
||||
"REDIS_PASSWORD": cfg.redis_password,
|
||||
"JWT_SECRET": cfg.jwt_secret,
|
||||
"JWT_EXPIRES_IN": "7d",
|
||||
"SEED_ADMIN_USERNAME": cfg.seed_admin_username,
|
||||
"SEED_ADMIN_PASSWORD": cfg.seed_admin_password,
|
||||
"SEED_ADMIN_NAME": cfg.seed_admin_name,
|
||||
"STORAGE_DRIVER": cfg.storage_driver,
|
||||
"STORAGE_LOCAL_DIR": "./storage",
|
||||
"STORAGE_PUBLIC_PREFIX": "/uploads",
|
||||
"CDN_BASE_URL": cfg.cdn_base_url,
|
||||
"OSS_ENDPOINT": cfg.oss_endpoint,
|
||||
"OSS_REGION": cfg.oss_region,
|
||||
"OSS_BUCKET": cfg.oss_bucket,
|
||||
"OSS_ACCESS_KEY_ID": cfg.oss_access_key_id,
|
||||
"OSS_ACCESS_KEY_SECRET": cfg.oss_access_key_secret,
|
||||
"BLOCKCHAIN_DRIVER": "mock",
|
||||
"TIANHE_BASE_URL": "",
|
||||
"TIANHE_APP_ID": "",
|
||||
"TIANHE_APP_KEY": "",
|
||||
"LOG_RETENTION_DAYS": "365",
|
||||
"WATERMARK_TEXT": "仅供溯源核验使用",
|
||||
"BACKUP_DIR": "/app/apps/api/backups",
|
||||
"API_IMAGE": f"{API_IMAGE_REPO}:{image_tag}",
|
||||
"BIND_HOST": cfg.bind_host,
|
||||
"ADMIN_HTTP_PORT": cfg.admin_http_port,
|
||||
"CLIENT_HTTP_PORT": cfg.client_http_port,
|
||||
}
|
||||
lines = [
|
||||
"# Artveris 远程部署环境变量,由 scripts/deploy_remote.py 生成,请勿提交到 Git。",
|
||||
*[f"{key}={env_value(value)}" for key, value in env.items()],
|
||||
"",
|
||||
]
|
||||
path.write_text("\n".join(lines), encoding="utf-8", newline="\n")
|
||||
|
||||
|
||||
def compose_text() -> str:
|
||||
return """name: artveris
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
|
||||
MYSQL_DATABASE: ${MYSQL_DATABASE}
|
||||
MYSQL_USER: ${MYSQL_USER}
|
||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
|
||||
command: >-
|
||||
--character-set-server=utf8mb4 --collation-server=utf8mb4_0900_ai_ci
|
||||
--default-authentication-plugin=mysql_native_password
|
||||
volumes:
|
||||
- artveris_mysql:/var/lib/mysql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -p$${MYSQL_ROOT_PASSWORD} --silent"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
command: >-
|
||||
sh -c 'if [ -n "$${REDIS_PASSWORD}" ]; then
|
||||
redis-server --appendonly yes --requirepass "$${REDIS_PASSWORD}";
|
||||
else
|
||||
redis-server --appendonly yes;
|
||||
fi'
|
||||
environment:
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
volumes:
|
||||
- artveris_redis:/data
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- 'if [ -n "$${REDIS_PASSWORD}" ]; then redis-cli -a "$${REDIS_PASSWORD}" ping; else redis-cli ping; fi'
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
|
||||
api:
|
||||
image: ${API_IMAGE}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
APP_NAME: ${APP_NAME}
|
||||
NODE_ENV: production
|
||||
API_PORT: 3000
|
||||
BASE_URL: ${BASE_URL}
|
||||
PUBLIC_TRACE_PATH: ${PUBLIC_TRACE_PATH}
|
||||
ADMIN_ORIGIN: ${ADMIN_ORIGIN}
|
||||
CLIENT_ORIGIN: ${CLIENT_ORIGIN}
|
||||
TRACE_URL_TEMPLATE: ${TRACE_URL_TEMPLATE}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: 6379
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
JWT_EXPIRES_IN: ${JWT_EXPIRES_IN}
|
||||
SEED_ADMIN_USERNAME: ${SEED_ADMIN_USERNAME}
|
||||
SEED_ADMIN_PASSWORD: ${SEED_ADMIN_PASSWORD}
|
||||
SEED_ADMIN_NAME: ${SEED_ADMIN_NAME}
|
||||
STORAGE_DRIVER: ${STORAGE_DRIVER}
|
||||
STORAGE_LOCAL_DIR: ${STORAGE_LOCAL_DIR}
|
||||
STORAGE_PUBLIC_PREFIX: ${STORAGE_PUBLIC_PREFIX}
|
||||
CDN_BASE_URL: ${CDN_BASE_URL}
|
||||
OSS_ENDPOINT: ${OSS_ENDPOINT}
|
||||
OSS_REGION: ${OSS_REGION}
|
||||
OSS_BUCKET: ${OSS_BUCKET}
|
||||
OSS_ACCESS_KEY_ID: ${OSS_ACCESS_KEY_ID}
|
||||
OSS_ACCESS_KEY_SECRET: ${OSS_ACCESS_KEY_SECRET}
|
||||
BACKUP_DIR: ${BACKUP_DIR}
|
||||
BLOCKCHAIN_DRIVER: ${BLOCKCHAIN_DRIVER}
|
||||
TIANHE_BASE_URL: ${TIANHE_BASE_URL}
|
||||
TIANHE_APP_ID: ${TIANHE_APP_ID}
|
||||
TIANHE_APP_KEY: ${TIANHE_APP_KEY}
|
||||
GEO_DRIVER: mock
|
||||
volumes:
|
||||
- artveris_storage:/app/apps/api/storage
|
||||
- artveris_backups:/app/apps/api/backups
|
||||
|
||||
web:
|
||||
image: nginx:alpine
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- api
|
||||
ports:
|
||||
- "${BIND_HOST}:${ADMIN_HTTP_PORT}:80"
|
||||
- "${BIND_HOST}:${CLIENT_HTTP_PORT}:8080"
|
||||
volumes:
|
||||
- ./admin-dist:/usr/share/nginx/html/admin:ro
|
||||
- ./client-dist:/usr/share/nginx/html/client:ro
|
||||
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
|
||||
volumes:
|
||||
artveris_mysql:
|
||||
artveris_redis:
|
||||
artveris_storage:
|
||||
artveris_backups:
|
||||
"""
|
||||
|
||||
|
||||
def nginx_text() -> str:
|
||||
return """map $http_x_forwarded_proto $artveris_forwarded_proto {
|
||||
default $http_x_forwarded_proto;
|
||||
"" $scheme;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html/admin;
|
||||
index index.html;
|
||||
client_max_body_size 120m;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://api:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $artveris_forwarded_proto;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
}
|
||||
|
||||
location /uploads/ {
|
||||
proxy_pass http://api:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $artveris_forwarded_proto;
|
||||
}
|
||||
|
||||
location /t/ {
|
||||
proxy_pass http://api:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $artveris_forwarded_proto;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html/client;
|
||||
index index.html;
|
||||
client_max_body_size 120m;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://api:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $artveris_forwarded_proto;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
}
|
||||
|
||||
location /uploads/ {
|
||||
proxy_pass http://api:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $artveris_forwarded_proto;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def build_release(cfg: DeployConfig) -> tuple[Path, Path, str]:
|
||||
timestamp = time.strftime("%Y%m%d%H%M%S")
|
||||
image_tag = f"remote-{timestamp}"
|
||||
bundle_dir = DEPLOY_ROOT / f"artveris-remote-{timestamp}"
|
||||
archive_path = DEPLOY_ROOT / f"artveris-remote-{timestamp}.tar.gz"
|
||||
remove_dir(bundle_dir)
|
||||
bundle_dir.mkdir(parents=True, exist_ok=True)
|
||||
(bundle_dir / "images").mkdir()
|
||||
|
||||
log("安装/校验前端依赖并构建前端产物。")
|
||||
ensure_pnpm()
|
||||
run_cmd(["pnpm", "install", "--frozen-lockfile"])
|
||||
run_cmd(["pnpm", "build:shared"])
|
||||
run_cmd(["pnpm", "--filter", "@artveris/admin", "build"])
|
||||
run_cmd(["pnpm", "--filter", "@artveris/client", "build"])
|
||||
|
||||
log("构建 linux/amd64 API 镜像。")
|
||||
api_image = f"{API_IMAGE_REPO}:{image_tag}"
|
||||
run_cmd([
|
||||
"docker",
|
||||
"build",
|
||||
"--platform",
|
||||
"linux/amd64",
|
||||
"-t",
|
||||
api_image,
|
||||
"-f",
|
||||
"docker/Dockerfile.api",
|
||||
".",
|
||||
])
|
||||
run_cmd(["docker", "save", "-o", str(bundle_dir / "images" / "artveris-api.tar"), api_image])
|
||||
|
||||
if cfg.include_base_images:
|
||||
log("拉取并打包基础镜像,远程服务器可离线加载。")
|
||||
for image in BASE_IMAGES:
|
||||
run_cmd(["docker", "pull", "--platform", "linux/amd64", image])
|
||||
run_cmd([
|
||||
"docker",
|
||||
"save",
|
||||
"-o",
|
||||
str(bundle_dir / "images" / "base-images.tar"),
|
||||
*BASE_IMAGES,
|
||||
])
|
||||
|
||||
log("整理部署包文件。")
|
||||
copy_tree(ROOT / "apps" / "admin" / "dist", bundle_dir / "admin-dist")
|
||||
copy_tree(ROOT / "apps" / "client" / "dist", bundle_dir / "client-dist")
|
||||
(bundle_dir / "docker-compose.remote.yml").write_text(compose_text(), encoding="utf-8", newline="\n")
|
||||
(bundle_dir / "nginx.conf").write_text(nginx_text(), encoding="utf-8", newline="\n")
|
||||
write_env_file(bundle_dir / ".env", cfg, image_tag)
|
||||
(bundle_dir / "manifest.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"createdAt": timestamp,
|
||||
"apiImage": api_image,
|
||||
"platform": "linux/amd64",
|
||||
"adminUrl": cfg.admin_url,
|
||||
"clientUrl": cfg.client_url,
|
||||
"includeBaseImages": cfg.include_base_images,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
newline="\n",
|
||||
)
|
||||
|
||||
if archive_path.exists():
|
||||
archive_path.unlink()
|
||||
log("压缩部署包。")
|
||||
with tarfile.open(archive_path, "w:gz") as tar:
|
||||
tar.add(bundle_dir, arcname=bundle_dir.name)
|
||||
return bundle_dir, archive_path, api_image
|
||||
|
||||
|
||||
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(cfg: DeployConfig):
|
||||
paramiko = import_paramiko()
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
log(f"连接 SSH:{cfg.ssh_username}@{cfg.ssh_host}:{cfg.ssh_port}")
|
||||
client.connect(
|
||||
hostname=cfg.ssh_host,
|
||||
port=cfg.ssh_port,
|
||||
username=cfg.ssh_username,
|
||||
password=cfg.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)
|
||||
del stdin
|
||||
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-deploy] 上传进度:{percent:3d}%", end="")
|
||||
|
||||
sftp.put(str(local_path), remote_path, callback=progress)
|
||||
print()
|
||||
finally:
|
||||
sftp.close()
|
||||
|
||||
|
||||
def deploy_remote(cfg: DeployConfig, archive_path: Path, api_image: str) -> None:
|
||||
ssh = ssh_connect(cfg)
|
||||
remote_archive = f"/tmp/{archive_path.name}"
|
||||
remote_dir_q = shlex.quote(cfg.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}")
|
||||
log(f"上传部署包到 {remote_archive}")
|
||||
upload_file(ssh, archive_path, remote_archive)
|
||||
remote_exec(
|
||||
ssh,
|
||||
" && ".join(
|
||||
[
|
||||
f"cd {remote_dir_q}",
|
||||
"rm -rf admin-dist client-dist images docker-compose.remote.yml nginx.conf .env manifest.json",
|
||||
f"tar -xzf {remote_archive_q} -C {remote_dir_q} --strip-components=1",
|
||||
f"docker load -i {shlex.quote(posixpath.join(cfg.remote_dir, 'images/artveris-api.tar'))}",
|
||||
]
|
||||
),
|
||||
)
|
||||
if cfg.include_base_images:
|
||||
remote_exec(
|
||||
ssh,
|
||||
f"docker load -i {shlex.quote(posixpath.join(cfg.remote_dir, 'images/base-images.tar'))}",
|
||||
)
|
||||
remote_exec(
|
||||
ssh,
|
||||
" && ".join(
|
||||
[
|
||||
f"cd {remote_dir_q}",
|
||||
"docker compose --env-file .env -f docker-compose.remote.yml up -d",
|
||||
"docker compose --env-file .env -f docker-compose.remote.yml ps",
|
||||
f"rm -f {remote_archive_q}",
|
||||
]
|
||||
),
|
||||
)
|
||||
finally:
|
||||
ssh.close()
|
||||
|
||||
log("远程部署完成。")
|
||||
log(f"已加载 API 镜像:{api_image}")
|
||||
log("请在 1Panel 里配置 HTTPS 反向代理:")
|
||||
log(f" {cfg.admin_url} -> http://{cfg.bind_host}:{cfg.admin_http_port}")
|
||||
log(f" {cfg.client_url} -> http://{cfg.bind_host}:{cfg.client_http_port}")
|
||||
log("如果是重复部署且更换过 MySQL/Redis 密码,旧 Docker 卷不会自动改密码,需要保持原密码或手动迁移数据。")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if os.name != "nt":
|
||||
log("当前脚本按 Windows 本机构建流程设计;Linux/macOS 也可尝试运行,但未作为主要路径。")
|
||||
cfg = ask_config()
|
||||
DEPLOY_ROOT.mkdir(exist_ok=True)
|
||||
_, archive_path, api_image = build_release(cfg)
|
||||
deploy_remote(cfg, archive_path, api_image)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
print()
|
||||
log("已取消部署。")
|
||||
sys.exit(130)
|
||||
Reference in New Issue
Block a user