mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-29 06:17:25 +00:00
Merge remote-tracking branch 'origin/main' into update/docker-image-versions-web-app-nextcloud-20261002-798c076
This commit is contained in:
commit
2b28d1e164
67 files changed
+1920
-63
No files matched your search
@@ -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` or `roles/*/meta/addons/*.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'
|
||||
|
||||
@@ -1,3 +1,77 @@
|
||||
# Update 🔄
|
||||
|
||||
Repository-side version maintenance: scan role configuration files for declared upstream versions and bump them in lockstep with new releases.
|
||||
|
||||
## Scope
|
||||
|
||||
Every role-scoped updater (`docker`, `source`, `pip`, `repository`) and the addon check skip a role whose [lifecycle](../../../docs/contributing/design/role/services/lifecycle.md) is `eol`: no update PR is opened for it and no external test warns about its pins.
|
||||
|
||||
## 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
|
||||
stalwart:
|
||||
webui_version: "v1.0.5"
|
||||
update:
|
||||
key: webui_version
|
||||
type: git_tags
|
||||
repository: https://github.com/stalwartlabs/webui.git
|
||||
```
|
||||
|
||||
`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.
|
||||
|
||||
The pinned value is a semver such as `v1.0.5`, `26.04.4.2.1` or `2.4.0p32`. A
|
||||
moving tag behind an `update:` block, or as the `version` of a monitored addon,
|
||||
fails `tests/lint/ansible/services/test_version_keys.py`.
|
||||
|
||||
An addon pins its version at the root of `meta/addons/<id>.yml` and declares
|
||||
the same fields in its `update:` block, beside `monitored`, `catalog` and
|
||||
`upstream_id`:
|
||||
|
||||
```yaml
|
||||
version: "9.15.7"
|
||||
update:
|
||||
type: http_regex
|
||||
url: https://maven.xwiki.org/releases/org/xwiki/contrib/ldap/ldap-authenticator/maven-metadata.xml
|
||||
pattern: '<version>([0-9][0-9.]*)</version>'
|
||||
```
|
||||
|
||||
A monitored addon of the `github-releases` catalog omits `type`. Its
|
||||
`upstream_id` is the `owner/repository` whose tags are its versions:
|
||||
|
||||
```yaml
|
||||
version: "v10.2.1"
|
||||
update:
|
||||
monitored: true
|
||||
catalog: github-releases
|
||||
upstream_id: ONLYOFFICE/onlyoffice-nextcloud
|
||||
```
|
||||
|
||||
An addon's `config.archive` stays a literal URL that carries the pinned version:
|
||||
|
||||
```yaml
|
||||
config:
|
||||
archive: "https://github.com/ONLYOFFICE/onlyoffice-nextcloud/releases/download/v10.2.1/onlyoffice.tar.gz"
|
||||
```
|
||||
|
||||
The updater rewrites both lines together. A URL that does not carry the pin
|
||||
fails `tests/lint/ansible/services/test_version_keys.py`.
|
||||
|
||||
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.
|
||||
@@ -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]
|
||||
Executable
+62
@@ -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 or roles/*/meta/addons/*.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())
|
||||
@@ -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:`. |
|
||||
|
||||
@@ -432,7 +432,7 @@ config: {} # optional, opaque, role-interpreted runtime payload
|
||||
| `bridges` | no | list | — | Non-empty list of in-repo service keys; each MUST resolve to a service block in the same role's `meta/services.yml`. Omit when there is no cross-role dependency. |
|
||||
| `version` | no | string | `""` | A pin MUST be a quoted string, never an unquoted number. `""` tracks the app default. |
|
||||
| `group` | no | string | — | Free grouping label (e.g. Odoo `core`/`optional`). MUST NOT affect enablement. |
|
||||
| `update` | no | map | — | `monitored` (bool, default `false`), `catalog` (a supported adapter), `upstream_id` (defaults to the addon id). |
|
||||
| `update` | no | map | — | `monitored` (bool, default `false`), `catalog` (a supported adapter), `upstream_id` (defaults to the addon id). A `version` pin MUST also name its version source here, or carry `# nocheck: unwatched-version` with a reason: either `type` with its fields, or `monitored: true` with `catalog: github-releases` and the `owner/repository` as `upstream_id`. See [Declared version sources](../../../../../cli/contributing/update/README.md#declared-version-sources). |
|
||||
| `config` | no | map | — | Opaque, role-interpreted runtime payload. Lint does not constrain its inner shape beyond requiring a mapping. Secrets inside `config` MUST resolve through `lookup('config', application_id, 'secrets.credentials.<name>')` and MUST NOT be inlined literally. |
|
||||
|
||||
Any credential an addon needs is declared in `meta/secrets.yml` `credentials:`
|
||||
|
||||
@@ -112,6 +112,7 @@ A role tagged `eol`:
|
||||
- MUST clearly state in its `README.md` that the project does not maintain or test it and that operators use it at their own risk.
|
||||
- SHOULD link to the upstream project / vendor for support.
|
||||
- MUST NOT block any release. CI MAY skip its deploy matrix entry entirely.
|
||||
- Is skipped by the version updaters: no update PR bumps its image versions, refs or pins (see [cli/contributing/update](../../../../../cli/contributing/update/README.md)).
|
||||
- MAY be removed without a deprecation cycle.
|
||||
|
||||
## The tested envelope 🧪
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -39,8 +39,38 @@ $STATUS_OUT
|
||||
|
||||
ERRMAIL
|
||||
|
||||
timeout "{{ email.timeout }}s" "$sendmail_bin" -t < "$mail_tmp"
|
||||
rc=$?
|
||||
attempts=3
|
||||
delay=10
|
||||
|
||||
for attempt in $(seq 1 "${attempts}"); do
|
||||
send_err="$(timeout "{{ email.timeout }}s" "$sendmail_bin" -t < "$mail_tmp" 2>&1 1>/dev/null)"
|
||||
rc=$?
|
||||
[ "$rc" -eq 0 ] && exit 0
|
||||
|
||||
case "$rc" in
|
||||
69 | 75 | 124 | 137) ;;
|
||||
76)
|
||||
case "$send_err" in
|
||||
*"the server sent an empty reply"*) ;;
|
||||
*) break ;;
|
||||
esac
|
||||
;;
|
||||
77)
|
||||
case "$send_err" in
|
||||
*"server message: 4"* | *"Temporary authentication failure"*) ;;
|
||||
*) break ;;
|
||||
esac
|
||||
;;
|
||||
*) break ;;
|
||||
esac
|
||||
|
||||
if [ "$attempt" -lt "$attempts" ]; then
|
||||
echo "sendmail transient failure (rc=${rc}), attempt ${attempt}/${attempts}; retrying in ${delay}s" >&2
|
||||
sleep "$delay"
|
||||
fi
|
||||
done
|
||||
|
||||
[ -n "$send_err" ] && echo "$send_err" >&2
|
||||
|
||||
if [ "$rc" -eq 124 ] || [ "$rc" -eq 137 ]; then
|
||||
echo "ERROR: sendmail timed out after {{ email.timeout }}s" >&2
|
||||
|
||||
@@ -21,6 +21,12 @@ for attempt in $(seq 1 "${attempts}"); do
|
||||
|
||||
case "${rc}" in
|
||||
69 | 75 | 124) ;;
|
||||
76)
|
||||
case "${msmtp_err}" in
|
||||
*"the server sent an empty reply"*) ;;
|
||||
*) exit "${rc}" ;;
|
||||
esac
|
||||
;;
|
||||
77)
|
||||
case "${msmtp_err}" in
|
||||
*"server message: 4"* | *"Temporary authentication failure"*) ;;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -3,6 +3,7 @@ enabled: "{{ lookup('config', 'web-app-jellyfin', 'services.ldap.enabled') | boo
|
||||
required: false
|
||||
mechanism: plugin
|
||||
source: upstream
|
||||
# nocheck: unwatched-version Reason: the pin is bound to config.tag, config.url and the md5 of that release archive, which a version bump alone cannot follow
|
||||
version: "23.0.0.0"
|
||||
update:
|
||||
monitored: true
|
||||
|
||||
@@ -8,6 +8,8 @@ update:
|
||||
monitored: true
|
||||
catalog: github-releases
|
||||
upstream_id: 9p4/jellyfin-plugin-sso
|
||||
match: "v"
|
||||
strip: true
|
||||
config:
|
||||
tag: "manifest-release"
|
||||
manifest: "https://raw.githubusercontent.com/9p4/jellyfin-plugin-sso/manifest-release/manifest.json"
|
||||
|
||||
@@ -3,6 +3,7 @@ enabled: "{{ lookup('config', 'web-app-joomla', 'services.sso.enabled') | bool }
|
||||
required: false
|
||||
mechanism: plugin
|
||||
source: built
|
||||
# nocheck: unwatched-version Reason: the plugin is built in this repository from files/joomla-oidc-plugin, so the version is ours and has no upstream
|
||||
version: "1.0.0"
|
||||
bridges:
|
||||
- sso
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# TODO
|
||||
|
||||
- Drop the custom image build once the pinned Mobilizon release ships the PostgreSQL 18 migration fix (upstream merge request 1683, milestone 5.3.0). The build of `files/Dockerfile` fails on that release and names the migration that no longer needs the patch. Then delete `files/Dockerfile`, the `build` block in `templates/compose.yml.j2`, `MOBILIZON_IMAGE` and `MOBILIZON_VERSION` in `vars/main.yml`, and `custom: true` in `meta/services.yml`.
|
||||
@@ -0,0 +1,18 @@
|
||||
ARG MOBILIZON_IMAGE
|
||||
ARG MOBILIZON_VERSION
|
||||
FROM ${MOBILIZON_IMAGE}:${MOBILIZON_VERSION}
|
||||
|
||||
RUN set -eu; \
|
||||
cd /lib/mobilizon-*/priv/repo/migrations; \
|
||||
for migration in \
|
||||
20190806131306_add_url_to_follows_and_move_to_uuid.exs \
|
||||
20190813160207_add_url_and_uuid_to_participants.exs \
|
||||
20200218170232_move_member_id_to_uuid.exs \
|
||||
20200721131521_add_url_to_conversation.exs; \
|
||||
do \
|
||||
if ! grep -q 'add(:id, :uuid, primary_key: true)$' "${migration}"; then \
|
||||
echo "${migration} no longer contains 'add(:id, :uuid, primary_key: true)': the base image ships the PostgreSQL 18 migration fix (framagit.org/kaihuri/mobilizon merge request 1683). Drop this Dockerfile and the custom build of web-app-mobilizon." >&2; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
sed -i 's/add(:id, :uuid, primary_key: true)$/add(:id, :uuid, primary_key: true, null: false)/' "${migration}"; \
|
||||
done
|
||||
@@ -40,6 +40,7 @@ mobilizon:
|
||||
image: docker.io/kaihuri/mobilizon
|
||||
name: mobilizon
|
||||
version: 5.2.4
|
||||
custom: true
|
||||
min_storage: 825MB
|
||||
titel: Mobilizon on {{ DOMAIN_PRIMARY | upper }}
|
||||
ports:
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
{% include 'roles/sys-svc-compose/templates/base.yml.j2' %}
|
||||
{% set service_name = 'mobilizon' %}
|
||||
{{ service_name }}:
|
||||
{{ lookup('template', 'roles/sys-svc-container/templates/build.yml.j2') | indent(4) }}
|
||||
args:
|
||||
MOBILIZON_IMAGE: "{{ MOBILIZON_IMAGE }}"
|
||||
MOBILIZON_VERSION: "{{ MOBILIZON_VERSION }}"
|
||||
{{ lookup('container_image', application_id, 'mobilizon') }}
|
||||
{{ lookup('compose_only', 'container_name', mobilizon_container) }}
|
||||
{{ lookup('container_volumes', service_name) | indent(4) }}
|
||||
|
||||
@@ -4,4 +4,6 @@ container_port: "{{ lookup('config', application_id, 'services.mobilizon.ports.i
|
||||
|
||||
mobilizon_host_conf_exs_file: "{{ [ lookup('container', application_id, 'directories.config'), 'config.exs' ] | path_join }}"
|
||||
mobilizon_container: "{{ lookup('config', application_id, 'services.mobilizon.name') }}"
|
||||
MOBILIZON_IMAGE: "{{ lookup('config', application_id, 'services.mobilizon.image') }}"
|
||||
MOBILIZON_VERSION: "{{ lookup('config', application_id, 'services.mobilizon.version') }}"
|
||||
MOBILIZON_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}"
|
||||
@@ -10,3 +10,4 @@ update:
|
||||
monitored: true
|
||||
catalog: github-releases
|
||||
upstream_id: microsoft/moodle-auth_oidc
|
||||
match: "v4.5."
|
||||
@@ -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"
|
||||
|
||||
@@ -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') }}"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -5,12 +5,13 @@ mechanism: plugin
|
||||
source: upstream
|
||||
bridges:
|
||||
- onlyoffice
|
||||
version: "v10.2.1"
|
||||
update:
|
||||
monitored: true
|
||||
catalog: nextcloud-appstore
|
||||
upstream_id: onlyoffice
|
||||
catalog: github-releases
|
||||
upstream_id: ONLYOFFICE/onlyoffice-nextcloud
|
||||
config:
|
||||
archive: "https://github.com/ONLYOFFICE/onlyoffice-nextcloud/releases/download/v10.1.2/onlyoffice.tar.gz"
|
||||
archive: "https://github.com/ONLYOFFICE/onlyoffice-nextcloud/releases/download/v10.2.1/onlyoffice.tar.gz"
|
||||
incompatible_plugins:
|
||||
- richdocuments
|
||||
- fileslibreofficeedit
|
||||
|
||||
@@ -4,5 +4,9 @@ required: false
|
||||
mechanism: plugin
|
||||
source: built
|
||||
version: "2.3.1"
|
||||
update:
|
||||
type: http_regex
|
||||
url: https://pypi.org/simple/pretix-oidc/
|
||||
pattern: "pretix[_-]oidc-([0-9][0-9.]*)\\.tar\\.gz"
|
||||
bridges:
|
||||
- sso
|
||||
@@ -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
|
||||
|
||||
@@ -13,7 +13,7 @@ socialhome:
|
||||
# nocheck: default-placement-manager embedded sqlite in a node-local volume; no clustered storage
|
||||
placement: manager
|
||||
image: ghcr.io/social-home-io/socialhome
|
||||
version: "2026.10.2"
|
||||
version: "2026.10.4"
|
||||
ports:
|
||||
local:
|
||||
http: 8089
|
||||
|
||||
@@ -182,8 +182,9 @@ account (or the Keycloak SSO token when SSO is enabled).
|
||||
it from GitHub on first boot, which fails behind restricted egress; the
|
||||
controller downloads it into a host-level cache (matrix rounds purge the
|
||||
instance dir, and per-round downloads hit GitHub rate limits) and bind-mounts
|
||||
it read-only. `webui_version` in `meta/services.yml` MUST be bumped together
|
||||
with the Stalwart `version`.
|
||||
it read-only. The `update:` block next to `webui_version` in
|
||||
`meta/services.yml` names the upstream tags, so the version-source updater
|
||||
bumps the bundle on its own.
|
||||
- **The embedded PostgreSQL pins the plain `postgres` image** — the platform's
|
||||
postgis default defeats baudolo's substring database detection and would
|
||||
degrade backups to torn live-file snapshots. `backup.project_hard_restart`
|
||||
|
||||
@@ -43,8 +43,12 @@ stalwart:
|
||||
# nocheck: default-placement-manager mail edge at a known IP: MX A-record, PTR and SPF bind to the stack host IP (a floating task's egress IP breaks deliverability); the mail store is NFS-hostile and IS the app — same rationale as web-app-mailu
|
||||
placement: manager
|
||||
image: stalwartlabs/stalwart
|
||||
version: "v0.16.24"
|
||||
version: "v0.16.25"
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -6,6 +6,10 @@ source: upstream
|
||||
bridges:
|
||||
- litellm
|
||||
version: "0.7"
|
||||
update:
|
||||
type: http_regex
|
||||
url: https://maven.xwiki.org/releases/org/xwiki/contrib/llm/application-ai-llm-models-ui/maven-metadata.xml
|
||||
pattern: "<version>([0-9][0-9.]*)</version>"
|
||||
group: ai-llm
|
||||
config:
|
||||
id: org.xwiki.contrib.llm:application-ai-llm-models-ui
|
||||
@@ -6,6 +6,10 @@ source: upstream
|
||||
bridges:
|
||||
- ldap
|
||||
version: "9.15.7"
|
||||
update:
|
||||
type: http_regex
|
||||
url: https://maven.xwiki.org/releases/org/xwiki/contrib/ldap/ldap-authenticator/maven-metadata.xml
|
||||
pattern: "<version>([0-9][0-9.]*)</version>"
|
||||
group: ldap
|
||||
config:
|
||||
id: org.xwiki.contrib.ldap:ldap-authenticator
|
||||
@@ -6,6 +6,10 @@ source: upstream
|
||||
bridges:
|
||||
- sso
|
||||
version: "2.19.6"
|
||||
update:
|
||||
type: http_regex
|
||||
url: https://maven.xwiki.org/releases/org/xwiki/contrib/oidc/oidc-authenticator/maven-metadata.xml
|
||||
pattern: "<version>([0-9][0-9.]*)</version>"
|
||||
group: oidc
|
||||
config:
|
||||
id: org.xwiki.contrib.oidc:oidc-authenticator
|
||||
@@ -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
|
||||
|
||||
@@ -13,8 +13,7 @@ redis:
|
||||
shared: "{{ 'svc-db-redis' in group_names }}"
|
||||
collabora:
|
||||
healthcheck:
|
||||
flavor: tcp
|
||||
path: hosting/discovery
|
||||
test: ["CMD", "/usr/bin/coolwsd", "--probe", "--use-env-vars"]
|
||||
modes:
|
||||
compose:
|
||||
enabled: true
|
||||
@@ -26,11 +25,7 @@ collabora:
|
||||
enabled: true
|
||||
shared: true
|
||||
image: collabora/code
|
||||
# TODO: 26.04.2.2.1 rebuilt the image as a Nix minimal image without
|
||||
# coolconfig or a shell (CollaboraOnline/online#16021) — every `docker exec`
|
||||
# fails. Unpin once the systemplate tasks are migrated to --use-env-vars
|
||||
# configuration or upstream restores the tooling.
|
||||
version: "26.04.2.1.1"
|
||||
version: "26.04.4.2.1"
|
||||
name: collabora
|
||||
min_storage: 734MB
|
||||
cpus: 2
|
||||
|
||||
@@ -10,19 +10,3 @@
|
||||
compose_repository_pull: false
|
||||
webserver_vhost_flavour: "basic"
|
||||
application_id: "web-svc-collabora"
|
||||
|
||||
- name: "🖥️ Collabora stack-host-only coolconfig setup"
|
||||
when: IS_STACK_HOST | bool
|
||||
block:
|
||||
- name: "🔍 Resolve collabora hosting node + container id"
|
||||
ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}"
|
||||
vars:
|
||||
resolve_service_key: collabora
|
||||
resolve_output_prefix: COLLABORA
|
||||
resolve_compose_cid: "{{ COLLABORA_CONTAINER_ADDRESS }}"
|
||||
|
||||
- name: "🔧 Run collabora coolconfig on the hosting node"
|
||||
ansible.builtin.include_tasks:
|
||||
file: 01_coolconfig.yml
|
||||
apply:
|
||||
delegate_to: "{{ COLLABORA_HOST_NODE }}"
|
||||
@@ -1,12 +0,0 @@
|
||||
---
|
||||
- name: 🔄 Update Collabora systemplate to include new fonts
|
||||
shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node
|
||||
container exec {{ COLLABORA_LOCAL_CID | quote }} coolconfig update-system-template
|
||||
register: collabora_fonts
|
||||
changed_when: "'updated' in collabora_fonts.stdout"
|
||||
|
||||
- name: 🖥️ Allow Nextcloud host IP for Collabora preview conversion
|
||||
shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node
|
||||
container exec {{ COLLABORA_LOCAL_CID | quote }} coolconfig set net.post_allow.host {{ networks.internet.ip4 }}
|
||||
register: collabora_preview
|
||||
changed_when: "'already present' not in collabora_preview.stdout"
|
||||
@@ -1,4 +1,4 @@
|
||||
{% include 'roles/sys-svc-container/templates/env.j2' %}
|
||||
|
||||
domain={{ COLLABORA_ALLOWED_DOMAINS }}
|
||||
extra_params=--o:ssl.enable=false --o:ssl.termination=true --o:net.service_root=/ --o:net.wopi_allowed_hosts={{ COLLABORA_ALLOWED_HOSTS }}
|
||||
extra_params=--o:ssl.enable=false --o:ssl.termination=true --o:net.service_root=/ --o:net.wopi_allowed_hosts={{ COLLABORA_ALLOWED_HOSTS }} --o:net.post_allow.host[99]={{ networks.internet.ip4 }}/32
|
||||
@@ -6,7 +6,6 @@ domain: "{{ lookup('domain',application_id) }}"
|
||||
http_port: "{{ lookup('config', application_id, 'services.collabora.ports.local.http') }}"
|
||||
|
||||
COLLABORA_CONTAINER: "{{ lookup('config', application_id, 'services.collabora.name') }}"
|
||||
COLLABORA_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}"
|
||||
COLLABORA_ALLOWED_DOMAINS: "(.*\\.|){{ DOMAIN_PRIMARY | regex_replace('\\.', '\\\\.') }}"
|
||||
COLLABORA_ALLOWED_HOSTS: "{{ lookup('domain','web-app-nextcloud') }}"
|
||||
COLLABORA_DISCOVERY_PATH: "/hosting/discovery"
|
||||
@@ -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
|
||||
|
||||
@@ -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' %}
|
||||
|
||||
@@ -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') }}"
|
||||
Executable
+13
@@ -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 "$@"
|
||||
@@ -25,6 +25,8 @@ pr_updated_at="${PR_UPDATED_AT:-}"
|
||||
pr_updated_at_floor=""
|
||||
last_run_state=""
|
||||
last_run_id=""
|
||||
lookup_failure_limit=30
|
||||
lookup_failures=0
|
||||
|
||||
if [[ -n "${pr_updated_at}" ]]; then
|
||||
if ! pr_updated_at_floor="$(date -u -d "${pr_updated_at} - 300 seconds" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null)"; then
|
||||
@@ -56,9 +58,15 @@ build_image_refs() {
|
||||
mapfile -t image_refs < <(build_image_refs)
|
||||
|
||||
find_matching_run() {
|
||||
local query="event=${TARGET_EVENT}&per_page=100"
|
||||
|
||||
if [[ -n "${pr_head_sha}" ]]; then
|
||||
query+="&head_sha=${pr_head_sha}"
|
||||
fi
|
||||
|
||||
gh api --paginate \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
"/repos/${GITHUB_REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?event=${TARGET_EVENT}&per_page=100" |
|
||||
"/repos/${GITHUB_REPOSITORY}/actions/workflows/${WORKFLOW_FILE}/runs?${query}" |
|
||||
jq -sc \
|
||||
--argjson pr_number "${PR_NUMBER}" \
|
||||
--arg pr_head_sha "${pr_head_sha}" \
|
||||
@@ -66,10 +74,14 @@ find_matching_run() {
|
||||
[
|
||||
.[]
|
||||
| .workflow_runs[]?
|
||||
| select(any(.pull_requests[]?;
|
||||
(.number // -1) == $pr_number
|
||||
and ($pr_head_sha == "" or (.head.sha // $pr_head_sha) == $pr_head_sha)
|
||||
))
|
||||
| select(
|
||||
if $pr_head_sha != "" then
|
||||
(.head_sha // "") == $pr_head_sha
|
||||
and ((.display_title // "") | test("PR #\($pr_number)( |$)"))
|
||||
else
|
||||
any(.pull_requests[]?; (.number // -1) == $pr_number)
|
||||
end
|
||||
)
|
||||
| select($pr_updated_at_floor == "" or .created_at >= $pr_updated_at_floor)
|
||||
]
|
||||
| sort_by(.created_at)
|
||||
@@ -105,7 +117,18 @@ for attempt in $(seq 1 "${WAIT_ATTEMPTS}"); do
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run_json="$(find_matching_run)"
|
||||
if run_json="$(find_matching_run)"; then
|
||||
lookup_failures=0
|
||||
else
|
||||
lookup_failures=$((lookup_failures + 1))
|
||||
if [[ "${lookup_failures}" -ge "${lookup_failure_limit}" ]]; then
|
||||
echo "The lookup of the privileged workflow run failed ${lookup_failures} times in a row." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "[${attempt}/${WAIT_ATTEMPTS}] Lookup of the privileged workflow run failed (${lookup_failures}/${lookup_failure_limit}). Waiting ${WAIT_SLEEP_SECONDS}s..."
|
||||
sleep "${WAIT_SLEEP_SECONDS}"
|
||||
continue
|
||||
fi
|
||||
|
||||
if [[ -n "${run_json}" && "${run_json}" != "null" ]]; then
|
||||
run_id="$(jq -r '.id' <<<"${run_json}")"
|
||||
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT: Path = Path(__file__).resolve().parents[4]
|
||||
@@ -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()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""A version only lives behind a key that says it is one.
|
||||
|
||||
``version`` is the tag of the entity's own image, ``<what>_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, a type the resolver does not know, or a pin that is not a semver moves
|
||||
nothing and says nothing. The updaters order upstream versions by semver, so a
|
||||
moving tag behind an ``update:`` block, or as the ``version`` of a monitored
|
||||
addon, fails.
|
||||
|
||||
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, "
|
||||
"`<what>_version` for any other upstream version, `<what>_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_can_move_a_semver_pin(self) -> None:
|
||||
problems = invalid_declarations(PROJECT_ROOT)
|
||||
self.assertEqual(problems, [], "\n".join(problems))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""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 value in ``roles/*/meta/services.yml`` and at the root of
|
||||
``roles/*/meta/addons/*.yml`` whose key names a version and whose content is a
|
||||
semver. Moving tags (``latest``, ``stable``, a branch name) are not pins and
|
||||
are ignored. So is every pin of an ``eol`` role: the updaters skip those roles,
|
||||
and the lifecycle already says nobody bumps them.
|
||||
|
||||
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.addons import iter_addon_files
|
||||
from utils.update.base import is_maintained, 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"
|
||||
_OPT_OUTS = (_RULE, "docker-version", "repository-version")
|
||||
_VERSION_KEY = re.compile(r"(^|_)(version|release|ref|tag)$")
|
||||
|
||||
|
||||
def _addon_label(addon_id: str) -> str:
|
||||
return f"addons/{addon_id}"
|
||||
|
||||
|
||||
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, _addon_label(e.entity) if e.addon else e.entity, e.key)
|
||||
for e in source_entries(PROJECT_ROOT)
|
||||
}
|
||||
return watched
|
||||
|
||||
|
||||
def _addon_findings(watched: set[tuple[str, str, str]]) -> list[str]:
|
||||
findings: list[str] = []
|
||||
for role, addon_path in iter_addon_files(PROJECT_ROOT / "roles"):
|
||||
if not is_maintained(PROJECT_ROOT / "roles", role):
|
||||
continue
|
||||
spec = load_yaml(str(addon_path))
|
||||
if not isinstance(spec, dict):
|
||||
continue
|
||||
label = _addon_label(addon_path.stem)
|
||||
lines = read_text(str(addon_path)).splitlines()
|
||||
for key, value in spec.items():
|
||||
text = str(value)
|
||||
if not _VERSION_KEY.search(str(key)) or not is_semver(text):
|
||||
continue
|
||||
if (role, label, str(key)) in watched:
|
||||
continue
|
||||
number = next(
|
||||
(
|
||||
index
|
||||
for index, line in enumerate(lines, start=1)
|
||||
if re.match(rf"^{re.escape(str(key))}\s*:", line)
|
||||
),
|
||||
0,
|
||||
)
|
||||
if number and any(
|
||||
is_suppressed_at(lines, number, rule) for rule in _OPT_OUTS
|
||||
):
|
||||
continue
|
||||
findings.append(f"- {role}/{label}.{key} = {text}")
|
||||
return findings
|
||||
|
||||
|
||||
def _findings() -> list[str]:
|
||||
watched = _watched()
|
||||
findings: list[str] = _addon_findings(watched)
|
||||
for config_path in sorted(
|
||||
(PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}")
|
||||
):
|
||||
role = config_path.parts[-3]
|
||||
if not is_maintained(PROJECT_ROOT / "roles", role):
|
||||
continue
|
||||
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 _OPT_OUTS
|
||||
):
|
||||
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: <the pinned key, omit for version>\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()
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,123 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape
|
||||
|
||||
from utils import PROJECT_ROOT
|
||||
|
||||
TEMPLATE_DIR = PROJECT_ROOT / "roles/sys-ctl-alm-email/templates"
|
||||
|
||||
EMPTY_REPLY = "sendmail: the server sent an empty reply"
|
||||
|
||||
SENDMAIL_STUB = """#!/usr/bin/env bash
|
||||
cat >/dev/null
|
||||
calls=$(( $(cat "${STUB_DIR}/calls" 2>/dev/null || echo 0) + 1 ))
|
||||
echo "${calls}" >"${STUB_DIR}/calls"
|
||||
if [ "${calls}" -gt "${STUB_FAILURES}" ]; then
|
||||
\texit 0
|
||||
fi
|
||||
echo "${STUB_MESSAGE}" >&2
|
||||
exit "${STUB_RC}"
|
||||
"""
|
||||
|
||||
QUIET_STUB = """#!/usr/bin/env bash
|
||||
exit 0
|
||||
"""
|
||||
|
||||
ECHO_STUB = """#!/usr/bin/env bash
|
||||
printf '%s\\n' "${@: -1}"
|
||||
"""
|
||||
|
||||
|
||||
def lookup(name, *_args):
|
||||
"""Return what the template's two lookups resolve to.
|
||||
|
||||
Args:
|
||||
name: lookup plugin the template calls.
|
||||
"""
|
||||
return {
|
||||
"email": {"from": "no-reply@example.test", "timeout": "30"},
|
||||
"users": {"email": "administrator@example.test"},
|
||||
}[name]
|
||||
|
||||
|
||||
def rendered_script() -> str:
|
||||
env = Environment(
|
||||
loader=FileSystemLoader(str(TEMPLATE_DIR)),
|
||||
undefined=StrictUndefined,
|
||||
autoescape=select_autoescape(),
|
||||
)
|
||||
return env.get_template("script.sh.j2").render(lookup=lookup, HOST_CS="utf-8")
|
||||
|
||||
|
||||
class TestAlmEmailScript(unittest.TestCase):
|
||||
def run_script(self, *, failures, rc, message):
|
||||
"""Run the rendered alarm script against a stubbed sendmail.
|
||||
|
||||
Args:
|
||||
failures: how many sendmail calls fail before one succeeds.
|
||||
rc: exit code of a failing call.
|
||||
message: what a failing call prints to stderr.
|
||||
|
||||
Returns:
|
||||
Tuple of the exit code, the retry lines and the whole stderr.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
bin_dir = Path(tmp)
|
||||
stubs = (
|
||||
("sendmail", SENDMAIL_STUB),
|
||||
("sleep", QUIET_STUB),
|
||||
("systemctl", QUIET_STUB),
|
||||
("systemd-escape", ECHO_STUB),
|
||||
)
|
||||
for name, body in stubs:
|
||||
stub = bin_dir / name
|
||||
stub.write_text(body)
|
||||
stub.chmod(0o755)
|
||||
script = bin_dir / "script.sh"
|
||||
script.write_text(rendered_script())
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}"
|
||||
env["STUB_DIR"] = tmp
|
||||
env["STUB_FAILURES"] = str(failures)
|
||||
env["STUB_RC"] = str(rc)
|
||||
env["STUB_MESSAGE"] = message
|
||||
done = subprocess.run(
|
||||
["bash", str(script), "example.service"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
retries = [
|
||||
line
|
||||
for line in done.stderr.splitlines()
|
||||
if "sendmail transient failure" in line
|
||||
]
|
||||
return done.returncode, retries, done.stderr
|
||||
|
||||
def test_a_dropped_connection_is_retried_and_the_alarm_is_sent(self):
|
||||
code, retries, _ = self.run_script(failures=1, rc=76, message=EMPTY_REPLY)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(len(retries), 1)
|
||||
self.assertIn("(rc=76), attempt 1/3", retries[0])
|
||||
|
||||
def test_a_permanent_rejection_is_reported_without_a_retry(self):
|
||||
rejection = "sendmail: recipient address rejected"
|
||||
code, retries, stderr = self.run_script(failures=99, rc=65, message=rejection)
|
||||
self.assertEqual(code, 65)
|
||||
self.assertEqual(retries, [])
|
||||
self.assertIn(rejection, stderr)
|
||||
|
||||
def test_the_third_failure_ends_the_alarm_with_the_last_exit_code(self):
|
||||
code, retries, stderr = self.run_script(failures=99, rc=76, message=EMPTY_REPLY)
|
||||
self.assertEqual(code, 76)
|
||||
self.assertEqual(len(retries), 2)
|
||||
self.assertIn(EMPTY_REPLY, stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Whitespace-only changes.
@@ -0,0 +1,91 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from utils import PROJECT_ROOT
|
||||
|
||||
SCRIPT = PROJECT_ROOT / "roles/sys-ctl-hlth-msmtp/files/shell/script.sh"
|
||||
|
||||
EMPTY_REPLY = "msmtp: the server sent an empty reply"
|
||||
|
||||
MSMTP_STUB = """#!/usr/bin/env bash
|
||||
cat >/dev/null
|
||||
calls=$(( $(cat "${STUB_DIR}/calls" 2>/dev/null || echo 0) + 1 ))
|
||||
echo "${calls}" >"${STUB_DIR}/calls"
|
||||
if [ "${calls}" -gt "${STUB_FAILURES}" ]; then
|
||||
\texit 0
|
||||
fi
|
||||
echo "${STUB_MESSAGE}" >&2
|
||||
exit "${STUB_RC}"
|
||||
"""
|
||||
|
||||
SLEEP_STUB = """#!/usr/bin/env bash
|
||||
exit 0
|
||||
"""
|
||||
|
||||
|
||||
class TestHlthMsmtpScript(unittest.TestCase):
|
||||
def run_script(self, *, failures, rc, message):
|
||||
"""Run the health script against a stubbed msmtp.
|
||||
|
||||
Args:
|
||||
failures: how many msmtp calls fail before one succeeds.
|
||||
rc: exit code of a failing call.
|
||||
message: what a failing call prints to stderr.
|
||||
|
||||
Returns:
|
||||
Tuple of the exit code and the retry lines the script printed.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
bin_dir = Path(tmp)
|
||||
for name, body in (("msmtp", MSMTP_STUB), ("sleep", SLEEP_STUB)):
|
||||
stub = bin_dir / name
|
||||
stub.write_text(body)
|
||||
stub.chmod(0o755)
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}"
|
||||
env["MAIL_RECIPIENT"] = "administrator@example.test"
|
||||
env["MAIL_TIMEOUT"] = "30"
|
||||
env["STUB_DIR"] = tmp
|
||||
env["STUB_FAILURES"] = str(failures)
|
||||
env["STUB_RC"] = str(rc)
|
||||
env["STUB_MESSAGE"] = message
|
||||
done = subprocess.run(
|
||||
["bash", str(SCRIPT)],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
retries = [
|
||||
line
|
||||
for line in done.stderr.splitlines()
|
||||
if "msmtp transient failure" in line
|
||||
]
|
||||
return done.returncode, retries
|
||||
|
||||
def test_a_dropped_connection_is_retried_until_the_mail_is_accepted(self):
|
||||
code, retries = self.run_script(failures=1, rc=76, message=EMPTY_REPLY)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(len(retries), 1)
|
||||
self.assertIn("(rc=76), attempt 1/10", retries[0])
|
||||
|
||||
def test_another_protocol_error_ends_the_check_at_once(self):
|
||||
code, retries = self.run_script(
|
||||
failures=99,
|
||||
rc=76,
|
||||
message="msmtp: cannot get initial OK message from server",
|
||||
)
|
||||
self.assertEqual(code, 76)
|
||||
self.assertEqual(retries, [])
|
||||
|
||||
def test_a_server_that_keeps_dropping_fails_after_the_last_attempt(self):
|
||||
code, retries = self.run_script(failures=99, rc=76, message=EMPTY_REPLY)
|
||||
self.assertEqual(code, 76)
|
||||
self.assertEqual(len(retries), 9)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Whitespace-only changes.
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from utils.cache.files import PROJECT_ROOT
|
||||
|
||||
SCRIPT = PROJECT_ROOT / "scripts" / "meta" / "wait" / "images.sh"
|
||||
HEAD_SHA = "5b002678df222f1095fae2f42e3bb10964adb8ef"
|
||||
RUN_TITLE = "pull_request_target / PR #1 / synchronize / fork:branch"
|
||||
STUBS = {
|
||||
"docker": '#!/usr/bin/env bash\n[[ -e "${STUB_DIR}/images-ready" ]]\n',
|
||||
"gh": (
|
||||
"#!/usr/bin/env bash\n"
|
||||
'printf "gh %s\\n" "$*" >&2\n'
|
||||
'if [[ -n "${STUB_IMAGES_APPEAR:-}" ]]; then\n'
|
||||
'\ttouch "${STUB_DIR}/images-ready"\n'
|
||||
"fi\n"
|
||||
'if [[ -e "${STUB_DIR}/gh-response" ]]; then\n'
|
||||
'\tcat "${STUB_DIR}/gh-response"\n'
|
||||
"\texit 0\n"
|
||||
"fi\n"
|
||||
'echo "HTTP 504" >&2\n'
|
||||
"exit 1\n"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def wait_for_images(
|
||||
tmp: str, runs: list[dict] | None = None, **overrides: str
|
||||
) -> subprocess.CompletedProcess:
|
||||
"""Run the wait script against stubbed ``docker`` and ``gh``.
|
||||
|
||||
Args:
|
||||
tmp: directory that holds the stubs and their state.
|
||||
runs: workflow runs ``gh`` answers with; without them every lookup fails.
|
||||
overrides: environment entries layered over the defaults.
|
||||
"""
|
||||
stub_dir = Path(tmp)
|
||||
for name, body in STUBS.items():
|
||||
stub = stub_dir / name
|
||||
stub.write_text(body)
|
||||
stub.chmod(0o755)
|
||||
if runs is not None:
|
||||
(stub_dir / "gh-response").write_text(json.dumps({"workflow_runs": runs}))
|
||||
inherited = {k: v for k, v in os.environ.items() if k != "BASH_ENV"}
|
||||
env = {
|
||||
**inherited,
|
||||
"PATH": f"{stub_dir}{os.pathsep}{os.environ['PATH']}",
|
||||
"STUB_DIR": str(stub_dir),
|
||||
"GITHUB_REPOSITORY": "acme/widgets",
|
||||
"GH_TOKEN": "unused",
|
||||
"WORKFLOW_FILE": "entry.yml",
|
||||
"TARGET_EVENT": "pull_request_target",
|
||||
"PR_NUMBER": "1",
|
||||
"PR_HEAD_SHA": HEAD_SHA,
|
||||
"IMAGE_TAG": "ci-test",
|
||||
"INFINITO_DISTROS": "debian",
|
||||
"WAIT_ATTEMPTS": "100",
|
||||
"WAIT_SLEEP_SECONDS": "0",
|
||||
**overrides,
|
||||
}
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT)],
|
||||
cwd=PROJECT_ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
class TestWaitForImages(unittest.TestCase):
|
||||
def test_failed_lookup_does_not_end_the_wait(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = wait_for_images(tmp, STUB_IMAGES_APPEAR="true")
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn(
|
||||
"Lookup of the privileged workflow run failed (1/30)", result.stdout
|
||||
)
|
||||
self.assertIn("All required CI images are available.", result.stdout)
|
||||
|
||||
def test_lookup_that_keeps_failing_ends_the_wait(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = wait_for_images(tmp)
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn("failed 30 times in a row", result.stderr)
|
||||
|
||||
def test_failed_privileged_run_of_a_fork_ends_the_wait(self) -> None:
|
||||
fork_run = {
|
||||
"id": 7,
|
||||
"status": "completed",
|
||||
"conclusion": "failure",
|
||||
"created_at": "2026-10-04T12:41:18Z",
|
||||
"head_sha": HEAD_SHA,
|
||||
"display_title": RUN_TITLE,
|
||||
"pull_requests": [],
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = wait_for_images(tmp, runs=[fork_run])
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn(
|
||||
"Privileged run 7 finished with conclusion=failure", result.stderr
|
||||
)
|
||||
self.assertIn(f"head_sha={HEAD_SHA}", result.stderr)
|
||||
|
||||
def test_run_of_another_head_is_ignored(self) -> None:
|
||||
other_run = {
|
||||
"id": 8,
|
||||
"status": "completed",
|
||||
"conclusion": "failure",
|
||||
"created_at": "2026-10-04T12:41:18Z",
|
||||
"head_sha": "0" * 40,
|
||||
"display_title": RUN_TITLE,
|
||||
"pull_requests": [],
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = wait_for_images(tmp, runs=[other_run], WAIT_ATTEMPTS="2")
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn(
|
||||
"No matching privileged workflow run found yet", result.stdout
|
||||
)
|
||||
self.assertIn("Timed out waiting for CI images", result.stderr)
|
||||
|
||||
def test_run_of_another_pull_request_on_the_same_head_is_ignored(self) -> None:
|
||||
own_run = {
|
||||
"id": 7,
|
||||
"status": "in_progress",
|
||||
"conclusion": None,
|
||||
"created_at": "2026-10-04T12:41:18Z",
|
||||
"head_sha": HEAD_SHA,
|
||||
"display_title": RUN_TITLE,
|
||||
"pull_requests": [],
|
||||
}
|
||||
other_run = {
|
||||
"id": 9,
|
||||
"status": "completed",
|
||||
"conclusion": "failure",
|
||||
"created_at": "2026-10-04T12:45:00Z",
|
||||
"head_sha": HEAD_SHA,
|
||||
"display_title": "pull_request_target / PR #12 / synchronize / fork:branch",
|
||||
"pull_requests": [],
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = wait_for_images(tmp, runs=[own_run, other_run], WAIT_ATTEMPTS="2")
|
||||
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
|
||||
self.assertIn("Privileged run 7 ", result.stdout)
|
||||
self.assertNotIn("Privileged run 9", result.stdout + result.stderr)
|
||||
self.assertIn("Timed out waiting for CI images", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,8 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from utils.roles.mapping import ROLE_FILE_META_SERVICES
|
||||
from utils.update.base import (
|
||||
is_maintained,
|
||||
is_semver,
|
||||
latest_semver,
|
||||
version_depth,
|
||||
@@ -53,5 +57,34 @@ class TestUpdateBase(unittest.TestCase):
|
||||
self.assertEqual(latest_semver(tags, 3, ""), "5.4.7")
|
||||
|
||||
|
||||
class TestIsMaintained(unittest.TestCase):
|
||||
def _roles(self, tmp: str, services: str | None) -> Path:
|
||||
roles_root = Path(tmp) / "roles"
|
||||
services_path = roles_root / "web-app-demo" / ROLE_FILE_META_SERVICES
|
||||
services_path.parent.mkdir(parents=True)
|
||||
if services is not None:
|
||||
services_path.write_text(services, encoding="utf-8")
|
||||
return roles_root
|
||||
|
||||
def test_an_eol_role_is_not_maintained(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
roles_root = self._roles(tmp, "demo:\n lifecycle: eol\n")
|
||||
|
||||
self.assertFalse(is_maintained(roles_root, "web-app-demo"))
|
||||
|
||||
def test_every_other_stage_is_maintained(self) -> None:
|
||||
for stage in ("pre-alpha", "beta", "maintenance", "deprecated"):
|
||||
with self.subTest(stage=stage), tempfile.TemporaryDirectory() as tmp:
|
||||
roles_root = self._roles(tmp, f"demo:\n lifecycle: {stage}\n")
|
||||
|
||||
self.assertTrue(is_maintained(roles_root, "web-app-demo"))
|
||||
|
||||
def test_a_role_without_a_lifecycle_is_maintained(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
roles_root = self._roles(tmp, None)
|
||||
|
||||
self.assertTrue(is_maintained(roles_root, "web-app-demo"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -258,6 +258,24 @@ class TestCollectEntriesCoversAddons(unittest.TestCase):
|
||||
|
||||
self.assertEqual(collect_entries(root), [])
|
||||
|
||||
def test_refs_of_an_eol_role_are_not_collected(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
root = Path(tmpdir)
|
||||
role = self._role(root)
|
||||
(role / ROLE_FILE_META_SERVICES).write_text(
|
||||
"example:\n"
|
||||
" lifecycle: eol\n"
|
||||
" repository: https://example.test/app.git\n"
|
||||
" ref: v1.0.0\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(role / ROLE_DIR_META_ADDONS / "plug.yml").write_text(
|
||||
"config:\n repository: https://example.test/plug.git\n ref: v2.0.0\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
self.assertEqual(collect_entries(root), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,260 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock as mock
|
||||
from pathlib import Path
|
||||
|
||||
from utils.roles.mapping import ROLE_DIR_META_ADDONS, 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
|
||||
"""
|
||||
|
||||
|
||||
ADDONS = {
|
||||
"released": """\
|
||||
---
|
||||
enabled: true
|
||||
version: "v1.2.0"
|
||||
update:
|
||||
monitored: true
|
||||
catalog: github-releases
|
||||
upstream_id: example/released
|
||||
config:
|
||||
archive: "https://example.test/released/download/v1.2.0/app.tar.gz"
|
||||
""",
|
||||
"declared": """\
|
||||
---
|
||||
enabled: true
|
||||
version: "3.4"
|
||||
update:
|
||||
type: http_regex
|
||||
url: https://example.test/metadata.xml
|
||||
pattern: '<version>([0-9.]+)</version>'
|
||||
""",
|
||||
"unmonitored": """\
|
||||
---
|
||||
enabled: true
|
||||
version: "1.0.0"
|
||||
update:
|
||||
monitored: false
|
||||
catalog: github-releases
|
||||
upstream_id: example/unmonitored
|
||||
""",
|
||||
"catalogued": """\
|
||||
---
|
||||
enabled: true
|
||||
version: "1.0.0"
|
||||
update:
|
||||
monitored: true
|
||||
catalog: wordpress-org
|
||||
""",
|
||||
"frozen": """\
|
||||
---
|
||||
enabled: true
|
||||
# nocheck: unwatched-version Reason: bound to a checksum
|
||||
version: "2.0.0"
|
||||
update:
|
||||
monitored: true
|
||||
catalog: github-releases
|
||||
upstream_id: example/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
|
||||
|
||||
|
||||
def _addon_repo(addons: dict[str, str] | None = None) -> Path:
|
||||
tmp = Path(tempfile.mkdtemp())
|
||||
directory = tmp / "roles" / "web-app-example" / ROLE_DIR_META_ADDONS
|
||||
directory.mkdir(parents=True)
|
||||
for addon_id, content in (ADDONS if addons is None else addons).items():
|
||||
(directory / f"{addon_id}.yml").write_text(content, 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), [])
|
||||
|
||||
|
||||
class TestAddons(unittest.TestCase):
|
||||
def test_only_a_declared_or_github_released_addon_pin_is_collected(self) -> None:
|
||||
entries = module.collect_entries(_addon_repo())
|
||||
|
||||
self.assertEqual(
|
||||
[
|
||||
(e.entity, e.key, e.current, e.source["type"], e.line, e.addon)
|
||||
for e in entries
|
||||
],
|
||||
[
|
||||
("declared", "version", "3.4", "http_regex", 3, True),
|
||||
("released", "version", "v1.2.0", "git_tags", 3, True),
|
||||
],
|
||||
)
|
||||
self.assertEqual(
|
||||
entries[1].source["repository"], "https://github.com/example/released.git"
|
||||
)
|
||||
|
||||
def test_an_addon_pin_moves_together_with_the_archive_that_carries_it(self) -> None:
|
||||
root = _addon_repo({"released": ADDONS["released"]})
|
||||
with mock.patch.object(module, "candidates", return_value=["v1.3.0"]):
|
||||
updates = module.find_outdated_updates(root)
|
||||
module.apply_updates(updates)
|
||||
|
||||
addon = (
|
||||
root / "roles" / "web-app-example" / ROLE_DIR_META_ADDONS / "released.yml"
|
||||
)
|
||||
written = addon.read_text() # nocheck: cache-read just rewritten here
|
||||
self.assertIn('version: "v1.3.0"', written)
|
||||
self.assertIn("released/download/v1.3.0/app.tar.gz", written)
|
||||
self.assertIn("upstream_id: example/released", written)
|
||||
|
||||
def test_an_archive_that_does_not_carry_the_pin_is_reported(self) -> None:
|
||||
drifted = ADDONS["released"].replace('version: "v1.2.0"', 'version: "v1.1.0"')
|
||||
root = _addon_repo({"drifted": drifted})
|
||||
|
||||
self.assertEqual(
|
||||
module.invalid_declarations(root),
|
||||
[
|
||||
(
|
||||
"web-app-example/addons/drifted.version: config.archive does "
|
||||
"not carry the pinned version, so a bump would move only one "
|
||||
"of the two"
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
def test_an_addon_block_that_cannot_resolve_is_reported(self) -> None:
|
||||
root = _addon_repo(
|
||||
{"broken": "---\nenabled: true\nupdate:\n type: carrier_pigeon\n"}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
module.invalid_declarations(root),
|
||||
[
|
||||
(
|
||||
"web-app-example/addons/broken: update.key 'version' names no "
|
||||
"key of the addon"
|
||||
),
|
||||
(
|
||||
"web-app-example/addons/broken.version: unknown update.type "
|
||||
"'carrier_pigeon', expected one of git_tags, registry_tags, npm, "
|
||||
"http_regex, script"
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class TestSemverPins(unittest.TestCase):
|
||||
def test_an_update_block_on_a_moving_tag_is_reported(self) -> None:
|
||||
root = _repo(SERVICES.replace("app_version: 2.0.0", "app_version: latest"))
|
||||
|
||||
self.assertEqual(
|
||||
module.invalid_declarations(root),
|
||||
[
|
||||
(
|
||||
"web-app-example/app.app_version: 'latest' is not a semver, so "
|
||||
"no upstream version orders above it and the pin never moves"
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
def test_a_monitored_addon_on_a_moving_tag_is_reported(self) -> None:
|
||||
root = _addon_repo(
|
||||
{
|
||||
"moving": ADDONS["catalogued"].replace('"1.0.0"', '"master"'),
|
||||
"pinned": ADDONS["catalogued"],
|
||||
"unpinned": ADDONS["catalogued"].replace('version: "1.0.0"\n', ""),
|
||||
"unmonitored": ADDONS["unmonitored"].replace('"1.0.0"', '"master"'),
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
module.invalid_declarations(root),
|
||||
[
|
||||
(
|
||||
"web-app-example/addons/moving.version: 'master' is not a "
|
||||
"semver, so no upstream version orders above it and the pin "
|
||||
"never moves"
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+24
-2
@@ -24,6 +24,7 @@ if TYPE_CHECKING:
|
||||
|
||||
from utils.cache.yaml import load_yaml_any
|
||||
from utils.roles.mapping import ROLE_DIR_META_ADDONS
|
||||
from utils.update.base import is_maintained
|
||||
|
||||
MECHANISMS: frozenset[str] = frozenset(
|
||||
{"addon", "plugin", "mu_plugin", "extension", "module", "bridge"}
|
||||
@@ -45,7 +46,26 @@ ADDON_KEYS: frozenset[str] = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
UPDATE_KEYS: frozenset[str] = frozenset({"monitored", "catalog", "upstream_id"})
|
||||
VERSION_SOURCE_KEYS: frozenset[str] = frozenset(
|
||||
{
|
||||
"key",
|
||||
"type",
|
||||
"repository",
|
||||
"image",
|
||||
"package",
|
||||
"url",
|
||||
"pattern",
|
||||
"path",
|
||||
"match",
|
||||
"strip",
|
||||
}
|
||||
)
|
||||
|
||||
UPDATE_KEYS: frozenset[str] = (
|
||||
frozenset({"monitored", "catalog", "upstream_id"}) | VERSION_SOURCE_KEYS
|
||||
)
|
||||
|
||||
GITHUB_RELEASES_CATALOG = "github-releases"
|
||||
|
||||
SUPPORTED_CATALOGS: frozenset[str] = frozenset(
|
||||
{
|
||||
@@ -60,7 +80,7 @@ SUPPORTED_CATALOGS: frozenset[str] = frozenset(
|
||||
"gnome-extensions",
|
||||
"chrome-webstore",
|
||||
"firefox-amo",
|
||||
"github-releases",
|
||||
GITHUB_RELEASES_CATALOG,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -157,6 +177,8 @@ def collect_addon_entries(roles_root: Path) -> list[AddonEntry]:
|
||||
"""
|
||||
entries: list[AddonEntry] = []
|
||||
for role_name, addon_file in iter_addon_files(roles_root):
|
||||
if not is_maintained(roles_root, role_name):
|
||||
continue
|
||||
spec = load_yaml_any(str(addon_file), default_if_missing={})
|
||||
if isinstance(spec, Mapping):
|
||||
entries.append(
|
||||
|
||||
@@ -25,7 +25,14 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from utils.roles.meta_lookup import get_role_lifecycle
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
UNMAINTAINED_LIFECYCLES = frozenset({"eol"})
|
||||
_SEMVER_CORE = r"v?\d+(?:\.\d+){0,4}"
|
||||
_VERSIONED_TAG_RE = re.compile(
|
||||
rf"^(?P<channel>[A-Za-z][A-Za-z0-9]*-)?(?P<semver>{_SEMVER_CORE})"
|
||||
@@ -87,3 +94,14 @@ def latest_semver(tags: list[str], depth: int, flavor: str = "") -> str | None:
|
||||
|
||||
def resolve_max_fetch_workers() -> int:
|
||||
return int(os.environ["INFINITO_WORKER_FETCH"])
|
||||
|
||||
|
||||
def is_maintained(roles_root: Path, role: str) -> bool:
|
||||
"""Return whether the version-bump backends watch a role.
|
||||
|
||||
Args:
|
||||
roles_root: the ``roles/`` directory that holds the role.
|
||||
role: role name, the directory name under ``roles_root``.
|
||||
"""
|
||||
lifecycle = get_role_lifecycle(roles_root / role, role_name=role)
|
||||
return lifecycle not in UNMAINTAINED_LIFECYCLES
|
||||
@@ -38,6 +38,7 @@ from utils.docker.image.ref import (
|
||||
from utils.docker.registry import fetch_registry_tags
|
||||
from utils.roles.mapping import ROLE_FILE_META_SERVICES
|
||||
from utils.update.base import (
|
||||
is_maintained,
|
||||
is_semver,
|
||||
latest_semver,
|
||||
resolve_max_fetch_workers,
|
||||
@@ -273,6 +274,8 @@ def collect_entries(repo_root: Path) -> list[DockerImageVersionEntry]:
|
||||
continue
|
||||
if not is_semver(ref.version):
|
||||
continue
|
||||
if not is_maintained(roles_root, ref.role):
|
||||
continue
|
||||
|
||||
config_path = roles_root / ref.role / ROLE_FILE_META_SERVICES
|
||||
if ref.service in suppressed_services(config_path):
|
||||
|
||||
+7
-3
@@ -28,7 +28,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from utils.annotations.suppress import is_suppressed_at
|
||||
from utils.cache.files import read_text
|
||||
from utils.update.base import is_semver, version_key
|
||||
from utils.update.base import is_maintained, is_semver, version_key
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
@@ -74,11 +74,15 @@ def collect_entries(repo_root: Path) -> list[PipPinEntry]:
|
||||
Args:
|
||||
repo_root: repository root to scan.
|
||||
"""
|
||||
roles_root = repo_root / "roles"
|
||||
entries: list[PipPinEntry] = []
|
||||
for path in sorted((repo_root / "roles").rglob("*.yml")):
|
||||
for path in sorted(roles_root.rglob("*.yml")):
|
||||
text = read_text(str(path))
|
||||
if "package_name:" not in text:
|
||||
continue
|
||||
role = path.relative_to(roles_root).parts[0]
|
||||
if not is_maintained(roles_root, role):
|
||||
continue
|
||||
lines = text.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
match = PIN_PATTERN.match(line)
|
||||
@@ -88,7 +92,7 @@ def collect_entries(repo_root: Path) -> list[PipPinEntry]:
|
||||
continue
|
||||
entries.append(
|
||||
PipPinEntry(
|
||||
role=path.relative_to(repo_root / "roles").parts[0],
|
||||
role=role,
|
||||
package=match.group("package"),
|
||||
version=match.group("version"),
|
||||
config_path=path,
|
||||
|
||||
@@ -32,6 +32,7 @@ from utils.cache.files import read_text
|
||||
from utils.cache.yaml import load_yaml_any
|
||||
from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES
|
||||
from utils.update.base import (
|
||||
is_maintained,
|
||||
is_semver,
|
||||
latest_semver,
|
||||
resolve_max_fetch_workers,
|
||||
@@ -199,6 +200,8 @@ def collect_entries(repo_root: Path) -> list[RepositoryRefEntry]:
|
||||
roles_root = repo_root / "roles"
|
||||
entries: list[RepositoryRefEntry] = []
|
||||
for role_dir in sorted(p for p in roles_root.iterdir() if p.is_dir()):
|
||||
if not is_maintained(roles_root, role_dir.name):
|
||||
continue
|
||||
services_path = role_dir / ROLE_FILE_META_SERVICES
|
||||
if services_path.is_file():
|
||||
entries += _entries_of_file(role_dir.name, services_path, ())
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
"""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::
|
||||
|
||||
stalwart:
|
||||
webui_version: "v1.0.5"
|
||||
update:
|
||||
key: webui_version
|
||||
type: git_tags
|
||||
repository: https://github.com/stalwartlabs/webui.git
|
||||
|
||||
``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).
|
||||
|
||||
An addon in ``meta/addons/<id>.yml`` declares the same fields in its
|
||||
``update:`` block, beside ``monitored``, ``catalog`` and ``upstream_id``. A
|
||||
monitored addon of the ``github-releases`` catalog needs no ``type``: its
|
||||
``upstream_id`` already names the repository whose tags are its versions. An
|
||||
addon's ``config.archive`` URL carries the pinned version and moves with it.
|
||||
"""
|
||||
|
||||
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.addons import GITHUB_RELEASES_CATALOG, iter_addon_files
|
||||
from utils.update.base import (
|
||||
is_maintained,
|
||||
is_semver,
|
||||
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"
|
||||
UNWATCHED_MARKER = "unwatched-version"
|
||||
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:
|
||||
"""One pin and the upstream it declares.
|
||||
|
||||
Args:
|
||||
role: role that carries the pin.
|
||||
entity: service entity in ``meta/services.yml``, or the addon id.
|
||||
key: pinned key.
|
||||
current: pinned version.
|
||||
source: the ``update:`` block.
|
||||
config_path: file that carries the pin.
|
||||
line: 1-indexed line of the pin.
|
||||
addon: whether the pin sits in ``meta/addons/<id>.yml``.
|
||||
"""
|
||||
|
||||
role: str
|
||||
entity: str
|
||||
key: str
|
||||
current: str
|
||||
source: dict[str, Any]
|
||||
config_path: Path
|
||||
line: int
|
||||
addon: bool = False
|
||||
|
||||
|
||||
@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 _top_level_line(lines: list[str], key: str) -> int | None:
|
||||
"""Return the 1-indexed line of ``key`` at the root of an addon file."""
|
||||
for number, line in enumerate(lines, start=1):
|
||||
if re.match(rf"^{re.escape(key)}\s*:", line):
|
||||
return number
|
||||
return None
|
||||
|
||||
|
||||
def _archive_index(lines: list[str]) -> int | None:
|
||||
"""Return the 0-indexed line of ``config.archive`` in an addon file."""
|
||||
for index, line in enumerate(lines):
|
||||
if re.match(r"^\s+archive\s*:", line):
|
||||
return index
|
||||
return None
|
||||
|
||||
|
||||
def _archive(spec: Any) -> str:
|
||||
"""Return the ``config.archive`` URL of an addon, or an empty string."""
|
||||
config = spec.get("config") if isinstance(spec, dict) else None
|
||||
return str(config.get("archive", "")) if isinstance(config, dict) else ""
|
||||
|
||||
|
||||
def addon_sources(spec: Any) -> list[dict[str, Any]]:
|
||||
"""Return the version sources an addon declares.
|
||||
|
||||
Args:
|
||||
spec: root mapping of a ``meta/addons/<id>.yml`` file.
|
||||
"""
|
||||
declared = spec.get(UPDATE_KEY) if isinstance(spec, dict) else None
|
||||
if not isinstance(declared, dict):
|
||||
return []
|
||||
if "type" in declared:
|
||||
return [declared]
|
||||
if (
|
||||
declared.get("monitored")
|
||||
and declared.get("catalog") == GITHUB_RELEASES_CATALOG
|
||||
and declared.get("upstream_id")
|
||||
):
|
||||
repository = f"https://github.com/{declared['upstream_id']}.git"
|
||||
return [{**declared, "type": "git_tags", "repository": repository}]
|
||||
return []
|
||||
|
||||
|
||||
def _monitored_pin(spec: Any) -> str:
|
||||
"""Return the version a monitored addon pins, or an empty string."""
|
||||
declared = spec.get(UPDATE_KEY) if isinstance(spec, dict) else None
|
||||
if not isinstance(declared, dict) or not declared.get("monitored"):
|
||||
return ""
|
||||
return str(spec.get(DEFAULT_KEY) or "").strip()
|
||||
|
||||
|
||||
def _not_semver(label: str, pinned: Any) -> str:
|
||||
return (
|
||||
f"{label}: '{pinned}' is not a semver, so no upstream version orders "
|
||||
"above it and the pin never moves"
|
||||
)
|
||||
|
||||
|
||||
def _declaration_problems(
|
||||
label: str, config: dict[str, Any], source: Any, owner: str
|
||||
) -> list[str]:
|
||||
"""Return what keeps one ``update:`` block from resolving.
|
||||
|
||||
Args:
|
||||
label: ``<role>/<entity>`` as it appears in the message.
|
||||
config: mapping that carries the pin.
|
||||
source: the ``update:`` block.
|
||||
owner: what ``config`` is, ``entity`` or ``addon``.
|
||||
"""
|
||||
if not isinstance(source, dict):
|
||||
return [f"{label}: update entry is not a mapping"]
|
||||
problems: list[str] = []
|
||||
key = str(source.get("key", DEFAULT_KEY))
|
||||
if key not in config:
|
||||
problems.append(f"{label}: update.key '{key}' names no key of the {owner}")
|
||||
elif not is_semver(str(config[key])):
|
||||
problems.append(_not_semver(f"{label}.{key}", config[key]))
|
||||
if source.get("type") not in TYPES:
|
||||
problems.append(
|
||||
f"{label}.{key}: unknown update.type "
|
||||
f"'{source.get('type')}', expected one of {', '.join(TYPES)}"
|
||||
)
|
||||
archive = _archive(config) if owner == "addon" else ""
|
||||
if archive and str(config.get(key, "")) not in archive:
|
||||
problems.append(
|
||||
f"{label}.{key}: config.archive does not carry the pinned version, "
|
||||
"so a bump would move only one of the two"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
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, a type the resolver does
|
||||
not know, or a pin that is not a semver would otherwise move nothing and
|
||||
say nothing. A monitored addon the resolver does not read is held to the
|
||||
same semver rule.
|
||||
|
||||
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:
|
||||
problems += _declaration_problems(
|
||||
f"{role}/{entity}", config, source, "entity"
|
||||
)
|
||||
for role, addon_path in iter_addon_files(repo_root / "roles"):
|
||||
spec = load_yaml(str(addon_path))
|
||||
label = f"{role}/addons/{addon_path.stem}"
|
||||
sources = addon_sources(spec)
|
||||
for source in sources:
|
||||
problems += _declaration_problems(label, spec, source, "addon")
|
||||
pinned = "" if sources else _monitored_pin(spec)
|
||||
if pinned and not is_semver(pinned):
|
||||
problems.append(_not_semver(f"{label}.{DEFAULT_KEY}", pinned))
|
||||
return problems
|
||||
|
||||
|
||||
def _addon_entries(repo_root: Path) -> list[VersionSourceEntry]:
|
||||
roles_root = repo_root / "roles"
|
||||
entries: list[VersionSourceEntry] = []
|
||||
for role, addon_path in iter_addon_files(roles_root):
|
||||
if not is_maintained(roles_root, role):
|
||||
continue
|
||||
spec = load_yaml(str(addon_path))
|
||||
lines = read_text(str(addon_path)).splitlines()
|
||||
for source in addon_sources(spec):
|
||||
key = str(source.get("key", DEFAULT_KEY))
|
||||
current = str(spec.get(key, "")).strip()
|
||||
line = _top_level_line(lines, key)
|
||||
if not current or line is None:
|
||||
continue
|
||||
if any(
|
||||
is_suppressed_at(lines, line, marker)
|
||||
for marker in (NOCHECK_MARKER, UNWATCHED_MARKER)
|
||||
):
|
||||
continue
|
||||
entries.append(
|
||||
VersionSourceEntry(
|
||||
role=role,
|
||||
entity=addon_path.stem,
|
||||
key=key,
|
||||
current=current,
|
||||
source=source,
|
||||
config_path=addon_path,
|
||||
line=line,
|
||||
addon=True,
|
||||
)
|
||||
)
|
||||
return entries
|
||||
|
||||
|
||||
def collect_entries(repo_root: Path) -> list[VersionSourceEntry]:
|
||||
"""Return every declared version source that is not suppressed."""
|
||||
roles_root = repo_root / "roles"
|
||||
entries: list[VersionSourceEntry] = []
|
||||
for config_path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_SERVICES}")):
|
||||
role = config_path.parts[-3]
|
||||
if not is_maintained(roles_root, role):
|
||||
continue
|
||||
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 + _addon_entries(repo_root)
|
||||
|
||||
|
||||
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)
|
||||
archive = _archive_index(lines) if update.entry.addon else None
|
||||
if archive is not None:
|
||||
lines[archive] = lines[archive].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
|
||||
Reference in new issue
Block a user