Harden 82 deploys for 2C/4G: 1536MB heap, swap, nice, .next rollback.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-01 23:50:10 +08:00
parent 70816b6ebe
commit fb703c8b85
3 changed files with 95 additions and 37 deletions

View File

@ -180,7 +180,7 @@ pnpm dev:api
- **首屏**:群组聊天在左、认识一下在右;窄屏收掉宇宙轨道,Ways 进首视口
- **滑卡 / 群聊**:手机更低滑动阈值、震动反馈;composer / 加入 sheet 全宽底栏
- **Meetup**:活动卡保留参与者头像 + 声纹条
- **发版**:`python deploy/social/deploy_82.py`(仅 82;打包跳过 `__pycache__`);冒烟 `https://nomadro.cn/social`
- **发版**:`python deploy/social/deploy_82.py`(仅 82;**2C/4G**:堆 1536MB + swap + nice;打包跳过 `__pycache__`;勿并发 SSH);冒烟 `https://nomadro.cn/social`
## test8(当前开发)

View File

@ -28,6 +28,13 @@ pnpm dev
## 线上增量(只部署 82)
生产机规格:**2C / 4G**。发版铁律(防 OOM 挂机):
- **禁止** `NODE_OPTIONS=--max-old-space-size=4096`(会吃光内存)
- `deploy/social/deploy_82.py` 默认堆 **1536MB** + `nice`/`ionice` + 确保 **2G swap**
- 构建失败会回滚上一份 `.next`;构建期间只停 `nomadro.service`
- **禁止**并行多次 SSH / 并发跑 deploy;一次发版一条会话
生产铁律:[`https://nomadro.cn`](https://nomadro.cn/) / MiroTalk / API / Centrifugo **全部在 `82.157.112.245`**,进房用 `mirotalk.nomadro.cn`。
```bash

View File

@ -1,11 +1,19 @@
#!/usr/bin/env python3
"""Deploy 游民社区 + MiroTalk(.cn) portal bits to 82.157.112.245 only."""
"""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
import time
from pathlib import Path
import paramiko
@ -15,12 +23,12 @@ 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
# Paths relative to repo root
INCLUDE = [
"src/modules/social",
"src/app/social",
"src/modules/social/lib/seed.ts", # covered by tree
"src/lib/remote-config.ts",
"src/components/sections/hero.tsx",
"src/app/layout.tsx",
@ -37,6 +45,8 @@ INCLUDE = [
"README.md",
]
_SKIP_DIR = {"__pycache__", "node_modules", ".next", ".git"}
def connect() -> paramiko.SSHClient:
c = paramiko.SSHClient()
@ -48,7 +58,8 @@ def connect() -> paramiko.SSHClient:
timeout=40,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
banner_timeout=90,
auth_timeout=40,
)
t = c.get_transport()
if t:
@ -56,16 +67,13 @@ def connect() -> paramiko.SSHClient:
return c
def run(c: paramiko.SSHClient, cmd: str, timeout: int = 1200) -> tuple[str, int]:
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
_SKIP_DIR = {"__pycache__", "node_modules", ".next", ".git"}
def _add_tree(tar: tarfile.TarFile, path: Path, arcname: str) -> None:
if path.is_file():
if path.suffix == ".pyc":
@ -102,24 +110,44 @@ def pack() -> Path:
def main() -> int:
archive = pack()
print("connecting (single session)...", flush=True)
c = connect()
print("connected")
print("connected", flush=True)
# upload
sftp = c.open_sftp()
sftp.put(str(archive), "/tmp/social82.tgz")
sftp.close()
print("uploaded")
print("uploaded", flush=True)
# extract into app (preserve remote-config backup)
script = f"""
set -euo pipefail
cd {APP}
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
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
# restore operational remote-config then merge social module key via python
python3 - <<'PY'
import json
from pathlib import Path
@ -128,14 +156,12 @@ 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 {{}}
# keep live ops flags; ensure modules.social exists from incoming
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': '社区'}}
# prefer base (prod) as SoT with social injected
if isinstance(base, dict):
base['modules'] = mods
live.write_text(json.dumps(base, ensure_ascii=False, indent=2) + '\\n', encoding='utf-8')
@ -144,7 +170,6 @@ else:
print('kept incoming remote-config')
PY
# portal env: force MiroTalk on 82 .cn
sudo mkdir -p /etc/nomadro
if [ -f /etc/nomadro/portal.env ]; then
sudo grep -q '^NEXT_PUBLIC_MIROTALK_URL=' /etc/nomadro/portal.env \\
@ -153,28 +178,54 @@ if [ -f /etc/nomadro/portal.env ]; then
else
echo 'NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn' | sudo tee /etc/nomadro/portal.env >/dev/null
fi
grep MIROTALK /etc/nomadro/portal.env || true
# .next often root-owned from prior deploys — clear then build as ubuntu
# 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}
sudo rm -rf {APP}/.next
export NODE_OPTIONS=--max-old-space-size=4096
/usr/local/bin/pnpm build
test -f .next/BUILD_ID
echo BUILD_ID=$(cat .next/BUILD_ID)
sudo chown -R ubuntu:ubuntu "$APP"
# keep previous .next as fallback until new build succeeds
if [ -d "$APP/.next" ]; then
rm -rf /tmp/nomadro.next.bak
mv "$APP/.next" /tmp/nomadro.next.bak
fi
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
sleep 5
trap - EXIT
sleep 4
systemctl is-active nomadro.service
curl -sk -o /dev/null -w 'home %{{http_code}}\\n' https://nomadro.cn/
curl -sk -o /dev/null -w 'social %{{http_code}}\\n' https://nomadro.cn/social
curl -sk -o /dev/null -w 'meetup %{{http_code}}\\n' https://nomadro.cn/social/meetup
curl -sk -o /dev/null -w 'mirotalk_cn %{{http_code}} %{{time_total}}\\n' 'https://mirotalk.nomadro.cn/join?room=t&name=t&notify=0'
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 (may take several minutes)...")
out, code = run(c, script, timeout=1500)
print(out[-8000:] if len(out) > 8000 else out)
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()