nomadro/deploy/social/deploy_82.py
Eric 8b4c3c6a4f Ensure pnpm install before low-mem portal build on 2C/4G.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 23:52:41 +08:00

244 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""Deploy 游民社区 portal bits to 82.157.112.245 — safe for 2C/4G.
Guardrails:
- single SSH session
- skip __pycache__ / node_modules in pack
- ensure 2G swap before build
- Node heap capped at 1536MB (never 4096 on 4G box)
- build niceness + single-threaded-ish Next
- keep site down only for the build window; always try start in finally
"""
from __future__ import annotations
import os
import tarfile
import tempfile
from pathlib import Path
import paramiko
HOST = "82.157.112.245"
USER = "ubuntu"
PASS = "Xiao4669805"
APP = "/var/www/nomadro.cn"
ROOT = Path(__file__).resolve().parents[2]
# 2C/4G: keep Node well under RAM so kernel + nginx survive
NODE_HEAP_MB = 1536
INCLUDE = [
"src/modules/social",
"src/app/social",
"src/lib/remote-config.ts",
"src/components/sections/hero.tsx",
"src/app/layout.tsx",
"src/app/hub.css",
"src/app/admin/verticals/page.tsx",
"data/remote-config.json",
"next.config.ts",
"tsconfig.json",
"apps/api/app/main.py",
"apps/api/services/social_svc",
"apps/api/services/community_svc/config.py",
"apps/api/services/community_svc/services/meetup_live.py",
"deploy/social",
"README.md",
]
_SKIP_DIR = {"__pycache__", "node_modules", ".next", ".git"}
def connect() -> paramiko.SSHClient:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HOST,
username=USER,
password=PASS,
timeout=40,
allow_agent=False,
look_for_keys=False,
banner_timeout=90,
auth_timeout=40,
)
t = c.get_transport()
if t:
t.set_keepalive(20)
return c
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 1800) -> tuple[str, int]:
_i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True)
out = o.read().decode("utf-8", "ignore")
code = o.channel.recv_exit_status()
return out, code
def _add_tree(tar: tarfile.TarFile, path: Path, arcname: str) -> None:
if path.is_file():
if path.suffix == ".pyc":
return
tar.add(path, arcname=arcname)
return
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if d not in _SKIP_DIR]
root_path = Path(root)
rel_root = root_path.relative_to(path)
for name in files:
if name.endswith(".pyc"):
continue
fp = root_path / name
if str(rel_root) == ".":
arc = f"{arcname}/{name}"
else:
arc = f"{arcname}/{rel_root.as_posix()}/{name}"
tar.add(fp, arcname=arc)
def pack() -> Path:
tmp = Path(tempfile.mkdtemp()) / "social82.tgz"
with tarfile.open(tmp, "w:gz") as tar:
for rel in INCLUDE:
p = ROOT / rel
if not p.exists():
print("skip missing", rel)
continue
_add_tree(tar, p, rel)
print("packed", tmp, "bytes", tmp.stat().st_size)
return tmp
def main() -> int:
archive = pack()
print("connecting (single session)...", flush=True)
c = connect()
print("connected", flush=True)
sftp = c.open_sftp()
sftp.put(str(archive), "/tmp/social82.tgz")
sftp.close()
print("uploaded", flush=True)
script = f"""
set -euo pipefail
APP='{APP}'
HEAP={NODE_HEAP_MB}
echo '=== preflight 2C/4G ==='
uptime
free -h | head -2
# swap (idempotent)
if ! swapon --show | grep -q .; then
if [ ! -f /swapfile ]; then
sudo fallocate -l 2G /swapfile || sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=none
sudo chmod 600 /swapfile
sudo mkswap /swapfile
fi
sudo swapon /swapfile || true
fi
grep -q '/swapfile' /etc/fstab || echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab >/dev/null
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-nomadro-swap.conf >/dev/null
sudo sysctl -p /etc/sysctl.d/99-nomadro-swap.conf >/dev/null || true
free -h | head -2
cd "$APP"
sudo cp -a data/remote-config.json /tmp/remote-config.pre-social.json || true
sudo chown -R ubuntu:ubuntu "$APP"
find "$APP/apps/api/services/social_svc" -type d -name '__pycache__' -prune -exec rm -rf {{}} + 2>/dev/null || true
tar -xzf /tmp/social82.tgz --no-same-owner
python3 - <<'PY'
import json
from pathlib import Path
app = Path('{APP}')
live = app / 'data' / 'remote-config.json'
bak = Path('/tmp/remote-config.pre-social.json')
incoming = json.loads(live.read_text(encoding='utf-8')) if live.exists() else {{}}
base = json.loads(bak.read_text(encoding='utf-8')) if bak.exists() else {{}}
mods = base.setdefault('modules', {{}}) if isinstance(base, dict) else {{}}
inc_mods = incoming.get('modules') if isinstance(incoming, dict) else {{}}
if isinstance(inc_mods, dict) and 'social' in inc_mods:
mods['social'] = inc_mods['social']
elif 'social' not in mods:
mods['social'] = {{'enabled': True, 'title': '游民社区', 'tabLabel': '社区'}}
if isinstance(base, dict):
base['modules'] = mods
live.write_text(json.dumps(base, ensure_ascii=False, indent=2) + '\\n', encoding='utf-8')
print('remote-config merged social')
else:
print('kept incoming remote-config')
PY
sudo mkdir -p /etc/nomadro
if [ -f /etc/nomadro/portal.env ]; then
sudo grep -q '^NEXT_PUBLIC_MIROTALK_URL=' /etc/nomadro/portal.env \\
&& sudo sed -i 's|^NEXT_PUBLIC_MIROTALK_URL=.*|NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn|' /etc/nomadro/portal.env \\
|| echo 'NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn' | sudo tee -a /etc/nomadro/portal.env >/dev/null
else
echo 'NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn' | sudo tee /etc/nomadro/portal.env >/dev/null
fi
# stop portal only for build; always restart
cleanup() {{
sudo systemctl start nomadro.service || true
}}
trap cleanup EXIT
sudo systemctl stop nomadro.service || true
sudo chown -R ubuntu:ubuntu "$APP"
# keep previous .next as fallback until new build succeeds
if [ -d "$APP/.next" ] && [ -f "$APP/.next/BUILD_ID" ]; then
rm -rf /tmp/nomadro.next.bak
mv "$APP/.next" /tmp/nomadro.next.bak
else
rm -rf "$APP/.next"
fi
# sync deps (e.g. centrifuge) without ballooning memory
/usr/local/bin/pnpm install --prefer-offline
export NODE_OPTIONS="--max-old-space-size=$HEAP"
export NEXT_TELEMETRY_DISABLED=1
export UV_THREADPOOL_SIZE=2
export CI=1
echo "building heap=${{HEAP}}MB nice=15"
# low priority so sshd/nginx stay responsive
set +e
nice -n 15 ionice -c2 -n7 /usr/local/bin/pnpm build
BUILD_CODE=$?
set -e
if [ "$BUILD_CODE" -ne 0 ] || [ ! -f "$APP/.next/BUILD_ID" ]; then
echo "BUILD FAILED code=$BUILD_CODE — restoring previous .next"
rm -rf "$APP/.next"
if [ -d /tmp/nomadro.next.bak ]; then
mv /tmp/nomadro.next.bak "$APP/.next"
fi
exit "$BUILD_CODE"
fi
rm -rf /tmp/nomadro.next.bak
echo BUILD_ID=$(cat "$APP/.next/BUILD_ID")
sudo systemctl start nomadro.service
trap - EXIT
sleep 4
systemctl is-active nomadro.service
curl -sk -m 10 -o /dev/null -w 'home %{{http_code}}\\n' https://nomadro.cn/ || true
curl -sk -m 10 -o /dev/null -w 'social %{{http_code}}\\n' https://nomadro.cn/social || true
curl -sk -m 10 -o /dev/null -w 'meetup %{{http_code}}\\n' https://nomadro.cn/social/meetup || true
echo DONE
"""
print("building on 82 (low-mem mode)...", flush=True)
out, code = run(c, script, timeout=2400)
print(out[-10000:] if len(out) > 10000 else out)
c.close()
try:
archive.unlink()
except OSError:
pass
return code
if __name__ == "__main__":
raise SystemExit(main())