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

279 lines
8.9 KiB
Python

#!/usr/bin/env python3
"""Migrate ops data dylive(107) → dy.nomadro.live(108): rooms, shorts, assign.
Preserves row IDs. Does not overwrite shorts_oauth_profiles (already migrated).
Remaps neko_instance_id > 4 down into 1..4 round-robin on destination.
"""
from __future__ import annotations
import io
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
SRC = ("107.173.30.245", "root", "Xiao4669805")
DST = ("108.174.50.68", "root", "Xiao4669805")
DB = "/opt/douyinWEB/backend/data/monitor.db"
TABLES = [
"rooms",
"blacklist",
"channel_groups",
"shorts_channels",
"yt_long_channels",
"yt_assign_groups",
"yt_assign_pool_urls",
"yt_assign_featured_urls",
"yt_assign_slot_urls",
]
def connect(host, user, password):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
host,
22,
user,
password,
timeout=45,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
return c
def run(c, cmd, t=300):
print(f"\n$ {cmd[:180]}", 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[-8000:] if len(out) > 8000 else out, flush=True)
return code, out
# 1) Export on dylive
src = connect(*SRC)
code, _ = run(
src,
rf"""
set -euo pipefail
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import sqlite3
from pathlib import Path
src = sqlite3.connect("{DB}")
dst_path = Path("/tmp/dylive_ops_export.db")
if dst_path.exists():
dst_path.unlink()
dst = sqlite3.connect(str(dst_path))
tables = {TABLES!r}
src_tables = {{r[0] for r in src.execute("SELECT name FROM sqlite_master WHERE type='table'")}}
for t in tables:
if t not in src_tables:
print(t, "MISSING")
continue
schema = src.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (t,)).fetchone()
if not schema or not schema[0]:
print(t, "NO_SCHEMA")
continue
dst.execute(schema[0])
cols = [r[1] for r in src.execute(f"PRAGMA table_info([{{t}}])")]
rows = src.execute(f"SELECT * FROM [{{t}}]").fetchall()
if rows:
q = ",".join(["?"] * len(cols))
csql = ",".join(f"[{{c}}]" for c in cols)
dst.executemany(f"INSERT INTO [{{t}}] ({{csql}}) VALUES ({{q}})", rows)
dst.commit()
print(t, len(rows))
dst.close(); src.close()
print("EXPORT_OK", dst_path.stat().st_size)
PY
""",
)
assert code == 0
# 2) SFTP pull then push
print("[sftp] download export...", flush=True)
sftp = src.open_sftp()
sftp.get("/tmp/dylive_ops_export.db", "C:/Users/admin/AppData/Local/Temp/dylive_ops_export.db")
sftp.close()
src.close()
dst = connect(*DST)
print("[sftp] upload export...", flush=True)
sftp = dst.open_sftp()
sftp.put("C:/Users/admin/AppData/Local/Temp/dylive_ops_export.db", "/tmp/dylive_ops_export.db")
sftp.close()
# 3) Ensure neko capacity enough, merge tables, remap neko ids
code, _ = run(
dst,
rf"""
set -euo pipefail
cd /opt/douyinWEB/backend
set -a; source /etc/douyinweb.env; set +a
export DY_PUBLIC_BASE_URL=https://dy.nomadro.live
export DY_NEKO_NAT1TO1=108.174.50.68
# Grow Neko fleet to cover remapped slots (max used id after remap = 4, but create 8 for headroom)
./.venv/bin/python - <<'PY'
from app import youtube_neko as yn
print(yn.ensure_capacity(8, start_instances=set(), reconcile_running=False))
print(yn.sync_nginx_proxy(8))
PY
nginx -t && systemctl reload nginx
./.venv/bin/python - <<'PY'
import sqlite3
from pathlib import Path
SRC = Path("/tmp/dylive_ops_export.db")
DST = Path("{DB}")
TABLES = {TABLES!r}
assert SRC.is_file() and DST.is_file()
# Init schema on dst via app
from app import db, yt_assign_db
_ = db.list_rooms()
yt_assign_db.ensure_yt_assign_tables()
src = sqlite3.connect(str(SRC))
dst = sqlite3.connect(str(DST))
src.row_factory = sqlite3.Row
dst.row_factory = sqlite3.Row
def cols(con, table):
return [r[1] for r in con.execute(f"PRAGMA table_info([{{table}}])").fetchall()]
def exists(con, table):
return bool(con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone())
report = {{}}
for t in TABLES:
if not exists(src, t):
report[t] = {{"skipped": "missing_src"}}
continue
if not exists(dst, t):
schema = src.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (t,)).fetchone()
if schema and schema[0]:
dst.execute(schema[0]); dst.commit()
else:
report[t] = {{"skipped": "no_schema"}}
continue
sc, dc = cols(src, t), cols(dst, t)
common = [c for c in sc if c in dc]
rows = src.execute(f"SELECT * FROM [{{t}}]").fetchall()
before = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0]
# clear destination table then insert (fresh box expected empty)
dst.execute(f"DELETE FROM [{{t}}]")
inserted = 0
for r in rows:
d = dict(r)
# Remap oversized Neko ids into 1..8
if t == "yt_assign_groups" and "neko_instance_id" in d:
try:
nid = int(d.get("neko_instance_id") or 0)
except Exception:
nid = 0
if nid > 8:
d["neko_instance_id"] = ((nid - 1) % 8) + 1
elif nid < 0:
d["neko_instance_id"] = 0
vals = [d.get(c) for c in common]
placeholders = ",".join(["?"] * len(common))
colnames = ",".join(f"[{{c}}]" for c in common)
dst.execute(
f"INSERT OR REPLACE INTO [{{t}}] ({{colnames}}) VALUES ({{placeholders}})",
vals,
)
inserted += 1
dst.commit()
after = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0]
report[t] = {{"src": len(rows), "before": before, "after": after, "inserted": inserted}}
dst.close(); src.close()
import json
print(json.dumps(report, ensure_ascii=False, indent=2))
# sanity via app APIs
rooms = db.list_rooms()
print("rooms_total", rooms.get("total") if isinstance(rooms, dict) else len(rooms))
chs = db.list_shorts_channels()
print("shorts_channels", len(chs), "with_rt", sum(1 for c in chs if str(c.get("refresh_token") or "").strip()))
groups = yt_assign_db.list_groups(include_urls=False)
print("assign_groups", len(groups))
neko_ids = sorted({{int(g.get("neko_instance_id") or 0) for g in groups}})
print("neko_ids", neko_ids)
PY
systemctl restart douyinweb-api douyinweb-web
sleep 4
systemctl is-active douyinweb-api douyinweb-web
""",
t=400,
)
assert code == 0
# 4) Firewall for Neko HTTP + WebRTC (ufw if present; else iptables accept)
code, _ = run(
dst,
r"""
set +e
echo ===FIREWALL===
if command -v ufw >/dev/null 2>&1; then
ufw status | head -5
# HTTP already 80/443; open neko webrtc ranges used by compose
ufw allow 52000:52499/udp comment 'douyinweb-neko-webrtc' || true
ufw allow 52000:52499/tcp comment 'douyinweb-neko-webrtc-tcp' || true
ufw allow 52300:52320/udp comment 'douyinweb-neko-mux' || true
ufw allow 52300:52320/tcp comment 'douyinweb-neko-mux-tcp' || true
ufw status numbered | tail -20
else
# iptables INPUT accepts for webrtc (idempotent check)
iptables -C INPUT -p udp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52000:52499 -j ACCEPT
iptables -C INPUT -p tcp --dport 52000:52499 -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport 52000:52499 -j ACCEPT
iptables -C INPUT -p udp --dport 52300:52320 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 52300:52320 -j ACCEPT
echo iptables_ok
fi
# smoke
curl -sS -c /tmp/dyj -b /tmp/dyj -o /tmp/l.json -w 'login:%{http_code}\n' -X POST https://dy.nomadro.live/api/auth/login \
-H 'Content-Type: application/json' -d '{"username":"hackrobot","password":"Xiao4669805@"}'
cat /tmp/l.json; echo
curl -sS -b /tmp/dyj -o /tmp/rooms.json -w 'rooms_api:%{http_code}\n' 'https://dy.nomadro.live/api/rooms?limit=5'
python3 - <<'PY'
import json
d=json.load(open('/tmp/rooms.json',encoding='utf-8'))
if isinstance(d, dict):
print('rooms', d.get('total'), 'sample', len(d.get('rooms') or []))
else:
print('rooms_raw', type(d))
PY
curl -sS -b /tmp/dyj -o /tmp/ch.json -w 'channels:%{http_code}\n' https://dy.nomadro.live/api/shorts/channels
python3 - <<'PY'
import json
d=json.load(open('/tmp/ch.json',encoding='utf-8'))
rows=d if isinstance(d,list) else (d.get('channels') or d.get('items') or [])
print('channels', len(rows))
print('names', [ (r.get('name') or '')[:30] for r in rows[:8] ])
PY
curl -sS -b /tmp/dyj -o /tmp/ag.json -w 'assign:%{http_code}\n' https://dy.nomadro.live/api/youtube/assign/groups
python3 - <<'PY'
import json
d=json.load(open('/tmp/ag.json',encoding='utf-8'))
rows=d if isinstance(d,list) else (d.get('groups') or [])
print('assign', len(rows))
print('names', [ (r.get('name') or '')[:30] for r in rows[:8] ])
PY
""",
)
dst.close()
print("DONE", time.strftime("%H:%M:%S"), "exit", code)
raise SystemExit(code)