diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index 6e827796f2..bc1599d217 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -65,6 +65,53 @@ jobs: UPDATE_BASE_BRANCH: main run: bash scripts/github/update/open/role_prs.sh roles + update-version-sources: + name: šŸ”– Update declared version sources + if: vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-latest + steps: + - name: ā¬‡ļø Checkout + uses: actions/checkout@v7.0.0 + with: + ref: main + + - name: šŸ”§ Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: šŸ“¦ Install update dependencies + run: bash scripts/github/update/install_python.sh + + - name: šŸ”„ Update declared version sources + run: bash scripts/github/update/version_sources.sh + + - name: šŸ”Ž Check for changes + id: diff + run: bash scripts/github/resolve/check_git_changes.sh roles + + - name: āš™ļø Generate app token + if: steps.diff.outputs.changed == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: šŸ“‚ Open PR if declared version sources changed + if: steps.diff.outputs.changed == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + UPDATE_BRANCH_PREFIX: update/version-sources + UPDATE_COMMIT_MESSAGE: "update(versions): update pins with a declared source" + UPDATE_PR_TITLE: "update(versions): update pins with a declared source" + UPDATE_PR_BODY: "Automated update of version pins declaring their upstream in an `update:` block of `roles/*/meta/services.yml`." + UPDATE_BASE_BRANCH: main + run: bash scripts/github/update/open/role_prs.sh roles + update-pip-pins: name: šŸ Update pinned pip requirements if: vars.CI_ENABLE_AUTO_UPDATES == 'true' diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 48fa109911..336bb06b76 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -1,3 +1,37 @@ # Update šŸ”„ Repository-side version maintenance: scan role configuration files for declared upstream versions and bump them in lockstep with new releases. + +## Declared version sources + +A pin the Docker updater (`image` + `version`) and the repository updater +(`repository` + `ref`) do not reach names its upstream next to itself: + +```yaml +lmstudio: + app_version: 0.0.25-1 + update: + key: app_version + type: http_regex + url: https://lmstudio.ai/install.sh + pattern: 'APP_VERSION="([0-9][0-9.-]*)"' +``` + +`key` names the pinned key and defaults to `version`; an entity with several +pins declares a list of such blocks. Types: + +| `type` | Fields | Reads | +| --------------- | --------------------- | -------------------------------------- | +| `git_tags` | `repository` | `git ls-remote --tags` | +| `registry_tags` | `image` | the registry's v2 tag list | +| `npm` | `package` | the npm registry | +| `http_regex` | `url`, `pattern` | the first capture group of each match | +| `script` | `path` | a role-local script printing versions | + +`match` keeps only the versions carrying that prefix (and filters server-side +on Docker Hub), `strip: true` removes it again so a pin without the upstream's +`v` stays without it. + +Run `python -m cli.contributing.update.source --dry-run` to list pending bumps; +the `update-version-sources` job of `.github/workflows/cron-update.yml` opens +the PRs, and `tests/external/update/source/` warns about them. diff --git a/cli/contributing/update/source/__init__.py b/cli/contributing/update/source/__init__.py new file mode 100644 index 0000000000..0f6478c67a --- /dev/null +++ b/cli/contributing/update/source/__init__.py @@ -0,0 +1,5 @@ +"""CLI entry point package for declared version-source updates.""" + +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/cli/contributing/update/source/__main__.py b/cli/contributing/update/source/__main__.py new file mode 100755 index 0000000000..0fc8202170 --- /dev/null +++ b/cli/contributing/update/source/__main__.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +from pathlib import Path + +from utils.update.source import apply_updates, find_outdated_updates + +from . import PROJECT_ROOT + + +def main() -> int: + parser = argparse.ArgumentParser( + description=( + "Update version pins that declare their upstream in an `update:` " + "block of roles/*/meta/services.yml." + ) + ) + parser.add_argument( + "--repo-root", + type=Path, + default=PROJECT_ROOT, + help="Repository root to scan and update", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print planned updates without modifying files", + ) + args = parser.parse_args() + + repo_root = args.repo_root.resolve() + updates = find_outdated_updates(repo_root) + + if not updates: + print("Declared version sources are already up to date.") + return 0 + + print("Planned version source updates:") + for update in updates: + entry = update.entry + rel_path = entry.config_path.relative_to(repo_root) + print( + f"- {rel_path}:{entry.line} {entry.role}/{entry.entity}.{entry.key} " + f"{entry.current} -> {update.latest}" + ) + + if args.dry_run: + return 0 + + changed_paths = apply_updates(updates) + if changed_paths: + print("\nUpdated files:") + for path in changed_paths: + print(f"- {path.relative_to(repo_root)}") + else: + print("\nNo files changed.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index b0f3939497..1b396ddf03 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -47,6 +47,8 @@ The placement rule is per check. The catalog "Position" column uses these labels | `onion-flag` | same or above | [test_onion_port_flag.py](../../../../tests/lint/ansible/services/test_onion_port_flag.py) | Accepts a `false` under `ports.onion`. The marker MUST carry a reason naming why that port stays off the node onion; a bare marker is rejected. | | `docker-version` | same or above | [test_image_versions.py](../../../../tests/external/update/docker/test_image_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live version-update warning and the non-semver-pin lint for that image's `version:` key. | | `repository-version` | same or above | [test_repository_versions.py](../../../../tests/external/update/repository/test_repository_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live ref-update warning and the non-semver-pin lint for that entity's `ref:` key. | +| `version-source` | same or above | [test_version_sources.py](../../../../tests/external/update/source/test_version_sources.py) | Skips the live update warning for a pin that declares its upstream in an `update:` block. | +| `unwatched-version` | same or above | [test_version_pins_are_watched.py](../../../../tests/lint/repository/test_version_pins_are_watched.py) | Accepts a semver pin that no updater bumps. The marker MUST carry a reason naming why the version stays where it is. | | `dockerfile-arg-default` | same or above | [test_arg_without_default.py](../../../../tests/lint/docker/dockerfile/test_arg_without_default.py) | Allows the marked `ARG` to carry a default. The caller normally supplies every build argument so a missing one fails the build instead of selecting a base image nobody chose. | | `debian-codename` | same or above | [test_no_debian_codename_tags.py](../../../../tests/lint/repository/test_no_debian_codename_tags.py) | Allows an image reference whose tag names a Debian release by codename. Reserved for an upstream that publishes no numeric tag; the marker MUST name which upstream, because a codename pin can never be raised by the updater. | | `direct-yaml` | same line / span | [test_no_direct_calls.py](../../../../tests/lint/repository/yaml/test_no_direct_calls.py) | Allows the marked `yaml.safe_load` / `safe_dump` call to bypass `utils.cache.yaml`. MUST use `nocheck:`, not `noqa:`. | diff --git a/roles/svc-storage-nfs-client/meta/services.yml b/roles/svc-storage-nfs-client/meta/services.yml index 8a17d3830d..6e2651c1f9 100644 --- a/roles/svc-storage-nfs-client/meta/services.yml +++ b/roles/svc-storage-nfs-client/meta/services.yml @@ -12,6 +12,7 @@ nfs-client: swarm: enabled: false name: nfs-client + # nocheck: unwatched-version Reason: the NFS protocol generation the client mounts with, not a release of a product nfs_version: 4 lifecycle: beta min_storage: "50MB" diff --git a/roles/web-app-flowise/meta/services.yml b/roles/web-app-flowise/meta/services.yml index 3979ca3023..0a6448c40e 100644 --- a/roles/web-app-flowise/meta/services.yml +++ b/roles/web-app-flowise/meta/services.yml @@ -62,6 +62,13 @@ flowise: # nocheck: docker-version version: "24-slim" npm_version: 3.1.4 + update: + - key: npm_version + type: npm + package: flowise + - key: sqlite_version + type: npm + package: better-sqlite3 sqlite_version: 12.11.1 custom: true name: flowise diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index 3f89210b70..bf0b9f8563 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -113,6 +113,9 @@ giteamcpupstream: shared: false image: docker.gitea.com/gitea-mcp-server version: "1.6.0" + update: + type: registry_tags + image: docker.gitea.com/gitea-mcp-server name: gitea-mcp cpus: 0.25 mem_reservation: 0.1g diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index bcab90817c..836b451aa7 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -38,6 +38,14 @@ hugo: builder_version: exts-0.148.0 source_repository: https://github.com/gohugoio/hugoDocs.git source_version: v0.148.0 + update: + - key: builder_version + type: registry_tags + image: hugomods/hugo + match: "exts-" + - key: source_version + type: git_tags + repository: https://github.com/gohugoio/hugoDocs.git hugo_environment: production hugo_minify: true ports: diff --git a/roles/web-app-mailu/meta/services.yml b/roles/web-app-mailu/meta/services.yml index e8433b424c..828b626233 100644 --- a/roles/web-app-mailu/meta/services.yml +++ b/roles/web-app-mailu/meta/services.yml @@ -39,6 +39,7 @@ mailu: shared: true covers: - email + # nocheck: unwatched-version Reason: Mailu ships its images under the release-series tag while its git tags are patch level (2024.06.58), so the series is the pin and moves only on a deliberate migration version: "2024.06" name: mailu backup: diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 8d8a476113..70f66d0f48 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -45,7 +45,13 @@ moodle: bond: 1 enabled: true # nocheck: dynamic-flag shared: true - release: 4.5.11 + app_version: 4.5.11 + update: + key: app_version + type: git_tags + repository: https://github.com/moodle/moodle.git + match: "v" + strip: true image: php # nocheck: docker-version version: "8.3-fpm" diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 7ddc796bbc..786edc0c15 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -39,7 +39,7 @@ MOODLE_ADMIN_USERNAME: "{{ lookup('users', 'administrator').username }}" MOODLE_ADMIN_PASSWORD: "{{ lookup('users', 'administrator').password }}" MOODLE_ADMIN_EMAIL: "{{ lookup('users', 'administrator').email }}" -MOODLE_RELEASE: "{{ lookup('config', application_id, 'services.moodle.release') }}" +MOODLE_RELEASE: "{{ lookup('config', application_id, 'services.moodle.app_version') }}" MOODLE_TARBALL_URL: "https://github.com/moodle/moodle/archive/refs/tags/v{{ MOODLE_RELEASE }}.tar.gz" MOODLE_MSMTP_SRC: "{{ lookup('path_absolute', 'roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2') }}" diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 46a71c10d2..a7ad1c3b40 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -68,6 +68,9 @@ n8n: no_stop_required: false image: docker.n8n.io/n8nio/n8n version: "1.100.1" + update: + type: registry_tags + image: docker.n8n.io/n8nio/n8n name: n8n min_storage: 422MB cpus: "1.0" diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index 449ea24995..cc973d1273 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -107,6 +107,9 @@ blackbox-exporter: cadvisor: image: gcr.io/cadvisor/cadvisor version: v0.52.1 + update: + type: registry_tags + image: gcr.io/cadvisor/cadvisor name: prometheus-cadvisor cpus: "0.25" mem_reservation: 128m diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index dfdb29767a..b769dd01d5 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -45,6 +45,10 @@ stalwart: image: stalwartlabs/stalwart version: "v0.16.24" webui_version: "v1.0.5" + update: + key: webui_version + type: git_tags + repository: https://github.com/stalwartlabs/webui.git name: stalwart backup: project_hard_restart: true diff --git a/roles/web-app-suitecrm/meta/services.yml b/roles/web-app-suitecrm/meta/services.yml index 7847ee0596..68c73b211d 100644 --- a/roles/web-app-suitecrm/meta/services.yml +++ b/roles/web-app-suitecrm/meta/services.yml @@ -49,6 +49,12 @@ suitecrm: version: 8.2-apache custom: true app_version: 8.9.1 + update: + key: app_version + type: git_tags + repository: https://github.com/salesagility/SuiteCRM-Core.git + match: "v" + strip: true name: suitecrm min_storage: 376MB cpus: 1.5 diff --git a/roles/web-app-zammad/meta/services.yml b/roles/web-app-zammad/meta/services.yml index 05b7d3fb46..47ccf4032e 100644 --- a/roles/web-app-zammad/meta/services.yml +++ b/roles/web-app-zammad/meta/services.yml @@ -116,6 +116,9 @@ websocket: search: image: docker.elastic.co/elasticsearch/elasticsearch version: "8.13.4" + update: + type: registry_tags + image: docker.elastic.co/elasticsearch/elasticsearch min_storage: 839MB cpus: "1.0" mem_reservation: 1g diff --git a/roles/web-svc-simpleicons/meta/services.yml b/roles/web-svc-simpleicons/meta/services.yml index 4a12b9ad13..6b12e72620 100644 --- a/roles/web-svc-simpleicons/meta/services.yml +++ b/roles/web-svc-simpleicons/meta/services.yml @@ -42,7 +42,7 @@ simpleicons: image: node version: 26-slim local_image: simpleicons-server - local_version: latest + local_tag: latest min_storage: 612MB cpus: 0.5 mem_reservation: 128m diff --git a/roles/web-svc-simpleicons/templates/compose.yml.j2 b/roles/web-svc-simpleicons/templates/compose.yml.j2 index e86f88c7c3..e6a170b79d 100644 --- a/roles/web-svc-simpleicons/templates/compose.yml.j2 +++ b/roles/web-svc-simpleicons/templates/compose.yml.j2 @@ -6,7 +6,7 @@ SIMPLEICONS_IMAGE: "{{ SIMPLEICONS_IMAGE }}" SIMPLEICONS_VERSION: "{{ SIMPLEICONS_VERSION }}" container_port: "{{ container_port | string }}" - {{ lookup('container_image', application_id, 'simpleicons', image=SIMPLEICONS_LOCAL_IMAGE, version=SIMPLEICONS_LOCAL_VERSION) }} + {{ lookup('container_image', application_id, 'simpleicons', image=SIMPLEICONS_LOCAL_IMAGE, version=SIMPLEICONS_LOCAL_TAG) }} {{ lookup('compose_only', 'container_name', "simpleicons-server") }} {{ lookup('container_ports', ['simpleicons', 'http', DOCKER_BIND_HOST]) | indent(4) }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} diff --git a/roles/web-svc-simpleicons/vars/main.yml b/roles/web-svc-simpleicons/vars/main.yml index 3ce76a329b..e6b0be1a80 100644 --- a/roles/web-svc-simpleicons/vars/main.yml +++ b/roles/web-svc-simpleicons/vars/main.yml @@ -8,4 +8,4 @@ SIMPLEICONS_HOST_PACKAGE_FILE: "{{ [ lookup('container', application_id, 'direct SIMPLEICONS_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" SIMPLEICONS_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" SIMPLEICONS_LOCAL_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.local_image') }}" -SIMPLEICONS_LOCAL_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.local_version') }}" +SIMPLEICONS_LOCAL_TAG: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.local_tag') }}" diff --git a/scripts/github/update/version_sources.sh b/scripts/github/update/version_sources.sh new file mode 100755 index 0000000000..769fb5d27a --- /dev/null +++ b/scripts/github/update/version_sources.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "${SCRIPT_DIR}/../../.." && pwd)" + +cd "${REPO_ROOT}" +make dotenv >/dev/null +set -a +# shellcheck disable=SC1091 +. .env +set +a +python3 -m cli.contributing.update.source "$@" diff --git a/tests/external/update/source/__init__.py b/tests/external/update/source/__init__.py new file mode 100644 index 0000000000..88f288ec1f --- /dev/null +++ b/tests/external/update/source/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/tests/external/update/source/test_version_sources.py b/tests/external/update/source/test_version_sources.py new file mode 100644 index 0000000000..3a40887bf2 --- /dev/null +++ b/tests/external/update/source/test_version_sources.py @@ -0,0 +1,62 @@ +"""Warn about pins whose declared upstream has moved ahead. + +A pin outside the Docker and repository updaters names its upstream in an +``update:`` block of ``roles/*/meta/services.yml``. This test resolves each +declared source and warns when it offers a newer version. + +Counterpart to ``tests/external/update/docker/test_image_versions.py`` and +``tests/external/update/repository/test_repository_versions.py``. The shared +logic lives in :mod:`utils.update.source`; the CI auto-update job at +``.github/workflows/cron-update.yml`` (``update-version-sources``) consumes the +same module to open PRs against ``main``. + +External test: depends on live registry, npm, git and HTTP calls. It always +passes, so normal validation stays stable when an upstream is slow or +unreachable; outdated pins surface as warnings and as GitHub Actions +annotations on the offending line. + +Suppress a check with ``# nocheck: version-source`` on the line above the pin. +""" + +from __future__ import annotations + +import unittest + +from utils.annotations.message import warning +from utils.update.source import collect_entries, find_outdated_updates + +from . import PROJECT_ROOT + + +class TestVersionSources(unittest.TestCase): + """Warn about outdated pins that declare their own upstream source.""" + + def test_declared_version_sources_are_current(self) -> None: + entries = collect_entries(PROJECT_ROOT) + updates = find_outdated_updates(PROJECT_ROOT) + + if updates: + rows = "\n".join( + f"{u.entry.role}/{u.entry.entity}.{u.entry.key}: " + f"{u.entry.current} -> {u.latest} ({u.entry.source.get('type')})" + for u in updates + ) + print( + f"\nāš ļø Outdated version pins:\n{rows}\n" + "\nšŸ’” To suppress a warning add above the pinned key:\n" + " # nocheck: version-source" + ) + for u in updates: + warning( + f"{u.entry.role}/{u.entry.entity}.{u.entry.key} is at " + f"{u.entry.current}, its source offers {u.latest}", + title="Outdated version pin", + file=str(u.entry.config_path.relative_to(PROJECT_ROOT)), + line=u.entry.line, + ) + + self.assertIsNotNone(entries) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_version_keys.py b/tests/lint/ansible/services/test_version_keys.py new file mode 100644 index 0000000000..5c86c9ac8b --- /dev/null +++ b/tests/lint/ansible/services/test_version_keys.py @@ -0,0 +1,87 @@ +"""A version only lives behind a key that says it is one. + +``version`` is the tag of the entity's own image, ``_version`` any other +upstream version it pins, and ``ref`` the git ref of the repository updater. +A semver behind ``release``, ``tag`` or a name invented once is invisible to +the three updaters and to everyone reading the file, which is how pins go +stale unnoticed. + +``update:`` blocks are checked too: a block naming a key the entity does not +carry, or a type the resolver does not know, resolves nothing and says nothing. + +Keys that hold a dotted number without naming a version are listed in +``_NOT_VERSIONS``: the container's ``cpus`` and ``bond`` shares and the +``upstream_host`` address. + +Per-line opt-out: ``# nocheck: version-key`` above the pin, with a reason. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.base import is_semver +from utils.update.source import invalid_declarations + +from . import PROJECT_ROOT + +_RULE = "version-key" +_VALID_KEY = re.compile(r"^(version|[a-z0-9_]+_version|ref)$") +_NOT_VERSIONS = frozenset({"cpus", "bond", "upstream_host"}) + + +def _findings() -> list[str]: + findings: list[str] = [] + for config_path in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + role = config_path.parts[-3] + lines = read_text(str(config_path)).splitlines() + for entity, config in (load_yaml(str(config_path)) or {}).items(): + if not isinstance(config, dict): + continue + for key, value in config.items(): + name, text = str(key), str(value) + if name in _NOT_VERSIONS or _VALID_KEY.match(name): + continue + if "." not in text or not is_semver(text): + continue + number = next( + ( + index + for index, line in enumerate(lines, start=1) + if re.match(rf"^\s+{re.escape(name)}\s*:", line) + ), + 0, + ) + if number and is_suppressed_at(lines, number, _RULE): + continue + findings.append(f"- {role}/{entity}.{name} = {text}") + return sorted(set(findings)) + + +class TestVersionKeys(unittest.TestCase): + def test_a_version_sits_behind_version_or_its_suffix(self) -> None: + findings = _findings() + self.assertEqual( + findings, + [], + "These values look like a version but their key does not say so. " + "Name the key `version` for the entity's own image tag, " + "`_version` for any other upstream version, `_tag` for " + f"a locally built image, or mark it `# nocheck: {_RULE}` with a " + "reason:\n" + "\n".join(findings), + ) + + def test_every_declared_update_source_resolves_a_key_it_knows(self) -> None: + problems = invalid_declarations(PROJECT_ROOT) + self.assertEqual(problems, [], "\n".join(problems)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/test_version_pins_are_watched.py b/tests/lint/repository/test_version_pins_are_watched.py new file mode 100644 index 0000000000..9e3ee644f4 --- /dev/null +++ b/tests/lint/repository/test_version_pins_are_watched.py @@ -0,0 +1,105 @@ +"""Every pinned version in a role is watched by something. + +Three updaters bump pins: the Docker updater (``image`` plus ``version``), the +repository updater (``repository`` plus ``ref``) and the version-source +resolver (an ``update:`` block naming the upstream). A pin outside all three is +frozen silently, and nothing tells the next reader whether that was a decision +or an oversight. + +Scope: every ``roles/*/meta/services.yml`` value whose key names a version and +whose content is a semver. Moving tags (``latest``, ``stable``, a branch name) +are not pins and are ignored. + +Per-line opt-out: ``# nocheck: unwatched-version`` above the pin, with a +reason, for a version that must stay where it is. An existing +``# nocheck: docker-version`` or ``# nocheck: repository-version`` counts as +the same statement: it already says this pin is not to be bumped. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.base import is_semver +from utils.update.docker import collect_entries as docker_entries +from utils.update.repository import collect_entries as repository_entries +from utils.update.source import collect_entries as source_entries + +from . import PROJECT_ROOT + +_RULE = "unwatched-version" +_VERSION_KEY = re.compile(r"(^|_)(version|release|ref|tag)$") + + +def _watched() -> set[tuple[str, str, str]]: + """Return ``(role, entity, key)`` of every pin an updater already bumps.""" + watched = {(e.role, e.service, "version") for e in docker_entries(PROJECT_ROOT)} + watched |= { + (e.role, e.entity_path[-1] if e.entity_path else "", "ref") + for e in repository_entries(PROJECT_ROOT) + } + watched |= {(e.role, e.entity, e.key) for e in source_entries(PROJECT_ROOT)} + return watched + + +def _findings() -> list[str]: + watched = _watched() + findings: list[str] = [] + for config_path in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + role = config_path.parts[-3] + lines = read_text(str(config_path)).splitlines() + for entity, config in (load_yaml(str(config_path)) or {}).items(): + if not isinstance(config, dict): + continue + for key, value in config.items(): + text = str(value) + if not _VERSION_KEY.search(str(key)) or not is_semver(text): + continue + if (role, str(entity), str(key)) in watched: + continue + number = next( + ( + index + for index, line in enumerate(lines, start=1) + if re.match( + rf"^\s+{re.escape(str(key))}\s*:\s*[\"']?{re.escape(text)}", + line, + ) + ), + 0, + ) + if number and any( + is_suppressed_at(lines, number, rule) + for rule in (_RULE, "docker-version", "repository-version") + ): + continue + findings.append(f"- {role}/{entity}.{key} = {text}") + return sorted(set(findings)) + + +class TestVersionPinsAreWatched(unittest.TestCase): + def test_every_semver_pin_is_watched_or_opted_out(self) -> None: + findings = _findings() + self.assertEqual( + findings, + [], + "These versions are pinned but nothing bumps them. Declare the " + "upstream next to the pin:\n\n" + " update:\n" + " key: \n" + " type: git_tags | registry_tags | npm | http_regex | script\n" + " ...\n\n" + f"or mark the pin with `# nocheck: {_RULE}` and a reason.\n\n" + + "\n".join(findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_source.py b/tests/unit/python/utils/update/test_source.py new file mode 100644 index 0000000000..773047bc65 --- /dev/null +++ b/tests/unit/python/utils/update/test_source.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update import source as module + +SERVICES = """\ +--- +app: + image: example + version: "1.2.3" + app_version: 2.0.0 + update: + - key: app_version + type: git_tags + repository: https://example.test/app.git + match: "v" + strip: true + - key: version + type: npm + package: example +frozen: + # nocheck: version-source Reason: stays where it is + app_version: 1.0.0 + update: + key: app_version + type: npm + package: frozen +""" + + +def _repo(services: str = SERVICES) -> Path: + tmp = Path(tempfile.mkdtemp()) + config = tmp / "roles" / "web-app-example" / ROLE_FILE_META_SERVICES + config.parent.mkdir(parents=True) + config.write_text(services, encoding="utf-8") + return tmp + + +class TestCollectEntries(unittest.TestCase): + def test_each_declared_pin_is_collected_and_a_suppressed_one_is_not(self) -> None: + entries = module.collect_entries(_repo()) + + self.assertEqual( + [(e.entity, e.key, e.current, e.source["type"]) for e in entries], + [ + ("app", "app_version", "2.0.0", "git_tags"), + ("app", "version", "1.2.3", "npm"), + ], + ) + self.assertEqual([e.line for e in entries], [5, 4]) + + +class TestCandidates(unittest.TestCase): + def test_match_selects_a_flavour_and_strip_drops_its_prefix(self) -> None: + root = _repo() + entry = next(e for e in module.collect_entries(root) if e.key == "app_version") + + with mock.patch.object( + module, "git_ls_remote_tags", return_value=["v2.1.0", "2.0.5", "nightly"] + ): + self.assertEqual(module.candidates(entry, root), ["2.1.0"]) + + +class TestOutdated(unittest.TestCase): + def _entry(self, root: Path): + return next(e for e in module.collect_entries(root) if e.key == "app_version") + + def test_a_newer_version_is_reported_and_written_to_its_own_line(self) -> None: + root = _repo() + entry = self._entry(root) + + with mock.patch.object(module, "candidates", return_value=["2.1.0"]): + updates = module.outdated([entry], root) + self.assertEqual( + [(u.entry.key, u.latest) for u in updates], [("app_version", "2.1.0")] + ) + + module.apply_updates(updates) + config = root / "roles" / "web-app-example" / ROLE_FILE_META_SERVICES + written = config.read_text() # nocheck: cache-read just rewritten here + self.assertIn("app_version: 2.1.0", written) + self.assertIn('version: "1.2.3"', written) + + def test_an_unchanged_upstream_reports_nothing(self) -> None: + root = _repo() + with mock.patch.object(module, "candidates", return_value=["2.0.0", "1.9.9"]): + self.assertEqual(module.outdated([self._entry(root)], root), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/update/source.py b/utils/update/source.py new file mode 100644 index 0000000000..852cd03736 --- /dev/null +++ b/utils/update/source.py @@ -0,0 +1,341 @@ +"""Resolve version pins that declare their own upstream source. + +The Docker updater watches ``image`` plus ``version``, the repository updater +``repository`` plus ``ref``. A pin outside both - an ``app_version``, a +``release``, a tag in a registry neither updater speaks - declares where its +upstream lives:: + + lmstudio: + app_version: 0.0.25-1 + update: + key: app_version + type: http_regex + url: https://lmstudio.ai/install.sh + pattern: 'APP_VERSION="([0-9][0-9.-]*)"' + +``key`` names the pinned key and defaults to ``version``; an entity with +several pins declares a list of such blocks. The types are +``git_tags`` (repository), ``registry_tags`` (image), ``npm`` (package), +``http_regex`` (url, pattern) and ``script`` (path, run with the current +version and printing the latest one). +""" + +from __future__ import annotations + +import json +import re +import subprocess +import urllib.error +import urllib.request +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any +from urllib.parse import urlencode + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.base import ( + latest_semver, + version_depth, + version_flavor, + version_key, +) +from utils.update.docker import ( + dockerhub_repo, + fetch_dockerhub_tags, + fetch_ghcr_tags, + fetch_mcr_tags, + is_dockerhub, + is_ghcr, + is_mcr, +) +from utils.update.repository import git_ls_remote_tags + +if TYPE_CHECKING: + from collections.abc import Iterable + from pathlib import Path + +NOCHECK_MARKER = "version-source" +UPDATE_KEY = "update" +DEFAULT_KEY = "version" +TIMEOUT_SECONDS = 30 +TYPES = ("git_tags", "registry_tags", "npm", "http_regex", "script") +USER_AGENT = "infinito-nexus-version-source" + + +@dataclass(frozen=True) +class VersionSourceEntry: + role: str + entity: str + key: str + current: str + source: dict[str, Any] + config_path: Path + line: int + + +@dataclass(frozen=True) +class VersionSourceUpdate: + entry: VersionSourceEntry + latest: str + + +def _get(url: str, headers: dict[str, str] | None = None) -> bytes: + request = urllib.request.Request( # noqa: S310 - https URL of a declared version source + url, headers={"User-Agent": USER_AGENT, **(headers or {})} + ) + with urllib.request.urlopen( # noqa: S310 - https URL of a declared version source + request, timeout=TIMEOUT_SECONDS + ) as response: + return response.read() + + +def dockerhub_named_tags(image: str, match: str) -> list[str]: + """Return the Docker Hub tags of *image* whose name contains *match*. + + Args: + image: Docker Hub reference. + match: substring the registry filters on, reaching tags beyond the + first pages of the unfiltered listing. + """ + query = urlencode({"name": match, "page_size": 100}) + url = f"https://hub.docker.com/v2/repositories/{dockerhub_repo(image)}/tags?{query}" + try: + payload = json.loads(_get(url)) + except (OSError, ValueError): + return [] + return [str(result["name"]) for result in payload.get("results") or []] + + +def registry_v2_tags(image: str, match: str = "") -> list[str]: + """Return the tags of *image* from its registry's v2 API. + + Args: + image: reference including the registry host, e.g. + ``gcr.io/cadvisor/cadvisor``. + match: when set and the registry can filter server-side, the + substring every returned tag carries. + """ + if is_dockerhub(image): + return ( + dockerhub_named_tags(image, match) if match else fetch_dockerhub_tags(image) + ) + if is_ghcr(image): + return fetch_ghcr_tags(image) + if is_mcr(image): + return fetch_mcr_tags(image) + host, _, repository = image.partition("/") + url = f"https://{host}/v2/{repository}/tags/list" + try: + return list(json.loads(_get(url)).get("tags") or []) + except urllib.error.HTTPError as error: + if error.code != 401: + return [] + challenge = error.headers.get("WWW-Authenticate", "") + except (OSError, ValueError): + return [] + fields = dict(re.findall(r'(\w+)="([^"]*)"', challenge)) + realm = fields.pop("realm", "") + if not realm: + return [] + query = "&".join(f"{name}={value}" for name, value in fields.items()) + try: + token = json.loads(_get(f"{realm}?{query}")).get("token", "") + payload = _get(url, {"Authorization": f"Bearer {token}"}) + return list(json.loads(payload).get("tags") or []) + except (OSError, ValueError): + return [] + + +def npm_versions(package: str) -> list[str]: + """Return every published version of an npm *package*.""" + try: + payload = json.loads(_get(f"https://registry.npmjs.org/{package}")) + except (OSError, ValueError): + return [] + return list((payload.get("versions") or {}).keys()) + + +def http_regex_versions(url: str, pattern: str) -> list[str]: + """Return every capture of *pattern* in the body of *url*.""" + try: + body = _get(url).decode("utf-8", "replace") + except OSError: + return [] + return [match.group(1) for match in re.finditer(pattern, body)] + + +def script_versions(repo_root: Path, role: str, path: str, current: str) -> list[str]: + """Return what a role-local updater prints for its pin. + + Args: + repo_root: repository root. + role: role the script belongs to. + path: role-relative path of the script. + current: the version currently pinned, passed as the first argument. + """ + script = repo_root / "roles" / role / path + try: + proc = subprocess.run( + [str(script), current], + capture_output=True, + text=True, + timeout=TIMEOUT_SECONDS, + check=False, + ) + except (OSError, subprocess.TimeoutExpired): + return [] + return proc.stdout.split() if proc.returncode == 0 else [] + + +def candidates(entry: VersionSourceEntry, repo_root: Path) -> list[str]: + """Return every upstream version the entry's declared source offers. + + ``match`` keeps only the versions carrying that prefix, and ``strip`` + removes it again, so a pin without the upstream's ``v`` stays without it. + """ + source = entry.source + kind = source.get("type") + match = str(source.get("match", "")) + if kind == "git_tags": + found = git_ls_remote_tags(str(source["repository"])) + elif kind == "registry_tags": + found = registry_v2_tags(str(source["image"]), match) + elif kind == "npm": + found = npm_versions(str(source["package"])) + elif kind == "http_regex": + found = http_regex_versions(str(source["url"]), str(source["pattern"])) + elif kind == "script": + found = script_versions( + repo_root, entry.role, str(source["path"]), entry.current + ) + else: + return [] + if match: + found = [version for version in found if version.startswith(match)] + if source.get("strip"): + found = [version.removeprefix(match) for version in found] + return found + + +def _key_line(lines: list[str], entity: str, key: str) -> int | None: + """Return the 1-indexed line of ``key`` inside the block of ``entity``.""" + inside = False + for number, line in enumerate(lines, start=1): + if re.match(rf"^{re.escape(entity)}\s*:", line): + inside = True + continue + if inside and line and not line[0].isspace(): + inside = False + if inside and re.match(rf"^\s+{re.escape(key)}\s*:", line): + return number + return None + + +def invalid_declarations(repo_root: Path) -> list[str]: + """Return one message per ``update:`` block that cannot be resolved. + + A block naming a key the entity does not carry, or a type the resolver + does not know, would otherwise pin nothing and say nothing. + + Args: + repo_root: repository root. + """ + problems: list[str] = [] + for config_path in sorted( + (repo_root / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + role = config_path.parts[-3] + for entity, config in (load_yaml(str(config_path)) or {}).items(): + declared = config.get(UPDATE_KEY) if isinstance(config, dict) else None + if declared is None: + continue + sources = declared if isinstance(declared, list) else [declared] + for source in sources: + if not isinstance(source, dict): + problems.append(f"{role}/{entity}: update entry is not a mapping") + continue + key = str(source.get("key", DEFAULT_KEY)) + if key not in config: + problems.append( + f"{role}/{entity}: update.key '{key}' names no key of the entity" + ) + if source.get("type") not in TYPES: + problems.append( + f"{role}/{entity}.{key}: unknown update.type " + f"'{source.get('type')}', expected one of {', '.join(TYPES)}" + ) + return problems + + +def collect_entries(repo_root: Path) -> list[VersionSourceEntry]: + """Return every declared version source that is not suppressed.""" + entries: list[VersionSourceEntry] = [] + for config_path in sorted( + (repo_root / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + role = config_path.parts[-3] + lines = read_text(str(config_path)).splitlines() + for entity, config in (load_yaml(str(config_path)) or {}).items(): + declared = config.get(UPDATE_KEY) if isinstance(config, dict) else None + sources = declared if isinstance(declared, list) else [declared] + for source in sources: + if not isinstance(source, dict): + continue + key = str(source.get("key", DEFAULT_KEY)) + current = str(config.get(key, "")).strip() + line = _key_line(lines, str(entity), key) + if not current or line is None: + continue + if is_suppressed_at(lines, line, NOCHECK_MARKER): + continue + entries.append( + VersionSourceEntry( + role=role, + entity=str(entity), + key=key, + current=current, + source=source, + config_path=config_path, + line=line, + ) + ) + return entries + + +def outdated( + entries: Iterable[VersionSourceEntry], repo_root: Path +) -> list[VersionSourceUpdate]: + """Return one update per entry whose source offers a newer version.""" + updates: list[VersionSourceUpdate] = [] + for entry in entries: + newest = latest_semver( + candidates(entry, repo_root), + version_depth(entry.current), + version_flavor(entry.current), + ) + if newest and version_key(entry.current) < version_key(newest): + updates.append(VersionSourceUpdate(entry=entry, latest=newest)) + return updates + + +def find_outdated_updates(repo_root: Path) -> list[VersionSourceUpdate]: + """Return every declared source that moved ahead of its pin.""" + return outdated(collect_entries(repo_root), repo_root) + + +def apply_updates(updates: Iterable[VersionSourceUpdate]) -> list[Path]: + """Rewrite every pin to its newer version and return the changed files.""" + changed: list[Path] = [] + for update in updates: + path = update.entry.config_path + lines = path.read_text( # nocheck: cache-read read-modify-write: a cached read serves the pre-write content when two pins of one file are bumped in the same run + encoding="utf-8" + ).splitlines(keepends=True) + index = update.entry.line - 1 + lines[index] = lines[index].replace(update.entry.current, update.latest, 1) + path.write_text("".join(lines), encoding="utf-8") + if path not in changed: + changed.append(path) + return changed