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

180 lines
6.5 KiB
Python

#!/usr/bin/env python3
"""Deeper cover/S3 probe: DB paths, public cover API, S3 bucket, env files."""
from __future__ import annotations
import json
import ssl
import sys
import time
import urllib.request
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
CTX = ssl.create_default_context()
HOSTS = [
("dylive", "107.173.30.245", "https://dylive.nomadro.com"),
("dy", "108.174.50.68", "https://dy.nomadro.live"),
]
def connect(host: str):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(8):
try:
c.connect(
host,
22,
"root",
"Xiao4669805",
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}")
SCRIPT = r"""
set +e
cd /opt/douyinWEB/backend
echo '=== systemd env snippets ==='
for u in douyinweb-api; do
systemctl show "$u" -p Environment -p EnvironmentFiles 2>/dev/null | head -5
done
ls /etc/systemd/system/douyinweb-api.service.d 2>/dev/null
grep -RniE 'S3_|PUBLIC_BASE|COVER|SEAWEED' /etc/systemd/system/douyinweb-api* /etc/default/douyinweb* /opt/douyinWEB/.env /opt/douyinWEB/backend/.env 2>/dev/null | head -40
echo
echo '=== session_auth covers gate on disk ==='
grep -n 'covers' /opt/douyinWEB/backend/app/session_auth.py | head -20
echo
echo '=== DB cover_path samples ==='
./.venv/bin/python - <<'PY'
from app.db import _connect, _lock
with _lock:
conn=_connect()
cols=[r[1] for r in conn.execute('PRAGMA table_info(sessions)').fetchall()]
print('sessions_cols_coverish=', [c for c in cols if 'cover' in c.lower() or c in ('id','anchor_name','status')])
# count
try:
n=conn.execute("SELECT COUNT(*) FROM sessions WHERE cover_path IS NOT NULL AND cover_path!=''").fetchone()[0]
print('sessions_with_cover_path=', n)
except Exception as e:
print('count_err', e)
try:
rows=conn.execute("SELECT id, substr(cover_path,1,160), anchor_name FROM sessions WHERE cover_path IS NOT NULL AND cover_path!='' ORDER BY rowid DESC LIMIT 10").fetchall()
for r in rows:
print('sess', r[0][:8], r[1], r[2])
except Exception as e:
print('rows_err', e)
# rooms avatar
try:
cols2=[r[1] for r in conn.execute('PRAGMA table_info(rooms)').fetchall()]
print('rooms_cols=', [c for c in cols2 if 'avatar' in c.lower() or 'cover' in c.lower() or c=='id'])
n2=conn.execute("SELECT COUNT(*) FROM rooms WHERE avatar_url IS NOT NULL AND avatar_url!=''").fetchone()[0]
print('rooms_with_avatar=', n2)
for r in conn.execute("SELECT id, substr(avatar_url,1,160), name FROM rooms WHERE avatar_url IS NOT NULL AND avatar_url!='' LIMIT 5").fetchall():
print('room', r)
except Exception as e:
print('rooms_err', e)
# assign pool
try:
for r in conn.execute("SELECT id, substr(cover_url,1,160) FROM yt_assign_pool_urls WHERE cover_url IS NOT NULL AND cover_url!='' LIMIT 5").fetchall():
print('pool', r)
except Exception as e:
print('pool_err', e)
PY
echo
echo '=== probe local cover file + APIs ==='
F=$(ls /opt/douyinWEB/backend/data/covers/*.jpg 2>/dev/null | head -1)
echo sample_file=$F
if [ -n "$F" ]; then
BN=$(basename "$F")
curl -sS -m 5 -o /dev/null -w "covers_file_noauth:%{http_code}\n" "http://127.0.0.1:8014/covers/$BN"
fi
# pick a session id with cover
SID=$(./.venv/bin/python - <<'PY'
from app.db import _connect, _lock
with _lock:
conn=_connect()
r=conn.execute("SELECT id FROM sessions WHERE cover_path IS NOT NULL AND cover_path!='' ORDER BY rowid DESC LIMIT 1").fetchone()
print(r[0] if r else '')
PY
)
echo sid=$SID
if [ -n "$SID" ]; then
curl -sS -m 5 -o /dev/null -w "api_cover_noauth:%{http_code} size:%{size_download}\n" "http://127.0.0.1:8014/api/sessions/$SID/cover"
curl -sS -m 5 "http://127.0.0.1:8014/api/sessions/$SID/cover" | head -c 20 | xxd | head -2
fi
echo
echo '=== S3 list bucket (boto-ish via app) ==='
./.venv/bin/python - <<'PY'
from app import s3_storage
from app.config import settings
print('s3_enabled_fn', s3_storage.s3_enabled())
print('settings.s3_enabled', settings.s3_enabled)
# try force client even if disabled
try:
import boto3
from botocore.client import Config
c=boto3.client('s3', endpoint_url=settings.s3_endpoint, aws_access_key_id=settings.s3_access_key, aws_secret_access_key=settings.s3_secret_key, region_name=settings.s3_region, config=Config(signature_version='s3v4'))
try:
c.head_bucket(Bucket=settings.s3_bucket)
print('head_bucket=OK')
except Exception as e:
print('head_bucket', type(e).__name__, e)
try:
r=c.list_objects_v2(Bucket=settings.s3_bucket, MaxKeys=5)
print('list_keys', [x['Key'] for x in r.get('Contents') or []])
print('key_count_page', len(r.get('Contents') or []), 'is_truncated', r.get('IsTruncated'))
except Exception as e:
print('list_err', type(e).__name__, e)
except Exception as e:
print('boto_err', e)
PY
echo HOST_DONE
"""
for label, host, public in HOSTS:
print(f"\n######## {label} {host} ########", flush=True)
c = connect(host)
_i, o, e = c.exec_command(SCRIPT, timeout=150)
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out, flush=True)
# extract a sample sid from output for public probe
sid = ""
for line in out.splitlines():
if line.startswith("sid=") and len(line) > 4:
sid = line[4:].strip()
if line.startswith("sample_file=") and "/covers/" not in line:
pass
bn = ""
for line in out.splitlines():
if line.startswith("sample_file=") and line.strip().endswith(".jpg"):
bn = line.split("/")[-1].strip()
print(f"--- public cover probes {public} ---", flush=True)
paths = []
if bn:
paths.append(f"/covers/{bn}")
if sid:
paths.append(f"/api/sessions/{sid}/cover")
for path in paths or ["/covers/"]:
url = public + path
t0 = time.time()
try:
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=20, context=CTX) as r:
data = r.read(64)
print(path, r.status, f"t={time.time()-t0:.2f}s", "bytes", len(data), "ct", r.headers.get("content-type"), flush=True)
except Exception as ex:
print(path, "ERR", ex, f"t={time.time()-t0:.2f}s", flush=True)
c.close()
print("ALL_DONE", flush=True)