From b17807faa3ff0132fe050a4446dddf98a2e58211 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 27 Oct 2026 13:35:30 +0100 Subject: [PATCH 01/21] fix(web-app-nextcloud): probe the Context Agent without curl Context Agent 2.10.0 (bumped in #1219) moved to a multi-stage image whose runtime stage ships no curl ("no vim, no git, no curl, no pipx/poetry", nextcloud/context_agent Dockerfile at v2.10.0). The curl healthcheck then fails with `exec: "curl": executable file not found in $PATH`, the task never leaves `starting`, and the swarm converge wait gives up on nextcloud_context_agent (main run 40401200083, Nextcloud#2). Switch to the http_status flavor, which speaks HTTP over bash's /dev/tcp and still requires a 2xx/3xx answer from /heartbeat. Co-Authored-By: Claude Opus 5.5 --- roles/web-app-nextcloud/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 1e35ea097a..eabc21d99a 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -155,7 +155,7 @@ context_agent: internal: http: 23000 healthcheck: - flavor: curl + flavor: http_status path: heartbeat # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it start_period: 20m From bebb366bd52113b0609588c6f192b43d051c2585 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:55:58 +0000 Subject: [PATCH 02/21] update(images): update Docker image versions (web-app-checkmk) --- roles/web-app-checkmk/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-checkmk/meta/services.yml b/roles/web-app-checkmk/meta/services.yml index 7790cd70ba..7e36215ffc 100644 --- a/roles/web-app-checkmk/meta/services.yml +++ b/roles/web-app-checkmk/meta/services.yml @@ -71,7 +71,7 @@ checkmk: pids_limit: 2048 min_storage: 1053MB image: checkmk/check-mk-raw - version: "2.4.0p38" + version: "2.4.0p39" backup: no_stop_required: true name: checkmk From d1f5847f042008f1f631d13f8d8b3c272f6fad80 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:56:05 +0000 Subject: [PATCH 03/21] update(images): update Docker image versions (web-app-openbao) --- roles/web-app-openbao/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-openbao/meta/services.yml b/roles/web-app-openbao/meta/services.yml index 53108ab4cb..8f8a9e2276 100644 --- a/roles/web-app-openbao/meta/services.yml +++ b/roles/web-app-openbao/meta/services.yml @@ -77,7 +77,7 @@ openbao: # nocheck: dynamic-flag build-stage image, not group-gated auth-ldap: image: ghcr.io/openbao/openbao-plugin-auth-ldap - version: "v0.1.0" + version: "v0.2.0" enabled: false # nocheck: playwright-service-flag From 9804ad47f7928ba65a55559f39a838cc9ddc96a2 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:58:16 +0000 Subject: [PATCH 04/21] update(versions): update pins with a declared source (web-app-n8n) --- roles/web-app-n8n/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 078823fdfc..cb068ec35d 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "2.45.4" + version: "3.0.0" update: type: registry_tags image: docker.n8n.io/n8nio/n8n From 49e053806c88546a8c97a6556fc7a406c510e211 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 27 Oct 2026 16:23:58 +0100 Subject: [PATCH 05/21] fix(web-app-stalwart): enforce the 31M body limit through server.yml and redirect the Mailu webmail path client_max_body_size 31M sat in the server block of the mail vhost, where the client_max_body_size of location / (server.client_max_body_size, 100m by default) overrode it. It now lives in meta/server.yml, so both Stalwart vhosts enforce 31M. The extra configuration of the mail vhost instead answers the legacy Mailu path /webmail with a 301 to the Roundcube base URL. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-stalwart/meta/server.yml | 1 + roles/web-app-stalwart/tasks/00_core.yml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/roles/web-app-stalwart/meta/server.yml b/roles/web-app-stalwart/meta/server.yml index 2d8044978c..00c3183855 100644 --- a/roles/web-app-stalwart/meta/server.yml +++ b/roles/web-app-stalwart/meta/server.yml @@ -1,4 +1,5 @@ --- +client_max_body_size: 31M status_codes: default: - 302 diff --git a/roles/web-app-stalwart/tasks/00_core.yml b/roles/web-app-stalwart/tasks/00_core.yml index f53d91ed82..26519610f1 100644 --- a/roles/web-app-stalwart/tasks/00_core.yml +++ b/roles/web-app-stalwart/tasks/00_core.yml @@ -79,7 +79,7 @@ vars: compose_handlers_flush: true webserver_vhost_flavour: "basic" - webserver_extra_configuration: "client_max_body_size 31M;" + webserver_extra_configuration: "location ^~ /webmail { return 301 {{ STALWART_WEBMAIL_BASE_URL }}/; }" proxy_forwarded_client_address: true domain: "{{ STALWART_WEB_DOMAIN }}" From 812ca4e3d7e4345dfc71a422e1ea3a3ff130dd3b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 27 Oct 2026 16:36:14 +0100 Subject: [PATCH 06/21] fix(web-svc-coturn): size the TURN allocation quota for Talk calls and test a six-person call coturn ran with a fixed --total-quota=100 for the whole server. A Nextcloud Talk call through the HPB opens N peer connections per participant and one allocation per TURN transport, about 2*N^2 allocations, so calls of more than about five participants ran out. services.coturn.total_quota now sets the quota, 2000 by default; on echoserver eight participants held connected media with it. The Nextcloud Playwright suite gains test-talk-call-capacity, gated like the Talk admin test: as administrator it creates a public room through the Talk API, joins six guests in separate contexts with fake media, and requires every guest to hold a connected peer connection to every participant and no TURN 486 Allocation Quota Reached. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/playwright/playwright.spec.js | 1 + .../playwright/test-talk-call-capacity.js | 109 ++++++++++++++++++ roles/web-svc-coturn/README.md | 1 + roles/web-svc-coturn/meta/services.yml | 1 + roles/web-svc-coturn/templates/compose.yml.j2 | 2 +- roles/web-svc-coturn/vars/main.yml | 1 + 6 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js diff --git a/roles/web-app-nextcloud/files/playwright/playwright.spec.js b/roles/web-app-nextcloud/files/playwright/playwright.spec.js index 7b62b8a83e..ff114cd6d8 100644 --- a/roles/web-app-nextcloud/files/playwright/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright/playwright.spec.js @@ -19,6 +19,7 @@ test.use({ test.beforeEach(shared.beforeEach); require("./test-talk-admin-settings").register(shared); +require("./test-talk-call-capacity").register(shared); require("./test-login-admin-oidc").register(shared); require("./test-login-admin-native").register(shared); require("./test-login-biber-oidc").register(shared); diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js new file mode 100644 index 0000000000..5eacba51c1 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js @@ -0,0 +1,109 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout, isOnionTarget } = require("./timeouts"); +const { decodeDotenvQuotedValue, gotoOnion } = require("./personas"); + +const talkEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED) === "true"; +const callParticipants = 6; +const ocsHeaders = { "OCS-APIRequest": "true", Accept: "application/json" }; +const joinCallPattern = /^(join call|start call|anruf beitreten|anruf starten)$/i; +const leaveCallPattern = /^(leave call|anruf verlassen)$/i; +const displayNamePattern = /display name|anzeigename/i; +const turnQuotaReachedCode = 486; + +function trackPeerConnections() { + const Original = window.RTCPeerConnection; + const stats = { connections: [], iceErrorCodes: [] }; + window.__talkCallStats = stats; + function Tracked(...args) { + const connection = new Original(...args); + stats.connections.push(connection); + connection.addEventListener("icecandidateerror", (event) => stats.iceErrorCodes.push(event.errorCode)); + return connection; + } + Tracked.prototype = Original.prototype; + Object.setPrototypeOf(Tracked, Original); + window.RTCPeerConnection = Tracked; +} + +function readCallStats(page) { + return page.evaluate(() => { + const stats = window.__talkCallStats; + return { + connected: stats.connections.filter((connection) => connection.connectionState === "connected").length, + iceErrorCodes: stats.iceErrorCodes, + }; + }); +} + +async function createPublicRoom(page, baseUrl) { + const response = await page.request.post(`${baseUrl}/ocs/v2.php/apps/spreed/api/v4/room`, { + headers: ocsHeaders, + data: { roomType: 3, roomName: `Playwright call capacity ${Date.now()}` }, + }); + expect(response.ok(), `creating the public Talk room answered HTTP ${response.status()}`).toBeTruthy(); + return (await response.json()).ocs.data.token; +} + +async function joinCallAsGuest(browser, roomUrl, name) { + const context = await browser.newContext({ ignoreHTTPSErrors: true, permissions: ["camera", "microphone"] }); + await context.addInitScript(trackPeerConnections); + const page = await context.newPage(); + await gotoOnion(page, roomUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + const dialog = page.getByRole("dialog"); + await dialog.getByLabel(displayNamePattern).first().fill(name, { timeout: resolveTimeout(60_000) }); + const joinButton = dialog.getByRole("button", { name: joinCallPattern }).last(); + await expect(joinButton, `${name}: the join button stays disabled after the display name`).toBeEnabled({ + timeout: resolveTimeout(30_000), + }); + await joinButton.click({ timeout: resolveTimeout(30_000) }); + await expect(page.getByRole("button", { name: leaveCallPattern }).first(), `${name} never entered the call`).toBeVisible({ + timeout: resolveTimeout(60_000), + }); + return { name, page, context }; +} + +exports.register = function (shared) { + test("nextcloud talk call holds more than five participants", async ({ browser }) => { + test.skip(!talkEnabled, "Talk is disabled in the current Playwright env"); + test.skip(isOnionTarget(), "Nextcloud Talk realtime (HPB signaling + STUN/TURN) is WebRTC; not reachable over Tor"); + test.setTimeout(resolveTimeout(15 * 60_000)); + + const baseUrl = shared.env.nextcloudBaseUrl; + const adminContext = await browser.newContext({ ignoreHTTPSErrors: true }); + const adminPage = await adminContext.newPage(); + const guests = []; + let token = ""; + + try { + await shared.loginToStandaloneNextcloud(adminPage); + token = await createPublicRoom(adminPage, baseUrl); + + for (let index = 1; index <= callParticipants; index += 1) { + guests.push(await joinCallAsGuest(browser, `${baseUrl}/call/${token}`, `Playwright guest ${index}`)); + } + + for (const guest of guests) { + await expect + .poll(async () => (await readCallStats(guest.page)).connected, { + timeout: resolveTimeout(120_000), + message: `${guest.name} must hold a connected peer connection to every participant of the ${callParticipants}-person call`, + }) + .toBeGreaterThanOrEqual(callParticipants); + expect( + (await readCallStats(guest.page)).iceErrorCodes, + `${guest.name}: TURN answered ${turnQuotaReachedCode} Allocation Quota Reached`, + ).not.toContain(turnQuotaReachedCode); + } + } finally { + for (const guest of guests) { + await guest.context.close().catch(() => {}); + } + if (token) { + await adminPage.request + .delete(`${baseUrl}/ocs/v2.php/apps/spreed/api/v4/room/${token}`, { headers: ocsHeaders }) + .catch(() => {}); + } + await adminContext.close().catch(() => {}); + } + }); +}; diff --git a/roles/web-svc-coturn/README.md b/roles/web-svc-coturn/README.md index bf4a9773a2..73134bbb5d 100644 --- a/roles/web-svc-coturn/README.md +++ b/roles/web-svc-coturn/README.md @@ -77,6 +77,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - Automatic TLS handling via `sys-stk-front-base` - TURN and STUN support over TCP and UDP - Configurable relay port ranges for scaling +- Configurable server-wide allocation quota (`services.coturn.total_quota`, default 2000); size it at about 2ยทNยฒ for every concurrent Nextcloud Talk call with N participants, as each participant opens N peer connections and requests one allocation per TURN transport - Integration into Infinito.Nexus inventory/variable system ## Quick Setup diff --git a/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 768dcf9ccb..ed17e5a592 100644 --- a/roles/web-svc-coturn/meta/services.yml +++ b/roles/web-svc-coturn/meta/services.yml @@ -12,6 +12,7 @@ coturn: version: 4.18.0 min_storage: 246MB user_auth_enabled: false + total_quota: 2000 cpus: 1.0 mem_reservation: 512m mem_limit: 1g diff --git a/roles/web-svc-coturn/templates/compose.yml.j2 b/roles/web-svc-coturn/templates/compose.yml.j2 index e9b4b8dc58..53a6e26cdf 100644 --- a/roles/web-svc-coturn/templates/compose.yml.j2 +++ b/roles/web-svc-coturn/templates/compose.yml.j2 @@ -53,7 +53,7 @@ {% endif %} --realm="${COTURN_REALM}" --fingerprint - --total-quota=100 + --total-quota={{ COTURN_TOTAL_QUOTA }} --stale-nonce --no-multicast-peers --no-cli diff --git a/roles/web-svc-coturn/vars/main.yml b/roles/web-svc-coturn/vars/main.yml index 1fd172c9aa..a198b9a548 100644 --- a/roles/web-svc-coturn/vars/main.yml +++ b/roles/web-svc-coturn/vars/main.yml @@ -11,6 +11,7 @@ COTURN_STUN_TURN_PORT: "{{ lookup('config', application_id, 'services.coturn.por COTURN_STUN_TURN_PORT_TLS: "{{ lookup('config', application_id, 'services.coturn.ports.public.stun_turn_tls') }}" COTURN_RELAY_PORT_START: "{{ lookup('config', application_id, 'services.coturn.ports.public.relay.start') }}" COTURN_RELAY_PORT_END: "{{ lookup('config', application_id, 'services.coturn.ports.public.relay.end') }}" +COTURN_TOTAL_QUOTA: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.total_quota') }}" COTURN_USER_NAME: "{{ lookup('users', 'coturnconsumer').username }}" COTURN_USER_PASSWORD: "{{ lookup('users', 'coturnconsumer').password }}" From a8fba45d605eb212255467151d78b79fe2b89892 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:26:06 +0000 Subject: [PATCH 07/21] update(images): update Docker image versions (web-app-matrix) --- roles/web-app-matrix/meta/services.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 841de75aec..1b9c8afaa6 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -80,7 +80,7 @@ postgres: synapse: healthcheck: flavor: curl - version: v1.163.2 + version: v1.164.0 image: matrixdotorg/synapse name: matrix-synapse backup: @@ -103,7 +103,7 @@ synapse: element: healthcheck: flavor: wget - version: v1.12.32 + version: v1.12.33 image: vectorim/element-web name: matrix-element ports: From c9ba7a71d1456bf76583c94b62ea2884ad589419 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 27 Oct 2026 17:34:15 +0100 Subject: [PATCH 08/21] fix(web-app-peertube): map release 8.3.2 to migration 1130 The role pins v8.3.2, which LAST_MIGRATION_VERSIONS did not list, so peertube_migration_version aborted every deploy. 8.3.2 keeps LAST_MIGRATION_VERSION 1130 from upstream server/core/initializers/constants.ts. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-peertube/filter_plugins/peertube_upgrade.py | 1 + 1 file changed, 1 insertion(+) diff --git a/roles/web-app-peertube/filter_plugins/peertube_upgrade.py b/roles/web-app-peertube/filter_plugins/peertube_upgrade.py index 4f54ba685f..0f078daaa0 100644 --- a/roles/web-app-peertube/filter_plugins/peertube_upgrade.py +++ b/roles/web-app-peertube/filter_plugins/peertube_upgrade.py @@ -46,6 +46,7 @@ LAST_MIGRATION_VERSIONS: dict[str, int] = { "8.2.4": 1040, "8.3.0": 1125, "8.3.1": 1130, + "8.3.2": 1130, } _RELEASE_RE = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$") From 2b603caa20ee4eb971c0ab5a7095c06dc7e0b7ec Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 27 Oct 2026 17:36:21 +0100 Subject: [PATCH 09/21] feat(sys-svc-journalctl): cap the persistent journal at a share of its disk SystemMaxUse was unset, so journald fell back to 10 % capped at 4 GiB regardless of the host. The role now measures the filesystem that holds /var/log/journal with df and sets SystemMaxUse to services.svc-journalctl.system_max_use_percent of it, 2 % by default, overridable per host in the inventory. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-svc-journalctl/README.md | 1 + roles/sys-svc-journalctl/meta/services.yml | 1 + roles/sys-svc-journalctl/tasks/main.yml | 16 ++++++++++++++++ .../templates/journald.conf.j2 | 2 +- roles/sys-svc-journalctl/vars/main.yml | 3 +++ 5 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 roles/sys-svc-journalctl/vars/main.yml diff --git a/roles/sys-svc-journalctl/README.md b/roles/sys-svc-journalctl/README.md index c874e8caee..d0bd657cbd 100644 --- a/roles/sys-svc-journalctl/README.md +++ b/roles/sys-svc-journalctl/README.md @@ -6,6 +6,7 @@ This Ansible role manages the configuration of `systemd-journald` on target host - Copies a customized `journald.conf` to `/etc/systemd/journald.conf` - Ensures log retention for one week +- Caps the persistent journal (`SystemMaxUse=`) at `system_max_use_percent` of the filesystem holding `/var/log/journal`, 2 % by default (`meta/services.yml`) - Restarts the `systemd-journald` service when configuration changes - Supports live log streaming via `journalctl -f` diff --git a/roles/sys-svc-journalctl/meta/services.yml b/roles/sys-svc-journalctl/meta/services.yml index f824a9b382..b7c8c2a7e3 100644 --- a/roles/sys-svc-journalctl/meta/services.yml +++ b/roles/sys-svc-journalctl/meta/services.yml @@ -2,3 +2,4 @@ # nocheck: required-by-coverage โ€” TODO: declare proper required_by svc-journalctl: lifecycle: beta + system_max_use_percent: 2 diff --git a/roles/sys-svc-journalctl/tasks/main.yml b/roles/sys-svc-journalctl/tasks/main.yml index 92f5f3bc41..8cd6096ff2 100644 --- a/roles/sys-svc-journalctl/tasks/main.yml +++ b/roles/sys-svc-journalctl/tasks/main.yml @@ -7,6 +7,22 @@ - include_tasks: utils/once/flag.yml when: run_once_sys_svc_journalctl is not defined +- name: ๐Ÿ” Check whether the persistent journal directory exists + ansible.builtin.stat: + path: "{{ SYS_SVC_JOURNALCTL_DIRECTORY }}" + register: sys_svc_journalctl_directory + +- name: ๐Ÿ“ Measure the filesystem that holds the persistent journal + ansible.builtin.command: + argv: + - df + - --output=size + - --block-size=1M + - "{{ SYS_SVC_JOURNALCTL_DIRECTORY if sys_svc_journalctl_directory.stat.exists else (SYS_SVC_JOURNALCTL_DIRECTORY | dirname) }}" + register: sys_svc_journalctl_filesystem + changed_when: false + check_mode: false + - name: ๐Ÿ“‹ copy journald.conf template: # nocheck: stack-host-template (per-host /etc/systemd/journald.conf, not stack-host-only) src: templates/journald.conf.j2 diff --git a/roles/sys-svc-journalctl/templates/journald.conf.j2 b/roles/sys-svc-journalctl/templates/journald.conf.j2 index 4ea46df775..0cf6395507 100644 --- a/roles/sys-svc-journalctl/templates/journald.conf.j2 +++ b/roles/sys-svc-journalctl/templates/journald.conf.j2 @@ -20,7 +20,7 @@ #SyncIntervalSec=5m #RateLimitIntervalSec=30s #RateLimitBurst=10000 -#SystemMaxUse= +SystemMaxUse={{ ((sys_svc_journalctl_filesystem.stdout_lines | last | int) * (SYS_SVC_JOURNALCTL_SYSTEM_MAX_USE_PERCENT | float) / 100) | int }}M #SystemKeepFree= #SystemMaxFileSize= #SystemMaxFiles=100 diff --git a/roles/sys-svc-journalctl/vars/main.yml b/roles/sys-svc-journalctl/vars/main.yml new file mode 100644 index 0000000000..0f6e4d096e --- /dev/null +++ b/roles/sys-svc-journalctl/vars/main.yml @@ -0,0 +1,3 @@ +--- +SYS_SVC_JOURNALCTL_DIRECTORY: /var/log/journal +SYS_SVC_JOURNALCTL_SYSTEM_MAX_USE_PERCENT: "{{ lookup('config', 'sys-svc-journalctl', 'services.svc-journalctl.system_max_use_percent') }}" From 82af35f4326281e6429d9a305e346a36509086c4 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:30:38 +0000 Subject: [PATCH 10/21] update(images): update Docker image versions (web-app-xwiki) --- roles/web-app-xwiki/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-xwiki/meta/services.yml b/roles/web-app-xwiki/meta/services.yml index 464373e48f..49023e8b3f 100644 --- a/roles/web-app-xwiki/meta/services.yml +++ b/roles/web-app-xwiki/meta/services.yml @@ -56,7 +56,7 @@ xwiki: enabled: true # nocheck: dynamic-flag shared: true image: xwiki - version: 18.8.0-postgres-tomcat + version: 18.9.0-postgres-tomcat custom: true name: xwiki min_storage: 965MB From a0ef5e0c562e92e093a7e9b96d68765456d9ccda Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:39:31 +0000 Subject: [PATCH 11/21] update(versions): update pins with a declared source (web-app-hugo) --- roles/web-app-hugo/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index 98f3b15f8d..7b999515d9 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -35,7 +35,7 @@ hugo: version: 1.31-alpine custom: true builder_image: ghcr.io/gohugoio/hugo - builder_version: v0.168.0 + builder_version: v0.169.0 source_repository: https://github.com/gohugoio/hugoDocs.git source_version: v0.165.0 update: From a6838f7a11f4a7ae0ce719e960c29e32fa576b4e Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:55:19 +0000 Subject: [PATCH 12/21] update(images): update Docker image versions (svc-ai-ollama) --- roles/svc-ai-ollama/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index c9672eb6d7..1c39365e90 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.40.11 + version: 0.40.12 name: ollama min_storage: 3473MB cpus: "4.0" From f0382013f11bdcfa94dda5bca1a7d33c730ad3f0 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:55:24 +0000 Subject: [PATCH 13/21] update(images): update Docker image versions (web-app-socialhome) --- roles/web-app-socialhome/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index bf86e05e13..2d1238bd0b 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -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.24" + version: "2026.10.27" ports: local: http: 8089 From bcc049dbcdd414fee9aebe08a22ab0bf39690e96 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:00:02 +0100 Subject: [PATCH 14/21] fix(web-app-nextcloud): make the Talk call capacity spec join guests the way Talk does The spec could never pass. It built URLs as ${baseUrl}/call/ with a base that already ends in a slash, so Talk's client router matched no route and rendered an empty page. It also expected a single display-name dialog, while Talk shows a welcome dialog (Enter your name, Submit name and join) when no call runs and a device check with a display name field when one does. And its guests had no media devices, so no peer connection ever formed. URLs now go through new URL(path, base) like every other Nextcloud spec, joinCallAsGuest follows both dialogs, and the guests run in a dedicated Chromium with fake media devices and a regular Chrome user agent, because Talk's unsupported-browser toast for HeadlessChrome covers the call button. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../playwright/test-talk-call-capacity.js | 45 ++++++++++++------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js index 5eacba51c1..58c67bbca9 100644 --- a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js +++ b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js @@ -1,4 +1,4 @@ -const { test, expect } = require("@playwright/test"); +const { test, expect, chromium } = require("@playwright/test"); const { resolveTimeout, isOnionTarget } = require("./timeouts"); const { decodeDotenvQuotedValue, gotoOnion } = require("./personas"); @@ -7,7 +7,8 @@ const callParticipants = 6; const ocsHeaders = { "OCS-APIRequest": "true", Accept: "application/json" }; const joinCallPattern = /^(join call|start call|anruf beitreten|anruf starten)$/i; const leaveCallPattern = /^(leave call|anruf verlassen)$/i; -const displayNamePattern = /display name|anzeigename/i; +const guestNamePattern = /enter your name|display name|anzeigename/i; +const submitGuestNamePattern = /submit name and join/i; const turnQuotaReachedCode = 486; function trackPeerConnections() { @@ -36,7 +37,7 @@ function readCallStats(page) { } async function createPublicRoom(page, baseUrl) { - const response = await page.request.post(`${baseUrl}/ocs/v2.php/apps/spreed/api/v4/room`, { + const response = await page.request.post(new URL("ocs/v2.php/apps/spreed/api/v4/room", baseUrl).toString(), { headers: ocsHeaders, data: { roomType: 3, roomName: `Playwright call capacity ${Date.now()}` }, }); @@ -45,20 +46,31 @@ async function createPublicRoom(page, baseUrl) { } async function joinCallAsGuest(browser, roomUrl, name) { - const context = await browser.newContext({ ignoreHTTPSErrors: true, permissions: ["camera", "microphone"] }); + // Talk flags a HeadlessChrome user agent as unsupported, and that error toast covers the call button. + const userAgent = `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${browser.version()} Safari/537.36`; + const context = await browser.newContext({ ignoreHTTPSErrors: true, permissions: ["camera", "microphone"], userAgent }); await context.addInitScript(trackPeerConnections); const page = await context.newPage(); await gotoOnion(page, roomUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); const dialog = page.getByRole("dialog"); - await dialog.getByLabel(displayNamePattern).first().fill(name, { timeout: resolveTimeout(60_000) }); - const joinButton = dialog.getByRole("button", { name: joinCallPattern }).last(); - await expect(joinButton, `${name}: the join button stays disabled after the display name`).toBeEnabled({ + const submitName = dialog.getByRole("button", { name: submitGuestNamePattern }); + const dialogJoin = dialog.getByRole("button", { name: joinCallPattern }).last(); + const leaveButton = page.getByRole("button", { name: leaveCallPattern }).first(); + await dialog.getByRole("textbox", { name: guestNamePattern }).fill(name, { timeout: resolveTimeout(60_000) }); + await expect(submitName.or(dialogJoin).first(), `${name}: the name dialog offers neither submit nor join`).toBeVisible({ timeout: resolveTimeout(30_000), }); - await joinButton.click({ timeout: resolveTimeout(30_000) }); - await expect(page.getByRole("button", { name: leaveCallPattern }).first(), `${name} never entered the call`).toBeVisible({ - timeout: resolveTimeout(60_000), - }); + if (await submitName.isVisible()) { + await submitName.click({ timeout: resolveTimeout(30_000) }); + await page.getByRole("button", { name: joinCallPattern }).first().click({ timeout: resolveTimeout(60_000) }); + await expect(leaveButton.or(dialogJoin).first(), `${name}: neither the call nor its device check opened`).toBeVisible({ + timeout: resolveTimeout(60_000), + }); + } + if (await dialogJoin.isVisible()) { + await dialogJoin.click({ timeout: resolveTimeout(30_000) }); + } + await expect(leaveButton, `${name} never entered the call`).toBeVisible({ timeout: resolveTimeout(60_000) }); return { name, page, context }; } @@ -71,6 +83,9 @@ exports.register = function (shared) { const baseUrl = shared.env.nextcloudBaseUrl; const adminContext = await browser.newContext({ ignoreHTTPSErrors: true }); const adminPage = await adminContext.newPage(); + const mediaBrowser = await chromium.launch({ + args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream"], + }); const guests = []; let token = ""; @@ -79,7 +94,7 @@ exports.register = function (shared) { token = await createPublicRoom(adminPage, baseUrl); for (let index = 1; index <= callParticipants; index += 1) { - guests.push(await joinCallAsGuest(browser, `${baseUrl}/call/${token}`, `Playwright guest ${index}`)); + guests.push(await joinCallAsGuest(mediaBrowser, new URL(`call/${token}`, baseUrl).toString(), `Playwright guest ${index}`)); } for (const guest of guests) { @@ -95,12 +110,10 @@ exports.register = function (shared) { ).not.toContain(turnQuotaReachedCode); } } finally { - for (const guest of guests) { - await guest.context.close().catch(() => {}); - } + await mediaBrowser.close().catch(() => {}); if (token) { await adminPage.request - .delete(`${baseUrl}/ocs/v2.php/apps/spreed/api/v4/room/${token}`, { headers: ocsHeaders }) + .delete(new URL(`ocs/v2.php/apps/spreed/api/v4/room/${token}`, baseUrl).toString(), { headers: ocsHeaders }) .catch(() => {}); } await adminContext.close().catch(() => {}); From cac25a8b54496f819ccb05ab453e596c97bd2421 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:04:18 +0100 Subject: [PATCH 15/21] fix(web-svc-coturn): listen and relay only on the host's own public addresses With host networking and no --relay-ip, coturn put every non-loopback IPv4 of the host into its relay list, Docker bridge gateways included, and handed IPv6 and bridge clients relays on those addresses while advertising the public ip4, so their media went nowhere. It also listened on every bridge address. In compose mode with host networking, coturn now listens on networks.internet.ip4, 127.0.0.1 for the healthcheck and networks.internet.ip6 when set, and relays on ip4. It pins only when the host owns ip4, and owns ip6 too or leaves it unset; behind 1:1 NAT, without the ip binary or with a foreign ip6 it renders the previous command unchanged, because coturn exits when it cannot bind a listening address. A unit test renders the real template and vars for every cell. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-svc-coturn/README.md | 1 + roles/web-svc-coturn/templates/compose.yml.j2 | 8 +- roles/web-svc-coturn/vars/main.yml | 7 + .../python/roles/web-svc-coturn/__init__.py | 3 + .../web-svc-coturn/templates/__init__.py | 5 + .../templates/test_compose_addresses.py | 213 ++++++++++++++++++ 6 files changed, 236 insertions(+), 1 deletion(-) create mode 100644 tests/unit/python/roles/web-svc-coturn/__init__.py create mode 100644 tests/unit/python/roles/web-svc-coturn/templates/__init__.py create mode 100644 tests/unit/python/roles/web-svc-coturn/templates/test_compose_addresses.py diff --git a/roles/web-svc-coturn/README.md b/roles/web-svc-coturn/README.md index 73134bbb5d..e3d7852c03 100644 --- a/roles/web-svc-coturn/README.md +++ b/roles/web-svc-coturn/README.md @@ -78,6 +78,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - TURN and STUN support over TCP and UDP - Configurable relay port ranges for scaling - Configurable server-wide allocation quota (`services.coturn.total_quota`, default 2000); size it at about 2ยทNยฒ for every concurrent Nextcloud Talk call with N participants, as each participant opens N peer connections and requests one allocation per TURN transport +- Pinned addresses on host networking in compose mode when the host carries `networks.internet.ip4` on an interface and carries `networks.internet.ip6` too or leaves it unset: listens on `networks.internet.ip4`, `127.0.0.1` for the healthcheck and the set `networks.internet.ip6`, and places every relay on `networks.internet.ip4` instead of on the Docker bridge addresses of the host. Any other host, such as one behind 1:1 NAT, keeps listening and relaying on every local address - Integration into Infinito.Nexus inventory/variable system ## Quick Setup diff --git a/roles/web-svc-coturn/templates/compose.yml.j2 b/roles/web-svc-coturn/templates/compose.yml.j2 index 53a6e26cdf..ec0164ec1a 100644 --- a/roles/web-svc-coturn/templates/compose.yml.j2 +++ b/roles/web-svc-coturn/templates/compose.yml.j2 @@ -51,6 +51,12 @@ {% if networks.internet.ip6 | default('') %} --external-ip={{ networks.internet.ip6 }} {% endif %} + {% if COTURN_ADDRESSES_PINNED | bool %} + {% for listening_ip in COTURN_LISTENING_IPS %} + --listening-ip={{ listening_ip }} + {% endfor %} + --relay-ip={{ COTURN_RELAY_IP }} + {% endif %} --realm="${COTURN_REALM}" --fingerprint --total-quota={{ COTURN_TOTAL_QUOTA }} @@ -67,7 +73,7 @@ {% endif %} --cipher-list=DEFAULT healthcheck: - test: ["CMD", "sh", "-c", "command -v turnutils_stunclient >/dev/null && turnutils_stunclient -p {{ COTURN_STUN_TURN_PORT }} 127.0.0.1 || nc -z 127.0.0.1 {{ COTURN_STUN_TURN_PORT }}"] + test: ["CMD", "sh", "-c", "command -v turnutils_stunclient >/dev/null && turnutils_stunclient -p {{ COTURN_STUN_TURN_PORT }} {{ COTURN_LOOPBACK_IP }} || nc -z {{ COTURN_LOOPBACK_IP }} {{ COTURN_STUN_TURN_PORT }}"] interval: 2m timeout: 5s retries: 3 diff --git a/roles/web-svc-coturn/vars/main.yml b/roles/web-svc-coturn/vars/main.yml index a198b9a548..79b3e699a5 100644 --- a/roles/web-svc-coturn/vars/main.yml +++ b/roles/web-svc-coturn/vars/main.yml @@ -6,6 +6,13 @@ domain: "{{ lookup('domain',application_id) }}" COTURN_CONTAINER: "{{ entity_name }}" COTURN_REALM: "{{ domain }}" COTURN_NETWORK_MODE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.network_mode') }}" +COTURN_LOOPBACK_IP: "127.0.0.1" +COTURN_RELAY_IP: "{{ networks.internet.ip4 }}" +# nocheck: host-local-fact read only for host networking in compose mode, where the host rendering this file is the host coturn binds on; Ansible omits both keys on a host without the ip binary, which leaves coturn unpinned +COTURN_HOST_ADDRESSES: "{{ (ansible_facts['all_ipv4_addresses'] | default([])) + (ansible_facts['all_ipv6_addresses'] | default([])) }}" +COTURN_IP6_UNSET: "{{ networks.internet.ip6 in ['', defaults_networks.internet.ip6] }}" +COTURN_ADDRESSES_PINNED: "{{ COTURN_NETWORK_MODE == 'host' and DEPLOYMENT_MODE == 'compose' and COTURN_RELAY_IP in COTURN_HOST_ADDRESSES and (COTURN_IP6_UNSET or networks.internet.ip6 in COTURN_HOST_ADDRESSES) }}" +COTURN_LISTENING_IPS: "{{ [COTURN_RELAY_IP, COTURN_LOOPBACK_IP] + ([] if COTURN_IP6_UNSET else [networks.internet.ip6]) }}" COTURN_STUN_TURN_PORT: "{{ lookup('config', application_id, 'services.coturn.ports.public.stun_turn') }}" COTURN_STUN_TURN_PORT_TLS: "{{ lookup('config', application_id, 'services.coturn.ports.public.stun_turn_tls') }}" diff --git a/tests/unit/python/roles/web-svc-coturn/__init__.py b/tests/unit/python/roles/web-svc-coturn/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/web-svc-coturn/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-svc-coturn/templates/__init__.py b/tests/unit/python/roles/web-svc-coturn/templates/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/web-svc-coturn/templates/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-svc-coturn/templates/test_compose_addresses.py b/tests/unit/python/roles/web-svc-coturn/templates/test_compose_addresses.py new file mode 100644 index 0000000000..f576286b1a --- /dev/null +++ b/tests/unit/python/roles/web-svc-coturn/templates/test_compose_addresses.py @@ -0,0 +1,213 @@ +"""coturn pins its addresses only on host networking in compose mode, and only addresses the host owns. + +Pinned, coturn listens on ``networks.internet.ip4``, on loopback for the +healthcheck and on ``networks.internet.ip6``, and relays on +``networks.internet.ip4`` instead of on whichever Docker bridge address the +allocation happens to land on. coturn exits when it cannot bind a listening +address, and a pinned coturn stops answering on every address it was not +given. So the command is pinned only when the host carries ip4 and either +carries ip6 as written or ip6 is unset (empty or the ``defaults_networks`` +placeholder); any other host keeps the unpinned command the role rendered +before, instead of losing its IPv6 listener or failing to bind. + +The real ``vars/main.yml`` is resolved by Ansible's templar and the real +``compose.yml.j2`` is rendered with the role's lookups stubbed, so a broken +ownership check or a gate that leaks into bridge or swarm mode fails here. +""" + +from __future__ import annotations + +import re +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.plugins.filter.core import to_bool +from ansible.template import Templar +from jinja2 import DictLoader, Environment, StrictUndefined, select_autoescape + +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE, ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles/web-svc-coturn" +TEMPLATE = ROLE / ROLE_FILE_TEMPL_COMPOSE +VARS = ROLE / ROLE_FILE_VARS_MAIN +NETWORK_DEFAULTS = DataLoader().load_from_file( + str(PROJECT_ROOT / "group_vars/all/08_networks.yml") +)["defaults_networks"] +PLACEHOLDER_IP6 = NETWORK_DEFAULTS["internet"]["ip6"] + +IP4 = "198.51.100.7" +IP6 = "2001:db8:1::2" +FOREIGN_IP4 = "203.0.113.7" +FOREIGN_IP6 = "2001:db8:ffff::9" +LOOPBACK = "127.0.0.1" + +OWNED = { + "all_ipv4_addresses": [IP4, "172.17.0.1", "192.168.101.1"], + "all_ipv6_addresses": [IP6, "fe80::1"], +} + +RESOLVED = ( + "COTURN_LOOPBACK_IP", + "COTURN_RELAY_IP", + "COTURN_ADDRESSES_PINNED", + "COTURN_LISTENING_IPS", +) + +STUBBED = { + "application_id": "web-svc-coturn", + "entity_name": "coturn", + "COTURN_CONTAINER": "coturn", + "COTURN_USER_AUTH_ENABLED": False, + "COTURN_TOTAL_QUOTA": 2000, + "COTURN_STUN_TURN_PORT": 3481, + "COTURN_STUN_TURN_PORT_TLS": 5351, + "COTURN_RELAY_PORT_START": 20000, + "COTURN_RELAY_PORT_END": 39999, + "COTURN_TLS_ENABLED": True, + "COTURN_TLS_CERT_PATH": "/etc/coturn/cert.pem", + "COTURN_TLS_KEY_PATH": "/etc/coturn/key.pem", + "DOCKER_BIND_HOST": LOOPBACK, +} + +INCLUDES = { + "roles/sys-svc-compose/templates/base.yml.j2": "services:\n", + "roles/sys-svc-container/templates/base.yml.j2": "", +} + +_HEALTHCHECK = re.compile(r"turnutils_stunclient -p \d+ (\S+) \|\| nc -z (\S+) \d+") + + +def render( + *, + ip4: str = IP4, + ip6: str = IP6, + facts: dict | None = None, + mode: str = "compose", + network: str = "host", +) -> str: + """The coturn compose file for one deployment. + + Args: + ip4: ``networks.internet.ip4``. + ip6: ``networks.internet.ip6``. + facts: the host's ``ansible_facts``; ``None`` means a host owning ``OWNED``. + mode: ``DEPLOYMENT_MODE``. + network: ``services.coturn.network_mode``. + """ + inputs = { + "networks": {"internet": {"ip4": ip4, "ip6": ip6, "dns": ""}}, + "defaults_networks": NETWORK_DEFAULTS, + "ansible_facts": OWNED if facts is None else facts, + "DEPLOYMENT_MODE": mode, + "COTURN_NETWORK_MODE": network, + } + declared = DataLoader().load_from_file(str(VARS), trusted_as_template=True) + templar = Templar(loader=DataLoader(), variables={**declared, **inputs}) + values = {name: templar.template(declared[name]) for name in RESOLVED} + + env = Environment( + autoescape=select_autoescape(default_for_string=False), + undefined=StrictUndefined, + trim_blocks=True, + lstrip_blocks=True, + loader=DictLoader(INCLUDES), + ) + env.filters["bool"] = to_bool + env.globals["lookup"] = lambda *_args, **_kwargs: "" + return env.from_string(read_text(str(TEMPLATE))).render( + **STUBBED, **inputs, **values + ) + + +def listening(rendered: str) -> list[str]: + return re.findall(r"--listening-ip=(\S+)", rendered) + + +def relay(rendered: str) -> list[str]: + return re.findall(r"--relay-ip=(\S+)", rendered) + + +class TestOwnedAddressesArePinned(unittest.TestCase): + def test_listeners_cover_ip4_loopback_and_ip6(self) -> None: + self.assertEqual(listening(render()), [IP4, LOOPBACK, IP6]) + + def test_relays_stay_on_ip4(self) -> None: + self.assertEqual( + relay(render()), + [IP4], + "without the pin coturn may place a relay on a Docker bridge " + "address and still announce the external IP for it", + ) + + def test_the_healthcheck_probes_a_pinned_listener(self) -> None: + rendered = render() + probed = _HEALTHCHECK.search(rendered) + self.assertIsNotNone(probed, "the healthcheck command changed shape") + for address in probed.groups(): + self.assertIn( + address, + listening(rendered), + "a pinned coturn answers only on its listening addresses, so a " + "probe aimed elsewhere marks a healthy server unhealthy", + ) + + +class TestAnUnsetIpv6IsLeftOut(unittest.TestCase): + def test_the_placeholder_is_left_out(self) -> None: + rendered = render(ip6=PLACEHOLDER_IP6) + self.assertEqual( + (listening(rendered), relay(rendered)), ([IP4, LOOPBACK], [IP4]) + ) + + def test_an_empty_ipv6_is_left_out(self) -> None: + rendered = render(ip6="") + self.assertEqual( + (listening(rendered), relay(rendered)), ([IP4, LOOPBACK], [IP4]) + ) + + +class TestAddressesTheHostLacksKeepTheUnpinnedCommand(unittest.TestCase): + def test_a_foreign_ipv6(self) -> None: + rendered = render(ip6=FOREIGN_IP6) + self.assertEqual( + (listening(rendered), relay(rendered)), + ([], []), + "pinning ip4 alone would drop the IPv6 listener the unpinned " + "command still had", + ) + + def test_an_ipv6_written_unlike_the_interface_lists_it(self) -> None: + rendered = render(ip6=IP6.upper()) + self.assertEqual((listening(rendered), relay(rendered)), ([], [])) + + def test_a_foreign_ipv4_keeps_the_unpinned_command(self) -> None: + rendered = render(ip4=FOREIGN_IP4) + self.assertEqual( + (listening(rendered), relay(rendered)), + ([], []), + "a 1:1-NAT host carries its public IPv4 nowhere, so pinning it " + "stops coturn from binding at all", + ) + + def test_a_host_without_address_facts_keeps_the_unpinned_command(self) -> None: + rendered = render(facts={}) + self.assertEqual((listening(rendered), relay(rendered)), ([], [])) + + +class TestOtherModesAreUnchanged(unittest.TestCase): + def test_bridge_and_swarm_never_pin(self) -> None: + for mode, network in ( + ("compose", "bridge"), + ("swarm", "host"), + ("swarm", "bridge"), + ): + with self.subTest(mode=mode, network=network): + rendered = render(mode=mode, network=network) + self.assertEqual((listening(rendered), relay(rendered)), ([], [])) + + +if __name__ == "__main__": + unittest.main() From 1352de5422fe056f9cd5e444dc039905cae4a982 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:08:06 +0100 Subject: [PATCH 16/21] feat(web-app-nextcloud): let Talk media reach Janus directly instead of only through TURN The aio-talk image runs Janus with its stock janus.jcfg: no rtp_port_range and no nat_1_1_mapping, so Janus offered only its bridge address and every stream of a call went through coturn as relay. Calls above about six participants stuttered and failed. When talk runs bridged next to standalone coturn in compose mode on a host that owns networks.internet.ip4, a rendered janus.jcfg is mounted over the stock one with rtp_port_range 61000-61999, nat_1_1_mapping = ip4 and keep_private_host, and that UDP range is published on ip4. TURN stays the fallback. Before rendering, the deploy reads the image's launcher and stock janus.jcfg and stops when Janus no longer reads the mounted path or the stock settings drifted from the template. Variant 0 publishes 64 ports so dev and CI exercise the path; the call capacity spec asserts a non-relay selected pair on ip4 in that range. With the flag off every rendered file is byte-identical to before. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../web-app-nextcloud/docs/Administration.md | 8 + .../playwright/test-talk-call-capacity.js | 59 ++++ .../filter_plugins/nextcloud_janus.py | 121 ++++++++ roles/web-app-nextcloud/meta/services.yml | 10 + roles/web-app-nextcloud/meta/variants.yml | 5 + roles/web-app-nextcloud/meta/volumes.yml | 9 + .../web-app-nextcloud/tasks/01_fullstack.yml | 55 ++++ .../templates/compose.yml.j2 | 26 +- .../web-app-nextcloud/templates/janus.jcfg.j2 | 57 ++++ .../templates/playwright.env.j2 | 8 + roles/web-app-nextcloud/vars/main.yml | 13 + .../filter_plugins/test_nextcloud_janus.py | 138 +++++++++ .../test_talk_direct_media.py | 284 ++++++++++++++++++ 13 files changed, 786 insertions(+), 7 deletions(-) create mode 100644 roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py create mode 100644 roles/web-app-nextcloud/templates/janus.jcfg.j2 create mode 100644 tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index 458df37ded..61e65dd23e 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -31,3 +31,11 @@ Check these admin URLs after deployment: - `/settings/admin/talk#signaling_server` - `/settings/admin/talk#stun_server` - `/settings/admin/talk#turn_server` + +## Talk media + +With `services.talk.direct_media` true, the Janus media server inside the `talk` container announces `networks.internet.ip4` and publishes `services.talk.ports.public.relay` (UDP, default 61000-61999) on that address, so clients send their media to Janus directly and only fall back to `web-svc-coturn` when UDP to that range is blocked. The flag is on in compose mode with a bridged `talk` service that uses `web-svc-coturn` for TURN, and only while `networks.internet.ip4` is an address of the host itself. Set it to `false` in the inventory to send every stream through TURN again. + +Open the range for UDP in any firewall in front of the host. Each participant of a call holds one peer connection per participant, so all calls together get at most as many peer connections as the range has ports, and a call of N participants needs Nยฒ of them. Janus refuses a new peer connection once the range is used up. Docker starts one `docker-proxy` process per published port. + +`templates/janus.jcfg.j2` replaces the `janus.jcfg` of the `nextcloud/aio-talk` image. Before every deploy the role reads `/supervisord.conf` and that file from the image and stops unless Janus is started with that file and its settings equal the template without `rtp_port_range`, `nat_1_1_mapping` and `keep_private_host`. Re-derive the template from the new image when that happens. diff --git a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js index 58c67bbca9..e1d3a7eb73 100644 --- a/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js +++ b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js @@ -3,6 +3,10 @@ const { resolveTimeout, isOnionTarget } = require("./timeouts"); const { decodeDotenvQuotedValue, gotoOnion } = require("./personas"); const talkEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED) === "true"; +const directMediaEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_DIRECT_MEDIA_ENABLED) === "true"; +const directMediaAddress = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_DIRECT_MEDIA_ADDRESS); +const directMediaPortStart = Number(decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_DIRECT_MEDIA_PORT_START)); +const directMediaPortEnd = Number(decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_DIRECT_MEDIA_PORT_END)); const callParticipants = 6; const ocsHeaders = { "OCS-APIRequest": "true", Accept: "application/json" }; const joinCallPattern = /^(join call|start call|anruf beitreten|anruf starten)$/i; @@ -14,6 +18,33 @@ const turnQuotaReachedCode = 486; function trackPeerConnections() { const Original = window.RTCPeerConnection; const stats = { connections: [], iceErrorCodes: [] }; + stats.selectedPairs = async () => { + const pairs = []; + for (const connection of stats.connections) { + if (connection.connectionState !== "connected") { + continue; + } + const entries = new Map(); + (await connection.getStats()).forEach((entry) => entries.set(entry.id, entry)); + const selectedIds = [...entries.values()] + .filter((entry) => entry.type === "transport" && entry.selectedCandidatePairId) + .map((entry) => entry.selectedCandidatePairId); + for (const id of selectedIds) { + const pair = entries.get(id); + const local = pair && entries.get(pair.localCandidateId); + const remote = pair && entries.get(pair.remoteCandidateId); + if (local && remote) { + pairs.push({ + localType: local.candidateType, + remoteType: remote.candidateType, + remoteAddress: remote.address || remote.ip, + remotePort: remote.port, + }); + } + } + } + return pairs; + }; window.__talkCallStats = stats; function Tracked(...args) { const connection = new Original(...args); @@ -36,6 +67,20 @@ function readCallStats(page) { }); } +function isDirectPair(pair) { + return ( + pair.localType !== "relay" && + pair.remoteType !== "relay" && + pair.remoteAddress === directMediaAddress && + pair.remotePort >= directMediaPortStart && + pair.remotePort <= directMediaPortEnd + ); +} + +function readSelectedPairs(page) { + return page.evaluate(() => window.__talkCallStats.selectedPairs()); +} + async function createPublicRoom(page, baseUrl) { const response = await page.request.post(new URL("ocs/v2.php/apps/spreed/api/v4/room", baseUrl).toString(), { headers: ocsHeaders, @@ -108,6 +153,20 @@ exports.register = function (shared) { (await readCallStats(guest.page)).iceErrorCodes, `${guest.name}: TURN answered ${turnQuotaReachedCode} Allocation Quota Reached`, ).not.toContain(turnQuotaReachedCode); + if (directMediaEnabled) { + await expect + .poll( + async () => { + const pairs = await readSelectedPairs(guest.page); + return pairs.some(isDirectPair) ? "direct" : JSON.stringify(pairs); + }, + { + timeout: resolveTimeout(60_000), + message: `${guest.name} must carry media to Janus on ${directMediaAddress}:${directMediaPortStart}-${directMediaPortEnd} without a TURN relay`, + }, + ) + .toBe("direct"); + } } } finally { await mediaBrowser.close().catch(() => {}); diff --git a/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py b/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py new file mode 100644 index 0000000000..ea7398fa7b --- /dev/null +++ b/roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import re + + +def _strip_comments(content): + out = [] + in_string = in_block = False + index = 0 + while index < len(content): + char = content[index] + if in_block: + if content.startswith("*/", index): + in_block = False + index += 1 + elif char == "\n": + out.append(char) + elif in_string: + out.append(char) + if char == "\\" and index + 1 < len(content): + out.append(content[index + 1]) + index += 1 + elif char == '"': + in_string = False + elif char == '"': + in_string = True + out.append(char) + elif content.startswith("/*", index): + in_block = True + index += 1 + elif char == "#" or content.startswith("//", index): + while index + 1 < len(content) and content[index + 1] != "\n": + index += 1 + else: + out.append(char) + index += 1 + return "".join(out) + + +def _without_blanks(line): + out = [] + in_string = False + for index, char in enumerate(line): + if char == '"' and (index == 0 or line[index - 1] != "\\"): + in_string = not in_string + if in_string or not char.isspace(): + out.append(char) + return "".join(out).rstrip(";") + + +def _key(setting): + for index, char in enumerate(setting): + if char in "=:": + return setting[:index] + if char == '"': + return "" + return "" + + +def janus_settings(content, overrides): + """Return the settings a Janus ``.jcfg`` file declares, one per line. + + Args: + content: text of a Janus libconfig file. + overrides: setting names to leave out, the ones a deployment sets on + top of the stock file; empty to keep every setting. + + Returns: + Every line that holds more than comments and blanks, with the comments, + a trailing ``;`` and the whitespace outside quoted strings removed, in + file order. + """ + dropped = {str(name) for name in overrides} + settings = [] + for raw in _strip_comments(str(content)).splitlines(): + setting = _without_blanks(raw) + if setting and _key(setting) not in dropped: + settings.append(setting) + return settings + + +def janus_config_drift(template, stock, overrides, launcher, target): + """Return why a rendered Janus config may not replace an image's own. + + Args: + template: the rendered config that is mounted over ``target``. + stock: the image's own file at ``target``. + overrides: setting names the template adds to the stock settings. + launcher: the image's process manager config that starts Janus. + target: the path the template is mounted at. + + Returns: + One message per problem; empty when Janus reads ``target`` and the + template without ``overrides`` declares exactly the stock settings. + """ + problems = [] + started_with = re.compile(rf"--config={re.escape(str(target))}( |$)", re.MULTILINE) + if not started_with.search(str(launcher)): + problems.append(f"Janus is not started with --config={target}") + expected = janus_settings(stock, []) + rendered = janus_settings(template, overrides) + if expected != rendered: + first = next( + ( + f"{index}: image {theirs!r}, template {ours!r}" + for index, (theirs, ours) in enumerate( + zip(expected, rendered, strict=False) + ) + if theirs != ours + ), + f"{len(expected)} settings in the image, {len(rendered)} in the template", + ) + problems.append(f"the stock settings differ at setting {first}") + return problems + + +class FilterModule: + def filters(self): + return { + "janus_config_drift": janus_config_drift, + } diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index eabc21d99a..bab4709cd9 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -204,6 +204,12 @@ talk: onboard_enabled: "{{ not ( 'web-svc-coturn' in group_names ) }}" standalone_enabled: "{{ 'web-svc-coturn' in group_names }}" network_mode: bridge + direct_media: >- + {{ (lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool) + and (lookup('config', 'web-app-nextcloud', 'services.talk.turn_server.standalone_enabled') | bool) + and (lookup('config', 'web-app-nextcloud', 'services.talk.network_mode') == 'bridge') + and (DEPLOYMENT_MODE == 'compose') + and (networks.internet.ip4 in ansible_facts['all_ipv4_addresses']) }} cpus: "2.0" mem_reservation: 1g mem_limit: 2g @@ -212,6 +218,10 @@ talk: ports: internal: signaling: 8081 + public: + relay: + start: 61000 + end: 61999 healthcheck: flavor: tcp port_key: signaling diff --git a/roles/web-app-nextcloud/meta/variants.yml b/roles/web-app-nextcloud/meta/variants.yml index 60a096f8d3..3efda1b2f3 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -52,6 +52,11 @@ talk: enabled: true shared: true + ports: + public: + relay: + start: 61000 + end: 61063 onlyoffice: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true diff --git a/roles/web-app-nextcloud/meta/volumes.yml b/roles/web-app-nextcloud/meta/volumes.yml index 364cc4d6b0..e9b28b9af2 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -61,6 +61,15 @@ infinito_conf: - service: cron target: *var_www_infinito_target +janus_conf: + type: config + source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'janus.jcfg' ] | path_join }}" + mode: "0444" + mounts: + - service: talk + target: /usr/local/etc/janus/janus.jcfg + when: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.direct_media') | bool }}" + php_hardening: type: config source: "{{ FILE_PHP_HARDENING_INI }}" diff --git a/roles/web-app-nextcloud/tasks/01_fullstack.yml b/roles/web-app-nextcloud/tasks/01_fullstack.yml index 24628d99b0..26fba72a2d 100644 --- a/roles/web-app-nextcloud/tasks/01_fullstack.yml +++ b/roles/web-app-nextcloud/tasks/01_fullstack.yml @@ -7,6 +7,51 @@ application_id: web-app-nextcloud webserver_client_max_body_size: 10G +- name: "๐Ÿ” Read the Janus launcher and config from {{ NEXTCLOUD_HPB_IMAGE }}" + ansible.builtin.command: + argv: + - container + - run + - --rm + - --pull + - always + - --entrypoint + - cat + - "{{ NEXTCLOUD_HPB_IMAGE }}" + - "{{ item }}" + environment: + CA_CONTAINER_ENABLED: "0" + loop: + - "{{ NEXTCLOUD_HPB_JANUS_LAUNCHER }}" + - "{{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }}" + register: nextcloud_janus_image_files + changed_when: false + retries: 3 + delay: 30 + until: nextcloud_janus_image_files is succeeded + when: + - NEXTCLOUD_HPB_MEDIA_DIRECT | bool + - IS_STACK_HOST | bool + +- name: "๐Ÿ›‘ Assert Janus reads the mounted config and the image's copy still matches" + ansible.builtin.assert: + that: nextcloud_janus_drift | length == 0 + fail_msg: >- + templates/janus.jcfg.j2 cannot replace {{ NEXTCLOUD_HPB_JANUS_CONFIG_TARGET }} + of {{ NEXTCLOUD_HPB_IMAGE }}: {{ nextcloud_janus_drift | join('; ') }}. + Re-derive the template from the new image before deploying. + quiet: true + vars: + nextcloud_janus_drift: >- + {{ lookup('template', 'janus.jcfg.j2') + | janus_config_drift(nextcloud_janus_image_files.results[1].stdout, + NEXTCLOUD_HPB_JANUS_OVERRIDES, + nextcloud_janus_image_files.results[0].stdout, + NEXTCLOUD_HPB_JANUS_CONFIG_TARGET) }} + when: + - NEXTCLOUD_HPB_MEDIA_DIRECT | bool + - IS_STACK_HOST | bool + - name: "๐Ÿ“„ Deploy '{{ NEXTCLOUD_INIT_GATE_HOST }}'" copy: src: "{{ NEXTCLOUD_INIT_GATE_SRC }}" @@ -78,3 +123,13 @@ role_templates: - src: "fpm-pool.conf.j2" dest: "{{ NEXTCLOUD_HOST_FPM_POOL_PATH }}" + +- name: "๐Ÿ“„ Render the Janus config that publishes Talk media directly" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "janus.jcfg.j2" + dest: "{{ NEXTCLOUD_HPB_JANUS_CONFIG_HOST }}" + mode: "0644" + when: NEXTCLOUD_HPB_MEDIA_DIRECT | bool diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index c4a1edb7ee..3d17c31bd4 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -74,14 +74,26 @@ {{ lookup('compose_only', 'container_name', NEXTCLOUD_HPB_CONTAINER) }} init: true {% if NEXTCLOUD_HPB_NETWORK_MODE == 'bridge' %} + {% set _talk_ports = [] %} {% if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool and NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS | bool %} - {{ lookup('container_ports', - {'service': 'nextcloud', 'protocol': 'stun_turn', - 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, - 'transport': ['tcp', 'udp'], 'container': 'same'}, - {'service': 'nextcloud', 'protocol': 'relay', - 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, - 'transport': ['udp', 'tcp'], 'container': 'same'}) | indent(4) }} + {% set _ = _talk_ports.extend([ + {'service': 'nextcloud', 'protocol': 'stun_turn', + 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, + 'transport': ['tcp', 'udp'], 'container': 'same'}, + {'service': 'nextcloud', 'protocol': 'relay', + 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, + 'transport': ['udp', 'tcp'], 'container': 'same'}, + ]) %} + {% endif %} + {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %} + {{ lookup('container_volumes', service_name) | indent(4) }} + {% set _ = _talk_ports.append( + {'service': 'talk', 'protocol': 'relay', + 'ip': NEXTCLOUD_HPB_MEDIA_PUBLIC_IP, + 'transport': 'udp', 'container': 'same'}) %} + {% endif %} + {% if _talk_ports %} + {{ lookup('container_ports', *_talk_ports) | indent(4) }} {% endif %} expose: - "{{ container_port }}" diff --git a/roles/web-app-nextcloud/templates/janus.jcfg.j2 b/roles/web-app-nextcloud/templates/janus.jcfg.j2 new file mode 100644 index 0000000000..983506ab06 --- /dev/null +++ b/roles/web-app-nextcloud/templates/janus.jcfg.j2 @@ -0,0 +1,57 @@ +general: { + configs_folder = "/usr/local/etc/janus" + plugins_folder = "/usr/local/lib/janus/plugins" + transports_folder = "/usr/local/lib/janus/transports" + events_folder = "/usr/local/lib/janus/events" + loggers_folder = "/usr/local/lib/janus/loggers" + debug_level = 4 + admin_secret = "janusoverlord" + protected_folders = [ + "/bin", + "/boot", + "/dev", + "/etc", + "/initrd", + "/lib", + "/lib32", + "/lib64", + "/proc", + "/sbin", + "/sys", + "/usr", + "/var", + "/opt/janus/bin", + "/opt/janus/etc", + "/opt/janus/include", + "/opt/janus/lib", + "/opt/janus/lib32", + "/opt/janus/lib64", + "/opt/janus/sbin" + ] +} + +certificates: { +} + +media: { + rtp_port_range = "{{ NEXTCLOUD_HPB_MEDIA_PORT_START }}-{{ NEXTCLOUD_HPB_MEDIA_PORT_END }}" +} + +nat: { + nice_debug = false + nat_1_1_mapping = "{{ NEXTCLOUD_HPB_MEDIA_PUBLIC_IP }}" + keep_private_host = true + ice_ignore_list = "vmnet" +} + +plugins: { +} + +transports: { +} + +loggers: { +} + +events: { +} diff --git a/roles/web-app-nextcloud/templates/playwright.env.j2 b/roles/web-app-nextcloud/templates/playwright.env.j2 index 8a51fc152f..9d2fd9cd50 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -41,6 +41,14 @@ NEXTCLOUD_MCP_UPSTREAM_PATH={{ lookup('config', application_id, 'mcp.adapter.ups NEXTCLOUD_ONLYOFFICE_EXPECTED_DOCUMENT_SERVER_URL={{ NEXTCLOUD_ONLYOFFICE_URL | dotenv_quote }} +NEXTCLOUD_TALK_DIRECT_MEDIA_ADDRESS={{ NEXTCLOUD_HPB_MEDIA_PUBLIC_IP | dotenv_quote }} + +NEXTCLOUD_TALK_DIRECT_MEDIA_ENABLED={{ NEXTCLOUD_HPB_MEDIA_DIRECT | string | lower }} + +NEXTCLOUD_TALK_DIRECT_MEDIA_PORT_END={{ NEXTCLOUD_HPB_MEDIA_PORT_END }} + +NEXTCLOUD_TALK_DIRECT_MEDIA_PORT_START={{ NEXTCLOUD_HPB_MEDIA_PORT_START }} + NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL={{ NEXTCLOUD_HPB_SIGNALING_URL | dotenv_quote }} NEXTCLOUD_TALK_EXPECTED_STUN_SERVER={{ NEXTCLOUD_HPB_STUN_ACTIVE_CONFIG | dotenv_quote }} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index 75cc1812aa..5e08d0ed93 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -154,6 +154,19 @@ NEXTCLOUD_HPB_PLUGIN_ENABLED: "{{ lookup('config', application_id, 'addons.spree NEXTCLOUD_HPB_INTERNAL_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_internal_secret') }}" NEXTCLOUD_HPB_DOMAIN: "{{ NEXTCLOUD_DOMAIN }}" +NEXTCLOUD_HPB_MEDIA_DIRECT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.direct_media') | bool }}" +NEXTCLOUD_HPB_MEDIA_PUBLIC_IP: "{{ networks.internet.ip4 }}" +NEXTCLOUD_HPB_MEDIA_PORT_START: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.start') }}" +NEXTCLOUD_HPB_MEDIA_PORT_END: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_HPB_SERVICE ~ '.ports.public.relay.end') }}" +NEXTCLOUD_HPB_JANUS_CONFIG_HOST: "{{ [ lookup('container', application_id, 'directories.volumes'), 'janus.jcfg' ] | path_join }}" +NEXTCLOUD_HPB_JANUS_CONFIG_TARGET: "{{ lookup('volume', application_id, 'janus_conf').target }}" +NEXTCLOUD_HPB_JANUS_LAUNCHER: "/supervisord.conf" +NEXTCLOUD_HPB_JANUS_OVERRIDES: + - rtp_port_range + - nat_1_1_mapping + - keep_private_host +NEXTCLOUD_HPB_IMAGE: "{{ lookup('image', application_id, NEXTCLOUD_HPB_SERVICE) }}" + NEXTCLOUD_HPB_SIGNALING_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.talk_signaling_secret') }}" NEXTCLOUD_HPB_SIGNALING_LOCATION: "/standalone-signaling/" NEXTCLOUD_HPB_SIGNALING_PORT: "{{ lookup('config', application_id, 'services.talk.ports.internal.signaling') }}" diff --git a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py new file mode 100644 index 0000000000..1b0d72af21 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_janus.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import importlib.util +import sys +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from . import PROJECT_ROOT + +OVERRIDES = ("rtp_port_range", "nat_1_1_mapping", "keep_private_host") +TARGET = "/usr/local/etc/janus/janus.jcfg" +LAUNCHER = ( + "[program:janus]\n" + "command=janus --config=/usr/local/etc/janus/janus.jcfg --disable-colors" + " --log-stdout --full-trickle --debug-level 3\n" +) + + +def _load_module(rel_path: str, name: str): + path = PROJECT_ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +MODULE = _load_module( + "roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py", "nextcloud_janus" +) + + +def _rendered_template() -> str: + env = Environment( + loader=FileSystemLoader( + str(PROJECT_ROOT / "roles/web-app-nextcloud/templates") + ), + undefined=StrictUndefined, + keep_trailing_newline=True, + autoescape=select_autoescape(default_for_string=False), + ) + return env.get_template("janus.jcfg.j2").render( + NEXTCLOUD_HPB_MEDIA_PORT_START=61000, + NEXTCLOUD_HPB_MEDIA_PORT_END=61999, + NEXTCLOUD_HPB_MEDIA_PUBLIC_IP="203.0.113.7", + ) + + +def _stock_like() -> str: + lines = ["/* a block comment the image ships", " over two lines */"] + for line in _rendered_template().splitlines(): + if line.strip().split(" ", 1)[0] in OVERRIDES: + lines.append("\t#" + line.strip() + "\t\t# commented out upstream") + continue + lines.append("\t\t# a comment line the image ships") + lines.append(line.replace(" = ", " = ") + "\t// trailing remark") + return "\n".join(lines) + "\n" + + +def _drift(stock: str, launcher: str = LAUNCHER) -> list[str]: + return MODULE.janus_config_drift( + _rendered_template(), stock, OVERRIDES, launcher, TARGET + ) + + +class TestJanusSettings(unittest.TestCase): + def test_comments_and_blank_lines_are_dropped(self): + content = "# head\n\ngeneral: {\n\tdebug_level = 4\t\t# level\n}\n" + self.assertEqual( + MODULE.janus_settings(content, []), ["general:{", "debug_level=4", "}"] + ) + + def test_block_comments_and_a_trailing_semicolon_are_dropped(self): + content = "/* head\n tail */\ndebug_level = 4; /* level */\n" + self.assertEqual(MODULE.janus_settings(content, []), ["debug_level=4"]) + + def test_a_hash_inside_a_quoted_value_is_kept(self): + content = 'log_prefix = "[janus] #1" # prefix\n' + self.assertEqual( + MODULE.janus_settings(content, []), ['log_prefix="[janus] #1"'] + ) + + def test_named_overrides_are_left_out(self): + content = 'nat: {\n\tnat_1_1_mapping = "1.2.3.4"\n\tnice_debug = false\n}\n' + self.assertEqual( + MODULE.janus_settings(content, ["nat_1_1_mapping"]), + ["nat:{", "nice_debug=false", "}"], + ) + + def test_the_template_sets_every_override_once(self): + keys = [ + setting.split("=", 1)[0] + for setting in MODULE.janus_settings(_rendered_template(), []) + ] + for override in OVERRIDES: + self.assertEqual(keys.count(override), 1, override) + + +class TestJanusConfigDrift(unittest.TestCase): + def test_a_stock_file_that_differs_only_in_comments_and_layout_passes(self): + self.assertEqual(_drift(_stock_like()), []) + + def test_a_moved_plugin_folder_stops_the_deploy(self): + stock = _stock_like().replace( + '"/usr/local/lib/janus/plugins"', '"/usr/lib/janus/plugins"' + ) + self.assertEqual(len(_drift(stock)), 1) + + def test_an_upstream_value_for_a_masked_key_stops_the_deploy(self): + stock = _stock_like().replace("\t#rtp_port_range", "\trtp_port_range", 1) + self.assertEqual(len(_drift(stock)), 1) + + def test_a_setting_upstream_added_stops_the_deploy(self): + stock = _stock_like().replace("nat: {", "nat: {\n\tice_tcp = true", 1) + self.assertEqual(len(_drift(stock)), 1) + + def test_an_empty_read_stops_the_deploy(self): + self.assertEqual(len(_drift("")), 1) + + def test_janus_reading_a_generated_config_stops_the_deploy(self): + launcher = LAUNCHER.replace(TARGET, "/conf/janus.jcfg") + self.assertEqual( + _drift(_stock_like(), launcher), + [f"Janus is not started with --config={TARGET}"], + ) + + def test_a_config_path_that_only_shares_the_prefix_stops_the_deploy(self): + launcher = LAUNCHER.replace(f"{TARGET} ", f"{TARGET}.generated ") + self.assertEqual(len(_drift(_stock_like(), launcher)), 1) + + def test_a_launcher_without_janus_stops_the_deploy(self): + self.assertEqual(len(_drift(_stock_like(), "")), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py new file mode 100644 index 0000000000..05f0349f3d --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -0,0 +1,284 @@ +from __future__ import annotations + +import itertools +import unittest +from unittest import mock + +from jinja2 import ( + ChainableUndefined, + ChoiceLoader, + DictLoader, + Environment, + FileSystemLoader, + select_autoescape, +) + +import plugins.lookup.container_ports as container_ports_lookup +from plugins.lookup.container_volumes import container_volumes +from utils.cache import _reset_cache_for_tests +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TEMPL_COMPOSE + +ROLE = "roles/web-app-nextcloud" +TEMPLATE = f"{ROLE}/{ROLE_FILE_TEMPL_COMPOSE}" +PUBLIC_IP = "203.0.113.7" +SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES)) + +LEGACY_BRIDGE_ONBOARD = """ talk: + + + + )> + init: true + ports: + - "203.0.113.7:3480:3480/tcp" + - "203.0.113.7:3480:3480/udp" + - "203.0.113.7:50000-59999:50000-59999/udp" + - "203.0.113.7:50000-59999:50000-59999/tcp" + expose: + - "8081" + """ + +LEGACY_BRIDGE = """ talk: + + + + )> + init: true + expose: + - "8081" + """ + +LEGACY_HOST = """ talk: + + + + )> + init: true + network_mode: host""" + +DIRECT_MOUNT = ( + " \n" + " configs:\n" + " - source: janus_conf\n" + " target: /usr/local/etc/janus/janus.jcfg\n" + " mode: 292" +) + +DIRECT_PORT = ' - "203.0.113.7:61000-61999:61000-61999/udp"' + + +class _Marker(ChainableUndefined): + def __str__(self): + return f"<{self._undefined_name}>" + + __repr__ = __str__ + + +def _bool(value): + if isinstance(value, bool): + return value + if value is None or isinstance(value, ChainableUndefined): + return False + return str(value).strip().lower() in {"y", "yes", "true", "on", "1"} + + +def _render( + template_text: str, *, onboard: bool, direct: bool, mode: str, network: str +) -> str: + applications = {"web-app-nextcloud": {"services": SERVICES}} + env = Environment( + loader=ChoiceLoader( + [ + DictLoader( + { + "roles/sys-svc-compose/templates/base.yml.j2": "services:\n", + "roles/sys-svc-container/templates/base.yml.j2": " \n", + "roles/sys-svc-container/templates/deploy.yml.j2": " \n", + "compose.yml.j2": template_text, + } + ), + FileSystemLoader(str(PROJECT_ROOT)), + ] + ), + trim_blocks=True, + lstrip_blocks=True, + keep_trailing_newline=True, + undefined=_Marker, + autoescape=select_autoescape(default_for_string=False), + ) + env.filters["bool"] = _bool + env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts) + variables = { + "application_id": "web-app-nextcloud", + "NEXTCLOUD_PROXY_SERVICE": "proxy", + "NEXTCLOUD_SERVICE": "nextcloud", + "NEXTCLOUD_CRON_SERVICE": "cron", + "DEPLOYMENT_MODE": mode, + "NEXTCLOUD_HPB_SIGNALING_ENABLED": True, + "NEXTCLOUD_HPB_SERVICE": "talk", + "NEXTCLOUD_HPB_SIGNALING_PORT": 8081, + "NEXTCLOUD_HPB_NETWORK_MODE": network, + "NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED": onboard, + "NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS": True, + "NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST": PUBLIC_IP, + "NEXTCLOUD_HPB_MEDIA_DIRECT": direct, + "NEXTCLOUD_HPB_MEDIA_PUBLIC_IP": PUBLIC_IP, + } + + def render_jinja(expression): + return env.from_string(expression).render(variables) + + class _Applications: + def run(self, terms, variables=None): + return [applications] + + class _Loader: + def get(self, name, **kwargs): + return _Applications() + + def lookup(name, *args, **kwargs): + if name == "config": + return {"services.talk.direct_media": direct}[args[1]] + if name == "container_ports": + with mock.patch.object(container_ports_lookup, "lookup_loader", _Loader()): + return container_ports_lookup.LookupModule().run( + list(args), variables=variables + )[0] + if name == "container_volumes": + block = container_volumes( + applications, "web-app-nextcloud", args[0], render_jinja=render_jinja + ) + return "\n" + block if block else block + return f"" + + env.globals["lookup"] = lookup + return env.get_template("compose.yml.j2").render(variables) + + +def _talk_block(rendered: str) -> str: + lines = rendered.splitlines() + start = lines.index(" talk:") + end = next( + index + for index in range(start + 1, len(lines)) + if lines[index].strip() and not lines[index].startswith(" ") + ) + return "\n".join(lines[start:end]).rstrip() + + +def _cells(direct: bool): + for onboard, mode, network in itertools.product( + (True, False), ("compose", "swarm"), ("bridge", "host") + ): + yield {"onboard": onboard, "direct": direct, "mode": mode, "network": network} + + +def _legacy(cell) -> str: + if cell["network"] == "host": + return LEGACY_HOST + return LEGACY_BRIDGE_ONBOARD if cell["onboard"] else LEGACY_BRIDGE + + +class TestTalkComposeBlock(unittest.TestCase): + def test_every_cell_without_direct_media_renders_the_legacy_block(self): + template = read_text(str(PROJECT_ROOT / TEMPLATE)) + for cell in _cells(direct=False): + with self.subTest(**cell): + self.assertEqual(_talk_block(_render(template, **cell)), _legacy(cell)) + + def test_host_networking_ignores_direct_media(self): + template = read_text(str(PROJECT_ROOT / TEMPLATE)) + for cell in _cells(direct=True): + if cell["network"] == "host": + with self.subTest(**cell): + self.assertEqual( + _talk_block(_render(template, **cell)), LEGACY_HOST + ) + + def test_direct_media_adds_only_the_janus_mount_and_the_udp_range(self): + template = read_text(str(PROJECT_ROOT / TEMPLATE)) + for cell in _cells(direct=True): + if cell["network"] != "bridge": + continue + with self.subTest(**cell): + block = _talk_block(_render(template, **cell)) + legacy = _legacy(cell) + expected = legacy.replace( + " init: true", " init: true\n" + DIRECT_MOUNT + ) + if cell["onboard"]: + expected = expected.replace( + " expose:", DIRECT_PORT + "\n expose:" + ) + else: + expected = expected.replace( + " expose:", " ports:\n" + DIRECT_PORT + "\n expose:" + ) + self.assertEqual(block, expected) + + def test_negative_control_an_unguarded_mount_breaks_the_legacy_block(self): + template = read_text(str(PROJECT_ROOT / TEMPLATE)).replace( + " {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n" + " {{ lookup('container_volumes', service_name) | indent(4) }}\n", + " {{ lookup('container_volumes', service_name) | indent(4) }}\n" + " {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n", + ) + cell = { + "onboard": False, + "direct": False, + "mode": "compose", + "network": "bridge", + } + rendered = _render(template, **cell) + self.assertNotIn("janus_conf", rendered) + self.assertNotEqual(_talk_block(rendered), _legacy(cell)) + + +def _direct_media(group_names, *, mode="compose", ip4=PUBLIC_IP, applications=None): + from ansible.parsing.dataloader import DataLoader + from ansible.template import Templar + + from utils.cache.applications import get_merged_applications + + variables = { + "group_names": group_names, + "applications": applications or {}, + "DEPLOYMENT_MODE": mode, + "networks": {"internet": {"ip4": ip4, "ip6": "::1"}}, + "ansible_facts": {"all_ipv4_addresses": [PUBLIC_IP, "10.208.0.1"]}, + } + templar = Templar(loader=DataLoader(), variables=dict(variables)) + templar.available_variables = dict(variables) + _reset_cache_for_tests() + try: + merged = get_merged_applications(variables=variables, templar=templar) + finally: + _reset_cache_for_tests() + return merged["web-app-nextcloud"]["services"]["talk"]["direct_media"] + + +STANDALONE_TURN = ("web-app-nextcloud", "web-svc-coturn") + + +class TestDirectMediaFlag(unittest.TestCase): + def test_compose_with_standalone_turn_and_an_owned_address_turns_it_on(self): + self.assertIs(_direct_media(list(STANDALONE_TURN)), True) + + def test_an_address_the_host_does_not_own_keeps_it_off(self): + self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="198.51.100.9"), False) + + def test_the_loopback_placeholder_keeps_it_off(self): + self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="127.0.0.1"), False) + + def test_swarm_keeps_it_off(self): + self.assertIs(_direct_media(list(STANDALONE_TURN), mode="swarm"), False) + + def test_onboard_turn_keeps_it_off(self): + forced = {"web-app-nextcloud": {"services": {"talk": {"enabled": True}}}} + self.assertIs(_direct_media(["web-app-nextcloud"], applications=forced), False) + + +if __name__ == "__main__": + unittest.main() From 9165bde600b35095223feeee020703da2260f4f3 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:11:10 +0100 Subject: [PATCH 17/21] feat(sys-svc-compose): decommission the compose stacks of roles no longer active Removing a role from the inventory left its compose stack running under /opt/compose, holding ports, memory and a stale instance directory, until someone stopped it by hand. On a full compose deploy with MODE_CLEANUP (no --id), the destructor now takes every directory below DIR_COMPOSITIONS that is named after a known role, carries the full instance layout and is owned by no active role (inventory-wide groups, group_names, the dependency closure and the instances this play prepared), stops it with compose down --remove-orphans without -v, verifies through the project and working_dir labels that no container is left, and only then deletes the directory; named volumes stay. Hand-made, partial or backup directories and instances a non-compose container is named after are left in place and listed. The step is the last block of the destructor, with the timer unlock in its always section, so a failure cannot leave timers locked. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-svc-compose/README.md | 1 + roles/sys-svc-compose/defaults/main.yml | 1 + .../compose_decommission_plan.py | 117 ++++++ .../tasks/02_stack_host_prep.yml | 4 + roles/sys-svc-compose/tasks/decommission.yml | 121 ++++++ tasks/stages/03_destructor.yml | 19 +- .../roles/sys-svc-compose/__init__.py | 3 + .../sys-svc-compose/test_decommission.py | 365 ++++++++++++++++++ .../filter_plugins/__init__.py | 5 + .../test_compose_decommission_plan.py | 289 ++++++++++++++ 10 files changed, 921 insertions(+), 4 deletions(-) create mode 100644 roles/sys-svc-compose/filter_plugins/compose_decommission_plan.py create mode 100644 roles/sys-svc-compose/tasks/decommission.yml create mode 100644 tests/integration/roles/sys-svc-compose/__init__.py create mode 100644 tests/integration/roles/sys-svc-compose/test_decommission.py create mode 100644 tests/unit/python/roles/sys-svc-compose/filter_plugins/__init__.py create mode 100644 tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_decommission_plan.py diff --git a/roles/sys-svc-compose/README.md b/roles/sys-svc-compose/README.md index d5ec9b04ed..cecc6b2727 100644 --- a/roles/sys-svc-compose/README.md +++ b/roles/sys-svc-compose/README.md @@ -32,6 +32,7 @@ To offer a centralized, extensible system for managing containerized application - **Dynamic Directory Structure:** Creates per-application instance folders for Compose setups. - **Reset Logic:** Cleans previous Compose project files and data when `MODE_RESET` is enabled. - **Handlers for Runtime Control:** Automatically builds, sets up, or restarts containers based on handlers. Notify `compose up` when rendered files or the service spec changed; notify `container recreate` when only in-container or in-database state changed and the process must reload it โ€” the latter force-recreates in compose mode and forces a task recreation in swarm mode, where `docker stack deploy` alone would leave the running task untouched. To rebuild and recreate single services while the rest of the stack keeps running, set `compose_service_up_targets` to their service keys and notify `compose-service-up`; it acts in compose mode only and recreates a service only when its image or configuration changed. +- **Decommission:** As the last step of a compose deploy without `--id` and with `MODE_CLEANUP`, every compose instance directly below `DIR_COMPOSITIONS` that no active role owns is stopped with `compose down --remove-orphans` and then deleted. Its named volumes stay; bind-mounted data inside the directory, such as `volumes/`, goes with it. A role counts as active when any host of the inventory carries it, when it is in the `CURRENT_PLAY_APPLICATIONS` dependency closure, or when the play prepared its instance. Only a directory named after a known role and carrying the full instance layout (`compose.yml`, `.env/`, `config/`, `services/`, `volumes/`) counts as an instance. An instance that a container outside its compose project is named after, such as a launcher-managed container, stays too. Every directory left alone is listed in the deploy output. The deploy fails before deleting anything when a container still carries the stopped project's name or working directory. - **Template-ready Service Files:** Predefined service base and health check templates. - **Integration Support:** Compatible with `sys-svc-proxy` and other Infinito.Nexus service roles. diff --git a/roles/sys-svc-compose/defaults/main.yml b/roles/sys-svc-compose/defaults/main.yml index ea72e5bd15..66afa9d69d 100644 --- a/roles/sys-svc-compose/defaults/main.yml +++ b/roles/sys-svc-compose/defaults/main.yml @@ -3,3 +3,4 @@ compose_handlers_flush: false # Set to true in the vars/main.yml of the includin compose_mode_force: "" # A role may set this to 'compose' or 'swarm' in its vars to override the cluster DEPLOYMENT_MODE for that role only compose_mode: "{{ compose_mode_force or DEPLOYMENT_MODE }}" # Effective deploy mode for this role (SPOT): the per-role override if set, else the cluster mode compose_repository_pull: "{{ compose_repository_url is defined and compose_repository_url is string and compose_repository_url | length > 0 }}" +compose_prepared_application_ids: [] # Application ids whose compose instance this play prepared on the host; tasks/decommission.yml keeps their directories diff --git a/roles/sys-svc-compose/filter_plugins/compose_decommission_plan.py b/roles/sys-svc-compose/filter_plugins/compose_decommission_plan.py new file mode 100644 index 0000000000..90a439181e --- /dev/null +++ b/roles/sys-svc-compose/filter_plugins/compose_decommission_plan.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +from pathlib import PurePosixPath + +from ansible.errors import AnsibleFilterError + +from utils.docker.paths_utils import get_docker_paths +from utils.roles.entity.name import get_entity_name + + +def _require(name: str, value, kind) -> None: + if not isinstance(value, kind): + raise AnsibleFilterError( + f"compose decommission: '{name}' has the wrong type {type(value).__name__}" + ) + + +def _instance_layout() -> tuple[frozenset[str], str]: + paths = get_docker_paths("instance", "/") + instance = PurePosixPath(paths["directories"]["instance"]) + directories = frozenset( + PurePosixPath(path).relative_to(instance).as_posix() + for key, path in paths["directories"].items() + if key != "instance" + ) + compose_file = PurePosixPath(paths["files"]["compose"]).relative_to(instance) + return directories, compose_file.as_posix() + + +def compose_decommission_plan( + entries: list[dict], root: str, active_roles: list[str], known_roles: list[str] +) -> dict[str, list[str]]: + """Split the directories below the compositions root that no active role owns. + + Args: + entries: ``find`` results for ``root`` down to depth 2, hidden entries + included, symlinks not followed. + root: ``DIR_COMPOSITIONS``. + active_roles: every role id or group that keeps its instance. + known_roles: every role id that can own an instance. + + Returns: + ``stale``: the sorted unowned directories named after a known role + that carry the full compose instance layout of ``get_docker_paths``. + ``unmanaged``: the sorted unowned directories that miss either; the + decommission leaves them alone. + """ + _require("entries", entries, (list, tuple)) + _require("root", root, str) + _require("active_roles", active_roles, (list, tuple)) + _require("known_roles", known_roles, (list, tuple)) + layout_directories, compose_file = _instance_layout() + base = PurePosixPath(root) + instances: set[PurePosixPath] = set() + present: set[tuple[PurePosixPath, str, bool]] = set() + for entry in entries: + path = PurePosixPath(entry["path"]) + if path.parent == base: + if entry["isdir"] and not path.name.startswith("."): + instances.add(path) + elif path.parent.parent == base and (entry["isdir"] or entry["isreg"]): + present.add((path.parent, path.name, entry["isdir"])) + owned = {get_entity_name(role) for role in active_roles} + known = {get_entity_name(role) for role in known_roles} + plan: dict[str, list[str]] = {"stale": [], "unmanaged": []} + for instance in sorted(instances): + if instance.name in owned: + continue + complete = ( + instance.name in known + and (instance, compose_file, False) in present + and all( + (instance, directory, True) in present + for directory in layout_directories + ) + ) + plan["stale" if complete else "unmanaged"].append(str(instance)) + return plan + + +def compose_decommission_confirm( + plan: dict[str, list[str]], namesakes: list[dict] +) -> dict[str, list[str]]: + """Keep the stale instances whose name a container outside their project holds. + + Args: + plan: the result of ``compose_decommission_plan``. + namesakes: the registered loop results of ``container ps --all`` per + stale instance, filtered on the instance name and formatted as + `` ``. + + Returns: + ``plan`` with ``stale`` reduced to the instances no foreign container + is named after and ``foreign`` listing the ones it holds back. + """ + _require("plan", plan, dict) + _require("namesakes", namesakes, (list, tuple)) + foreign = set() + for result in namesakes: + instance = result[result["ansible_loop_var"]] + name = PurePosixPath(instance).name + for line in result["stdout_lines"]: + if line.partition(" ")[2].strip() != name: + foreign.add(instance) + return { + "stale": [instance for instance in plan["stale"] if instance not in foreign], + "unmanaged": plan["unmanaged"], + "foreign": sorted(foreign), + } + + +class FilterModule: + def filters(self): + return { + "compose_decommission_plan": compose_decommission_plan, + "compose_decommission_confirm": compose_decommission_confirm, + } diff --git a/roles/sys-svc-compose/tasks/02_stack_host_prep.yml b/roles/sys-svc-compose/tasks/02_stack_host_prep.yml index b88fb5ce42..8be2f00ce4 100644 --- a/roles/sys-svc-compose/tasks/02_stack_host_prep.yml +++ b/roles/sys-svc-compose/tasks/02_stack_host_prep.yml @@ -8,6 +8,10 @@ running_check: "{{ compose_mode == 'compose' }}" register: compose_instance_before_files +- name: "๐Ÿ“ Record '{{ application_id }}' as a compose instance of this play" + ansible.builtin.set_fact: + compose_prepared_application_ids: "{{ compose_prepared_application_ids | union([application_id]) }}" + - name: "๐Ÿ›ก๏ธ Ensure PHP hardening assets are installed" ansible.builtin.include_role: name: sys-svc-compose-php diff --git a/roles/sys-svc-compose/tasks/decommission.yml b/roles/sys-svc-compose/tasks/decommission.yml new file mode 100644 index 0000000000..9f41b1fc28 --- /dev/null +++ b/roles/sys-svc-compose/tasks/decommission.yml @@ -0,0 +1,121 @@ +--- +- name: "๐Ÿ” Find the compose instances below '{{ DIR_COMPOSITIONS }}'" + ansible.builtin.find: + paths: "{{ DIR_COMPOSITIONS }}" + file_type: any + hidden: true + recurse: true + depth: 2 + register: compose_instances_found + +- name: "๐Ÿงฎ Plan the decommission of the instances no active role owns" + ansible.builtin.set_fact: + compose_decommission_candidates: >- + {{ + compose_instances_found.files + | compose_decommission_plan( + DIR_COMPOSITIONS, + lookup('deployment').inventory + + group_names + + (CURRENT_PLAY_APPLICATIONS | list) + + compose_prepared_application_ids, + lookup('deployment').all + ) + }} + +- name: "๐Ÿ” Find containers named like a stale compose instance" + ansible.builtin.command: + argv: + - container + - ps + - --all + - --filter + - "name=^/?{{ compose_stale_candidate | basename }}$" + - --format + - '{{ "{{" }}.Names{{ "}}" }} {{ "{{" }}.Label "com.docker.compose.project"{{ "}}" }}' + register: compose_stale_namesakes + changed_when: false + check_mode: false + loop: "{{ compose_decommission_candidates.stale }}" + loop_control: + loop_var: compose_stale_candidate + +- name: "๐Ÿงฎ Hold back the instances a container outside compose is named after" + ansible.builtin.set_fact: + compose_decommission: "{{ compose_decommission_candidates | compose_decommission_confirm(compose_stale_namesakes.results) }}" + +- name: "โš ๏ธ Keep the unowned directories that are no compose instance" + ansible.builtin.debug: + msg: >- + No active role owns {{ compose_decommission.unmanaged | join(', ') }}, but + they are no compose instance of a known role, so the decommission leaves + them in place. + when: compose_decommission.unmanaged | length > 0 + +- name: "โš ๏ธ Keep the stale instances a container outside compose runs from" + ansible.builtin.debug: + msg: >- + No active role owns {{ compose_decommission.foreign | join(', ') }}, but a + container their compose project does not own carries their name, so the + decommission leaves them in place. + when: compose_decommission.foreign | length > 0 + +- name: "๐Ÿ›‘ Stop the stale compose stacks and keep their volumes" + ansible.builtin.command: + argv: + - "{{ BIN_COMPOSE }}" + - --chdir + - "{{ compose_stale_instance }}" + - down + - --remove-orphans + removes: "{{ [compose_stale_instance, 'compose.yml'] | path_join }}" + timeout: "{{ lookup('timeout', 600) | int }}" + loop: "{{ compose_decommission.stale }}" + loop_control: + loop_var: compose_stale_instance + +- name: "๐Ÿ” Resolve '{{ DIR_COMPOSITIONS }}' like the compose wrapper" + ansible.builtin.command: + argv: + - realpath + - --canonicalize-missing + - "{{ DIR_COMPOSITIONS }}" + register: compose_compositions_resolved + changed_when: false + check_mode: false + +- name: "๐Ÿ›‘ Fail when a stopped compose stack left containers behind" + ansible.builtin.command: + argv: + - container + - ps + - --all + - --quiet + - --filter + - "label={{ compose_stale_label }}" + vars: + compose_stale_names: "{{ compose_decommission.stale | map('basename') | list }}" + compose_stale_working_dirs: >- + {{ + compose_decommission.stale + + (compose_stale_names | map('regex_replace', '^', compose_compositions_resolved.stdout ~ '/') | list) + }} + register: compose_stale_leftovers + changed_when: false + failed_when: compose_stale_leftovers.rc != 0 or (compose_stale_leftovers.stdout | length > 0) + loop: >- + {{ + (compose_stale_names | map('regex_replace', '^', 'com.docker.compose.project=') | list) + + (compose_stale_working_dirs | unique | map('regex_replace', '^', 'com.docker.compose.project.working_dir=') | list) + }} + loop_control: + loop_var: compose_stale_label + when: not ansible_check_mode + +- name: "๐Ÿ—‘๏ธ Remove the stale compose instance directories" + ansible.builtin.file: + path: "{{ compose_stale_instance }}" + state: absent + loop: "{{ compose_decommission.stale }}" + loop_control: + loop_var: compose_stale_instance diff --git a/tasks/stages/03_destructor.yml b/tasks/stages/03_destructor.yml index dda4e72ede..61608f9c26 100644 --- a/tasks/stages/03_destructor.yml +++ b/tasks/stages/03_destructor.yml @@ -26,7 +26,18 @@ name: test-e2e-cli when: RUNTIME in ['dev', 'act', 'github'] -- name: "๐Ÿ”“ Unlock all timers" - include_role: - name: sys-service-terminator - tasks_from: 02_unlock.yml +- name: "๐Ÿงน Decommission stale compose stacks while the timers are still locked" + block: + - name: "๐Ÿงน Decommission the compose stacks of roles no longer active on this host" + include_role: + name: sys-svc-compose + tasks_from: decommission.yml + when: + - MODE_CLEANUP | bool + - DEPLOYMENT_MODE == 'compose' + - lookup('deployment').whitelist | length == 0 + always: + - name: "๐Ÿ”“ Unlock all timers" + include_role: + name: sys-service-terminator + tasks_from: 02_unlock.yml diff --git a/tests/integration/roles/sys-svc-compose/__init__.py b/tests/integration/roles/sys-svc-compose/__init__.py new file mode 100644 index 0000000000..88f288ec1f --- /dev/null +++ b/tests/integration/roles/sys-svc-compose/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/tests/integration/roles/sys-svc-compose/test_decommission.py b/tests/integration/roles/sys-svc-compose/test_decommission.py new file mode 100644 index 0000000000..ba12470274 --- /dev/null +++ b/tests/integration/roles/sys-svc-compose/test_decommission.py @@ -0,0 +1,365 @@ +from __future__ import annotations + +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from utils.cache.yaml import dump_yaml, load_yaml_any + +from . import PROJECT_ROOT + +LAYOUT = (".env", "config", "services", "volumes") + +FAKE_COMPOSE = """#!/bin/sh +printf '%s\\n' "$*" >> "$FAKE_COMPOSE_LOG" +""" + +FAKE_CONTAINER = """#!/bin/sh +printf '%s\\n' "$*" >> "$FAKE_CONTAINER_LOG" +case "$3" in +--quiet) + if grep -qxF -- "${5#label=}" "$FAKE_CONTAINER_LEFTOVERS"; then + echo 0123456789ab + fi + ;; +--filter) + name=$(printf '%s' "$4" | sed -e 's/^name=^\\/?//' -e 's/\\$$//') + grep -E "^$name " "$FAKE_CONTAINER_NAMESAKES" + ;; +esac +exit 0 +""" + +_RECAP = re.compile( + r"^(?P\S+)\s*:\s*ok=\d+\s+changed=(?P\d+)\s+" + r"unreachable=\d+\s+failed=(?P\d+)", + re.MULTILINE, +) + + +def _includes(tasks: list[dict], tasks_from: str) -> bool: + return any( + isinstance(task.get("include_role"), dict) + and task["include_role"].get("tasks_from") == tasks_from + for task in tasks + ) + + +def _destructor_block() -> dict: + stage = load_yaml_any(str(PROJECT_ROOT / "tasks" / "stages" / "03_destructor.yml")) + return next( + task + for task in stage + if "block" in task and _includes(task["block"], "decommission.yml") + ) + + +def _destructor_task() -> dict: + return next( + task + for task in _destructor_block()["block"] + if _includes([task], "decommission.yml") + ) + + +def _prepared_tasks() -> list[dict]: + prep = load_yaml_any( + str( + PROJECT_ROOT + / "roles" + / "sys-svc-compose" + / "tasks" + / "02_stack_host_prep.yml" + ) + ) + record = next(task for task in prep if "ansible.builtin.set_fact" in task) + return [ + dict( + record, + vars={ + "application_id": "web-app-prepared", + "compose_prepared_application_ids": [], + }, + ), + dict(record, vars={"application_id": "web-app-alsoprepared"}), + ] + + +def _lines(path: Path) -> list[str]: + return path.read_text().splitlines() # nocheck: cache-read tempdir log + + +def _executable(path: Path, content: str) -> None: + path.write_text(content) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def _instance(root: Path, name: str, *, layout: bool = True, compose: bool = True): + instance = root / name + instance.mkdir(parents=True) + if layout: + for directory in LAYOUT: + (instance / directory).mkdir() + if compose: + (instance / "compose.yml").write_text("services: {}\n") + return instance + + +@unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook is required") +class TestComposeDecommission(unittest.TestCase): + def setUp(self) -> None: + self.work = Path(tempfile.mkdtemp(prefix="compose-decommission-")) + self.addCleanup(shutil.rmtree, self.work, ignore_errors=True) + self.bin = self.work / "bin" + self.bin.mkdir() + self.fake_compose = self.bin / "compose" + _executable(self.fake_compose, FAKE_COMPOSE) + _executable(self.bin / "container", FAKE_CONTAINER) + self.compose_log = self.work / "compose.log" + self.container_log = self.work / "container.log" + self.leftovers = self.work / "leftovers" + self.namesakes = self.work / "namesakes" + for path in ( + self.compose_log, + self.container_log, + self.leftovers, + self.namesakes, + ): + path.write_text("") + self.playbook = self.work / "playbook.yml" + dump_yaml( + self.playbook, + [ + { + "hosts": "all", + "gather_facts": False, + "tasks": [*_prepared_tasks(), _destructor_task()], + } + ], + ) + + def _host( + self, name: str, *, symlinked: bool = False, **overrides + ) -> tuple[Path, dict]: + root = self.work / name / "compose" + if symlinked: + target = self.work / name / "real-compose" + target.mkdir(parents=True) + root.symlink_to(target) + else: + root.mkdir(parents=True) + values = { + "ansible_connection": "local", + "ansible_python_interpreter": sys.executable, + "DIR_COMPOSITIONS": f"{root}/", + "BIN_COMPOSE": str(self.fake_compose), + "MODE_CLEANUP": True, + "DEPLOYMENT_MODE": "compose", + "APPLICATIONS_WHITELIST": [], + "CURRENT_PLAY_APPLICATIONS": {"web-app-closure": {}}, + } + values.update(overrides) + return root, values + + def _inventory(self, hosts: dict, elsewhere: dict | None = None) -> Path: + inventory = self.work / "inventory.yml" + children = {"web-app-grouped": {"hosts": {name: {} for name in hosts}}} + for group, members in (elsewhere or {}).items(): + children[group] = {"hosts": {name: {} for name in members}} + dump_yaml(inventory, {"all": {"hosts": hosts, "children": children}}) + return inventory + + def _play(self, inventory: Path, *args: str) -> subprocess.CompletedProcess: + env = dict(os.environ) + env.update( + { + "ANSIBLE_CONFIG": str(PROJECT_ROOT / "ansible.cfg"), + "ANSIBLE_LOCAL_TEMP": str(self.work / "ansible-local"), + "ANSIBLE_REMOTE_TEMP": str(self.work / "ansible-remote"), + "ANSIBLE_NOCOLOR": "1", + "PATH": f"{self.bin}{os.pathsep}{env['PATH']}", + "FAKE_COMPOSE_LOG": str(self.compose_log), + "FAKE_CONTAINER_LOG": str(self.container_log), + "FAKE_CONTAINER_LEFTOVERS": str(self.leftovers), + "FAKE_CONTAINER_NAMESAKES": str(self.namesakes), + } + ) + return subprocess.run( + ["ansible-playbook", "-i", str(inventory), str(self.playbook), *args], + cwd=str(PROJECT_ROOT), + env=env, + capture_output=True, + text=True, + check=False, + ) + + def _open_host(self) -> tuple[Path, dict]: + root, values = self._host("open") + stale = _instance(root, "mailu") + (stale / "volumes" / "data.txt").write_text("bind data\n") + for name in ( + "grouped", + "closure", + "prepared", + "alsoprepared", + "baserow", + "discourse", + ): + _instance(root, name) + ( + _instance(root, "handmade", layout=False, compose=False) / "notes.txt" + ).write_text("operator notes\n") + _instance(root, "partial", layout=False) + _instance(root, "nextcloud-old") + _instance(root, ".hidden") + (root / "linked").symlink_to(_instance(self.work, "elsewhere")) + self.namesakes.write_text("mailu mailu\ndiscourse \n") + return root, values + + def _assert_ok(self, result: subprocess.CompletedProcess) -> dict: + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return { + m["host"]: (int(m["changed"]), int(m["failed"])) + for m in _RECAP.finditer(result.stdout) + } + + def _guard_queries(self) -> list[str]: + return [ + line + for line in _lines(self.container_log) + if line.startswith("ps --all --quiet") + ] + + def test_the_timers_unlock_even_when_the_decommission_fails(self): + stage = load_yaml_any( + str(PROJECT_ROOT / "tasks" / "stages" / "03_destructor.yml") + ) + block = _destructor_block() + self.assertIs(stage[-1], block) + self.assertTrue(_includes(block["always"], "02_unlock.yml")) + self.assertFalse( + _includes([task for task in stage if task is not block], "02_unlock.yml") + ) + + def test_check_mode_reports_the_decommission_and_changes_nothing(self): + root, values = self._open_host() + before = sorted(p.name for p in root.iterdir()) + + recap = self._assert_ok( + self._play(self._inventory({"open": values}), "--check") + ) + + self.assertGreater(recap["open"][0], 0) + self.assertEqual(sorted(p.name for p in root.iterdir()), before) + self.assertEqual(_lines(self.compose_log), []) + self.assertEqual(self._guard_queries(), []) + + def test_only_an_unrestricted_cleanup_deploy_decommissions_and_a_rerun_is_idle( + self, + ): + root, open_values = self._open_host() + gated = { + "whitelisted": {"APPLICATIONS_WHITELIST": ["web-app-grouped"]}, + "cleanup_off": {"MODE_CLEANUP": False}, + "swarm": {"DEPLOYMENT_MODE": "swarm"}, + } + hosts = {"open": open_values} + gated_roots = {} + for name, overrides in gated.items(): + gated_roots[name], hosts[name] = self._host(name, **overrides) + _instance(gated_roots[name], "mailu") + _, hosts["absent"] = self._host( + "absent", DIR_COMPOSITIONS=f"{self.work}/absent/missing/" + ) + inventory = self._inventory(hosts, {"web-app-baserow": ["whitelisted"]}) + + result = self._play(inventory) + recap = self._assert_ok(result) + output = " ".join(result.stdout.split()) + + self.assertEqual( + sorted(p.name for p in root.iterdir()), + [ + ".hidden", + "alsoprepared", + "baserow", + "closure", + "discourse", + "grouped", + "handmade", + "linked", + "nextcloud-old", + "partial", + "prepared", + ], + ) + self.assertTrue((root / "handmade" / "notes.txt").is_file()) + self.assertTrue((self.work / "elsewhere" / "compose.yml").is_file()) + for gated_root in gated_roots.values(): + self.assertTrue((gated_root / "mailu" / "compose.yml").is_file()) + self.assertEqual( + _lines(self.compose_log), + [f"--chdir {root}/mailu down --remove-orphans"], + ) + self.assertEqual( + self._guard_queries(), + [ + "ps --all --quiet --filter label=com.docker.compose.project=mailu", + ( + "ps --all --quiet --filter " + f"label=com.docker.compose.project.working_dir={root}/mailu" + ), + ], + ) + self.assertIn( + f"No active role owns {root}/handmade, {root}/nextcloud-old, " + f"{root}/partial, but", + output, + ) + self.assertIn(f"No active role owns {root}/discourse, but a container", output) + self.assertGreater(recap["open"][0], 0) + for name in (*gated, "absent"): + self.assertEqual(recap[name], (0, 0)) + + rerun = self._assert_ok(self._play(inventory)) + + self.assertEqual(set(rerun.values()), {(0, 0)}) + self.assertEqual(len(_lines(self.compose_log)), 1) + + def test_a_stack_that_keeps_containers_fails_and_keeps_its_directory(self): + cases = ( + ("project", "com.docker.compose.project=mailu", False), + ("workdir", "com.docker.compose.project.working_dir={root}/mailu", False), + ( + "resolved", + "com.docker.compose.project.working_dir={resolved}/mailu", + True, + ), + ) + for name, label, symlinked in cases: + with self.subTest(case=name): + root, values = self._host(name, symlinked=symlinked) + _instance(root, "mailu") + self.leftovers.write_text( + label.format(root=root, resolved=root.resolve()) + "\n" + ) + + result = self._play(self._inventory({"open": values})) + + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn("0123456789ab", result.stdout) + self.assertTrue((root / "mailu" / "compose.yml").is_file()) + self.assertIn( + f"--chdir {root}/mailu down --remove-orphans", + _lines(self.compose_log), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-compose/filter_plugins/__init__.py b/tests/unit/python/roles/sys-svc-compose/filter_plugins/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-compose/filter_plugins/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_decommission_plan.py b/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_decommission_plan.py new file mode 100644 index 0000000000..ed2868fb03 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_decommission_plan.py @@ -0,0 +1,289 @@ +import importlib.util +import unittest + +from ansible.errors import AnsibleFilterError + +from . import PROJECT_ROOT + +ROOT = "/opt/compose/" +LAYOUT = (".env", "config", "services", "volumes") +KNOWN = [ + f"web-app-{name}" + for name in ( + "mailu", + "stalwart", + "baserow", + "discourse", + "handmade", + "partial", + "odd", + "dotenv", + "outer", + "inner", + "alpha", + "zeta", + ) +] + ["svc-db-postgres", "svc-db-mariadb", "svc-prx-openresty", "web-svc-simpleicons"] + + +def _load_module(): + path = ( + PROJECT_ROOT + / "roles" + / "sys-svc-compose" + / "filter_plugins" + / "compose_decommission_plan.py" + ) + spec = importlib.util.spec_from_file_location("compose_decommission_plan", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) # type: ignore[union-attr] + return module + + +def _entry(path, isdir=False, isreg=False): + return {"path": path, "isdir": isdir, "isreg": isreg, "islnk": False} + + +def _instance(name, skip=()): + base = f"/opt/compose/{name}" + entries = [_entry(base, isdir=True)] + entries += [_entry(f"{base}/{d}", isdir=True) for d in LAYOUT if d not in skip] + if "compose.yml" not in skip: + entries.append(_entry(f"{base}/compose.yml", isreg=True)) + return entries + + +def _namesakes(instance, *lines): + return { + "ansible_loop_var": "compose_stale_candidate", + "compose_stale_candidate": instance, + "stdout_lines": list(lines), + } + + +class TestComposeDecommissionPlan(unittest.TestCase): + def setUp(self): + self.plan = _load_module().compose_decommission_plan + + def test_the_instance_of_a_role_removed_from_the_host_is_stale(self): + entries = _instance("mailu") + _instance("stalwart") + self.assertEqual( + self.plan(entries, ROOT, ["web-app-stalwart"], KNOWN), + {"stale": ["/opt/compose/mailu"], "unmanaged": []}, + ) + + def test_the_instances_of_active_shared_services_are_kept(self): + entries = ( + _instance("postgres") + + _instance("mariadb") + + _instance("openresty") + + _instance("simpleicons") + ) + active = [ + "svc-db-postgres", + "svc-db-mariadb", + "svc-prx-openresty", + "web-svc-simpleicons", + ] + self.assertEqual( + self.plan(entries, ROOT, active, KNOWN), {"stale": [], "unmanaged": []} + ) + + def test_a_full_instance_of_no_known_role_is_unmanaged(self): + entries = _instance("nextcloud-old") + _instance("mailu.bak") + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), + { + "stale": [], + "unmanaged": ["/opt/compose/mailu.bak", "/opt/compose/nextcloud-old"], + }, + ) + + def test_a_directory_without_compose_file_is_unmanaged(self): + entries = _instance("handmade", skip=("compose.yml",)) + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), + {"stale": [], "unmanaged": ["/opt/compose/handmade"]}, + ) + + def test_each_missing_layout_directory_makes_the_directory_unmanaged(self): + for missing in LAYOUT: + with self.subTest(missing=missing): + self.assertEqual( + self.plan(_instance("partial", skip=(missing,)), ROOT, [], KNOWN), + {"stale": [], "unmanaged": ["/opt/compose/partial"]}, + ) + + def test_a_compose_file_that_is_a_directory_does_not_count(self): + entries = [ + *_instance("odd", skip=("compose.yml",)), + _entry("/opt/compose/odd/compose.yml", isdir=True), + ] + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), + {"stale": [], "unmanaged": ["/opt/compose/odd"]}, + ) + + def test_a_layout_entry_that_is_a_file_does_not_count(self): + entries = [ + *_instance("dotenv", skip=(".env",)), + _entry("/opt/compose/dotenv/.env", isreg=True), + ] + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), + {"stale": [], "unmanaged": ["/opt/compose/dotenv"]}, + ) + + def test_hidden_directories_are_ignored(self): + self.assertEqual( + self.plan(_instance(".trash"), ROOT, [], KNOWN), + {"stale": [], "unmanaged": []}, + ) + + def test_symlinks_and_files_below_the_root_are_ignored(self): + entries = [ + { + "path": "/opt/compose/linked", + "isdir": False, + "isreg": False, + "islnk": True, + }, + _entry("/opt/compose/README", isreg=True), + ] + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), {"stale": [], "unmanaged": []} + ) + + def test_a_layout_found_deeper_does_not_make_an_instance(self): + entries = [_entry("/opt/compose/outer", isdir=True)] + [ + dict( + entry, + path=entry["path"].replace("/opt/compose/", "/opt/compose/outer/"), + ) + for entry in _instance("inner")[1:] + ] + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), + {"stale": [], "unmanaged": ["/opt/compose/outer"]}, + ) + + def test_the_root_matches_with_and_without_trailing_slash(self): + for root in ("/opt/compose", "/opt/compose/"): + with self.subTest(root=root): + self.assertEqual( + self.plan(_instance("mailu"), root, [], KNOWN)["stale"], + ["/opt/compose/mailu"], + ) + + def test_a_group_name_that_is_no_role_does_not_keep_a_stale_instance(self): + self.assertEqual( + self.plan(_instance("mailu"), ROOT, ["servers", "web-app-stalwart"], KNOWN)[ + "stale" + ], + ["/opt/compose/mailu"], + ) + + def test_both_lists_come_back_sorted(self): + entries = ( + _instance("mailu") + + _instance("baserow") + + _instance("zeta", skip=("compose.yml",)) + + _instance("alpha", skip=("compose.yml",)) + ) + self.assertEqual( + self.plan(entries, ROOT, [], KNOWN), + { + "stale": ["/opt/compose/baserow", "/opt/compose/mailu"], + "unmanaged": ["/opt/compose/alpha", "/opt/compose/zeta"], + }, + ) + + def test_no_entries_yield_an_empty_plan(self): + self.assertEqual( + self.plan([], ROOT, ["web-app-stalwart"], KNOWN), + {"stale": [], "unmanaged": []}, + ) + + def test_wrongly_typed_arguments_fail(self): + cases = ( + ("/opt/compose/mailu", ROOT, [], KNOWN), + ([], ["/opt/compose/"], [], KNOWN), + ([], ROOT, "web-app-mailu", KNOWN), + ([], ROOT, [], "web-app-mailu"), + ) + for args in cases: + with self.subTest(args=args), self.assertRaises(AnsibleFilterError): + self.plan(*args) + + +class TestComposeDecommissionConfirm(unittest.TestCase): + def setUp(self): + self.confirm = _load_module().compose_decommission_confirm + self.plan = { + "stale": ["/opt/compose/discourse", "/opt/compose/mailu"], + "unmanaged": ["/opt/compose/handmade"], + } + + def test_instances_without_namesakes_stay_stale(self): + self.assertEqual( + self.confirm( + self.plan, + [ + _namesakes("/opt/compose/discourse"), + _namesakes("/opt/compose/mailu"), + ], + ), + dict(self.plan, foreign=[]), + ) + + def test_a_namesake_of_the_own_project_keeps_the_instance_stale(self): + result = self.confirm( + self.plan, + [ + _namesakes("/opt/compose/discourse"), + _namesakes("/opt/compose/mailu", "mailu mailu"), + ], + ) + self.assertEqual( + result["stale"], ["/opt/compose/discourse", "/opt/compose/mailu"] + ) + + def test_a_namesake_without_compose_project_holds_the_instance_back(self): + self.assertEqual( + self.confirm( + self.plan, + [ + _namesakes("/opt/compose/discourse", "discourse "), + _namesakes("/opt/compose/mailu"), + ], + ), + { + "stale": ["/opt/compose/mailu"], + "unmanaged": ["/opt/compose/handmade"], + "foreign": ["/opt/compose/discourse"], + }, + ) + + def test_a_namesake_of_another_project_holds_the_instance_back(self): + result = self.confirm( + self.plan, + [ + _namesakes("/opt/compose/discourse"), + _namesakes("/opt/compose/mailu", "mailu mailu", "mailu stalwart"), + ], + ) + self.assertEqual(result["foreign"], ["/opt/compose/mailu"]) + self.assertEqual(result["stale"], ["/opt/compose/discourse"]) + + def test_no_probe_results_change_nothing(self): + plan = {"stale": [], "unmanaged": []} + self.assertEqual(self.confirm(plan, []), dict(plan, foreign=[])) + + def test_wrongly_typed_arguments_fail(self): + for args in (([], []), (self.plan, {})): + with self.subTest(args=args), self.assertRaises(AnsibleFilterError): + self.confirm(*args) + + +if __name__ == "__main__": + unittest.main() From 368856212899834fe5e81ddca0d1e679e672ceb6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 25 Oct 2026 07:35:37 +0100 Subject: [PATCH 18/21] fix(web-app-decidim): create the organization outside production too Since db:seed only runs under MODE_DEMO (8e35d053a2), nothing created an organization on a non-production deploy, so the host and OIDC tasks that follow had none to configure. Co-Authored-By: Claude Opus 5.5 --- roles/web-app-decidim/tasks/01_setup.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/roles/web-app-decidim/tasks/01_setup.yml b/roles/web-app-decidim/tasks/01_setup.yml index bdee01699d..f9491abece 100644 --- a/roles/web-app-decidim/tasks/01_setup.yml +++ b/roles/web-app-decidim/tasks/01_setup.yml @@ -37,7 +37,6 @@ stdin: "{{ lookup('file', 'ruby/ensure/organization.rb') }}" register: decidim_organization_result changed_when: "'Organization created' in decidim_organization_result.stdout" - when: ENVIRONMENT == 'production' delegate_to: "{{ DECIDIM_HOST_NODE }}" - name: "๐ŸŒฑ Decidim | Seed the demo data" From 6e7956798d64b10ca6604ba93066b80134ff8635 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:25:21 +0100 Subject: [PATCH 19/21] fix(web-app-nextcloud): drop the swarm-only mode from the Janus config mount janus_conf is mounted only when direct media is on, which requires compose mode, and compose ignores a config mode outside swarm and warns about it on every deploy. The file keeps the 0644 it is rendered with on the host. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/meta/volumes.yml | 1 - .../python/roles/web-app-nextcloud/test_talk_direct_media.py | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/roles/web-app-nextcloud/meta/volumes.yml b/roles/web-app-nextcloud/meta/volumes.yml index e9b28b9af2..599520cdcf 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -64,7 +64,6 @@ infinito_conf: janus_conf: type: config source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'janus.jcfg' ] | path_join }}" - mode: "0444" mounts: - service: talk target: /usr/local/etc/janus/janus.jcfg diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index 05f0349f3d..ccc161752a 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -62,8 +62,7 @@ DIRECT_MOUNT = ( " \n" " configs:\n" " - source: janus_conf\n" - " target: /usr/local/etc/janus/janus.jcfg\n" - " mode: 292" + " target: /usr/local/etc/janus/janus.jcfg" ) DIRECT_PORT = ' - "203.0.113.7:61000-61999:61000-61999/udp"' From 9f543c408186fa7cb55f271a3c15b5aae514787d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:26:42 +0100 Subject: [PATCH 20/21] fix(sys-front-tls): stop enabling OCSP stapling no certificate can serve Every TLS vhost set ssl_stapling on. Let's Encrypt certificates carry no OCSP responder URL since Let's Encrypt ended OCSP in 2025, and the self-signed development certificates have no issuer chain for it, so nginx ignored the directive and logged a warning for every server block on every reload. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-front-tls/templates/nginx_ssl_header.j2 | 3 --- 1 file changed, 3 deletions(-) diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 6fc4b4f1a7..02bbc026a3 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -13,9 +13,6 @@ ssl_session_tickets on; add_header Strict-Transport-Security max-age=31536000 always; -ssl_stapling on; -ssl_stapling_verify on; - {% include 'roles/sys-front-tls/templates/ssl_credentials.j2' %} {% else %} From e2a49f89b5741beaadd136159140cbb38dd11365 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 03:29:23 +0100 Subject: [PATCH 21/21] test: settle the CodeQL notes on the unit test imports CodeQL flagged five notes on PR #1215: four test modules imported unittest both as a module and through from-import, and sys-front-inj-matomo's __init__ exported PROJECT_ROOT without declaring it, so the import from test_site_cache.py read as unused. The modules now bind mock through import unittest.mock as mock, and the package declares __all__, the same fixes main carries from 3610e7b9ef and 6e776a5780. The same pattern is fixed in the new Talk direct-media test and the decommission integration package, and the coturn test package drops an __init__ export nothing imports. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/integration/roles/sys-svc-compose/__init__.py | 2 ++ tests/unit/python/roles/svc-db-postgres/files/test_cluster.py | 2 +- tests/unit/python/roles/sys-front-inj-matomo/__init__.py | 2 ++ .../sys-svc-compose/library/test_compose_instance_prepare.py | 2 +- .../python/roles/web-app-keycloak/files/test_email_verified.py | 2 +- .../python/roles/web-app-keycloak/files/test_keycloak_admin.py | 2 +- .../python/roles/web-app-nextcloud/test_talk_direct_media.py | 2 +- tests/unit/python/roles/web-svc-coturn/__init__.py | 3 --- 8 files changed, 9 insertions(+), 8 deletions(-) diff --git a/tests/integration/roles/sys-svc-compose/__init__.py b/tests/integration/roles/sys-svc-compose/__init__.py index 88f288ec1f..eec6d4835a 100644 --- a/tests/integration/roles/sys-svc-compose/__init__.py +++ b/tests/integration/roles/sys-svc-compose/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-db-postgres/files/test_cluster.py b/tests/unit/python/roles/svc-db-postgres/files/test_cluster.py index d3859cbd7d..de7a87da6a 100644 --- a/tests/unit/python/roles/svc-db-postgres/files/test_cluster.py +++ b/tests/unit/python/roles/svc-db-postgres/files/test_cluster.py @@ -7,9 +7,9 @@ import subprocess import sys import tempfile import unittest +import unittest.mock as mock from datetime import UTC, datetime from pathlib import Path -from unittest import mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/sys-front-inj-matomo/__init__.py b/tests/unit/python/roles/sys-front-inj-matomo/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/sys-front-inj-matomo/__init__.py +++ b/tests/unit/python/roles/sys-front-inj-matomo/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-svc-compose/library/test_compose_instance_prepare.py b/tests/unit/python/roles/sys-svc-compose/library/test_compose_instance_prepare.py index bfcb79fde5..fdafbe4396 100644 --- a/tests/unit/python/roles/sys-svc-compose/library/test_compose_instance_prepare.py +++ b/tests/unit/python/roles/sys-svc-compose/library/test_compose_instance_prepare.py @@ -9,9 +9,9 @@ import stat import sys import tempfile import unittest +import unittest.mock as mock from pathlib import Path from typing import TYPE_CHECKING -from unittest import mock from ansible.module_utils.testing import patch_module_args diff --git a/tests/unit/python/roles/web-app-keycloak/files/test_email_verified.py b/tests/unit/python/roles/web-app-keycloak/files/test_email_verified.py index f65275f163..d57b40936b 100644 --- a/tests/unit/python/roles/web-app-keycloak/files/test_email_verified.py +++ b/tests/unit/python/roles/web-app-keycloak/files/test_email_verified.py @@ -3,8 +3,8 @@ import io import os import sys import unittest +import unittest.mock as mock import urllib.parse -from unittest import mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py b/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py index 0ddc3bb301..f27d8c58a1 100644 --- a/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py +++ b/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py @@ -3,9 +3,9 @@ import json import sys import tempfile import unittest +import unittest.mock as mock import urllib.error from pathlib import Path -from unittest import mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index ccc161752a..9d3ddb3211 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -2,7 +2,7 @@ from __future__ import annotations import itertools import unittest -from unittest import mock +import unittest.mock as mock from jinja2 import ( ChainableUndefined, diff --git a/tests/unit/python/roles/web-svc-coturn/__init__.py b/tests/unit/python/roles/web-svc-coturn/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/web-svc-coturn/__init__.py +++ b/tests/unit/python/roles/web-svc-coturn/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]