Repositories | Polyback | Log in to see private repositories


polyback-website / 4e3cec34a8b37065044edb337c27d5951760e480 / container/deploy/build-runner.py

16,215 bytes | parent directory

#!/usr/bin/env python3
"""Polyback build runner: builds what /admin/deploy-updates asks for into staged artifacts.

Runs as the unprivileged user polybuild (started by /srv/polygon/start.sh). Takes queued rows
from DeployBuilds one at a time, fetches the configured branch, builds it and leaves the output
in <deploy_root>/artifacts/<build id>/; nothing here touches what is live. Deploying a staged
build is deployd.py's job (root).

URLs under the site's own git server (https://polyback.xyz/git/<name>.git) are read straight from
the bare repository on disk, so private repositories need no credentials.

Building runs code from the repository (build scripts, cargo build scripts): whoever can push to
a configured branch can run code as polybuild. That user can only write its own folders and read and
update the build rows.
"""

import json
import os
import queue
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time

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

CONF = load_conf()
ROOT = CONF["deploy_root"]
WORK = os.path.join(ROOT, "work")
ARTIFACTS = os.path.join(ROOT, "artifacts")
KEEP_BUILDS = int(CONF.get("keep_builds", 5))
TIMEOUT = int(CONF.get("build_timeout_seconds", 3600))
PHP = CONF.get("php", "php85")

HOME = os.path.expanduser("~polybuild") if os.geteuid() != 0 else "/home/polybuild"
ENV = {
    "HOME": HOME,
    "USER": "polybuild",
    "LANG": "C.UTF-8",
    "PATH": ":".join(CONF.get("path", ["/opt/odin", "/usr/lib/llvm21/bin"]) + ["/usr/local/bin", "/usr/bin", "/bin"]),
    "CARGO_HOME": os.path.join(HOME, ".cargo"),
    "GIT_TERMINAL_PROMPT": "0",
    "GIT_ASKPASS": "/bin/false",
}


class BuildError(Exception):
    pass


class Cancelled(Exception):
    pass


