150 lines
5.7 KiB
Python
150 lines
5.7 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Diagnose nomadvlog flap via python sqlite on VPS."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sys
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
PY = r'''
|
|
import json, time, sqlite3, datetime
|
|
DB="/opt/douyinWEB/backend/data/monitor.db"
|
|
BJ=datetime.timezone(datetime.timedelta(hours=8))
|
|
conn=sqlite3.connect(DB)
|
|
conn.row_factory=sqlite3.Row
|
|
|
|
def bj(ts):
|
|
try:
|
|
return datetime.datetime.fromtimestamp(float(ts or 0), BJ).strftime("%Y-%m-%d %H:%M:%S")
|
|
except Exception:
|
|
return str(ts)
|
|
|
|
# find group(s)
|
|
rows=conn.execute("SELECT id,name,category,enabled,neko_instance_id,youtube_channel_id FROM yt_assign_groups WHERE lower(name) LIKE '%nomadvlog%'").fetchall()
|
|
print("GROUPS", [dict(r) for r in rows])
|
|
gids=[r["id"] for r in rows]
|
|
if not gids:
|
|
raise SystemExit("no nomadvlog group")
|
|
|
|
# tables present
|
|
tabs={r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}
|
|
print("HAS", {t for t in tabs if "relay" in t or "event" in t or "session" in t or "kv" in t})
|
|
|
|
for gid in gids:
|
|
print("\n====", gid)
|
|
if "youtube_relay_state" in tabs:
|
|
st=conn.execute("SELECT * FROM youtube_relay_state WHERE group_id=?", (gid,)).fetchone()
|
|
if st:
|
|
d=dict(st)
|
|
print("STATE status=", d.get("status"), "room=", d.get("source_room_id"), "anchor=", d.get("anchor_name"), "pid=", d.get("ffmpeg_pid"))
|
|
print(" err=", (d.get("error") or "")[:200])
|
|
print(" upd=", bj(d.get("updated_at")), "start=", bj(d.get("started_at")))
|
|
log=d.get("recent_log") or ""
|
|
if isinstance(log, str) and log.startswith("["):
|
|
try: log=json.loads(log)
|
|
except Exception: pass
|
|
if isinstance(log, list):
|
|
print(" recent_log:")
|
|
for line in log[-40:]:
|
|
print(" ", line)
|
|
else:
|
|
print(" recent_log_raw=", str(log)[-1500:])
|
|
# sessions for this group (youtube monitor uses room_pk=group_id)
|
|
if "sessions" in tabs:
|
|
sess=conn.execute(
|
|
"""
|
|
SELECT id,room_id,status,anchor_name,title,
|
|
started_at,ended_at,updated_at
|
|
FROM sessions
|
|
WHERE room_pk=? OR room_id LIKE ?
|
|
ORDER BY started_at DESC LIMIT 40
|
|
""",
|
|
(gid, f"%{gid}%"),
|
|
).fetchall()
|
|
print("SESSIONS", len(sess))
|
|
for s in sess:
|
|
print(" ", bj(s["started_at"]), "->", bj(s["ended_at"] or 0), "st=", s["status"], "room=", s["room_id"], "title=", (s["title"] or "")[:50])
|
|
|
|
# events
|
|
print("\n==== EVENTS 24h nomadvlog / YouTube 开停播 ====")
|
|
ev=conn.execute(
|
|
"""
|
|
SELECT created_at, kind, level, message, room_id, room_pk, session_id
|
|
FROM events
|
|
WHERE created_at > ?
|
|
AND (
|
|
message LIKE '%nomadvlog%'
|
|
OR message LIKE '%YouTube 开播%'
|
|
OR message LIKE '%YouTube 停播%'
|
|
OR room_pk IN ({})
|
|
)
|
|
ORDER BY created_at DESC LIMIT 120
|
|
""".format(",".join("?"*len(gids))),
|
|
(time.time()-24*3600, *gids),
|
|
).fetchall()
|
|
for e in ev:
|
|
print(bj(e["created_at"]), e["kind"], (e["message"] or "")[:130])
|
|
|
|
# count flaps last 24h
|
|
opens=sum(1 for e in ev if "开播" in (e["message"] or "") and "nomadvlog" in (e["message"] or "").lower())
|
|
# also by room_pk
|
|
opens2=sum(1 for e in ev if "开播" in (e["message"] or "") and e["room_pk"] in gids)
|
|
closes=sum(1 for e in ev if "停播" in (e["message"] or "") and (e["room_pk"] in gids or "nomadvlog" in (e["message"] or "").lower()))
|
|
print("FLAP_COUNT open_by_name", opens, "open_by_pk", opens2, "close", closes)
|
|
|
|
# settings
|
|
print("\n==== SETTINGS ====")
|
|
for k in ["youtube_relay_enabled","youtube_relay_time_slot_mode","youtube_relay_exclusive_live","youtube_relay_respect_schedule","youtube_relay_on_air_deadline_sec"]:
|
|
# try kv_settings and settings
|
|
row=None
|
|
if "kv_settings" in tabs:
|
|
row=conn.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone()
|
|
if not row and "settings" in tabs:
|
|
row=conn.execute("SELECT value FROM settings WHERE key=?", (k,)).fetchone()
|
|
print(k, row["value"] if row else None)
|
|
|
|
# schedule
|
|
print("\n==== SCHEDULE ====")
|
|
import sys
|
|
sys.path.insert(0,"/opt/douyinWEB/backend")
|
|
from app import yt_assign_db
|
|
sched=yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True)
|
|
print("now keys", list(sched.keys())[:20])
|
|
for c in (sched.get("channels") or []):
|
|
name=str(c.get("name") or "")
|
|
if "nomadvlog" in name.lower() or c.get("active"):
|
|
print(json.dumps({k:c.get(k) for k in c.keys() if k in ("name","active","group_id","alias_group_ids","window_label","slot_label","start","end","window","label","begin","finish","from","to") or "slot" in k or "window" in k or "time" in k}, ensure_ascii=False))
|
|
|
|
conn.close()
|
|
'''
|
|
|
|
REMOTE = r"""#!/bin/bash
|
|
set -e
|
|
cat > /tmp/_dy_nv_diag.py <<'EOF'
|
|
""" + PY + r"""
|
|
EOF
|
|
/opt/douyinWEB/backend/.venv/bin/python /tmp/_dy_nv_diag.py
|
|
echo "=== JOURNAL ==="
|
|
journalctl -u douyinweb-api.service --since '24 hours ago' --no-pager 2>/dev/null | grep -iE 'nomadvlog|45f9bd79|source_switch|outside_slot|invalid push|on_air|halt_session|exclusive' | tail -150 || true
|
|
"""
|
|
|
|
|
|
def main():
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False)
|
|
sftp = c.open_sftp()
|
|
with sftp.file("/tmp/_dy_nv_remote.sh", "w") as f:
|
|
f.write(REMOTE.replace("\r\n", "\n"))
|
|
sftp.close()
|
|
_, o, e = c.exec_command("bash /tmp/_dy_nv_remote.sh", timeout=180)
|
|
print((o.read() + e.read()).decode("utf-8", "replace"))
|
|
c.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|