#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Copy Douyin rooms + YouTube channel tables from physical → dylive VPS.""" from __future__ import annotations import json import sys import time import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") VPS = ("107.173.30.245", 22, "root", "Xiao4669805") PHYS = ("107.173.30.245", 4014, "eric", "4669805") GUEST_SUDO = "4669805" DB = "/opt/douyinWEB/backend/data/monitor.db" TS = time.strftime("%Y%m%d_%H%M%S") CHANNEL_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", ] KV_KEYS = [ "shorts_oauth_profiles", "cookie", "douyin_cookie", "monitor_cookie", "web_cookie", ] PHYS_SNAP_PY = f""" import sqlite3 src = sqlite3.connect("{DB}") dst = sqlite3.connect("/tmp/phys_monitor_for_dylive.db") src.backup(dst) dst.close() src.close() c = sqlite3.connect("/tmp/phys_monitor_for_dylive.db") tables = {CHANNEL_TABLES!r} for t in tables: try: n = c.execute(f"select count(*) from [{{t}}]").fetchone()[0] except Exception as e: n = str(e) print(t, n) c.close() print("SNAP_OK") """ MERGE_PY = f""" import json import sqlite3 from pathlib import Path SRC = Path("/tmp/phys_monitor_for_dylive.db") DST = Path("{DB}") TABLES = {CHANNEL_TABLES!r} KV_KEYS = {KV_KEYS!r} assert SRC.is_file(), f"missing src {{SRC}}" assert DST.is_file(), f"missing dst {{DST}}" 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 table_exists(con, table): return bool(con.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,) ).fetchone()) report = {{"tables": {{}}, "kv": {{}}}} for t in TABLES: if not table_exists(src, t): report["tables"][t] = {{"skipped": "missing_on_physical"}} continue if not table_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["tables"][t] = {{"skipped": "no_schema"}} continue sc = cols(src, t) dc = cols(dst, t) common = [c for c in sc if c in dc] if not common: report["tables"][t] = {{"skipped": "no_common_cols"}} continue before = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0] dst.execute(f"DELETE FROM [{{t}}]") rows = src.execute(f"SELECT * FROM [{{t}}]").fetchall() if rows: qcols = ",".join(f"[{{c}}]" for c in common) placeholders = ",".join("?" for _ in common) sql = f"INSERT INTO [{{t}}] ({{qcols}}) VALUES ({{placeholders}})" payload = [] for r in rows: d = dict(r) payload.append(tuple(d.get(c) for c in common)) dst.executemany(sql, payload) after = dst.execute(f"SELECT COUNT(*) FROM [{{t}}]").fetchone()[0] report["tables"][t] = {{ "before": before, "copied": len(rows), "after": after, "cols": len(common), }} if table_exists(src, "kv_settings") and table_exists(dst, "kv_settings"): for key in KV_KEYS: row = src.execute("SELECT value FROM kv_settings WHERE key=?", (key,)).fetchone() if not row: report["kv"][key] = "absent_on_physical" continue dst.execute( "INSERT INTO kv_settings(key, value) VALUES(?, ?) " "ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, row[0]), ) report["kv"][key] = "copied" if table_exists(dst, "yt_assign_groups"): gcols = set(cols(dst, "yt_assign_groups")) if "neko_enabled" in gcols: cur = dst.execute("UPDATE yt_assign_groups SET neko_enabled = 0 WHERE neko_enabled != 0") report["neko_disabled"] = cur.rowcount dst.commit() src.close() dst.close() print(json.dumps(report, ensure_ascii=False, indent=2)) print("MERGE_OK") """ COUNT_PY = f""" import sqlite3 c = sqlite3.connect("{DB}") for t in {CHANNEL_TABLES!r}: try: n = c.execute(f"select count(*) from [{{t}}]").fetchone()[0] except Exception as e: n = str(e) print(t, n) try: ne = c.execute("select count(*) from yt_assign_groups where neko_enabled=1").fetchone()[0] except Exception: ne = "n/a" print("neko_enabled_on", ne) c.close() """ def connect(host, port, user, password): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( host, port, user, password, timeout=60, banner_timeout=120, allow_agent=False, look_for_keys=False, ) return c def run(c, cmd, timeout=300): print(f"\n$ {cmd[:240]}{'…' if len(cmd) > 240 else ''}", flush=True) _i, o, e = c.exec_command(cmd, timeout=timeout) code = o.channel.recv_exit_status() out = (o.read() + e.read()).decode("utf-8", "replace") if out.strip(): print(out[-10000:] if len(out) > 10000 else out, flush=True) print(f"→ exit={code}", flush=True) return code, out def sftp_put(c, data: bytes, remote: str): sftp = c.open_sftp() try: with sftp.open(remote, "wb") as f: f.write(data) finally: sftp.close() def sftp_get(c, remote: str) -> bytes: sftp = c.open_sftp() try: with sftp.open(remote, "rb") as f: return f.read() finally: sftp.close() def main() -> int: print(f"=== physical channels → dylive ts={TS} ===", flush=True) # 1) physical snapshot p = connect(*PHYS) try: sftp_put(p, PHYS_SNAP_PY.encode("utf-8"), "/tmp/phys_snap_channels.py") code, out = run( p, f"echo '{GUEST_SUDO}' | sudo -S -p '' bash -lc '" f"python3 /tmp/phys_snap_channels.py && " f"chown eric:eric /tmp/phys_monitor_for_dylive.db && " f"ls -lh /tmp/phys_monitor_for_dylive.db" f"'", timeout=120, ) if code != 0 or "SNAP_OK" not in out: print("FATAL: physical snapshot failed", flush=True) return 1 blob = sftp_get(p, "/tmp/phys_monitor_for_dylive.db") print(f"downloaded bytes={len(blob)}", flush=True) finally: p.close() # 2) VPS backup + merge v = connect(*VPS) try: bak = f"/root/dylive_bak_before_phys_channels_{TS}" code, _ = run( v, f"set -e; mkdir -p {bak}; " f"cp -a {DB} {bak}/monitor.db; " f"cp -a {DB}-wal {bak}/ 2>/dev/null || true; " f"cp -a {DB}-shm {bak}/ 2>/dev/null || true; " f"cp -a /etc/douyinweb.env {bak}/douyinweb.env 2>/dev/null || true; " f"cp -a /etc/systemd/system/douyinweb-api.service {bak}/ 2>/dev/null || true; " f"cp -a /etc/systemd/system/douyinweb-web.service {bak}/ 2>/dev/null || true; " f"systemctl cat douyinweb-api > {bak}/douyinweb-api.service.cat 2>/dev/null || true; " f"ls -lah {bak}", timeout=90, ) if code != 0: print("FATAL: backup failed", flush=True) return 1 print("\n--- VPS counts BEFORE ---", flush=True) sftp_put(v, COUNT_PY.encode("utf-8"), "/tmp/count_channels.py") run(v, "python3 /tmp/count_channels.py", timeout=60) sftp_put(v, blob, "/tmp/phys_monitor_for_dylive.db") sftp_put(v, MERGE_PY.encode("utf-8"), f"/tmp/merge_phys_channels_{TS}.py") run(v, "systemctl stop douyinweb-api; sleep 2; systemctl is-active douyinweb-api || true", 60) code, out = run(v, f"python3 /tmp/merge_phys_channels_{TS}.py", 180) if code != 0 or "MERGE_OK" not in out: print("FATAL: merge failed, restoring", flush=True) run( v, f"cp -a {bak}/monitor.db {DB}; systemctl start douyinweb-api; sleep 2; systemctl is-active douyinweb-api", 60, ) return 1 run( v, "systemctl start douyinweb-api; sleep 3; systemctl is-active douyinweb-api", 60, ) print("\n--- VPS counts AFTER ---", flush=True) run(v, "python3 /tmp/count_channels.py", 60) run( v, "curl -sS -m 15 -o /dev/null -w 'dylive=%{http_code}\\n' https://dylive.nomadro.com/api/health; " "curl -sS -m 15 -o /dev/null -w 'dy_com=%{http_code}\\n' https://dy.nomadro.com/api/health", 40, ) print(f"\nOK backup_dir={bak}", flush=True) return 0 finally: v.close() if __name__ == "__main__": raise SystemExit(main())