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

207 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Deploy pending dy features to dylive.nomadro.com. Never recreate Neko."""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
PASS = "Xiao4669805"
HOST = "107.173.30.245"
FILES = [
"backend/app/yt_stream_key_db.py",
"backend/app/yt_assign_db.py",
"backend/app/youtube_relay_status.py",
"backend/app/models.py",
"backend/app/main.py",
"backend/neko/browser-launch.sh",
"frontend/src/lib/ytRelayStatus.ts",
"frontend/src/components/YtAssignPanel.tsx",
"frontend/src/components/YtRelayProStatusPanel.tsx",
"frontend/src/app/youtube/keys/page.tsx",
"frontend/src/app/youtube-relay-log/page.tsx",
]
def connect(retries: int = 15):
last = None
for i in range(retries):
try:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
22,
"root",
PASS,
timeout=60,
allow_agent=False,
look_for_keys=False,
banner_timeout=300,
auth_timeout=60,
)
return c
except Exception as e:
last = e
print(f"ssh_retry {i}: {e}", flush=True)
time.sleep(4 + i * 2)
raise SystemExit(f"ssh_fail: {last}")
def run(c, cmd: str, t: int = 900) -> tuple[int, str]:
print(f"\n===== {cmd[:100].replace(chr(10), ' ')} =====", flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
out = (o.read() + e.read()).decode("utf-8", "replace")
code = o.channel.recv_exit_status()
print(out[-12000:] if len(out) > 12000 else out, flush=True)
return code, out
for rel in FILES:
assert (ROOT / rel).is_file(), rel
c = connect()
code, before = run(
c,
"docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; "
"systemctl is-active douyinweb-api douyinweb-web; free -h | head -2",
)
before_up = {ln.split()[0] for ln in before.splitlines() if " Up " in ln and "neko" in ln}
print("before_up", sorted(before_up), flush=True)
# upload files
sftp = c.open_sftp()
for rel in FILES:
remote = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}"
run(c, f"mkdir -p {'/'.join(remote.split('/')[:-1])}", t=30)
print("put", rel, flush=True)
sftp.put(str(ROOT / rel), remote)
sftp.close()
# patch browser-launch into whatever inode running nekos mount
run(
c,
r"""
set +e
SRC=/opt/douyinWEB/backend/neko/browser-launch.sh
grep -n jitless "$SRC" | head -3
for name in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do
ino=$(docker exec "$name" sh -c 'ls -li /etc/neko/browser-launch.sh' 2>/dev/null | awk '{print $1}')
[ -z "$ino" ] && continue
match=$(ls -li /opt/douyinWEB/backend/neko/browser-launch.sh* 2>/dev/null | awk -v i="$ino" '$1==i{print $NF; exit}')
if [ -n "$match" ]; then
cat "$SRC" > "$match"
echo patched "$name" "$match"
fi
if docker exec "$name" grep -q jitless /etc/neko/browser-launch.sh 2>/dev/null; then
echo OK_VISIBLE "$name"
else
echo STALE "$name"
fi
done
""",
)
# API restart + import keys from assign + optional peer import from local export if we pull from dy later
run(
c,
r"""
set -euo pipefail
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app import yt_stream_key_db, yt_assign_db, models
gs = yt_assign_db.list_groups(include_urls=False, include_secret=True)
print('groups', len(gs), 'with_stream_key', sum(1 for g in gs if g.get('stream_key')))
print('import', yt_stream_key_db.import_from_assign_groups(replace=False))
print('registry_total', yt_stream_key_db.list_entries(include_secret=False)['total'])
PY
systemctl restart douyinweb-api
sleep 5
systemctl is-active douyinweb-api
curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 200; echo
""",
)
# Frontend: prefer copying .next from local tarball if exists; else low-mem build
tgz = ROOT / "scripts" / "_dy_next_keys.tgz"
if tgz.is_file() and tgz.stat().st_size > 1_000_000:
print("upload next tarball", tgz.stat().st_size, flush=True)
sftp = c.open_sftp()
sftp.put(str(tgz), "/tmp/dy-next-keys.tgz")
sftp.close()
run(
c,
r"""
set -euo pipefail
cd /opt/douyinWEB/frontend
mkdir -p .next
tar -xzf /tmp/dy-next-keys.tgz -C /opt/douyinWEB/frontend
# ensure source files exist too
test -f src/app/youtube/keys/page.tsx && echo keys_src_ok
systemctl restart douyinweb-web
sleep 4
systemctl is-active douyinweb-web
""",
)
else:
run(
c,
r"""
set -euo pipefail
cd /opt/douyinWEB/frontend
export NODE_OPTIONS=--max-old-space-size=1536
# drop caches to help build
sync; echo 3 > /proc/sys/vm/drop_caches || true
if [ -d node_modules ]; then
npm run build
else
echo 'FATAL no node_modules'
exit 3
fi
systemctl restart douyinweb-web
sleep 4
systemctl is-active douyinweb-web
""",
t=900,
)
code, after = run(
c,
r"""
set +e
docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort
curl -sk -m 15 -o /dev/null -w 'home:%{http_code}\n' https://dylive.nomadro.com/
curl -sk -m 15 -o /dev/null -w 'youtube:%{http_code}\n' https://dylive.nomadro.com/youtube
curl -sk -m 15 -o /dev/null -w 'keys:%{http_code}\n' https://dylive.nomadro.com/youtube/keys
# smoke login + groups have stream_key
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json, urllib.request, http.cookiejar
cj=http.cookiejar.CookieJar()
op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login', data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(), headers={'Content-Type':'application/json'}, method='POST')
print('login', op.open(req, timeout=20).status)
gs=json.loads(op.open('http://127.0.0.1:8014/api/youtube/assign/groups', timeout=60).read()).get('groups') or []
print('groups', len(gs), 'key_fields', sum(1 for g in gs if g.get('stream_key')))
keys=json.loads(op.open('http://127.0.0.1:8014/api/youtube/stream-keys', timeout=30).read())
print('registry', keys.get('total'))
PY
""",
)
after_up = {ln.split()[0] for ln in after.splitlines() if " Up " in ln and "neko" in ln}
lost = before_up - after_up
if lost:
print("CRITICAL neko lost", lost, flush=True)
run(c, "docker start " + " ".join(sorted(lost)) + "; sleep 6; docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort")
raise SystemExit(2)
print("neko_ok", sorted(after_up), flush=True)
c.close()
print("ALL_DONE")