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

273 lines
9.1 KiB
Python

#!/usr/bin/env python3
"""Fix nginx include dupes; check avatar existence on dy S3; align public_base."""
from __future__ import annotations
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, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805"
def connect(host):
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("retry", host, e, flush=True)
time.sleep(2 + i)
raise SystemExit("ssh fail")
def run(c, script, timeout=120):
_i, o, e = c.exec_command(script, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
print("=== dy nginx full conf + includes ===", flush=True)
c = connect(DY)
print(run(c, r"""
set -e
CONF=/etc/nginx/conf.d/dy-nomadro-live.conf
echo '---- current conf ----'
nl -ba "$CONF" | sed -n '1,120p'
echo
echo '---- includes mentioning covers ----'
grep -RniE 'douyin-covers|covers' /etc/nginx 2>/dev/null | head -40
"""), flush=True)
# Fix: strip ALL douyin-covers from main conf and from bak, write ONE block; also check includes
print(run(c, r"""
set -e
python3 - <<'PY'
from pathlib import Path
import re
p=Path('/etc/nginx/conf.d/dy-nomadro-live.conf')
# start from bak.covers OR current
cands=[Path('/etc/nginx/conf.d/dy-nomadro-live.conf.bak.covers'), p]
text=None
for c in cands:
if c.exists():
text=c.read_text(encoding='utf-8', errors='replace')
print('base', c)
break
# remove ALL location /douyin-covers/ blocks
while True:
text2,n=re.subn(r"\n[ \t]*location\s+/douyin-covers/[^{]*\{(?:[^{}]|\{[^{}]*\})*\}", "\n", text, count=1)
if not n:
break
text=text2
print('removed one block')
# also remove our botched insert that might be malformed
text=re.sub(r"\n[ \t]*location\s+/douyin-covers/[\s\S]*?\n[ \t]*\}\n", "\n", text)
block='''
location /douyin-covers/ {
proxy_http_version 1.1;
proxy_pass http://127.0.0.1:8333;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}
'''
if text.count('location /douyin-covers/')!=0:
print('STILL HAS', text.count('location /douyin-covers/'))
# nuke lines containing douyin-covers location start through matching braces manually
lines=text.splitlines(True)
out=[]; i=0
while i < len(lines):
if re.search(r'location\s+/douyin-covers/', lines[i]):
# skip until brace balance 0
bal=0; started=False
while i < len(lines):
bal += lines[i].count('{') - lines[i].count('}')
started=True
i+=1
if started and bal<=0:
break
continue
out.append(lines[i]); i+=1
text=''.join(out)
print('after strip count', text.count('location /douyin-covers/'))
m=re.search(r"(server_name\s+[^;]+;)", text)
if not m:
raise SystemExit('no server_name')
text=text[:m.end()]+"\n"+block+text[m.end():]
p.write_text(text, encoding='utf-8')
print('final count', text.count('location /douyin-covers/'))
PY
# if include file also has it, comment out
for f in /etc/nginx/conf.d/*.inc /etc/nginx/conf.d/*covers* ; do
[ -f "$f" ] || continue
if grep -q 'location /douyin-covers' "$f" 2>/dev/null; then
echo "FOUND in $f — commenting"
sed -i 's/^\(\s*location \/douyin-covers\)/# \1/' "$f" || true
fi
done
nginx -t
systemctl reload nginx
echo nginx_reloaded_ok
"""), flush=True)
# Probe avatars on local dy S3 vs s3.nomadro (via listing a few from DB)
print(run(c, r"""
set -e
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app.db import _connect, _lock
import urllib.request
with _lock:
conn=_connect()
rows=conn.execute("SELECT avatar_url FROM rooms WHERE avatar_url LIKE 'https://s3.nomadro.com/%' LIMIT 20").fetchall()
ok=bad=[]
for (u,) in rows:
key=u.split('https://s3.nomadro.com/douyin-covers/',1)[-1]
local='http://127.0.0.1:8333/douyin-covers/'+key
try:
urllib.request.urlopen(local, timeout=3).read(16)
ok.append(key)
except Exception as e:
bad.append(key)
print('dy_local_ok', len(ok), 'bad', len(bad))
print('ok_sample', ok[:5])
print('bad_sample', bad[:8])
# if many ok on dy local but missing on s3.nomadro, point avatar_url to dy.nomadro.live
PY
# Also set DY_S3_PUBLIC_BASE to dy.nomadro.live so new uploads get working host
grep -n S3_PUBLIC /etc/systemd/system/douyinweb-api.service /etc/douyinweb.env 2>/dev/null | head
"""), flush=True)
c.close()
# If dy local has avatars that s3 doesn't, rewrite avatar base to https://dy.nomadro.live/douyin-covers
print("=== maybe rewrite to dy.nomadro.live if objects live there ===", flush=True)
c = connect(DY)
out = run(c, r"""
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app.db import _connect, _lock
import urllib.request
with _lock:
conn=_connect()
rows=conn.execute("SELECT id, avatar_url FROM rooms WHERE avatar_url LIKE 'https://s3.nomadro.com/douyin-covers/%'").fetchall()
moved=0
keep=0
missing_both=0
for rid, u in rows:
key=u.split('https://s3.nomadro.com/douyin-covers/',1)[-1]
on_dy=False
on_s3=False
try:
urllib.request.urlopen('http://127.0.0.1:8333/douyin-covers/'+key, timeout=2).read(8)
on_dy=True
except Exception:
pass
# don't call remote s3 from here for all — use on_dy preference
if on_dy:
new='https://dy.nomadro.live/douyin-covers/'+key
conn.execute('UPDATE rooms SET avatar_url=? WHERE id=?', (new, rid))
moved+=1
else:
missing_both+=1
conn.commit()
print('moved_to_dy_live', moved, 'not_on_dy', missing_both)
for r in conn.execute("SELECT substr(avatar_url,1,100), COUNT(*) FROM rooms WHERE avatar_url LIKE 'http%' GROUP BY 1 LIMIT 5"):
pass
from collections import Counter
c=Counter()
for (u,) in conn.execute("SELECT CASE WHEN avatar_url LIKE 'https://dy.nomadro.live%' THEN 'dy.live' WHEN avatar_url LIKE 'https://s3.nomadro.com%' THEN 's3' ELSE 'other' END FROM rooms WHERE avatar_url LIKE 'http%'"):
c[u]+=1
print(dict(c))
PY
""")
print(out, flush=True)
c.close()
# Sync same rewrite logic on dylive DB: for each avatar, if not on local s3, point to dy.nomadro.live
c = connect(DYLIVE)
print(run(c, r"""
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
from app.db import _connect, _lock
import urllib.request
with _lock:
conn=_connect()
rows=conn.execute("SELECT id, avatar_url FROM rooms WHERE avatar_url LIKE 'http%'").fetchall()
to_live=to_s3=missing=0
for rid,u in rows:
u=str(u)
if '/douyin-covers/' not in u:
continue
key=u.split('/douyin-covers/',1)[-1]
on_local=False
try:
urllib.request.urlopen('http://127.0.0.1:8333/douyin-covers/'+key, timeout=2).read(8)
on_local=True
except Exception:
pass
if on_local:
new='https://s3.nomadro.com/douyin-covers/'+key
to_s3+=1
else:
# prefer dy.nomadro.live public path (peer VPS bucket)
new='https://dy.nomadro.live/douyin-covers/'+key
to_live+=1
if new!=u:
conn.execute('UPDATE rooms SET avatar_url=? WHERE id=?', (new, rid))
conn.commit()
print('point_s3', to_s3, 'point_dy_live', to_live)
from collections import Counter
c=Counter()
for (u,) in conn.execute("SELECT CASE WHEN avatar_url LIKE 'https://dy.nomadro.live%' THEN 'dy.live' WHEN avatar_url LIKE 'https://s3.nomadro.com%' THEN 's3' WHEN avatar_url LIKE 'https://dy.nomadro.com%' THEN 'dy.com' ELSE 'other' END FROM rooms WHERE avatar_url LIKE 'http%'"):
c[u]+=1
print(dict(c))
PY
# also pool urls
./.venv/bin/python - <<'PY'
from app.db import _connect, _lock
with _lock:
conn=_connect()
try:
n=0
for a,b in [
('https://dy.nomadro.com/douyin-covers','https://dy.nomadro.live/douyin-covers'),
('https://s3.nomadro.com/douyin-covers','https://dy.nomadro.live/douyin-covers'),
]:
# only rewrite s3->live for keys missing locally — skip bulk for pool; just dy.com -> live
pass
cur=conn.execute("UPDATE yt_assign_pool_urls SET cover_url=REPLACE(cover_url,'https://dy.nomadro.com/douyin-covers','https://dy.nomadro.live/douyin-covers') WHERE cover_url LIKE 'https://dy.nomadro.com/douyin-covers%'")
print('pool_dycom', cur.rowcount)
conn.commit()
except Exception as e:
print('pool', e)
PY
"""), flush=True)
c.close()
# public verify avatars now
print("=== verify ===", flush=True)
for u in [
"https://dy.nomadro.live/douyin-covers/covers/avatars/16693589495.jpg",
"https://dy.nomadro.live/douyin-covers/covers/avatars/288944177940.jpg",
"https://dy.nomadro.live/douyin-covers/covers/avatars/562629369787.jpg",
"https://s3.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg",
"https://dy.nomadro.com/douyin-covers/covers/avatars/562629369787.jpg",
"https://dy.nomadro.live/douyin-covers/covers/ab13d4f5-9639-40db-a40f-6af8443f3757.jpg",
]:
try:
r=urllib.request.urlopen(urllib.request.Request(u, headers={"User-Agent":"v"}), timeout=15, context=CTX)
print(r.status, u)
except urllib.error.HTTPError as e:
print("HTTP", e.code, u)
except Exception as ex:
print("ERR", ex, u)
print("ALL_DONE", flush=True)