Document test9 tag 2026-11-02 for upload; POST config pull + WS, fixed dark home, no debug bar. Co-authored-by: Cursor <cursoragent@cursor.com>
258 lines
8.8 KiB
Python
258 lines
8.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Deploy admin SPA + CRUD APIs (stats series, social ugc, community, memo/books/orders).
|
|
|
|
- Never wipe catalogs unless catalog PUT is called by operator
|
|
- Snapshot /api/config version before/after
|
|
- Set SOCIAL_DB_PATH + fix social.db perms for www
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import json
|
|
import subprocess
|
|
import tarfile
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
REPO = Path(__file__).resolve().parents[3]
|
|
ADMIN = REPO / "apps/admin"
|
|
HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805"
|
|
|
|
API_FILES = [
|
|
("apps/api/services/ebook_svc/services/store.py", "services/store.py"),
|
|
("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"),
|
|
("apps/api/services/ebook_svc/services/memo_store.py", "services/memo_store.py"),
|
|
("apps/api/services/ebook_svc/services/shop_store.py", "services/shop_store.py"),
|
|
("apps/api/services/ebook_svc/schemas/admin.py", "schemas/admin.py"),
|
|
("apps/api/services/ebook_svc/routers/admin.py", "routers/admin.py"),
|
|
("apps/api/services/ebook_svc/routers/social_ugc_admin.py", "routers/social_ugc_admin.py"),
|
|
("apps/api/services/ebook_svc/routers/community_admin.py", "routers/community_admin.py"),
|
|
("apps/api/services/ebook_svc/routers/memo_admin.py", "routers/memo_admin.py"),
|
|
("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_admin.py"),
|
|
]
|
|
|
|
|
|
def rewrite(text: str) -> str:
|
|
return text.replace("ebook_svc.", "app.")
|
|
|
|
|
|
def snapshot() -> dict:
|
|
req = urllib.request.Request(
|
|
"https://api.nomadro.cn/api/config",
|
|
headers={"User-Agent": "nomadro-admin-crud-deploy"},
|
|
)
|
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
|
data = json.loads(resp.read().decode("utf-8"))
|
|
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
|
mods = cfg.get("modules") if isinstance(cfg.get("modules"), dict) else {}
|
|
return {
|
|
"version": cfg.get("version"),
|
|
"social": mods.get("social"),
|
|
"source": data.get("source"),
|
|
}
|
|
|
|
|
|
def build_admin() -> None:
|
|
print("vite build…", flush=True)
|
|
r = subprocess.run(
|
|
["pnpm", "exec", "vite", "build"],
|
|
cwd=ADMIN,
|
|
shell=True,
|
|
capture_output=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
)
|
|
if r.returncode != 0:
|
|
print(r.stdout)
|
|
print(r.stderr)
|
|
raise SystemExit(r.returncode)
|
|
|
|
|
|
def pack() -> bytes:
|
|
buf = io.BytesIO()
|
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
|
for rel, dest in API_FILES:
|
|
src = REPO / rel
|
|
text = rewrite(src.read_text(encoding="utf-8"))
|
|
if "ebook_svc" in text and dest != "main.py":
|
|
# main may mention ebook only in comments; services must be clean
|
|
if "ebook_svc." in text:
|
|
raise SystemExit(f"rewrite failed: {rel}")
|
|
data = text.encode("utf-8")
|
|
info = tarfile.TarInfo(name="api/" + dest)
|
|
info.size = len(data)
|
|
tar.addfile(info, io.BytesIO(data))
|
|
dist = ADMIN / "dist"
|
|
for p in dist.rglob("*"):
|
|
if p.is_file():
|
|
tar.add(p, arcname="admin-dist/" + p.relative_to(dist).as_posix())
|
|
buf.seek(0)
|
|
blob = buf.read()
|
|
print("pack", len(blob), flush=True)
|
|
return blob
|
|
|
|
|
|
def main() -> int:
|
|
before = snapshot()
|
|
print("BEFORE", before, flush=True)
|
|
build_admin()
|
|
blob = pack()
|
|
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
c.connect(HOST, username=USER, password=PASS, timeout=60, allow_agent=False, look_for_keys=False)
|
|
sftp = c.open_sftp()
|
|
with sftp.file("/tmp/admin-crud.tar.gz", "wb") as rf:
|
|
rf.write(blob)
|
|
sftp.close()
|
|
|
|
cmd = r"""
|
|
set -e
|
|
cd /tmp
|
|
rm -rf admin-crud && mkdir admin-crud
|
|
tar -xzf admin-crud.tar.gz -C admin-crud
|
|
|
|
API_ROOT=$(systemctl show nomadmini-api -p WorkingDirectory --value 2>/dev/null || true)
|
|
if [ -z "$API_ROOT" ] || [ "$API_ROOT" = "/" ]; then API_ROOT=/opt/nomadmini/backend; fi
|
|
B=$API_ROOT/app
|
|
if [ ! -d "$B" ]; then B=$API_ROOT/backend/app; fi
|
|
echo B=$B
|
|
TS=$(date -u +%Y%m%dT%H%M%SZ)
|
|
|
|
sudo mkdir -p "$B/services" "$B/routers" "$B/schemas"
|
|
for f in \
|
|
services/store.py \
|
|
services/social_ugc.py \
|
|
services/memo_store.py \
|
|
services/shop_store.py \
|
|
schemas/admin.py \
|
|
routers/admin.py \
|
|
routers/social_ugc_admin.py \
|
|
routers/community_admin.py \
|
|
routers/memo_admin.py \
|
|
routers/shop_admin.py
|
|
do
|
|
if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi
|
|
sudo cp "admin-crud/api/$f" "$B/$f"
|
|
done
|
|
|
|
# Patch main.py to include new routers (idempotent)
|
|
python3 - <<'PY'
|
|
from pathlib import Path
|
|
p = Path("/opt/nomadmini/backend/app/main.py")
|
|
text = p.read_text(encoding="utf-8")
|
|
changed = False
|
|
if "social_ugc_admin" not in text:
|
|
needle = "from app.routers import social_ops_admin"
|
|
if needle in text:
|
|
text = text.replace(
|
|
needle,
|
|
needle
|
|
+ "\nfrom app.routers import social_ugc_admin # noqa: E402\nfrom app.routers import community_admin # noqa: E402",
|
|
1,
|
|
)
|
|
changed = True
|
|
if "include_router(social_ugc_admin.router)" not in text:
|
|
needle2 = "include_router(social_ops_admin.router)"
|
|
if needle2 in text:
|
|
text = text.replace(
|
|
needle2,
|
|
needle2
|
|
+ "\napp.include_router(social_ugc_admin.router)\napp.include_router(community_admin.router)",
|
|
1,
|
|
)
|
|
changed = True
|
|
if changed:
|
|
p.write_text(text, encoding="utf-8")
|
|
print("patched_main")
|
|
else:
|
|
print("main_ok")
|
|
PY
|
|
|
|
# social db perms + env for nomadmini-api
|
|
sudo mkdir -p /var/www/nomadro-data/social /var/www/nomadro-data/community
|
|
if [ -f /var/www/nomadro-data/social/social.db ]; then
|
|
sudo chown www:www /var/www/nomadro-data/social/social.db || true
|
|
sudo chmod 664 /var/www/nomadro-data/social/social.db || true
|
|
sudo chown www:www /var/www/nomadro-data/social || true
|
|
fi
|
|
sudo mkdir -p /etc/systemd/system/nomadmini-api.service.d
|
|
sudo tee /etc/systemd/system/nomadmini-api.service.d/social-db.conf >/dev/null <<'EOF'
|
|
[Service]
|
|
Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db
|
|
Environment=COMMUNITY_STORE_PATH=/var/www/nomadro-data/community/community_store.json
|
|
EOF
|
|
sudo systemctl daemon-reload
|
|
|
|
sudo rsync -a --delete /tmp/admin-crud/admin-dist/ /www/wwwroot/admin.nomadro.cn/
|
|
sudo chown -R www:www /www/wwwroot/admin.nomadro.cn
|
|
echo admin_synced
|
|
|
|
sudo systemctl restart nomadmini-api
|
|
sleep 3
|
|
systemctl is-active nomadmini-api
|
|
|
|
TOK=$(curl -sk -X POST https://api.nomadro.cn/api/admin/login -H 'Content-Type: application/json' -d '{"username":"admin","password":"Xiao4669805"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))")
|
|
AUTH="Authorization: Bearer $TOK"
|
|
|
|
echo -n 'stats '
|
|
curl -sk -o /tmp/st.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats
|
|
python3 - <<'PY'
|
|
import json
|
|
d=json.load(open('/tmp/st.json',encoding='utf-8'))
|
|
assert 'series' in d, d
|
|
print('series_ok', len(d['series'].get('revenue',[])), 'top', len(d.get('topEvents') or []))
|
|
PY
|
|
|
|
echo -n 'social_ugc '
|
|
curl -sk -o /tmp/su.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/social/ugc/overview
|
|
python3 - <<'PY'
|
|
import json
|
|
d=json.load(open('/tmp/su.json',encoding='utf-8'))
|
|
print('ugc', d.get('exists'), d.get('writable'), d.get('counts'))
|
|
PY
|
|
|
|
echo -n 'community '
|
|
curl -sk -o /tmp/co.json -w "%{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/community/overview
|
|
|
|
for u in /wechat /wechat/social/data /wechat/community /wechat/books; do
|
|
curl -sk -o /dev/null -w "admin$u %{http_code}\n" "https://admin.nomadro.cn$u"
|
|
done
|
|
|
|
curl -sk https://api.nomadro.cn/api/config -o /tmp/cfg-after.json
|
|
python3 - <<'PY'
|
|
import json
|
|
d=json.load(open('/tmp/cfg-after.json',encoding='utf-8'))
|
|
social=d.get('config',{}).get('modules',{}).get('social')
|
|
print('live_social', social)
|
|
assert isinstance(social, dict) and social.get('enabled') is True
|
|
print('config_ok')
|
|
PY
|
|
|
|
rm -rf /tmp/admin-crud /tmp/admin-crud.tar.gz /tmp/st.json /tmp/su.json /tmp/co.json /tmp/cfg-after.json
|
|
"""
|
|
_, stdout, _ = c.exec_command(cmd, timeout=300, get_pty=True)
|
|
while not stdout.channel.exit_status_ready():
|
|
if stdout.channel.recv_ready():
|
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
|
time.sleep(0.05)
|
|
while stdout.channel.recv_ready():
|
|
print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True)
|
|
code = stdout.channel.recv_exit_status()
|
|
c.close()
|
|
|
|
after = snapshot()
|
|
print("AFTER", after, flush=True)
|
|
if after.get("version") != before.get("version") or after.get("social") != before.get("social"):
|
|
print("FAIL config drifted", flush=True)
|
|
return 3
|
|
print(f"[exit {code}] admin CRUD deployed; version {after.get('version')}", flush=True)
|
|
return code
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|