class Build:
    def __init__(self, db, row):
        self.db, self.row, self.id, self.program = db, row, row["ID"], row["Program"]
        self.buf = LogBuffer(lambda text: db.run("UPDATE DeployBuilds SET Log = %s WHERE ID = %s", (text, self.id)))
        self.out = os.path.join(ARTIFACTS, str(self.id))
        self.deadline = time.time() + TIMEOUT

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

    def stage(self, text):
        self.log(f"### {text}")
        self.db.run("UPDATE DeployBuilds SET Stage = %s WHERE ID = %s", (text[:100], self.id))

    def check_cancel(self):
        row = self.db.one("SELECT CancelRequested FROM DeployBuilds WHERE ID = %s", (self.id,))
        if row and row["CancelRequested"]:
            raise Cancelled()

    def run(self, cmd, cwd=None, env=None, quiet=False):
        """Run a command, logging its output; raises BuildError if it fails."""
        if not quiet:
            self.log("$ " + " ".join(cmd))
        proc = subprocess.Popen(
            cmd,
            cwd=cwd,
            env={**ENV, **(env or {})},
            stdin=subprocess.DEVNULL,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            start_new_session=True,
            text=True,
            errors="replace",
        )
        lines = queue.Queue()
        reader = threading.Thread(target=lambda: ([lines.put(l) for l in proc.stdout], lines.put(None)), daemon=True)
        reader.start()
        next_check = time.time() + 2
        try:
            while True:
                try:
                    line = lines.get(timeout=1)
                    if line is None:
                        break
                    self.log(line)
                except queue.Empty:
                    self.buf.flush()
                if time.time() > next_check:
                    next_check = time.time() + 2
                    self.db.heartbeat("runner", f"building {self.program} #{self.id}")
                    self.check_cancel()
                    if time.time() > self.deadline:
                        raise BuildError(f"the build took longer than {TIMEOUT} s")
        except BaseException:
            try:
                os.killpg(proc.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
            proc.wait()
            raise
        code = proc.wait()
        if code != 0:
            raise BuildError(f"{cmd[0]} exited with status {code}")

    def capture(self, cmd, cwd=None):
        p = subprocess.run(cmd, cwd=cwd, env=ENV, stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
        if p.returncode != 0:
            raise BuildError(f"{' '.join(cmd)} failed: {p.stderr.decode(errors='replace').strip()[:500]}")
        return p.stdout.decode(errors="replace")

    # ---------- steps ----------

    def fetch(self):
        url, branch = self.row["GitURL"], self.row["Branch"]
        if not valid_git_url(url) or not valid_branch(branch):
            raise BuildError("invalid git URL or branch")
        source = url
        prefix = CONF["local_git_prefix"]
        if url.startswith(prefix):
            m = re.fullmatch(r"([A-Za-z0-9_][A-Za-z0-9._-]{0,63})\.git", url[len(prefix) :])
            if not m:
                raise BuildError("that isn't a repository URL on this site (…/git/<name>.git)")
            source = os.path.join(CONF["git_root"], m.group(1) + ".git")
            if not os.path.isdir(source):
                raise BuildError(f"the repository {m.group(1)} doesn't exist on this site's git server")
        self.stage(f"Fetching {branch} from {url}")
        repo = os.path.join(WORK, self.program, "repo")
        if not os.path.isdir(os.path.join(repo, ".git")):
            shutil.rmtree(repo, ignore_errors=True)
            os.makedirs(repo)
            self.run(["git", "init", "--quiet", repo], quiet=True)
        ref = "refs/remotes/build/source"
        self.run(["git", "-c", "core.hooksPath=/dev/null", "fetch", "--quiet", "--no-tags", "--force", "--end-of-options", source, f"+refs/heads/{branch}:{ref}"], cwd=repo, quiet=True)
        commit = self.capture(["git", "rev-parse", "--verify", ref + "^{commit}"], cwd=repo).strip()
        self.run(["git", "-c", "core.hooksPath=/dev/null", "checkout", "--quiet", "--force", "--detach", commit], cwd=repo, quiet=True)
        self.run(["git", "clean", "-ffdxq"], cwd=repo, quiet=True)
        info = self.capture(["git", "show", "-s", "--format=%an%x00%ct%x00%B", commit], cwd=repo).split("\0", 2)
        author, when, message = info[0], int(info[1] or 0), info[2].strip()
        self.db.run(
            "UPDATE DeployBuilds SET CommitHash = %s, CommitAuthor = %s, CommitTime = %s, CommitMessage = %s WHERE ID = %s",
            (commit, author[:255], when, message[:4000], self.id),
        )
        self.log(f"commit {commit} by {author}: {message.splitlines()[0] if message else ''}")
        self.repo, self.commit = repo, commit

    def pick_version(self):
        version = time.strftime("%Y.%m%d.%H%M", time.gmtime())
        taken = self.db.one("SELECT COUNT(*) AS n FROM DeployBuilds WHERE Program = %s AND Version = %s", (self.program, version))
        if taken["n"]:
            version += f"-{self.id}"
        assert VERSION_RE.match(version)
        self.version = version
        self.db.run("UPDATE DeployBuilds SET Version = %s WHERE ID = %s", (version, self.id))
        self.log(f"version {version}")

    def need(self, path):
        if not os.path.exists(os.path.join(self.repo, path)):
            raise BuildError(f"this commit has no {path}: it is older than the Deploy Updates support")

    def build_website(self):
        self.stage("Checking PHP syntax")
        files = [f for f in self.capture(["git", "ls-files", "-z", "*.php"], cwd=self.repo).split("\0") if f]
        bad = []
        jobs = CONF.get("jobs", os.cpu_count() or 4)
        pending = list(files)
        running = []
        while pending or running:
            while pending and len(running) < jobs:
                f = pending.pop()
                running.append((f, subprocess.Popen([PHP, "-n", "-l", os.path.join(self.repo, f)], env=ENV, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)))
            f, p = running.pop(0)
            out = p.communicate()[0].decode(errors="replace").strip()
            if p.returncode != 0:
                bad.append(f)
                self.log(f"{f}: {out}")
        if bad:
            raise BuildError(f"{len(bad)} PHP file(s) have syntax errors")
        self.log(f"{len(files)} PHP files OK")
        self.stage("Packing")
        name = f"website-{self.version}.tar.gz"
        self.run(["git", "archive", "--format=tar.gz", "-o", os.path.join(self.out, name), self.commit], cwd=self.repo)
        return {"site": name}

    def build_gameserver(self):
        target = os.path.join(WORK, "gameserver", "target")
        env = {"CARGO_TARGET_DIR": target}
        self.need("Cargo.lock")
        self.stage("Running tests")
        self.run(["cargo", "test", "--release", "--locked"], cwd=self.repo, env=env)
        self.stage("Building (cargo build --release)")
        self.run(["cargo", "build", "--release", "--locked"], cwd=self.repo, env=env)
        name = "polygon-gameserver"
        shutil.copy2(os.path.join(target, "release", "polygon-gameserver"), os.path.join(self.out, name))
        return {"linux-x86_64-musl": name}

    def build_engine(self):
        self.need("tools/build-dist.sh")
        self.stage("Building for Linux and Windows")
        self.run(["sh", "tools/build-dist.sh", self.out, self.version, "all"], cwd=self.repo)
        found = {}
        for name in sorted(os.listdir(self.out)):
            for suffix in (".tar.gz", ".zip"):
                prefix = f"polyback-{self.version}-"
                if name.startswith(prefix) and name.endswith(suffix):
                    found[name[len(prefix) : -len(suffix)]] = name
        for platform in ("linux-x86_64-musl", "windows-x86_64"):
            if platform not in found:
                raise BuildError(f"the build made no {platform} package")
        self.stage("Testing the packages")
        with tempfile.TemporaryDirectory(dir=WORK) as tmp:
            self.run(["tar", "-xzf", os.path.join(self.out, found["linux-x86_64-musl"]), "-C", tmp])
            self.expect_version([os.path.join(tmp, "polyback"), "--version"], cwd=tmp)
            self.run(["unzip", "-q", os.path.join(self.out, found["windows-x86_64"]), "-d", os.path.join(tmp, "win")])
            self.check_pe(os.path.join(tmp, "win", "polyback.exe"))
        return {p: found[p] for p in ("linux-x86_64-musl", "windows-x86_64")}

    def build_bootstrapper(self):
        self.need("build-dist.sh")
        self.stage("Building for Linux and Windows")
        self.run(["sh", "build-dist.sh", self.out, CONF["site_url"], self.version], cwd=self.repo)
        self.stage("Testing the binaries")
        self.expect_version([os.path.join(self.out, "polyback-player"), "--version"], cwd=self.out)
        self.check_pe(os.path.join(self.out, "polyback-player.exe"))
        return {"linux-x86_64": "polyback-player", "windows-x86_64": "polyback-player.exe"}

    def expect_version(self, cmd, cwd):
        out = self.capture(cmd, cwd=cwd)
        self.log(f"{os.path.basename(cmd[0])} --version: {out.strip()}")
        if self.version not in out.split():
            raise BuildError("the built binary reports another version")

    def check_pe(self, path):
        """A Windows executable for x86-64 (it can't be run here)."""
        with open(path, "rb") as f:
            data = f.read(4096)
        off = int.from_bytes(data[0x3C:0x40], "little")
        if data[:2] != b"MZ" or data[off : off + 4] != b"PE\0\0" or data[off + 4 : off + 6] != b"\x64\x86":
            raise BuildError(f"{os.path.basename(path)} isn't a 64-bit Windows executable")
        self.log(f"{os.path.basename(path)}: PE32+ x86-64 (not run: no Windows here)")

    # ---------- the whole thing ----------

    def execute(self):
        shutil.rmtree(self.out, ignore_errors=True)
        os.makedirs(self.out, mode=0o755)
        self.fetch()
        self.pick_version()
        files = getattr(self, "build_" + self.program)()
        artifacts, total = {}, 0
        for platform, name in files.items():
            path = os.path.join(self.out, name)
            if not FILE_RE.match(name) or not os.path.isfile(path):
                raise BuildError(f"missing output {name}")
            size = os.path.getsize(path)
            artifacts[platform] = {"file": name, "size": size, "sha256": sha256_file(path)}
            total += size
            self.log(f"{platform}: {name}, {size} bytes, sha256 {artifacts[platform]['sha256']}")
        for name in os.listdir(self.out):  # readable for the deploy daemon, nothing else kept
            path = os.path.join(self.out, name)
            if name not in files.values():
                shutil.rmtree(path) if os.path.isdir(path) and not os.path.islink(path) else os.unlink(path)
        self.db.run("UPDATE DeployBuilds SET Artifacts = %s, ArtifactBytes = %s WHERE ID = %s", (json.dumps(artifacts), total, self.id))

    def finish(self, status, message):
        self.log(message)
        self.buf.flush()
        if status != "success":
            shutil.rmtree(self.out, ignore_errors=True)
        self.db.run("UPDATE DeployBuilds SET Status = %s, Stage = NULL, TimeFinished = UNIX_TIMESTAMP() WHERE ID = %s", (status, self.id))


def prune(db, program):
    """Keep the artifacts of the newest few successful builds and of the deployed and previous ones."""
    keep = {r["ID"] for r in db.all("SELECT ID FROM DeployBuilds WHERE Program = %s AND Status = 'success' ORDER BY ID DESC LIMIT %s", (program, KEEP_BUILDS))}
    for r in db.all("SELECT CurrentBuildID, PreviousBuildID FROM DeployState"):
        keep |= {r["CurrentBuildID"], r["PreviousBuildID"]}
    for r in db.all("SELECT ID FROM DeployBuilds WHERE Program = %s AND Status = 'success' AND Artifacts IS NOT NULL", (program,)):
        if r["ID"] not in keep:
            shutil.rmtree(os.path.join(ARTIFACTS, str(r["ID"])), ignore_errors=True)
            db.run("UPDATE DeployBuilds SET Artifacts = NULL WHERE ID = %s", (r["ID"],))
            log(f"build {r['ID']}: old artifacts removed")


def claim(db):
    row = db.one("SELECT * FROM DeployBuilds WHERE Status = 'queued' ORDER BY ID LIMIT 1")
    if not row:
        return None
    cur = db.run(
        "UPDATE DeployBuilds SET Status = 'running', Stage = 'Starting', 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("build-runner: run me as polybuild, not root")
    os.umask(0o022)
    db = DB(CONF, "polybuild")
    db.run(
        "UPDATE DeployBuilds SET Status = 'failed', Stage = NULL, TimeFinished = UNIX_TIMESTAMP(), "
        "Log = CONCAT(IFNULL(Log, ''), '\nThe build runner was restarted during this build.\n') WHERE Status = 'running'"
    )
    log("build-runner: ready")
    beat = 0
    while True:
        try:
            if time.time() - beat > 15:
                beat = time.time()
                db.heartbeat("runner", "idle")
            row = claim(db)
            if not row:
                time.sleep(2)
                continue
            log(f"build {row['ID']}: {row['Program']} from {row['GitURL']} {row['Branch']}")
            beat = 0
            build = Build(db, row)
            try:
                if row["Program"] not in PROGRAMS:
                    raise BuildError("unknown program")
                build.execute()
                build.finish("success", "Build finished: ready to deploy.")
            except Cancelled:
                build.finish("cancelled", "Build cancelled.")
            except BuildError as e:
                build.finish("failed", f"Build failed: {e}")
            except (OSError, subprocess.SubprocessError, ValueError) as e:
                build.finish("failed", f"Build failed: {type(e).__name__}: {e}")
            prune(db, row["Program"])
        except Exception as e:  # e.g. the database is restarting
            log(f"build-runner: {type(e).__name__}: {e}")
            time.sleep(5)


if __name__ == "__main__":
    main()