diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index c051176c84..1df151b7c9 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -18,7 +18,7 @@ The `applications` lookup is the ONLY supported runtime entry point for merged a | `lookup('applications')` | Full merged mapping keyed by `application_id`. | | `lookup('applications', '')` | Merged entry for that application. Raises when missing. | | `lookup('applications', '', default_value)` | Merged entry, or `default_value` when the entry is missing. | -| `lookup('applications', carrier=True)` | `{"key": [...], "applications": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the constructor's carrier task (see below). | +| `lookup('applications', carrier=True)` | `{"key": [...], "applications": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the `applications_carrier` action (see below). | ## Data Sources πŸ“š @@ -33,9 +33,12 @@ No other source is consulted. Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). -The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY` or `SYSTEM_EMAIL_DOMAIN`). +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or a changed path or content of the tokens file). -- The task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. +- The stage-wide task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. +- The carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every persisted token in `roles/sys-token-store/tasks/write.yml`. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. +- The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. +- The tokens file enters the key as the SHA-256 of its content, memoised per inode, mtime and size, so a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. - The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. - User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which read the users cache fresh. - The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. diff --git a/docs/contributing/tools/agents/cheatsheet.md b/docs/contributing/tools/agents/cheatsheet.md index 9ebae273cd..1233c92a11 100644 --- a/docs/contributing/tools/agents/cheatsheet.md +++ b/docs/contributing/tools/agents/cheatsheet.md @@ -29,6 +29,7 @@ from its procedure file. Run `make install-skills` to (re)install them. | Cleaning up code, docs, or roles after a change | `i8-refactor` | | Checking a branch out into a parallel worktree | `i8-worktree-create` | | Releasing a parallel worktree and its slot | `i8-worktree-down` | +| Freeing disk space and `/tmp` that agents filled | `i8-cleanup` | | A GitHub Actions / CI run failed and needs triage | `triage` | | A local deploy is failing on the host | `i8-debug-local` | | Inspecting a `*.log` or `*job-logs.txt` file dropped in the workdir | `i8-debug-log` | diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index ce05759532..b57393630b 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -14,13 +14,18 @@ instead of rendering:: for the merge block, which it drops again at the block's end, one after the ``add_host`` tasks for the swarm bootstrap roles, parked only when ``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and the -tokens file's path, mtime and size, so a carrier whose groups or tokens no +tokens file's path and content digest, so a carrier whose groups or tokens no longer match is rejected and the reader renders afresh:: - name: 🧊 Drop the merge-block carrier so later stages re-render applications_carrier: clear: true +``tasks/utils/setup/role.yml`` parks one after every role, +``tasks/utils/load/app.yml`` one after every nested application load and +``roles/sys-token-store/tasks/write.yml`` one after every persisted token; +where the key still matches they serve the carried payload without rendering. + The result is masked by the action itself: the fact is the whole rendered tree, about 0.4 MB with every application's credentials, and printing it at ``-v`` is neither credential debugging nor readable. @@ -39,7 +44,7 @@ from ansible.module_utils.parsing.convert_bool import boolean from ansible.plugins.action import ActionBase from ansible.plugins.loader import lookup_loader -from utils.cache.carrier import APPLICATIONS_RENDERED_FACT +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, revalidate_tokens_file class ActionModule(ActionBase): @@ -64,10 +69,18 @@ class ActionModule(ActionBase): ) return result - lookup = lookup_loader.get( - "applications", loader=self._loader, templar=self._templar - ) - carrier = lookup.run([], variables=task_vars, carrier=True)[0] + revalidate_tokens_file(task_vars) + render_vars = dict(task_vars) + render_vars.pop("application_id", None) + previous = self._templar.available_variables + self._templar.available_variables = render_vars + try: + lookup = lookup_loader.get( + "applications", loader=self._loader, templar=self._templar + ) + carrier = lookup.run([], variables=render_vars, carrier=True)[0] + finally: + self._templar.available_variables = previous result.update( changed=False, diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index d8c4807895..94cc4f4124 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.5 + version: 0.40.6 name: ollama min_storage: 3473MB cpus: "4.0" diff --git a/roles/sys-ctl-hlth-journalctl/README.md b/roles/sys-ctl-hlth-journalctl/README.md index c60c77d27d..6f53fb6f81 100644 --- a/roles/sys-ctl-hlth-journalctl/README.md +++ b/roles/sys-ctl-hlth-journalctl/README.md @@ -2,11 +2,13 @@ ## Description -Scans `journalctl` over the last day for β€œerror” entries and alerts if any are found. +Scans `journalctl` over the last day for β€œerror” entries outside container logs and alerts if any are found. ## Overview This role searches the systemd journal for errors over the past day and alerts if any are found. +Container output is skipped, because every compose service logs to journald and application errors would otherwise trigger the host check. +Docker daemon and system errors are still reported. ## Cosmos @@ -23,8 +25,11 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Features -- Runs `journalctl --since '1 day ago' | grep -i error`. -- Exits non-zero on matches. +- Reads the last day of the journal as JSON with every field in full (`--all`) and drops every entry that carries a `CONTAINER_ID` field. +- Joins a repeated `MESSAGE` field into one line before matching. +- Matches the remaining messages case-insensitively against `error`. +- Prints one `source: message` line per match, naming the systemd unit or, without one, the syslog identifier, so alerts show who logged the error. +- Exits non-zero on matches, and also when `journalctl` itself fails, so a broken check never passes silently. - Scheduled via systemd timer. - Alerts via `sys-ctl-alm-compose` on detection. diff --git a/roles/sys-ctl-hlth-journalctl/files/python/script.py b/roles/sys-ctl-hlth-journalctl/files/python/script.py new file mode 100755 index 0000000000..75ddf4483b --- /dev/null +++ b/roles/sys-ctl-hlth-journalctl/files/python/script.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +import json +import subprocess +import sys +import tempfile + +JOURNALCTL = [ + "journalctl", + "--since", + "1 day ago", + "--no-pager", + "--all", + "--output=json", + "--output-fields=MESSAGE,CONTAINER_ID,SYSLOG_IDENTIFIER,_SYSTEMD_UNIT", +] + + +def message_text(value): + """Return a journal MESSAGE as one line of text. + + Args: + value: the MESSAGE field; journald encodes non-UTF-8 messages as a list of bytes and a repeated field as a list of its values. + + Returns: + The message with line breaks collapsed to spaces. + """ + if isinstance(value, list) and all(isinstance(item, int) for item in value): + value = bytes(value).decode("utf-8", errors="replace") + elif isinstance(value, list): + value = "\n".join(message_text(item) for item in value) + return " ".join(str(value).splitlines()) + + +def host_errors(lines): + """Yield `source: message` for every non-container entry that mentions an error. + + Args: + lines: iterable of journalctl JSON lines, one entry per line, consumed lazily. + + Returns: + Iterator of readable error lines. + """ + for line in lines: + if not line.strip(): + continue + entry = json.loads(line) + if "CONTAINER_ID" in entry: + continue + message = message_text(entry.get("MESSAGE", "")) + if "error" not in message.lower(): + continue + source = ( + entry.get("_SYSTEMD_UNIT") or entry.get("SYSLOG_IDENTIFIER") or "unknown" + ) + yield f"{source}: {message}" + + +def main(): + print("Checking journalctl for error messages outside container logs...") + with tempfile.TemporaryFile( + mode="w+", encoding="utf-8", errors="replace" + ) as stderr: + with subprocess.Popen( + JOURNALCTL, + stdout=subprocess.PIPE, + stderr=stderr, + encoding="utf-8", + errors="replace", + ) as journal: + errors = list(host_errors(journal.stdout)) + if journal.returncode != 0: + stderr.seek(0) + print( + f"journalctl failed with exit code {journal.returncode}: {stderr.read().strip()}" + ) + return 2 + if errors: + print("Some errors were found:") + print("\n".join(errors)) + return 1 + print("No errors found in the journal.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/sys-ctl-hlth-journalctl/files/shell/script.sh b/roles/sys-ctl-hlth-journalctl/files/shell/script.sh deleted file mode 100644 index 4903b597d1..0000000000 --- a/roles/sys-ctl-hlth-journalctl/files/shell/script.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -echo "Checking journalctl for error messages..." -journalctl_errors="$(journalctl --since '1 day ago' --no-pager | grep -i 'error')" -if [ -n "$journalctl_errors" ] -then - echo "Some errors where found: $journalctl_errors" - exit 1 -fi -echo "All docker containers are healthy." -exit 0 diff --git a/roles/sys-token-store/tasks/00_core.yml b/roles/sys-token-store/tasks/00_core.yml index 7f77bcb4c0..1d27b4468f 100644 --- a/roles/sys-token-store/tasks/00_core.yml +++ b/roles/sys-token-store/tasks/00_core.yml @@ -14,6 +14,8 @@ ansible.builtin.file: path: "{{ FILE_TOKENS }}" state: touch + modification_time: preserve + access_time: preserve owner: "{{ SYS_TOKEN_STORE_OWNER }}" group: "{{ SYS_TOKEN_STORE_GROUP }}" mode: "{{ SYS_TOKEN_STORE_FILE_MODE }}" diff --git a/roles/sys-token-store/tasks/write.yml b/roles/sys-token-store/tasks/write.yml index 51c6f5190f..6ee10926a5 100644 --- a/roles/sys-token-store/tasks/write.yml +++ b/roles/sys-token-store/tasks/write.yml @@ -51,6 +51,7 @@ run_once: true no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" become: true + register: sys_token_store_persisted - name: "πŸͺž Mirror the store onto the controller, where every users lookup reads" ansible.builtin.copy: @@ -63,3 +64,8 @@ delegate_to: localhost run_once: true no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: sys_token_store_mirrored + +- name: 🧊 Re-render the applications SPOT the new token invalidated + applications_carrier: {} + when: sys_token_store_persisted is changed or sys_token_store_mirrored is changed diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bd57ce9239..3bbedadcef 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -112,7 +112,7 @@ giteamcpupstream: enabled: "{{ lookup('config', 'web-app-gitea', 'mcp.enabled') | bool }}" shared: false image: docker.gitea.com/gitea-mcp-server - version: "1.8.1" + version: "1.9.0" update: type: registry_tags image: docker.gitea.com/gitea-mcp-server diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 9148ba0361..93642e25c6 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -66,7 +66,7 @@ synapse: element: healthcheck: flavor: wget - version: v1.12.31 + version: v1.12.32 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 e1899e35c4..bc243ea400 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "2.44.2" + version: "2.44.3" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index d7f917433f..8186d975af 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -13,7 +13,7 @@ socialhome: # nocheck: default-placement-manager embedded sqlite in a node-local volume; no clustered storage placement: manager image: ghcr.io/social-home-io/socialhome - version: "2026.10.14" + version: "2026.10.16" ports: local: http: 8089 diff --git a/roles/web-app-suitecrm/README.md b/roles/web-app-suitecrm/README.md index 8091a52906..a23cea4fa5 100644 --- a/roles/web-app-suitecrm/README.md +++ b/roles/web-app-suitecrm/README.md @@ -142,6 +142,14 @@ docker run --rm -it \ the Tor SOCKS proxy whenever the issuer is an onion, because a `.onion` issuer is unresolvable directly. `/auth` stays reachable as the local break-glass login. +- **Auto-created accounts** reach `User::save()` through SuiteCRM's own `CreateUser` + while the request is still anonymous. Since 8.10.2 that save answers + `RuntimeException: Not authorized` and forces `status = Inactive`, so + `files/patch/external-auth-user-create.patch` makes the stored system user the current + user around the save and restores the caller's afterwards. + [`files/Dockerfile`](./files/Dockerfile) applies it with `patch -F0` on the unpacked + release; the image build fails once the hunk stops matching. + ## Persona contract opt-outs [`templates/env.j2`](./templates/env.j2) seeds only the administrator into SuiteCRM (`SUITECRM_ADMIN_USERNAME` / `SUITECRM_ADMIN_PASSWORD`); `biber` reaches the app through SuiteCRM's own SAML login against Keycloak, where `SAML_AUTO_CREATE` mints the account on first assertion. In the `services.sso.enabled: false` matrix variants there is no SAML entry point and `biber` has no native account, so [`templates/playwright.env.j2`](./templates/playwright.env.j2) renders `PERSONA_BIBER_BLOCKED=true` for the generic persona journeys (the LDAP spec still signs `biber` in from the directory). The `administrator` persona keeps its native login via `ADMIN_NATIVE_PASSWORD` and runs in every variant. diff --git a/roles/web-app-suitecrm/files/Dockerfile b/roles/web-app-suitecrm/files/Dockerfile index 08c8f95e71..a2a6a6ec0e 100644 --- a/roles/web-app-suitecrm/files/Dockerfile +++ b/roles/web-app-suitecrm/files/Dockerfile @@ -19,6 +19,7 @@ RUN rm -rf /var/lib/apt/lists/* \ libonig-dev \ libxml2-dev \ libldap2-dev \ + patch \ && docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu \ && docker-php-ext-install \ pdo \ @@ -56,6 +57,8 @@ FROM base AS builder ARG SUITECRM_APP_VERSION ARG SUITECRM_APP_DIR ARG SUITECRM_LDAP_EXTENSION_DIR +ARG SUITECRM_EXTERNAL_AUTH_PATCH_HOST_REL +ARG SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER WORKDIR ${SUITECRM_APP_DIR} @@ -69,6 +72,11 @@ RUN set -eux; \ rm /tmp/suitecrm.tar.gz; \ chmod +x bin/console +COPY ${SUITECRM_EXTERNAL_AUTH_PATCH_HOST_REL} ${SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER} +RUN set -eux; \ + patch -p1 -F0 -i ${SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER}; \ + rm ${SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER} + RUN set -eux; \ composer install \ --prefer-dist \ diff --git a/roles/web-app-suitecrm/files/patch/external-auth-user-create.patch b/roles/web-app-suitecrm/files/patch/external-auth-user-create.patch new file mode 100644 index 0000000000..6f7275b53d --- /dev/null +++ b/roles/web-app-suitecrm/files/patch/external-auth-user-create.patch @@ -0,0 +1,69 @@ +SuiteCRM 8.10.2 tightened User::hasSaveAccess() from `return true` to +`return is_admin($current_user)` for a record without an id, and +restrictAdminOnlyFields() now forces `status = Inactive` on such a record +(release commit 6c7ce002a). CreateUser::create() runs while the browser is +still anonymous, because it is the LDAP and SAML auto-create path +(AppLdapUserProvider::createUser, AppSamlUserFactory::createUser, both via +UserHandler::createExternalAuthUser), so every first login of a directory +account ends in `RuntimeException: Not authorized`, HTTP 500 on POST /login +and no session after a SAML assertion. v8.10.1 and earlier exempted a new +record from both guards; upstream has no release and no hotfix carrying a fix. + +\CreateUser is reachable only from that provisioning stack and from the +installer, so the admin context is raised here instead of relaxing the guards, +which keeps them closed for every request-driven save. + +The raised context is the stored system user, never a fresh in-memory bean +carrying `is_admin = 1`. User::verify_data() compares `$this->id == +$current_user->id`, which is `'' == ''` between two unsaved beans, so a +deployment holding a single administrator takes the last-admin branch for the +very account it is creating. That branch reads the legacy `$mod_strings`, which +this request never loads, so an LDAP login ends in `ErrorException: Trying to +access array offset on value of type null` at modules/Users/User.php:1678 and +HTTP 500 on POST /login, while a SAML assertion redirects to +`index.php?action=Error&module=Users` and leaves no session. + +`$current_user` is assigned before `getSystemUser()` runs, not from its return +value. User::retrieve() calls loadPreferences() after it has filled the bean, +and both UserPreference::loadPreferences() and reloadPreferences() dereference +`$current_user->id` unguarded, so retrieving while the caller's anonymous +`$current_user` is still in place would raise `Attempt to read property "id" on +null` and answer HTTP 500 again. Assigning first makes the global the very bean +being filled, so those reads see an object throughout and the only session key +written is the system user's own. + +Generated with `diff -u` against the v8.10.2 tarball and applied with `-F0`, so +the build fails instead of letting GNU patch's default fuzz factor land the +hunk somewhere upstream moved it to. + +--- a/public/legacy/include/portability/User/CreateUser.php ++++ b/public/legacy/include/portability/User/CreateUser.php +@@ -68,6 +68,8 @@ + */ + public function create(string $name, array $fields): ?SugarBean + { ++ global $current_user; ++ + $user = BeanFactory::newBean('Users'); + $user->user_name = $name; + +@@ -77,7 +79,18 @@ + $user->$key = $value; + } + +- $user->save(); ++ $callerUser = $current_user; ++ ++ if (!is_admin($current_user)) { ++ $current_user = BeanFactory::newBean('Users'); ++ $current_user->getSystemUser(); ++ } ++ ++ try { ++ $user->save(); ++ } finally { ++ $current_user = $callerUser; ++ } + + if (empty($user)) { + return null; diff --git a/roles/web-app-suitecrm/meta/services.yml b/roles/web-app-suitecrm/meta/services.yml index 042eb5b315..af98ccff10 100644 --- a/roles/web-app-suitecrm/meta/services.yml +++ b/roles/web-app-suitecrm/meta/services.yml @@ -59,7 +59,7 @@ suitecrm: # nocheck: docker-version version: 8.2-apache custom: true - app_version: 8.9.1 + app_version: 8.10.2 phpredis_version: 6.3.0 update: - key: app_version diff --git a/roles/web-app-suitecrm/tasks/01_manager_ops.yml b/roles/web-app-suitecrm/tasks/01_manager_ops.yml index 373126537c..f0a6bc481a 100644 --- a/roles/web-app-suitecrm/tasks/01_manager_ops.yml +++ b/roles/web-app-suitecrm/tasks/01_manager_ops.yml @@ -30,6 +30,14 @@ - compose-up - compose-build +- name: "πŸš€ Deploy '{{ SUITECRM_EXTERNAL_AUTH_PATCH_HOST_ABS }}'" + copy: + src: "{{ SUITECRM_EXTERNAL_AUTH_PATCH_SRC }}" + dest: "{{ SUITECRM_EXTERNAL_AUTH_PATCH_HOST_ABS }}" + notify: + - compose-up + - compose-build + - name: "🐳 Docker Compose Up for '{{ application_id }}'" meta: flush_handlers diff --git a/roles/web-app-suitecrm/templates/compose.yml.j2 b/roles/web-app-suitecrm/templates/compose.yml.j2 index a4a9f433e8..2735bcb41b 100644 --- a/roles/web-app-suitecrm/templates/compose.yml.j2 +++ b/roles/web-app-suitecrm/templates/compose.yml.j2 @@ -9,6 +9,8 @@ SUITECRM_PHPREDIS_VERSION: "{{ SUITECRM_PHPREDIS_VERSION }}" SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL: "{{ SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL }}" SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER }}" + SUITECRM_EXTERNAL_AUTH_PATCH_HOST_REL: "{{ SUITECRM_EXTERNAL_AUTH_PATCH_HOST_REL }}" + SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER: "{{ SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER }}" SUITECRM_LDAP_EXTENSION_DIR: "{{ SUITECRM_LDAP_EXTENSION_DIR }}" SUITECRM_APP_DIR: "{{ SUITECRM_APP_DIR }}" SUITECRM_PHP_MEMORY_LIMIT: "{{ SUITECRM_PHP_MEMORY_LIMIT }}" diff --git a/roles/web-app-suitecrm/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index ec66f96ded..dbec4594ec 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -41,5 +41,11 @@ SUITECRM_ENTRYPOINT_SCRIPT_HOST_ABS: "{{ [ lookup('container', application_id, ' SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL: "volumes/{{ SUITECRM_ENTRYPOINT_SCRIPT_FILE }}" SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ [ '/usr/local/bin/', SUITECRM_ENTRYPOINT_SCRIPT_FILE ] | path_join }}" +SUITECRM_EXTERNAL_AUTH_PATCH_FILE: "external-auth-user-create.patch" +SUITECRM_EXTERNAL_AUTH_PATCH_SRC: "patch/{{ SUITECRM_EXTERNAL_AUTH_PATCH_FILE }}" +SUITECRM_EXTERNAL_AUTH_PATCH_HOST_ABS: "{{ [ lookup('container', application_id, 'directories.volumes'), SUITECRM_EXTERNAL_AUTH_PATCH_FILE ] | path_join }}" +SUITECRM_EXTERNAL_AUTH_PATCH_HOST_REL: "volumes/{{ SUITECRM_EXTERNAL_AUTH_PATCH_FILE }}" +SUITECRM_EXTERNAL_AUTH_PATCH_DOCKER: "{{ [ '/tmp/', SUITECRM_EXTERNAL_AUTH_PATCH_FILE ] | path_join }}" + SUITECRM_MAX_OLD_SPACE_SIZE: "{{ lookup('node_max_old_space_size', application_id, entity_name) }}" SUITECRM_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index a56aa4270f..3116fb74d6 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.7.0 +version: v0.7.1 update: monitored: true catalog: github-releases diff --git a/scripts/tests/deploy/ci/dns53-sampler.sh b/scripts/tests/deploy/ci/dns53-sampler.sh index c565215836..3d5bec1a37 100755 --- a/scripts/tests/deploy/ci/dns53-sampler.sh +++ b/scripts/tests/deploy/ci/dns53-sampler.sh @@ -20,15 +20,20 @@ zone_probe_name() { printf 'rescue-probe.%s' "${zone}" } +uptime_ms() { + read -r up _ /dev/null 2>&1; then verdict=ok else verdict=fail fi - printf ' %s=%s/%sms' "${name}" "${verdict}" "$(($(date -u '+%s%3N') - start))" + printf ' %s=%s/%sms' "${name}" "${verdict}" "$(($(uptime_ms) - start))" } [ "${DNS53_SAMPLER_LIB:-}" = "1" ] && return 0 diff --git a/skills/i8-cleanup/SKILL.md b/skills/i8-cleanup/SKILL.md new file mode 100644 index 0000000000..0fc2fb1c3b --- /dev/null +++ b/skills/i8-cleanup/SKILL.md @@ -0,0 +1,76 @@ +--- +name: i8-cleanup +description: > + Free the disk space and /tmp that agents filled on an Infinito.Nexus host: + run the portable `cleanup` skill and apply this repository's rules for + stacks, worktrees, images, shared caches and teardown targets on top of it. + Trigger on /i8-cleanup or when the operator asks to clean up after agents in + this repository. Infinito.Nexus specific. +--- + +Follow the instructions from AGENTS.md, then run the `cleanup` skill (installed +by `make install-skills`) and apply the rules below on top of it; where a rule +here is stricter, it wins. This skill never runs under the `robot` skill. + +## Attribution + +- **Stacks**: group containers, volumes and networks by their + `com.docker.compose.project` label and map each project to its worktree with + `git worktree list`. A stack consists of the DinD container, its `-coredns` + sidecar, the volumes `_docker` (the nested Docker of the whole + deployment), `_infinito`, `_letsencrypt`, the network + `_default` and the image `/debian:latest`. +- **Orphaned images**: a `/debian:latest` whose worktree no longer + exists has no owner. +- **Shared cache stack**, claimed by every session and never a candidate: + `infinito-registry-cache`, `infinito-package-cache`, + `infinito-package-cache-frontend`, `infinito-coredns`, the network + `infinito-nexus-core_default` and `/var/cache/infinito/core/cache`. +- **Act and swarm**: `local/act-runner-fixed:latest`, + `infinito-swarm-node:latest`, the volume `act-toolcache` and `~/.cache/act` + stay while any peer runs a swarm step or a roundtrip. +- **`infinito-i18n-libretranslate`**: model weights; downloading them again + needs an `allowed_domains` entry. High risk. +- **/tmp**: deploy and gate logs follow `/tmp/-.log`. A log whose name + contains a role name can be requirement evidence; it stays unless its + session releases it. Session scratch lives under + `/tmp/claude-///`. +- **Archive duties**: before deleting a scratchpad, grep the memory directory + for its name and for `archiv`. The designer generator dirs + (`scratchpad/cssmap/`) go to `refs/backup/designer/tools/` first. + +## Teardown and delete paths + +| Target | Command | Destroys | +| ------ | ------- | -------- | +| Stack of a worktree | `make -C compose-down` | containers and volumes including `_docker`; the next deploy needs `mode=initialize` | +| Stack, checkout and slot | `make worktree-down branch=` | as above plus the checkout; refuses uncommitted changes | +| One app inside a stack | `make -C compose-entity-purge apps=` | the app's containers, volumes and inventory group; the output must name `removed '' from inventory` | +| One swarm cluster | `make swarm-down name=` | its DinD nodes, lab network and act outer container | +| Every act-swarm leftover | `make swarm-clean` | all clusters including in-flight runs; only when no peer runs a swarm step | +| Container-owned files in a checkout | `make -C clean-container-owned` or `make -C compose-exec cmd='rm -rf '` | the named paths | +| The dev container's own `/tmp` (tmpfs) | `make compose-exec cmd='df -h /tmp'`, then `make compose-exec cmd='rm -rf /tmp/playwright-transform-cache-0'` | the Playwright transform cache | + +- Run `compose-down`, `compose-entity-purge` and `worktree-down` for another + worktree with the inherited `INFINITO_*` variables stripped: + `env $(printenv | grep -o -E '^INFINITO_[A-Z0-9_]+' | sed 's/^/-u /') make ...`. +- A worktree that ran a container gate keeps container-owned files: remove + them from inside it with `make compose-exec` before `make worktree-down`. +- After removing `/debian` images, offer + `docker builder prune --filter until=24h`; their layers stay in the build + cache until then. +- When the classifier refuses a purge or teardown, report the exact `make` + command to the operator. + +## Never + +- `make system-purge`: runs `docker compose down --volumes` and + `docker system prune -a --volumes` across every stack. +- `make clean-cache`: wipes `/var/cache/infinito/core/cache` and stops the + cache containers every deploy builds through. +- `make worktree-prune` as a cleanup step: it also drops detached-HEAD + registrations whose commits may be reachable only through them. + +Begin by clarifying every open requirement with the `active-listening` skill. +The task is finished when the `cleanup` report shows the before and after sizes +and every peer that answered has been told what was removed near its items. diff --git a/tasks/utils/load/app.yml b/tasks/utils/load/app.yml index abf1e21cb4..818b4d6278 100644 --- a/tasks/utils/load/app.yml +++ b/tasks/utils/load/app.yml @@ -15,3 +15,6 @@ domain: "{{ lookup('domain', load_app_id) }}" when: - groups[load_app_id] is not defined or inventory_hostname in groups[load_app_id] + +- name: "🧊 Carry the applications SPOT past nested {{ load_app_id }}" + applications_carrier: {} diff --git a/tasks/utils/setup/role.yml b/tasks/utils/setup/role.yml index b618b6195d..34b31c5fb2 100644 --- a/tasks/utils/setup/role.yml +++ b/tasks/utils/setup/role.yml @@ -6,3 +6,6 @@ - name: "🚿 flush handlers after {{ role_entry.app }}" ansible.builtin.meta: flush_handlers + +- name: "🧊 Carry the applications SPOT past {{ role_entry.app }}" + applications_carrier: {} diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index 841b2eea44..4e0c8d213e 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -12,21 +12,30 @@ class _FakeTask: self.args = {} if args is None else dict(args) +class _FakeTemplar: + def __init__(self, available_variables=None): + self.available_variables = available_variables + + class _FakeLookup: - def __init__(self, carrier): + def __init__(self, carrier, templar=None): self.carrier = carrier + self.templar = templar self.calls = [] + self.templar_variables = [] def run(self, terms, variables=None, **kwargs): self.calls.append((terms, variables, kwargs)) + if self.templar is not None: + self.templar_variables.append(dict(self.templar.available_variables)) return [self.carrier] -def _make_action(task: _FakeTask) -> ActionModule: +def _make_action(task: _FakeTask, templar=None) -> ActionModule: action = object.__new__(ActionModule) action._task = task action._loader = None - action._templar = None + action._templar = _FakeTemplar() if templar is None else templar return action @@ -56,6 +65,73 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): self.assertEqual(variables, {"applications": {}}) self.assertTrue(kwargs["carrier"]) + def test_renders_without_the_callers_application_id(self): + task_vars = {"applications": {}, "application_id": "web-app-bluesky"} + templar = _FakeTemplar(task_vars) + lookup = _FakeLookup({"key": ["roles", []], "applications": {}}, templar) + action = _make_action(_FakeTask(), templar) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + return_value=lookup, + ), + patch("plugins.action.applications_carrier.revalidate_tokens_file"), + ): + action.run(task_vars=task_vars) + + _, variables, _ = lookup.calls[0] + self.assertEqual(variables, {"applications": {}}) + self.assertEqual(lookup.templar_variables, [{"applications": {}}]) + self.assertIs(templar.available_variables, task_vars) + self.assertEqual(task_vars["application_id"], "web-app-bluesky") + + def test_revalidates_the_tokens_file_before_rendering(self): + order = [] + lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) + lookup.run = lambda *args, **kwargs: order.append("render") or [{}] + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + return_value=lookup, + ), + patch( + "plugins.action.applications_carrier.revalidate_tokens_file", + side_effect=lambda variables: order.append(("revalidate", variables)), + ), + ): + action.run(task_vars={"FILE_TOKENS": "/x/tokens.yml"}) + + self.assertEqual( + order, [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "render"] + ) + + def test_clear_does_not_revalidate(self): + action = _make_action(_FakeTask(args={"clear": True})) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.revalidate_tokens_file" + ) as revalidate, + ): + action.run(task_vars={}) + + revalidate.assert_not_called() + def test_rejects_arguments(self): action = _make_action(_FakeTask(args={"foo": 1})) with ( diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py new file mode 100644 index 0000000000..8a4f44007f --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py @@ -0,0 +1,147 @@ +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "roles/sys-ctl-hlth-journalctl/files/python/script.py" + +JOURNALCTL_STUB = """#!/usr/bin/env bash +printf '%s\\n' "$*" >"${STUB_DIR}/args" +cat "${STUB_DIR}/journal" +if [ "${STUB_RC}" -ne 0 ]; then +\techo "journalctl: unrecognized option '--output-fields'" >&2 +fi +exit "${STUB_RC}" +""" + +APP_ERROR = { + "MESSAGE": "ERROR: pixelfed queue failed", + "CONTAINER_ID": "0123456789ab", + "SYSLOG_IDENTIFIER": "pixelfed", + "_SYSTEMD_UNIT": "docker.service", +} +DAEMON_ERROR = { + "MESSAGE": 'level=error msg="failed to start container"', + "SYSLOG_IDENTIFIER": "dockerd", + "_SYSTEMD_UNIT": "docker.service", +} +KERNEL_ERROR = {"MESSAGE": "EXT4-fs error (device sda1)", "SYSLOG_IDENTIFIER": "kernel"} +BINARY_ERROR = { + "MESSAGE": list(b"I/O error \xff on disk"), + "_SYSTEMD_UNIT": "smartd.service", +} +REPEATED_ERROR = { + "MESSAGE": ["unit started", list(b"disk error \xff on sdb")], + "_SYSTEMD_UNIT": "zfs-import.service", +} +SYSTEM_INFO = { + "MESSAGE": "Started Daily apt download activities.", + "_SYSTEMD_UNIT": "init.scope", +} + + +class TestHlthJournalctlScript(unittest.TestCase): + def run_script(self, *entries, rc=0): + """Run the health script against a stubbed journalctl. + + Args: + entries: journal entries the stub prints, one JSON object per line. + rc: exit code of the stubbed journalctl. + + Returns: + Tuple of the exit code, the script output, and the journalctl arguments. + """ + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) + stub = bin_dir / "journalctl" + stub.write_text(JOURNALCTL_STUB) + stub.chmod(0o755) + (bin_dir / "journal").write_text( + "".join(json.dumps(entry) + "\n" for entry in entries) + ) + env = dict(os.environ) + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["STUB_DIR"] = tmp + env["STUB_RC"] = str(rc) + done = subprocess.run( + [sys.executable, str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=False, + ) + args = (bin_dir / "args").read_text() # nocheck: cache-read tempdir fixture + return done.returncode, done.stdout, args + + def test_reads_the_journal_as_json_with_the_source_fields(self): + _, _, args = self.run_script(SYSTEM_INFO) + self.assertIn("--output=json", args) + self.assertIn( + "--output-fields=MESSAGE,CONTAINER_ID,SYSLOG_IDENTIFIER,_SYSTEMD_UNIT", + args, + ) + + def test_reads_every_field_in_full(self): + _, _, args = self.run_script(SYSTEM_INFO) + self.assertIn("--all", args.split()) + + def test_a_repeated_message_field_is_joined_and_reported(self): + code, output, _ = self.run_script(REPEATED_ERROR, DAEMON_ERROR) + self.assertEqual(code, 1) + self.assertIn("zfs-import.service: unit started disk error", output) + self.assertIn('docker.service: level=error msg="failed to start', output) + + def test_an_application_error_from_a_container_is_ignored(self): + code, _, _ = self.run_script(APP_ERROR, SYSTEM_INFO) + self.assertEqual(code, 0) + + def test_a_docker_daemon_error_is_reported_with_its_unit(self): + code, output, _ = self.run_script(APP_ERROR, DAEMON_ERROR) + self.assertEqual(code, 1) + self.assertIn( + 'docker.service: level=error msg="failed to start container"', output + ) + self.assertNotIn("pixelfed queue failed", output) + + def test_an_entry_without_unit_is_named_by_its_identifier(self): + code, output, _ = self.run_script(KERNEL_ERROR) + self.assertEqual(code, 1) + self.assertIn("kernel: EXT4-fs error (device sda1)", output) + + def test_a_non_utf8_message_is_decoded_and_reported(self): + code, output, _ = self.run_script(BINARY_ERROR) + self.assertEqual(code, 1) + self.assertIn("smartd.service: I/O error", output) + + def test_many_container_errors_are_streamed_past_and_not_reported(self): + container_lines = [ + {**APP_ERROR, "MESSAGE": f"ERROR: pixelfed request {n} failed"} + for n in range(20000) + ] + code, output, _ = self.run_script(*container_lines, DAEMON_ERROR) + self.assertEqual(code, 1) + self.assertNotIn("pixelfed request", output) + self.assertEqual( + output.splitlines()[-1], + 'docker.service: level=error msg="failed to start container"', + ) + self.assertEqual(len(output.splitlines()), 3) + + def test_a_journal_without_errors_passes(self): + code, _, _ = self.run_script(SYSTEM_INFO) + self.assertEqual(code, 0) + + def test_a_failing_journalctl_fails_the_check(self): + code, output, _ = self.run_script(rc=1) + self.assertEqual(code, 2) + self.assertIn("journalctl failed with exit code 1", output) + self.assertIn("unrecognized option '--output-fields'", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py b/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py index d8ca33dc49..0c37be6f81 100644 --- a/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py +++ b/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py @@ -8,6 +8,7 @@ clients whose remote end is :53, other ports, or the embedded Docker DNS. from __future__ import annotations +import os import subprocess import tempfile import unittest @@ -59,7 +60,7 @@ class SamplerTickTests(unittest.TestCase): class AnswerProbeTests(unittest.TestCase): - def _answer(self, name: str) -> str: + def _answer(self, name: str, env: dict[str, str] | None = None) -> str: proc = subprocess.run( [ "sh", @@ -72,12 +73,23 @@ class AnswerProbeTests(unittest.TestCase): capture_output=True, text=True, check=True, + env=env, ) return proc.stdout def test_a_resolvable_name_is_reported_ok_with_its_latency(self): self.assertRegex(self._answer("localhost"), r"^ localhost=ok/\d+ms$") + def test_the_latency_does_not_depend_on_the_date_implementation(self): + with tempfile.TemporaryDirectory() as stub_dir: + stub = Path(stub_dir) / "date" + stub.write_text("#!/bin/sh\necho 1792150731%3N\n", encoding="utf-8") + stub.chmod(0o755) + env = {**os.environ, "PATH": f"{stub_dir}{os.pathsep}{os.environ['PATH']}"} + self.assertRegex( + self._answer("localhost", env=env), r"^ localhost=ok/\d+ms$" + ) + def test_an_unresolvable_name_is_reported_fail_not_skipped(self): self.assertRegex( self._answer("rescue-probe.invalid"), diff --git a/tests/unit/python/utils/cache/test_base.py b/tests/unit/python/utils/cache/test_base.py index 044cd168e9..657fbbd12d 100644 --- a/tests/unit/python/utils/cache/test_base.py +++ b/tests/unit/python/utils/cache/test_base.py @@ -10,9 +10,11 @@ files; this file pins the contract of base itself. from __future__ import annotations +import os import tempfile import textwrap import unittest +import unittest.mock as mock from pathlib import Path from utils.cache import _reset_cache_for_tests, base @@ -153,11 +155,13 @@ class TestStableVariablesSignature(unittest.TestCase): class TestTokensFileSignature(unittest.TestCase): - def test_missing_file_returns_zeroed_signature(self): + def setUp(self): + base._reset() + + def test_missing_file_returns_an_empty_digest(self): with tempfile.TemporaryDirectory() as tmp: - sig = base._tokens_file_signature(Path(tmp) / "absent.yml") - self.assertEqual(sig[1], 0) - self.assertEqual(sig[2], 0) + path = Path(tmp) / "absent.yml" + self.assertEqual(base._tokens_file_signature(path), (str(path), "")) def test_signature_changes_when_file_changes(self): with tempfile.TemporaryDirectory() as tmp: @@ -168,6 +172,37 @@ class TestTokensFileSignature(unittest.TestCase): sig_after = base._tokens_file_signature(path) self.assertNotEqual(sig_before, sig_after) + def test_a_touch_keeps_the_signature(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tokens.yml" + path.write_text("a: 1\n", encoding="utf-8") + sig_before = base._tokens_file_signature(path) + later = path.stat().st_mtime_ns + 5_000_000_000 + os.utime(path, ns=(later, later)) + self.assertEqual(base._tokens_file_signature(path), sig_before) + + def test_an_unchanged_stat_serves_the_digest_without_reading(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tokens.yml" + path.write_text("a: 1\n", encoding="utf-8") + sig_before = base._tokens_file_signature(path) + with mock.patch.object(Path, "open", side_effect=AssertionError): + self.assertEqual(base._tokens_file_signature(path), sig_before) + + +class TestRevalidateTokensFile(unittest.TestCase): + def test_opens_the_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tokens.yml" + path.write_text("a: 1\n", encoding="utf-8") + with mock.patch.object(Path, "open", wraps=path.open) as opened: + base._revalidate_tokens_file(path) + opened.assert_called_once_with("rb") + + def test_a_missing_file_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + base._revalidate_tokens_file(Path(tmp) / "absent.yml") + class TestRenderWithTemplar(unittest.TestCase): """`_render_with_templar` is the single ansible-coupled symbol in diff --git a/utils/cache/README.md b/utils/cache/README.md index a4d0080e34..d602b889cd 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -26,7 +26,7 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. -Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked once by the constructor stage) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. ## Test-Only Helpers πŸ§ͺ diff --git a/utils/cache/base.py b/utils/cache/base.py index f9c2d23276..27510d8941 100644 --- a/utils/cache/base.py +++ b/utils/cache/base.py @@ -16,10 +16,12 @@ only when actually invoked. from __future__ import annotations import copy +import hashlib +import os import threading from collections.abc import Mapping from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import Any from plugins.filter.merge.with_defaults import ( merge_with_defaults, # noqa: F401 re-exported @@ -28,8 +30,7 @@ from utils.paths import FILE_TOKENS from . import PROJECT_ROOT, ROLES_DIR # noqa: F401 -if TYPE_CHECKING: - import os +_TOKENS_DIGESTS: dict[tuple, str] = {} try: from ansible.parsing.vault import EncryptedString as _AnsibleEncryptedString @@ -125,18 +126,46 @@ def _stable_variables_signature(variables: Mapping[str, Any] | None) -> tuple: ) -def _tokens_file_signature(path: Path) -> tuple: - """Return a cheap stat-based signature for the tokens file. +def _stat_identity(st: os.stat_result) -> tuple: + return (st.st_ino, st.st_mtime_ns, st.st_size) - The merged-users cache must invalidate whenever sys-token-store persists a - new token β€” otherwise downstream `lookup('users', ...)` returns stale tokens - within the same play. stat() is cheap and captures in-place writes. + +def _tokens_file_signature(path: Path) -> tuple: + """Return ``(path, sha256 of the content)`` for the tokens file. + + Args: + path: the tokens file. + + Returns: + ``(str(path), "")`` when the file cannot be read. """ try: - st = path.stat() - except (FileNotFoundError, OSError): - return (str(path), 0, 0) - return (str(path), st.st_mtime_ns, st.st_size) + identity = (str(path), *_stat_identity(path.stat())) + except OSError: + return (str(path), "") + digest = _TOKENS_DIGESTS.get(identity) + if digest is None: + try: + with path.open("rb") as handle: + identity = (str(path), *_stat_identity(os.fstat(handle.fileno()))) + digest = hashlib.sha256(handle.read()).hexdigest() + except OSError: + return (str(path), "") + _TOKENS_DIGESTS[identity] = digest + return (str(path), digest) + + +def _revalidate_tokens_file(path: Path) -> None: + """Open and close the tokens file so an NFS client refreshes its attributes. + + Args: + path: the tokens file. + """ + try: + with path.open("rb"): + pass + except OSError: + return def _deep_merge(base: Any, override: Any) -> Any: @@ -287,5 +316,5 @@ def _render_with_templar( def _reset() -> None: - """No-op kept so the `data._reset_cache_for_tests` facade can call every - domain module uniformly. This module owns no cache.""" + """Clear the tokens-file digest memo.""" + _TOKENS_DIGESTS.clear() diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index dfda350ae4..aafed31415 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Any from .base import ( _cache_key, _resolve_roles_dir, + _revalidate_tokens_file, _stable_variables_signature, _tokens_file_signature, ) @@ -42,7 +43,7 @@ def merged_applications_cache_key( Returns: ``(resolved roles dir, stable variables signature extended by the - tokens file's path, mtime and size)``. + tokens file's path and content digest)``. """ from .users import _resolve_tokens_file @@ -53,6 +54,17 @@ def merged_applications_cache_key( ) +def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: + """Refresh an NFS client's attributes of the tokens file before a carrier is keyed. + + Args: + variables: The play's variable scope the tokens file resolves from. + """ + from .users import _resolve_tokens_file + + _revalidate_tokens_file(_resolve_tokens_file(variables)) + + def _carried_applications( variables: Mapping[str, Any], cache_key: tuple[str, tuple] ) -> dict[str, Any] | None: