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

168 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Continue: sync key registry dy→dylive; apply jitless chrome restart on dylive neko-12; verify both."""
from __future__ import annotations
import json
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
PASS = "Xiao4669805"
DY = "108.174.50.68"
DYLIVE = "107.173.30.245"
def connect(host: str, retries: int = 12):
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,
)
return c
except Exception as e:
last = e
print(f"ssh_retry {host} {i}: {e}", flush=True)
time.sleep(3 + i)
raise SystemExit(f"ssh_fail {host}: {last}")
def run(c, cmd: str, t: int = 180) -> str:
print(f"\n===== {cmd[:90].replace(chr(10),' ')} =====", flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out[-10000:] if len(out) > 10000 else out, flush=True)
return out
# 1) export registry from dy
print("=== export dy registry ===", flush=True)
dy = connect(DY)
out = run(
dy,
r"""
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json
from app import yt_stream_key_db
print('EXPORT_JSON_START')
print(json.dumps(yt_stream_key_db.export_all(), ensure_ascii=False))
print('EXPORT_JSON_END')
print('neko:')
import subprocess
print(subprocess.check_output("docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}'", shell=True).decode())
PY
""",
)
dy.close()
start = out.find("EXPORT_JSON_START")
end = out.find("EXPORT_JSON_END")
assert start >= 0 and end > start, "no export"
payload = json.loads(out[start + len("EXPORT_JSON_START") : end].strip())
items = payload.get("items") or []
print(f"exported {len(items)} keys", flush=True)
# 2) import to dylive + restart chrome with jitless on neko-12 only
print("=== dylive import + chrome restart ===", flush=True)
dl = connect(DYLIVE)
sftp = dl.open_sftp()
with sftp.file("/tmp/yt_stream_keys_from_dy.json", "w") as f:
f.write(json.dumps({"items": items}, ensure_ascii=False))
sftp.close()
run(
dl,
r"""
set +e
echo '=== before neko ==='
docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort
free -h | head -2
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json
from app import yt_stream_key_db
data = json.load(open('/tmp/yt_stream_keys_from_dy.json', encoding='utf-8'))
print('peer_import', yt_stream_key_db.import_payload(data.get('items') or [], replace=False))
print('local_assign_snap', yt_stream_key_db.import_from_assign_groups(replace=False))
print('total', yt_stream_key_db.list_entries(include_secret=False)['total'])
# sample
for it in (yt_stream_key_db.list_entries(include_secret=True).get('items') or [])[:3]:
print('sample', it.get('name'), (it.get('stream_key') or '')[-4:])
PY
# ensure jitless on running neko chrome
if docker ps --format '{{.Names}}' | grep -qx douyinweb-neko-12; then
docker exec douyinweb-neko-12 grep -n jitless /etc/neko/browser-launch.sh | head -2
docker exec douyinweb-neko-12 supervisorctl restart google-chrome
sleep 10
docker exec douyinweb-neko-12 supervisorctl status google-chrome
docker exec douyinweb-neko-12 sh -c 'for p in /proc/[0-9]*; do
cmd=$(tr "\0" " " < "$p/cmdline" 2>/dev/null)
case "$cmd" in
*remote-debugging-port=9222*) echo "$cmd" | tr " " "\n" | grep -E "jitless|js-flags"; break;;
esac
done'
fi
echo '=== after neko ==='
docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort
systemctl is-active douyinweb-api douyinweb-web
""",
)
dl.close()
# 3) public verify both
print("=== public verify ===", flush=True)
import ssl
import urllib.request
import http.cookiejar
ctx = ssl.create_default_context()
def check(base: str):
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(cj),
urllib.request.HTTPSHandler(context=ctx),
)
req = urllib.request.Request(
base + "/api/auth/login",
data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
print(base, "login", op.open(req, timeout=30).status)
gs = json.loads(op.open(base + "/api/youtube/assign/groups", timeout=60).read()).get("groups") or []
keys = json.loads(op.open(base + "/api/youtube/stream-keys", timeout=30).read())
print(
base,
"groups",
len(gs),
"with_key",
sum(1 for g in gs if g.get("stream_key")),
"registry",
keys.get("total"),
"keys_page",
op.open(base + "/youtube/keys", timeout=30).status,
)
check("https://dy.nomadro.live")
check("https://dylive.nomadro.com")
print("DONE")