# -*- coding: utf-8 -*- """Deploy pending ebook API backend only (no admin SPA). - Rewrite ebook_svc.* → app.* - Hot-copy into /opt/nomadmini/backend/app - Restart nomadmini-api only - Snapshot /api/config version before/after (must not drift) """ from __future__ import annotations import io import json import tarfile import time import urllib.request from pathlib import Path import paramiko REPO = Path(__file__).resolve().parents[3] 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/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/services/weapp_switches.py", "services/weapp_switches.py"), ("apps/api/services/ebook_svc/services/social_ugc.py", "services/social_ugc.py"), ("apps/api/services/ebook_svc/services/social_ops.py", "services/social_ops.py"), ( "apps/api/services/ebook_svc/services/public_config_snapshot.py", "services/public_config_snapshot.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/memo_admin.py", "routers/memo_admin.py"), ("apps/api/services/ebook_svc/routers/shop_admin.py", "routers/shop_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/social_ops_admin.py", "routers/social_ops_admin.py"), ("apps/api/services/ebook_svc/routers/public_config.py", "routers/public_config.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-api-backend-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"), "book": mods.get("book"), "source": data.get("source"), } 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 if not src.is_file(): raise SystemExit(f"missing {rel}") text = rewrite(src.read_text(encoding="utf-8")) 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)) buf.seek(0) blob = buf.read() print("pack", len(blob), "files", len(API_FILES), flush=True) return blob def main() -> int: before = snapshot() print("BEFORE", before, flush=True) 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/api-backend.tar.gz", "wb") as rf: rf.write(blob) sftp.close() cmd = r""" set -e cd /tmp rm -rf api-backend && mkdir api-backend tar -xzf api-backend.tar.gz -C api-backend 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/memo_store.py \ services/shop_store.py \ services/weapp_switches.py \ services/social_ugc.py \ services/social_ops.py \ services/public_config_snapshot.py \ schemas/admin.py \ routers/admin.py \ routers/memo_admin.py \ routers/shop_admin.py \ routers/social_ugc_admin.py \ routers/community_admin.py \ routers/social_ops_admin.py \ routers/public_config.py do if [ -f "$B/$f" ]; then sudo cp "$B/$f" "$B/$f.bak-$TS"; fi sudo cp "api-backend/api/$f" "$B/$f" echo copied $f done # Ensure main.py registers new admin routers (idempotent) python3 - <<'PY' from pathlib import Path candidates = [ Path("/opt/nomadmini/backend/app/main.py"), ] for p in candidates: if not p.is_file(): continue text = p.read_text(encoding="utf-8") changed = False imports = [ ("social_ops_admin", "from app.routers import social_ops_admin # noqa: E402"), ("social_ugc_admin", "from app.routers import social_ugc_admin # noqa: E402"), ("community_admin", "from app.routers import community_admin # noqa: E402"), ] for key, line in imports: if key not in text: # append near other router imports anchor = "from app.routers import" idx = text.rfind(anchor) if idx >= 0: end = text.find("\n", idx) text = text[: end + 1] + line + "\n" + text[end + 1 :] changed = True else: text = line + "\n" + text changed = True includes = [ ("social_ops_admin.router", "app.include_router(social_ops_admin.router)"), ("social_ugc_admin.router", "app.include_router(social_ugc_admin.router)"), ("community_admin.router", "app.include_router(community_admin.router)"), ] for key, line in includes: if key not in text: # after last include_router needle = "app.include_router(" idx = text.rfind(needle) if idx >= 0: end = text.find("\n", idx) text = text[: end + 1] + line + "\n" + text[end + 1 :] changed = True if changed: p.write_text(text, encoding="utf-8") print("patched_main", p) else: print("main_ok", p) PY cd "$API_ROOT" if [ -x .venv/bin/python ]; then .venv/bin/python - <<'PY' from app.services.weapp_switches import read_weapp_switches from app.services import public_config_snapshot print("import_ok", read_weapp_switches().get("bookAudit")) print("snapshot_cls", public_config_snapshot.PublicConfigSnapshot) PY fi sudo systemctl restart nomadmini-api sleep 4 systemctl is-active nomadmini-api curl -sk -o /dev/null -w "health %{http_code}\n" https://api.nomadro.cn/health curl -sk -o /dev/null -w "config %{http_code}\n" https://api.nomadro.cn/api/config curl -sk -o /dev/null -w "meta %{http_code}\n" https://api.nomadro.cn/api/config/meta 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',''))") echo token_len=${#TOK} AUTH="Authorization: Bearer $TOK" curl -sk -o /dev/null -w "switches %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/weapp/switches curl -sk -o /dev/null -w "stats %{http_code}\n" -H "$AUTH" https://api.nomadro.cn/api/admin/stats rm -rf /tmp/api-backend /tmp/api-backend.tar.gz """ _, 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}] api backend deployed; version {after.get('version')}", flush=True) return code if __name__ == "__main__": raise SystemExit(main())