diff --git a/library/database_query.py b/library/database_query.py index 5cf6971b15..30ec772d6b 100755 --- a/library/database_query.py +++ b/library/database_query.py @@ -109,7 +109,7 @@ _ENGINES: dict[str, dict[str, object]] = { "user_flag": "-U", "db_flag": "-d", "shared_flags": ["-v", "ON_ERROR_STOP=1"], - "rows_flags": ["-tA"], + "rows_flags": ["-qtA"], "row_separator": "|", "password_env": "PGPASSWORD", "string_quote": "'", diff --git a/roles/svc-opt-ssd-hdd/files/python/script.py b/roles/svc-opt-ssd-hdd/files/python/script.py index ba59e5caa3..91a12bb98e 100644 --- a/roles/svc-opt-ssd-hdd/files/python/script.py +++ b/roles/svc-opt-ssd-hdd/files/python/script.py @@ -38,10 +38,34 @@ def start_containers(containers): run_command(f"container start {container_list}") +DATABASE_IMAGES = { + "elasticsearch", + "mariadb", + "memcached", + "mongo", + "mysql", + "openldap", + "opensearch", + "postgis", + "postgres", + "qdrant", + "rabbitmq", + "redis", + "typesense", + "valkey", +} + + def is_database(image): - databases = {"postgres", "mariadb", "redis", "memcached", "mongo"} - prefix = image.split(":")[0] - return prefix in databases + """Tell whether an image reference names a database engine. + + Args: + image: reference as the container's `.Config.Image` reports it, with + optional registry, namespace, tag and digest; a locally built + `_custom` image counts as its engine. + """ + name = image.rsplit("/", 1)[-1].split("@")[0].split(":")[0] + return name.removesuffix("_custom") in DATABASE_IMAGES def is_symbolic_link(file_path): diff --git a/roles/update/README.md b/roles/update/README.md index 04d09e8680..1ccdc81110 100644 --- a/roles/update/README.md +++ b/roles/update/README.md @@ -26,7 +26,7 @@ message when a host runs a distribution that this role does not yet cover. | `CentOS` | `centos.yml` | `ansible.builtin.dnf` | | anything else | `unsupported.yml` | `ansible.builtin.fail` | -`centos.yml` first runs [centos_mirror.sh](files/shell/centos_mirror.sh), which replaces every `metalink=` of the CentOS Stream repo files with a `baseurl=` on `mirror.stream.centos.org`, and then includes `fedora.yml`. The [Dockerfile](../../Dockerfile) runs the same script before its first `dnf` call, so the CentOS dev and swarm-node images resolve against the same source. +`centos.yml` first runs [centos_mirror.sh](files/shell/centos_mirror.sh), which replaces every `metalink=` of the CentOS Stream repo files with a `baseurl=` on `mirror.stream.centos.org` and every `metalink=` of the EPEL repo files with the file's own `baseurl` template on `dl.fedoraproject.org`, and then includes `fedora.yml`. The [Dockerfile](../../Dockerfile) runs the same script before its first `dnf` call, so the CentOS dev and swarm-node images resolve against the same source. ## Cosmos diff --git a/roles/update/files/shell/centos_mirror.sh b/roles/update/files/shell/centos_mirror.sh index d44cbc66aa..0c69851241 100755 --- a/roles/update/files/shell/centos_mirror.sh +++ b/roles/update/files/shell/centos_mirror.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Param: none. Rewrites the CentOS Stream repo files in /etc/yum.repos.d in place and prints the metalink repo of every section it pinned; prints nothing when there is nothing left to pin. +# Param: none. Rewrites the CentOS Stream and EPEL repo files in /etc/yum.repos.d in place and prints the metalink repo or EPEL file of everything it pinned; prints nothing when there is nothing left to pin, exits 1 on an EPEL file whose metalinks lack their baseurl template. set -euo pipefail master="https://mirror.stream.centos.org" @@ -36,3 +36,24 @@ done pin "centos-extras-sig-extras-common-[\$]stream" "SIGs/\$stream/extras/\$basearch/extras-common" pin "centos-extras-sig-extras-common-source-[\$]stream" "SIGs/\$stream/extras/source/extras-common" + +pin_epel() { + local file="$1" metalinks templates + metalinks="$(awk '/^metalink=https:\/\/mirrors\.fedoraproject\.org\// { n++ } END { print n + 0 }' "${file}")" + templates="$(awk '/^#baseurl=https:\/\/download\.example\/pub\/epel\// { n++ } END { print n + 0 }' "${file}")" + [[ "${metalinks}" -gt 0 ]] || return 0 + if [[ "${templates}" -ne "${metalinks}" ]]; then + echo "ERROR: ${file} has ${metalinks} Fedora metalinks but ${templates} download.example baseurl templates" >&2 + exit 1 + fi + sed -i -E \ + -e 's|^#baseurl=https://download\.example/pub/epel/|baseurl=https://dl.fedoraproject.org/pub/epel/|' \ + -e '/^metalink=https:\/\/mirrors\.fedoraproject\.org\//d' \ + "${file}" + echo "${file##*/}" +} + +for file in "${repo_dir}"/epel*.repo; do + [[ -f "${file}" ]] || continue + pin_epel "${file}" +done diff --git a/roles/update/tasks/centos.yml b/roles/update/tasks/centos.yml index 2908c2ddc5..f09165b328 100644 --- a/roles/update/tasks/centos.yml +++ b/roles/update/tasks/centos.yml @@ -1,5 +1,5 @@ --- -- name: "📌 update (dnf) | pin the CentOS Stream repos to mirror.stream.centos.org" +- name: "📌 update (dnf) | pin the CentOS Stream and EPEL repos to their master mirrors" become: true ansible.builtin.script: shell/centos_mirror.sh register: update_centos_pinned diff --git a/roles/web-app-erpnext/meta/services.yml b/roles/web-app-erpnext/meta/services.yml index 1abb8b0bfb..765ba169e0 100644 --- a/roles/web-app-erpnext/meta/services.yml +++ b/roles/web-app-erpnext/meta/services.yml @@ -68,7 +68,7 @@ erpnext: enabled: true shared: true image: frappe/erpnext - version: "v16.52.0" + version: "v16.52.1" name: erpnext min_storage: 1017MB ports: diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index bf32bc843b..7d32a3d957 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -75,7 +75,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "2.45.1" + version: "2.45.2" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-peertube/files/sql/check-application/defaults.sql b/roles/web-app-peertube/files/sql/check-application/defaults.sql index 4f3232e046..023a3dd811 100644 --- a/roles/web-app-peertube/files/sql/check-application/defaults.sql +++ b/roles/web-app-peertube/files/sql/check-application/defaults.sql @@ -1,7 +1,6 @@ -SELECT a.attname -FROM pg_catalog.pg_attribute a -LEFT JOIN pg_catalog.pg_attrdef d - ON d.adrelid = a.attrelid AND d.adnum = a.attnum -WHERE a.attrelid = 'public.application'::regclass - AND a.attname IN ('nodeVersion', 'nodeABIVersion') - AND d.adbin IS NULL; +SELECT column_name +FROM information_schema.columns +WHERE table_schema = 'public' + AND table_name = 'application' + AND column_name IN ('nodeVersion', 'nodeABIVersion') + AND column_default IS NULL; diff --git a/roles/web-app-peertube/tasks/02_fix-application-schema.yml b/roles/web-app-peertube/tasks/02_fix-application-schema.yml index 2c7167ca7f..b14d23918b 100644 --- a/roles/web-app-peertube/tasks/02_fix-application-schema.yml +++ b/roles/web-app-peertube/tasks/02_fix-application-schema.yml @@ -42,11 +42,12 @@ and (_peertube_app_table_check.rows[0][0] | default('')) == 'application' changed_when: false -- name: "🔎 PEERTUBE | Read which of the two columns still carries no default" +- name: "🔍 PEERTUBE | Find the bootstrap columns that still lack a default" database_query: mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" config: "{{ lookup('database', application_id) }}" query: "{{ lookup('file', role_path ~ '/files/sql/check-application/defaults.sql') }}" # nocheck: database-query-raw controller-read so the SQL travels to the remote swarm host that lacks the repo files + expect_rows: true register: _peertube_app_defaults_missing changed_when: false @@ -55,7 +56,7 @@ mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" config: "{{ lookup('database', application_id) }}" query: "{{ lookup('file', role_path ~ '/files/sql/backfill-application-defaults.sql') }}" # nocheck: database-query-raw controller-read so the SQL travels to the remote swarm host that lacks the repo files - when: (_peertube_app_defaults_missing.rows | default([]) | length) > 0 + when: _peertube_app_defaults_missing.rows | length > 0 changed_when: true notify: compose-up diff --git a/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh b/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh index 426d3d1502..c3a5e5d1bf 100755 --- a/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh +++ b/scripts/tests/deploy/swarm/utils/unmount/nfs_mounts.sh @@ -16,7 +16,7 @@ for container in "$@"; do docker inspect "${container}" >/dev/null 2>&1 || continue echo ">>> swarm-cleanup: detach NFS mounts inside ${container}" - if ! timeout "${NFS_CONTAINER_TIMEOUT}" docker exec -e NFS_UNMOUNT_TIMEOUT="${NFS_UNMOUNT_TIMEOUT}" "${container}" sh -s <<'SH'; then + if ! timeout "${NFS_CONTAINER_TIMEOUT}" docker exec -e NFS_UNMOUNT_TIMEOUT="${NFS_UNMOUNT_TIMEOUT}" "${container}" sh -s <<'SH' set -eu mounts="$( @@ -62,6 +62,7 @@ printf '%s\n' "${mounts}" | while IFS= read -r mount_point; do fi done SH + then echo "WARNING: could not inspect/unmount NFS mounts inside ${container} (gave up after ${NFS_CONTAINER_TIMEOUT})" >&2 fi done diff --git a/tests/unit/python/library/test_database_query.py b/tests/unit/python/library/test_database_query.py index 83ae8969d8..2f9d53e125 100644 --- a/tests/unit/python/library/test_database_query.py +++ b/tests/unit/python/library/test_database_query.py @@ -93,13 +93,13 @@ class BuildCmdPostgresTests(unittest.TestCase): self.assertIn("ON_ERROR_STOP=1", cmd) self.assertNotIn("s3cret", cmd) - def test_postgres_expect_rows_adds_tuples_only_flag(self): + def test_postgres_expect_rows_adds_quiet_tuples_only_flag(self): cmd, _ = _DB_MOD._build_cmd(_BASE_CONFIG, expect_rows=True) - self.assertIn("-tA", cmd) + self.assertIn("-qtA", cmd) def test_postgres_no_rows_omits_tuples_only_flag(self): cmd, _ = _DB_MOD._build_cmd(_BASE_CONFIG, expect_rows=False) - self.assertNotIn("-tA", cmd) + self.assertNotIn("-qtA", cmd) class BuildCmdMariadbTests(unittest.TestCase): diff --git a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py index d7ea8b8b90..e9c72826dd 100644 --- a/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py +++ b/tests/unit/python/roles/svc-opt-ssd-hdd/test_storage_optimizer.py @@ -54,5 +54,31 @@ class TestHealthCheckLogic(unittest.TestCase): ) +class TestIsDatabase(unittest.TestCase): + def test_classification(self): + test_cases = [ + ("postgres_custom:18", True), + ("openldap_custom:13.7-slim", True), + ("mariadb_custom:11.8", True), + ("postgis/postgis:17-3.5", True), + ("valkey/valkey:8", True), + ("docker.io/library/postgres:18", True), + ("ghcr.io/infinito-nexus/mirror/docker.io/library/postgres:18", True), + ("registry.infinito.test:5000/openldap_custom:13.7-slim", True), + ("postgres@sha256:" + "0" * 64, True), + ("docker.elastic.co/elasticsearch/elasticsearch:9.1.0", True), + ("bigbluebutton_custom:v3.0.39", False), + ("registry.infinito.test:5000/nextcloud:31", False), + ("ghcr.io/ldapaccountmanager/lam:9", False), + ("phpldapadmin/phpldapadmin:2", False), + ] + for image_name, expected in test_cases: + self.assertEqual( + storage_optimizer.is_database(image_name), + expected, + f"Image {image_name} expected {expected}", + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/install/lint/test_main.py b/tests/unit/python/utils/install/lint/test_main.py index 1ac3539ca8..be096bf743 100644 --- a/tests/unit/python/utils/install/lint/test_main.py +++ b/tests/unit/python/utils/install/lint/test_main.py @@ -17,6 +17,8 @@ def _make_repo_root(tmp: str, *, stamp_age_offset: float | None = None) -> Path: (root / "scripts" / "install").mkdir(parents=True) (root / "scripts" / "install" / "lint.sh").write_text("#\n", encoding="utf-8") (root / "pyproject.toml").write_text("[project]\n", encoding="utf-8") + (root / cli._PINS).parent.mkdir(parents=True) + (root / cli._PINS).write_text("---\n", encoding="utf-8") if stamp_age_offset is not None: stamp = root / cli._STAMP stamp.parent.mkdir(parents=True, exist_ok=True) @@ -86,6 +88,24 @@ class TestStampLogic(unittest.TestCase): inst.assert_called_once() self.assertTrue((root / cli._STAMP).exists()) + def test_a_newer_release_pin_triggers_install(self) -> None: + with TemporaryDirectory() as tmp: + root = _make_repo_root(tmp, stamp_age_offset=60.0) + pins = root / cli._PINS + later = time.time() + 120.0 + os.utime(pins, (later, later)) + with ( + mock.patch.object(cli, "PROJECT_ROOT", root), + mock.patch.object(cli.shutil, "which", return_value="/usr/bin/x"), + mock.patch.object( + cli.mermaid_cli, "browser_installed", return_value=True + ), + mock.patch.object(cli, "_install_all") as inst, + ): + rc = cli.main([]) + self.assertEqual(rc, 0) + inst.assert_called_once() + def test_no_stamp_triggers_install_and_touches(self) -> None: with TemporaryDirectory() as tmp: root = _make_repo_root(tmp) diff --git a/tests/unit/python/utils/install/lint/test_shfmt.py b/tests/unit/python/utils/install/lint/test_shfmt.py new file mode 100644 index 0000000000..95b63997a5 --- /dev/null +++ b/tests/unit/python/utils/install/lint/test_shfmt.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import subprocess +import unittest +import unittest.mock as mock + +from utils.install.lint import shfmt + +_WANT = shfmt.resolve_release("shfmt")[1] + + +def _ensure(*versions: str | None) -> mock.MagicMock: + with ( + mock.patch.object(shfmt, "_installed_version", side_effect=list(versions)), + mock.patch.object(shfmt, "_install_binary") as install, + ): + shfmt.ensure() + return install + + +class TestEnsure(unittest.TestCase): + def test_the_pinned_release_stays(self) -> None: + _ensure(_WANT).assert_not_called() + + def test_a_distribution_release_is_replaced(self) -> None: + _ensure("3.8.0", _WANT).assert_called_once() + + def test_a_missing_shfmt_is_installed(self) -> None: + _ensure(None, _WANT).assert_called_once() + + def test_a_shadowed_install_fails_loudly(self) -> None: + with self.assertRaisesRegex(RuntimeError, "must precede"): + _ensure("3.8.0", "3.8.0") + + +class TestInstalledVersion(unittest.TestCase): + def _version(self, **run: object) -> str | None: + with mock.patch.object(shfmt.subprocess, "run", **run): + return shfmt._installed_version() + + def test_a_release_binary_drops_its_v(self) -> None: + done = subprocess.CompletedProcess([], 0, stdout="v3.14.1\n", stderr="") + self.assertEqual(self._version(return_value=done), "3.14.1") + + def test_a_distribution_build_reads_as_is(self) -> None: + done = subprocess.CompletedProcess([], 0, stdout="3.8.0\n", stderr="") + self.assertEqual(self._version(return_value=done), "3.8.0") + + def test_a_missing_binary_reads_as_none(self) -> None: + self.assertIsNone(self._version(side_effect=FileNotFoundError("shfmt"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/install/lint/__main__.py b/utils/install/lint/__main__.py index 9fed403e4b..432167f92a 100644 --- a/utils/install/lint/__main__.py +++ b/utils/install/lint/__main__.py @@ -37,12 +37,15 @@ from utils.install.lint.ansible import collections as ansible_collections from utils.install.lint.ansible import commands as ansible_commands from utils.install.lint.ansible import lint as ansible_lint from utils.install.primitives import warn +from utils.roles.mapping import ROLE_FILE_META_SERVICES _STAMP_KEY = hashlib.sha256(sys.executable.encode("utf-8")).hexdigest()[:8] _STAMP = f"build/install-lint-{_STAMP_KEY}.stamp" +_PINS = f"roles/sys-lint/{ROLE_FILE_META_SERVICES}" _STAMP_DEPS = ( "scripts/install/lint.sh", "pyproject.toml", + _PINS, ) _STAMP_TOOLS = ( diff --git a/utils/install/lint/shfmt.py b/utils/install/lint/shfmt.py index 90b822f24e..51385983de 100644 --- a/utils/install/lint/shfmt.py +++ b/utils/install/lint/shfmt.py @@ -1,9 +1,10 @@ -"""Install shfmt: system-pkg first, GitHub release fallback.""" +"""Install shfmt via GitHub-release prebuilt binary.""" from __future__ import annotations import os import platform +import subprocess import tempfile from pathlib import Path @@ -13,9 +14,7 @@ from utils.install.primitives import ( ensure_dir_on_path, install_with_optional_sudo, log, - which, ) -from utils.install.system_pkg import detect_package_manager, install_command_via_pkg # nocheck: environ-get-default contributor tooling, never deployed: no inventory or image declares SHFMT_INSTALL_DIR, it only lets a workstation without write access to /usr/local/bin redirect the binary _DEFAULT_INSTALL_DIR = os.environ.get("SHFMT_INSTALL_DIR", "/usr/local/bin") @@ -63,27 +62,29 @@ def _install_binary() -> None: ensure_dir_on_path(_DEFAULT_INSTALL_DIR) -def ensure() -> None: - if which("shfmt"): - return - - log("Missing command 'shfmt'. Attempting system package installation.") +def _installed_version() -> str | None: try: - manager = detect_package_manager() - try: - install_command_via_pkg("shfmt") - except RuntimeError as exc: - log(f"System package install failed for 'shfmt' via {manager}: {exc}") - except RuntimeError: - log( - "No supported package manager found; falling back to GitHub release binary." + proc = subprocess.run( + ["shfmt", "--version"], capture_output=True, text=True, check=True ) + except (OSError, subprocess.CalledProcessError): + return None + return proc.stdout.strip().lstrip("v") or None - if which("shfmt"): + +def ensure() -> None: + _slug, want = resolve_release("shfmt") + found = _installed_version() + if found == want: return - log("Falling back to official shfmt binary.") + log(f"Installing shfmt v{want} (found {found or 'no shfmt'}).") _install_binary() - if not which("shfmt"): - raise RuntimeError("Command 'shfmt' is still unavailable after installation.") + found = _installed_version() + if found != want: + raise RuntimeError( + f"Command 'shfmt' reports {found or 'nothing'} after installing " + f"v{want} into {_DEFAULT_INSTALL_DIR}; that directory must precede " + "any other shfmt on PATH." + )