diff --git a/.github/workflows/release-retention.yml b/.github/workflows/release-retention.yml index 94d87143..5101c5ab 100644 --- a/.github/workflows/release-retention.yml +++ b/.github/workflows/release-retention.yml @@ -1,9 +1,11 @@ name: Release retention -# Keeps the newest RELEASES_TO_KEEP version tags with their releases and their versioned images, -# 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), the latest stable release, or an image version that carries a tag no release made -# (latest, main, a sha). +# 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: @@ -49,12 +51,17 @@ jobs: 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: @@ -62,6 +69,50 @@ jobs: 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: @@ -118,7 +169,9 @@ jobs: 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)) @@ -126,17 +179,76 @@ jobs: 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)}") - chosen_ids = {version_id for version_id, _ in images[package]} - left = [version for version in versions if version["id"] not in chosen_ids] + 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") + 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, chosen in images.items(): + 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}")