diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index e77c6afbe2..32d50480f1 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 gpu: true min_storage: 3473MB diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 5c369103f3..ae24cd11f7 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 %} diff --git a/roles/sys-svc-compose/README.md b/roles/sys-svc-compose/README.md index 193e8ec190..33a4bc2298 100644 --- a/roles/sys-svc-compose/README.md +++ b/roles/sys-svc-compose/README.md @@ -19,5 +19,6 @@ 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 21f3a8f598..5310c09865 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/roles/sys-svc-journalctl/README.md b/roles/sys-svc-journalctl/README.md index 101affdf59..a1023f4ec6 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') }}" diff --git a/roles/web-app-checkmk/meta/services.yml b/roles/web-app-checkmk/meta/services.yml index 9fb01b7467..7c0d11e1de 100644 --- a/roles/web-app-checkmk/meta/services.yml +++ b/roles/web-app-checkmk/meta/services.yml @@ -78,7 +78,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 diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index 6d004c995b..966441610f 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -51,7 +51,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: diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 3433f811cd..686073b097 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -94,7 +94,7 @@ postgres: synapse: healthcheck: flavor: curl - version: v1.163.2 + version: v1.164.0 image: matrixdotorg/synapse name: matrix-synapse backup: @@ -117,7 +117,7 @@ synapse: element: healthcheck: flavor: wget - version: v1.12.32 + version: v1.12.33 image: vectorim/element-web name: matrix-element ports: diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index facd98d691..834ed7379d 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -75,7 +75,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "2.45.4" + version: "3.0.0" update: type: registry_tags image: docker.n8n.io/n8nio/n8n 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/playwright.spec.js b/roles/web-app-nextcloud/files/playwright/playwright.spec.js index 986719fe1a..c82c4fb37c 100644 --- a/roles/web-app-nextcloud/files/playwright/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright/playwright.spec.js @@ -20,6 +20,7 @@ test.beforeEach(shared.beforeEach); require("./test-design").register(shared); 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..e1d3a7eb73 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/test-talk-call-capacity.js @@ -0,0 +1,181 @@ +const { test, expect, chromium } = 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 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; +const leaveCallPattern = /^(leave call|anruf verlassen)$/i; +const guestNamePattern = /enter your name|display name|anzeigename/i; +const submitGuestNamePattern = /submit name and join/i; +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); + 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, + }; + }); +} + +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, + 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) { + // 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"); + 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), + }); + 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 }; +} + +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 mediaBrowser = await chromium.launch({ + args: ["--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream"], + }); + 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(mediaBrowser, new URL(`call/${token}`, baseUrl).toString(), `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); + 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(() => {}); + if (token) { + await adminPage.request + .delete(new URL(`ocs/v2.php/apps/spreed/api/v4/room/${token}`, baseUrl).toString(), { headers: ocsHeaders }) + .catch(() => {}); + } + await adminContext.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 417a745ecf..72e20d2acb 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 @@ -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 382c788d39..9880d5ab98 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -56,6 +56,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 5ec4895b85..384d050809 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -70,6 +70,14 @@ 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 }}" + 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 e6dc7c4d7d..fc1733eb2f 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 }}" @@ -88,3 +133,13 @@ dest: "{{ NEXTCLOUD_HOST_TALK_BACKENDS_PATH }}" mode: "0444" when: NEXTCLOUD_HPB_SIGNALING_ENABLED | bool + +- 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 1e3249a105..9461ef089c 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -76,14 +76,26 @@ {{ lookup('container_volumes', service_name) | indent(4) }} 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 280db3cbed..6ffd0638d2 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -47,6 +47,14 @@ NEXTCLOUD_MCP_UPSTREAM_PATH={{ lookup('config', application_id, 'mcp.adapter.ups NEXTCLOUD_ONLYOFFICE_EXPECTED_DOCUMENT_SERVER_URL={{ [NEXTCLOUD_URL, NEXTCLOUD_ONLYOFFICE_LOCATION] | url_join | 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 1546fcff2a..3d1e5b7193 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -162,6 +162,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/roles/web-app-openbao/meta/services.yml b/roles/web-app-openbao/meta/services.yml index 87ad4c60e1..1276055947 100644 --- a/roles/web-app-openbao/meta/services.yml +++ b/roles/web-app-openbao/meta/services.yml @@ -82,7 +82,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 diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index a013b28882..061fb9e12c 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -14,7 +14,7 @@ socialhome: placement: manager name: socialhome image: ghcr.io/social-home-io/socialhome - version: "2026.10.24" + version: "2026.10.27" ports: local: http: 8089 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 3dfed02727..e500abf9d3 100644 --- a/roles/web-app-stalwart/tasks/00_core.yml +++ b/roles/web-app-stalwart/tasks/00_core.yml @@ -86,7 +86,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 }}" diff --git a/roles/web-app-xwiki/meta/services.yml b/roles/web-app-xwiki/meta/services.yml index 0dbdd108b1..18b3bd42a1 100644 --- a/roles/web-app-xwiki/meta/services.yml +++ b/roles/web-app-xwiki/meta/services.yml @@ -59,7 +59,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 diff --git a/roles/web-svc-coturn/README.md b/roles/web-svc-coturn/README.md index efe665584b..b288f36ba2 100644 --- a/roles/web-svc-coturn/README.md +++ b/roles/web-svc-coturn/README.md @@ -39,6 +39,8 @@ Typical use cases: - 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 +- 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 ## Further Resources diff --git a/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 50d3813fa8..9879e110f5 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..ec0164ec1a 100644 --- a/roles/web-svc-coturn/templates/compose.yml.j2 +++ b/roles/web-svc-coturn/templates/compose.yml.j2 @@ -51,9 +51,15 @@ {% 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=100 + --total-quota={{ COTURN_TOTAL_QUOTA }} --stale-nonce --no-multicast-peers --no-cli @@ -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 7f6a3fc5b3..512e180643 100644 --- a/roles/web-svc-coturn/vars/main.yml +++ b/roles/web-svc-coturn/vars/main.yml @@ -6,11 +6,19 @@ 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') }}" 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 }}" 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..eec6d4835a --- /dev/null +++ b/tests/integration/roles/sys-svc-compose/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] 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/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/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() 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/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..9d3ddb3211 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -0,0 +1,283 @@ +from __future__ import annotations + +import itertools +import unittest +import unittest.mock as 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" +) + +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() 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..e69de29bb2 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()