Files
marqdo-site/scripts/activate-release.py
T
2026-12-02 10:39:28 +08:00

132 lines
5.4 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 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):
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 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 promote_current(base):
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")
digest, _ = live_digest(base)
release_name = f"site-{website_sha}-{digest}"
if not (base / "releases" / release_name).is_dir():
return "waiting for current candidate"
return activate(base, release_name, 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="?")
options = parser.parse_args()
base = options.base.resolve()
if 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))