nomadro/apps/hackrobot/deploy/pull_from_129.py
Eric 1dac5fd5fd Sync vip.hackrobot.cn and admin.hackrobot.cn into apps/hackrobot with mandatory server backups.
Keep VIP stack isolated from Nomadro admin; pull/deploy scripts always snapshot /opt/hackrobot-backup first.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-22 10:48:49 +08:00

200 lines
6.7 KiB
Python

# -*- coding: utf-8 -*-
"""
Pull live VIP stack from 129 → apps/hackrobot/ (no secrets, no node_modules/.next).
Targets:
- vip.hackrobot.cn → apps/hackrobot/vip (/www/wwwroot/nomadvip)
- admin.hackrobot.cn → apps/hackrobot/admin-site
- nomadmini :8010 → apps/hackrobot/nomadmini
- vip-track :4011 → apps/hackrobot/vip-track (optional)
"""
from __future__ import annotations
import os
import tarfile
import tempfile
from pathlib import Path
import paramiko
HOST, USER, PASS = "129.204.21.129", "ubuntu", "Xiao4669805"
ROOT = Path(__file__).resolve().parents[1] # apps/hackrobot
REMOTE_PACK = r"""
set -e
OUT=/tmp/hackrobot_sync_$$
mkdir -p "$OUT"
# VIP Next source (exclude heavy/secrets)
sudo tar -C /www/wwwroot/nomadvip -czf "$OUT/vip-src.tgz" \
--exclude=node_modules --exclude=.next --exclude=.git \
--exclude='.env' --exclude='.env.local' --exclude='.env.*.local' \
app lib public scripts config data docs \
package.json pnpm-lock.yaml pnpm-workspace.yaml \
next.config.ts tsconfig.json postcss.config.mjs eslint.config.mjs \
middleware.ts next-env.d.ts README.md vip.sh .env.example .gitignore 2>/dev/null || true
# env example keys only
python3 - <<'PY'
from pathlib import Path
src=Path('/www/wwwroot/nomadvip/.env.local')
dst=Path('/tmp/hackrobot_sync_envkeys')
if src.exists():
lines=[]
for line in src.read_text('utf-8','ignore').splitlines():
if not line.strip() or line.strip().startswith('#'):
lines.append(line); continue
if '=' in line:
k=line.split('=',1)[0]
lines.append(f'{k}=')
else:
lines.append(line)
Path('/tmp').joinpath('vip.env.example.keys').write_text('\n'.join(lines)+'\n','utf-8')
PY
if [ -f /tmp/vip.env.example.keys ]; then
# fold into pack dir
mkdir -p "$OUT/extra"
cp /tmp/vip.env.example.keys "$OUT/extra/vip.env.keys.example"
fi
# Admin SPA live site
sudo tar -C /www/wwwroot/admin.hackrobot.cn -czf "$OUT/admin-site.tgz" \
--exclude='*.bak*' .
# nomadmini backend (no venv)
if [ -d /opt/nomadmini ]; then
sudo tar -C /opt/nomadmini -czf "$OUT/nomadmini.tgz" \
--exclude='backend/.venv' --exclude='**/__pycache__' --exclude='**/.env' \
--exclude='**/.git' --exclude='node_modules' .
fi
# vip-track
if [ -d /opt/vip-track ]; then
sudo tar -C /opt/vip-track -czf "$OUT/vip-track.tgz" \
--exclude='.venv' --exclude='**/__pycache__' --exclude='.env' --exclude='.git' .
fi
# nginx snippets (reference)
mkdir -p "$OUT/nginx"
sudo cp -a /www/server/panel/vhost/nginx/vip.hackrobot.cn.conf "$OUT/nginx/" 2>/dev/null || true
sudo cp -a /www/server/panel/vhost/nginx/admin.hackrobot.cn.conf "$OUT/nginx/" 2>/dev/null || true
sudo cp -a /www/server/panel/vhost/nginx/extension/vip.hackrobot.cn "$OUT/nginx/ext-vip" 2>/dev/null || true
sudo cp -a /www/server/panel/vhost/nginx/extension/admin.hackrobot.cn "$OUT/nginx/ext-admin" 2>/dev/null || true
sudo tar -C "$OUT/nginx" -czf "$OUT/nginx-ref.tgz" .
# manifest
python3 - <<PY
import json, os, time
from pathlib import Path
out=Path('$OUT')
files={p.name: p.stat().st_size for p in out.glob('*.tgz')}
meta={
'host':'129.204.21.129',
'pulled_at': time.strftime('%Y-%m-%dT%H:%M:%S%z'),
'files': files,
'notes': {
'vip': '/www/wwwroot/nomadvip → next :4007 = vip.hackrobot.cn',
'admin': '/www/wwwroot/admin.hackrobot.cn static SPA',
'nomadmini': '/opt/nomadmini → :8010 live ops',
'vip_track': '/opt/vip-track → :4011',
}
}
(out/'MANIFEST.json').write_text(json.dumps(meta,ensure_ascii=False,indent=2),'utf-8')
print(json.dumps(meta,ensure_ascii=False,indent=2))
PY
# single bundle for scp
sudo tar -C "$OUT" -czf /tmp/hackrobot_sync_bundle.tgz .
sudo chown ubuntu:ubuntu /tmp/hackrobot_sync_bundle.tgz
ls -lah /tmp/hackrobot_sync_bundle.tgz
echo "BUNDLE_OK:/tmp/hackrobot_sync_bundle.tgz"
"""
def extract_into(tgz: Path, dest: Path) -> None:
dest.mkdir(parents=True, exist_ok=True)
with tarfile.open(tgz, "r:gz") as tar:
tar.extractall(dest)
def main() -> None:
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)
print("[remote] packing…")
chan = c.get_transport().open_session()
chan.settimeout(300)
chan.get_pty()
chan.exec_command(REMOTE_PACK)
out = b""
while True:
chunk = chan.recv(65536)
if not chunk:
break
out += chunk
print(chunk.decode("utf-8", "replace"), end="", flush=True)
if b"BUNDLE_OK" not in out:
raise SystemExit("remote pack failed")
local_bundle = ROOT / "deploy" / ".cache" / "hackrobot_sync_bundle.tgz"
local_bundle.parent.mkdir(parents=True, exist_ok=True)
print("[scp] downloading bundle…")
sftp = c.open_sftp()
sftp.get("/tmp/hackrobot_sync_bundle.tgz", str(local_bundle))
sftp.close()
c.close()
print("[local]", local_bundle, local_bundle.stat().st_size)
with tempfile.TemporaryDirectory() as td:
td_path = Path(td)
with tarfile.open(local_bundle, "r:gz") as tar:
tar.extractall(td_path)
mapping = {
"vip-src.tgz": ROOT / "vip",
"admin-site.tgz": ROOT / "admin-site",
"nomadmini.tgz": ROOT / "nomadmini",
"vip-track.tgz": ROOT / "vip-track",
"nginx-ref.tgz": ROOT / "nginx-ref",
}
for name, dest in mapping.items():
src = td_path / name
if not src.exists():
print("[skip]", name)
continue
if dest.exists():
# wipe tracked content carefully: keep .gitkeep only if empty after
for child in dest.iterdir():
if child.name == ".gitkeep":
continue
if child.is_dir():
import shutil
shutil.rmtree(child)
else:
child.unlink()
else:
dest.mkdir(parents=True, exist_ok=True)
extract_into(src, dest)
print("[ok]", name, "→", dest)
# extras
extra = td_path / "extra"
if extra.exists():
(ROOT / "vip").mkdir(exist_ok=True)
for f in extra.iterdir():
target = ROOT / "vip" / f.name
target.write_bytes(f.read_bytes())
print("[extra]", target)
manifest = td_path / "MANIFEST.json"
if manifest.exists():
(ROOT / "SYNC_MANIFEST.json").write_bytes(manifest.read_bytes())
print("[manifest]", ROOT / "SYNC_MANIFEST.json")
print("[done] synced under", ROOT)
if __name__ == "__main__":
main()