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

177 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""Continue dylive recovery: status + start only the needed Neko (no recreate)."""
from __future__ import annotations
import json
import ssl
import sys
import time
import urllib.request
from http.cookiejar import CookieJar
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
CTX = ssl.create_default_context()
def ssh():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(10):
try:
c.connect(
"107.173.30.245",
22,
"root",
"Xiao4669805",
timeout=40,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
return c
except Exception as e:
print("ssh_retry", i, e, flush=True)
time.sleep(2)
raise SystemExit("ssh fail")
def run(c, cmd, t=120):
print(f"\n$ {cmd[:110].replace(chr(10),' ')}", flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
o.channel.settimeout(t)
try:
out = (o.read() + e.read()).decode("utf-8", "replace")
except Exception as ex:
out = f"TIMEOUT {ex}"
print(out[-10000:] if len(out) > 10000 else out, flush=True)
return out
print("=== public smoke ===", flush=True)
try:
with urllib.request.urlopen("https://dylive.nomadro.com/youtube", timeout=20, context=CTX) as r:
print("youtube", r.status)
except Exception as e:
print("youtube FAIL", e)
c = ssh()
run(c, "free -m | head -2; uptime; systemctl is-active douyinweb-api douyinweb-web caddy")
run(
c,
r"""
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app import db, yt_assign_db
cfg = db.get_settings_map()
keys = [
'youtube_relay_enabled','youtube_relay_time_slot_mode','youtube_relay_exclusive_live',
'youtube_relay_timeslot_test','youtube_relay_timeslot_test_group_id'
]
for k in keys:
print(f'{k}={cfg.get(k)}')
print('--- groups ---')
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
if g.get('neko_enabled') or g.get('enabled'):
print(
f" {g.get('name')[:28]:28} cat={g.get('category')} neko={g.get('neko_instance_id')} "
f"neko_en={g.get('neko_enabled')} armed={g.get('time_slot_armed')} key={bool(g.get('has_stream_key'))}"
)
PY
""",
)
run(c, "docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V")
# Decide which neko to start:
# Prefer exclusive winner / timeslot active / neko_enabled=True; else none.
out = run(
c,
r"""
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app import db, yt_assign_db
cfg = db.get_settings_map()
auto = bool(cfg.get('youtube_relay_enabled'))
slot = bool(cfg.get('youtube_relay_time_slot_mode'))
excl = bool(cfg.get('youtube_relay_exclusive_live', True))
groups = yt_assign_db.list_groups(include_urls=False, include_secret=False)
# already enabled neko
enabled = [g for g in groups if g.get('neko_enabled') and int(g.get('neko_instance_id') or 0) > 0]
pick = None
if enabled:
pick = enabled[0]
elif slot and auto:
# current timeslot winner
try:
sch = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True)
active = next((ch for ch in (sch.get('channels') or []) if ch.get('active')), None)
if active:
gid = str(active.get('group_id') or '')
pick = next((g for g in groups if str(g.get('id'))==gid), None)
except Exception as e:
print('sched_err', e)
# fallback: first normal with key if auto and not slot
if pick is None and auto and not slot:
for g in groups:
if str(g.get('category') or 'normal') != 'time_slot' and g.get('has_stream_key') and g.get('enabled'):
pick = g
break
if pick:
print(f"PICK id={pick.get('id')} name={pick.get('name')} neko={pick.get('neko_instance_id')} cat={pick.get('category')}")
else:
print('PICK none')
print(f'FLAGS auto={auto} slot={slot} excl={excl}')
PY
""",
)
# parse PICK
neko_id = None
for line in out.splitlines():
if line.startswith("PICK id=") and "neko=" in line:
try:
neko_id = int(line.split("neko=")[1].split()[0])
except Exception:
pass
break
if neko_id and neko_id > 0:
name = f"douyinweb-neko-{neko_id}"
print(f"\n=== start only {name} ===", flush=True)
run(
c,
f"""
set +e
# stop any other running nekos first (exclusive RAM)
for n in $(docker ps --format '{{{{.Names}}}}' | grep '^douyinweb-neko-' | grep -v '^{name}$'); do
echo stop $n; docker stop "$n"
done
docker start {name} || true
sleep 12
docker ps --filter name=douyinweb-neko --format '{{{{.Names}}}} {{{{.Status}}}}' | sort -V
docker exec {name} supervisorctl status 2>/dev/null | head -8
docker exec {name} sh -c 'curl -sS -m 3 http://127.0.0.1:9222/json/version | head -c 100; echo'
free -m | head -2
""",
t=180,
)
else:
print("\n=== no neko pick — leave stopped ===", flush=True)
run(c, "free -m | head -2; docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V")
# API login smoke
run(
c,
r"""
CS=$(mktemp)
curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"username":"hackrobot","password":"Xiao4669805@"}' | head -c 100; echo
curl -sS -m 10 -b "$CS" -o /dev/null -w 'relay:%{http_code}\n' http://127.0.0.1:8014/api/youtube/relay/status
curl -sS -m 10 -o /dev/null -w 'fe:%{http_code}\n' http://127.0.0.1:4015/youtube
""",
)
c.close()
print("ALL_DONE")