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

324 lines
11 KiB
Python

#!/usr/bin/env python3
"""Fix dual-VPS S3 public images for dylive.nomadro.com + dy.nomadro.live."""
from __future__ import annotations
import json
import ssl
import sys
import time
import urllib.error
import urllib.request
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
CTX = ssl.create_default_context()
DYLIVE = "107.173.30.245"
DY = "108.174.50.68"
PASS = "Xiao4669805"
def connect(host: str):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(10):
try:
c.connect(
host,
22,
"root",
PASS,
timeout=40,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
return c
except Exception as e:
print(f"ssh_retry {host} {i}: {e}", flush=True)
time.sleep(2 + i)
raise SystemExit(f"ssh_fail {host}")
def run(c, script: str, timeout=180) -> str:
_i, o, e = c.exec_command(script, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def put(c, local_bytes: bytes, remote: str):
sftp = c.open_sftp()
with sftp.file(remote, "wb") as f:
f.write(local_bytes)
sftp.close()
def http_code(url: str) -> str:
try:
req = urllib.request.Request(url, headers={"User-Agent": "fix"})
with urllib.request.urlopen(req, timeout=20, context=CTX) as r:
return f"{r.status} {r.headers.get('content-type','')}"
except urllib.error.HTTPError as e:
return f"HTTP {e.code}"
except Exception as ex:
return f"ERR {ex}"
# --- 1) Fix dy VPS (108.174.50.68): anonymous S3 + nginx /douyin-covers ---
print("######## FIX dy VPS 108.174.50.68 ########", flush=True)
c_dy = connect(DY)
print(
run(
c_dy,
r"""
set -e
echo '=== nginx sites with douyin / covers ==='
ls /etc/nginx/sites-enabled /etc/nginx/conf.d 2>/dev/null
grep -RniE 'dy\.nomadro\.live|douyin-covers|8333|covers|proxy_pass' /etc/nginx 2>/dev/null | head -60
echo
echo '=== current s3.json ==='
python3 - <<'PY'
import json
p='/etc/seaweedfs/douyinweb-s3.json'
print(open(p).read()[:800])
PY
""",
),
flush=True,
)
# Apply anonymous read + backup
print(run(c_dy, r"""
set -e
CFG=/etc/seaweedfs/douyinweb-s3.json
cp -a "$CFG" "${CFG}.bak.$(date +%Y%m%d%H%M%S)"
python3 - <<'PY'
import json
p='/etc/seaweedfs/douyinweb-s3.json'
d=json.load(open(p))
idents=d.get('identities') or []
# ensure anonymous Read
anon=None
for i in idents:
if i.get('name')=='anonymous':
anon=i
break
if anon is None:
idents.insert(0, {'name':'anonymous','actions':['Read']})
else:
acts=set(anon.get('actions') or [])
acts.add('Read')
anon['actions']=sorted(acts)
d['identities']=idents
json.dump(d, open(p,'w'), indent=2)
print('wrote', p)
print(json.dumps(d, indent=2)[:1200])
PY
systemctl restart douyinweb-s3.service
sleep 1
systemctl is-active douyinweb-s3.service
# anonymous GET smoke
curl -sS -m 5 -o /dev/null -w 'anon:%{http_code}\n' \
'http://127.0.0.1:8333/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg' || true
"""), flush=True)
# nginx: ensure /douyin-covers proxies to local S3
print(run(c_dy, r"""
set -e
# find server block for dy.nomadro.live
CONF=$(grep -Rl 'dy.nomadro.live' /etc/nginx 2>/dev/null | head -1)
echo conf=$CONF
if [ -z "$CONF" ]; then
echo 'NO_NGINX_CONF'
exit 0
fi
cp -a "$CONF" "${CONF}.bak.s3fix.$(date +%Y%m%d%H%M%S)"
python3 - <<'PY'
import pathlib, re, time
conf=pathlib.Path(""" + '"$(grep -Rl dy.nomadro.live /etc/nginx 2>/dev/null | head -1)"' + r""")
# above injection messy — redo in shell heredoc properly
PY
"""), flush=True)
c_dy.close()
# Cleaner nginx patch via dedicated remote script
c_dy = connect(DY)
nginx_fix = r'''#!/bin/bash
set -euo pipefail
CONF=$(grep -Rl 'server_name.*dy.nomadro.live' /etc/nginx 2>/dev/null | head -1 || true)
if [ -z "$CONF" ]; then
CONF=$(grep -Rl 'dy.nomadro.live' /etc/nginx 2>/dev/null | head -1 || true)
fi
echo "CONF=$CONF"
if [ -z "$CONF" ]; then
echo "MISSING_CONF"; exit 2
fi
cp -a "$CONF" "${CONF}.bak.s3fix.$(date +%Y%m%d%H%M%S)"
python3 - "$CONF" <<'PY'
import pathlib, sys, re
p = pathlib.Path(sys.argv[1])
text = p.read_text(encoding="utf-8", errors="replace")
block = """
location /douyin-covers/ {
proxy_pass http://127.0.0.1:8333;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_hide_header x-amz-id-2;
proxy_hide_header x-amz-request-id;
}
"""
if "location /douyin-covers/" in text:
# replace existing location block roughly
text2, n = re.subn(
r"location\s+/douyin-covers/\s*\{[\s\S]*?\n\s*\}",
block.strip(),
text,
count=1,
)
if n:
text = text2
print("replaced existing /douyin-covers location")
else:
print("found marker but regex miss; appending before last } of file carefully")
# insert before last closing brace of server — fallback: after server_name line
text = text.replace("server_name", block + "\n server_name", 1)
else:
# insert after first server_name line inside file
if "server_name" in text:
text = text.replace("server_name", block + "\n server_name", 1)
print("inserted /douyin-covers after server_name")
else:
raise SystemExit("cannot find insertion point")
p.write_text(text, encoding="utf-8")
print("patched", p)
PY
nginx -t
systemctl reload nginx
echo nginx_reloaded
# public local via nginx
curl -sS -m 5 -o /dev/null -w 'nginx_local_s3:%{http_code}\n' \
-H 'Host: dy.nomadro.live' \
'http://127.0.0.1/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg' || true
'''
put(c_dy, nginx_fix.encode(), "/tmp/fix_dy_nginx_s3.sh")
print(run(c_dy, "bash /tmp/fix_dy_nginx_s3.sh"), flush=True)
# Also bind S3 to 0.0.0.0 so peer VPS can reach if needed? User said both VPS - for dy.nomadro.com on dylive,
# better point Caddy to this host's public IP:8333 OR use SSH tunnel.
# Prefer: change dylive Caddy /douyin-covers -> 127.0.0.1:8333 (local anonymous bucket shares many avatars)
# AND rewrite dy.nomadro.com avatars that 404 to try s3 — but first check object presence.
# For now also open seaweed bind to 0.0.0.0 on dy so dylive can proxy to 108.174.50.68:8333
print(run(c_dy, r"""
set -e
UNIT=/etc/systemd/system/douyinweb-s3.service
cp -a "$UNIT" "${UNIT}.bak.$(date +%Y%m%d%H%M%S)"
# change -ip.bind=127.0.0.1 to 0.0.0.0 if present
sed -i 's/-ip.bind=127.0.0.1/-ip.bind=0.0.0.0/g' "$UNIT"
systemctl daemon-reload
systemctl restart douyinweb-s3.service
sleep 1
systemctl is-active douyinweb-s3.service
ss -lntp | grep 8333 || true
# firewall? allow from dylive only if ufw
if command -v ufw >/dev/null; then ufw status | head -20; fi
# iptables quick allow 8333 from dylive if needed — check listen first
curl -sS -m 3 -o /dev/null -w 'local_anon:%{http_code}\n' 'http://127.0.0.1:8333/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg'
"""), flush=True)
c_dy.close()
# --- 2) Fix dylive Caddy: /douyin-covers -> local 8333 (same as s3.nomadro.com) ---
# Avatars historically on dy.nomadro.com; many objects also on s3.nomadro.com.
# Additionally reverse_proxy to dy VPS public :8333 as fallback is hard in Caddy without rewrite.
# Strategy: point dy.nomadro.com /douyin-covers to 108.174.50.68:8333 (peer VPS S3 now public bind)
print("######## FIX dylive Caddy dy.nomadro.com ########", flush=True)
c_v = connect(DYLIVE)
print(run(c_v, r"""
set -e
CFG=/etc/caddy/sites/dy.nomadro.com.caddy
cp -a "$CFG" "${CFG}.bak.s3fix.$(date +%Y%m%d%H%M%S)"
python3 - <<'PY'
from pathlib import Path
p=Path('/etc/caddy/sites/dy.nomadro.com.caddy')
text=p.read_text(encoding='utf-8')
old='reverse_proxy 127.0.0.1:28333'
# Prefer peer dy VPS S3 (where avatar objects for dy.nomadro.com historically lived).
# Fallback local VPS S3 also has anonymous read for objects mirrored there.
new='reverse_proxy 108.174.50.68:8333'
if old in text:
text=text.replace(old, new)
print('replaced 28333 -> 108.174.50.68:8333')
elif 'handle /douyin-covers/*' in text:
import re
text2,n=re.subn(
r'(handle /douyin-covers/\* \{\n\s*reverse_proxy )[^\n]+',
r'\g<1>108.174.50.68:8333',
text,
count=1,
)
if n:
text=text2
print('regex replaced douyin-covers upstream')
else:
raise SystemExit('could not patch douyin-covers')
else:
raise SystemExit('no douyin-covers block')
# Host header: Seaweed virtual-host style — keep Host as dy.nomadro.com or use s3 style.
# Path-style /douyin-covers/... needs Host that seaweed accepts; previously Host {host}.
p.write_text(text, encoding='utf-8')
print('ok')
PY
# show snippet
grep -nA3 'douyin-covers' /etc/caddy/sites/dy.nomadro.com.caddy | head -20
caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20
systemctl reload caddy
echo caddy_reloaded
# probe peer S3 from this host
curl -sS -m 8 -o /dev/null -w 'peer_s3:%{http_code}\n' \
'http://108.174.50.68:8333/douyin-covers/covers/avatars/16693589495.jpg' || echo peer_fail
curl -sS -m 8 -o /dev/null -w 'local_s3_avatar:%{http_code}\n' \
'http://127.0.0.1:8333/douyin-covers/covers/avatars/16693589495.jpg' || true
"""), flush=True)
# Deploy session_auth fix to both
auth_local = open(r"c:\Users\admin\Desktop\douyinWEB\backend\app\session_auth.py", "rb").read()
for label, host in [("dylive", DYLIVE), ("dy", DY)]:
print(f"######## deploy session_auth -> {label} ########", flush=True)
c = connect(host)
put(c, auth_local, "/opt/douyinWEB/backend/app/session_auth.py")
print(
run(
c,
r"""
set -e
grep -n 'covers/' /opt/douyinWEB/backend/app/session_auth.py | head -10
systemctl restart douyinweb-api
sleep 2
systemctl is-active douyinweb-api
# pick a cover file if any
F=$(ls /opt/douyinWEB/backend/data/covers/*.jpg 2>/dev/null | head -1 || true)
if [ -n "$F" ]; then
BN=$(basename "$F")
curl -sS -m 5 -o /dev/null -w "covers_noauth:%{http_code}\n" "http://127.0.0.1:8014/covers/$BN"
fi
""",
),
flush=True,
)
c.close()
# --- public verify ---
print("######## PUBLIC VERIFY ########", flush=True)
urls = [
"https://s3.nomadro.com/douyin-covers/covers/avatars/193393415810.jpg",
"https://dy.nomadro.com/douyin-covers/covers/avatars/16693589495.jpg",
"https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg",
"https://dy.nomadro.live/douyin-covers/covers/avatars/690114366322.jpg",
"https://dylive.nomadro.com/api/sessions/b9197cd9-b9af-432f-8e2a-880370ce75da/cover",
"https://dy.nomadro.live/api/sessions/ab13d4f5-9639-40db-a40f-6af8443f3757/cover",
]
for u in urls:
print(http_code(u), u, flush=True)
print("ALL_DONE", flush=True)