douyinWEB/scripts/_reinstall_dy_nomadro_fresh.py
2026-09-13 22:10:49 -05:00

563 lines
18 KiB
Python

#!/usr/bin/env python3
"""Full wipe + reinstall current douyinWEB on 108.174.50.68 (dy.nomadro.live)."""
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",
"agent-transcripts",
".cursor",
"desktop", # not needed on VPS web deploy
}
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
# skip huge one-off probe outputs
if rel.startswith("scripts/_") and rel.endswith((".txt", ".out", ".log")):
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)
n = 0
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
tar.add(full, arcname=rel)
n += 1
print(f"[pack] files={n} size={tar_path.stat().st_size / 1024 / 1024:.1f} MB", flush=True)
return tar_path
WIPE_SH = r"""#!/usr/bin/env bash
set -euo pipefail
log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; }
log "STOP old douyinweb stack"
systemctl stop douyinweb-web douyinweb-api douyinweb-yt douyinweb-pb \
douyinweb-s3 douyinweb-sw-filer douyinweb-sw-volume douyinweb-sw-master \
douyinweb-yt-slot-watch douyinweb-yt-viz-api douyinweb-yt-viz-recorder 2>/dev/null || true
systemctl disable douyinweb-web douyinweb-api douyinweb-yt douyinweb-pb \
douyinweb-s3 douyinweb-sw-filer douyinweb-sw-volume douyinweb-sw-master \
douyinweb-yt-slot-watch douyinweb-yt-viz-api douyinweb-yt-viz-recorder 2>/dev/null || true
log "REMOVE old Neko containers (keep docker engine)"
if command -v docker >/dev/null 2>&1; then
ids=$(docker ps -aq --filter name=douyinweb-neko || true)
if [ -n "${ids:-}" ]; then
docker rm -f $ids || true
fi
# drop compose project leftovers
rm -rf /opt/douyinWEB/backend/neko-runtime /opt/douyinWEB/backend/data/neko 2>/dev/null || true
fi
log "DELETE old app tree + runtime data"
rm -rf /opt/douyinWEB
rm -rf /data/douyinweb-seaweed
mkdir -p /data/douyinweb-seaweed/{master,volume,filer}
log "REMOVE obsolete unit extras / stop page"
rm -f /etc/systemd/system/douyinweb-yt-slot-watch.service \
/etc/systemd/system/douyinweb-yt-viz-api.service \
/etc/systemd/system/douyinweb-yt-viz-recorder.service
rm -rf /etc/systemd/system/douyinweb-api.service.d \
/etc/systemd/system/douyinweb-web.service.d
rm -rf /var/www/dy-stopped
systemctl daemon-reload
# Keep /etc/douyinweb.env (DOMAIN/ADMIN/SESSION/S3 secrets) — regenerate missing keys only later.
log "WIPE done"
df -h /
"""
# Reuse deploy bootstrap body from _deploy_dy_nomadro.py (extract+build+nginx+ssl)
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 "ensure 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}
DY_PUBLIC_BASE_URL=${PUBLIC_BASE}
DY_NEKO_NAT1TO1=108.174.50.68
EOF
chmod 600 "$ENV_FILE"
else
# ensure public base / nat present
grep -q '^DY_PUBLIC_BASE_URL=' "$ENV_FILE" || echo "DY_PUBLIC_BASE_URL=${PUBLIC_BASE}" >>"$ENV_FILE"
grep -q '^DY_NEKO_NAT1TO1=' "$ENV_FILE" || echo "DY_NEKO_NAT1TO1=108.174.50.68" >>"$ENV_FILE"
grep -q '^PUBLIC_BASE=' "$ENV_FILE" || echo "PUBLIC_BASE=${PUBLIC_BASE}" >>"$ENV_FILE"
fi
# shellcheck disable=SC1090
source "$ENV_FILE"
# force admin credentials from this install
ADMIN_USER="${ADMIN_USER}"
ADMIN_PASS="${ADMIN_PASS}"
SESSION_SECRET="${SESSION_SECRET:?missing SESSION_SECRET}"
S3_SECRET="${S3_SECRET:?missing S3_SECRET}"
S3_ACCESS="${S3_ACCESS:-douyin}"
S3_BUCKET="${S3_BUCKET:-douyin-covers}"
log "extract app to $APP_DIR"
mkdir -p "$APP_DIR"
rm -rf "$APP_DIR"/* "$APP_DIR"/.[!.]* 2>/dev/null || true
tar -xzf /tmp/douyinweb_deploy.tar.gz -C "$APP_DIR"
# Fresh install: never import local monitor.db (no default Douyin rooms)
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}
Environment=DY_NEKO_NAT1TO1=108.174.50.68
EnvironmentFile=-/etc/douyinweb.env
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 8
"$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 (restore app; remove stop page)"
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;
}
# files only — do not proxy the /covers page (Next)
location ^~ /covers/ {
proxy_pass http://127.0.0.1:__API_PORT__;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
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 (reuse existing cert if present)"
certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos --register-unsafely-without-email --redirect || true
nginx -t && systemctl reload nginx
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)"
# ensure empty rooms
.venv/bin/python - <<'PY'
from app import db
n=len(db.list_rooms() if hasattr(db,'list_rooms') else [])
print('rooms_count', n)
PY
log "verify"
sleep 3
systemctl is-active douyinweb-api douyinweb-web douyinweb-pb douyinweb-yt douyinweb-s3 || true
curl -fsS "http://127.0.0.1:${API_PORT}/api/health" | head -c 400; 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_script(client: paramiko.SSHClient, content: str, remote: str, timeout: int = 3600) -> int:
sftp = client.open_sftp()
with sftp.file(remote, "w") as f:
f.write(content)
sftp.chmod(remote, 0o755)
sftp.close()
chan = client.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty(width=200, height=50)
chan.exec_command(f"bash {remote}")
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:
print("=== pack current source ===", flush=True)
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("=== WIPE old install ===", flush=True)
code = run_script(client, WIPE_SH, "/tmp/wipe_dy_nomadro.sh", timeout=300)
if code != 0:
print(f"wipe failed: {code}", flush=True)
return code
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)
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))
)
print("=== bootstrap fresh install ===", flush=True)
code = run_script(client, sh, "/tmp/bootstrap_dy_nomadro_fresh.sh", timeout=3600)
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())