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

151 lines
5.8 KiB
Python

# -*- coding: utf-8 -*-
"""Deploy safe perf hardenings (no business/data) to phys + VPS."""
from __future__ import annotations
import json
import sys
import time
import http.cookiejar
import urllib.request
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
BACKEND = [
"backend/app/main.py",
"backend/app/shellcrash_hub.py",
"backend/app/network_hub.py",
"backend/app/youtube_live.py",
"backend/app/youtube_neko.py",
"backend/app/youtube_client.py",
"backend/app/pb_sync.py",
]
FRONTEND = [
"frontend/src/app/ops/mobile/page.tsx",
"frontend/src/lib/douyinLive.ts",
"frontend/src/lib/youtubeLive.ts",
"frontend/src/components/YtAssignPanel.tsx",
]
REMOTE_SH = r"""#!/bin/bash
set -euo pipefail
ROOT=/opt/douyinWEB
mkdir -p "$ROOT/backend/app" "$ROOT/frontend/src/app/ops/mobile" \
"$ROOT/frontend/src/lib" "$ROOT/frontend/src/components"
# Install uploaded files (LF-safe)
python3 - <<'PY'
from pathlib import Path
import os
pairs = []
for name in os.listdir('/tmp'):
if not name.startswith('_dy_opt_'):
continue
# _dy_opt_N__relpath_with_underscores stored as map file
print('skip map')
PY
i=0
while [ -f "/tmp/_dy_opt_${i}.path" ]; do
rel=$(cat "/tmp/_dy_opt_${i}.path")
dst="$ROOT/$rel"
mkdir -p "$(dirname "$dst")"
python3 -c "from pathlib import Path; p=Path('/tmp/_dy_opt_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\\r\\n',b'\\n').replace(b'\\r',b'\\n')); print('ok', d)"
i=$((i+1))
done
systemctl restart douyinweb-api.service
sleep 5
systemctl is-active douyinweb-api.service
# Rebuild frontend if sources changed (Next)
if [ -d "$ROOT/frontend" ] && command -v npm >/dev/null 2>&1; then
cd "$ROOT/frontend"
npm run build >/tmp/dy_opt_fe.log 2>&1 && echo FE_OK || { echo FE_FAIL; tail -30 /tmp/dy_opt_fe.log; }
systemctl restart douyinweb-web.service 2>/dev/null || systemctl restart douyinweb-next.service 2>/dev/null || true
sleep 3
systemctl is-active douyinweb-web.service 2>/dev/null || systemctl is-active douyinweb-next.service 2>/dev/null || true
fi
# Verify markers in code
grep -n '_HEALTH_DEPS_CACHE\|deps_cached\|DY_LIVE_HTTP_PROBE\|include_minute_reports\|STATUS_CACHE_TTL' \
"$ROOT/backend/app/main.py" "$ROOT/backend/app/shellcrash_hub.py" "$ROOT/backend/app/youtube_live.py" \
"$ROOT/backend/app/youtube_neko.py" 2>/dev/null | head -25
curl -sS -m 5 http://127.0.0.1:8014/api/ping || true
echo
curl -sS -m 8 http://127.0.0.1:8014/api/health | python3 -c "import sys,json; d=json.load(sys.stdin); print('health ok',d.get('ok'),'deps_cached',d.get('deps_cached'),'yt', (d.get('youtube') or {}).get('ok'),'pb',(d.get('pocketbase') or {}).get('ok'),'s3',(d.get('s3') or {}).get('ok'))" || echo health_fail
# second health should often be cached
sleep 1
curl -sS -m 8 http://127.0.0.1:8014/api/health | python3 -c "import sys,json; d=json.load(sys.stdin); print('health2 deps_cached',d.get('deps_cached'))" || true
systemctl is-active douyinweb-shellcrash-tuic-guard.service 2>/dev/null || true
systemctl is-active douyinweb-wireguard-watch.service douyinweb-neko-watch.service douyinweb-api-watch.service 2>/dev/null || true
"""
def deploy(label: str, host: str, port: int, user: str, pw: str, *, sudo: bool) -> None:
print(f"\n===== deploy {label} =====")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host, port, user, pw, timeout=50, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
files = BACKEND + FRONTEND
for i, rel in enumerate(files):
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
with sftp.file(f"/tmp/_dy_opt_{i}.bin", "wb") as f:
f.write(data)
with sftp.file(f"/tmp/_dy_opt_{i}.path", "w") as f:
f.write(rel.replace("\\", "/"))
with sftp.file("/tmp/_dy_opt_remote.sh", "w") as f:
f.write(REMOTE_SH.replace("\r\n", "\n"))
sftp.close()
cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_opt_remote.sh" if sudo else "bash /tmp/_dy_opt_remote.sh"
_, o, e = c.exec_command(cmd, timeout=600)
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out[-12000:] if len(out) > 12000 else out)
c.close()
def pub(base: str) -> None:
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode()
req = urllib.request.Request(
base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"}
)
try:
op.open(req, timeout=35)
with op.open(urllib.request.Request(base + "/api/health"), timeout=20) as r:
h = json.loads(r.read().decode())
with op.open(urllib.request.Request(base + "/api/rooms?limit=5"), timeout=30) as r:
rooms = json.loads(r.read().decode())
with op.open(urllib.request.Request(base + "/api/network/shellcrash/status"), timeout=40) as r:
sc = json.loads(r.read().decode())
shell = sc.get("shellcrash") or sc
print(
base,
"health=", h.get("ok"),
"deps_cached=", h.get("deps_cached"),
"rooms=", len(rooms.get("rooms") or []),
"sc_node=", shell.get("selected_node"),
"sc_default=", shell.get("default_node"),
"allow_vless=", shell.get("allow_vless_autopick"),
)
except Exception as exc:
print(base, "ERR", exc)
deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True)
deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False)
time.sleep(3)
print("\n===== public =====")
for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"):
pub(b)
print("done")