Files
Artveris/scripts/deploy_remote.py
T

911 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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"
REMOTE_SECRETS_FILE = DEPLOY_ROOT / "remote-secrets.json"
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")
BASE_IMAGE_FALLBACKS = {
"mysql:8.0": "docker.1panel.live/library/mysql:8.0",
"redis:7-alpine": "docker.1panel.live/library/redis:7-alpine",
"nginx:alpine": "docker.1panel.live/library/nginx:alpine",
}
NODE_IMAGE = "node:20-slim"
NODE_1PANEL_IMAGE = "docker.1panel.live/library/node:20-slim"
@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
clean_remote_artveris: 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_required_secret(prompt: str) -> str:
while True:
value = getpass.getpass(f"{prompt}: ").strip()
if value:
return value
log("该项不能为空,请重新输入。")
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 load_remote_secrets() -> dict[str, str]:
try:
with open(REMOTE_SECRETS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return {str(k): str(v) for k, v in data.items() if v}
except (OSError, json.JSONDecodeError):
pass
return {}
def save_remote_secrets(values: dict[str, str]) -> None:
DEPLOY_ROOT.mkdir(exist_ok=True)
with open(REMOTE_SECRETS_FILE, "w", encoding="utf-8", newline="\n") as f:
json.dump(values, f, ensure_ascii=False, indent=2)
def secret_default(saved: dict[str, str], key: str, length: int = 32) -> str:
return saved.get(key) or random_secret(length)
def normalize_url(value: str) -> str:
return value.rstrip("/")
def ask_config() -> DeployConfig:
log("请填写生产部署配置。密码输入时不会回显。")
saved_secrets = load_remote_secrets()
if saved_secrets:
log(f"已加载本机保存的远程部署密钥:{REMOTE_SECRETS_FILE}")
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 密码", secret_default(saved_secrets, "mysql_root_password", 24))
mysql_database = ask("MySQL 业务库名", "artveris")
mysql_user = ask("MySQL 业务用户名", "artveris")
mysql_password = ask_secret("MySQL 业务用户密码", secret_default(saved_secrets, "mysql_password", 24))
redis_password = ask_secret("Redis 密码", secret_default(saved_secrets, "redis_password", 24))
jwt_secret = ask_secret("JWT_SECRET", secret_default(saved_secrets, "jwt_secret", 48))
seed_admin_username = ask("初始超级管理员账号", "admin")
seed_admin_password = ask_secret("初始超级管理员密码", saved_secrets.get("seed_admin_password") or "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 不稳定时可开启)",
False,
)
clean_remote_artveris = 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 密码")
save_remote_secrets(
{
"mysql_root_password": mysql_root_password,
"mysql_password": mysql_password,
"redis_password": redis_password,
"jwt_secret": jwt_secret,
"seed_admin_password": seed_admin_password,
}
)
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,
clean_remote_artveris=clean_remote_artveris,
ssh_host=ssh_host,
ssh_port=ssh_port,
ssh_username=ssh_username,
ssh_password=ssh_password,
)
def resolve_cmd(args: list[str]) -> list[str]:
resolved_args = args[:]
executable = shutil.which(resolved_args[0])
if executable:
resolved_args[0] = executable
return resolved_args
def run_cmd(args: list[str], cwd: Path | None = None, check: bool = True) -> int:
log("$ " + " ".join(shlex.quote(str(item)) for item in args))
resolved_args = resolve_cmd(args)
result = subprocess.run(resolved_args, cwd=str(cwd or ROOT), check=check)
return result.returncode
def cmd_success(args: list[str], cwd: Path | None = None) -> bool:
result = subprocess.run(
resolve_cmd(args),
cwd=str(cwd or ROOT),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
return result.returncode == 0
def docker_image_exists(image: str) -> bool:
return cmd_success(["docker", "image", "inspect", image])
def build_api_image_with_base(api_image: str, node_image: str, check: bool = True) -> int:
base_cmd = [
"docker",
"build",
"--platform",
"linux/amd64",
"--build-arg",
f"NODE_IMAGE={node_image}",
"-t",
api_image,
"-f",
"docker/Dockerfile.api",
".",
]
return run_cmd(base_cmd, check=check)
def docker_build_api_image(api_image: str) -> None:
if docker_image_exists(NODE_IMAGE):
log(f"检测到本地已有 {NODE_IMAGE},直接用于 API 镜像构建。")
build_api_image_with_base(api_image, NODE_IMAGE)
return
if docker_image_exists(NODE_1PANEL_IMAGE):
log(f"检测到本地已有 {NODE_1PANEL_IMAGE},直接用于 API 镜像构建。")
build_api_image_with_base(api_image, NODE_1PANEL_IMAGE)
return
if build_api_image_with_base(api_image, NODE_IMAGE, check=False) == 0:
return
log("Docker 官方 node:20-slim 拉取/构建失败,切换 1Panel 镜像代理后重试。")
build_api_image_with_base(api_image, NODE_1PANEL_IMAGE)
def docker_pull_with_fallback(image: str) -> None:
if run_cmd(["docker", "pull", "--platform", "linux/amd64", image], check=False) == 0:
return
fallback = BASE_IMAGE_FALLBACKS.get(image)
if not fallback:
run_cmd(["docker", "pull", "--platform", "linux/amd64", image])
return
log(f"Docker 官方镜像 {image} 拉取失败,切换 1Panel 镜像代理后重试。")
run_cmd(["docker", "pull", "--platform", "linux/amd64", fallback])
run_cmd(["docker", "tag", fallback, image])
def remove_dir(path: Path) -> None:
if path.exists():
shutil.rmtree(path)
def cleanup_deploy_cache(*keep: Path) -> None:
if not DEPLOY_ROOT.exists():
return
keep_set = {item.resolve() for item in keep}
for path in DEPLOY_ROOT.glob("artveris-remote-*"):
try:
if path.resolve() in keep_set:
continue
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
except OSError as exc:
log(f"清理本地部署缓存失败,已跳过:{path}({exc})")
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": "",
"TIANHE_USER_ID": "",
"TIANHE_USER_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 sql_string(value: str) -> str:
return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
def sql_identifier(value: str) -> str:
return "`" + value.replace("`", "``") + "`"
def write_mysql_init_sql(path: Path, cfg: DeployConfig) -> None:
database = sql_identifier(cfg.mysql_database)
user = sql_string(cfg.mysql_user)
password = sql_string(cfg.mysql_password)
sql = f"""CREATE DATABASE IF NOT EXISTS {database}
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS {user}@'%' IDENTIFIED BY {password};
ALTER USER {user}@'%' IDENTIFIED BY {password};
GRANT ALL PRIVILEGES ON {database}.* TO {user}@'%';
FLUSH PRIVILEGES;
"""
path.write_text(sql, 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_ROOT_HOST: "%"
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
expose:
- "3306"
volumes:
- artveris_mysql:/var/lib/mysql
- ./mysql-init.sql:/artveris-init.sql:ro
networks:
- artveris_private
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}
expose:
- "6379"
volumes:
- artveris_redis:/data
networks:
- artveris_private
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}
TIANHE_USER_ID: ${TIANHE_USER_ID}
TIANHE_USER_KEY: ${TIANHE_USER_KEY}
GEO_DRIVER: mock
volumes:
- artveris_storage:/app/apps/api/storage
- artveris_backups:/app/apps/api/backups
networks:
- artveris_private
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
networks:
- artveris_private
volumes:
artveris_mysql:
artveris_redis:
artveris_storage:
artveris_backups:
networks:
artveris_private:
driver: bridge
"""
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}"
docker_build_api_image(api_image)
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:
docker_pull_with_fallback(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)
write_mysql_init_sql(bundle_dir / "mysql-init.sql", cfg)
(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 remote_connection_check_command(remote_dir: str) -> str:
script = (
"const net=require('net');"
"const checks=[['mysql',3306],['redis',6379]];"
"let left=checks.length;"
"let failed=false;"
"function done(ok){failed=failed||!ok;if(--left===0)process.exit(failed?1:0);}"
"for(const [host,port] of checks){"
"const socket=net.createConnection({host,port,timeout:5000},()=>{"
"console.log(`${host}:${port} ok`);socket.destroy();done(true);"
"});"
"socket.on('error',(error)=>{console.error(`${host}:${port} ${error.message}`);done(false);});"
"socket.on('timeout',()=>{console.error(`${host}:${port} timeout`);socket.destroy();done(false);});"
"}"
)
return (
f"cd {shlex.quote(remote_dir)} && "
"docker compose --env-file .env -f docker-compose.remote.yml "
f"exec -T api node -e {shlex.quote(script)}"
)
def remote_mysql_init_command(remote_dir: str) -> str:
script = (
'for i in $(seq 1 60); do '
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql -h127.0.0.1 -uroot '
'-e "SELECT 1" >/dev/null 2>&1 && break; '
'if [ "$i" = "60" ]; then echo "MySQL root 登录失败,请确认是否复用了旧数据卷和旧 root 密码" >&2; exit 1; fi; '
'sleep 2; '
'done; '
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql '
'-h127.0.0.1 -uroot --default-character-set=utf8mb4 < /artveris-init.sql'
)
return (
f"cd {shlex.quote(remote_dir)} && "
"docker compose --env-file .env -f docker-compose.remote.yml "
"exec -T mysql sh -c "
+ shlex.quote(script)
)
def remote_clean_artveris_command(remote_dir: str) -> str:
script = r"""
set -eu
if [ -f docker-compose.remote.yml ]; then
docker compose --env-file .env -f docker-compose.remote.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 '^artveris-api:' || true)"
if [ -n "$images" ]; then
docker rmi -f $images || true
fi
rm -rf admin-dist client-dist images docker-compose.remote.yml nginx.conf mysql-init.sql .env manifest.json
"""
return f"cd {shlex.quote(remote_dir)} && sh -c {shlex.quote(script)}"
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}")
if cfg.clean_remote_artveris:
log("按用户选择清理线上 Artveris 旧容器/卷/网络/API镜像。")
remote_exec(ssh, remote_clean_artveris_command(cfg.remote_dir))
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 mysql-init.sql .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 mysql redis",
"docker compose --env-file .env -f docker-compose.remote.yml ps mysql redis",
]
),
)
remote_exec(ssh, remote_mysql_init_command(cfg.remote_dir))
remote_exec(
ssh,
" && ".join(
[
f"cd {remote_dir_q}",
"docker compose --env-file .env -f docker-compose.remote.yml up -d api web",
"docker compose --env-file .env -f docker-compose.remote.yml ps",
f"rm -f {remote_archive_q}",
]
),
)
remote_exec(ssh, remote_connection_check_command(cfg.remote_dir))
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)
cleanup_deploy_cache()
bundle_dir, archive_path, api_image = build_release(cfg)
deploy_remote(cfg, archive_path, api_image)
cleanup_deploy_cache(bundle_dir, archive_path)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print()
log("已取消部署。")
sys.exit(130)