douyinWEB/scripts/_deploy_relay_lock_kick.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

159 lines
5.5 KiB
Python

# -*- coding: utf-8 -*-
"""Deploy relay lock fix, dedupe ffmpeg, verify EvanVlogs push."""
from __future__ import annotations
import sys
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
CMD = r"""
set -e
while IFS= read -r line; do
[ -n "$line" ] || continue
export "$line"
done < <(systemctl show douyinweb-api -p Environment --value | tr ' ' '\n')
systemctl restart douyinweb-api
sleep 8
systemctl is-active douyinweb-api
cd /opt/douyinWEB/backend
.venv/bin/python <<'PY'
import json, time, os, signal, subprocess, urllib.request, urllib.error
from app import db, yt_assign_db, youtube_relay_db, youtube_neko
from app.youtube_relay_pipeline import _group_in_active_slot, pick_source_for_group, _time_slot_mode
from app.session_auth import (
create_session_token, get_admin_credentials, SESSION_COOKIE,
ensure_default_admin_credentials, hash_password,
)
from app.config import settings
db.init_db()
ensure_default_admin_credentials()
db.update_settings_map({
'admin_username': str(settings.admin_username or 'hackrobot'),
'admin_password_hash': hash_password(str(settings.admin_password or '')),
'youtube_relay_time_slot_mode': True,
'youtube_relay_enabled': True,
'youtube_relay_exclusive_live': True,
})
print('cookie', len(str(db.get_settings_map().get('dy_cookie') or '')), 'slot', _time_slot_mode())
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')[:400])
raise
def yt_ffmpegs():
out = []
for line in subprocess.getoutput('ps -eo pid,cmd').splitlines():
if 'ffmpeg' not in line or 'rtmps.youtube' not in line:
continue
parts = line.strip().split(None, 1)
try:
pid = int(parts[0])
except Exception:
continue
out.append(pid)
return out
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=True, 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'))
print('pick', pick_source_for_group(winner, respect_schedule=True) if winner else None)
if winner:
keep_neko = int(winner.get('neko_instance_id') or 0)
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:
print('stop_neko', nid, g.get('name'), youtube_neko.stop_instance(nid))
if keep_neko:
print('start_neko', youtube_neko.ensure_instance_running(keep_neko))
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','reused','source_url')})
time.sleep(25)
stt = youtube_relay_db.get_relay_state(str(winner['id'])) or {} if winner else {}
keep = int(stt.get('ffmpeg_pid') or 0)
print('db', stt.get('status'), 'pid', keep, str(stt.get('source_url') or '')[:60])
for line in (stt.get('recent_log') or [])[-8:]:
print('LOG', line)
pids = yt_ffmpegs()
print('ffmpeg_before_dedupe', pids)
for p in pids:
if keep and p == keep:
print('KEEP', p)
continue
try:
os.kill(p, signal.SIGTERM)
print('KILLED', p)
except Exception as e:
print('kill_fail', p, e)
time.sleep(12)
pids2 = yt_ffmpegs()
print('ffmpeg_after', pids2)
st2 = call('GET', '/api/youtube/relay/status')
print('running', st2.get('running'))
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')),
'ff', row.get('ffmpeg_pid'),
'err', str(row.get('error') or '')[:100])
print(subprocess.getoutput("docker ps --format '{{.Names}} {{.Status}}' | grep -i neko | head -10"))
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)
sftp = c.open_sftp()
local = ROOT / "backend/app/youtube_relay_pipeline.py"
sftp.put(str(local), "/opt/douyinWEB/backend/app/youtube_relay_pipeline.py")
print("uploaded youtube_relay_pipeline.py")
sftp.close()
_, 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[-2000:])
print("exit", code)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())