#!/usr/bin/env python3 """Install Centrifugo on 82 + nginx /rt/ proxy under nomadro.cn. Idempotent. Uploads local binary tarball if GitHub is unreachable from the server. """ from __future__ import annotations import json import secrets import sys from pathlib import Path import paramiko HOST = "82.157.112.245" USER = "ubuntu" PASS = "Xiao4669805" VERSION = "5.4.9" PORT = 8008 INSTALL_DIR = "/opt/centrifugo" CONF_DIR = "/etc/centrifugo" SECRETS_FILE = f"{CONF_DIR}/nomadro-secrets.json" NGINX_EXT = "/www/server/panel/vhost/nginx/extension/www.nomadro.cn/centrifugo-rt.conf" ENV_HINT = "/etc/nomadro/centrifugo.env" ROOT = Path(__file__).resolve().parents[3] LOCAL_TGZ = ROOT / ".tmp_cf" / "centrifugo.tgz" def ssh_connect() -> paramiko.SSHClient: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( HOST, username=USER, password=PASS, timeout=40, banner_timeout=60, auth_timeout=40, allow_agent=False, look_for_keys=False, ) tr = c.get_transport() if tr: tr.set_keepalive(15) return c def run(c: paramiko.SSHClient, cmd: str, t: int = 180) -> tuple[str, int]: i, o, e = c.exec_command(cmd, timeout=t, get_pty=True) out = o.read().decode("utf-8", "ignore") code = o.channel.recv_exit_status() clean = "\n".join( ln for ln in out.splitlines() if PASS not in ln and "password for" not in ln.lower() ) return clean, code def sudo(c: paramiko.SSHClient, cmd: str, t: int = 180) -> tuple[str, int]: import base64 b64 = base64.b64encode(cmd.encode("utf-8")).decode("ascii") wrapped = f"echo {PASS} | sudo -S bash -lc 'echo {b64} | base64 -d | bash'" return run(c, wrapped, t=t) def main() -> int: if not LOCAL_TGZ.exists(): print("missing local tarball:", LOCAL_TGZ) print("download: curl -L -o .tmp_cf/centrifugo.tgz " f"https://github.com/centrifugal/centrifugo/releases/download/v{VERSION}/centrifugo_{VERSION}_linux_amd64.tar.gz") return 1 c = ssh_connect() sftp = c.open_sftp() print("=== upload binary ===", LOCAL_TGZ.stat().st_size) sftp.put(str(LOCAL_TGZ), "/tmp/centrifugo.tgz") print("=== dirs ===") out, code = sudo( c, f"mkdir -p {INSTALL_DIR} {CONF_DIR} /www/server/panel/vhost/nginx/extension/www.nomadro.cn /etc/nomadro", ) print(out, "code", code) secrets_data = None try: with sftp.file(SECRETS_FILE, "r") as f: secrets_data = json.loads(f.read().decode("utf-8")) print("loaded existing secrets") except Exception: secrets_data = { "token_hmac_secret_key": secrets.token_urlsafe(48), "api_key": secrets.token_urlsafe(32), "admin_password": secrets.token_urlsafe(16), "admin_secret": secrets.token_urlsafe(24), } with sftp.file("/tmp/centrifugo-secrets.json", "w") as f: f.write(json.dumps(secrets_data, indent=2) + "\n") sudo(c, f"install -m 600 /tmp/centrifugo-secrets.json {SECRETS_FILE}") print("generated secrets") token_secret = secrets_data["token_hmac_secret_key"] api_key = secrets_data["api_key"] admin_password = secrets_data["admin_password"] admin_secret = secrets_data["admin_secret"] config = { "token_hmac_secret_key": token_secret, "api_key": api_key, "admin_password": admin_password, "admin_secret": admin_secret, "admin": False, "port": PORT, "address": "127.0.0.1", "allowed_origins": [ "https://nomadro.cn", "https://www.nomadro.cn", "http://localhost:3000", "http://127.0.0.1:3000", ], "namespaces": [ { "name": "social", "allow_subscribe_for_client": True, "allow_publish_for_client": False, "presence": True, } ], } unit = f"""[Unit] Description=Centrifugo realtime for Nomadro social After=network.target [Service] Type=simple ExecStart={INSTALL_DIR}/centrifugo --config={CONF_DIR}/config.json Restart=on-failure RestartSec=3 LimitNOFILE=65535 [Install] WantedBy=multi-user.target """ nginx_rt = f"""# Centrifugo realtime — /rt/ → 127.0.0.1:{PORT} location ^~ /rt/ {{ rewrite ^/rt/(.*)$ /$1 break; proxy_pass http://127.0.0.1:{PORT}; 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 Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 3600s; proxy_send_timeout 3600s; proxy_buffering off; }} """ env_file = f"""CENTRIFUGO_ENABLED=true CENTRIFUGO_API_URL=http://127.0.0.1:{PORT}/api CENTRIFUGO_API_KEY={api_key} CENTRIFUGO_TOKEN_SECRET={token_secret} CENTRIFUGO_WS_URL=wss://nomadro.cn/rt/connection/websocket """ with sftp.file("/tmp/centrifugo-config.json", "w") as f: f.write(json.dumps(config, indent=2) + "\n") with sftp.file("/tmp/centrifugo.service", "w") as f: f.write(unit) with sftp.file("/tmp/centrifugo-rt.conf", "w") as f: f.write(nginx_rt) with sftp.file("/tmp/centrifugo.env", "w") as f: f.write(env_file) sftp.close() print("=== install binary from uploaded tarball ===") out, code = sudo( c, f""" set -e cd /tmp tar -xzf centrifugo.tgz centrifugo install -m 755 centrifugo {INSTALL_DIR}/centrifugo rm -f centrifugo {INSTALL_DIR}/centrifugo version """, ) print(out) if code != 0: print("binary install failed", code) return 1 print("=== install config/service/nginx ===") out, code = sudo( c, f""" set -e install -m 600 /tmp/centrifugo-config.json {CONF_DIR}/config.json install -m 644 /tmp/centrifugo.service /etc/systemd/system/centrifugo.service install -m 644 /tmp/centrifugo-rt.conf {NGINX_EXT} install -m 600 /tmp/centrifugo.env {ENV_HINT} # merge centrifugo env into portal.env for Next rewrites / future API touch /etc/nomadro/portal.env for k in CENTRIFUGO_ENABLED CENTRIFUGO_API_URL CENTRIFUGO_API_KEY CENTRIFUGO_TOKEN_SECRET CENTRIFUGO_WS_URL; do v=$(grep "^$k=" {ENV_HINT} | head -1) if grep -q "^$k=" /etc/nomadro/portal.env; then sed -i "s|^$k=.*|$v|" /etc/nomadro/portal.env else echo "$v" >> /etc/nomadro/portal.env fi done systemctl daemon-reload systemctl enable centrifugo.service systemctl restart centrifugo.service sleep 1 systemctl is-active centrifugo.service ss -lntp | grep ':{PORT}' || true nginx -t nginx -s reload sleep 1 curl -sk -o /dev/null -w 'local %{{http_code}}\\n' http://127.0.0.1:{PORT}/ curl -sk -o /dev/null -w 'rt %{{http_code}}\\n' https://nomadro.cn/rt/ curl -sS -H 'Content-Type: application/json' -H 'X-API-Key: {api_key}' \\ -d '{{"channel":"social:lobby","data":{{"type":"ping","ok":true}}}}' \\ http://127.0.0.1:{PORT}/api/publish echo """, t=120, ) print(out) print("exit", code) print("WS wss://nomadro.cn/rt/connection/websocket") print("ENV", ENV_HINT) c.close() return 0 if code == 0 else 1 if __name__ == "__main__": sys.exit(main())