From c3c665e7990eaa8444177ee3a7410cf7721aadb9 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 19:27:15 +0000 Subject: [PATCH 1/3] feat(image): describe every image: labels, a readme page and build metadata The registry page shows the description as plain text, every label, and links to source, documentation and licence; it renders no readme. Each Dockerfile now carries one label block (title, description, source, url, documentation, licenses, authors, base.name and net.rkdr.mortis.purpose/contents/usage), the build adds version, revision and created, and docs/images/.md says what the image is for, what it contains and how to use it. check_image_versions.py pins fails when a label or that page is missing. The labels are image inputs, so the three images get their PATCH bump. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- .gitea/workflows/image.yml | 12 +++- CLAUDE.md | 7 ++ docs/images/ci.md | 66 +++++++++++++++++++ docs/images/molecule-ubuntu2404.md | 77 ++++++++++++++++++++++ docs/images/molecule-ubuntu2604.md | 77 ++++++++++++++++++++++ galaxy.yml | 1 + images/ci/Dockerfile | 11 +++- images/molecule-ubuntu2404/Dockerfile | 11 +++- images/molecule-ubuntu2604/Dockerfile | 11 +++- scripts/check_image_versions.py | 50 ++++++++++++++ tests/scripts/test_check_image_versions.py | 51 +++++++++++++- 11 files changed, 363 insertions(+), 11 deletions(-) create mode 100644 docs/images/ci.md create mode 100644 docs/images/molecule-ubuntu2404.md create mode 100644 docs/images/molecule-ubuntu2604.md diff --git a/.gitea/workflows/image.yml b/.gitea/workflows/image.yml index bf54987..4614f7c 100644 --- a/.gitea/workflows/image.yml +++ b/.gitea/workflows/image.yml @@ -76,17 +76,17 @@ jobs: matrix: include: - name: molecule-ubuntu2404 - version: 0.1.2 + version: 0.1.3 subpath: images/molecule-ubuntu2404 dockerfile: Dockerfile job_image: ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac - name: molecule-ubuntu2604 - version: 0.1.0 + version: 0.1.1 subpath: images/molecule-ubuntu2604 dockerfile: Dockerfile job_image: ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 - name: ci - version: 0.2.5 + version: 0.2.6 subpath: "" dockerfile: images/ci/Dockerfile job_image: ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 @@ -292,6 +292,11 @@ jobs: exit 0 fi dests=(--destination "${image}:${IMAGE_VERSION}" --destination "${image}:latest") + # Labels only the build knows (the static ones are in the Dockerfile). The package page of + # the registry lists them next to the Dockerfile's. + labels=(--label "org.opencontainers.image.version=${IMAGE_VERSION}" + --label "org.opencontainers.image.revision=${SHA}" + --label "org.opencontainers.image.created=$(date -u +%Y-%m-%dT%H:%M:%SZ)") # Context: this commit of this repository, cloned by kaniko (##: # clone , check out ). With a sub-path only that directory is the @@ -314,6 +319,7 @@ jobs: --context "git://${registry}/${REPO}.git#${REF}#${SHA}" \ "${ctx[@]}" \ "${dests[@]}" \ + "${labels[@]}" \ --snapshot-mode=redo \ --cache=false \ --push-retry 3 \ diff --git a/CLAUDE.md b/CLAUDE.md index 419eac7..6fc181d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,6 +69,13 @@ protection, or create tags: those are the operator's. tag and digest, and the version bump. Digest drift within a release is tolerated. A `job_image`-only bump is not an image input: no version bump, nothing rebuilt; the post-merge Images run only reaches the prepare step for published versions, so that is its only exercise. +- Image metadata: Gitea's package page shows the description as plain text (no markdown), lists every label, + and links source, documentation and licence; it renders no README. So each Dockerfile carries the same + label block (`org.opencontainers.image.*` plus `net.rkdr.mortis.purpose/contents/usage`), the build adds + `version`, `revision` and `created`, and the readme-style text lives in `docs/images/.md`, which the + `documentation` label links to. `check_image_versions.py pins` fails when a label or that file is missing. + The docs sit outside the image directories on purpose: editing them is not an image input, so it needs no + new version. Editing a label in a Dockerfile is an input and does. - Each pushed layer must stay below 100 MB: Cloudflare rejects larger request bodies with HTTP 413. That is why the `ci` image deletes the Go toolchains from the hook cache. - `image.yml` tries the job token first with a write probe; Gitea 28 refuses it for the org's packages diff --git a/docs/images/ci.md b/docs/images/ci.md new file mode 100644 index 0000000..e017597 --- /dev/null +++ b/docs/images/ci.md @@ -0,0 +1,66 @@ +# ci + +The **CI tooling image** of the [`mortis.kamino`](https://git.rkdr.net/mortis/kamino) Collection: everything the Lint and Build +workflows used to install on each run is baked in, so a job only checks out the code and runs. + +## What is in it + +Ubuntu 26.04 with: + +- **Python tools** in `/opt/venv` (on `PATH`), from `requirements-dev.txt`: `ansible-core`, + `ansible-lint`, `pre-commit`, `antsibull-changelog`, `galaxy-importer`, `reuse`. +- **Every pre-commit hook environment** of `.pre-commit-config.yaml` in `/opt/pre-commit` + (`PRE_COMMIT_HOME`): conventional-pre-commit, gitleaks, yamllint, pre-commit-hooks, actionlint and the + local hooks. The Go hooks are prebuilt; their toolchains are removed to keep layers small. +- **`ansible-test sanity` virtualenvs**, primed in `/root/.ansible/test`, and Python 3.11 and 3.13 as + `python3.11` / `python3.13` next to the distribution's 3.12, so sanity runs its compile test for all three. +- `git`, `shellcheck` (actionlint runs it over `run:` blocks) and `ca-certificates`. +- `/opt/ci-pins.sha256`: the checksums of the two pin files this image was built from. + +It has no Node, so JavaScript actions (`actions/checkout`) cannot run in it: clone with `git`. + +## How to use it + +As the job container of a workflow on the `kamino-docker` runner, pinned by tag and digest: + +```yaml +jobs: + lint: + runs-on: kamino-docker + container: + image: git.rkdr.net/mortis/ci:@sha256: + env: + PRE_COMMIT_HOME: /opt/pre-commit + steps: + - run: git clone "$REPO_URL" . && git checkout "$SHA" # see .gitea/workflows/lint.yml + - run: sha256sum --quiet -c /opt/ci-pins.sha256 && pre-commit run --all-files +``` + +A job first compares the checkout's `requirements-dev.txt` and `.pre-commit-config.yaml` with +`/opt/ci-pins.sha256`. When they match, the baked tools are used as they are. When a pull request changes a +pin, the check fails and the job installs the pinned tools itself for that run (slower, same result), until +the image is rebuilt from `main`. See `.gitea/workflows/lint.yml` and `build.yml`. + +## Tags and pinning + +- `` is semver, independent of the Collection's version. A published version is never moved or + rebuilt, so one digest belongs to exactly one version. `latest` is the newest version, for looking only. +- Pin `ci:@sha256:`; the digest is what is enforced. Consumers: `lint.yml` and `build.yml`. +- Renovate moves the pins to a new version after the image is built on `main`. + +## How it is built and kept up to date + +`.gitea/workflows/image.yml` builds it with kaniko (repository root as build context, because the pin +files are copied in) on every push to `main` that changes its inputs: `images/ci/`, `requirements-dev.txt` +or `.pre-commit-config.yaml`. Renovate's bump of one of those files carries the PATCH bump of the image +version, and the merge builds the image. Each pushed layer stays below 100 MB (Cloudflare's request limit), +which is why the Go toolchains are deleted from the hook cache. + +## Image metadata + +The `org.opencontainers.image.*` labels (title, description, version, revision, created, source, +documentation, licenses, authors) and `net.rkdr.mortis.*` labels (what it is for, what it contains, +how to use it, the Ubuntu release) are listed on the package page of the registry; `version`, +`revision` and `created` are set by the build. + +Source: [https://git.rkdr.net/mortis/kamino](https://git.rkdr.net/mortis/kamino), `images/ci/Dockerfile`. Licence: GPL-3.0-or-later. diff --git a/docs/images/molecule-ubuntu2404.md b/docs/images/molecule-ubuntu2404.md new file mode 100644 index 0000000..632a7cf --- /dev/null +++ b/docs/images/molecule-ubuntu2404.md @@ -0,0 +1,77 @@ +# molecule-ubuntu2404 + +A disposable **Ubuntu 24.04** test target for the molecule scenarios of the +[`mortis.kamino`](https://git.rkdr.net/mortis/kamino) Ansible Collection: a container that behaves like a small +24.04 host (systemd as PID 1), so a role can be converged and verified in it without a VM. +It is the release most of the hosts run today. + +## What is in it + +- Ubuntu 24.04 (the official `ubuntu:24.04` image, pinned by digest in the Dockerfile). +- systemd as the init system (`systemd`, `systemd-sysv`), D-Bus, `sudo`, `iproute2`, + `ca-certificates`. +- Python for Ansible on the target: `python3`, `python3-apt`, `python3-systemd`. +- The packages the roles manage, preinstalled so a converge makes no network calls: + `iptables`, `ufw`, `fail2ban`, `openssh-server` (the `ssh` unit is enabled). +- Throwaway SSH host keys and a machine-id generated at build time. They are not secrets and the + image is a test target that must never be exposed to a network. + +Package versions are not pinned: they are whatever the 24.04 archive held at build time. +`image-smoke`-style checks (below) assert the contract, not versions. + +## How to use it + +In a molecule scenario (`extensions/molecule/*/molecule.yml` or `roles/*/molecule/*/molecule.yml`) +with the docker driver: + +```yaml +driver: + name: docker +platforms: + - name: instance + image: ${MOLECULE_IMAGE} # :@sha256:, set by .gitea/workflows/molecule.yml + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined +``` + +systemd needs a writable cgroup, the firewall tools need `NET_ADMIN`, and nothing runs privileged. + +The scenario `extensions/molecule/image-smoke` tests this image against that contract (release, +systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`). + +## Tags and pinning + +- `` is semver (`MAJOR.MINOR.PATCH`), independent of the Collection's version. A published + version is never moved or rebuilt, so one digest belongs to exactly one version. `latest` is the + newest version and is for looking, not for pinning. +- Pin `molecule-ubuntu2404:@sha256:`; the digest is what is enforced. Consumers here: + `.gitea/workflows/molecule.yml`. +- Renovate moves the pin to a new version after the image is built on `main`. + +## How it is built and kept up to date + +`.gitea/workflows/image.yml` builds it with kaniko on every push to `main` that changes its inputs +(`images/molecule-ubuntu2404/`), never on a pull request. A change to the image needs a new `version:` in that +workflow's matrix (Renovate's bump step does it for dependency updates). The base image +and the Ubuntu release are fixed by the name: a new Ubuntu release is a new image +(`molecule-ubuntuNNNN`), and the roles are tested on every release the hosts run or are moving to. + +## Image metadata + +The `org.opencontainers.image.*` labels (title, description, version, revision, created, source, +documentation, licenses, authors) and `net.rkdr.mortis.*` labels (what it is for, what it contains, +how to use it, the Ubuntu release) are listed on the package page of the registry; `version`, +`revision` and `created` are set by the build. + +Source: [https://git.rkdr.net/mortis/kamino](https://git.rkdr.net/mortis/kamino), `images/molecule-ubuntu2404/Dockerfile`. Licence: GPL-3.0-or-later. diff --git a/docs/images/molecule-ubuntu2604.md b/docs/images/molecule-ubuntu2604.md new file mode 100644 index 0000000..22b1a78 --- /dev/null +++ b/docs/images/molecule-ubuntu2604.md @@ -0,0 +1,77 @@ +# molecule-ubuntu2604 + +A disposable **Ubuntu 26.04** test target for the molecule scenarios of the +[`mortis.kamino`](https://git.rkdr.net/mortis/kamino) Ansible Collection: a container that behaves like a small +26.04 host (systemd as PID 1), so a role can be converged and verified in it without a VM. +It is the release the hosts are moving to; the roles are tested on it next to 24.04. + +## What is in it + +- Ubuntu 26.04 (the official `ubuntu:26.04` image, pinned by digest in the Dockerfile). +- systemd as the init system (`systemd`, `systemd-sysv`), D-Bus, `sudo`, `iproute2`, + `ca-certificates`. +- Python for Ansible on the target: `python3`, `python3-apt`, `python3-systemd`. +- The packages the roles manage, preinstalled so a converge makes no network calls: + `iptables`, `ufw`, `fail2ban`, `openssh-server` (the `ssh` unit is enabled). +- Throwaway SSH host keys and a machine-id generated at build time. They are not secrets and the + image is a test target that must never be exposed to a network. + +Package versions are not pinned: they are whatever the 26.04 archive held at build time. +`image-smoke`-style checks (below) assert the contract, not versions. + +## How to use it + +In a molecule scenario (`extensions/molecule/*/molecule.yml` or `roles/*/molecule/*/molecule.yml`) +with the docker driver: + +```yaml +driver: + name: docker +platforms: + - name: instance + image: ${MOLECULE_IMAGE_2604} # :@sha256:, set by .gitea/workflows/molecule.yml + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined +``` + +systemd needs a writable cgroup, the firewall tools need `NET_ADMIN`, and nothing runs privileged. + +The scenario `extensions/molecule/image-smoke-2604` tests this image against that contract (release, +systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`). + +## Tags and pinning + +- `` is semver (`MAJOR.MINOR.PATCH`), independent of the Collection's version. A published + version is never moved or rebuilt, so one digest belongs to exactly one version. `latest` is the + newest version and is for looking, not for pinning. +- Pin `molecule-ubuntu2604:@sha256:`; the digest is what is enforced. Consumers here: + `.gitea/workflows/molecule.yml`. +- Renovate moves the pin to a new version after the image is built on `main`. + +## How it is built and kept up to date + +`.gitea/workflows/image.yml` builds it with kaniko on every push to `main` that changes its inputs +(`images/molecule-ubuntu2604/`), never on a pull request. A change to the image needs a new `version:` in that +workflow's matrix (Renovate's bump step does it for dependency updates). The base image +and the Ubuntu release are fixed by the name: a new Ubuntu release is a new image +(`molecule-ubuntuNNNN`), and the roles are tested on every release the hosts run or are moving to. + +## Image metadata + +The `org.opencontainers.image.*` labels (title, description, version, revision, created, source, +documentation, licenses, authors) and `net.rkdr.mortis.*` labels (what it is for, what it contains, +how to use it, the Ubuntu release) are listed on the package page of the registry; `version`, +`revision` and `created` are set by the build. + +Source: [https://git.rkdr.net/mortis/kamino](https://git.rkdr.net/mortis/kamino), `images/molecule-ubuntu2604/Dockerfile`. Licence: GPL-3.0-or-later. diff --git a/galaxy.yml b/galaxy.yml index af53f86..83da7a6 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -30,6 +30,7 @@ build_ignore: - .reuse - .venv - .yamllint + - docs - .ansible-lint - CLAUDE.md - CONTRIBUTING.md diff --git a/images/ci/Dockerfile b/images/ci/Dockerfile index b4e7aae..27a2fcd 100644 --- a/images/ci/Dockerfile +++ b/images/ci/Dockerfile @@ -115,9 +115,16 @@ RUN set -eu; \ FROM os AS final LABEL org.opencontainers.image.title="ci" \ - org.opencontainers.image.description="Lint and build tooling for mortis.kamino, baked in" \ + org.opencontainers.image.description="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs. It bakes in ansible-core, ansible-lint, pre-commit with every hook environment of the repository, antsibull-changelog, galaxy-importer, reuse, git, shellcheck, Python 3.11, 3.12 and 3.13 and primed ansible-test sanity virtualenvs. Use it as a job container pinned by tag and digest; it has no Node, so clone with git." \ org.opencontainers.image.source="https://git.rkdr.net/mortis/kamino" \ - org.opencontainers.image.licenses="GPL-3.0-or-later" + org.opencontainers.image.url="https://git.rkdr.net/mortis/kamino" \ + org.opencontainers.image.documentation="https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images/ci.md" \ + org.opencontainers.image.licenses="GPL-3.0-or-later" \ + org.opencontainers.image.authors="Defame1297 and contributors" \ + org.opencontainers.image.base.name="ubuntu:26.04" \ + net.rkdr.mortis.purpose="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs." \ + net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, ansible-lint, pre-commit, antsibull-changelog, galaxy-importer, reuse), /opt/pre-commit hook environments, ansible-test sanity venvs, python3.11/3.12/3.13, git, shellcheck, /opt/ci-pins.sha256" \ + net.rkdr.mortis.usage="Job container on the kamino-docker runner: container image ci:version@sha256:digest, PRE_COMMIT_HOME=/opt/pre-commit; compare the checkout with sha256sum -c /opt/ci-pins.sha256 and install the pinned tools when a pull request changes them. See the documentation label." ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \ PRE_COMMIT_HOME=/opt/pre-commit \ diff --git a/images/molecule-ubuntu2404/Dockerfile b/images/molecule-ubuntu2404/Dockerfile index ce0e8cd..d1fa17d 100644 --- a/images/molecule-ubuntu2404/Dockerfile +++ b/images/molecule-ubuntu2404/Dockerfile @@ -28,9 +28,16 @@ FROM ubuntu:24.04@sha256:68ee22004a9109b44973313b02ff7b1de250f1de0f5ecb628d73f579aaff33ac LABEL org.opencontainers.image.title="molecule-ubuntu2404" \ - org.opencontainers.image.description="systemd-capable Ubuntu 24.04 molecule test target for mortis.kamino" \ + org.opencontainers.image.description="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection. systemd runs as PID 1 with D-Bus, sudo, python3 and the packages the roles manage (iptables, ufw, fail2ban, openssh-server) preinstalled, so a converge makes no network calls. Start it as a molecule platform (usage label); it carries throwaway SSH host keys and is a test target only, never to be exposed." \ org.opencontainers.image.source="https://git.rkdr.net/mortis/kamino" \ - org.opencontainers.image.licenses="GPL-3.0-or-later" + org.opencontainers.image.url="https://git.rkdr.net/mortis/kamino" \ + org.opencontainers.image.documentation="https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images/molecule-ubuntu2404.md" \ + org.opencontainers.image.licenses="GPL-3.0-or-later" \ + org.opencontainers.image.authors="Defame1297 and contributors" \ + org.opencontainers.image.base.name="ubuntu:24.04" \ + net.rkdr.mortis.purpose="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection." \ + net.rkdr.mortis.contents="Ubuntu 24.04, systemd, systemd-sysv, dbus, sudo, iproute2, ca-certificates, python3, python3-apt, python3-systemd, iptables, ufw, fail2ban, openssh-server (ssh enabled)" \ + net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN (not privileged). Pin name:version@sha256:digest. See the documentation label." ENV DEBIAN_FRONTEND=noninteractive diff --git a/images/molecule-ubuntu2604/Dockerfile b/images/molecule-ubuntu2604/Dockerfile index 93ac595..a4e2b20 100644 --- a/images/molecule-ubuntu2604/Dockerfile +++ b/images/molecule-ubuntu2604/Dockerfile @@ -28,9 +28,16 @@ FROM ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 LABEL org.opencontainers.image.title="molecule-ubuntu2604" \ - org.opencontainers.image.description="systemd-capable Ubuntu 26.04 molecule test target for mortis.kamino" \ + org.opencontainers.image.description="Disposable Ubuntu 26.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection. systemd runs as PID 1 with D-Bus, sudo, python3 and the packages the roles manage (iptables, ufw, fail2ban, openssh-server) preinstalled, so a converge makes no network calls. Start it as a molecule platform (usage label); it carries throwaway SSH host keys and is a test target only, never to be exposed." \ org.opencontainers.image.source="https://git.rkdr.net/mortis/kamino" \ - org.opencontainers.image.licenses="GPL-3.0-or-later" + org.opencontainers.image.url="https://git.rkdr.net/mortis/kamino" \ + org.opencontainers.image.documentation="https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images/molecule-ubuntu2604.md" \ + org.opencontainers.image.licenses="GPL-3.0-or-later" \ + org.opencontainers.image.authors="Defame1297 and contributors" \ + org.opencontainers.image.base.name="ubuntu:26.04" \ + net.rkdr.mortis.purpose="Disposable Ubuntu 26.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection." \ + net.rkdr.mortis.contents="Ubuntu 26.04, systemd, systemd-sysv, dbus, sudo, iproute2, ca-certificates, python3, python3-apt, python3-systemd, iptables, ufw, fail2ban, openssh-server (ssh enabled)" \ + net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN (not privileged). Pin name:version@sha256:digest. See the documentation label." ENV DEBIAN_FRONTEND=noninteractive diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index 03f29d4..4aa8cac 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -21,6 +21,8 @@ pins No file under .gitea/workflows may mention `git.rkdr.net/defame1297/`: the Every matrix entry names its job container (`job_image: ubuntu:@sha256:...`), and that release must equal the release of the `FROM ubuntu:` lines of its Dockerfile: kaniko runs inside the job container and unpacks the image over it. + Every image's Dockerfile carries the labels its registry page shows (REQUIRED_LABELS) and + links to docs/images/.md, which must exist. Offline: whether the tag points at the digest is a registry fact, see the "unverified" note in the PR description. bump Fails when the diff ...HEAD touches an input of an image without a @@ -387,6 +389,53 @@ def check_job_images(matrix, read_file, workflow_text): return errors +REQUIRED_LABELS = ("org.opencontainers.image.title", "org.opencontainers.image.description", + "org.opencontainers.image.source", "org.opencontainers.image.url", + "org.opencontainers.image.documentation", "org.opencontainers.image.licenses", + "org.opencontainers.image.authors", "net.rkdr.mortis.purpose", + "net.rkdr.mortis.contents", "net.rkdr.mortis.usage") +LABEL_KEY_RE = re.compile(r"(?:^|\s)(?P[A-Za-z0-9][A-Za-z0-9._-]*)=") + + +def dockerfile_labels(dockerfile_text): + """{key: raw value text} of the LABEL instructions of a Dockerfile (quotes kept).""" + labels = {} + for unused, line in _instructions(dockerfile_text): + parts = line.split(None, 1) + if len(parts) == 2 and parts[0].upper() == "LABEL": + rest = parts[1] + keys = list(LABEL_KEY_RE.finditer(rest)) + for n, m in enumerate(keys): + end = keys[n + 1].start() if n + 1 < len(keys) else len(rest) + labels[m["key"]] = rest[m.end():end].strip().rstrip("\\").strip() + return labels + + +def check_image_metadata(matrix, read_file, exists): + """Errors where an image lacks the labels its registry page shows, or the document they link to.""" + errors = [] + for name, entry in matrix.items(): + path = str(pathlib.PurePosixPath(entry["subpath"]) / entry["dockerfile"]) if entry["subpath"] else entry["dockerfile"] + try: + labels = dockerfile_labels(read_file(path)) + except OSError as exc: + errors.append(f"image '{name}': cannot read {path}: {exc}") + continue + missing = [key for key in REQUIRED_LABELS if not labels.get(key, "").strip("\"' ")] + if missing: + errors.append(f"image '{name}': {path} lacks the label(s) {', '.join(missing)}") + doc = f"docs/images/{name}.md" + link = labels.get("org.opencontainers.image.documentation", "") + if link and not link.strip("\"' ").endswith(f"/{doc}"): + errors.append(f"image '{name}': the documentation label must link to {doc}") + if not exists(doc): + errors.append(f"image '{name}': {doc} is missing (the documentation label links to it)") + title = labels.get("org.opencontainers.image.title", "").strip("\"' ") + if title and title != name: + errors.append(f"image '{name}': the title label is '{title}', expected the image name") + return errors + + def changed_images(head_matrix, changed, read_head_file): """{name: sorted touched inputs} for each image of the matrix whose inputs are in `changed`.""" result = {} @@ -477,6 +526,7 @@ def run(argv): texts = {f: pathlib.Path(f).read_text() for f in CONSUMERS if pathlib.Path(f).exists()} errors = check_pins(matrix, texts) errors += check_job_images(matrix, lambda p: pathlib.Path(p).read_text(), image_yml) + errors += check_image_metadata(matrix, lambda p: pathlib.Path(p).read_text(), lambda p: pathlib.Path(p).is_file()) workflows = sorted(pathlib.Path(WORKFLOW_DIR).glob("*.y*ml")) if pathlib.Path(WORKFLOW_DIR).is_dir() else [] errors += check_foreign_images({str(f): f.read_text() for f in workflows}) note = " (checked: " + ", ".join(texts) + ")" diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 6d2e09c..933d651 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -36,6 +36,15 @@ jobs: CI_DOCKERFILE = f"FROM {JOB} AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\nCOPY --from=b /a /b\n" + +def labelled(name, body=""): + """A Dockerfile text with the labels check_image_metadata requires.""" + values = {key: "x" for key in civ.REQUIRED_LABELS} + values["org.opencontainers.image.title"] = name + values["org.opencontainers.image.documentation"] = f"https://example.org/src/branch/main/docs/images/{name}.md" + return (f"FROM {JOB}\nLABEL " + " \\\n ".join(f'{k}="{v}"' for k, v in values.items()) + "\n" + body) + + def run(cwd, *cmd): return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True, env={**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}) @@ -283,6 +292,42 @@ class PureTest(unittest.TestCase): with self.assertRaises(civ.CheckError): civ.matrix_of(text) + def test_image_metadata_labels_and_documentation(self): + text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0") + matrix = civ.matrix_of(text) + base = "https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images" + + def dockerfile(name, drop=(), doc=None): + values = {key: "x" for key in civ.REQUIRED_LABELS} + values["org.opencontainers.image.title"] = name + values["org.opencontainers.image.documentation"] = doc or f"{base}/{name}.md" + keys = [k for k in values if k not in drop] + return f"FROM {JOB}\nLABEL " + " \\\n ".join(f'{k}="{values[k]}"' for k in keys) + "\n" + + files = {"images/mol/Dockerfile": dockerfile("mol"), "images/ci/Dockerfile": dockerfile("ci")} + have = {"docs/images/mol.md", "docs/images/ci.md"} + + def check(): + return civ.check_image_metadata(matrix, lambda path: files[path], lambda path: path in have) + + self.assertEqual(check(), []) + files["images/ci/Dockerfile"] = dockerfile("ci", drop=("net.rkdr.mortis.usage",)) + self.assertEqual(len(check()), 1) + self.assertIn("lacks the label(s) net.rkdr.mortis.usage", check()[0]) + files["images/ci/Dockerfile"] = dockerfile("ci", doc=f"{base}/other.md") + self.assertIn("must link to docs/images/ci.md", check()[0]) + files["images/ci/Dockerfile"] = dockerfile("renamed") + self.assertTrue(any("expected the image name" in e for e in check())) + files["images/ci/Dockerfile"] = dockerfile("ci") + have.discard("docs/images/ci.md") + self.assertIn("docs/images/ci.md is missing", check()[0]) + + def test_real_dockerfiles_carry_the_metadata(self): + root = pathlib.Path(__file__).resolve().parents[2] + matrix = civ.matrix_of((root / civ.MATRIX_FILE).read_text()) + self.assertEqual(civ.check_image_metadata(matrix, lambda p: (root / p).read_text(), + lambda p: (root / p).is_file()), []) + def test_scripts_do_not_import_yaml(self): # The bump step runs in the Renovate image, whose python3 has no PyYAML (dry run 2453). for script in ("check_image_versions.py", "bump_image_versions.py"): @@ -313,8 +358,10 @@ class GitTest(unittest.TestCase): run(self.repo, "git", "config", "user.email", "t@example.org") run(self.repo, "git", "config", "user.name", "t") self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.0")) - self.write("images/ci/Dockerfile", CI_DOCKERFILE) - self.write("images/mol/Dockerfile", f"FROM {JOB}\n") + self.write("images/ci/Dockerfile", labelled("ci", CI_DOCKERFILE.split("\n", 1)[1])) + self.write("images/mol/Dockerfile", labelled("mol")) + self.write("docs/images/ci.md", "ci\n") + self.write("docs/images/mol.md", "mol\n") self.write("requirements-dev.txt", "a==1\n") self.write(".pre-commit-config.yaml", "repos: []\n") self.commit("base") -- 2.43.0 From aa1848a9958972793fbd70bb9de02468fc701604 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 19:32:03 +0000 Subject: [PATCH 2/3] fix(image): act on the review of the image metadata Label parser: split the LABEL instruction like a shell (a value may hold NAME=value text), read the last stage only, require base.name and tie it to the FROM tag, require the documentation link to be /src/branch/main/docs/images/.md and the page to be non-empty. Docs: do not name a Python version the base may not ship, show the lint.yml pin check as it is, say which workflow paths start a build, name the system-language local hooks, add the apparmor option and the registry path to the molecule usage, and soften unverified Renovate and host-release statements. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- docs/images/ci.md | 51 +++++++++++------ docs/images/molecule-ubuntu2404.md | 24 ++++---- docs/images/molecule-ubuntu2604.md | 22 +++++--- images/ci/Dockerfile | 10 ++-- images/molecule-ubuntu2404/Dockerfile | 2 +- images/molecule-ubuntu2604/Dockerfile | 2 +- scripts/check_image_versions.py | 64 +++++++++++++++------- tests/scripts/test_check_image_versions.py | 52 +++++++++++------- 8 files changed, 142 insertions(+), 85 deletions(-) diff --git a/docs/images/ci.md b/docs/images/ci.md index e017597..0ab2915 100644 --- a/docs/images/ci.md +++ b/docs/images/ci.md @@ -10,18 +10,24 @@ Ubuntu 26.04 with: - **Python tools** in `/opt/venv` (on `PATH`), from `requirements-dev.txt`: `ansible-core`, `ansible-lint`, `pre-commit`, `antsibull-changelog`, `galaxy-importer`, `reuse`. - **Every pre-commit hook environment** of `.pre-commit-config.yaml` in `/opt/pre-commit` - (`PRE_COMMIT_HOME`): conventional-pre-commit, gitleaks, yamllint, pre-commit-hooks, actionlint and the - local hooks. The Go hooks are prebuilt; their toolchains are removed to keep layers small. + (`PRE_COMMIT_HOME`): conventional-pre-commit, gitleaks, yamllint, pre-commit-hooks and actionlint. The Go + hooks are prebuilt; their toolchains are removed to keep layers small. The local hooks (`reuse-lint`, + `antsibull-changelog-lint`, `ansible-lint`) are `language: system`: they run from `/opt/venv`, which is why + that directory must be on `PATH` (it is, in the image). - **`ansible-test sanity` virtualenvs**, primed in `/root/.ansible/test`, and Python 3.11 and 3.13 as - `python3.11` / `python3.13` next to the distribution's 3.12, so sanity runs its compile test for all three. -- `git`, `shellcheck` (actionlint runs it over `run:` blocks) and `ca-certificates`. + `python3.11` / `python3.13` (python-build-standalone, installed with uv) next to the distribution's + `python3`, so sanity runs its compile test for those interpreters instead of skipping it. +- `git`, `shellcheck` (actionlint runs it over `run:` blocks), `python3`, `python3-venv` and `ca-certificates`. + The image runs as root and sets no working directory. - `/opt/ci-pins.sha256`: the checksums of the two pin files this image was built from. It has no Node, so JavaScript actions (`actions/checkout`) cannot run in it: clone with `git`. ## How to use it -As the job container of a workflow on the `kamino-docker` runner, pinned by tag and digest: +As the job container of a workflow on the `kamino-docker` runner, pinned by tag and digest. This is the +shape of `.gitea/workflows/lint.yml` (which also holds the checkout step with the job-token authentication the +private repository needs; read it for the full version): ```yaml jobs: @@ -32,35 +38,46 @@ jobs: env: PRE_COMMIT_HOME: /opt/pre-commit steps: - - run: git clone "$REPO_URL" . && git checkout "$SHA" # see .gitea/workflows/lint.yml - - run: sha256sum --quiet -c /opt/ci-pins.sha256 && pre-commit run --all-files + # ... clone the repository and check out the commit (the image has no Node, so no actions/checkout) + - name: Check the baked tooling against the pins # run from the checkout root + run: | + if ! sha256sum --quiet -c /opt/ci-pins.sha256; then + /opt/venv/bin/pip install --quiet -r requirements-dev.txt # a pin changed: install the pinned tools + fi + - name: Run pre-commit on all files + run: | + export PATH="/opt/venv/bin:$PATH" + pre-commit run --all-files --show-diff-on-failure ``` -A job first compares the checkout's `requirements-dev.txt` and `.pre-commit-config.yaml` with -`/opt/ci-pins.sha256`. When they match, the baked tools are used as they are. When a pull request changes a -pin, the check fails and the job installs the pinned tools itself for that run (slower, same result), until -the image is rebuilt from `main`. See `.gitea/workflows/lint.yml` and `build.yml`. +`/opt/ci-pins.sha256` lists the two pin files by relative name, so `sha256sum -c` runs in the checkout root. When +the checkout's `requirements-dev.txt` and `.pre-commit-config.yaml` match, the baked tools are used as they are. +When a pull request changes a pin the check fails and the job installs the pinned tools itself for that run +(slower, same result), until the image is rebuilt from `main`. `lint.yml` and `build.yml` are the real consumers. ## Tags and pinning - `` is semver, independent of the Collection's version. A published version is never moved or rebuilt, so one digest belongs to exactly one version. `latest` is the newest version, for looking only. - Pin `ci:@sha256:`; the digest is what is enforced. Consumers: `lint.yml` and `build.yml`. -- Renovate moves the pins to a new version after the image is built on `main`. +- Renovate is configured to move the pins to a new version after the image is built on `main` (the rule is in + `renovate.json`; the first pin of a brand-new image is made by hand). ## How it is built and kept up to date `.gitea/workflows/image.yml` builds it with kaniko (repository root as build context, because the pin -files are copied in) on every push to `main` that changes its inputs: `images/ci/`, `requirements-dev.txt` -or `.pre-commit-config.yaml`. Renovate's bump of one of those files carries the PATCH bump of the image -version, and the merge builds the image. Each pushed layer stays below 100 MB (Cloudflare's request limit), -which is why the Go toolchains are deleted from the hook cache. +files are copied in). The workflow runs on pushes to `main` that touch `images/**`, `requirements-dev.txt`, +`.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an image only when its +`version:` in the workflow's matrix is not yet published. A change to the image's inputs therefore needs a new +`version:` (Lint enforces it, and Renovate's bump step does it for dependency updates), and the merge builds +the image. Each pushed layer stays below 100 MB (Cloudflare's request limit), which is why the Go toolchains +are deleted from the hook cache. ## Image metadata The `org.opencontainers.image.*` labels (title, description, version, revision, created, source, documentation, licenses, authors) and `net.rkdr.mortis.*` labels (what it is for, what it contains, -how to use it, the Ubuntu release) are listed on the package page of the registry; `version`, +how to use it; the base image is `base.name`) are listed on the package page of the registry; `version`, `revision` and `created` are set by the build. Source: [https://git.rkdr.net/mortis/kamino](https://git.rkdr.net/mortis/kamino), `images/ci/Dockerfile`. Licence: GPL-3.0-or-later. diff --git a/docs/images/molecule-ubuntu2404.md b/docs/images/molecule-ubuntu2404.md index 632a7cf..ac0ff1c 100644 --- a/docs/images/molecule-ubuntu2404.md +++ b/docs/images/molecule-ubuntu2404.md @@ -3,7 +3,7 @@ A disposable **Ubuntu 24.04** test target for the molecule scenarios of the [`mortis.kamino`](https://git.rkdr.net/mortis/kamino) Ansible Collection: a container that behaves like a small 24.04 host (systemd as PID 1), so a role can be converged and verified in it without a VM. -It is the release most of the hosts run today. +It is the release of the home lab's LXC hosts today. ## What is in it @@ -29,7 +29,7 @@ driver: name: docker platforms: - name: instance - image: ${MOLECULE_IMAGE} # :@sha256:, set by .gitea/workflows/molecule.yml + image: ${MOLECULE_IMAGE} # git.rkdr.net/mortis/molecule-ubuntu2404:@sha256:, set by molecule.yml pre_build_image: true pull: true command: /sbin/init @@ -45,7 +45,9 @@ platforms: - apparmor=unconfined ``` -systemd needs a writable cgroup, the firewall tools need `NET_ADMIN`, and nothing runs privileged. +systemd needs a writable cgroup (`cgroupns_mode: host`, the `/sys/fs/cgroup` mount and tmpfs on `/run`), the +firewall tools need `NET_ADMIN`, AppArmor is left unconfined for the container (`apparmor=unconfined`), and +nothing runs privileged. The docker driver needs molecule's docker plugin, which the runner provides. The scenario `extensions/molecule/image-smoke` tests this image against that contract (release, systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`). @@ -57,21 +59,23 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`) newest version and is for looking, not for pinning. - Pin `molecule-ubuntu2404:@sha256:`; the digest is what is enforced. Consumers here: `.gitea/workflows/molecule.yml`. -- Renovate moves the pin to a new version after the image is built on `main`. +- Renovate is configured to move the pin to a new version after the image is built on `main` (the rule is in + `renovate.json`; the first pin of a brand-new image is made by hand). ## How it is built and kept up to date -`.gitea/workflows/image.yml` builds it with kaniko on every push to `main` that changes its inputs -(`images/molecule-ubuntu2404/`), never on a pull request. A change to the image needs a new `version:` in that -workflow's matrix (Renovate's bump step does it for dependency updates). The base image -and the Ubuntu release are fixed by the name: a new Ubuntu release is a new image -(`molecule-ubuntuNNNN`), and the roles are tested on every release the hosts run or are moving to. +`.gitea/workflows/image.yml` builds it with kaniko. The workflow runs on pushes to `main` that touch `images/**`, +`requirements-dev.txt`, `.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an +image only when its `version:` in the workflow's matrix is not yet published. A change under +`images/molecule-ubuntu2404/` therefore needs a new `version:` (Lint enforces it) and the merge builds the image. The +Ubuntu release is fixed by the name: a new Ubuntu release is a new image (`molecule-ubuntuNNNN`), and the roles +are tested on every release the hosts run or are moving to. ## Image metadata The `org.opencontainers.image.*` labels (title, description, version, revision, created, source, documentation, licenses, authors) and `net.rkdr.mortis.*` labels (what it is for, what it contains, -how to use it, the Ubuntu release) are listed on the package page of the registry; `version`, +how to use it; the base image is `base.name`) are listed on the package page of the registry; `version`, `revision` and `created` are set by the build. Source: [https://git.rkdr.net/mortis/kamino](https://git.rkdr.net/mortis/kamino), `images/molecule-ubuntu2404/Dockerfile`. Licence: GPL-3.0-or-later. diff --git a/docs/images/molecule-ubuntu2604.md b/docs/images/molecule-ubuntu2604.md index 22b1a78..ad618f7 100644 --- a/docs/images/molecule-ubuntu2604.md +++ b/docs/images/molecule-ubuntu2604.md @@ -29,7 +29,7 @@ driver: name: docker platforms: - name: instance - image: ${MOLECULE_IMAGE_2604} # :@sha256:, set by .gitea/workflows/molecule.yml + image: ${MOLECULE_IMAGE_2604} # git.rkdr.net/mortis/molecule-ubuntu2604:@sha256:, set by molecule.yml pre_build_image: true pull: true command: /sbin/init @@ -45,7 +45,9 @@ platforms: - apparmor=unconfined ``` -systemd needs a writable cgroup, the firewall tools need `NET_ADMIN`, and nothing runs privileged. +systemd needs a writable cgroup (`cgroupns_mode: host`, the `/sys/fs/cgroup` mount and tmpfs on `/run`), the +firewall tools need `NET_ADMIN`, AppArmor is left unconfined for the container (`apparmor=unconfined`), and +nothing runs privileged. The docker driver needs molecule's docker plugin, which the runner provides. The scenario `extensions/molecule/image-smoke-2604` tests this image against that contract (release, systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`). @@ -57,21 +59,23 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`) newest version and is for looking, not for pinning. - Pin `molecule-ubuntu2604:@sha256:`; the digest is what is enforced. Consumers here: `.gitea/workflows/molecule.yml`. -- Renovate moves the pin to a new version after the image is built on `main`. +- Renovate is configured to move the pin to a new version after the image is built on `main` (the rule is in + `renovate.json`; the first pin of a brand-new image is made by hand). ## How it is built and kept up to date -`.gitea/workflows/image.yml` builds it with kaniko on every push to `main` that changes its inputs -(`images/molecule-ubuntu2604/`), never on a pull request. A change to the image needs a new `version:` in that -workflow's matrix (Renovate's bump step does it for dependency updates). The base image -and the Ubuntu release are fixed by the name: a new Ubuntu release is a new image -(`molecule-ubuntuNNNN`), and the roles are tested on every release the hosts run or are moving to. +`.gitea/workflows/image.yml` builds it with kaniko. The workflow runs on pushes to `main` that touch `images/**`, +`requirements-dev.txt`, `.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an +image only when its `version:` in the workflow's matrix is not yet published. A change under +`images/molecule-ubuntu2604/` therefore needs a new `version:` (Lint enforces it) and the merge builds the image. The +Ubuntu release is fixed by the name: a new Ubuntu release is a new image (`molecule-ubuntuNNNN`), and the roles +are tested on every release the hosts run or are moving to. ## Image metadata The `org.opencontainers.image.*` labels (title, description, version, revision, created, source, documentation, licenses, authors) and `net.rkdr.mortis.*` labels (what it is for, what it contains, -how to use it, the Ubuntu release) are listed on the package page of the registry; `version`, +how to use it; the base image is `base.name`) are listed on the package page of the registry; `version`, `revision` and `created` are set by the build. Source: [https://git.rkdr.net/mortis/kamino](https://git.rkdr.net/mortis/kamino), `images/molecule-ubuntu2604/Dockerfile`. Licence: GPL-3.0-or-later. diff --git a/images/ci/Dockerfile b/images/ci/Dockerfile index 27a2fcd..4269966 100644 --- a/images/ci/Dockerfile +++ b/images/ci/Dockerfile @@ -9,8 +9,8 @@ # image: git.rkdr.net/mortis/ci@sha256: # # What is baked in, and from where: -# - OS packages: git, shellcheck (actionlint runs it over run: blocks), Python 3.12 -# (the distribution's) and ca-certificates. +# - OS packages: git, shellcheck (actionlint runs it over run: blocks), the +# distribution's python3 and ca-certificates. # - /opt/venv: requirements-dev.txt (ansible-core, ansible-lint, pre-commit, # antsibull-changelog, galaxy-importer, reuse). # - /opt/pre-commit: every hook environment of .pre-commit-config.yaml, installed by @@ -115,7 +115,7 @@ RUN set -eu; \ FROM os AS final LABEL org.opencontainers.image.title="ci" \ - org.opencontainers.image.description="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs. It bakes in ansible-core, ansible-lint, pre-commit with every hook environment of the repository, antsibull-changelog, galaxy-importer, reuse, git, shellcheck, Python 3.11, 3.12 and 3.13 and primed ansible-test sanity virtualenvs. Use it as a job container pinned by tag and digest; it has no Node, so clone with git." \ + org.opencontainers.image.description="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs. It bakes in ansible-core, ansible-lint, pre-commit with every hook environment of the repository, antsibull-changelog, galaxy-importer, reuse, git, shellcheck, Python 3.11 and 3.13 next to the distribution's python3 and primed ansible-test sanity virtualenvs. Use it as a job container pinned by tag and digest; it has no Node, so clone with git." \ org.opencontainers.image.source="https://git.rkdr.net/mortis/kamino" \ org.opencontainers.image.url="https://git.rkdr.net/mortis/kamino" \ org.opencontainers.image.documentation="https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images/ci.md" \ @@ -123,8 +123,8 @@ LABEL org.opencontainers.image.title="ci" \ org.opencontainers.image.authors="Defame1297 and contributors" \ org.opencontainers.image.base.name="ubuntu:26.04" \ net.rkdr.mortis.purpose="CI tooling image for the mortis.kamino Ansible Collection: the Lint and Build workflows run in it, so a job only checks out the code and runs." \ - net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, ansible-lint, pre-commit, antsibull-changelog, galaxy-importer, reuse), /opt/pre-commit hook environments, ansible-test sanity venvs, python3.11/3.12/3.13, git, shellcheck, /opt/ci-pins.sha256" \ - net.rkdr.mortis.usage="Job container on the kamino-docker runner: container image ci:version@sha256:digest, PRE_COMMIT_HOME=/opt/pre-commit; compare the checkout with sha256sum -c /opt/ci-pins.sha256 and install the pinned tools when a pull request changes them. See the documentation label." + net.rkdr.mortis.contents="Ubuntu 26.04, /opt/venv (ansible-core, ansible-lint, pre-commit, antsibull-changelog, galaxy-importer, reuse), /opt/pre-commit hook environments, ansible-test sanity venvs, python3 (distribution), python3.11, python3.13, git, shellcheck, /opt/ci-pins.sha256" \ + net.rkdr.mortis.usage="Job container on the kamino-docker runner: container image git.rkdr.net/mortis/ci:version@sha256:digest with PRE_COMMIT_HOME set to /opt/pre-commit; in the checkout root run sha256sum -c /opt/ci-pins.sha256 and install the pinned tools when a pull request changed them, else use /opt/venv/bin. See the documentation label." ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \ PRE_COMMIT_HOME=/opt/pre-commit \ diff --git a/images/molecule-ubuntu2404/Dockerfile b/images/molecule-ubuntu2404/Dockerfile index d1fa17d..62df610 100644 --- a/images/molecule-ubuntu2404/Dockerfile +++ b/images/molecule-ubuntu2404/Dockerfile @@ -37,7 +37,7 @@ LABEL org.opencontainers.image.title="molecule-ubuntu2404" \ org.opencontainers.image.base.name="ubuntu:24.04" \ net.rkdr.mortis.purpose="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection." \ net.rkdr.mortis.contents="Ubuntu 24.04, systemd, systemd-sysv, dbus, sudo, iproute2, ca-certificates, python3, python3-apt, python3-systemd, iptables, ufw, fail2ban, openssh-server (ssh enabled)" \ - net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN (not privileged). Pin name:version@sha256:digest. See the documentation label." + net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN, security_opts apparmor=unconfined (not privileged). Pin git.rkdr.net/mortis/name:version@sha256:digest. See the documentation label." ENV DEBIAN_FRONTEND=noninteractive diff --git a/images/molecule-ubuntu2604/Dockerfile b/images/molecule-ubuntu2604/Dockerfile index a4e2b20..1efcfff 100644 --- a/images/molecule-ubuntu2604/Dockerfile +++ b/images/molecule-ubuntu2604/Dockerfile @@ -37,7 +37,7 @@ LABEL org.opencontainers.image.title="molecule-ubuntu2604" \ org.opencontainers.image.base.name="ubuntu:26.04" \ net.rkdr.mortis.purpose="Disposable Ubuntu 26.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection." \ net.rkdr.mortis.contents="Ubuntu 26.04, systemd, systemd-sysv, dbus, sudo, iproute2, ca-certificates, python3, python3-apt, python3-systemd, iptables, ufw, fail2ban, openssh-server (ssh enabled)" \ - net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN (not privileged). Pin name:version@sha256:digest. See the documentation label." + net.rkdr.mortis.usage="Molecule docker-driver platform with pre_build_image true, command /sbin/init, cgroupns_mode host, /sys/fs/cgroup mounted rw, tmpfs on /run and /run/lock, capability NET_ADMIN, security_opts apparmor=unconfined (not privileged). Pin git.rkdr.net/mortis/name:version@sha256:digest. See the documentation label." ENV DEBIAN_FRONTEND=noninteractive diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py index 4aa8cac..8f1e61d 100644 --- a/scripts/check_image_versions.py +++ b/scripts/check_image_versions.py @@ -53,6 +53,7 @@ import fnmatch import json import pathlib import re +import shlex import subprocess import sys @@ -359,6 +360,12 @@ def dockerfile_releases(dockerfile_text): return releases, problems +def file_size(path): + """Size in bytes of a regular file, or None when there is none.""" + p = pathlib.Path(path) + return p.stat().st_size if p.is_file() else None + + def check_job_images(matrix, read_file, workflow_text): """Errors where an image's job container (`job_image`) is not the Ubuntu release its Dockerfile builds. @@ -392,47 +399,62 @@ def check_job_images(matrix, read_file, workflow_text): REQUIRED_LABELS = ("org.opencontainers.image.title", "org.opencontainers.image.description", "org.opencontainers.image.source", "org.opencontainers.image.url", "org.opencontainers.image.documentation", "org.opencontainers.image.licenses", - "org.opencontainers.image.authors", "net.rkdr.mortis.purpose", + "org.opencontainers.image.authors", "org.opencontainers.image.base.name", "net.rkdr.mortis.purpose", "net.rkdr.mortis.contents", "net.rkdr.mortis.usage") -LABEL_KEY_RE = re.compile(r"(?:^|\s)(?P[A-Za-z0-9][A-Za-z0-9._-]*)=") def dockerfile_labels(dockerfile_text): - """{key: raw value text} of the LABEL instructions of a Dockerfile (quotes kept).""" + """{key: value} of the LABEL instructions of the LAST stage of a Dockerfile (labels of an earlier + stage are not inherited by a stage that starts from another image). The instruction is split like a + shell would split it, so a quoted value may hold spaces and `NAME=value` text.""" labels = {} for unused, line in _instructions(dockerfile_text): parts = line.split(None, 1) - if len(parts) == 2 and parts[0].upper() == "LABEL": - rest = parts[1] - keys = list(LABEL_KEY_RE.finditer(rest)) - for n, m in enumerate(keys): - end = keys[n + 1].start() if n + 1 < len(keys) else len(rest) - labels[m["key"]] = rest[m.end():end].strip().rstrip("\\").strip() + if not parts: + continue + if parts[0].upper() == "FROM": + labels = {} + elif parts[0].upper() == "LABEL" and len(parts) == 2: + try: + tokens = shlex.split(parts[1]) + except ValueError: + continue # an unbalanced quote: the labels stay missing, which the check reports + for token in tokens: + key, equals, value = token.partition("=") + if equals and key: + labels[key] = value return labels -def check_image_metadata(matrix, read_file, exists): - """Errors where an image lacks the labels its registry page shows, or the document they link to.""" +def check_image_metadata(matrix, read_file, size_of): + """Errors where an image lacks the labels its registry page shows, or the document they link to. + size_of(path) is the size in bytes of a file, or None when there is no such file.""" errors = [] for name, entry in matrix.items(): path = str(pathlib.PurePosixPath(entry["subpath"]) / entry["dockerfile"]) if entry["subpath"] else entry["dockerfile"] try: - labels = dockerfile_labels(read_file(path)) + text = read_file(path) except OSError as exc: errors.append(f"image '{name}': cannot read {path}: {exc}") continue - missing = [key for key in REQUIRED_LABELS if not labels.get(key, "").strip("\"' ")] + labels = dockerfile_labels(text) + missing = [key for key in REQUIRED_LABELS if not labels.get(key, "").strip()] if missing: - errors.append(f"image '{name}': {path} lacks the label(s) {', '.join(missing)}") + errors.append(f"image '{name}': the last stage of {path} lacks the label(s) {', '.join(missing)}") doc = f"docs/images/{name}.md" - link = labels.get("org.opencontainers.image.documentation", "") - if link and not link.strip("\"' ").endswith(f"/{doc}"): - errors.append(f"image '{name}': the documentation label must link to {doc}") - if not exists(doc): - errors.append(f"image '{name}': {doc} is missing (the documentation label links to it)") - title = labels.get("org.opencontainers.image.title", "").strip("\"' ") + source = labels.get("org.opencontainers.image.source", "").strip() + link = labels.get("org.opencontainers.image.documentation", "").strip() + if link and link != f"{source}/src/branch/main/{doc}": + errors.append(f"image '{name}': the documentation label must be /src/branch/main/{doc}") + if not size_of(doc): + errors.append(f"image '{name}': {doc} is missing or empty (the documentation label links to it)") + title = labels.get("org.opencontainers.image.title", "").strip() if title and title != name: errors.append(f"image '{name}': the title label is '{title}', expected the image name") + base = labels.get("org.opencontainers.image.base.name", "").strip() + releases, unused = dockerfile_releases(text) + if base and sorted(set(releases)) and base not in {f"ubuntu:{r}" for r in releases}: + errors.append(f"image '{name}': base.name label '{base}' differs from the FROM line(s) of {path}") return errors @@ -526,7 +548,7 @@ def run(argv): texts = {f: pathlib.Path(f).read_text() for f in CONSUMERS if pathlib.Path(f).exists()} errors = check_pins(matrix, texts) errors += check_job_images(matrix, lambda p: pathlib.Path(p).read_text(), image_yml) - errors += check_image_metadata(matrix, lambda p: pathlib.Path(p).read_text(), lambda p: pathlib.Path(p).is_file()) + errors += check_image_metadata(matrix, lambda p: pathlib.Path(p).read_text(), file_size) workflows = sorted(pathlib.Path(WORKFLOW_DIR).glob("*.y*ml")) if pathlib.Path(WORKFLOW_DIR).is_dir() else [] errors += check_foreign_images({str(f): f.read_text() for f in workflows}) note = " (checked: " + ", ".join(texts) + ")" diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 933d651..6b8f71f 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -41,7 +41,9 @@ def labelled(name, body=""): """A Dockerfile text with the labels check_image_metadata requires.""" values = {key: "x" for key in civ.REQUIRED_LABELS} values["org.opencontainers.image.title"] = name + values["org.opencontainers.image.source"] = "https://example.org" values["org.opencontainers.image.documentation"] = f"https://example.org/src/branch/main/docs/images/{name}.md" + values["org.opencontainers.image.base.name"] = "ubuntu:24.04" return (f"FROM {JOB}\nLABEL " + " \\\n ".join(f'{k}="{v}"' for k, v in values.items()) + "\n" + body) @@ -295,38 +297,46 @@ class PureTest(unittest.TestCase): def test_image_metadata_labels_and_documentation(self): text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0") matrix = civ.matrix_of(text) - base = "https://git.rkdr.net/mortis/kamino/src/branch/main/docs/images" - - def dockerfile(name, drop=(), doc=None): - values = {key: "x" for key in civ.REQUIRED_LABELS} - values["org.opencontainers.image.title"] = name - values["org.opencontainers.image.documentation"] = doc or f"{base}/{name}.md" - keys = [k for k in values if k not in drop] - return f"FROM {JOB}\nLABEL " + " \\\n ".join(f'{k}="{values[k]}"' for k in keys) + "\n" - - files = {"images/mol/Dockerfile": dockerfile("mol"), "images/ci/Dockerfile": dockerfile("ci")} - have = {"docs/images/mol.md", "docs/images/ci.md"} + files = {"images/mol/Dockerfile": labelled("mol"), "images/ci/Dockerfile": labelled("ci")} + sizes = {"docs/images/mol.md": 5, "docs/images/ci.md": 5} def check(): - return civ.check_image_metadata(matrix, lambda path: files[path], lambda path: path in have) + return civ.check_image_metadata(matrix, lambda path: files[path], sizes.get) self.assertEqual(check(), []) - files["images/ci/Dockerfile"] = dockerfile("ci", drop=("net.rkdr.mortis.usage",)) - self.assertEqual(len(check()), 1) + files["images/ci/Dockerfile"] = labelled("ci").replace('net.rkdr.mortis.usage="x"', 'net.rkdr.mortis.usage=""') self.assertIn("lacks the label(s) net.rkdr.mortis.usage", check()[0]) - files["images/ci/Dockerfile"] = dockerfile("ci", doc=f"{base}/other.md") - self.assertIn("must link to docs/images/ci.md", check()[0]) - files["images/ci/Dockerfile"] = dockerfile("renamed") + files["images/ci/Dockerfile"] = labelled("ci").replace("docs/images/ci.md", "docs/images/other.md") + self.assertIn("documentation label must be", check()[0]) + files["images/ci/Dockerfile"] = labelled("ci").replace("https://example.org/src", "https://evil.example/src") + self.assertIn("documentation label must be", check()[0]) + files["images/ci/Dockerfile"] = labelled("renamed") self.assertTrue(any("expected the image name" in e for e in check())) - files["images/ci/Dockerfile"] = dockerfile("ci") - have.discard("docs/images/ci.md") - self.assertIn("docs/images/ci.md is missing", check()[0]) + files["images/ci/Dockerfile"] = labelled("ci").replace('base.name="ubuntu:24.04"', 'base.name="ubuntu:22.04"') + self.assertIn("base.name label 'ubuntu:22.04' differs", check()[0]) + files["images/ci/Dockerfile"] = labelled("ci") + sizes["docs/images/ci.md"] = 0 + self.assertIn("docs/images/ci.md is missing or empty", check()[0]) + del sizes["docs/images/ci.md"] + self.assertIn("docs/images/ci.md is missing or empty", check()[0]) + del files["images/ci/Dockerfile"] + sizes["docs/images/ci.md"] = 5 + with self.assertRaises(KeyError): + check() + + def test_dockerfile_labels_parse_like_a_shell(self): + text = ('FROM a AS b\nLABEL builder=1\nFROM c\n' + 'LABEL one="x y=z w" two=\'q r\' \\\n three=plain\n' + 'LABEL four="PRE_COMMIT_HOME=/opt/pre-commit; done" legacy value\n') + self.assertEqual(civ.dockerfile_labels(text), + {"one": "x y=z w", "two": "q r", "three": "plain", "four": "PRE_COMMIT_HOME=/opt/pre-commit; done"}) + self.assertEqual(civ.dockerfile_labels('FROM c\nLABEL a="unbalanced\n'), {}) def test_real_dockerfiles_carry_the_metadata(self): root = pathlib.Path(__file__).resolve().parents[2] matrix = civ.matrix_of((root / civ.MATRIX_FILE).read_text()) self.assertEqual(civ.check_image_metadata(matrix, lambda p: (root / p).read_text(), - lambda p: (root / p).is_file()), []) + lambda p: (root / p).stat().st_size if (root / p).is_file() else None), []) def test_scripts_do_not_import_yaml(self): # The bump step runs in the Renovate image, whose python3 has no PyYAML (dry run 2453). -- 2.43.0 From b90acd714739b8fddfd67257f9b90d40241c8f01 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Mon, 26 Oct 2026 19:34:35 +0000 Subject: [PATCH 3/3] style(tests): one blank line fewer before labelled() (pep8 E303) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm --- tests/scripts/test_check_image_versions.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py index 6b8f71f..0ad00c5 100644 --- a/tests/scripts/test_check_image_versions.py +++ b/tests/scripts/test_check_image_versions.py @@ -36,7 +36,6 @@ jobs: CI_DOCKERFILE = f"FROM {JOB} AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\nCOPY --from=b /a /b\n" - def labelled(name, body=""): """A Dockerfile text with the labels check_image_metadata requires.""" values = {key: "x" for key in civ.REQUIRED_LABELS} -- 2.43.0