Files
LihonT/scripts/deploy_members.py
cheb0chik b78266d40c LihonT 3 Luna beta 1: the site look, the floating island, full-screen video and the agent
The "Как сайт" look by default, also in TikTok's settings and all their sub-pages, where every item is its own rounded row.
The bottom bar floats as an island, 9:16 videos reach under it, the seek bar is lifted, thicker and on by default, the
comment input is an island too, and "only sound" downloads are saved as audio. The LihonT agent: a chat that makes cards and
slides for a photo post, looks things up on the web, signs in with Telegram and has a daily limit on the server. Also the
нейронка.рус landing page and the 3D-phone promo scripts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:10:45 +03:00

140 lines
6.2 KiB
Python

"""Swap the LihonT members service (badges, avatar shapes, frames, the community catalog and its moderation bot) on the Helsinki
server and roll it back.
py scripts/deploy_members.py --dry-run compare the live files with the local ones, change nothing
py scripts/deploy_members.py back up, upload, restart lihont-members, roll back on failure
py scripts/deploy_members.py --rollback restore the newest backup (or --stamp <timestamp>)
The python files of services/members are replaced in /opt/lihont-members; the database is never touched (new tables and columns
are created by the service itself when it starts, so an older server.py keeps working on the same file). Every live file that is
replaced is copied to <name>.bak-<timestamp> first, the new ones are compiled on the server before anything goes live, and the
service is asked for its health after the restart; a failed check puts the backups back.
Not done here, by design: the service's environment file (/etc/lihont-members.env: MOD_BOT_TOKEN, MOD_OWNER_ID, GROQ_KEY) and the
nginx rules for uploads are server configuration, set up once by hand.
"""
from __future__ import annotations
import argparse
import hashlib
import shlex
import subprocess
import sys
import time
from pathlib import Path
HOST = "hels"
FOLDER = "/opt/lihont-members"
SERVICE = "lihont-members"
HEALTH = "http://127.0.0.1:18746/members/v1/health"
SOURCE = Path(__file__).resolve().parents[1] / "services" / "members"
# every python file of the service that exists here (the moderation bot is not part of the public source, so it is simply absent there)
FILES = tuple(name for name in ("server.py", "ai.py", "community.py", "moderation.py", "modbot.py", "catalog.py", "report.py", "accounts.py", "authbot.py") if (SOURCE / name).is_file())
SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", HOST]
def remote(command: str, data: bytes | None = None) -> subprocess.CompletedProcess:
return subprocess.run(SSH + [command], input=data, capture_output=True, timeout=120)
def text(result: subprocess.CompletedProcess) -> str:
# ssh prints a post-quantum key exchange warning on stderr; it is not an error.
lines = [line for line in result.stderr.decode("utf-8", "replace").splitlines() if line and not line.startswith("**")]
return "\n".join(lines)
def live_digests() -> dict[str, str]:
"""sha256 of every file on the server, "?" for one that is not there."""
names = " ".join(shlex.quote(FOLDER + "/" + name) for name in FILES)
result = remote("sha256sum %s 2>/dev/null" % names)
found = {}
for line in result.stdout.decode().splitlines():
parts = line.split()
if len(parts) == 2:
found[parts[1].rsplit("/", 1)[-1]] = parts[0]
return {name: found.get(name, "?") for name in FILES}
def healthy() -> bool:
return remote("curl -sf %s" % shlex.quote(HEALTH)).returncode == 0
def deploy(dry_run: bool) -> int:
local = {name: (SOURCE / name).read_bytes() for name in FILES}
live = live_digests()
changed = [name for name in FILES if hashlib.sha256(local[name]).hexdigest() != live[name]]
for name in FILES:
print("%-14s %s" % (name, "changed" if name in changed else "same"))
if dry_run:
print("Dry run: nothing was changed." if changed else "Already deployed.")
return 0
if not changed:
print("The server already runs these files.")
return 0
for name in changed: # compile every new file on the server before anything goes live
result = remote("python3 -c 'import sys; compile(sys.stdin.read(), \"new\", \"exec\")'", local[name])
if result.returncode:
print("%s does not compile on the server, nothing was changed:\n%s" % (name, text(result)))
return 1
stamp = time.strftime("%Y%m%d-%H%M%S")
for name in changed:
result = remote("set -e; cat > /tmp/members-%s.new" % shlex.quote(name), local[name])
if result.returncode:
print("Upload of %s failed, nothing is live yet:\n%s" % (name, text(result)))
return 1
steps = []
for name in changed:
live_path = FOLDER + "/" + name
steps.append("([ -f %s ] && cp -p %s %s.bak-%s || true)" % (shlex.quote(live_path), shlex.quote(live_path), shlex.quote(live_path), stamp))
steps.append("install -m 644 /tmp/members-%s.new %s" % (shlex.quote(name), shlex.quote(live_path)))
steps.append("rm -f /tmp/members-%s.new" % shlex.quote(name))
result = remote("set -e; " + "; ".join(steps))
if result.returncode:
print("Installing failed:\n" + text(result))
return restore(stamp)
print("backups: *.bak-%s" % stamp)
remote("systemctl restart %s" % SERVICE)
time.sleep(2)
if healthy():
print("The service answers; deployed.")
return 0
print("The service did not answer: putting the backups back.")
return restore(stamp)
def restore(stamp: str) -> int:
"""Puts back every file that has a backup with this stamp (files that did not exist before stay; the old server.py ignores them)."""
steps = ["([ -f %s/%s.bak-%s ] && cp -p %s/%s.bak-%s %s/%s || true)" % ((FOLDER, name, stamp) * 2 + (FOLDER, name)) for name in FILES]
result = remote("; ".join(steps) + "; systemctl restart %s" % SERVICE)
if result.returncode:
print("Restoring failed:\n" + text(result))
return 1
time.sleep(2)
ok = healthy()
print("Restored backup %s; the service answers: %s" % (stamp, ok))
return 0 if ok else 1
def rollback(stamp: str | None) -> int:
if not stamp:
listing = remote("ls -1 %s/server.py.bak-2* 2>/dev/null | tail -1" % shlex.quote(FOLDER)).stdout.decode().strip()
if not listing:
print("No dated backup found.")
return 1
stamp = listing.rsplit(".bak-", 1)[-1]
return restore(stamp)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--rollback", action="store_true")
parser.add_argument("--stamp")
args = parser.parse_args()
return rollback(args.stamp) if args.rollback else deploy(args.dry_run)
if __name__ == "__main__":
sys.exit(main())