name: Release retention # Keeps the newest RELEASES_TO_KEEP version tags with their releases, and names the older ones. The # run that follows a release only lists. A manual run deletes when "dry run" is off. It never touches # a tag that is not a version tag (vX.Y.Z with an optional pre-release) or the latest stable release. # Image versions: one goes with its deleted release tag. One that carries no tag of a kept release # and not "main" goes too when it is untagged or tagged with a sha only, unless its digest is a # manifest that an image which stays lists. An index whose manifests are not versions of the # package stops the job. The plan is in the summary before anything is deleted. on: workflow_dispatch: inputs: dry_run: description: "List only and delete nothing" type: boolean default: true workflow_run: workflows: ["Tagged Release"] types: [completed] permissions: contents: write packages: write concurrency: group: release-retention cancel-in-progress: false env: GH_TOKEN: ${{ github.token }} RELEASES_TO_KEEP: "3" # The two images release.yml pushes under the tag's version, for a user-owned package owner. IMAGE_PACKAGES: "openultrasast openultrasast-runner" jobs: retention: if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 with: fetch-depth: 0 - name: List what the retention deletes, then delete unless this is a dry run env: APPLY: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run == false }} run: | python3 - <<'PYTHON' import json import os import re import subprocess import sys OWNER, REPO = os.environ["GITHUB_REPOSITORY"].split("/") ACTOR = os.environ["GITHUB_ACTOR"] KEEP = int(os.environ["RELEASES_TO_KEEP"]) APPLY = os.environ["APPLY"] == "true" PACKAGES = os.environ["IMAGE_PACKAGES"].split() VERSION = re.compile(r"^v(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z][0-9A-Za-z.-]*)?$") SHA_TAG = re.compile(r"^sha-[0-9a-f]{7,40}$") LIMIT = 20 # More deletions than this in one run is a plan that nobody has read. IMAGE_LIMIT = 100 # The same for image versions: a repository that pushed an image for every commit has many. REGISTRY = f"ghcr.io/{OWNER}" def gh(*args): try: return subprocess.run(["gh", *args], check=True, capture_output=True, text=True).stdout except subprocess.CalledProcessError as error: sys.exit(f"gh {' '.join(args)}: exit {error.returncode}\n{error.stderr}") def docker(*args, stdin=None): """One docker call. A failed one stops the job and names the call and the reason.""" try: result = subprocess.run( ["docker", *args], check=True, capture_output=True, text=True, input=stdin, ) return result.stdout except FileNotFoundError: sys.exit("docker: not found on the runner") except subprocess.CalledProcessError as error: sys.exit(f"docker {' '.join(args)}: exit {error.returncode}\n{error.stderr}") def digest_of(version): """The digest a package version is stored under.""" return version.get("digest") or version.get("name") or "" read_indexes = {} def index_children(package, tag, digests): """The digests of the manifests an image index lists; each index is read once. An image that is one manifest lists none.""" if (package, tag) in read_indexes: return read_indexes[(package, tag)] raw = docker("buildx", "imagetools", "inspect", f"{REGISTRY}/{package}:{tag}", "--raw") try: index = json.loads(raw) except json.JSONDecodeError as error: sys.exit(f"docker buildx imagetools inspect {package}:{tag}: the output is not JSON: {error}") if not isinstance(index, dict): sys.exit(f"docker buildx imagetools inspect {package}:{tag}: the output is not an image index") entries = index.get("manifests", []) if any(not isinstance(entry.get("digest"), str) for entry in entries): sys.exit(f"docker buildx imagetools inspect {package}:{tag}: an entry of the index has no digest") children = [entry["digest"] for entry in entries] # An index none of whose manifests is a version of this package: the parts of an image # cannot be told from orphans, so the job stops before it prunes or deletes anything. if children and not digests & set(children): sys.exit( f"image {package}:{tag} lists {len(children)} manifests, and none is a version of the " "package: the safeguard for untagged versions cannot work; nothing is done" ) read_indexes[(package, tag)] = children return children def say(line): print(line) with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: summary.write(line + "\n") def image_tags(tag): """The tags docker/metadata-action gives the images of a release tag.""" name = tag[1:] if "-" in name: return {name} major, minor = VERSION.match(tag)[1], VERSION.match(tag)[2] return {name, f"{major}.{minor}"} def plan(tags, latest): """The version tags to keep and to delete, newest first by the date of the tag.""" version_tags = [tag for tag in tags if VERSION.match(tag)] kept, deleted = version_tags[:KEEP], version_tags[KEEP:] if latest in deleted: deleted.remove(latest) kept.append(latest) return kept, deleted def image_plan(versions, deleted): """The versions whose every tag came from a deleted release tag.""" allowed = set() for tag in deleted: allowed |= image_tags(tag) chosen = [] for version in versions: tags = set(version["metadata"]["container"]["tags"]) if tags and tags <= allowed: chosen.append((version["id"], sorted(tags))) return chosen if KEEP < 1: sys.exit("RELEASES_TO_KEEP must be at least 1") tags = subprocess.run( ["git", "for-each-ref", "--sort=-creatordate", "--format=%(refname:short)", "refs/tags"], check=True, capture_output=True, text=True, ).stdout.split() # One read, and it must succeed: a swallowed failure here would turn the protection of # the latest stable release off while the job went on deleting. listed = gh( "release", "list", "--limit", "400", "--json", "tagName,isLatest", "--jq", ".[] | [.tagName, .isLatest] | @tsv", ) rows = [line.split("\t") for line in listed.splitlines()] releases = {tag for tag, _ in rows} latest = next((tag for tag, is_latest in rows if is_latest == "true"), "") kept, deleted = plan(tags, latest) say(f"## Release retention: {'delete' if APPLY else 'dry run'}") say(f"Kept, the newest version tags by the date of the tag, and the latest stable release: {', '.join(kept)}") kinds = [f"{tag} (release and tag)" if tag in releases else f"{tag} (tag)" for tag in deleted] say(f"To delete: {', '.join(kinds) if kinds else 'nothing'}") if len(deleted) > LIMIT: sys.exit(f"{len(deleted)} tags to delete, more than the limit of {LIMIT}: nothing is done") docker("login", "ghcr.io", "-u", ACTOR, "--password-stdin", stdin=os.environ["GH_TOKEN"]) images = {} pruned = {} for package in PACKAGES: path = f"/user/packages/container/{package}/versions?per_page=100" pages = json.loads(gh("api", "--paginate", "--slurp", path)) versions = [version for page in pages for version in page] images[package] = image_plan(versions, deleted) for version_id, tags_of_version in images[package]: say(f"To delete: image {package}, version {version_id}, tags {', '.join(tags_of_version)}") with_release = {version_id for version_id, _ in images[package]} # Every image that stays has its index read, whatever tag keeps it: a tag of a kept # release, main, or one this rule does not name (latest, a hand-made one). Every # manifest the index lists stays with it: an untagged version can be the image # manifest or the attestation manifest of a release image. keep_tags = {tag for kept_tag in kept for tag in image_tags(kept_tag)} | {"main"} digests = {digest_of(version) for version in versions} - {""} stays = set() outside = [] for version in versions: tags_of_version = set(version["metadata"]["container"]["tags"]) named_tags = {tag for tag in tags_of_version if not SHA_TAG.match(tag)} if version["id"] in with_release or not named_tags: continue if digest_of(version): stays.add(digest_of(version)) if not named_tags & keep_tags: outside.append(", ".join(sorted(named_tags))) # The tags of one version lead to one image: a kept tag names the release, and # else the longest tag is read. tag = max(named_tags & keep_tags or named_tags, key=len) stays.update(index_children(package, tag, digests)) pruned[package], unnamed = [], [] for version in versions: tags_of_version = set(version["metadata"]["container"]["tags"]) if version["id"] in with_release or digest_of(version) in stays: continue sha_only = bool(tags_of_version) and all(SHA_TAG.match(tag) for tag in tags_of_version) if (not tags_of_version and digest_of(version)) or sha_only: pruned[package].append(version) else: unnamed.append(version) for version in pruned[package]: tags_of_version = version["metadata"]["container"]["tags"] named = ", ".join(tags_of_version) if tags_of_version else "untagged" say(f"To prune: image {package}, version {version['id']}, {digest_of(version)[:19]}, {named}") gone = with_release | {version["id"] for version in pruned[package]} left = [version for version in versions if version["id"] not in gone] names = [] for version in left: tags_left = version["metadata"]["container"]["tags"] names.append(", ".join(tags_left) if tags_left else f"id {version['id']}, untagged") say(f"Image {package}: {len(left)} of {len(versions)} versions stay: {'; '.join(names)}") parts = [ version["id"] for version in left if not version["metadata"]["container"]["tags"] and digest_of(version) in stays ] parts_listed = " ".join(str(part) for part in parts) if parts else "none" say( f"Image {package}: untagged versions that stay, each part of an image that stays: {parts_listed}" ) if outside: say(f"Image {package}: stays under a tag this rule does not name: {'; '.join(outside)}") if unnamed: unplaced = [] for version in unnamed: tags_unplaced = version["metadata"]["container"]["tags"] unplaced.append(", ".join(tags_unplaced) if tags_unplaced else f"id {version['id']}, untagged") say(f"Image {package}: stays, and this rule cannot place it: {'; '.join(unplaced)}") count = sum(len(chosen) for chosen in images.values()) + sum(len(chosen) for chosen in pruned.values()) if count > IMAGE_LIMIT: sys.exit(f"{count} image versions to delete, more than the limit of {IMAGE_LIMIT}: nothing is done") if not APPLY: say("Dry run: nothing was deleted.") sys.exit(0) for package in PACKAGES: pruned_here = [ (version["id"], version["metadata"]["container"]["tags"]) for version in pruned[package] ] chosen = images[package] + pruned_here for version_id, _ in chosen: gh("api", "--method", "DELETE", f"/user/packages/container/{package}/versions/{version_id}") say(f"Deleted image {package}, version {version_id}") for tag in deleted: if tag in releases: gh("release", "delete", tag, "--yes", "--cleanup-tag") say(f"Deleted the release and the tag {tag}") else: gh("api", "--method", "DELETE", f"repos/{OWNER}/{REPO}/git/refs/tags/{tag}") say(f"Deleted the tag {tag}") PYTHON