Repositories | Polyback | Log in to see private repositories


polyback-website / fe552ae720b75aa69ca0c73f420ab929961b458d / container/deploy/deployd.py

28,346 bytes | parent directory

#!/usr/bin/env python3
"""Polyback deploy daemon: puts staged builds live when /admin/deploy-updates asks for it.

Runs as root (started by /srv/polygon/start.sh), because deploying writes root-owned files and
restarts services. It only knows a fixed set of actions: "deploy" or "rollback" of one of the four
programs. A request (a DeployActions row) is a program name, an action and a build number; no
command, path or URL from the database is ever run or used. File names, versions and checksums
recorded by the build runner are checked, and each build is copied into the root-owned
<deploy_root>/releases/<program>/<build id>/ before use, so it can't change underneath us. Rollbacks
use that copy too.

The code being deployed is trusted, of course: the website's nginx.conf and the game server
manager run as root on this server.
"""

import hashlib
import json
import os
import pwd
import shutil
import signal
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.request

from common import DB, FILE_RE, LogBuffer, PROGRAMS, VERSION_RE, load_conf, log, sha256_file

CONF = load_conf()
ROOT = CONF["deploy_root"]
ARTIFACTS = os.path.join(ROOT, "artifacts")
RELEASES = os.path.join(ROOT, "releases")
KEEP_RELEASES = int(CONF.get("keep_releases", 5))

WEBROOT = "/var/www/polygon"
NGINX_CONF = "/etc/nginx/nginx.conf"
SITE_LOCAL = "http://127.0.0.1:8080"
DB_ENV = "/srv/polygon/runtime/db.env"
CLIENTS = "/var/www/polygonshared/assets/clients"
ENGINES = "/srv/polygon/runtime/gameserver-engine"
MANAGER = "/srv/polygon/polygon-gameserver/polygon-gameserver"
MANAGER_RUNNING = "/srv/polygon/runtime/gameserver-work/running.json"
START = "/srv/polygon/start.sh"

# never copied to the web root, and never deleted from it
RSYNC_EXCLUDES = [
    "/.git",
    "/container/",
    "/Containerfile",
    "/nginx.conf",
    "/api/private/ErrorLog.json",
    "/api/private/config.php",
    "/thumbs/assets/",
    "/thumbs/avatars/",
    "/asset/files/",
]
SCHEMA_FILES = ["container/db/schema.sql", "container/db/forums.sql"]

# what a build of each program must contain, and the only file names accepted for it
# ({v}: the build's version)
PLATFORMS = {
    "website": {"site": "website-{v}.tar.gz"},
    "gameserver": {"linux-x86_64-musl": "polygon-gameserver"},
    "engine": {"linux-x86_64-musl": "polyback-{v}-linux-x86_64-musl.tar.gz", "windows-x86_64": "polyback-{v}-windows-x86_64.zip"},
    "bootstrapper": {"linux-x86_64": "polyback-player", "windows-x86_64": "polyback-player.exe"},
}

CHILD_ENV = {"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8", "HOME": "/root"}


class DeployError(Exception):
    pass


def exe_of(pid):
    try:
        return os.readlink(f"/proc/{pid}/exe").removesuffix(" (deleted)")
    except OSError:
        return ""


def pids():
    return [int(p) for p in os.listdir("/proc") if p.isdigit()]


def replace_file(src, dst, mode, owner=None):
    """Copy src over dst in one step (a reader sees the old or the new file, never half)."""
    tmp = dst + ".deploying"
    if os.path.lexists(tmp):
        os.unlink(tmp)
    shutil.copyfile(src, tmp)
    os.chmod(tmp, mode)
    if owner:
        shutil.chown(tmp, owner, owner)
    os.replace(tmp, dst)


