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

219 lines
7.3 KiB
Python

# -*- coding: utf-8 -*-
"""Fix neko edges: native Caddy/Nginx per-id reverse_proxy (WS-safe), no Python gateway.
Generates /neko/1..N → :9200+(n-1) so new groups never 404 and WebSocket works.
"""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
MAX_N = 64 # headroom; create_group can grow; raise via env later if needed
UP_COM = "10.8.0.2"
UP_CN = "10.9.0.2"
def caddy_neko_routes(n: int) -> str:
lines = [
f"\t# Neko 1..{n} — native reverse_proxy (WebSocket OK). Do not route via :9199 gateway.",
]
for i in range(1, n + 1):
port = 9199 + i # 1→9200
lines.append(
f"""\thandle /neko/{i} {{
\t\tredir /neko/{i}/ 308
\t}}
\thandle_path /neko/{i}/* {{
\t\treverse_proxy {UP_COM}:{port} {{
\t\t\theader_up Host {{host}}
\t\t\theader_up X-Forwarded-Proto {{scheme}}
\t\t\theader_up X-Forwarded-Host {{host}}
\t\t}}
\t}}"""
)
return "\n".join(lines) + "\n"
def nginx_neko_routes(n: int) -> str:
parts = [f" # Neko 1..{n} — native proxy_pass (WebSocket OK)\n"]
for i in range(1, n + 1):
port = 9199 + i
parts.append(
f""" location = /neko/{i} {{ return 308 /neko/{i}/; }}
location /neko/{i}/ {{
proxy_pass http://{UP_CN}:{port}/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_buffering off;
}}
"""
)
return "".join(parts)
def ssh(h, p, u, pw):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(h, p, u, pw, timeout=60, allow_agent=False, look_for_keys=False)
return c
def run(c, cmd, t=120):
_, o, e = c.exec_command(cmd, timeout=t)
return (o.read() + e.read()).decode("utf-8", "replace")
def replace_neko_section_caddy(text: str, new_block: str) -> str:
# Remove any existing neko-related handles / gateway
import re
# Drop from first neko-ish comment/handle until before handle /_/* or handle {
# Simpler: remove known patterns then insert before handle /_/*
text = re.sub(
r"\n\t# (Unlimited Neko|Neko 1\.\.).*?(?=\n\thandle /_/\*|\n\thandle \{)",
"\n",
text,
flags=re.S,
)
text = re.sub(r"\n\thandle /neko(?:/\d+)? \{\n\t\tredir[\s\S]*?\n\t\}\n", "\n", text)
text = re.sub(r"\n\thandle_path /neko/\d+/\* \{[\s\S]*?\n\t\}\n", "\n", text)
text = re.sub(r"\n\t@neko path /neko /neko/\*\n", "\n", text)
text = re.sub(r"\n\thandle @neko \{[\s\S]*?\n\t\}\n", "\n", text)
if "handle /_/*" in text:
return text.replace("handle /_/*", new_block + "\n\thandle /_/*", 1)
return text.replace("\thandle {", new_block + "\n\thandle {", 1)
def replace_neko_section_nginx(text: str, new_block: str) -> str:
import re
text = re.sub(
r"\n\s*# (Unlimited Neko|Neko 1\.\.)[\s\S]*?(?=\n\s*location / \{\n\s*proxy_pass http://dy_cn_web;)",
"\n",
text,
)
text = re.sub(
r"\n\s*location = /neko(?:/\d+)? \{[^}]*\}\n\s*location /neko(?:/\d+)?/ \{[\s\S]*?\n\s*\}\n",
"\n",
text,
)
text = re.sub(r"\n\s*location = /neko/\d+ \{ return 308 /neko/\d+/; \}\n", "\n", text)
text = re.sub(r"\n\s*location /neko/\d+/ \{[\s\S]*?\n\s*\}\n", "\n", text)
text = re.sub(
r"\n\s*location /neko/ \{[\s\S]*?\n\s*\}\n",
"\n",
text,
)
marker = " location / {\n proxy_pass http://dy_cn_web;"
if marker not in text:
raise SystemExit("nginx marker missing")
return text.replace(marker, new_block + "\n" + marker, 1)
def main():
# physical: ensure containers 1..max_group up; ignore gateway for public path
g = ssh("107.173.30.245", 4014, "eric", "4669805")
print(
run(
g,
"echo '4669805' | sudo -S -p '' bash -lc '"
"python3 - <<\"PY\"\n"
"import sqlite3\n"
"c=sqlite3.connect(\"/opt/douyinWEB/backend/data/monitor.db\")\n"
"m=c.execute(\"select coalesce(max(neko_instance_id),0) from yt_assign_groups\").fetchone()[0]\n"
"print(\"max_neko\", m)\n"
"PY\n"
"for i in 1 2 3 4 5 6; do docker start douyinweb-neko-$i 2>/dev/null || true; done\n"
"sleep 2\n"
"for i in 1 5 6; do curl -sS -m 4 -o /dev/null -w \"c$i=%{http_code}\\n\" http://127.0.0.1:$((9199+i))/; done\n"
"'",
90,
),
flush=True,
)
g.close()
block = caddy_neko_routes(MAX_N)
v = ssh("107.173.30.245", 22, "root", "Xiao4669805")
path = "/etc/caddy/sites/dy.nomadro.com.caddy"
old = run(v, f"cat {path}")
new = replace_neko_section_caddy(old, block)
run(v, f"cp -a {path} {path}.bak-native-$(date +%s)")
sftp = v.open_sftp()
with sftp.file(path, "w") as f:
f.write(new)
sftp.close()
print(
run(
v,
"caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -8; "
"systemctl reload caddy; sleep 1; systemctl is-active caddy; "
"grep -c 'handle_path /neko/' /etc/caddy/sites/dy.nomadro.com.caddy; "
"grep -n '9199\\|@neko' /etc/caddy/sites/dy.nomadro.com.caddy | head || echo no_gateway",
),
flush=True,
)
d = ssh("82.157.112.245", 22, "ubuntu", "Xiao4669805")
npath = "/www/server/panel/vhost/nginx/dy.nomadro.cn.conf"
nold = run(d, f"sudo cat {npath}")
nnew = replace_neko_section_nginx(nold, nginx_neko_routes(MAX_N))
run(d, f"sudo cp -a {npath} {npath}.bak-native-$(date +%s)")
sftp = d.open_sftp()
with sftp.file("/tmp/dy.cn.neko.conf", "w") as f:
f.write(nnew)
sftp.close()
print(
run(
d,
f"sudo mv /tmp/dy.cn.neko.conf {npath}; sudo nginx -t 2>&1 | tail -8; "
"sudo nginx -s reload; echo nginx_ok",
),
flush=True,
)
d.close()
time.sleep(2)
print("=== VERIFY ===", flush=True)
print(
run(
v,
r"""
# trailing slash redirect
code=$(curl -sS -m 8 -o /dev/null -w "%{http_code}" -D /tmp/h5.txt https://dy.nomadro.com/neko/5)
loc=$(grep -i '^location:' /tmp/h5.txt | awk '{print $2}' | tr -d '\r')
echo "bare5=$code loc=$loc"
# html + js
curl -sS -m 10 -o /dev/null -w "slash5=%{http_code}\n" https://dy.nomadro.com/neko/5/
curl -sS -m 10 -o /dev/null -w "js5=%{http_code} size=%{size_download}\n" https://dy.nomadro.com/neko/5/js/app.5d9731bf.js
curl -sS -m 10 -o /dev/null -w "slash1=%{http_code}\n" https://dy.nomadro.com/neko/1/
# websocket upgrade headers (expect 101 from neko)
curl -sS -m 8 -o /dev/null -D - \
-H 'Connection: Upgrade' -H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
https://dy.nomadro.com/neko/5/ws | head -20 || true
curl -sS -m 12 -o /dev/null -w "dylive=%{http_code}\n" https://dylive.nomadro.com/api/health
""",
90,
),
flush=True,
)
v.close()
print("DONE", flush=True)
if __name__ == "__main__":
main()