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

169 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Recover neko-7 Studio tab after Aw Snap; free pressure without wiping Cookies."""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
def ssh():
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,
banner_timeout=120,
)
return c
def run(c, cmd, t=180):
print(f"\n$ {cmd[:220]}", flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
code = o.channel.recv_exit_status()
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out[-16000:] if len(out) > 16000 else out, flush=True)
return code, out
c = ssh()
# Drop page caches only (safe); show top mem hogs excluding sing-box/frpp/wg
run(
c,
r"""
set +e
echo ===MEM_BEFORE===
free -h
# sync + drop caches to relieve immediate pressure (not stopping services)
sync; echo 3 > /proc/sys/vm/drop_caches
sleep 1
echo ===MEM_AFTER_DROP===
free -h
echo ===TOP_RSS===
ps -eo pid,user,rss,comm --sort=-rss | head -25
echo ===NEKO7_STATS===
docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}}' douyinweb-neko-7
""",
)
# Soft Chrome renderer recover inside container: SIGTERM chrome only, let supervisord/neko relaunch.
# Do NOT docker recreate / wipe profile.
run(
c,
r"""
set +e
echo ===SOFT_CHROME===
# List chrome pids via /proc (no ps in image sometimes)
docker exec douyinweb-neko-7 sh -c 'for p in /proc/[0-9]*; do
cmd=$(tr "\0" " " < $p/cmdline 2>/dev/null)
case "$cmd" in
*chrome*|*chromium*) echo "${p#/proc/} $cmd" | head -c 200; echo;;
esac
done' | head -40
# Graceful: kill chrome renderer/browser; neko entrypoint should restart browser
docker exec douyinweb-neko-7 sh -c 'pkill -TERM -f "/usr/bin/google-chrome|/usr/bin/chromium|chrome --type=gpu|chrome --type=renderer" 2>/dev/null; pkill -TERM chrome 2>/dev/null; true'
sleep 4
docker exec douyinweb-neko-7 sh -c 'pgrep -a chrome 2>/dev/null | head -10 || echo no_chrome_yet'
# If still dead, ask neko open studio via our helper
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json, time
from app import youtube_neko as yn, yt_assign_db
nid=7
# wait CDP back
ok=False
for i in range(20):
try:
urls=yn._cdp_live_studio_urls(nid)
tabs=yn._cdp_fetch_tabs(nid)
pages=[t for t in tabs if (t.get("type") or "page")=="page"]
print("wait", i, "pages", len(pages), "live_urls", urls[:1])
if pages:
ok=True
break
except Exception as e:
print("wait_err", i, e)
time.sleep(2)
print("cdp_ready", ok)
# Find asian time_slot group bound to neko 7
g=None
for row in yt_assign_db.list_groups(include_urls=False):
if int(row.get("neko_instance_id") or 0)==7:
g=row
print("group", row.get("name"), row.get("id"), row.get("youtube_channel_id"))
break
studio = ""
if g:
ycid=str(g.get("youtube_channel_id") or "").strip()
studio = yn.studio_live_control_url(ycid) if ycid else ""
# Prefer exact video livestreaming URL if telemetry/cdp had one
for t in yn._cdp_fetch_tabs(nid):
u=str(t.get("url") or "")
if "studio.youtube.com" in u and "livestreaming" in u:
studio=u
break
if not studio:
studio="https://studio.youtube.com/video/4dntxn9WM_Y/livestreaming"
print("open", studio[:120])
# Activate or open Live tab (safe CDP)
r=yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio)
print("ensure_tab", r)
time.sleep(8)
# Reload once more for Aw Snap residue
py='''
import json,urllib.request,base64,os,socket,struct,time
tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read().decode())
pages=[t for t in tabs if (t.get("type") or "page")=="page"]
live=[t for t in pages if "livestreaming" in (t.get("url") or "").lower()]
pick=(live or [None])[0]
print("tabs",[( (t.get("url") or "")[:100], (t.get("title") or "")[:40]) for t in pages])
if not pick: raise SystemExit(0)
tid=pick["id"]; ws=pick.get("webSocketDebuggerUrl"); url=pick.get("url")
urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}",timeout=3).read()
def ws_connect(u):
hostport,path=u[5:].split("/",1); path="/"+path; host,port=hostport.split(":")
sock=socket.create_connection((host,int(port)),timeout=8)
key=base64.b64encode(os.urandom(16)).decode()
sock.sendall(f"GET {path} HTTP/1.1\\r\\nHost: {hostport}\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Key: {key}\\r\\nSec-WebSocket-Version: 13\\r\\n\\r\\n".encode())
buf=b""
while b"\\r\\n\\r\\n" not in buf: buf+=sock.recv(4096)
return sock
def ws_send(sock,payload):
data=json.dumps(payload).encode(); mask=os.urandom(4)
hdr=bytearray([0x81,0x80|len(data)]); hdr.extend(mask)
sock.sendall(bytes(hdr)+bytes(b^mask[i%4] for i,b in enumerate(data)))
sock=ws_connect(ws)
ws_send(sock,{"id":1,"method":"Page.reload","params":{"ignoreCache":True}})
time.sleep(2)
ws_send(sock,{"id":2,"method":"Page.navigate","params":{"url":url}})
time.sleep(1)
print("reloaded", url[:120])
'''
code,out=yn._run(["docker","exec",yn._container_name(nid),"python3","-c",py], timeout=40)
print(out[-2000:])
time.sleep(10)
sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0)
print("FINAL", json.dumps({k:sig.get(k) for k in ("ok","url","live_status","on_air","control_ready","preparing_stream","health","text","error")}, ensure_ascii=False)[:900])
print("MEM_HINT")
PY
free -h
docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}} cpu={{.CPUPerc}}' douyinweb-neko-7
""",
)
c.close()
print("DONE", time.strftime("%H:%M:%S"))