class Deploy:
    def __init__(self, db, action):
        self.db, self.action, self.program = db, action, action["Program"]
        self.buf = LogBuffer(lambda text: db.run("UPDATE DeployActions SET Log = %s WHERE ID = %s", (text, action["ID"])))

    def log(self, line):
        self.buf.add(line)

    def run(self, cmd, **kw):
        self.log("$ " + " ".join(cmd))
        p = subprocess.run(cmd, env=CHILD_ENV, stdin=kw.pop("stdin", subprocess.DEVNULL), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=600, **kw)
        out = p.stdout.decode(errors="replace").strip()
        if out:
            for line in out.splitlines()[-40:]:
                self.log("  " + line)
        if p.returncode != 0:
            raise DeployError(f"{cmd[0]} exited with status {p.returncode}")

    # ---------- which build, and our own copy of it ----------

    def state(self):
        return self.db.one("SELECT * FROM DeployState WHERE Program = %s", (self.program,))

    def release_dir(self, build_id):
        return os.path.join(RELEASES, self.program, str(int(build_id)))

    def load_release(self, build_id):
        with open(os.path.join(self.release_dir(build_id), "release.json")) as f:
            return json.load(f)

    def import_build(self, build_id):
        """Copy a finished build from the runner's folder into our own, checking everything."""
        if os.path.exists(os.path.join(self.release_dir(build_id), "release.json")):
            return self.load_release(build_id)
        row = self.db.one("SELECT * FROM DeployBuilds WHERE ID = %s", (build_id,))
        if not row or row["Program"] != self.program or row["Status"] != "success":
            raise DeployError("that isn't a finished build of this program")
        if not row["Artifacts"]:
            raise DeployError("that build's files have been cleaned up: build it again")
        version = row["Version"] or ""
        if not VERSION_RE.match(version):
            raise DeployError("the build has an invalid version")
        artifacts = json.loads(row["Artifacts"])
        dst = self.release_dir(build_id)
        tmp = dst + ".new"
        shutil.rmtree(tmp, ignore_errors=True)
        os.makedirs(tmp, mode=0o700)
        builder = pwd.getpwnam("polybuild").pw_uid
        files = {}
        for platform, pattern in PLATFORMS[self.program].items():
            name = pattern.format(v=version)
            a = artifacts.get(platform) or {}
            if a.get("file") != name or not FILE_RE.match(name):
                raise DeployError(f"the build has no {platform} file")
            fd = os.open(os.path.join(ARTIFACTS, str(int(build_id)), name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
            with os.fdopen(fd, "rb") as src:
                st = os.fstat(src.fileno())
                if not stat.S_ISREG(st.st_mode) or st.st_uid != builder:
                    raise DeployError(f"{name} isn't the build runner's file")
                with open(os.path.join(tmp, name), "wb") as out:
                    shutil.copyfileobj(src, out, 1 << 20)
            sha = sha256_file(os.path.join(tmp, name))
            if sha != a.get("sha256"):
                raise DeployError(f"{name} doesn't match the checksum recorded when it was built")
            files[platform] = {"file": name, "size": os.path.getsize(os.path.join(tmp, name)), "sha256": sha}
        self.write_release(tmp, version, files)
        os.rename(tmp, dst)
        self.log(f"build #{build_id} ({version}) checked and copied to {dst}")
        return self.load_release(build_id)

    def write_release(self, folder, version, files):
        with open(os.path.join(folder, "release.json"), "w") as f:
            json.dump({"version": version, "files": files}, f, indent=1)

    def snapshot_live(self):
        """First deploy of a program: keep what is live now as a build, so it can be rolled back to."""
        found = getattr(self, "live_" + self.program)()
        if not found:
            self.log("nothing live to keep for a rollback")
            return None, None
        version, sources = found  # platform -> existing file, or a function writing one
        cur = self.db.run(
            "INSERT INTO DeployBuilds (Program, Status, RequestedBy, TimeRequested, TimeStarted, TimeFinished, GitURL, Branch, CommitMessage, Version, Log) "
            "VALUES (%s, 'success', %s, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '', '', %s, %s, %s)",
            (self.program, self.action["RequestedBy"], "What was live before the first deploy from this page", version, "Copied from the live server by the deploy daemon.\n"),
        )
        build_id = cur.lastrowid
        dst = self.release_dir(build_id)
        os.makedirs(dst, mode=0o700)
        files = {}
        for platform, source in sources.items():
            name = PLATFORMS[self.program][platform].format(v=version)
            path = os.path.join(dst, name)
            source(path) if callable(source) else shutil.copyfile(source, path)
            files[platform] = {"file": name, "size": os.path.getsize(path), "sha256": sha256_file(path)}
        self.write_release(dst, version, files)
        self.db.run(
            "UPDATE DeployBuilds SET Artifacts = %s, ArtifactBytes = %s WHERE ID = %s",
            (json.dumps(files), sum(f["size"] for f in files.values()), build_id),
        )
        self.log(f"kept what is live now as build #{build_id} ({version})")
        return build_id, version

    def prune_releases(self, keep):
        folder = os.path.join(RELEASES, self.program)
        ids = sorted((int(d) for d in os.listdir(folder) if d.isdigit()), reverse=True)
        for i in ids[KEEP_RELEASES:]:
            if i not in keep:
                shutil.rmtree(os.path.join(folder, str(i)), ignore_errors=True)

    # ---------- the request ----------

    def execute(self):
        state = self.state() or {}
        current, previous = state.get("CurrentBuildID"), state.get("PreviousBuildID")
        current_version = state.get("CurrentVersion")
        if self.action["Action"] == "rollback":
            if not previous:
                raise DeployError("there is no previous version to go back to")
            target = previous
        elif self.action["Action"] == "deploy":
            target = self.action["BuildID"]
            if not target:
                raise DeployError("no build given")
        else:
            raise DeployError("unknown action")
        release = self.import_build(target)
        if current is None:
            current, current_version = self.snapshot_live()
        self.log(f"deploying {self.program} {release['version']} (build #{target})")
        fallback = self.load_release(current) if current and current != target else None
        getattr(self, "deploy_" + self.program)(self.release_dir(target), release, fallback and (self.release_dir(current), fallback))
        if current == target:  # deployed again
            current, current_version = previous, state.get("PreviousVersion")
        self.db.run(
            "REPLACE INTO DeployState (Program, CurrentBuildID, CurrentVersion, PreviousBuildID, PreviousVersion, Updated) VALUES (%s, %s, %s, %s, %s, UNIX_TIMESTAMP())",
            (self.program, target, release["version"], current, current_version),
        )
        self.prune_releases({target, current})

    # ---------- website ----------

    def live_website(self):
        def pack(path):
            cmd = ["tar", "-czf", path, "-C", WEBROOT] + [f"--exclude=.{e.rstrip('/')}" for e in RSYNC_EXCLUDES if e != "/nginx.conf"] + ["."]
            # the same layout as a build: the nginx config goes back under container/
            with tempfile.TemporaryDirectory(dir=RELEASES) as tmp:
                subprocess.run(cmd, check=True, env=CHILD_ENV)
                with tarfile.open(path) as t:
                    t.extractall(tmp, filter="data")
                os.makedirs(os.path.join(tmp, "container"), exist_ok=True)
                shutil.copyfile(NGINX_CONF, os.path.join(tmp, "container", "nginx.conf"))
                subprocess.run(["tar", "-czf", path, "-C", tmp, "."], check=True, env=CHILD_ENV)

        return "before-" + time.strftime("%Y.%m%d.%H%M", time.gmtime()), {"site": pack}

    def deploy_website(self, folder, release, fallback):
        with tempfile.TemporaryDirectory(dir=RELEASES) as tmp:
            os.chmod(tmp, 0o755)
            self.unpack_site(folder, release, tmp)
            self.apply_schema(tmp)
            self.install_site(tmp)
        problem = self.check_site()
        if problem:
            self.log(f"the site doesn't work after the update: {problem}")
            if not fallback:
                raise DeployError("the site is broken and there is nothing to go back to")
            self.log(f"putting {fallback[1]['version']} back")
            with tempfile.TemporaryDirectory(dir=RELEASES) as tmp:
                os.chmod(tmp, 0o755)
                self.unpack_site(fallback[0], fallback[1], tmp)
                self.install_site(tmp)
            raise DeployError("the update was undone (schema changes stay): " + (self.check_site() or "the previous version works again"))
        self.log("the site answers normally")

    def unpack_site(self, folder, release, tree):
        with tarfile.open(os.path.join(folder, release["files"]["site"]["file"])) as t:
            t.extractall(tree, filter="data")  # refuses paths, links and devices outside the tree
        if not os.path.isfile(os.path.join(tree, "api/private/core.php")):
            raise DeployError("that build isn't the website (no api/private/core.php)")

    def apply_schema(self, tree):
        """Run what the schema files gained since the last deploy (or all of one whose earlier
        part changed: every statement in them can run again). As the site's own DB user."""
        for name in SCHEMA_FILES:
            path = os.path.join(tree, name)
            if not os.path.isfile(path):
                self.log(f"{name}: not in this build, skipped")
                continue
            with open(path, "rb") as f:
                data = f.read()
            row = self.db.one("SELECT * FROM SchemaApplied WHERE File = %s", (name,))
            digest = hashlib.sha256(data).hexdigest()
            if row and row["SHA256"] == digest:
                self.log(f"{name}: no changes")
                continue
            if row and len(data) < row["Bytes"]:
                self.log(f"{name}: shorter than what was already applied (an older version), skipped")
                continue
            if row and hashlib.sha256(data[: row["Bytes"]]).hexdigest() == row["SHA256"]:
                sql = data[row["Bytes"] :]
                self.log(f"{name}: applying {len(sql)} new bytes")
            else:
                sql = data
                self.log(f"{name}: applying the whole file" + (" (earlier parts changed)" if row else ""))
            self.run_sql(b"SET NAMES utf8mb4;\n" + sql)
            self.db.run("REPLACE INTO SchemaApplied (File, Bytes, SHA256, Applied) VALUES (%s, %s, %s, UNIX_TIMESTAMP())", (name, len(data), digest))

    def run_sql(self, sql):
        env = {}
        with open(DB_ENV) as f:
            for line in f:
                k, _, v = line.strip().partition("=")
                env[k] = v.strip("'\"")
        # the password goes to the client in a private file, not on a command line or in the log
        with tempfile.NamedTemporaryFile("w", dir=ROOT, prefix=".db-", suffix=".cnf") as cnf:  # mode 600
            quoted = env["MARIADB_PASSWORD"].replace("\\", "\\\\").replace('"', '\\"')
            cnf.write(f'[client]\nuser="{env["MARIADB_USER"]}"\npassword="{quoted}"\nsocket="{CONF["db_socket"]}"\n')
            cnf.flush()
            p = subprocess.run(
                ["mariadb", f"--defaults-file={cnf.name}", "--batch", "--sandbox", env["MARIADB_DATABASE"]],
                input=sql, env=CHILD_ENV, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=1800,
            )
        if p.returncode != 0:
            raise DeployError("a schema statement failed (the site's files weren't changed): " + p.stdout.decode(errors="replace").strip()[-800:])

    def install_site(self, tree):
        new_conf = os.path.join(tree, "container/nginx.conf")
        nginx_changed = False
        if os.path.isfile(new_conf):
            with open(new_conf, "rb") as a, open(NGINX_CONF, "rb") as b:
                nginx_changed = a.read() != b.read()
        if nginx_changed:
            candidate = NGINX_CONF + ".deploying"
            shutil.copyfile(new_conf, candidate)
            try:
                self.run(["nginx", "-t", "-q", "-c", candidate])
            except DeployError:
                os.unlink(candidate)
                raise DeployError("the new nginx configuration is invalid (the site's files weren't changed)")
        cmd = ["rsync", "-rlpt", "--checksum", "--delete", "--delay-updates", "--chown=root:root"]
        self.run(cmd + [f"--exclude={e}" for e in RSYNC_EXCLUDES] + ["--out-format=%o %n", tree + "/", WEBROOT + "/"])
        error_log = os.path.join(WEBROOT, "api/private/ErrorLog.json")
        if not os.path.exists(error_log):
            with open(error_log, "w") as f:
                f.write("[]\n")
        shutil.chown(error_log, "www-data", "www-data")
        self.run(["chown", "-R", "www-data:www-data", os.path.join(WEBROOT, "thumbs")])
        if nginx_changed:
            shutil.copyfile(NGINX_CONF, os.path.join(ROOT, "nginx.conf.previous"))
            os.replace(candidate, NGINX_CONF)
            self.run(["nginx", "-s", "reload"])
        # PHP needs no restart: the opcode cache checks file times every 2 s

    def check_site(self):
        """None, or what is wrong with the site."""
        problem = "no answer"
        for _ in range(10):
            time.sleep(1)
            problem = None
            for path in ("/", "/login", "/api/client/latest"):
                try:
                    with urllib.request.urlopen(SITE_LOCAL + path, timeout=20) as r:
                        body = r.read()
                        if not body:
                            problem = f"{path} is empty"
                except urllib.error.HTTPError as e:
                    if e.code >= 500:
                        problem = f"{path} answers {e.code}"
                except OSError as e:
                    problem = f"{path}: {e}"
                if problem:
                    break
            if problem is None:
                return None
        return problem

    # ---------- game server manager ----------

    def live_gameserver(self):
        if not os.path.isfile(MANAGER):
            return None
        return "before-" + time.strftime("%Y.%m%d.%H%M", time.gmtime()), {"linux-x86_64-musl": MANAGER}

    def deploy_gameserver(self, folder, release, fallback):
        self.note_games()
        if self.swap_manager(os.path.join(folder, release["files"]["linux-x86_64-musl"]["file"])):
            return
        if not fallback:
            raise DeployError("the new manager doesn't stay up and there is nothing to go back to")
        self.log(f"the new manager doesn't stay up: putting {fallback[1]['version']} back")
        ok = self.swap_manager(os.path.join(fallback[0], fallback[1]["files"]["linux-x86_64-musl"]["file"]))
        raise DeployError("the update was undone; the previous manager " + ("runs again" if ok else "doesn't start either: see /var/log/polyback/gameserver.log"))

    def note_games(self):
        """Say what happens to the games running now."""
        games = [p for p in pids() if exe_of(p).startswith(ENGINES + "/") and os.path.basename(exe_of(p)) == "polyback"]
        try:
            with open(MANAGER_RUNNING) as f:
                known = {j["pid"] for j in json.load(f)}
        except (OSError, ValueError, KeyError, TypeError):
            known = set()
        kept = [p for p in games if p in known]
        if kept:
            self.log(f"{len(kept)} running game(s) keep running: the new manager takes them over")
        if len(games) > len(kept):
            self.log(f"{len(games) - len(kept)} running game(s) were started by a manager without handover and will end")

    def manager_pids(self):
        return [p for p in pids() if exe_of(p) == MANAGER]

    def swap_manager(self, binary):
        replace_file(binary, MANAGER, 0o755)
        old = [p for p in pids() if exe_of(p) in (MANAGER, MANAGER + ".deploying")]
        for pid in old:
            os.kill(pid, signal.SIGTERM)
        for _ in range(100):
            if not any(os.path.exists(f"/proc/{p}/exe") and exe_of(p) for p in old):
                break
            time.sleep(0.1)
        else:
            for pid in old:
                try:
                    os.kill(pid, signal.SIGKILL)
                except ProcessLookupError:
                    pass
        self.log("old manager stopped; starting the new one")
        # its own session: nothing that happens to this daemon reaches the manager
        subprocess.run(["/bin/sh", START], env=CHILD_ENV, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, timeout=120)
        time.sleep(4)
        first = self.manager_pids()
        time.sleep(3)
        if first and self.manager_pids() == first:
            self.log(f"the manager runs (pid {first[0]})")
            return True
        return False

    # ---------- players' files ----------

    def read_manifest(self):
        path = os.path.join(CLIENTS, "manifest.json")
        if not os.path.exists(path):
            return {}
        with open(path) as f:
            return json.load(f)  # a broken manifest stops the deploy instead of being replaced

    def write_manifest(self, m):
        path = os.path.join(CLIENTS, "manifest.json")
        tmp = path + ".deploying"
        with open(tmp, "w") as f:
            json.dump(m, f, indent=1)
        os.chmod(tmp, 0o644)
        shutil.chown(tmp, "www-data", "www-data")
        os.replace(tmp, path)
        self.log("manifest updated: " + json.dumps(m))

    def client_file(self, url):
        """The file behind a /client-releases/ URL of the manifest."""
        path = os.path.realpath(os.path.join(CLIENTS, url.removeprefix("/client-releases/")))
        if not path.startswith(os.path.realpath(CLIENTS) + "/") or not os.path.isfile(path):
            raise DeployError(f"the live manifest names a missing file: {url}")
        return path

    # ---------- engine ----------

    def live_engine(self):
        m = self.read_manifest()
        builds = m.get("builds") or {}
        if not VERSION_RE.match(m.get("version", "")) or "linux-x86_64-musl" not in builds:
            return None
        return m["version"], {p: self.client_file(builds[p]["url"]) for p in PLATFORMS["engine"] if p in builds}

    def deploy_engine(self, folder, release, fallback):
        version, files = release["version"], release["files"]
        # the game servers' copy first, checked before anything points at it
        target = os.path.join(ENGINES, version)
        if not os.path.isfile(os.path.join(target, "polyback")):
            tmp = target + ".deploying"
            shutil.rmtree(tmp, ignore_errors=True)
            os.makedirs(tmp, mode=0o755)
            with tarfile.open(os.path.join(folder, files["linux-x86_64-musl"]["file"])) as t:
                t.extractall(tmp, filter="data")
            os.chmod(os.path.join(tmp, "polyback"), 0o755)
            out = subprocess.run([os.path.join(tmp, "polyback"), "--version"], env=CHILD_ENV, stdin=subprocess.DEVNULL, capture_output=True, timeout=60, cwd="/")
            if out.returncode != 0 or out.stdout.decode(errors="replace").strip() != version:
                shutil.rmtree(tmp, ignore_errors=True)
                raise DeployError("the engine doesn't report its version on this server")
            os.rename(tmp, target)
        os.makedirs(CLIENTS, exist_ok=True)
        builds = {}
        for platform, f in files.items():
            replace_file(os.path.join(folder, f["file"]), os.path.join(CLIENTS, f["file"]), 0o644, "www-data")
            builds[platform] = {
                "url": "/client-releases/" + f["file"],
                "sha256": f["sha256"],
                "size": f["size"],
                "archive": "zip" if f["file"].endswith(".zip") else "tar.gz",
            }
        # servers and players must switch together (players only join servers of their version)
        link = os.path.join(ENGINES, "current.deploying")
        if os.path.lexists(link):
            os.unlink(link)
        os.symlink(version, link)
        m = self.read_manifest()
        m["version"], m["builds"] = version, builds  # other keys (the bootstrapper) stay
        os.replace(link, os.path.join(ENGINES, "current"))
        self.write_manifest(m)
        self.log(f"new games start on {version} ({ENGINES}/current)")
        self.prune_engines({version, fallback[1]["version"] if fallback else version})

    def prune_engines(self, keep):
        dirs = sorted(d for d in os.listdir(ENGINES) if d.startswith("20") and not os.path.islink(os.path.join(ENGINES, d)))
        in_use = {exe_of(p) for p in pids()}
        for d in dirs[:-4]:
            path = os.path.join(ENGINES, d)
            if d in keep or any(e.startswith(path + "/") for e in in_use):
                continue
            shutil.rmtree(path, ignore_errors=True)
            self.log(f"removed old engine {d} (no game uses it)")

    # ---------- bootstrapper ----------

    def live_bootstrapper(self):
        entries = self.read_manifest().get("bootstrapper") or {}
        found = {p: self.client_file(entries[p]["url"]) for p in PLATFORMS["bootstrapper"] if p in entries}
        version = entries.get("linux-x86_64", {}).get("version", "")
        return (version, found) if found and VERSION_RE.match(version) else None

    def deploy_bootstrapper(self, folder, release, fallback):
        version, files = release["version"], release["files"]
        dest = os.path.join(CLIENTS, "bootstrapper")
        os.makedirs(dest, exist_ok=True)
        entries = {}
        for platform, f in files.items():
            src, (stem, ext) = os.path.join(folder, f["file"]), os.path.splitext(f["file"])
            # players update from a file of this version (so the file and its checksum always
            # match); the plain name is the download page's
            versioned = f"{stem}-{version}{ext}"
            replace_file(src, os.path.join(dest, versioned), 0o755, "www-data")
            replace_file(src, os.path.join(dest, f["file"]), 0o755, "www-data")
            entries[platform] = {"version": version, "url": f"/client-releases/bootstrapper/{versioned}", "sha256": f["sha256"]}
        m = self.read_manifest()
        m["bootstrapper"] = entries
        self.write_manifest(m)


def claim(db):
    row = db.one("SELECT * FROM DeployActions WHERE Status = 'queued' ORDER BY ID LIMIT 1")
    if not row:
        return None
    cur = db.run("UPDATE DeployActions SET Status = 'running', TimeStarted = UNIX_TIMESTAMP() WHERE ID = %s AND Status = 'queued'", (row["ID"],))
    return row if cur.rowcount == 1 else None


def main():
    if os.geteuid() != 0:
        sys.exit("deployd: needs root")
    os.umask(0o022)
    for p in PROGRAMS:
        os.makedirs(os.path.join(RELEASES, p), exist_ok=True)
    os.chmod(RELEASES, 0o700)
    db = DB(CONF, "root")
    db.run(
        "UPDATE DeployActions SET Status = 'failed', TimeFinished = UNIX_TIMESTAMP(), "
        "Log = CONCAT(IFNULL(Log, ''), '\nThe deploy daemon was restarted during this deploy: check the server, then deploy again.\n') WHERE Status = 'running'"
    )
    log("deployd: ready")
    beat = 0
    while True:
        try:
            if time.time() - beat > 15:
                beat = time.time()
                db.heartbeat("deployd", "idle")
            row = claim(db)
            if not row:
                time.sleep(2)
                continue
            log(f"action {row['ID']}: {row['Action']} {row['Program']} build {row['BuildID']}")
            db.heartbeat("deployd", f"{row['Action']} {row['Program']}")
            deploy = Deploy(db, row)
            status = "failed"
            try:
                if row["Program"] not in PROGRAMS:
                    raise DeployError("unknown program")
                deploy.execute()
                status = "success"
                deploy.log("Done.")
            except DeployError as e:
                deploy.log(f"Failed: {e}")
            except Exception as e:
                deploy.log(f"Failed: {type(e).__name__}: {e}")
            deploy.buf.flush()
            db.run("UPDATE DeployActions SET Status = %s, TimeFinished = UNIX_TIMESTAMP() WHERE ID = %s", (status, row["ID"]))
        except Exception as e:  # e.g. the database is restarting
            log(f"deployd: {type(e).__name__}: {e}")
            time.sleep(5)


if __name__ == "__main__":
    main()