nomadro/scripts/finish_us_nomadro_com.py
Eric ffa456afdf Ship social join profile + SeaweedFS avatars, notify/coffee, and .com audience stack.
Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 02:25:05 +08:00

534 lines
19 KiB
Python

# -*- coding: utf-8 -*-
"""Finish US nomadro.com deploy after partial portal rsync."""
from __future__ import annotations
import io
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
sys.stderr.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
CN = ("82.157.112.245", "ubuntu", "Xiao4669805")
US = ("108.174.50.68", "root", "Xiao4669805")
def connect(host, user, password):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host, 22, user, password, timeout=60, allow_agent=False, look_for_keys=False, banner_timeout=120)
return c
def run(c, cmd, timeout=600, check=True):
print(f"\n$ {cmd[:220]}", flush=True)
chan = c.get_transport().open_session()
chan.get_pty(width=200, height=50)
chan.settimeout(timeout)
chan.exec_command(cmd)
buf = io.BytesIO()
deadline = time.time() + timeout
last = time.time()
while True:
if chan.recv_ready():
chunk = chan.recv(8192)
if chunk:
buf.write(chunk)
# suppress rsync progress spam — print only every 5s summary lines
text = chunk.decode("utf-8", "replace")
if "rsync" in cmd or "--info=progress2" in cmd:
if time.time() - last > 5:
lines = [ln for ln in text.splitlines() if ln.strip()]
if lines:
print(lines[-1][:180], flush=True)
last = time.time()
else:
sys.stdout.write(text)
sys.stdout.flush()
if chan.recv_stderr_ready():
chunk = chan.recv_stderr(8192)
buf.write(chunk)
sys.stderr.write(chunk.decode("utf-8", "replace"))
sys.stderr.flush()
if chan.exit_status_ready():
while chan.recv_ready():
chunk = chan.recv(8192)
buf.write(chunk)
while chan.recv_stderr_ready():
chunk = chan.recv_stderr(8192)
buf.write(chunk)
break
if time.time() > deadline:
chan.close()
raise TimeoutError(cmd[:160])
time.sleep(0.15)
code = chan.recv_exit_status()
text = buf.getvalue().decode("utf-8", "replace")
# always print last 1.5k of non-rsync or on failure
if check and code != 0:
print(text[-2500:], flush=True)
raise RuntimeError(f"failed ({code}): {cmd[:160]}")
if "--info=progress2" in cmd or "rsync" in cmd:
print(text[-800:], flush=True)
elif text.strip() and len(text) < 4000:
pass # already streamed
return code, text
def put(c, path, content, mode=0o644):
sftp = c.open_sftp()
with sftp.file(path, "w") as f:
f.write(content)
sftp.chmod(path, mode)
sftp.close()
PORTAL_ENV = """NOMADRO_PUBLIC_ORIGIN=https://nomadro.com
CENTRIFUGO_ENABLED=false
API_URL=http://127.0.0.1:8020
"""
API_ENV = """DEBUG=false
WX_ALLOW_DEVTOOLS_LOGIN=true
JWT_SECRET=nomadro-jwt-prod-us-2026
ADMIN_USERNAME=hackrobot
ADMIN_PASSWORD=Xiao4669805@
USE_POCKETBASE=false
PUBLIC_API_BASE=https://api.nomadro.com
ADMIN_ORIGIN=https://admin.nomadro.com
CORS_ORIGINS=https://admin.nomadro.com,https://api.nomadro.com,https://nomadro.com,https://www.nomadro.com
DEFAULT_PRODUCT_ID=ebook_unlock_default
DEFAULT_PRICE_FEN=100
DEFAULT_UNLOCK_PERCENT=30
SQLITE_PATH=/opt/nomadmini/data/nomadmini.db
NTFY_ENABLED=false
WX_PAY_ENV=1
"""
NOMADRO_SERVICE = """[Unit]
Description=Nomadro Next.js App (nomadro.com)
After=network.target
[Service]
EnvironmentFile=-/etc/nomadro/portal.env
Type=simple
WorkingDirectory=/var/www/nomadro.cn
Environment=PORT=4003
Environment=NODE_ENV=production
Environment=HOSTNAME=127.0.0.1
ExecStart=/usr/local/bin/pnpm start
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
"""
API_SERVICE = """[Unit]
Description=Nomadmini FastAPI (api.nomadro.com)
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/nomadmini/backend
EnvironmentFile=/opt/nomadmini/backend/.env
Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db
Environment=COMMUNITY_STORE_PATH=/var/www/nomadro-data/community/community_store.json
ExecStart=/opt/nomadmini/backend/.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8010
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
"""
SOCIAL_SERVICE = """[Unit]
Description=Nomadro social API (isolated)
After=network.target
[Service]
Type=simple
WorkingDirectory=/var/www/nomadro.cn/apps/api
Environment=HOST=127.0.0.1
Environment=PORT=8020
Environment=SOCIAL_ENABLED=true
Environment=SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db
Environment=PYTHONPATH=/var/www/nomadro.cn/apps/api:/var/www/nomadro.cn/apps/api/services
ExecStart=/var/www/nomadro.cn/apps/api/.venv-social/bin/python -m uvicorn social_main:app --host 127.0.0.1 --port 8020
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
"""
NGINX_HTTP = r"""
server {
listen 80;
listen [::]:80;
server_name nomadro.com www.nomadro.com;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; default_type text/plain; allow all; }
location = /api/config {
proxy_pass http://127.0.0.1:8010;
proxy_set_header Host api.nomadro.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /api/config/meta {
proxy_pass http://127.0.0.1:8010;
proxy_set_header Host api.nomadro.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location ^~ /api/social/ {
proxy_pass http://127.0.0.1:8020;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Social-Guest-Id $http_x_social_guest_id;
}
location / {
proxy_pass http://127.0.0.1:4003;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
listen [::]:80;
server_name api.nomadro.com;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; default_type text/plain; allow all; }
location / {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 80;
listen [::]:80;
server_name admin.nomadro.com;
root /www/wwwroot/admin.nomadro.com;
index index.html;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; default_type text/plain; allow all; }
location /api/ {
proxy_pass http://127.0.0.1:8010/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /health { proxy_pass http://127.0.0.1:8010/health; }
location / { try_files $uri $uri/ /index.html; }
}
"""
NGINX_PORTAL = r"""
server {
listen 80;
listen [::]:80;
server_name nomadro.com www.nomadro.com;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; default_type text/plain; allow all; }
location / { return 301 https://$host$request_uri; }
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name nomadro.com www.nomadro.com;
ssl_certificate /etc/letsencrypt/live/nomadro.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/nomadro.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
client_max_body_size 32m;
location = /api/config {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host api.nomadro.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
add_header Cache-Control "no-store";
}
location = /api/config/meta {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host api.nomadro.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
add_header Cache-Control "no-store";
}
location ^~ /api/social/ {
proxy_pass http://127.0.0.1:8020;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Social-Guest-Id $http_x_social_guest_id;
}
location = /favicon.ico { alias /var/www/nomadro.cn/public/favicon.ico; access_log off; }
location = /favicon.svg { alias /var/www/nomadro.cn/public/favicon.svg; access_log off; }
location / {
proxy_pass http://127.0.0.1:4003;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
}
}
"""
NGINX_API = r"""
server {
listen 80;
listen [::]:80;
server_name api.nomadro.com;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; default_type text/plain; allow all; }
location / { return 301 https://$host$request_uri; }
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name api.nomadro.com;
client_max_body_size 32m;
ssl_certificate /etc/letsencrypt/live/api.nomadro.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.nomadro.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location /api/config/ws {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_buffering off;
}
location / {
proxy_pass http://127.0.0.1:8010;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
}
}
"""
NGINX_ADMIN = r"""
server {
listen 80;
listen [::]:80;
server_name admin.nomadro.com;
location ^~ /.well-known/acme-challenge/ { root /var/www/acme; default_type text/plain; allow all; }
location / { return 301 https://$host$request_uri; }
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name admin.nomadro.com;
root /www/wwwroot/admin.nomadro.com;
index index.html;
client_max_body_size 20m;
ssl_certificate /etc/letsencrypt/live/admin.nomadro.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/admin.nomadro.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location /api/ {
proxy_pass http://127.0.0.1:8010/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /health { proxy_pass http://127.0.0.1:8010/health; proxy_set_header Host $host; }
location /assets/ { try_files $uri =404; expires 30d; add_header Cache-Control "public, immutable"; }
location / { try_files $uri $uri/ /index.html; }
}
"""
def main():
print("=== connect ===", flush=True)
cn = connect(*CN)
us = connect(*US)
# ensure key still works
run(cn, "ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new root@108.174.50.68 'echo ok'", timeout=30)
print("=== verify/repair portal sync (quiet, no --delete) ===", flush=True)
# Complete any missing portal files without deleting; exclude miniprogram to speed up
run(
cn,
"rsync -aH --info=stats2 "
"--exclude node_modules/.cache --exclude .git --exclude apps/miniprogram "
"--exclude '**/.tmp*' --exclude '*.log' "
"--exclude apps/api/.venv --exclude apps/api/.venv-social "
"/var/www/nomadro.cn/ root@108.174.50.68:/var/www/nomadro.cn/",
timeout=3600,
)
print("=== sync API backend (no venv) ===", flush=True)
run(
cn,
"rsync -aH --info=stats2 --delete "
"--exclude .venv --exclude '__pycache__' --exclude '*.pyc' --exclude data "
"/opt/nomadmini/backend/ root@108.174.50.68:/opt/nomadmini/backend/ && "
"ssh root@108.174.50.68 'mkdir -p /opt/nomadmini/data /var/www/nomadro-data/social /var/www/nomadro-data/community' && "
"(test -f /opt/nomadmini/data/nomadmini.db && rsync -aH /opt/nomadmini/data/nomadmini.db root@108.174.50.68:/opt/nomadmini/data/nomadmini.db || true) && "
"(test -f /var/www/nomadro-data/social/social.db && rsync -aH /var/www/nomadro-data/social/social.db root@108.174.50.68:/var/www/nomadro-data/social/social.db || true) && "
"(test -f /var/www/nomadro-data/community/community_store.json && rsync -aH /var/www/nomadro-data/community/community_store.json root@108.174.50.68:/var/www/nomadro-data/community/community_store.json || true) && "
"echo API_OK",
timeout=600,
)
print("=== sync admin SPA ===", flush=True)
run(
cn,
"rsync -aH --info=stats2 --delete /www/wwwroot/admin.nomadro.cn/ root@108.174.50.68:/www/wwwroot/admin.nomadro.com/ && echo ADMIN_OK",
timeout=180,
)
print("=== envs + systemd ===", flush=True)
run(us, "mkdir -p /etc/nomadro /var/www/acme /etc/nginx/sites-available /etc/nginx/sites-enabled")
put(us, "/etc/nomadro/portal.env", PORTAL_ENV)
put(us, "/opt/nomadmini/backend/.env", API_ENV, 0o600)
put(us, "/etc/systemd/system/nomadro.service", NOMADRO_SERVICE)
put(us, "/etc/systemd/system/nomadmini-api.service", API_SERVICE)
put(us, "/etc/systemd/system/nomadro-social.service", SOCIAL_SERVICE)
# ensure nginx includes sites-enabled
run(
us,
"grep -q 'sites-enabled' /etc/nginx/nginx.conf || "
"sed -i '/include \\/etc\\/nginx\\/conf.d\\/\\*\\.conf;/a\\ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf",
)
print("=== python venvs ===", flush=True)
run(
us,
r"""
set -euo pipefail
cd /opt/nomadmini/backend
python3 -m venv .venv
.venv/bin/pip -q install -U pip wheel
.venv/bin/pip -q install -r requirements.txt
.venv/bin/pip -q install 'uvicorn[standard]' fastapi || true
cd /var/www/nomadro.cn/apps/api
python3 -m venv .venv-social
.venv-social/bin/pip -q install -U pip wheel
if [ -f requirements.txt ]; then .venv-social/bin/pip -q install -r requirements.txt; fi
.venv-social/bin/pip -q install 'uvicorn[standard]' fastapi pydantic pydantic-settings httpx aiosqlite python-multipart || true
echo VENV_OK
ls -la /opt/nomadmini/backend/app/main.py /var/www/nomadro.cn/apps/api/social_main.py /var/www/nomadro.cn/package.json
du -sh /var/www/nomadro.cn /var/www/nomadro.cn/node_modules /opt/nomadmini/backend /www/wwwroot/admin.nomadro.com
""",
timeout=900,
)
print("=== start services ===", flush=True)
run(
us,
"systemctl daemon-reload && "
"systemctl enable nomadro nomadmini-api nomadro-social && "
"systemctl restart nomadmini-api nomadro-social nomadro",
timeout=90,
)
time.sleep(5)
run(us, "systemctl --no-pager -l status nomadmini-api nomadro-social nomadro | head -60", check=False)
run(us, "ss -lntp | grep -E '4003|8010|8020' || true", check=False)
print("=== nginx HTTP + certbot ===", flush=True)
put(us, "/etc/nginx/sites-available/nomadro-http.conf", NGINX_HTTP)
run(
us,
"ln -sfn /etc/nginx/sites-available/nomadro-http.conf /etc/nginx/sites-enabled/nomadro-http.conf && "
"nginx -t && systemctl reload nginx",
)
run(
us,
r"""
set -euo pipefail
mkdir -p /var/www/acme
certbot certonly --webroot -w /var/www/acme -d nomadro.com -d www.nomadro.com \
--non-interactive --agree-tos --email admin@nomadro.com --keep-until-expiring
certbot certonly --webroot -w /var/www/acme -d api.nomadro.com \
--non-interactive --agree-tos --email admin@nomadro.com --keep-until-expiring
certbot certonly --webroot -w /var/www/acme -d admin.nomadro.com \
--non-interactive --agree-tos --email admin@nomadro.com --keep-until-expiring
ls /etc/letsencrypt/live/
""",
timeout=300,
check=False,
)
_c, out = run(
us,
"test -f /etc/letsencrypt/live/nomadro.com/fullchain.pem && "
"test -f /etc/letsencrypt/live/api.nomadro.com/fullchain.pem && "
"test -f /etc/letsencrypt/live/admin.nomadro.com/fullchain.pem && echo CERTS_OK || echo CERTS_MISSING",
check=False,
)[:2]
if "CERTS_OK" in out:
put(us, "/etc/nginx/sites-available/nomadro.com.conf", NGINX_PORTAL)
put(us, "/etc/nginx/sites-available/api.nomadro.com.conf", NGINX_API)
put(us, "/etc/nginx/sites-available/admin.nomadro.com.conf", NGINX_ADMIN)
run(
us,
"rm -f /etc/nginx/sites-enabled/nomadro-http.conf && "
"ln -sfn /etc/nginx/sites-available/nomadro.com.conf /etc/nginx/sites-enabled/nomadro.com.conf && "
"ln -sfn /etc/nginx/sites-available/api.nomadro.com.conf /etc/nginx/sites-enabled/api.nomadro.com.conf && "
"ln -sfn /etc/nginx/sites-available/admin.nomadro.com.conf /etc/nginx/sites-enabled/admin.nomadro.com.conf && "
"nginx -t && systemctl reload nginx && echo TLS_NGINX_OK",
)
else:
print("WARN certs missing, HTTP-only for now", flush=True)
print("=== smoke ===", flush=True)
run(
us,
r"""
set +e
ss -lntp | grep -E ':80|:443|:4003|:8010|:8020'
curl -sS -o /dev/null -w 'local_portal:%{http_code}\n' http://127.0.0.1:4003/
curl -sS -o /dev/null -w 'local_api:%{http_code}\n' http://127.0.0.1:8010/health
curl -sS -o /dev/null -w 'local_social:%{http_code}\n' http://127.0.0.1:8020/docs
curl -sS -o /dev/null -w 'public_portal:%{http_code}\n' https://nomadro.com/
curl -sS -o /dev/null -w 'public_api:%{http_code}\n' https://api.nomadro.com/health
curl -sS -o /dev/null -w 'public_admin:%{http_code}\n' https://admin.nomadro.com/
systemctl is-active nomadro nomadmini-api nomadro-social nginx
""",
timeout=90,
check=False,
)
cn.close()
us.close()
print("=== DONE ===", flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())