Releases for cnx01: every push to main becomes a signed release
As thukthuk and lampbench-web: once the checks pass on a push to main, the CI job `release` reserves the next CalVer version (YYYY.M.MICRO, Bangkok time) with a draft release, builds the server on Ubuntu 22.04 (glibc 2.35) with that version and the commit (`VISA_COMMIT`), packs bin/visa, VERSION and COMMIT as visa-linux-x86_64.tar.gz, signs it with the repository secret RELEASE_SIGNING_KEY (ssh-keygen, namespace visa-release, principal visa-ci; checked against release/allowed-signers before it is published) and publishes the release. cnx01 will install a release only with that signature (cnx-network-clan modules/visa, in a PR of its own). - .gitea/scripts/release.py and test_release.py from lamp-testbench (the same reserve/publish/discard and version order), with visa's one archive; sign-release.sh; build-release.sh. The release scripts' tests run in the check job. - `visa --version` (and `visa version`): "visa <version> (<commit>)", which CI and cnx01's fetch check. - The key was made locally, put into the secret through the API and deleted; only its public half is in the repo. - README, AGENTS (main is live: push only whole steps), PLAN's decisions. Checks: fmt, clippy; test_release.py 14 tests OK in WSL; `visa --version`.
This commit is contained in:
1 parent
1f54d93643
commit
0d3b2d8b84
10 files changed
+866
-9
No files matched your search
@@ -0,0 +1,316 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Release the pushed commit as the next CalVer version (job `release` in .gitea/workflows/ci.yml).
|
||||
|
||||
python3 .gitea/scripts/release.py reserve # version= and release_id= to $GITHUB_OUTPUT
|
||||
python3 .gitea/scripts/release.py publish <id> dist/* # attach the files, then publish
|
||||
python3 .gitea/scripts/release.py discard <id> # after a failure: delete the draft
|
||||
|
||||
The version is YYYY.M.MICRO in Bangkok time, MICRO counting the month's releases from 0
|
||||
(2026.11.0, 2026.11.1, 2026.12.0), and the tag has the same name. `reserve` holds the number with
|
||||
a draft release on the commit, so two runs never take the same one and the build can carry it.
|
||||
`publish` waits until no older draft of a live run is left, so releases go out in version order
|
||||
and the newest one is always Gitea's latest: releases/download/latest/<file> then fetches its
|
||||
files. A commit that already has a release keeps it (a re-run replaces the files); a commit that a
|
||||
newer release or draft already contains gets none.
|
||||
|
||||
Reads GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_SHA and GITHUB_RUN_ID as Gitea Actions sets
|
||||
them, and TOKEN (the job token). Needs git and a checkout with history and tags.
|
||||
"""
|
||||
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
TOOL = "visa"
|
||||
CALVER = re.compile(r"^(\d{4})\.([1-9]\d?)\.(0|[1-9]\d*)$")
|
||||
BANGKOK = dt.timezone(dt.timedelta(hours=7)) # Thailand has no daylight saving time
|
||||
# A draft older than this belongs to a run that is gone: the release job times out sooner.
|
||||
STALE = dt.timedelta(minutes=95)
|
||||
# Publish anyway after waiting this long for older drafts; the next release puts the order right.
|
||||
WAIT_LIMIT = dt.timedelta(minutes=float(os.environ.get("RELEASE_WAIT_MINUTES", "40")))
|
||||
MARK = re.compile(r"<!-- ci-run (\d+) -->")
|
||||
WEB = "visa-linux-x86_64.tar.gz"
|
||||
PLATFORMS = {
|
||||
WEB: "Linux x86_64, glibc 2.35 or newer: the server",
|
||||
WEB + ".sig": "the server's signature by this repository's CI",
|
||||
}
|
||||
MAX_COMMITS = 50
|
||||
POLL = float(os.environ.get("RELEASE_POLL_SECONDS", "20"))
|
||||
|
||||
|
||||
def vkey(tag):
|
||||
m = CALVER.match(tag or "")
|
||||
return tuple(int(x) for x in m.groups()) if m else None
|
||||
|
||||
|
||||
def git(*args, check=True):
|
||||
r = subprocess.run(["git", *args], capture_output=True, text=True, encoding="utf-8")
|
||||
if check and r.returncode:
|
||||
sys.exit(f"git {' '.join(args)}: {r.stderr.strip()}")
|
||||
return r
|
||||
|
||||
|
||||
def remote_tags():
|
||||
"""CalVer tags on the server and the commit each points at."""
|
||||
tags = {}
|
||||
for line in git("ls-remote", "--tags", "origin").stdout.splitlines():
|
||||
sha, ref = line.split("\t")
|
||||
name = ref.removeprefix("refs/tags/")
|
||||
peeled = name.endswith("^{}")
|
||||
name = name.removesuffix("^{}")
|
||||
if vkey(name) and (peeled or name not in tags):
|
||||
tags[name] = sha
|
||||
return tags
|
||||
|
||||
|
||||
def contains(newer, older):
|
||||
"""True when commit `older` is `newer` or one of its ancestors."""
|
||||
return git("merge-base", "--is-ancestor", older, newer, check=False).returncode == 0
|
||||
|
||||
|
||||
def now():
|
||||
return dt.datetime.now(BANGKOK)
|
||||
|
||||
|
||||
def parse_time(text):
|
||||
return dt.datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, server, repo, token):
|
||||
self.api = f"{server.rstrip('/')}/api/v1/repos/{repo}"
|
||||
self.web = f"{server.rstrip('/')}/{repo}"
|
||||
self.auth = {"Authorization": f"token {token}"}
|
||||
|
||||
def call(self, method, path, body=None, ctype="application/json"):
|
||||
data = json.dumps(body).encode() if isinstance(body, dict) else body
|
||||
req = urllib.request.Request(
|
||||
self.api + path,
|
||||
data=data,
|
||||
method=method,
|
||||
headers={**self.auth, "Content-Type": ctype, "Accept": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=300) as r:
|
||||
raw = r.read()
|
||||
return json.loads(raw) if raw.strip() else None
|
||||
|
||||
def get(self, path):
|
||||
"""GET, or None on 404."""
|
||||
try:
|
||||
return self.call("GET", path)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
def drafts(self):
|
||||
out, page = [], 1
|
||||
while True:
|
||||
batch = self.call("GET", f"/releases?draft=true&limit=50&page={page}") or []
|
||||
out += [r for r in batch if r.get("draft")]
|
||||
if len(batch) < 50:
|
||||
return out
|
||||
page += 1
|
||||
|
||||
def create_draft(self, tag, sha, run_id):
|
||||
return self.call(
|
||||
"POST",
|
||||
"/releases",
|
||||
{
|
||||
"tag_name": tag,
|
||||
"target_commitish": sha,
|
||||
"name": f"{TOOL} {tag}",
|
||||
"body": f"<!-- ci-run {run_id} -->\nBuilding {sha[:10]} ...",
|
||||
"draft": True,
|
||||
"prerelease": False,
|
||||
},
|
||||
)
|
||||
|
||||
def upload(self, rel_id, name, data):
|
||||
b = uuid.uuid4().hex
|
||||
head = (
|
||||
f'--{b}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\n'
|
||||
"Content-Type: application/octet-stream\r\n\r\n"
|
||||
).encode()
|
||||
body = head + data + f"\r\n--{b}--\r\n".encode()
|
||||
self.call(
|
||||
"POST",
|
||||
f"/releases/{rel_id}/assets?name={urllib.parse.quote(name)}",
|
||||
body,
|
||||
f"multipart/form-data; boundary={b}",
|
||||
)
|
||||
|
||||
def alive(self, draft):
|
||||
"""Whether the run that reserved `draft` may still publish it."""
|
||||
if now() - parse_time(draft["created_at"]) > STALE:
|
||||
return False
|
||||
m = MARK.search(draft.get("body") or "")
|
||||
if m:
|
||||
try:
|
||||
run = self.call("GET", f"/actions/runs/{m.group(1)}")
|
||||
if run and run.get("status") == "completed":
|
||||
return False
|
||||
except urllib.error.HTTPError as e:
|
||||
print(f" (run {m.group(1)}: HTTP {e.code}; the draft's age decides)")
|
||||
return True
|
||||
|
||||
|
||||
def output(**values):
|
||||
path = os.environ.get("GITHUB_OUTPUT")
|
||||
lines = "".join(f"{k}={v}\n" for k, v in values.items())
|
||||
if path:
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(lines)
|
||||
print(lines, end="")
|
||||
|
||||
|
||||
def reserve(g, sha, run_id):
|
||||
# branches and tags pushed since the checkout, for the ancestry checks below
|
||||
git("fetch", "-q", "origin", "+refs/heads/*:refs/remotes/origin/*", "+refs/tags/*:refs/tags/*")
|
||||
tags = remote_tags()
|
||||
mine = sorted((t for t, s in tags.items() if s == sha), key=vkey)
|
||||
if mine:
|
||||
tag = mine[-1]
|
||||
rel = g.get(f"/releases/tags/{urllib.parse.quote(tag, safe='')}")
|
||||
if rel is None: # a tag without a release
|
||||
rel = g.create_draft(tag, sha, run_id)
|
||||
print(f"{sha[:10]} is already {tag}: release {rel['id']} gets the new files")
|
||||
return rel
|
||||
drafts = g.drafts()
|
||||
for d in drafts:
|
||||
if d.get("target_commitish") == sha:
|
||||
g.call("PATCH", f"/releases/{d['id']}", {"body": f"<!-- ci-run {run_id} -->\nBuilding {sha[:10]} ..."})
|
||||
print(f"{sha[:10]} already holds {d['tag_name']} (draft {d['id']} of an earlier attempt)")
|
||||
return d
|
||||
others = list(tags.items()) + [(d["tag_name"], d.get("target_commitish", "")) for d in drafts]
|
||||
for name, other in others:
|
||||
if other and other != sha and contains(other, sha):
|
||||
print(f"{name} ({other[:10]}) already contains {sha[:10]}: no release of its own")
|
||||
return None
|
||||
for _ in range(10):
|
||||
t = now()
|
||||
taken = set(tags) | {d["tag_name"] for d in drafts}
|
||||
micro = 1 + max((vkey(x)[2] for x in taken if vkey(x) and vkey(x)[:2] == (t.year, t.month)), default=-1)
|
||||
tag = f"{t.year}.{t.month}.{micro}"
|
||||
try:
|
||||
rel = g.create_draft(tag, sha, run_id)
|
||||
print(f"reserved {tag} for {sha[:10]} (draft {rel['id']})")
|
||||
return rel
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 409:
|
||||
raise
|
||||
print(f"{tag} was taken meanwhile")
|
||||
time.sleep(2)
|
||||
tags, drafts = remote_tags(), g.drafts()
|
||||
sys.exit("no free version after 10 attempts")
|
||||
|
||||
|
||||
def notes(tag, sha, files):
|
||||
tags = remote_tags()
|
||||
older = [t for t, s in tags.items() if t != tag and s != sha and contains(sha, s)]
|
||||
prev = max(older, key=vkey, default=None)
|
||||
log = git("log", "--no-merges", "--format=- %s (%h)", f"{tags[prev]}..{sha}" if prev else sha).stdout
|
||||
log = log.splitlines()
|
||||
if len(log) > MAX_COMMITS:
|
||||
log = log[:MAX_COMMITS] + [f"- and {len(log) - MAX_COMMITS} earlier commits"]
|
||||
t = now()
|
||||
rows = "\n".join(
|
||||
f"| `{p.name}` | {PLATFORMS.get(p.name, '')} | `{hashlib.sha256(p.read_bytes()).hexdigest()}` |"
|
||||
for p in files
|
||||
)
|
||||
head = f"Changes since {prev}:" if prev else "Commits in this first release:"
|
||||
held = (
|
||||
f"`{WEB}` holds the server `bin/visa`; cnx01 installs it as visa.buildfor.life only with "
|
||||
"its signature beside it (`release/allowed-signers`)."
|
||||
)
|
||||
return (
|
||||
f"Built by CI from {sha[:10]} on main, {t:%B} {t.day}, {t.year}. {held}\n\n"
|
||||
f"| File | Platform | SHA-256 |\n|---|---|---|\n{rows}\n\n"
|
||||
f"{head}\n\n" + ("\n".join(log) or "- (no new commits)") + "\n"
|
||||
)
|
||||
|
||||
|
||||
def publish(g, rel_id, sha, files):
|
||||
rel = g.call("GET", f"/releases/{rel_id}")
|
||||
tag = rel["tag_name"]
|
||||
old = {a["name"]: a["id"] for a in rel.get("assets") or []}
|
||||
for p in files:
|
||||
if p.name in old:
|
||||
g.call("DELETE", f"/releases/{rel_id}/assets/{old[p.name]}")
|
||||
data = p.read_bytes()
|
||||
g.upload(rel_id, p.name, data)
|
||||
print(f" {'replaced' if p.name in old else 'attached'} {p.name} ({len(data):,} bytes)")
|
||||
if rel["draft"]:
|
||||
wait_for_older(g, rel)
|
||||
g.call("PATCH", f"/releases/{rel_id}", {"body": notes(tag, sha, files), "draft": False})
|
||||
got = remote_tags().get(tag)
|
||||
if got != sha:
|
||||
sys.exit(f"tag {tag} points at {got}, not at {sha}")
|
||||
print(f"published {g.web}/releases/tag/{tag}")
|
||||
|
||||
|
||||
def wait_for_older(g, rel):
|
||||
"""Publish in version order: wait while an older draft of a live run exists."""
|
||||
me = vkey(rel["tag_name"])
|
||||
give_up = time.monotonic() + WAIT_LIMIT.total_seconds()
|
||||
while True:
|
||||
older = [d for d in g.drafts() if d["id"] != rel["id"] and vkey(d["tag_name"]) and vkey(d["tag_name"]) < me]
|
||||
alive = []
|
||||
for d in older:
|
||||
if g.alive(d):
|
||||
alive.append(d)
|
||||
else:
|
||||
g.call("DELETE", f"/releases/{d['id']}")
|
||||
print(f"deleted {d['tag_name']}, a draft whose run is gone")
|
||||
if not alive:
|
||||
return
|
||||
waiting = ", ".join(d["tag_name"] for d in alive)
|
||||
if time.monotonic() > give_up:
|
||||
print(f"warning: {waiting} still unpublished after {WAIT_LIMIT}; publishing {rel['tag_name']} first")
|
||||
return
|
||||
print(f"waiting for {waiting} to be published first")
|
||||
time.sleep(POLL)
|
||||
|
||||
|
||||
def discard(g, rel_id):
|
||||
rel = g.get(f"/releases/{rel_id}") if rel_id else None
|
||||
if rel and rel["draft"]:
|
||||
g.call("DELETE", f"/releases/{rel_id}")
|
||||
print(f"deleted draft {rel['tag_name']}: the number is free again")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2 or sys.argv[1] not in ("reserve", "publish", "discard"):
|
||||
sys.exit(__doc__)
|
||||
names = ("GITHUB_SERVER_URL", "GITHUB_REPOSITORY", "GITHUB_SHA", "GITHUB_RUN_ID", "TOKEN")
|
||||
env = {k: os.environ.get(k, "") for k in names}
|
||||
missing = [k for k, v in env.items() if not v]
|
||||
if missing:
|
||||
sys.exit(f"missing environment: {', '.join(missing)}")
|
||||
g = Gitea(env["GITHUB_SERVER_URL"], env["GITHUB_REPOSITORY"], env["TOKEN"])
|
||||
sha = env["GITHUB_SHA"]
|
||||
cmd, args = sys.argv[1], sys.argv[2:]
|
||||
if cmd == "reserve":
|
||||
rel = reserve(g, sha, env["GITHUB_RUN_ID"])
|
||||
output(version=rel["tag_name"] if rel else "", release_id=rel["id"] if rel else "")
|
||||
elif cmd == "publish":
|
||||
files = [Path(p) for p in args[1:]]
|
||||
if not args or not files:
|
||||
sys.exit("publish <release id> <file>...")
|
||||
publish(g, int(args[0]), sha, files)
|
||||
else:
|
||||
discard(g, args[0] if args else "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user