A pair of people can have a kitten, a puppy or a lion cub in place of TikTok's streak creature: it grows with the days of the streak (cub, teen, adult, elder), goes grey while the streak is about to burn out, can be dragged in the chat and is also shown on the big streak screen. An animal is given by a link (lihont.space/pet) that the friend accepts. The drawings are made by scripts/make_pet_designs.py and served as strips of frames. Also here: the promo video scripts (make_pet_video.py on top of make_store_video.py), a retry pause for strips that failed to load, stricter checks in the answer to a gift. Work in progress: the gift service is not switched on for everyone yet and there is no public build with the animals. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
140 lines
6.2 KiB
Python
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", "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())
|