douyinWEB/scripts/_rehash_and_kick_relay.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

123 lines
4.8 KiB
Python

# -*- coding: utf-8 -*-
"""Load systemd env, mint session with matching secret, kick current slot winner."""
from __future__ import annotations
import sys
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
CMD = r"""
set -e
# Export each KEY=value from systemd Environment safely (handles @ , commas)
while IFS= read -r line; do
[ -n "$line" ] || continue
export "$line"
done < <(systemctl show douyinweb-api -p Environment --value | tr ' ' '\n')
cd /opt/douyinWEB/backend
.venv/bin/python <<'PY'
import json, time, urllib.request, urllib.error, subprocess
from app import db, yt_assign_db, youtube_relay_db, youtube_neko
from app.youtube_relay_pipeline import _group_in_active_slot
from app.session_auth import (
create_session_token, get_admin_credentials, hash_password,
verify_admin, SESSION_COOKIE, ensure_default_admin_credentials,
)
from app.config import settings
print('secret', (settings.session_secret or '')[:12], 'user', settings.admin_username)
db.init_db()
ensure_default_admin_credentials()
# force hash match in case prior bad rehash
db.update_settings_map({
'admin_username': str(settings.admin_username or 'hackrobot'),
'admin_password_hash': hash_password(str(settings.admin_password or '')),
})
print('verify', verify_admin(settings.admin_username, settings.admin_password))
print('cookie', len(str(db.get_settings_map().get('dy_cookie') or '')))
print('slot_mode', db.get_settings_map().get('youtube_relay_time_slot_mode'),
'enabled', db.get_settings_map().get('youtube_relay_enabled'))
user, _ = get_admin_credentials()
token = create_session_token(user)
port = 8014
def call(method, path, body=None, timeout=300):
data = None if body is None else json.dumps(body).encode()
req = urllib.request.Request(
f'http://127.0.0.1:{port}{path}', data=data, method=method,
headers={'Cookie': f'{SESSION_COOKIE}={token}', 'Content-Type': 'application/json'},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode())
except urllib.error.HTTPError as e:
print('HTTP', e.code, path, e.read().decode('utf-8', 'replace')[:500])
raise
st = call('POST', '/api/youtube/relay/start')
print('relay', st.get('enabled'), st.get('running'))
winner = None
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
if g.get('has_stream_key') and g.get('enabled') and _group_in_active_slot(str(g.get('id')), keyed_only=True):
winner = g
break
print('winner', (winner or {}).get('name'), 'neko', (winner or {}).get('neko_instance_id'), (winner or {}).get('id'))
if winner:
keep = int(winner.get('neko_instance_id') or 0)
# stop off-slot nekos
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
if str(g.get('id')) == str(winner.get('id')):
continue
if not g.get('has_stream_key'):
continue
nid = int(g.get('neko_instance_id') or 0)
if nid > 0 and hasattr(youtube_neko, 'stop_instance'):
print('stop_neko', nid, g.get('name'), youtube_neko.stop_instance(nid))
if keep:
print('start_neko', keep, youtube_neko.ensure_instance_running(keep))
r = call('POST', f"/api/youtube/relay/groups/{winner['id']}/start")
print('group_start', {k: r.get(k) for k in ('ok', 'waiting', 'error', 'note', 'ffmpeg_pid', 'fatal')})
stt = youtube_relay_db.get_relay_state(str(winner['id'])) or {}
print('db_status', stt.get('status'), str(stt.get('error') or '')[:300])
for line in (stt.get('recent_log') or [])[-20:]:
print('LOG', line)
time.sleep(25)
st2 = call('GET', '/api/youtube/relay/status')
print('after_running', st2.get('running'), 'enabled', st2.get('enabled'))
for row in st2.get('groups') or []:
print('G', row.get('name'),
'biz', row.get('business_status'),
'st', row.get('status'),
'neko', ((row.get('neko') or {}).get('running')),
'err', str(row.get('error') or '')[:160])
print(subprocess.getoutput("ps aux | grep '[f]fmpeg' | grep -iE 'rtmp|youtube|a\\.rtmp' | head -10"))
print(subprocess.getoutput("docker ps --format '{{.Names}} {{.Status}}' | grep -i neko | head -20"))
PY
"""
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=60, allow_agent=False, look_for_keys=False)
_, o, e = c.exec_command(CMD, timeout=480)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
code = o.channel.recv_exit_status()
print(out[-12000:] if len(out) > 12000 else out)
if err.strip():
print("STDERR", err[-2500:])
print("exit", code)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())