Repositories | Polyback | Log in to see private repositories
4,612 bytes | parent directory
"""Shared bits of the Deploy Updates build runner (build-runner.py, runs as the unprivileged
polybuild user) and deploy daemon (deployd.py, runs as root).
Both read /srv/polygon/deploy/deploy.conf (JSON, see deploy.conf.example), talk to the site's
MariaDB over its unix socket (unix_socket authentication: no passwords anywhere), and log
plain text. Neither ever logs secrets: they don't read config.php, and db.env is only read by
deployd to hand the site's DB credentials to the mariadb client through a private file.
"""
import hashlib
import json
import os
import re
import sys
import time
import pymysql
CONF_PATH = os.environ.get("POLYBACK_DEPLOY_CONF", "/srv/polygon/deploy/deploy.conf")
PROGRAMS = ("website", "engine", "gameserver", "bootstrapper")
# the same rules as the admin page (Deploy::ValidSource): https only, or the site's own git
GIT_URL_RE = re.compile(r"^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?/[A-Za-z0-9._~/%+-]*$")
BRANCH_RE = re.compile(r"^[A-Za-z0-9._/][A-Za-z0-9._/-]{0,99}$")
# a version string: also a folder and file name (manifest, gameserver-engine/<version>)
VERSION_RE = re.compile(r"^[0-9A-Za-z][0-9A-Za-z._-]{0,39}$")
# artifact file names (no folders)
FILE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
def load_conf():
with open(CONF_PATH) as f:
conf = json.load(f)
conf.setdefault("db", "polygon")
conf.setdefault("db_socket", "/run/mysqld/mysqld.sock")
conf.setdefault("deploy_root", "/srv/polygon/deploy")
conf.setdefault("site_url", "https://polyback.xyz")
conf.setdefault("local_git_prefix", "https://polyback.xyz/git/")
conf.setdefault("git_root", "/var/www/polygondata/git")
return conf
def valid_branch(branch):
return (
isinstance(branch, str)
and BRANCH_RE.match(branch) is not None
and not branch.startswith("-")
and ".." not in branch
and "//" not in branch
and not branch.endswith("/")
and not branch.endswith(".lock")
and not branch.startswith("/")
)
def valid_git_url(url):
return isinstance(url, str) and len(url) <= 255 and GIT_URL_RE.match(url) is not None and ".." not in url
def log(*parts):
print(time.strftime("%Y-%m-%d %H:%M:%S"), *parts, flush=True)
class DB:
"""A reconnecting connection (MariaDB drops idle connections after wait_timeout)."""
def __init__(self, conf, user):
self.conf, self.user, self.conn = conf, user, None
def _connect(self):
self.conn = pymysql.connect(
unix_socket=self.conf["db_socket"],
user=self.user,
database=self.conf["db"],
charset="utf8mb4",
autocommit=True,
cursorclass=pymysql.cursors.DictCursor,
)
def run(self, sql, args=None):
for attempt in (1, 2):
try:
if self.conn is None:
self._connect()
cur = self.conn.cursor()
cur.execute(sql, args)
return cur
except (pymysql.err.OperationalError, pymysql.err.InterfaceError):
self.conn = None
if attempt == 2:
raise
time.sleep(1)
def one(self, sql, args=None):
return self.run(sql, args).fetchone()
def all(self, sql, args=None):
return self.run(sql, args).fetchall()
def heartbeat(self, name, info):
self.run(
"INSERT INTO DeployDaemons (Name, Heartbeat, Info) VALUES (%s, UNIX_TIMESTAMP(), %s) "
"ON DUPLICATE KEY UPDATE Heartbeat = UNIX_TIMESTAMP(), Info = VALUES(Info)",
(name, info[:255]),
)
class LogBuffer:
"""A build's or action's log, kept in memory and written to its row now and then."""
MAX = 1_500_000 # keep the head and the tail of very long logs
def __init__(self, flush):
self.text, self.flush_fn, self.last = "", flush, 0.0
def add(self, line):
line = line.rstrip("\n")
sys.stdout.write(line + "\n")
self.text += line + "\n"
if len(self.text) > self.MAX:
head = self.text[: self.MAX // 4]
tail = self.text[-(self.MAX // 2) :]
self.text = head + "\n[... log shortened ...]\n" + tail
if time.time() - self.last > 1.5:
self.flush()
def flush(self):
self.last = time.time()
self.flush_fn(self.text)
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()