Files
marqdo-site/scripts/activate-release.py
T
2026-12-02 11:09:41 +08:00

205 lines
9.0 KiB
Python

#!/usr/bin/env python3
"""Switch an already staged and verified Marqdo website release."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import re
from shutil import copyfile, copytree
from tempfile import TemporaryDirectory
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, build_opener
from release_artifacts import HEX, read_json, verify
REV = re.compile(r"[0-9a-f]{40}")
ORIGIN = "https://marqdo.com"
def live_digest(base):
data = read_json(base / "public-data/current.json")
digest = data["sha256"]
if not HEX.fullmatch(digest) or data["snapshot"] != f"/data/snapshots/{digest}.json":
raise ValueError("Invalid live data pointer")
return digest, data["revision"]
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_args, **_kwargs):
return None
def probe(expected):
opener = build_opener(NoRedirect())
for path in ("/", "/en/", "/download/", "/assets/logo.svg"):
with opener.open(ORIGIN + path, timeout=10) as response:
if response.status != 200:
raise ValueError(f"Unhealthy path: {path}")
with opener.open(ORIGIN + "/build.json", timeout=10) as response:
if json.load(response) != expected:
raise ValueError("Production identity differs from candidate")
try:
opener.open(ORIGIN + "/__marqdo_missing_health/", timeout=10).close()
except HTTPError as error:
if error.code == 404:
return
raise
raise ValueError("Missing path did not return HTTP 404")
def replace_link(base, release):
with TemporaryDirectory(prefix=".switch-", dir=base) as temporary:
link = Path(temporary) / "current"
link.symlink_to(release.relative_to(base), target_is_directory=True)
os.replace(link, base / "current")
def activate(base, release_name, website_sha, health_probe=probe, current_website_sha=None):
releases = base / "releases"
candidate = releases / release_name
current = base / "current"
recovery = releases / "safe"
if not re.fullmatch(r"site-[0-9a-f]{40}-[0-9a-f]{64}", release_name) or not REV.fullmatch(website_sha):
raise ValueError("Invalid release or website source identity")
if candidate.is_symlink() or recovery.is_symlink() or releases.is_symlink():
raise ValueError("Release directories must be real paths")
with (base / ".deploy.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
digest, revision = live_digest(base)
identity = verify(candidate)
expected_name = f"site-{website_sha}-{digest}"
if (identity.get("mode") != "release" or release_name != expected_name
or (identity["website_sha"], identity["snapshot_sha256"], identity["revision"]) != (website_sha, digest, revision)):
raise ValueError("Candidate is stale or has the wrong source identity")
if current.exists() and not current.is_symlink():
raise ValueError("The current path must be a managed symbolic link")
previous = current.resolve(strict=False)
if previous == candidate:
health_probe(identity)
return "already active"
verify(recovery, safe=True)
fallback = recovery
if previous.parent == releases and previous.is_dir() and previous != recovery:
previous_id = verify(previous)
if previous_id.get("snapshot_sha256") == digest and previous_id.get("revision") == revision:
fallback = previous
if current_website_sha is not None and current_website_sha() != website_sha:
raise ValueError("Website main changed before activation")
if live_digest(base) != (digest, revision):
raise ValueError("Data pointer changed before activation")
replace_link(base, candidate)
try:
health_probe(identity)
if live_digest(base) != (digest, revision):
raise ValueError("Data pointer changed during activation")
except Exception:
try:
if live_digest(base) != (digest, revision):
fallback = recovery
except (OSError, ValueError, KeyError, TypeError):
fallback = recovery
replace_link(base, fallback)
raise
return "activated"
def protected_website_sha():
opener = build_opener(NoRedirect())
branch_url = "https://git.cflmy.cn/api/v1/repos/cflmy/marqdo-site/branches/main"
with opener.open(branch_url, timeout=10) as response:
branch = json.load(response)
website_sha = branch.get("commit", {}).get("id", "")
if branch.get("protected") is not True or not REV.fullmatch(website_sha):
raise ValueError("Current website main must be protected")
return website_sha
def receive_release(base, source, name, *, safe=False, expected_digest=None, website_sha=None):
releases = base / "releases"
destination = releases / name
if releases.is_symlink():
raise ValueError("Serving releases directory may not be a symlink")
def check(directory):
identity = verify(directory, safe=safe)
if expected_digest is not None and identity["artifacts_sha256"] != expected_digest:
raise ValueError("Received release differs from the approved artifact")
if website_sha is not None and identity.get("website_sha") != website_sha:
raise ValueError("Received release has the wrong website source")
if not safe:
release_name = f"site-{identity.get('website_sha')}-{identity.get('snapshot_sha256')}"
if identity.get("mode") != "release" or name != release_name:
raise ValueError("Received release identity does not match its directory")
return identity
if destination.exists() or destination.is_symlink():
return check(destination)
if source.is_symlink() or not source.is_dir():
raise ValueError("Uploaded release must be a real directory")
with TemporaryDirectory(prefix=".receive-", dir=releases) as staging:
candidate = Path(staging) / name
copytree(source, candidate, symlinks=True, copy_function=copyfile)
identity = check(candidate)
for path in candidate.rglob("*"):
path.chmod(0o755 if path.is_dir() else 0o644)
candidate.chmod(0o755)
try:
os.rename(candidate, destination)
except OSError:
if not destination.is_dir():
raise
return check(destination)
return identity
def bootstrap(base, incoming, website_sha, artifacts_sha):
if not REV.fullmatch(website_sha) or not HEX.fullmatch(artifacts_sha):
raise ValueError("Bootstrap requires verified website and artifact identities")
recovery = base / "releases" / "safe"
current = base / "current"
with (base / ".deploy.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
receive_release(base, incoming / f"bootstrap-{website_sha}", "safe",
safe=True, expected_digest=artifacts_sha, website_sha=website_sha)
if current.exists() or current.is_symlink():
if not current.is_symlink() or current.resolve() != recovery:
raise ValueError("An existing website activation is in place")
return "bootstrap already ready"
replace_link(base, recovery)
return "bootstrap ready"
def promote_current(base, incoming=None):
if not (base / "public-data/current.json").is_file():
return "waiting for public release data"
website_sha = protected_website_sha()
digest, _ = live_digest(base)
release_name = f"site-{website_sha}-{digest}"
if not (base / "releases" / release_name).is_dir():
if incoming is None or not (incoming / release_name).is_dir():
return "waiting for current candidate"
receive_release(base, incoming / release_name, release_name)
return activate(base, release_name, website_sha, current_website_sha=protected_website_sha)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("base", type=Path)
parser.add_argument("release", nargs="?")
parser.add_argument("expected_website_sha", nargs="?")
parser.add_argument("--incoming", type=Path)
parser.add_argument("--bootstrap", nargs=2, metavar=("WEBSITE_SHA", "ARTIFACTS_SHA256"))
options = parser.parse_args()
base = options.base.resolve()
if options.bootstrap:
if not options.incoming or options.release or options.expected_website_sha:
parser.error("Bootstrap requires --incoming and no positional release")
print(bootstrap(base, options.incoming, *options.bootstrap))
elif options.release and options.expected_website_sha:
print(activate(base, options.release, options.expected_website_sha))
elif options.release or options.expected_website_sha:
parser.error("Pass both release and expected_website_sha, or neither")
else:
print(promote_current(base, options.incoming))