488 lines
15 KiB
Python
488 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Full deploy douyinWEB to dy.nomadro.live (108.174.50.68)."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
HOST = "108.174.50.68"
|
|
USER = "root"
|
|
PASSWORD = "Xiao4669805"
|
|
DOMAIN = "dy.nomadro.live"
|
|
ADMIN_USER = "hackrobot"
|
|
ADMIN_PASS = "Xiao4669805@"
|
|
APP_DIR = "/opt/douyinWEB"
|
|
LOCAL_ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
WEB_PORT = 4015
|
|
API_PORT = 8014
|
|
PB_PORT = 8092
|
|
YT_PORT = 8020
|
|
S3_PORT = 8333
|
|
PUBLIC_BASE = f"https://{DOMAIN}"
|
|
|
|
SKIP_DIRS = {
|
|
".git",
|
|
"node_modules",
|
|
".next",
|
|
"__pycache__",
|
|
".venv",
|
|
"venv",
|
|
"backend/data/covers",
|
|
"backend/data/clips",
|
|
"backend/data/monitor.db",
|
|
"backend/data/monitor.db-shm",
|
|
"backend/data/monitor.db-wal",
|
|
"pb/pb_data",
|
|
"scripts/_audit",
|
|
}
|
|
SKIP_EXTS = {".pyc", ".pyo"}
|
|
|
|
|
|
def should_skip(rel: str) -> bool:
|
|
parts = Path(rel).parts
|
|
for i in range(len(parts)):
|
|
sub = "/".join(parts[: i + 1])
|
|
if sub in SKIP_DIRS or parts[i] in SKIP_DIRS:
|
|
return True
|
|
if rel.endswith(tuple(SKIP_EXTS)):
|
|
return True
|
|
if "scripts/_audit" in rel.replace("\\", "/"):
|
|
return True
|
|
return False
|
|
|
|
|
|
def make_tarball() -> Path:
|
|
tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False)
|
|
tmp.close()
|
|
tar_path = Path(tmp.name)
|
|
print(f"[pack] {LOCAL_ROOT} -> {tar_path}", flush=True)
|
|
with tarfile.open(tar_path, "w:gz") as tar:
|
|
for root, dirs, files in os.walk(LOCAL_ROOT):
|
|
dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".git")]
|
|
for name in files:
|
|
full = Path(root) / name
|
|
rel = full.relative_to(LOCAL_ROOT).as_posix()
|
|
if should_skip(rel):
|
|
continue
|
|
if rel.startswith("scripts/_") and rel.endswith(".txt"):
|
|
continue
|
|
tar.add(full, arcname=rel)
|
|
print(f"[pack] size {tar_path.stat().st_size / 1024 / 1024:.1f} MB", flush=True)
|
|
return tar_path
|
|
|
|
|
|
BOOTSTRAP_SH = r"""#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
DOMAIN="__DOMAIN__"
|
|
ADMIN_USER="__ADMIN_USER__"
|
|
ADMIN_PASS="__ADMIN_PASS__"
|
|
APP_DIR="__APP_DIR__"
|
|
PUBLIC_BASE="__PUBLIC_BASE__"
|
|
WEB_PORT="__WEB_PORT__"
|
|
API_PORT="__API_PORT__"
|
|
PB_PORT="__PB_PORT__"
|
|
YT_PORT="__YT_PORT__"
|
|
S3_PORT="__S3_PORT__"
|
|
SW_MASTER_PORT=19333
|
|
SW_VOLUME_PORT=18080
|
|
SW_FILER_PORT=18888
|
|
PB_VER=0.25.8
|
|
WEED_VER=3.80
|
|
S3_ACCESS=douyin
|
|
S3_BUCKET=douyin-covers
|
|
PB_ADMIN_EMAIL="${ADMIN_USER}@${DOMAIN}"
|
|
ENV_FILE=/etc/douyinweb.env
|
|
|
|
log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; }
|
|
|
|
export DEBIAN_FRONTEND=noninteractive
|
|
log "install packages"
|
|
apt-get update -y
|
|
apt-get install -y --no-install-recommends \
|
|
git curl unzip ca-certificates ffmpeg \
|
|
python3 python3-venv python3-pip \
|
|
nginx certbot python3-certbot-nginx
|
|
|
|
if ! command -v node >/dev/null 2>&1 || [ "$(node -v | tr -d v | cut -d. -f1)" -lt 18 ]; then
|
|
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
|
apt-get install -y nodejs
|
|
fi
|
|
node -v
|
|
python3 --version
|
|
ffmpeg -version | head -1
|
|
|
|
if [ ! -f "$ENV_FILE" ]; then
|
|
SESSION_SECRET=$(openssl rand -hex 24)
|
|
S3_SECRET=$(openssl rand -hex 18)
|
|
cat >"$ENV_FILE" <<EOF
|
|
DOMAIN=${DOMAIN}
|
|
PUBLIC_BASE=${PUBLIC_BASE}
|
|
ADMIN_USER=${ADMIN_USER}
|
|
SESSION_SECRET=${SESSION_SECRET}
|
|
S3_SECRET=${S3_SECRET}
|
|
S3_ACCESS=${S3_ACCESS}
|
|
S3_BUCKET=${S3_BUCKET}
|
|
WEB_PORT=${WEB_PORT}
|
|
API_PORT=${API_PORT}
|
|
PB_PORT=${PB_PORT}
|
|
YT_PORT=${YT_PORT}
|
|
S3_PORT=${S3_PORT}
|
|
EOF
|
|
chmod 600 "$ENV_FILE"
|
|
fi
|
|
# shellcheck disable=SC1090
|
|
source "$ENV_FILE"
|
|
|
|
log "extract app to $APP_DIR"
|
|
mkdir -p "$APP_DIR"
|
|
rm -rf "$APP_DIR"/*
|
|
tar -xzf /tmp/douyinweb_deploy.tar.gz -C "$APP_DIR"
|
|
# Never import another environment's runtime DB (no default Douyin room URLs on fresh install)
|
|
rm -f "$APP_DIR/backend/data/monitor.db" \
|
|
"$APP_DIR/backend/data/monitor.db-shm" \
|
|
"$APP_DIR/backend/data/monitor.db-wal"
|
|
mkdir -p "$APP_DIR/backend/data/covers" "$APP_DIR/backend/data/clips" "$APP_DIR/pb/pb_data"
|
|
|
|
log "pocketbase"
|
|
mkdir -p "$APP_DIR/pb"
|
|
if [ ! -x "$APP_DIR/pb/pocketbase" ]; then
|
|
curl -fsSL -o /tmp/pb.zip \
|
|
"https://github.com/pocketbase/pocketbase/releases/download/v${PB_VER}/pocketbase_${PB_VER}_linux_amd64.zip"
|
|
unzip -o /tmp/pb.zip pocketbase -d "$APP_DIR/pb"
|
|
chmod +x "$APP_DIR/pb/pocketbase"
|
|
rm -f /tmp/pb.zip
|
|
fi
|
|
|
|
log "seaweedfs"
|
|
mkdir -p /opt/seaweedfs /data/douyinweb-seaweed/{master,volume,filer} /etc/seaweedfs
|
|
if [ ! -x /opt/seaweedfs/weed ]; then
|
|
curl -fsSL -o /tmp/weed.tgz \
|
|
"https://github.com/seaweedfs/seaweedfs/releases/download/${WEED_VER}/linux_amd64.tar.gz"
|
|
tar -xzf /tmp/weed.tgz -C /opt/seaweedfs weed
|
|
chmod +x /opt/seaweedfs/weed
|
|
rm -f /tmp/weed.tgz
|
|
fi
|
|
cat >/etc/seaweedfs/douyinweb-s3.json <<EOF
|
|
{
|
|
"identities": [{
|
|
"name": "douyinweb",
|
|
"credentials": [{"accessKey": "${S3_ACCESS}", "secretKey": "${S3_SECRET}"}],
|
|
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
|
|
}]
|
|
}
|
|
EOF
|
|
|
|
NODE_BIN=$(command -v node)
|
|
NPM_BIN=$(command -v npm)
|
|
|
|
log "systemd units"
|
|
cat >/etc/systemd/system/douyinweb-pb.service <<EOF
|
|
[Unit]
|
|
Description=DouyinWEB PocketBase
|
|
After=network.target
|
|
[Service]
|
|
Type=simple
|
|
WorkingDirectory=${APP_DIR}/pb
|
|
ExecStart=${APP_DIR}/pb/pocketbase serve --http=127.0.0.1:${PB_PORT}
|
|
Restart=always
|
|
RestartSec=3
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-yt.service <<EOF
|
|
[Unit]
|
|
Description=DouyinWEB YouTube.js sidecar
|
|
After=network.target
|
|
[Service]
|
|
Type=simple
|
|
WorkingDirectory=${APP_DIR}/youtube-svc
|
|
Environment=YT_SVC_HOST=127.0.0.1
|
|
Environment=YT_SVC_PORT=${YT_PORT}
|
|
Environment=NODE_ENV=production
|
|
ExecStart=${NODE_BIN} src/server.mjs
|
|
Restart=always
|
|
RestartSec=3
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-api.service <<EOF
|
|
[Unit]
|
|
Description=DouyinWEB FastAPI
|
|
After=network.target douyinweb-pb.service douyinweb-s3.service
|
|
[Service]
|
|
Type=simple
|
|
WorkingDirectory=${APP_DIR}/backend
|
|
Environment=TZ=Asia/Shanghai
|
|
Environment=DY_PB_URL=http://127.0.0.1:${PB_PORT}
|
|
Environment=DY_PB_ADMIN_EMAIL=${PB_ADMIN_EMAIL}
|
|
Environment=DY_PB_ADMIN_PASSWORD=${ADMIN_PASS}
|
|
Environment=DY_S3_ENABLED=true
|
|
Environment=DY_S3_ENDPOINT=http://127.0.0.1:${S3_PORT}
|
|
Environment=DY_S3_PUBLIC_BASE=${PUBLIC_BASE}
|
|
Environment=DY_S3_ACCESS_KEY=${S3_ACCESS}
|
|
Environment=DY_S3_SECRET_KEY=${S3_SECRET}
|
|
Environment=DY_S3_BUCKET=${S3_BUCKET}
|
|
Environment=DY_S3_REGION=us-east-1
|
|
Environment=DY_YOUTUBE_SVC_URL=http://127.0.0.1:${YT_PORT}
|
|
Environment=DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
|
|
Environment=DY_CORS_ORIGINS=${PUBLIC_BASE},http://127.0.0.1:${WEB_PORT}
|
|
Environment=DY_AUTH_ENABLED=true
|
|
Environment=DY_ADMIN_USERNAME=${ADMIN_USER}
|
|
Environment=DY_ADMIN_PASSWORD=${ADMIN_PASS}
|
|
Environment=DY_SESSION_SECRET=${SESSION_SECRET}
|
|
ExecStart=${APP_DIR}/backend/.venv/bin/python -m uvicorn app.main:app --host 127.0.0.1 --port ${API_PORT}
|
|
Restart=always
|
|
RestartSec=3
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-web.service <<EOF
|
|
[Unit]
|
|
Description=DouyinWEB Next.js
|
|
After=network.target douyinweb-api.service
|
|
[Service]
|
|
Type=simple
|
|
WorkingDirectory=${APP_DIR}/frontend
|
|
Environment=TZ=Asia/Shanghai
|
|
Environment=NODE_ENV=production
|
|
Environment=DY_INTERNAL_API_URL=http://127.0.0.1:${API_PORT}
|
|
Environment=DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
|
|
Environment=PORT=${WEB_PORT}
|
|
Environment=HOSTNAME=127.0.0.1
|
|
ExecStart=${NPM_BIN} run start -- --hostname 127.0.0.1 --port ${WEB_PORT}
|
|
Restart=always
|
|
RestartSec=3
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-sw-master.service <<EOF
|
|
[Unit]
|
|
Description=SeaweedFS master
|
|
After=network.target
|
|
[Service]
|
|
ExecStart=/opt/seaweedfs/weed master -ip=127.0.0.1 -port=${SW_MASTER_PORT} -mdir=/data/douyinweb-seaweed/master
|
|
Restart=always
|
|
RestartSec=2
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-sw-volume.service <<EOF
|
|
[Unit]
|
|
Description=SeaweedFS volume
|
|
After=douyinweb-sw-master.service
|
|
Requires=douyinweb-sw-master.service
|
|
[Service]
|
|
ExecStart=/opt/seaweedfs/weed volume -mserver=127.0.0.1:${SW_MASTER_PORT} -ip=127.0.0.1 -port=${SW_VOLUME_PORT} -dir=/data/douyinweb-seaweed/volume -max=100
|
|
Restart=always
|
|
RestartSec=2
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-sw-filer.service <<EOF
|
|
[Unit]
|
|
Description=SeaweedFS filer
|
|
After=douyinweb-sw-volume.service
|
|
[Service]
|
|
ExecStart=/opt/seaweedfs/weed filer -master=127.0.0.1:${SW_MASTER_PORT} -ip=127.0.0.1 -port=${SW_FILER_PORT} -defaultReplicaPlacement=000
|
|
Restart=always
|
|
RestartSec=2
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
cat >/etc/systemd/system/douyinweb-s3.service <<EOF
|
|
[Unit]
|
|
Description=SeaweedFS S3
|
|
After=douyinweb-sw-filer.service
|
|
[Service]
|
|
ExecStart=/opt/seaweedfs/weed s3 -filer=127.0.0.1:${SW_FILER_PORT} -ip.bind=127.0.0.1 -port=${S3_PORT} -config=/etc/seaweedfs/douyinweb-s3.json
|
|
Restart=always
|
|
RestartSec=2
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
systemctl daemon-reload
|
|
|
|
log "python + npm build"
|
|
python3 -m venv "$APP_DIR/backend/.venv"
|
|
"$APP_DIR/backend/.venv/bin/pip" install -U pip
|
|
"$APP_DIR/backend/.venv/bin/pip" install -r "$APP_DIR/backend/requirements.txt"
|
|
(cd "$APP_DIR/youtube-svc" && npm install --omit=dev --no-audit --no-fund)
|
|
(cd "$APP_DIR/frontend" && npm install --no-audit --no-fund && npm run build)
|
|
|
|
log "start stack"
|
|
systemctl enable --now \
|
|
douyinweb-sw-master douyinweb-sw-volume douyinweb-sw-filer douyinweb-s3 \
|
|
douyinweb-pb douyinweb-yt douyinweb-api douyinweb-web
|
|
sleep 6
|
|
|
|
"$APP_DIR/pb/pocketbase" superuser upsert "$PB_ADMIN_EMAIL" "$ADMIN_PASS" || true
|
|
export S3_PORT S3_ACCESS S3_SECRET S3_BUCKET
|
|
"$APP_DIR/backend/.venv/bin/python" - <<PY || true
|
|
import boto3, os
|
|
from botocore.client import Config
|
|
c=boto3.client("s3", endpoint_url=f"http://127.0.0.1:{os.environ.get('S3_PORT','8333')}",
|
|
aws_access_key_id=os.environ.get("S3_ACCESS","douyin"),
|
|
aws_secret_access_key=os.environ.get("S3_SECRET",""),
|
|
region_name="us-east-1", config=Config(signature_version="s3v4", s3={"addressing_style":"path"}))
|
|
try:
|
|
c.create_bucket(Bucket=os.environ.get("S3_BUCKET","douyin-covers"))
|
|
except Exception as e:
|
|
print("bucket", e)
|
|
PY
|
|
|
|
log "nginx vhost"
|
|
cat >/etc/nginx/conf.d/dy-nomadro-live.conf <<'NGX'
|
|
server {
|
|
listen 80;
|
|
server_name __DOMAIN__;
|
|
|
|
client_max_body_size 200m;
|
|
|
|
location ^~ /api/ {
|
|
proxy_pass http://127.0.0.1:__API_PORT__;
|
|
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 $scheme;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection "upgrade";
|
|
proxy_read_timeout 3600s;
|
|
}
|
|
location ^~ /covers/ {
|
|
proxy_pass http://127.0.0.1:__API_PORT__;
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Forwarded-Proto $scheme;
|
|
}
|
|
location ^~ /_/ {
|
|
proxy_pass http://127.0.0.1:__PB_PORT__;
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Forwarded-Proto $scheme;
|
|
}
|
|
location ^~ /douyin-covers/ {
|
|
proxy_pass http://127.0.0.1:__S3_PORT__;
|
|
proxy_set_header Host $host;
|
|
proxy_set_header X-Forwarded-Proto $scheme;
|
|
client_max_body_size 200m;
|
|
}
|
|
location / {
|
|
proxy_pass http://127.0.0.1:__WEB_PORT__;
|
|
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 $scheme;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection "upgrade";
|
|
proxy_read_timeout 60s;
|
|
}
|
|
}
|
|
NGX
|
|
sed -i "s/__DOMAIN__/${DOMAIN}/g; s/__API_PORT__/${API_PORT}/g; s/__PB_PORT__/${PB_PORT}/g; s/__S3_PORT__/${S3_PORT}/g; s/__WEB_PORT__/${WEB_PORT}/g" \
|
|
/etc/nginx/conf.d/dy-nomadro-live.conf
|
|
|
|
nginx -t
|
|
systemctl reload nginx
|
|
|
|
log "certbot ssl"
|
|
certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email --redirect || \
|
|
certbot certonly --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email || true
|
|
|
|
if [ -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
|
|
log "cert obtained"
|
|
systemctl reload nginx || true
|
|
fi
|
|
|
|
log "sync admin"
|
|
cd "$APP_DIR/backend"
|
|
.venv/bin/python -c "from app.session_auth import ensure_default_admin_credentials; ensure_default_admin_credentials(); from app.session_auth import get_admin_credentials; u,h=get_admin_credentials(); print('admin', u)"
|
|
|
|
log "verify"
|
|
sleep 3
|
|
systemctl is-active douyinweb-api douyinweb-web douyinweb-pb || true
|
|
curl -fsS "http://127.0.0.1:${API_PORT}/api/health" | head -c 300; echo
|
|
curl -sS -o /dev/null -w "web:%{http_code}\n" "http://127.0.0.1:${WEB_PORT}/login" || true
|
|
curl -sS -o /dev/null -w "pub:%{http_code}\n" --max-time 25 "${PUBLIC_BASE}/login" || true
|
|
echo "DONE ${PUBLIC_BASE}"
|
|
"""
|
|
|
|
|
|
def run_remote_bootstrap(client: paramiko.SSHClient) -> int:
|
|
sh = (
|
|
BOOTSTRAP_SH.replace("__DOMAIN__", DOMAIN)
|
|
.replace("__ADMIN_USER__", ADMIN_USER)
|
|
.replace("__ADMIN_PASS__", ADMIN_PASS)
|
|
.replace("__APP_DIR__", APP_DIR)
|
|
.replace("__PUBLIC_BASE__", PUBLIC_BASE)
|
|
.replace("__WEB_PORT__", str(WEB_PORT))
|
|
.replace("__API_PORT__", str(API_PORT))
|
|
.replace("__PB_PORT__", str(PB_PORT))
|
|
.replace("__YT_PORT__", str(YT_PORT))
|
|
.replace("__S3_PORT__", str(S3_PORT))
|
|
)
|
|
remote_sh = "/tmp/bootstrap_dy_nomadro.sh"
|
|
sftp = client.open_sftp()
|
|
with sftp.file(remote_sh, "w") as f:
|
|
f.write(sh)
|
|
sftp.chmod(remote_sh, 0o755)
|
|
sftp.close()
|
|
|
|
chan = client.get_transport().open_session()
|
|
chan.settimeout(3600)
|
|
chan.get_pty(width=200, height=50)
|
|
chan.exec_command(f"bash {remote_sh}")
|
|
while True:
|
|
if chan.recv_ready():
|
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
|
if chan.recv_stderr_ready():
|
|
print(chan.recv_stderr(65535).decode("utf-8", "replace"), end="", flush=True)
|
|
if chan.exit_status_ready() and not chan.recv_ready() and not chan.recv_stderr_ready():
|
|
break
|
|
time.sleep(0.3)
|
|
while chan.recv_ready():
|
|
print(chan.recv(65535).decode("utf-8", "replace"), end="", flush=True)
|
|
return chan.recv_exit_status()
|
|
|
|
|
|
def main() -> int:
|
|
tar_path = make_tarball()
|
|
client = paramiko.SSHClient()
|
|
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
print(f"connecting {HOST}...", flush=True)
|
|
client.connect(HOST, 22, USER, PASSWORD, timeout=45, allow_agent=False, look_for_keys=False)
|
|
|
|
print("[upload tarball]", flush=True)
|
|
sftp = client.open_sftp()
|
|
sftp.put(str(tar_path), "/tmp/douyinweb_deploy.tar.gz")
|
|
sftp.close()
|
|
os.unlink(tar_path)
|
|
|
|
code = run_remote_bootstrap(client)
|
|
client.close()
|
|
print(f"\n=== exit {code} ===", flush=True)
|
|
print(f"URL: {PUBLIC_BASE}/", flush=True)
|
|
print(f"Login: {ADMIN_USER} / {ADMIN_PASS}", flush=True)
|
|
return code
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|