diff --git a/.claude/settings.json b/.claude/settings.json index 49edc61332..8727119dd9 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -157,6 +157,7 @@ "WebFetch(domain:download-center.epson.com)", "WebFetch(domain:download.ebz.epson.net)", "WebFetch(domain:download.ebz.epson.net)", + "WebFetch(domain:download.fedoraproject.org)", "WebFetch(domain:download.rockylinux.org)", "WebFetch(domain:dyn.manpages.debian.org)", "WebFetch(domain:element.io)", @@ -186,7 +187,10 @@ "WebFetch(domain:framatube.org)", "WebFetch(domain:frappe.io)", "WebFetch(domain:frappeframework.com)", + "WebFetch(domain:ftp-stud.hs-esslingen.de)", "WebFetch(domain:ftp.debian.org)", + "WebFetch(domain:ftp.uni-stuttgart.de)", + "WebFetch(domain:ftp2.osuosl.org)", "WebFetch(domain:fvonline-db.bplaced.net)", "WebFetch(domain:gcc.gnu.org)", "WebFetch(domain:geminicli.com)", @@ -251,8 +255,11 @@ "WebFetch(domain:memcached.org)", "WebFetch(domain:meta.discourse.org)", "WebFetch(domain:micro-editor.github.io)", + "WebFetch(domain:mirror.dogado.de)", "WebFetch(domain:mirror.manjaro.org)", + "WebFetch(domain:mirror.netzwerge.de)", "WebFetch(domain:mirror.stream.centos.org)", + "WebFetch(domain:mirrors.xtom.de)", "WebFetch(domain:mobilizon.org)", "WebFetch(domain:moodle.org)", "WebFetch(domain:moodledev.io)", diff --git a/.dockerignore b/.dockerignore index de4f7e28df..16bbaa26aa 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,6 +3,9 @@ # NEVER TOUCH THE .dockerignore, BECAUSE IT ANYHOW WILL BE OVERWRITTEN site.retry +.cache +.ansible/ +.stack-torn-down *__pycache__ compose.cache.override.yml venv @@ -20,12 +23,16 @@ build/* .claude-* collections/ .env +.onion-identity/ custom.env logs/ job-logs.txt *.lock node_modules/ +vendor/ +.phpunit.result.cache inventories/production/ +/core.* # No-op for Git (ignored implicitly), but Docker needs .git in its ignore-list — keeps make dockerignore as a pure cat of this file. .git diff --git a/.github/PULL_REQUEST_TEMPLATE/server.md b/.github/PULL_REQUEST_TEMPLATE/server.md index 6828cb6f45..58d5de3579 100644 --- a/.github/PULL_REQUEST_TEMPLATE/server.md +++ b/.github/PULL_REQUEST_TEMPLATE/server.md @@ -88,7 +88,7 @@ Check the relevant rows and explain intentional omissions in `Additional Notes`. | [ ] | `meta/server.yml` | Usually | Server-level config (file root IS `applications..server`). CSP, `domains`, `status_codes`, plus the per-role `networks.local.{subnet,dns_resolver}`. | | [ ] | `meta/rbac.yml` | When the role declares RBAC | RBAC declarations (file root IS `applications..rbac`). | | [ ] | `meta/volumes.yml` | When the role declares Compose volumes | Volumes map (file root IS the volumes map; no `compose:`/`volumes:` wrapper). | -| [ ] | `meta/schema.yml` | When the role declares credentials | Credential schema with optional `default:` field. | +| [ ] | `meta/secrets.yml` | When the role declares credentials | Credential schema with optional `default:` field. | | [ ] | `tasks/main.yml` | Usually | Acts as the role entry point and includes the main task flow. | | [ ] | `templates/compose.yml.j2` | For containerized app roles | Defines the service, volume, environment, port, and network wiring. | | [ ] | `templates/env.j2` | When the app uses environment files | Renders the app environment configuration. | diff --git a/.github/workflows/README.md b/.github/workflows/README.md index cb214ffeb7..1c013893f4 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -28,32 +28,21 @@ flowchart TB codeql["cron-security-codeql.yml"] buildci["build-ci-images: images-build-ci.yml"] --> dns["test-dns.yml"] mirror["images-mirror-missing.yml"] - seq["sequencing: serial or parallel, per line"] - subgraph prio["priority line, skipped without a priority input"] - swarmprio["test-deploy-swarm-priority"] - swarmprio -->|"serial"| composeprio["test-deploy-compose-priority"] - composeprio -->|"serial"| hostprio["test-deploy-host-priority"] - snprio["test-deploy-single-node-priority: parallel"] + subgraph chain["serial chunk chain"] + chunk0["test-deploy-chunk-0"] + chunk0 --> chunk1["test-deploy-chunk-1"] + chunk1 --> chunk2["test-deploy-chunk-2"] end - subgraph reg["regular line"] - swarmreg["test-deploy-swarm"] - swarmreg -->|"serial"| composereg["test-deploy-compose"] - composereg -->|"serial"| hostreg["test-deploy-host"] - snreg["test-deploy-single-node: parallel"] - end + lintwf --> chain + testwf --> chain + dns --> chain + mirror --> chain + buildci --> chain - lintwf --> prio - testwf --> prio - dns --> prio - mirror --> prio - seq --> prio - prio -->|"all priority jobs green"| reg - - swarmreg --> smoke["test-runner-smoke.yml"] - prio --> report["report-main-failures"] - reg --> report + chunk0 --> smoke["test-runner-smoke.yml"] + chain --> report["report-main-failures"] instmake["test-install-make.yml"] instpkgmgr["test-install-pkgmgr.yml"] @@ -61,9 +50,7 @@ flowchart TB buildci --> testguide["test-instructions.yml"] mirror --> testguide - prio --> donegate["done"] - reg --> donegate - seq --> donegate + chain --> donegate["done"] smoke --> donegate instmake --> donegate instpkgmgr --> donegate @@ -71,111 +58,207 @@ flowchart TB testguide --> donegate end - snprio --> singlenode["test-deploy-single-node.yml"] - snreg --> singlenode - singlenode --> deploycompose["test-deploy-compose.yml"] - singlenode --> deployhost["test-deploy-host.yml"] - composeprio --> deploycompose - composereg --> deploycompose - hostprio --> deployhost - hostreg --> deployhost - swarmprio --> deployswarm["test-deploy-swarm.yml"] - swarmreg --> deployswarm + chunk0 --> deploy["call-test-deploy.yml"] + chunk1 --> deploy + chunk2 --> deploy ``` -The priority line runs only when the orchestrator's `priority` input is set; -with it empty every priority job is skipped and the regular line starts -directly. The regular jobs receive the priority ids as `blacklist`, so each -role deploys in exactly one line. +## Sweeps and chunks -## Deploy-line sequencing +A **sweep** is one orchestrator run. It builds a single ordered list of +`role#variant` rows, assigns each row a deploy mode and a tor state, and +deploys the list in serial **chunk** blocks. -A **line** is one half of a run: the priority line (`⭐`, the roles named in -`priority`) or the regular line (`🔁`, everything else). Each line deploys up -to three **modes**: swarm, compose, host. The lines are always sequential -relative to each other; this section is about the order *inside* one line. - -### Why the order exists +### Why chunks exist GitHub cancels a job that has sat queued for 24 hours. That clock starts when the job is queued, not when the run starts, and a `needs:` edge delays queueing -until the dependency completes. A line that starts all three modes at once -queues its whole matrix in one go, so with more roles than runner slots the -tail of that matrix waits past the cut and dies unrun. Deploying the modes one -after the other restarts the clock per mode. +until the dependency completes. A run that queues its whole matrix at once +leaves the tail waiting past the cut, where it dies unrun. Deploying in chunks +chained on `needs:` restarts the clock per chunk. -Serialising costs wall-clock, so it is only worth it above a certain size. The -run does not pay it on a small diff. +The chunk size is what makes that safe, and `cli.meta.ci.slots` derives it +rather than pinning it: -### The decision +```text +waves = floor(INFINITO_CI_QUEUE_HOURS / the deploy job's timeout-minutes) +chunk size = INFINITO_CI_CONCURRENCY * waves +``` -The `sequencing` job resolves the effective whitelist (the same -`scripts/github/resolve/effective_whitelist.sh` the discover steps use) and -calls `cli.meta.ci.sequencing` once per line, emitting `serial` or `parallel` -as a job output. +Assuming every job burns its full timeout is deliberately pessimistic — no job +can outlast it — so the estimate can only overshoot the real drain time. With +the current constants that is 4 waves of 20 runners, so 80 rows per chunk, and +the last job of a chunk starts around t=18h, well inside the 24h window. -Job counts are taken on the row basis each mode actually runs on: swarm -selections are `role#variant` tokens that map 1:1 onto jobs, compose and host -selections are whole roles whose variants pack into bundles -(`utils.github.variant.bundles`). The count deliberately omits the -runner-storage filter that `scripts/meta/resolve/apps.sh` applies inside -GitHub Actions, so it can only overestimate — erring towards the sequential -layout, which cannot be cancelled. +### How many chunks a sweep spends -| `sequencing` input | Behaviour | +The run's 256-job cap is the second ceiling. `slots` counts every non-deploy +job the orchestrator chain spawns, subtracts the worst `entry-*.yml` overhead, +and what remains is `available` — the rows one sweep may deploy across all its +chunks. Rows beyond that roll into the next sweep, which starts reading the +regular line at an offset (`cli.meta.ci.chunks`), so consecutive sweeps walk +the whole list instead of re-testing the same head forever. + +GitHub Actions cannot generate a variable number of jobs, so the chunk blocks +are written out in the orchestrator. `INFINITO_CI_MAX_CHUNKS` must equal how +many exist there — `slots` plans a sweep against that key, and a sweep planned +larger than the chain silently drops its tail. Blocks whose slice comes back +empty skip themselves and cost nothing. + +Run `python -m cli.meta.ci.slots --matrix` to see the whole budget. + +### Priority + +`priority` names the roles that lead. They sort to the head of the list and the +split forces a chunk boundary at the priority/regular seam, so a chunk is +either all priority or all regular — the seam chunk stays short rather than +being topped up. That is what guarantees every priority row is deployed before +the first regular one starts. Priority rows wear a trailing `⭐` in their job +name and never move with the sweep offset. + +They are also the rows a run must not sample. A priority row is deployed in +**every combination it can take** — each variant, in each mode its role offers, +and on the modes that carry the onion axis once behind Tor and once on +clearnet — all within the same sweep. A 3-variant role offering compose and +swarm therefore becomes 3 × 2 × 2 = **12 jobs**, not 3. That is the point of +naming a role in `priority`: it is proven everywhere at once instead of over +four sweeps. + +An explicit `tor` input still wins over the full coverage: `enforced`, +`exclusive` and `disabled` are operator narrowings, and a variant that pins +`services.tor.enabled` to false never gets an onion run regardless. + +### Selection tokens + +An entry in `whitelist` or `priority` is a role name that MAY pin the axes the +row would otherwise be assigned. Two spellings are accepted: + +| Form | Example | |---|---| -| `auto` (default) | `serial` above `INFINITO_CI_SEQUENTIAL_THRESHOLD` jobs in that line, `parallel` at or below it | -| `serial` | forced; skips the count entirely | -| `parallel` | forced; skips the count entirely | +| ASCII | `web-app-nextcloud#0,2@swarm+tor%debian/zfs` | +| the job label, pasted back out of the failed run | `🐳🧅🌀🦓网络应用·Nextcloud#0` | -The threshold lives in [`default.env`](../../default.env) as -`INFINITO_CI_SEQUENTIAL_THRESHOLD`. Both lines are decided independently: a -small priority line can run parallel while the regular line behind it runs -serial. +| Separator | Axis | Values | +|---|---|---| +| `#` | variants | comma-separated indices | +| `@` | deploy mode | `compose`, `swarm`, `host` | +| `+` | onion state | `tor`, `clearnet` | +| `%` | distro | `arch`, `debian`, `ubuntu`, `fedora`, `centos` | +| `/` | filesystem | `zfs`, `btrfs`, `ext4` | -### The two layouts +The onion state is spelled `+clearnet` rather than `-tor` because a role id may +itself end in `-tor`. -Serial order is **swarm, then compose, then host** — heaviest mode first, so -the longest queue drains while the run is youngest. +What a token leaves open belongs to the line it stands in: `priority` covers +every remaining combination in one sweep, `whitelist` keeps the rotation and +the row's position in the matrix. A pin the row cannot take aborts the matrix +rather than dropping the row, because a dropped row would report a green run +for a combination that never ran. Such a pin is `@swarm` on a role without its +own stack, `+tor` on a variant that pins `services.tor.enabled` false, or any +axis that fights the run's own `mode`, `tor`, `distros` or `filesystem` input. -- **parallel** — `test-deploy-swarm-priority` plus - `test-deploy-single-node-priority`, which fans compose and host out - together. This is the layout the pipeline had before sequencing existed. -- **serial** — `test-deploy-swarm-priority` → - `test-deploy-compose-priority` → `test-deploy-host-priority`, each chained - on the previous through `needs:`. +That is also what a retrigger replays: `--failed` reads the glyphs off the failed +job's title and writes them back as a token, so the row comes back in the mode, +onion state and distribution it died on rather than on whatever the rotation +would pick next. The filesystem is deliberately left out. A title states the +kind the matrix *assigned*, which a deploy is allowed to fall back from, so +pinning it would both misstate what the job ran on and turn the kind into a +demand, failing the retrigger on the very condition the fallback absorbs. -The regular line mirrors this with the unsuffixed job names. +### Mode, tor, distro and filesystem -A `needs:` edge is static, so a workflow cannot make one conditional. Both -layouts therefore exist as separate jobs and the `sequencing` output skips -one of them. Because a skipped dependency otherwise skips its dependents, the -serial jobs carry `always()` plus explicit `needs..result` checks on the -real gates. The swarm job depends on no sequencing decision at all: it leads -in either layout. +The `tor` input decides what the onion axis is allowed to do at all: + +| Value | Effect | +|---|---| +| `auto` | rotates; a priority row covers both states in one sweep | +| `enforced` | every capable row runs behind the onion | +| `exclusive` | as `enforced`, and rows that cannot take an onion are dropped | +| `disabled` | no row takes the onion | + +`distros` and `filesystem` narrow the pools the other two axes draw from. Both +default to empty, which means the whole declared set. That is what a sweep +wants, because the rows are spread over the pool rather than all sharing one +value. Narrowing is for chasing a single distribution or a single filesystem. + +Whether the assigned filesystem is binding depends on who chose it: + +| How the row got its kind | The kind is | A host that cannot serve it | +|---|---|---| +| the rotation, from a pool of two or more (every automatic run) | a preference | falls back inside the pool, and says so in the step summary | +| the rotation, from a pool of exactly one (`filesystem: zfs`) | a demand | fails the row | +| a selection token (`role#0/zfs`) | a demand | fails the row | + +A pool of two or more stays a preference because the matrix already narrowed +each row to one kind out of it: falling back to the other kind the run allowed +is inside what the operator asked for, while failing the row is not. A run whose +whole pool is unservable fails rather than leaving the pool. + +The narrow case is what a deploy job actually sees, because the matrix hands +every row exactly one kind. Reading that narrowness as a demand would turn every +condition the applying step tolerates into a red row on every deploy: a loop +device it could not claim, a pool another job still holds. The run's own input +decides instead. + +A fallback is reported, never silent. The job title and artifact name carry the +kind the matrix *assigned*, while +[docker_dataroot.sh](../../scripts/tests/deploy/utils/filesystem/docker_dataroot.sh) +writes the *effective* filesystem and the reason into the step summary. When a +run has to prove a filesystem-dependent path, read the summary rather than the +title, or name the kind on the run to make it a demand. The snapshot mode of +`svc-bkp-volume-2-local` is the case that matters: it only engages on btrfs and +zfs. + +The userland tools are baked into every distro image by +[filesystem.sh](../../scripts/install/filesystem.sh); the kernel side comes from +the host. + +For **regular** rows every axis is a deterministic rotation over the row's +position in the global list and the sweep number, never random, so a red job +reproduces by re-running the same sweep: + +| Axis | Rotation | +|---|---| +| mode | `(position + sweep) % len(modes the role offers)` | +| tor | `(position + sweep // 2) % 2` | +| distro | `(position + sweep) % len(distro pool)` | +| filesystem | `(position // len(distro pool) + sweep) % len(filesystem pool)` | + +A role offers at most two modes in practice — swarm needs its own stack, host +needs the absence of one — so a row flips between its two modes on consecutive +sweeps. Tor turns on `sweep // 2` so it does not flip in lockstep: a row walks +all four mode/tor combinations over four sweeps instead of only two. Distro and +filesystem read the position like an odometer, the distro as the low digit, so +consecutive rows walk every pairing of the two pools rather than a diagonal +through it. Turning both on the position directly would cover only as many +pairings as the pools are long whenever they happen to be the same length, and +no sweep would unlock that, because the sweep shifts both by the same amount. +Priority rows skip the +mode/tor rotation entirely and take the whole cross-product at once; their +distro and filesystem walk on across those combinations, so one priority role +proves several distributions in one sweep. + +Because the same variant can run several times in one sweep, the onion state is +part of what identifies a job: it is in the job label (`🧅` vs `🌐`) and in every +artifact name. Two jobs uploading under one artifact name is a conflict, not an +overwrite. The distro and +filesystem glyphs follow it in the label (`🐳🧅🌀🦓`), so a title says which +combination died without opening the job. ### Stopping on failure -`mode_fail_fast` (default `true`) decides whether a serial line stops at its -first failed mode: +`chunk_gate` (default `true`) decides whether the chain stops at its first +failed chunk: | Value | Behaviour | |---|---| -| `true` | swarm fails → compose and host of that line are skipped | -| `false` | every mode deploys and reports; the run still ends red | +| `true` | chunk 0 fails → the remaining chunks are skipped | +| `false` | every chunk deploys and reports; the run still ends red | -`skipped` counts as passed, so a mode absent from `modes` never blocks the -chain. The parallel layout ignores the switch — with no order there is nothing -to stop. The setting is a checkbox on `entry-manual-steer.yml`; the other entry -points take the default. - -### Job budget - -`cli.meta.ci.slots` divides the run's 256-job cap between the deploy -matrices and reads the orchestrator to do it, so every deploy caller — -including the serial twins — must be listed in its `_DEPLOY_CALLERS`. -A caller missing there is charged a guessed dynamic-matrix estimate instead -of its single discover job. +`skipped` counts as passed, so an empty chunk never blocks the chain. After +fixing what broke a sweep, `resume_from_chunk` re-enters at that index instead +of re-running the green chunks. Both are inputs on `entry-manual-steer.yml`; +the other entry points take the defaults. ## Cancellation @@ -183,10 +266,17 @@ of its single discover job. flowchart TB prclose["pull_request_target: closed, converted_to_draft"] --> eprcancel["entry-pr-closed-cancel-workflows.yml"] branchdelete["delete: branch"] --> delbranch["entry-delete-branch.yml"] + newcommit["push (not main) / pull_request_target: opened, synchronize, reopened, ready_for_review, labeled"] --> superseded["entry-cancel-superseded.yml"] eprcancel -.->|"cancels concurrency group"| runningci["running entry + child workflow runs"] delbranch -.->|"cancels concurrency group"| runningci + superseded -.->|"cancels via API what the group left behind"| runningci ``` +The concurrency group stays the primary mechanism; it reaps within seconds of a +run being created and needs no runner. `entry-cancel-superseded.yml` is the +fallback for the case where it does not, and carries no group of its own, +because the run holding a group cannot be the run that frees it. + ## Scheduled and standalone ```mermaid @@ -209,5 +299,5 @@ flowchart TB Also manually dispatchable: `cron-images-mirror-all.yml`, `cron-images-cleanup-ci.yml`, `cron-cleanup-stale.yml`, `cron-update.yml`, `cron-release-highest.yml`, `call-release-version.yml`, -`call-lint.yml`, `call-test.yml`, `call-test-deploy-swarm.yml`, `call-test-dns.yml`, +`call-lint.yml`, `call-test.yml`, `call-test-dns.yml`, `test-workspace.yml`, `test-runner-smoke.yml`. diff --git a/.github/workflows/call-images-build-ci.yml b/.github/workflows/call-images-build-ci.yml index 2d102b466c..1719d9a623 100644 --- a/.github/workflows/call-images-build-ci.yml +++ b/.github/workflows/call-images-build-ci.yml @@ -35,7 +35,6 @@ on: permissions: contents: read - packages: write concurrency: group: infinito-build-${{ github.repository }}-${{ inputs.concurrency_channel }}-${{ inputs.checkout_ref || github.ref }} @@ -62,6 +61,9 @@ jobs: name: 🏗️ Build (${{ matrix.distro }}) needs: prepare runs-on: ubuntu-latest + permissions: + contents: read + packages: write strategy: fail-fast: false diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index b8853da214..be528068fd 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -3,9 +3,10 @@ on: workflow_call: inputs: distros: - description: "Space-separated distro list" - required: true + description: "Distro pool the deploy matrix spreads its rows over. Empty: every declared distro, which is what a sweep wants. The rows rotate over the pool, so narrowing it only makes sense to chase one distribution." + required: false type: string + default: "" whitelist: description: "Optional space-separated whitelist of app ids" required: false @@ -16,28 +17,38 @@ on: required: false type: string default: "" - modes: - description: "Deploy modes to run (space-separated: 'swarm compose host'). Only listed modes run their deploy job." - required: false - type: string - default: "swarm compose host" - priority: - description: "Optional space-separated app ids for the priority line: deployed first in every mode; the regular line runs the remaining roles only after every priority job succeeded." - required: false - type: string - default: "" - sequencing: - description: "🐛 Deploy-mode order per line. 'serial': swarm, then compose, then host. 'parallel': all at once. 'auto': serial above the job threshold." + mode: + description: "Deploy modes rows may be drawn from: 'auto' rotates every row over the modes its role offers; a subset of 'host compose swarm' keeps only the rows those modes can take." required: false type: string default: "auto" - mode_fail_fast: - description: "🛑 Stop a serial line at its first failed mode. Off: keep deploying the remaining modes." + priority: + description: "Optional space-separated app ids for the priority line: sorted to the head of the list and cut into chunks of their own, so every priority row is deployed before the first regular one starts. Priority rows skip the sweep rotation and run every combination they can take (each variant, each offered mode, Tor and clearnet)." + required: false + type: string + default: "" + sweep: + description: "Sweep number driving the mode and tor rotation. Empty: the run number." + required: false + type: string + default: "" + offset: + description: "Regular rows to skip before filling the chunks. 0 starts at the head of the ranking; raise it to reach rows the budget leaves behind." + required: false + type: string + default: "0" + resume_from_chunk: + description: "⏭️ Skip every chunk below this index. Use to continue a sweep after fixing what broke it, instead of re-running the green chunks. Typed string, not number: a workflow_dispatch number input reaches the caller as a string, and handing that to a number-typed workflow_call input makes GitHub reject the job before it is created." + required: false + type: string + default: "0" + chunk_gate: + description: "🛑 Stop the chunk chain at its first failed chunk. Off: keep deploying the remaining chunks." required: false type: boolean default: true filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." + description: "🗄️ Filesystem pool the deploy matrix spreads its rows over (ext4, btrfs, zfs). Empty: all three." required: false type: string default: "" @@ -56,115 +67,94 @@ on: required: false type: string default: "auto" + workspace_track: + description: "Which workspace track each distro runs: 'rotate' splits them across compose and swarm and flips with the run number, 'compose'/'swarm' pin every distro." + required: false + type: string + default: "rotate" instructions: description: "Run the instructions test (role README Production command). 'auto' runs it on a global scope only, 'true'/'false' force it." required: false type: string default: "auto" + tor: + description: "Tor axis of the deploy matrix: 'auto' rotates the onion over the tor-capable rows, 'enforced' onions all of them, 'exclusive' also drops the rows that cannot, 'disabled' onions none." + required: false + type: string + default: "auto" trusted_pr: description: "True when the PR carries the maintainer '🛡️ Trusted' label; skips the fork-prereq wait." required: false type: boolean default: false - force_cancel_in_progress: - description: "When true, a new run always cancels the running orchestrator on the same ref, ignoring the CI_CANCEL_IN_PROGRESS repository variable." - required: false - type: boolean - default: false concurrency: group: infinito-test-${{ github.ref }} - cancel-in-progress: ${{ inputs.force_cancel_in_progress || vars.CI_CANCEL_IN_PROGRESS != 'false' }} + cancel-in-progress: ${{ github.event_name == 'workflow_dispatch' || github.ref != 'refs/heads/main' }} permissions: - actions: write + actions: read contents: read - packages: write - security-events: write - issues: write + packages: read jobs: - wait-fork-prereq-run: - name: ⏳ Wait for fork run - runs-on: ubuntu-latest - env: - WAIT_REQUIRED: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && !inputs.trusted_pr }} - steps: - - name: 🏷️ Mark fork prerequisites as ready outside fork PRs or for trusted PRs - if: ${{ env.WAIT_REQUIRED != 'true' }} - shell: bash - run: | - set -euo pipefail - echo "Fork prerequisites are implicitly ready (non-fork PR or '🛡️ Trusted' label)." - - - name: ⬇️ Checkout trusted workflow repo (helpers) - if: ${{ env.WAIT_REQUIRED == 'true' }} - uses: actions/checkout@v7.0.0 - with: - ref: ${{ github.event.pull_request.base.sha }} - persist-credentials: false - - - name: 🔑 Login to GHCR for CI image checks - if: ${{ env.WAIT_REQUIRED == 'true' }} - uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: ⏳ Wait for privileged fork CI images - if: ${{ env.WAIT_REQUIRED == 'true' }} - shell: bash - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - WORKFLOW_FILE: entry-pr-change-orchestrate.yml - TARGET_EVENT: pull_request_target - PR_NUMBER: ${{ github.event.pull_request.number }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - PR_UPDATED_AT: ${{ github.event.pull_request.updated_at }} - INFINITO_DISTROS: "arch debian ubuntu fedora centos" - IMAGE_TAG: ci-${{ github.sha }} - WAIT_ATTEMPTS: ${{ inputs.image_wait_attempts }} - WAIT_SLEEP_SECONDS: ${{ inputs.image_wait_sleep_seconds }} - run: ./scripts/meta/wait/images.sh - - fork-prereqs-ready: - name: 🚦 Gate Dependencies - needs: wait-fork-prereq-run - if: ${{ always() }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7.0.0 - - name: ✅ Assert privileged prerequisites are ready - shell: bash - env: - RESULT: ${{ needs.wait-fork-prereq-run.result }} - run: ./scripts/github/gate/fork_prereqs.sh + validate-selection: + name: 🎯 Selection + uses: ./.github/workflows/call-validation.yml + with: + whitelist: ${{ inputs.whitelist }} + priority: ${{ inputs.priority }} + mode: ${{ inputs.mode }} + tor: ${{ inputs.tor }} + distros: ${{ inputs.distros }} + filesystem: ${{ inputs.filesystem }} + lifecycles: ${{ inputs.lifecycles }} + fork_prereqs: true + trusted_pr: ${{ inputs.trusted_pr }} + image_wait_attempts: ${{ inputs.image_wait_attempts }} + image_wait_sleep_seconds: ${{ inputs.image_wait_sleep_seconds }} + secrets: inherit security-codeql: + needs: validate-selection + permissions: + contents: read + packages: read + security-events: write uses: ./.github/workflows/cron-security-codeql.yml lint: + needs: validate-selection uses: ./.github/workflows/call-lint.yml test: + needs: validate-selection uses: ./.github/workflows/call-test.yml build-ci-images: + needs: validate-selection + permissions: + contents: read + packages: write uses: ./.github/workflows/call-images-build-ci.yml with: distros: "arch debian ubuntu fedora centos" concurrency_channel: ci-orchestrator-build-consumer secrets: inherit - + test-dns: - needs: + needs: - build-ci-images + - validate-selection uses: ./.github/workflows/call-test-dns.yml with: distros: "arch debian ubuntu fedora centos" - + images-mirror-missing: + needs: validate-selection + permissions: + contents: read + packages: write uses: ./.github/workflows/call-images-mirror-missing.yml with: concurrency_channel: ci-orchestrator-mirror-consumer @@ -172,311 +162,121 @@ jobs: image_wait_sleep_seconds: ${{ inputs.image_wait_sleep_seconds }} secrets: inherit - sequencing: - name: 🐛 Sequencing - runs-on: ubuntu-latest - timeout-minutes: 60 - outputs: - priority: ${{ steps.priority.outputs.sequencing }} - regular: ${{ steps.regular.outputs.sequencing }} - env: - INFINITO_APP_DISCOVERY_RUNNER: host - INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} - INFINITO_HOST_EXCLUDE_COMPOSE: ${{ contains(inputs.modes, 'compose') && 'true' || 'false' }} - steps: - - uses: actions/checkout@v7.0.0 - with: - fetch-depth: 0 - - - name: 🔧 Set up Python - uses: actions/setup-python@v6 - with: - python-version: "3.12" - cache: pip - cache-dependency-path: pyproject.toml - - - name: 📦 Install project (host venv) - shell: bash - run: make install - - - name: 🔍 Resolve effective whitelist (diff vs origin/main) - id: resolve_wl - shell: bash - env: - INPUT_WHITELIST: ${{ inputs.whitelist }} - run: ./scripts/github/resolve/effective_whitelist.sh - - - name: ⭐ Decide the priority line - id: priority - if: ${{ inputs.priority != '' }} - shell: bash - run: | - source scripts/meta/env/load.sh - "${PYTHON}" -m cli.meta.ci.sequencing \ - --modes "${{ inputs.modes }}" \ - --whitelist "${{ inputs.priority }}" \ - --lifecycles "${{ inputs.lifecycles }}" \ - --choice "${{ inputs.sequencing }}" \ - | tee -a "$GITHUB_OUTPUT" - - - name: 🔁 Decide the regular line - id: regular - shell: bash - run: | - source scripts/meta/env/load.sh - "${PYTHON}" -m cli.meta.ci.sequencing \ - --modes "${{ inputs.modes }}" \ - --whitelist "${{ steps.resolve_wl.outputs.whitelist }}" \ - --blacklist "${{ inputs.priority }}" \ - --lifecycles "${{ inputs.lifecycles }}" \ - --choice "${{ inputs.sequencing }}" \ - | tee -a "$GITHUB_OUTPUT" - - test-deploy-swarm-priority: - name: ⭐ Priority · swarm - if: ${{ inputs.priority != '' && contains(inputs.modes, 'swarm') }} - needs: - - lint - - test - - build-ci-images - - images-mirror-missing - uses: ./.github/workflows/call-test-deploy-swarm.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.priority }} - lifecycles: ${{ inputs.lifecycles }} - filesystem: ${{ inputs.filesystem }} - marker: " ⭐" - - test-deploy-single-node-priority: - name: ⭐ Priority · single-node - if: >- - ${{ inputs.priority != '' - && needs.sequencing.outputs.priority == 'parallel' - && (contains(inputs.modes, 'compose') || contains(inputs.modes, 'host')) }} - needs: - - test-dns - - images-mirror-missing - - lint - - test - - sequencing - uses: ./.github/workflows/call-test-deploy-single-node.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.priority }} - lifecycles: ${{ inputs.lifecycles }} - filesystem: ${{ inputs.filesystem }} - modes: ${{ inputs.modes }} - marker: " ⭐" - - test-deploy-compose-priority: - name: ⭐ Priority · compose + test-deploy-chunk-0: + name: 🧱 Chunk 0 if: >- ${{ always() - && inputs.priority != '' - && needs.sequencing.outputs.priority == 'serial' - && contains(inputs.modes, 'compose') - && needs.lint.result == 'success' - && needs.test.result == 'success' - && needs.test-dns.result == 'success' - && needs.images-mirror-missing.result == 'success' - && (!inputs.mode_fail_fast - || contains(fromJSON('["success","skipped"]'), needs.test-deploy-swarm-priority.result)) }} - needs: - - test-dns - - images-mirror-missing - - lint - - test - - sequencing - - test-deploy-swarm-priority - uses: ./.github/workflows/call-test-deploy-compose.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.priority }} - lifecycles: ${{ inputs.lifecycles }} - filesystem: ${{ inputs.filesystem }} - marker: " ⭐" - - test-deploy-host-priority: - name: ⭐ Priority · host - if: >- - ${{ always() - && inputs.priority != '' - && needs.sequencing.outputs.priority == 'serial' - && contains(inputs.modes, 'host') - && needs.lint.result == 'success' - && needs.test.result == 'success' - && needs.test-dns.result == 'success' - && needs.images-mirror-missing.result == 'success' - && (!inputs.mode_fail_fast - || contains(fromJSON('["success","skipped"]'), needs.test-deploy-compose-priority.result)) }} - needs: - - test-dns - - images-mirror-missing - - lint - - test - - sequencing - - test-deploy-compose-priority - uses: ./.github/workflows/call-test-deploy-host.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.priority }} - lifecycles: ${{ inputs.lifecycles }} - filesystem: ${{ inputs.filesystem }} - marker: " ⭐" - exclude_compose_covered: ${{ contains(inputs.modes, 'compose') && 'true' || 'false' }} - - test-deploy-swarm: - name: 🔁 Regular · swarm - if: >- - ${{ always() - && contains(inputs.modes, 'swarm') + && inputs.resume_from_chunk <= 0 && needs.lint.result == 'success' && needs.test.result == 'success' && needs.build-ci-images.result == 'success' && needs.images-mirror-missing.result == 'success' - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-single-node-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-compose-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-host-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-swarm-priority.result) }} + && needs.test-dns.result == 'success' }} needs: + - lint + - test - build-ci-images - images-mirror-missing - - test-deploy-single-node-priority - - test-deploy-compose-priority - - test-deploy-host-priority - - test-deploy-swarm-priority - - lint - - test - uses: ./.github/workflows/call-test-deploy-swarm.yml + - test-dns + - validate-selection + uses: ./.github/workflows/call-test-deploy.yml with: distros: ${{ inputs.distros }} + index: "0" + sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} + offset: ${{ inputs.offset }} whitelist: ${{ inputs.whitelist }} + priority: ${{ inputs.priority }} lifecycles: ${{ inputs.lifecycles }} + modes: ${{ inputs.mode }} filesystem: ${{ inputs.filesystem }} - blacklist: ${{ inputs.priority }} + tor: ${{ inputs.tor }} - test-deploy-single-node: - name: 🔁 Regular · single-node + test-deploy-chunk-1: + name: 🧱 Chunk 1 if: >- ${{ always() - && needs.sequencing.outputs.regular == 'parallel' - && (contains(inputs.modes, 'compose') || contains(inputs.modes, 'host')) + && inputs.resume_from_chunk <= 1 && needs.lint.result == 'success' && needs.test.result == 'success' - && needs.test-dns.result == 'success' + && needs.build-ci-images.result == 'success' && needs.images-mirror-missing.result == 'success' - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-single-node-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-compose-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-host-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-swarm-priority.result) }} + && needs.test-dns.result == 'success' + && (!inputs.chunk_gate + || contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-0.result)) }} needs: - - test-dns - - images-mirror-missing - - sequencing - - test-deploy-single-node-priority - - test-deploy-compose-priority - - test-deploy-host-priority - - test-deploy-swarm-priority - lint - test - uses: ./.github/workflows/call-test-deploy-single-node.yml + - build-ci-images + - images-mirror-missing + - test-dns + - test-deploy-chunk-0 + uses: ./.github/workflows/call-test-deploy.yml with: distros: ${{ inputs.distros }} + index: "1" + sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} + offset: ${{ inputs.offset }} whitelist: ${{ inputs.whitelist }} + priority: ${{ inputs.priority }} lifecycles: ${{ inputs.lifecycles }} + modes: ${{ inputs.mode }} filesystem: ${{ inputs.filesystem }} - modes: ${{ inputs.modes }} - blacklist: ${{ inputs.priority }} + tor: ${{ inputs.tor }} - test-deploy-compose: - name: 🔁 Regular · compose + test-deploy-chunk-2: + name: 🧱 Chunk 2 if: >- ${{ always() - && needs.sequencing.outputs.regular == 'serial' - && contains(inputs.modes, 'compose') + && inputs.resume_from_chunk <= 2 && needs.lint.result == 'success' && needs.test.result == 'success' - && needs.test-dns.result == 'success' + && needs.build-ci-images.result == 'success' && needs.images-mirror-missing.result == 'success' - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-single-node-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-compose-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-host-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-swarm-priority.result) - && (!inputs.mode_fail_fast - || contains(fromJSON('["success","skipped"]'), needs.test-deploy-swarm.result)) }} + && needs.test-dns.result == 'success' + && (!inputs.chunk_gate + || contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-1.result)) }} needs: - - test-dns - - images-mirror-missing - - sequencing - - test-deploy-single-node-priority - - test-deploy-compose-priority - - test-deploy-host-priority - - test-deploy-swarm-priority - - test-deploy-swarm - lint - test - uses: ./.github/workflows/call-test-deploy-compose.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.whitelist }} - lifecycles: ${{ inputs.lifecycles }} - filesystem: ${{ inputs.filesystem }} - blacklist: ${{ inputs.priority }} - - test-deploy-host: - name: 🔁 Regular · host - if: >- - ${{ always() - && needs.sequencing.outputs.regular == 'serial' - && contains(inputs.modes, 'host') - && needs.lint.result == 'success' - && needs.test.result == 'success' - && needs.test-dns.result == 'success' - && needs.images-mirror-missing.result == 'success' - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-single-node-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-compose-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-host-priority.result) - && contains(fromJSON('["success","skipped"]'), needs.test-deploy-swarm-priority.result) - && (!inputs.mode_fail_fast - || contains(fromJSON('["success","skipped"]'), needs.test-deploy-compose.result)) }} - needs: - - test-dns + - build-ci-images - images-mirror-missing - - sequencing - - test-deploy-single-node-priority - - test-deploy-compose-priority - - test-deploy-host-priority - - test-deploy-swarm-priority - - test-deploy-compose - - lint - - test - uses: ./.github/workflows/call-test-deploy-host.yml + - test-dns + - test-deploy-chunk-1 + uses: ./.github/workflows/call-test-deploy.yml with: distros: ${{ inputs.distros }} + index: "2" + sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} + offset: ${{ inputs.offset }} whitelist: ${{ inputs.whitelist }} + priority: ${{ inputs.priority }} lifecycles: ${{ inputs.lifecycles }} + modes: ${{ inputs.mode }} filesystem: ${{ inputs.filesystem }} - blacklist: ${{ inputs.priority }} - exclude_compose_covered: ${{ contains(inputs.modes, 'compose') && 'true' || 'false' }} + tor: ${{ inputs.tor }} test-runner-smoke: needs: - - test-deploy-swarm - if: ${{ always() && vars.CI_SELF_HOSTED_RUNNER_COUNT != '0' && vars.CI_SELF_HOSTED_RUNNER_COUNT != '' && (needs.test-deploy-swarm.result == 'success' || needs.test-deploy-swarm.result == 'failure') }} + - test-deploy-chunk-0 + if: ${{ always() && vars.CI_SELF_HOSTED_RUNNER_COUNT != '0' && vars.CI_SELF_HOSTED_RUNNER_COUNT != '' && (needs.test-deploy-chunk-0.result == 'success' || needs.test-deploy-chunk-0.result == 'failure') }} uses: ./.github/workflows/call-test-runner-smoke.yml with: ref: ${{ github.sha }} secrets: inherit test-install-make: + needs: validate-selection uses: ./.github/workflows/call-test-install-make.yml test-install-pkgmgr: + needs: validate-selection uses: ./.github/workflows/call-test-install-pkgmgr.yml test-workspace: if: ${{ inputs.workspace == 'true' || (inputs.workspace == 'auto' && (inputs.whitelist == '' || inputs.whitelist == '__ALL__')) }} uses: ./.github/workflows/call-test-workspace.yml + with: + workspace_track: ${{ inputs.workspace_track }} needs: - images-mirror-missing - lint @@ -491,21 +291,17 @@ jobs: - build-ci-images - lint - test + - validate-selection with: - distros: ${{ inputs.distros }} + distros: "arch debian ubuntu fedora centos" secrets: inherit report-main-failures: name: 🐞 Report main role failures needs: - - test-deploy-single-node-priority - - test-deploy-compose-priority - - test-deploy-host-priority - - test-deploy-swarm-priority - - test-deploy-single-node - - test-deploy-compose - - test-deploy-host - - test-deploy-swarm + - test-deploy-chunk-0 + - test-deploy-chunk-1 + - test-deploy-chunk-2 if: ${{ always() && github.ref == 'refs/heads/main' && (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) }} runs-on: ubuntu-latest permissions: @@ -522,22 +318,15 @@ jobs: done: name: 🏁 Finish pipeline needs: - - wait-fork-prereq-run - - fork-prereqs-ready + - validate-selection - build-ci-images - images-mirror-missing - test-dns - test-install-make - test-install-pkgmgr - - sequencing - - test-deploy-single-node-priority - - test-deploy-compose-priority - - test-deploy-host-priority - - test-deploy-swarm-priority - - test-deploy-single-node - - test-deploy-compose - - test-deploy-host - - test-deploy-swarm + - test-deploy-chunk-0 + - test-deploy-chunk-1 + - test-deploy-chunk-2 - test-runner-smoke - test-workspace - test-instructions diff --git a/.github/workflows/call-release-version.yml b/.github/workflows/call-release-version.yml index 775896c695..25ca45302e 100644 --- a/.github/workflows/call-release-version.yml +++ b/.github/workflows/call-release-version.yml @@ -11,7 +11,7 @@ on: workflow_dispatch: inputs: tag: - description: "Version tag to release (e.g. v1.2.3)" + description: "🏷️ Version tag to release (e.g. v1.2.3)" required: true type: string @@ -20,10 +20,8 @@ concurrency: cancel-in-progress: false permissions: - contents: write - packages: write - security-events: write - actions: read + contents: read + packages: read env: REGISTRY: ghcr.io @@ -52,7 +50,7 @@ jobs: - name: 🔍 Resolve release inputs id: vars shell: bash - run: bash _helpers/scripts/github/resolve/release_inputs.sh "${{ inputs.tag || github.event.inputs.tag }}" + run: bash _helpers/scripts/github/resolve/release/inputs.sh "${{ inputs.tag || github.event.inputs.tag }}" - name: ⬇️ Checkout repository at version tag uses: actions/checkout@v7.0.0 @@ -102,6 +100,9 @@ jobs: name: 🏗️ Build missing CI images needs: check-ci-images if: needs.check-ci-images.outputs.missing == 'true' + permissions: + contents: read + packages: write uses: ./.github/workflows/call-images-build-ci.yml with: distros: ${{ needs.check-ci-images.outputs.distros }} @@ -123,6 +124,9 @@ jobs: needs.build-ci-images-if-missing.result == 'skipped' ) runs-on: ubuntu-latest + permissions: + contents: read + packages: write env: VERSION_TAG: ${{ needs.check-ci-images.outputs.version_tag }} OWNER: ${{ needs.check-ci-images.outputs.owner }} diff --git a/.github/workflows/call-test-deploy-compose.yml b/.github/workflows/call-test-deploy-compose.yml deleted file mode 100644 index 4c4922726c..0000000000 --- a/.github/workflows/call-test-deploy-compose.yml +++ /dev/null @@ -1,249 +0,0 @@ -name: "📦 Test: Deploy (compose)" - -on: - workflow_call: - inputs: - distros: - description: "Space-separated distro list" - required: true - type: string - whitelist: - description: "Optional space-separated whitelist of app ids" - required: false - type: string - default: "" - lifecycles: - description: "Lifecycle envelope for discovery (comma/space-separated)." - required: false - type: string - default: "" - blacklist: - description: "Optional space-separated app ids to drop from discovery" - required: false - type: string - default: "" - marker: - description: "Optional suffix appended to the discover job name (e.g. ' ⭐' for the priority line)" - required: false - type: string - default: "" - filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." - required: false - type: string - default: "" - -permissions: - contents: read - packages: read - -env: - INFINITO_DISTROS: ${{ inputs.distros }} - NIX_CONFIG: | - access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} - INFINITO_IMAGE_TAG: ci-${{ github.sha }} - INFINITO_GHCR_MIRROR_PREFIX: mirror - INFINITO_PLAYWRIGHT_KEEP: ${{ vars.INFINITO_PLAYWRIGHT_KEEP }} - INFINITO_MAIL_PRODUCTION_HOST: ${{ vars.INFINITO_MAIL_PRODUCTION_HOST }} - INFINITO_MAIL_PRODUCTION_RESOLVER: ${{ vars.INFINITO_MAIL_PRODUCTION_RESOLVER }} - INFINITO_APP_DISCOVERY_RUNNER: host - INFINITO_DEPLOY_MODE: compose - INFINITO_DOCKER_FILESYSTEM_ALLOWED: ${{ inputs.filesystem }} - INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} - INFINITO_BLACKLIST: ${{ inputs.blacklist }} -jobs: - discover: - name: 🪼 Compose (${{ inputs.distros }})${{ inputs.marker }} - runs-on: ubuntu-latest - timeout-minutes: 60 - outputs: - apps: ${{ steps.discover.outputs.apps }} - - steps: - - uses: actions/checkout@v7.0.0 - with: - fetch-depth: 0 - - - name: 🔍 Resolve repository owner - shell: bash - run: | - set -euo pipefail - echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" - - - name: 📦 Install jq - shell: bash - run: ./scripts/install/apt.sh jq - - - name: 📦 Install deps (jq + envsubst) - shell: bash - run: ./scripts/install/apt.sh jq gettext-base - - - name: 🔧 Set up Python - uses: actions/setup-python@v6 - with: - python-version: "3.12" - cache: pip - cache-dependency-path: pyproject.toml - - - name: 📦 Install project (host venv) - shell: bash - run: make install - - - name: 🔍 Resolve effective whitelist (diff vs origin/main) - id: resolve_wl - shell: bash - env: - INPUT_WHITELIST: ${{ inputs.whitelist }} - run: ./scripts/github/resolve/effective_whitelist.sh - - - name: 🔍 Discover apps - id: discover - shell: bash - env: - INFINITO_WHITELIST: ${{ steps.resolve_wl.outputs.whitelist }} - run: ./scripts/github/resolve/output_apps.sh - - - name: 🗺️ Render the plan into the run summary - shell: bash - run: | - source scripts/meta/env/load.sh - "${PYTHON}" -m cli.meta.ci.plan \ - --distros "${{ inputs.distros }}" \ - --whitelist "${{ steps.resolve_wl.outputs.whitelist }}" \ - --priority "${{ inputs.blacklist }}" \ - --modes "compose" \ - --lifecycles "${{ inputs.lifecycles }}" \ - >> "$GITHUB_STEP_SUMMARY" - - compose: - name: 🐳${{ matrix.label }} - if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' - runs-on: ubuntu-latest - timeout-minutes: 355 - needs: discover - - concurrency: - group: "infinito-deploy-compose-${{ matrix.apps }}#${{ matrix.variant_slug }}" - cancel-in-progress: false - queue: max - - strategy: - fail-fast: false - matrix: - include: ${{ fromJson(needs.discover.outputs.apps) }} - - steps: - - name: 🧹 Free disk space - uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be # v1.3.1 - with: - tool-cache: true - android: true - dotnet: true - haskell: true - large-packages: true - docker-images: true - swap-storage: true - - - uses: actions/checkout@v7.0.0 - - - name: "📥 Load rescue-diagnostics SPOT into job env" - shell: bash - run: grep '^INFINITO_RESCUE_DIAGNOSTICS_BASE=' default.env >> "$GITHUB_ENV" - - - name: 💾 Enlarge swap space - shell: bash - run: ./scripts/github/runner/enlarge_swap.sh - - - name: 📦 Relocate Docker data-root onto /mnt when roomier - if: ${{ !env.ACT }} - shell: bash - run: ./scripts/github/runner/relocate_docker_dataroot.sh - - - name: 🔍 Resolve repository owner - shell: bash - run: | - set -euo pipefail - echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" - - - name: 📦 Install jq - shell: bash - run: ./scripts/install/apt.sh jq - - - name: 🚀 Deploy app - timeout-minutes: 350 - shell: bash - env: - apps: ${{ matrix.apps }} - variant: ${{ matrix.variant }} - ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log - run: ./scripts/tests/deploy/ci/all.sh 2>&1 | tee "/tmp/ansible-${{ matrix.apps }}.log" - - - name: 🚫 Fail on deprecation warnings - if: always() - shell: bash - run: ./scripts/tests/deploy/ci/assert_no_deprecation_warnings.sh "/tmp/ansible-${{ matrix.apps }}.log" - - - name: 📊 Role runtimes - if: always() - shell: bash - run: | - set -euo pipefail - python3 -m cli.meta.ci.roles.runtime "/tmp/ansible-${{ matrix.apps }}.log" \ - --format csv --output "/tmp/role-runtimes-${{ matrix.apps }}.csv" - python3 -m cli.meta.ci.roles.runtime "/tmp/role-runtimes-${{ matrix.apps }}.csv" \ - --format markdown >> "$GITHUB_STEP_SUMMARY" - - - name: ⬆️ Upload role runtimes CSV - if: always() - uses: actions/upload-artifact@v7 - with: - name: role-runtimes-${{ matrix.apps }} - path: /tmp/role-runtimes-${{ matrix.apps }}.csv - if-no-files-found: ignore - - - name: 🩺 Dump runner state (on failure) - if: failure() - timeout-minutes: 5 - shell: bash - run: ./scripts/github/runner/dump_state.sh "post-deploy failure (${{ matrix.apps }})" - - - name: ⬆️ Upload rescue diagnostics - if: always() - uses: actions/upload-artifact@v7 - with: - name: rescue-diagnostics-compose-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} - path: ${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/ - if-no-files-found: ignore - - - name: 🗜️ Zip generated inventory for debugging - if: always() - shell: bash - env: - APP_ID: ${{ matrix.apps }} - run: bash scripts/github/inventory/zip/compose_for_upload.sh - - - name: ⬆️ Upload inventory artifact - if: ${{ always() && !env.ACT }} - uses: actions/upload-artifact@v7 - with: - name: inventory-compose-${{ matrix.apps }} - path: /tmp/inventory-compose-${{ matrix.apps }}.zip - if-no-files-found: ignore - - - name: 📋 Playwright step summary - if: always() - shell: bash - run: | - set -euo pipefail - python3 utils/github/playwright_summary.py \ - /tmp/playwright-artifacts \ - "${{ matrix.apps }}" \ - >> "$GITHUB_STEP_SUMMARY" - - - name: ⬆️ Upload Playwright artifacts - if: always() - uses: actions/upload-artifact@v7.0.1 - with: - name: playwright-compose-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} - path: /tmp/playwright-artifacts/ - if-no-files-found: ignore diff --git a/.github/workflows/call-test-deploy-host.yml b/.github/workflows/call-test-deploy-host.yml deleted file mode 100644 index b129f79066..0000000000 --- a/.github/workflows/call-test-deploy-host.yml +++ /dev/null @@ -1,237 +0,0 @@ -name: "💻 Test: Deploy (host)" - -on: - workflow_call: - inputs: - distros: - description: "Space-separated distro list" - required: true - type: string - whitelist: - description: "Optional space-separated whitelist of app ids" - required: false - type: string - default: "" - lifecycles: - description: "Lifecycle envelope for discovery (comma/space-separated)." - required: false - type: string - default: "" - blacklist: - description: "Optional space-separated app ids to drop from discovery" - required: false - type: string - default: "" - marker: - description: "Optional suffix appended to the discover job name (e.g. ' ⭐' for the priority line)" - required: false - type: string - default: "" - filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." - required: false - type: string - default: "" - exclude_compose_covered: - description: "Drop roles the same run's compose line already deploys" - required: false - type: string - default: "false" - -permissions: - contents: read - packages: read - -env: - INFINITO_DISTROS: ${{ inputs.distros }} - NIX_CONFIG: | - access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} - INFINITO_IMAGE_TAG: ci-${{ github.sha }} - INFINITO_GHCR_MIRROR_PREFIX: mirror - INFINITO_PLAYWRIGHT_KEEP: ${{ vars.INFINITO_PLAYWRIGHT_KEEP }} - INFINITO_MAIL_PRODUCTION_HOST: ${{ vars.INFINITO_MAIL_PRODUCTION_HOST }} - INFINITO_MAIL_PRODUCTION_RESOLVER: ${{ vars.INFINITO_MAIL_PRODUCTION_RESOLVER }} - INFINITO_APP_DISCOVERY_RUNNER: host - INFINITO_DEPLOY_MODE: host - INFINITO_DOCKER_FILESYSTEM_ALLOWED: ${{ inputs.filesystem }} - INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} - INFINITO_BLACKLIST: ${{ inputs.blacklist }} - INFINITO_HOST_EXCLUDE_COMPOSE: ${{ inputs.exclude_compose_covered }} -jobs: - discover: - name: 💻 Host (${{ inputs.distros }})${{ inputs.marker }} - runs-on: ubuntu-latest - timeout-minutes: 60 - outputs: - apps: ${{ steps.discover.outputs.apps }} - - steps: - - uses: actions/checkout@v7.0.0 - with: - fetch-depth: 0 - - - name: 🔍 Resolve repository owner - shell: bash - run: | - set -euo pipefail - echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" - - - name: 📦 Install jq - shell: bash - run: ./scripts/install/apt.sh jq - - - name: 📦 Install deps (jq + envsubst) - shell: bash - run: ./scripts/install/apt.sh jq gettext-base - - - name: 🔧 Set up Python - uses: actions/setup-python@v6 - with: - python-version: "3.12" - cache: pip - cache-dependency-path: pyproject.toml - - - name: 📦 Install project (host venv) - shell: bash - run: make install - - - name: 🔍 Resolve effective whitelist (diff vs origin/main) - id: resolve_wl - shell: bash - env: - INPUT_WHITELIST: ${{ inputs.whitelist }} - run: ./scripts/github/resolve/effective_whitelist.sh - - - name: 🔍 Discover host roles - id: discover - shell: bash - env: - INFINITO_WHITELIST: ${{ steps.resolve_wl.outputs.whitelist }} - run: ./scripts/github/resolve/output_apps.sh - - - name: 🗺️ Render the plan into the run summary - shell: bash - run: | - source scripts/meta/env/load.sh - "${PYTHON}" -m cli.meta.ci.plan \ - --distros "${{ inputs.distros }}" \ - --whitelist "${{ steps.resolve_wl.outputs.whitelist }}" \ - --priority "${{ inputs.blacklist }}" \ - --modes "host" \ - --lifecycles "${{ inputs.lifecycles }}" \ - >> "$GITHUB_STEP_SUMMARY" - - host: - name: 💻${{ matrix.label }} - if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' - runs-on: ubuntu-latest - timeout-minutes: 355 - needs: discover - - concurrency: - group: "infinito-deploy-host-${{ matrix.apps }}#${{ matrix.variant_slug }}" - cancel-in-progress: false - queue: max - - strategy: - fail-fast: false - matrix: - include: ${{ fromJson(needs.discover.outputs.apps) }} - - steps: - - name: 🧹 Free disk space - uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be # v1.3.1 - with: - tool-cache: true - android: true - dotnet: true - haskell: true - large-packages: true - docker-images: true - swap-storage: true - - - uses: actions/checkout@v7.0.0 - - - name: "📥 Load rescue-diagnostics SPOT into job env" - shell: bash - run: grep '^INFINITO_RESCUE_DIAGNOSTICS_BASE=' default.env >> "$GITHUB_ENV" - - - name: 💾 Enlarge swap space - shell: bash - run: ./scripts/github/runner/enlarge_swap.sh - - - name: 📦 Relocate Docker data-root onto /mnt when roomier - if: ${{ !env.ACT }} - shell: bash - run: ./scripts/github/runner/relocate_docker_dataroot.sh - - - name: 🔍 Resolve repository owner - shell: bash - run: | - set -euo pipefail - echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" - - - name: 📦 Install jq - shell: bash - run: ./scripts/install/apt.sh jq - - - name: 🚀 Deploy host role - timeout-minutes: 350 - shell: bash - env: - apps: ${{ matrix.apps }} - variant: ${{ matrix.variant }} - ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log - run: ./scripts/tests/deploy/ci/all.sh 2>&1 | tee "/tmp/ansible-${{ matrix.apps }}.log" - - - name: 🚫 Fail on deprecation warnings - if: always() - shell: bash - run: ./scripts/tests/deploy/ci/assert_no_deprecation_warnings.sh "/tmp/ansible-${{ matrix.apps }}.log" - - - name: 📊 Role runtimes - if: always() - shell: bash - run: | - set -euo pipefail - python3 -m cli.meta.ci.roles.runtime "/tmp/ansible-${{ matrix.apps }}.log" \ - --format csv --output "/tmp/role-runtimes-${{ matrix.apps }}.csv" - python3 -m cli.meta.ci.roles.runtime "/tmp/role-runtimes-${{ matrix.apps }}.csv" \ - --format markdown >> "$GITHUB_STEP_SUMMARY" - - - name: ⬆️ Upload role runtimes CSV - if: always() - uses: actions/upload-artifact@v7 - with: - name: role-runtimes-host-${{ matrix.apps }} - path: /tmp/role-runtimes-${{ matrix.apps }}.csv - if-no-files-found: ignore - - - name: 🩺 Dump runner state (on failure) - if: failure() - timeout-minutes: 5 - shell: bash - run: ./scripts/github/runner/dump_state.sh "post-deploy failure (${{ matrix.apps }})" - - - name: ⬆️ Upload rescue diagnostics - if: always() - uses: actions/upload-artifact@v7 - with: - name: rescue-diagnostics-host-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} - path: ${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/ - if-no-files-found: ignore - - - name: 🗜️ Zip generated inventory for debugging - if: always() - shell: bash - env: - APP_ID: ${{ matrix.apps }} - run: bash scripts/github/inventory/zip/compose_for_upload.sh - - - name: ⬆️ Upload inventory artifact - if: ${{ always() && !env.ACT }} - uses: actions/upload-artifact@v7 - with: - name: inventory-host-${{ matrix.apps }} - path: /tmp/inventory-compose-${{ matrix.apps }}.zip - if-no-files-found: ignore diff --git a/.github/workflows/call-test-deploy-single-node.yml b/.github/workflows/call-test-deploy-single-node.yml deleted file mode 100644 index ed6873c33e..0000000000 --- a/.github/workflows/call-test-deploy-single-node.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: "🏝️ Test: Deploy (single-node)" - -on: - workflow_call: - inputs: - distros: - description: "Space-separated distro list" - required: true - type: string - whitelist: - description: "Optional space-separated whitelist of app ids" - required: false - type: string - default: "" - lifecycles: - description: "Lifecycle envelope for discovery (comma/space-separated)." - required: false - type: string - default: "" - modes: - description: "Single-node deploy modes to run (space-separated subset of 'compose host')." - required: false - type: string - default: "compose host" - blacklist: - description: "Optional space-separated app ids to drop from discovery" - required: false - type: string - default: "" - marker: - description: "Optional suffix appended to the discover job names (e.g. ' ⭐' for the priority line)" - required: false - type: string - default: "" - filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." - required: false - type: string - default: "" - -permissions: - contents: read - packages: read - -jobs: - compose: - name: 📦 Compose - if: ${{ contains(inputs.modes, 'compose') }} - uses: ./.github/workflows/call-test-deploy-compose.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.whitelist }} - lifecycles: ${{ inputs.lifecycles }} - blacklist: ${{ inputs.blacklist }} - marker: ${{ inputs.marker }} - filesystem: ${{ inputs.filesystem }} - - host: - name: 💻 Host - if: ${{ contains(inputs.modes, 'host') }} - uses: ./.github/workflows/call-test-deploy-host.yml - with: - distros: ${{ inputs.distros }} - whitelist: ${{ inputs.whitelist }} - lifecycles: ${{ inputs.lifecycles }} - blacklist: ${{ inputs.blacklist }} - marker: ${{ inputs.marker }} - filesystem: ${{ inputs.filesystem }} - exclude_compose_covered: ${{ contains(inputs.modes, 'compose') && 'true' || 'false' }} diff --git a/.github/workflows/call-test-deploy-swarm.yml b/.github/workflows/call-test-deploy.yml similarity index 52% rename from .github/workflows/call-test-deploy-swarm.yml rename to .github/workflows/call-test-deploy.yml index 61e2205625..767d1b09d7 100644 --- a/.github/workflows/call-test-deploy-swarm.yml +++ b/.github/workflows/call-test-deploy.yml @@ -1,60 +1,115 @@ -name: "🐝 Test: Deploy (swarm)" +name: "🚀 Test: Deploy" on: workflow_call: inputs: distros: - description: "Space-separated distro list (shown in the discover job name)" + description: "🐧 Space-separated distro pool the matrix spreads its rows over. Empty: every declared distro." + required: false + type: string + default: "" + index: + description: "Chunk index this call deploys; chunks run serially, one block per index." required: true type: string + sweep: + description: "Sweep number driving the mode and tor rotation and the regular-line offset." + required: true + type: string + offset: + description: "Regular rows to skip before filling the chunks; 0 starts at the head of the ranking." + required: false + type: string + default: "0" whitelist: description: "Optional space-separated whitelist of app ids" required: false type: string default: "" + priority: + description: "Optional space-separated app ids for the priority line: sorted to the head of the list, cut into chunks of their own, and deployed in every combination they can take." + required: false + type: string + default: "" lifecycles: description: "Lifecycle envelope for discovery (comma/space-separated)." required: false type: string default: "" - blacklist: - description: "Optional space-separated app ids to drop from discovery" + modes: + description: "Deploy modes rows may be drawn from: 'auto' for every mode, or a subset of 'host compose swarm'." required: false type: string - default: "" + default: "auto" filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." + description: "🗄️ Space-separated filesystem pool the matrix spreads its rows over (ext4, btrfs, zfs). Empty: all three." required: false type: string default: "" marker: - description: "Optional suffix appended to the discover job name (e.g. ' ⭐' for the priority line)" + description: "Optional suffix appended to the discover job name (e.g. ' ⭐' for a priority chunk)" + required: false + type: string + default: "" + tor: + required: false + type: string + default: auto + disable: + description: "Comma-separated provider keys removed from the test inventory; used when the matrix row carries none of its own." required: false type: string default: "" workflow_dispatch: inputs: distros: - description: "Space-separated distro list (shown in the discover job name)" - required: true + description: "🐧 Distro pool the matrix spreads its rows over. Empty: every declared distro" + required: false type: string + default: "" + index: + description: "📦 Chunk index to deploy." + required: false + type: string + default: "0" + sweep: + description: "🔁 Sweep number driving the mode/tor rotation and the regular-line offset." + required: false + type: string + default: "0" whitelist: - description: "Optional space-separated whitelist of app ids" + description: "🎯 Roles to deploy. Empty: diff vs origin/main. '__ALL__': every role." + required: false + type: string + default: "" + priority: + description: "⭐ Roles to deploy first, in every combination they can take." required: false type: string default: "" lifecycles: - description: "Lifecycle envelope for discovery (comma/space-separated)." + description: "♻️ Lifecycle envelope for discovery (comma/space-separated)." required: false type: string default: "" - blacklist: - description: "Optional space-separated app ids to drop from discovery" + modes: + description: "🚀 Deploy modes to draw from: 'auto' or a subset of 'host compose swarm'" required: false type: string - default: "" + default: "auto" filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." + description: "🗄️ Filesystem pool the matrix spreads its rows over. Empty: ext4, btrfs, zfs" + required: false + type: string + default: "" + tor: + description: "🧅 Tor axis; see .github/workflows/README.md for what each value does" + required: false + type: choice + default: auto + options: [auto, enforced, exclusive, disabled] + disable: + description: "🚫 Provider keys removed from the test inventory (comma-separated)" required: false type: string default: "" @@ -71,22 +126,22 @@ env: INFINITO_GHCR_MIRROR_PREFIX: mirror INFINITO_MAIL_PRODUCTION_HOST: ${{ vars.INFINITO_MAIL_PRODUCTION_HOST }} INFINITO_MAIL_PRODUCTION_RESOLVER: ${{ vars.INFINITO_MAIL_PRODUCTION_RESOLVER }} + INFINITO_PLAYWRIGHT_KEEP: ${{ vars.INFINITO_PLAYWRIGHT_KEEP }} INFINITO_APP_DISCOVERY_RUNNER: host - INFINITO_DEPLOY_MODE: swarm INFINITO_DOCKER_FILESYSTEM_ALLOWED: ${{ inputs.filesystem }} INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} - INFINITO_BLACKLIST: ${{ inputs.blacklist }} + INFINITO_DISCOVERY_SEED: ${{ github.run_id }} jobs: discover: - name: 🚢 Swarm (${{ inputs.distros }})${{ inputs.marker }} + name: 🔍 Chunk ${{ inputs.index }}${{ inputs.marker }} runs-on: ubuntu-latest timeout-minutes: 60 outputs: apps: ${{ steps.discover.outputs.apps }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@v7.0.0 with: fetch-depth: 0 @@ -96,10 +151,6 @@ jobs: set -euo pipefail echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" - - name: 📦 Install jq - shell: bash - run: ./scripts/install/apt.sh jq - - name: 📦 Install deps (jq + envsubst) shell: bash run: ./scripts/install/apt.sh jq gettext-base @@ -126,36 +177,56 @@ jobs: INPUT_WHITELIST: ${{ inputs.whitelist }} run: ./scripts/github/resolve/effective_whitelist.sh - - name: 🔍 Discover apps + - name: 🔍 Discover the chunk's rows id: discover shell: bash env: INFINITO_WHITELIST: ${{ steps.resolve_wl.outputs.whitelist }} + INFINITO_PRIORITY: ${{ inputs.priority }} + INFINITO_MODES: ${{ inputs.modes }} + INFINITO_TOR: ${{ inputs.tor }} + INFINITO_CI_SWEEP: ${{ inputs.sweep }} + INFINITO_CI_CHUNK: ${{ inputs.index }} + INFINITO_CI_OFFSET: ${{ inputs.offset }} run: ./scripts/github/resolve/output_apps.sh - name: 🗺️ Render the plan into the run summary shell: bash + env: + INFINITO_CI_SWEEP: ${{ inputs.sweep }} + PLAN_DISTROS: ${{ inputs.distros }} + PLAN_FILESYSTEM: ${{ inputs.filesystem }} + PLAN_WHITELIST: ${{ steps.resolve_wl.outputs.whitelist }} + PLAN_PRIORITY: ${{ inputs.priority }} + PLAN_MODES: ${{ inputs.modes }} + PLAN_LIFECYCLES: ${{ inputs.lifecycles }} + PLAN_TOR: ${{ inputs.tor }} + PLAN_OFFSET: ${{ inputs.offset }} run: | source scripts/meta/env/load.sh "${PYTHON}" -m cli.meta.ci.plan \ - --distros "${{ inputs.distros }}" \ - --whitelist "${{ steps.resolve_wl.outputs.whitelist }}" \ - --priority "${{ inputs.blacklist }}" \ - --modes "swarm" \ - --lifecycles "${{ inputs.lifecycles }}" \ + --distros "${PLAN_DISTROS}" \ + --filesystem "${PLAN_FILESYSTEM}" \ + --whitelist "${PLAN_WHITELIST}" \ + --priority "${PLAN_PRIORITY}" \ + --modes "${PLAN_MODES}" \ + --lifecycles "${PLAN_LIFECYCLES}" \ + --tor "${PLAN_TOR}" \ + --offset "${PLAN_OFFSET}" \ >> "$GITHUB_STEP_SUMMARY" - swarm: - name: "🐝${{ matrix.label }}" + deploy: + name: "${{ matrix.label }}" if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' runs-on: ubuntu-latest timeout-minutes: 355 needs: discover - concurrency: - group: "infinito-deploy-swarm-${{ matrix.apps }}#${{ matrix.variant_slug }}" - cancel-in-progress: false - queue: max + # TODO: blocks the queue and prevents job cancelling. + # concurrency: + # group: "infinito-deploy-${{ matrix.mode }}-${{ matrix.tor }}-${{ matrix.apps }}#${{ matrix.variant }}" + # cancel-in-progress: false + # queue: max strategy: fail-fast: false @@ -164,6 +235,11 @@ jobs: env: APP_ID: ${{ matrix.apps }} + INFINITO_DEPLOY_MODE: ${{ matrix.mode }} + INFINITO_DISTROS: ${{ matrix.distro }} + INFINITO_DOCKER_FILESYSTEM_ALLOWED: ${{ inputs.filesystem }} + INFINITO_DOCKER_FILESYSTEM_PICK: ${{ matrix.filesystem }} + INFINITO_DOCKER_FILESYSTEM_ENFORCED: ${{ matrix.enforce_filesystem }} RESCHED_TIMEOUT: "120" SCRIPTS: scripts/tests/deploy/swarm/routine @@ -182,7 +258,7 @@ jobs: - name: "⬇️ Checkout" if: ${{ !env.ACT }} - uses: actions/checkout@v7 + uses: actions/checkout@v7.0.0 - name: "📥 Load rescue-diagnostics SPOT into job env" shell: bash @@ -198,15 +274,28 @@ jobs: shell: bash run: ./scripts/github/runner/relocate_docker_dataroot.sh + - name: 🔍 Resolve repository owner + shell: bash + run: | + set -euo pipefail + echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" + + - name: 📦 Install jq + shell: bash + run: ./scripts/install/apt.sh jq + - name: "🔍 Resolve SWARM_NAME (mandatory; default to the matrix app)" + if: ${{ matrix.mode == 'swarm' }} shell: bash run: echo "SWARM_NAME=${SWARM_NAME:-${{ matrix.apps }}}" >> "$GITHUB_ENV" - name: "📥 Load swarm topology SPOT into job env" + if: ${{ matrix.mode == 'swarm' }} shell: bash run: scripts/tests/deploy/swarm/utils/topology/export.sh - name: 🔧 Set up Python + if: ${{ matrix.mode == 'swarm' }} uses: actions/setup-python@v6 with: python-version: "3.12" @@ -214,6 +303,7 @@ jobs: cache-dependency-path: pyproject.toml - name: 📦 Install project (host venv) + if: ${{ matrix.mode == 'swarm' }} shell: bash run: | make install-force @@ -221,14 +311,32 @@ jobs: source scripts/meta/env/load.sh echo "${VENV}/bin" >> "${GITHUB_PATH}" - - name: "🚀 Drill ${{ matrix.apps }} per distro: ${{ inputs.distros }}" + - name: "🚀 Drill ${{ matrix.apps }} on ${{ matrix.distro }}/${{ matrix.filesystem }}" + if: ${{ matrix.mode == 'swarm' }} shell: bash env: variant: ${{ matrix.variant }} + disable: ${{ matrix.disable || inputs.disable }} run: ./scripts/tests/deploy/distros.sh "${{ env.SCRIPTS }}/00_one.sh" 2>&1 | tee "/tmp/ansible-${{ matrix.apps }}.log" + - name: 🚀 Deploy app + if: ${{ matrix.mode != 'swarm' }} + timeout-minutes: 350 + shell: bash + env: + apps: ${{ matrix.apps }} + variant: ${{ matrix.variant }} + disable: ${{ matrix.disable || inputs.disable }} + ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log + run: ./scripts/tests/deploy/ci/all.sh 2>&1 | tee "/tmp/ansible-${{ matrix.apps }}.log" + + - name: 🚫 Fail on deprecation warnings + if: ${{ always() && matrix.mode != 'swarm' }} + shell: bash + run: ./scripts/tests/deploy/ci/assert_no_deprecation_warnings.sh "/tmp/ansible-${{ matrix.apps }}.log" + - name: "🗄️ Effective node filesystems" - if: always() + if: ${{ always() && matrix.mode == 'swarm' }} shell: bash run: ./scripts/tests/deploy/utils/filesystem/report.sh "/tmp/ansible-${{ matrix.apps }}.log" @@ -251,15 +359,21 @@ jobs: if: ${{ always() && !env.ACT }} uses: actions/upload-artifact@v7 with: - name: role-runtimes-swarm-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} + name: role-runtimes-${{ matrix.artifact }} path: /tmp/role-runtimes-${{ matrix.apps }}.csv if-no-files-found: ignore + - name: 🩺 Dump runner state (on failure) + if: ${{ failure() && matrix.mode != 'swarm' }} + timeout-minutes: 5 + shell: bash + run: ./scripts/github/runner/dump_state.sh "post-deploy failure (${{ matrix.apps }})" + - name: "⬆️ Upload rescue diagnostics" if: ${{ always() && !env.ACT }} uses: actions/upload-artifact@v7 with: - name: rescue-diagnostics-swarm-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} + name: rescue-diagnostics-${{ matrix.artifact }} path: ${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/ if-no-files-found: ignore @@ -268,14 +382,19 @@ jobs: shell: bash env: APP_ID: ${{ matrix.apps }} - run: bash scripts/github/inventory/zip/swarm_for_upload.sh + run: | + set -euo pipefail + kind=swarm + [ "${{ matrix.mode }}" = "swarm" ] || kind=compose + bash "scripts/github/inventory/zip/${kind}_for_upload.sh" + echo "INVENTORY_ZIP=/tmp/inventory-${kind}-${APP_ID}.zip" >> "$GITHUB_ENV" - name: "⬆️ Upload inventory artifact" if: ${{ always() && !env.ACT }} uses: actions/upload-artifact@v7 with: - name: inventory-swarm-${{ matrix.apps }} - path: /tmp/inventory-swarm-${{ matrix.apps }}.zip + name: inventory-${{ matrix.artifact }} + path: ${{ env.INVENTORY_ZIP }} if-no-files-found: ignore - name: "📋 Playwright step summary" @@ -290,13 +409,13 @@ jobs: - name: "⬆️ Upload Playwright artifacts" if: ${{ always() && !env.ACT }} - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v7.0.1 with: - name: playwright-swarm-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} + name: playwright-${{ matrix.artifact }} path: /tmp/playwright-artifacts/ if-no-files-found: ignore - name: "🧹 Cleanup" - if: always() + if: ${{ always() && matrix.mode == 'swarm' }} timeout-minutes: 15 run: scripts/tests/deploy/swarm/utils/clean/teardown.sh diff --git a/.github/workflows/call-test-dns.yml b/.github/workflows/call-test-dns.yml index 18354b8b2c..133b4194bf 100644 --- a/.github/workflows/call-test-dns.yml +++ b/.github/workflows/call-test-dns.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: inputs: distros: - description: "Space-separated distro list (e.g. 'arch debian ubuntu')" + description: "🐧 Space-separated distro list (e.g. 'arch debian ubuntu')" required: false default: "debian" type: string diff --git a/.github/workflows/call-test-install-make.yml b/.github/workflows/call-test-install-make.yml index 5b2c740624..06acb0304f 100644 --- a/.github/workflows/call-test-install-make.yml +++ b/.github/workflows/call-test-install-make.yml @@ -4,7 +4,6 @@ on: workflow_call: permissions: - actions: write contents: read packages: read diff --git a/.github/workflows/call-test-install-pkgmgr.yml b/.github/workflows/call-test-install-pkgmgr.yml index 34f680ca94..836eb87a31 100644 --- a/.github/workflows/call-test-install-pkgmgr.yml +++ b/.github/workflows/call-test-install-pkgmgr.yml @@ -4,7 +4,6 @@ on: workflow_call: permissions: - actions: write contents: read packages: read diff --git a/.github/workflows/call-test-instructions.yml b/.github/workflows/call-test-instructions.yml index a230f60057..fe3bc1be60 100644 --- a/.github/workflows/call-test-instructions.yml +++ b/.github/workflows/call-test-instructions.yml @@ -25,21 +25,21 @@ on: workflow_dispatch: inputs: distros: - description: "Space-separated distro list" + description: "🐧 Space-separated distro list" required: true type: string role: - description: "Role to test; empty picks one at random" + description: "📖 Role to test; empty picks one at random" required: false type: string default: "" priority: - description: "Space-separated app ids; a random one is preferred over whitelist" + description: "⭐ App ids; a random one is preferred over the whitelist" required: false type: string default: "" whitelist: - description: "Space-separated app ids; a random one is used when no role or priority is given" + description: "🎯 App ids; a random one runs when no role or priority is given" required: false type: string default: "" diff --git a/.github/workflows/call-test-runner-smoke.yml b/.github/workflows/call-test-runner-smoke.yml index d12c530dbd..18f5065767 100644 --- a/.github/workflows/call-test-runner-smoke.yml +++ b/.github/workflows/call-test-runner-smoke.yml @@ -1,10 +1,11 @@ -name: "🏃 Test: Runner smoke (self-hosted)" +name: "🏃 Test: Runner smoke" +run-name: "🏃 Test: Runner smoke (self-hosted)" on: workflow_dispatch: inputs: ref: - description: "Git ref to check out (branch, tag, or SHA). Defaults to the repo default branch." + description: "🔀 Git ref to check out; empty takes the repo default branch." required: false default: "" type: string @@ -49,6 +50,6 @@ jobs: docker run --rm hello-world - name: 🔍 Dump runner state (on failure) - if: failure() + if: failure() || cancelled() shell: bash run: ./scripts/github/runner/dump_state.sh "runner-smoke failure" diff --git a/.github/workflows/call-test-workspace.yml b/.github/workflows/call-test-workspace.yml index 2e1b8531d6..64f255f51a 100644 --- a/.github/workflows/call-test-workspace.yml +++ b/.github/workflows/call-test-workspace.yml @@ -2,51 +2,65 @@ name: "💻 Test: Workspace" on: workflow_dispatch: + inputs: + workspace_track: + description: "🧑‍💻 Track per distro: rotate splits compose/swarm, or pin one" + type: choice + default: rotate + options: [rotate, compose, swarm] workflow_call: + inputs: + workspace_track: + type: string + default: rotate permissions: - actions: write contents: read packages: read jobs: prepare: - name: 📋 Workspace Matrix + name: 🧑‍💻 Workspace Matrix runs-on: ubuntu-latest timeout-minutes: 5 outputs: - images: ${{ steps.matrix.outputs.images }} + matrix: ${{ steps.matrix.outputs.matrix }} steps: - name: ⬇️ Checkout repository uses: actions/checkout@v7.0.0 - - name: 🐍 Read the distro SPOT + - name: 🐍 Assign one workspace track per distro id: matrix shell: bash + env: + WORKSPACE_TRACK: ${{ inputs.workspace_track }} + RUN_NUMBER: ${{ github.run_number }} run: | set -euo pipefail - images="$(python3 -m cli.meta.ci.dev_runtime images)" - echo "images=${images}" | tee -a "$GITHUB_OUTPUT" + matrix="$(python3 -m cli.meta.ci.dev_runtime matrix \ + --mode "${WORKSPACE_TRACK:-rotate}" --run "${RUN_NUMBER:-0}")" + echo "matrix=${matrix}" | tee -a "$GITHUB_OUTPUT" test-workspace: - name: 🧑‍💻 Workspace (${{ matrix.dev_runtime_image }}) + name: ${{ matrix.icon }} Workspace (${{ matrix.label }}) runs-on: ubuntu-latest timeout-minutes: 345 needs: prepare concurrency: - group: infinito-workspace-${{ matrix.dev_runtime_image }} + group: infinito-workspace-${{ matrix.image }}-${{ matrix.track }} cancel-in-progress: false queue: max strategy: fail-fast: false matrix: - dev_runtime_image: ${{ fromJson(needs.prepare.outputs.images) }} + include: ${{ fromJson(needs.prepare.outputs.matrix) }} env: - DEV_RUNTIME_IMAGE: ${{ matrix.dev_runtime_image }} + DEV_RUNTIME_IMAGE: ${{ matrix.image }} + INFINITO_WORKSPACE_TRACKS: base ${{ matrix.track }} NIX_CONFIG: | access-tokens = github.com=${{ secrets.GITHUB_TOKEN }} INFINITO_CACHE_REGISTRY_MAX_SIZE: 16g @@ -76,9 +90,11 @@ jobs: shell: bash run: | set -euo pipefail + make dotenv { grep '^INFINITO_RESCUE_DIAGNOSTICS_BASE=' default.env - echo "INFINITO_WORKSPACE_SLUG=$(printf '%s' "${DEV_RUNTIME_IMAGE}" | tr '/:' '--')" + grep '^INFINITO_DNS53_SAMPLER_LOG=' .env + echo "INFINITO_WORKSPACE_SLUG=$(printf '%s' "${DEV_RUNTIME_IMAGE}" | tr '/:' '--')-${{ matrix.track }}" } >> "$GITHUB_ENV" - name: "📥 Resolve the workspace distro" @@ -100,6 +116,7 @@ jobs: -e GITHUB_REPOSITORY_OWNER="${{ github.repository_owner }}" \ -e GITHUB_SHA="${{ github.sha }}" \ -e DEV_RUNTIME_IMAGE \ + -e INFINITO_WORKSPACE_TRACKS \ -e INFINITO_DISTRO \ -e INFINITO_IMAGE="infinito-${INFINITO_DISTRO}" \ -e INFINITO_PULL_POLICY=never \ @@ -119,11 +136,11 @@ jobs: -w "${HOST_WORKDIR}" \ "${DEV_RUNTIME_IMAGE}" \ bash -lc ' - bash ./scripts/tests/environment/00_orchestrator.sh + bash ./scripts/tests/workspace/00_orchestrator.sh ' - name: 🩺 Capture rescue diagnostics - if: failure() + if: failure() || cancelled() timeout-minutes: 15 shell: bash run: | diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml new file mode 100644 index 0000000000..b992ba236f --- /dev/null +++ b/.github/workflows/call-validation.yml @@ -0,0 +1,204 @@ +# The gate every entry point passes before it spends a runner on anything else. +# What it checks depends on the event and on the inputs it is handed, not on +# which workflow called it: a pull request gets its branch prefix and its merge +# base asserted, a run that carries a selection gets that selection checked +# against the branch it would deploy from, and a fork PR waits here for the +# privileged run's images. Nothing downstream may start before this is green, +# so a refusal fails the whole run instead of surfacing as one red job beside a +# chain that keeps going. +# +# Under pull_request_target the token is privileged and the head belongs to the +# fork, so the code under test is not checked out at all there and the branch +# prefix is validated from the calling ref's own tooling. Only the merge +# assertion and the selection check read the head, and both are reachable on +# pull_request and workflow_dispatch alone. +name: "✅ CI: Validation" + +on: + workflow_call: + inputs: + pr_scope: + description: "🔎 Detected PR scope. Set: the branch prefix is validated against it. Empty: not a PR entry, skipped." + required: false + type: string + default: "" + whitelist: + description: "🎯 Selection to validate against this branch. Empty: nothing to check." + required: false + type: string + default: "" + priority: + description: "⭐ Priority line to validate against this branch. Empty: nothing to check." + required: false + type: string + default: "" + mode: + description: "🚀 Deploy modes the run draws from; narrows what a pinned mode may be." + required: false + type: string + default: "auto" + tor: + description: "🧅 Tor axis of the run; decides whether a pinned onion state is reachable." + required: false + type: string + default: "auto" + distros: + description: "🐧 Distro pool of the run; narrows what a pinned distro may be." + required: false + type: string + default: "" + filesystem: + description: "🗄️ Filesystem pool of the run; narrows what a pinned filesystem may be." + required: false + type: string + default: "" + lifecycles: + description: "♻️ Lifecycle envelope; a role outside it has no row to match." + required: false + type: string + default: "" + fork_prereqs: + description: "🍴 Wait for the privileged fork run's images. Off for entries that build their own." + required: false + type: boolean + default: false + trusted_pr: + description: "🛡️ True when the PR carries the maintainer Trusted label; skips the fork-prereq wait." + required: false + type: boolean + default: false + image_wait_attempts: + description: "🔁 Polling attempts while waiting on prebuilt or mirrored images." + required: false + type: string + default: "1980" + image_wait_sleep_seconds: + description: "⏱️ Polling interval in seconds while waiting on images." + required: false + type: string + default: "10" + +permissions: + contents: read + +jobs: + validation: + name: ✅ Validation + runs-on: ubuntu-latest + steps: + - name: ⬇️ Checkout the calling ref for its tooling + uses: actions/checkout@v7.0.0 + with: + path: .base-tooling + persist-credentials: false + + - name: ⬇️ Checkout the code under test + if: ${{ github.event_name != 'pull_request_target' }} + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: ${{ inputs.pr_scope != '' && '0' || '1' }} + path: pr-head + persist-credentials: false + + - name: 🧭 Validate the branch prefix against the detected scope + if: ${{ inputs.pr_scope != '' }} + working-directory: .base-tooling + env: + PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} + PR_SCOPE: ${{ inputs.pr_scope }} + run: ./scripts/meta/resolve/pr/branch_prefix.sh + + - name: 🔀 Assert the base branch is fully merged into the PR head + if: ${{ github.event_name == 'pull_request' && inputs.pr_scope != '' }} + working-directory: pr-head + env: + INFINITO_MAIN_REMOTE: origin + INFINITO_MAIN_BRANCH: ${{ github.event.pull_request.base.ref }} + run: bash "${GITHUB_WORKSPACE}/.base-tooling/scripts/git/assert/main_merged.sh" + + - name: 🔧 Set up Python + if: ${{ inputs.whitelist != '' || inputs.priority != '' }} + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pr-head/pyproject.toml + + - name: 📦 Install project (host venv) + if: ${{ inputs.whitelist != '' || inputs.priority != '' }} + working-directory: pr-head + shell: bash + run: make install + + - name: 🎯 Validate the selection against this branch + if: ${{ inputs.whitelist != '' || inputs.priority != '' }} + working-directory: pr-head + shell: bash + env: + INPUT_WHITELIST: ${{ inputs.whitelist }} + INPUT_PRIORITY: ${{ inputs.priority }} + INPUT_MODE: ${{ inputs.mode }} + INPUT_TOR: ${{ inputs.tor }} + INPUT_DISTROS: ${{ inputs.distros }} + INPUT_FILESYSTEM: ${{ inputs.filesystem }} + INPUT_LIFECYCLES: ${{ inputs.lifecycles }} + run: ./scripts/github/validate/selection.sh + + wait-fork-prereq-run: + name: ⏳ Wait for fork run + if: ${{ inputs.fork_prereqs }} + runs-on: ubuntu-latest + env: + WAIT_REQUIRED: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && !inputs.trusted_pr }} + steps: + - name: 🏷️ Mark fork prerequisites as ready outside fork PRs or for trusted PRs + if: ${{ env.WAIT_REQUIRED != 'true' }} + shell: bash + run: | + set -euo pipefail + echo "Fork prerequisites are implicitly ready (non-fork PR or '🛡️ Trusted' label)." + + - name: ⬇️ Checkout trusted workflow repo (helpers) + if: ${{ env.WAIT_REQUIRED == 'true' }} + uses: actions/checkout@v7.0.0 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + + - name: 🔑 Login to GHCR for CI image checks + if: ${{ env.WAIT_REQUIRED == 'true' }} + uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: ⏳ Wait for privileged fork CI images + if: ${{ env.WAIT_REQUIRED == 'true' }} + shell: bash + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + WORKFLOW_FILE: entry-pr-change-orchestrate.yml + TARGET_EVENT: pull_request_target + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_UPDATED_AT: ${{ github.event.pull_request.updated_at }} + INFINITO_DISTROS: "arch debian ubuntu fedora centos" + IMAGE_TAG: ci-${{ github.sha }} + WAIT_ATTEMPTS: ${{ inputs.image_wait_attempts }} + WAIT_SLEEP_SECONDS: ${{ inputs.image_wait_sleep_seconds }} + run: ./scripts/meta/wait/images.sh + + fork-prereqs-ready: + name: 🚦 Gate Dependencies + needs: wait-fork-prereq-run + if: ${{ always() && inputs.fork_prereqs }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.0 + - name: ✅ Assert privileged prerequisites are ready + shell: bash + env: + RESULT: ${{ needs.wait-fork-prereq-run.result }} + run: ./scripts/github/gate/fork_prereqs.sh diff --git a/.github/workflows/cron-cleanup-stale.yml b/.github/workflows/cron-cleanup-stale.yml index 2bfe5ee646..35a5d0168e 100644 --- a/.github/workflows/cron-cleanup-stale.yml +++ b/.github/workflows/cron-cleanup-stale.yml @@ -1,4 +1,5 @@ -name: "⏰ Cleanup: Stale Repository Data" +name: "🧹 Prune stale data" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🧹 Prune stale data" on: schedule: @@ -6,15 +7,15 @@ on: workflow_dispatch: permissions: - contents: write - issues: write - pull-requests: write - packages: write + contents: read jobs: stale: name: 🏷️ Close inactive issues and pull requests runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write steps: - name: 🏷️ Mark stale issues and pull requests @@ -45,6 +46,9 @@ jobs: delete-stale-branches: name: 🌿 Delete inactive branches runs-on: ubuntu-latest + permissions: + contents: write + issues: write steps: - name: 🌿 Delete branches inactive for 360 days @@ -62,6 +66,9 @@ jobs: cleanup-ghcr-ci-images: name: 📦 Delete old GHCR CI images runs-on: ubuntu-latest + permissions: + contents: read + packages: write steps: - name: ⬇️ Checkout diff --git a/.github/workflows/cron-images-cleanup-ci.yml b/.github/workflows/cron-images-cleanup-ci.yml index b1443b559d..33b136a357 100644 --- a/.github/workflows/cron-images-cleanup-ci.yml +++ b/.github/workflows/cron-images-cleanup-ci.yml @@ -1,4 +1,5 @@ -name: "⏰ Images: Cleanup CI (GHCR)" +name: "🧹 Prune CI images" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🧹 Prune CI images" on: schedule: @@ -6,7 +7,7 @@ on: workflow_dispatch: inputs: days: - description: "Delete CI images older than N days (default: 7)" + description: "🧹 Delete CI images older than N days (default: 7)" required: false default: "7" type: string diff --git a/.github/workflows/cron-images-mirror-all.yml b/.github/workflows/cron-images-mirror-all.yml index 4094632b5a..af8df88f85 100644 --- a/.github/workflows/cron-images-mirror-all.yml +++ b/.github/workflows/cron-images-mirror-all.yml @@ -1,4 +1,5 @@ -name: "⏰ Mirror: Docker Hub → GHCR" +name: "🪞 Mirror all images" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🪞 Mirror all images" on: schedule: @@ -7,21 +8,21 @@ on: workflow_dispatch: inputs: ghcr_namespace: - description: "GHCR namespace/org (default: repository owner)" + description: "🏛️ GHCR namespace/org (default: repository owner)" required: false type: string ghcr_prefix: - description: "GHCR repo prefix (default: mirror)" + description: "🏷️ GHCR repo prefix (default: mirror)" required: false default: "mirror" type: string repo_root: - description: "Repository root path (default: .)" + description: "📁 Repository root path (default: .)" required: false default: "." type: string images_per_hour: - description: "Optional throttle: max images mirrored per hour" + description: "⏱️ Optional throttle: max images mirrored per hour" required: false type: string diff --git a/.github/workflows/cron-release-highest.yml b/.github/workflows/cron-release-highest.yml index 9551ff4e88..563e6e5b50 100644 --- a/.github/workflows/cron-release-highest.yml +++ b/.github/workflows/cron-release-highest.yml @@ -1,4 +1,5 @@ -name: "⏰ Release: Highest Missing Version" +name: "🚀 Release missing tag" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🚀 Release missing tag" on: schedule: diff --git a/.github/workflows/cron-rerun-cancelled.yml b/.github/workflows/cron-rerun-cancelled.yml deleted file mode 100644 index 706734dbfa..0000000000 --- a/.github/workflows/cron-rerun-cancelled.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: "⏰ Rerun: Cancelled Branch Runs" - -concurrency: - group: rerun-cancelled - cancel-in-progress: true - -on: - schedule: - - cron: "0 * * * *" - workflow_dispatch: - -permissions: - actions: write - contents: read - -jobs: - rerun: - name: 🔁 Rerun the failed jobs of cancelled runs - runs-on: ubuntu-latest - timeout-minutes: 15 - - steps: - - name: ⬇️ Checkout repository - uses: actions/checkout@v7.0.0 - - - name: ⏱️ Decide whether this hour is due - id: due - if: ${{ github.event_name == 'schedule' }} - shell: bash - env: - INTERVAL_MINUTES: ${{ vars.CI_RERUN_INTERVAL_MINUTES || '60' }} - run: bash scripts/github/rerun/due.sh - - - name: 🔁 Restart the failed jobs per branch - if: ${{ steps.due.outputs.due != 'false' }} - shell: bash - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - REPOSITORY: ${{ github.repository }} - MAX_ATTEMPTS: ${{ vars.CI_RERUN_MAX_ATTEMPTS || '0' }} - MAX_AGE_HOURS: ${{ vars.CI_RERUN_MAX_AGE_HOURS || '24' }} - run: bash scripts/github/rerun/cancelled_branch_runs.sh diff --git a/.github/workflows/cron-security-codeql.yml b/.github/workflows/cron-security-codeql.yml index f2c667453a..35f47e7b7f 100644 --- a/.github/workflows/cron-security-codeql.yml +++ b/.github/workflows/cron-security-codeql.yml @@ -11,7 +11,8 @@ # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # -name: "⏰ Scan: CodeQL (Advanced)" +name: "🔐 Scan with CodeQL" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🔐 Scan with CodeQL" concurrency: group: codeql-${{ github.repository }}-${{ github.ref }} @@ -22,6 +23,8 @@ on: schedule: - cron: '0 0 * * 6' +permissions: + contents: read jobs: analyze: diff --git a/.github/workflows/cron-security-scorecard.yml b/.github/workflows/cron-security-scorecard.yml index 2167093df5..69eb85746f 100644 --- a/.github/workflows/cron-security-scorecard.yml +++ b/.github/workflows/cron-security-scorecard.yml @@ -3,7 +3,8 @@ # policy, and support documentation. # nocheck: comments-valid vendored OSSF scorecard workflow; upstream comments kept verbatim -name: "⏰ Scorecard supply-chain security" +name: "🛡️ Score supply chain" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🛡️ Score supply chain" on: # For Branch-Protection check. Only the default branch is supported. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection @@ -15,6 +16,10 @@ on: push: branches: [ "main" ] +concurrency: + group: scorecard-${{ github.repository }}-${{ github.ref_name }} + cancel-in-progress: true + # Declare default permissions as read only. permissions: read-all diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index 3553c1083f..33ee4e3bcf 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -1,4 +1,5 @@ -name: "⏰ Update: Versions" +name: "🔄 Update versions" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🔄 Update versions" on: push: @@ -8,6 +9,10 @@ on: - cron: "0 0 * * 6" workflow_dispatch: +concurrency: + group: update-versions-${{ github.repository }}-${{ github.ref_name }} + cancel-in-progress: true + permissions: contents: read pull-requests: read diff --git a/.github/workflows/entry-cancel-superseded.yml b/.github/workflows/entry-cancel-superseded.yml new file mode 100644 index 0000000000..c0f789cc82 --- /dev/null +++ b/.github/workflows/entry-cancel-superseded.yml @@ -0,0 +1,76 @@ +# Deliberately without a `concurrency:` block: this workflow frees the very +# groups that block other runs, so a group of its own would deadlock it. + +name: "🚫 Cancel: Superseded Runs" + +on: + push: + branches: + - "feature/**" + - "hotfix/**" + - "fix/**" + - "update/**" + - "chore/**" + - "alert-autofix-*" + pull_request_target: + types: + - opened + - synchronize + - reopened + - ready_for_review + - labeled + +permissions: + contents: read + +jobs: + cancel-branch-runs: + name: 🚫 Cancel superseded branch runs + if: ${{ github.event_name == 'push' && github.ref_name != 'main' }} + runs-on: ubuntu-latest + permissions: + actions: write + contents: read + steps: + - name: ⬇️ Checkout repository + uses: actions/checkout@v7.0.0 + + - name: 🚫 Cancel branch runs superseded by a newer one + shell: bash + env: + BRANCH: ${{ github.ref_name }} + CURRENT_RUN_ID: ${{ github.run_id }} + KEEP_NEWEST_PER: all + FORCE_CANCEL_AFTER_SECONDS: "60" + INCLUDE_PATHS: | + .github/workflows/entry-push-latest.yml + .github/workflows/entry-manual-steer.yml + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + run: bash scripts/github/cancel/branch_runs.sh + + cancel-pull-request-runs: + name: 🚫 Cancel superseded pull request runs + if: ${{ github.event_name == 'pull_request_target' }} + runs-on: ubuntu-latest + permissions: + actions: write + contents: read + pull-requests: read + steps: + - name: ⬇️ Checkout repository + uses: actions/checkout@v7.0.0 + + - name: 🚫 Cancel pull request runs superseded by a newer one + shell: bash + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} + PR_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} + CURRENT_RUN_ID: ${{ github.run_id }} + KEEP_NEWEST_PER: event + FORCE_CANCEL_AFTER_SECONDS: "60" + INCLUDE_PATHS: .github/workflows/entry-pr-change-orchestrate.yml + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + run: bash scripts/github/cancel/pull_request_runs.sh diff --git a/.github/workflows/entry-delete-branch.yml b/.github/workflows/entry-delete-branch.yml index 080b2b3234..66f1f9e538 100644 --- a/.github/workflows/entry-delete-branch.yml +++ b/.github/workflows/entry-delete-branch.yml @@ -32,4 +32,4 @@ jobs: BRANCH: ${{ github.event.ref }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPOSITORY: ${{ github.repository }} - run: bash scripts/github/cancel/deleted_branch_runs.sh + run: bash scripts/github/cancel/branch_runs.sh diff --git a/.github/workflows/entry-manual-mirror-cleanup.yml b/.github/workflows/entry-manual-mirror-cleanup.yml index 5fb5f10bf0..b0b60f3fd6 100644 --- a/.github/workflows/entry-manual-mirror-cleanup.yml +++ b/.github/workflows/entry-manual-mirror-cleanup.yml @@ -1,20 +1,21 @@ -name: "🧹 Images: Cleanup GHCR (Private)" +name: "🧹 Images: Cleanup GHCR" +run-name: "🧹 Images: Cleanup GHCR (Private)" on: workflow_dispatch: inputs: ghcr_namespace: - description: "GHCR namespace/org (default: repository owner)" + description: "🏛️ GHCR namespace/org (default: repository owner)" required: false type: string default: "" ghcr_prefix: - description: "Package name prefix to delete (default: mirror)" + description: "🏷️ Package name prefix to delete (default: mirror)" required: false type: string default: "mirror" visibility: - description: "Visibility filter: only packages with this visibility are deleted" + description: "👁️ Visibility filter: only these packages are deleted" required: false type: choice default: "private" @@ -23,12 +24,12 @@ on: - public - internal dry_run: - description: "Dry-run: list packages that would be deleted without deleting them" + description: "🧪 Dry-run: list what would be deleted without deleting it" required: false type: boolean default: true token: - description: "Classic PAT with delete:packages scope. Leave empty to use the default GITHUB_TOKEN The default token may lack the delete:packages scope." + description: "🔑 Classic PAT with delete:packages. Empty: the default GITHUB_TOKEN" required: false type: string default: "" diff --git a/.github/workflows/entry-manual-steer.yml b/.github/workflows/entry-manual-steer.yml index 28840187a8..84464babf6 100644 --- a/.github/workflows/entry-manual-steer.yml +++ b/.github/workflows/entry-manual-steer.yml @@ -1,5 +1,5 @@ name: "🕹️ Manual" -run-name: "🕹️ ${{ inputs.mode_fail_fast && '🛑 ' || '' }}${{ inputs.sequencing != 'auto' && format('🐛{0} ', inputs.sequencing == 'serial' && '序' || '并') || '' }}${{ inputs.workspace != 'auto' && format('🧑‍💻{0} ', inputs.workspace == 'true' && '是' || '否') || '' }}${{ inputs.instructions != 'auto' && format('📖{0} ', inputs.instructions == 'true' && '是' || '否') || '' }}${{ inputs.filesystem != '' && format('🗄️{0} ', inputs.filesystem) || '' }}${{ inputs.distros != '' && format('🐧{0} ', inputs.distros) || '' }}${{ inputs.lifecycles != '' && format('♻️{0} ', inputs.lifecycles) || '' }}${{ inputs.modes != 'swarm compose host' && format('🚀{0} ', inputs.modes) || '' }}${{ inputs.priority != '' && format('⭐{0} ', inputs.priority) || '' }}${{ inputs.whitelist != '' && format('🎯{0}', inputs.whitelist) || '🔀 diff (origin/main)' }}" +run-name: "🕹️ ${{ inputs.chunk_gate && '🛑 ' || '' }}${{ inputs.offset != '0' && inputs.offset != '' && format('⏩{0} ', inputs.offset) || '' }}${{ inputs.workspace != 'auto' && format('🧑‍💻{0} ', inputs.workspace == 'true' && '是' || '否') || '' }}${{ inputs.instructions != 'auto' && format('📖{0} ', inputs.instructions == 'true' && '是' || '否') || '' }}${{ inputs.tor != 'auto' && format('{0} ', inputs.tor == 'disabled' && '🌐' || inputs.tor == 'enforced' && '🧅强制' || '🧅独占') || '' }}${{ inputs.filesystem != '' && format('🗄️{0} ', inputs.filesystem) || '' }}${{ inputs.distros != '' && format('🐧{0} ', inputs.distros) || '' }}${{ inputs.lifecycles != '' && format('♻️{0} ', inputs.lifecycles) || '' }}${{ inputs.mode != 'auto' && format('🚀{0} ', inputs.mode) || '' }}${{ inputs.priority != '' && format('⭐{0} ', inputs.priority) || '' }}${{ inputs.whitelist != '' && format('🎯{0}', inputs.whitelist) || '🔀 diff (origin/main)' }}" concurrency: group: global-ci-${{ github.repository }}-${{ github.ref_name }} @@ -9,17 +9,17 @@ on: workflow_dispatch: inputs: distros: - description: "🐧 Distros to sweep. Empty: one at random. Example: 'arch debian'" + description: "🐧 Distro pool the rows are spread over. Empty: all five. Example: 'arch debian'" required: false default: "" type: string priority: - description: "⭐ Roles to deploy first. The rest waits until they are green." + description: "⭐ Roles to lead, in every combination left open (see README)" required: false default: "" type: string whitelist: - description: "🎯 Roles to deploy. Empty: diff vs origin/main. '__ALL__': every role." + description: "🎯 Roles to deploy. Empty: diff vs origin/main. '__ALL__': every role" required: false default: "" type: string @@ -28,32 +28,48 @@ on: required: false default: "" type: string - modes: - description: "🚀 Deploy modes to test. Only the listed ones run their deploy job." - required: false - default: "swarm compose host" - type: string - filesystem: - description: "🗄️ Space-separated filesystems the per-distro pick draws from (ext4, btrfs, zfs). Empty: all three." - required: false - default: "" - type: string - sequencing: - description: "🐛 Deploy-mode order per line. 'serial': swarm, then compose, then host. 'parallel': all at once. 'auto': serial above 65 jobs per line." + mode: + description: "🚀 Deploy mode. 'auto' rotates a row over the modes its role offers" required: false default: "auto" type: choice options: - "auto" - - "serial" - - "parallel" - mode_fail_fast: - description: "🛑 Stop a serial line at its first failed mode. Off: keep deploying the remaining modes." + - "host" + - "compose" + - "swarm" + filesystem: + description: "🗄️ Filesystem pool the rows are spread over. Empty: ext4, btrfs, zfs" + required: false + default: "" + type: string + tor: + description: "🧅 Tor axis for swarm and compose; the four values are in the README" + required: false + default: "auto" + type: choice + options: + - "auto" + - "enforced" + - "exclusive" + - "disabled" + offset: + description: "⏩ Where chunk 0 starts: a row count, or a token like web-app-x#2" + required: false + default: "0" + type: string + chunk_gate: + description: "🛑 Stop the chunk chain at its first failed chunk" required: false default: true type: boolean + sweep: + description: "🔁 Sweep number driving the mode and tor rotation. Empty: the run number" + required: false + default: "" + type: string workspace: - description: "🧑‍💻 Run the workspace test (dev-runtime image matrix). 'auto' runs it on a global scope only." + description: "🧑‍💻 Run the workspace test. 'auto': on a global scope only" required: false default: "auto" type: choice @@ -61,8 +77,17 @@ on: - "auto" - "true" - "false" + workspace_track: + description: "🧑‍💻 Workspace track per distro. 'rotate' splits compose and swarm" + required: false + default: "rotate" + type: choice + options: + - "rotate" + - "compose" + - "swarm" instructions: - description: "📖 Run the instructions test (role README Production command). 'auto' runs it on a global scope only." + description: "📖 Run the instructions test. 'auto': on a global scope only" required: false default: "auto" type: choice @@ -72,40 +97,29 @@ on: - "false" permissions: contents: read - packages: write - security-events: write - actions: write - issues: write jobs: - pick-distro: - name: 🎲 Pick distro(s) - runs-on: ubuntu-latest - outputs: - distros: ${{ steps.pick.outputs.distros }} - steps: - - uses: actions/checkout@v7.0.0 - - - id: pick - shell: bash - env: - INPUT_DISTROS: ${{ inputs.distros }} - run: ./scripts/github/resolve/manual_distros.sh - ci-orchestrator: name: 🎛️ Orchestrate CI (manual) - needs: pick-distro + permissions: + actions: read + contents: read + packages: write + security-events: write + issues: write uses: ./.github/workflows/call-orchestrator.yml with: - distros: ${{ needs.pick-distro.outputs.distros }} + distros: ${{ inputs.distros }} whitelist: ${{ inputs.whitelist }} lifecycles: ${{ inputs.lifecycles }} - modes: ${{ inputs.modes }} + mode: ${{ inputs.mode }} priority: ${{ inputs.priority }} - sequencing: ${{ inputs.sequencing }} - mode_fail_fast: ${{ inputs.mode_fail_fast }} + sweep: ${{ inputs.sweep }} + offset: ${{ inputs.offset }} + chunk_gate: ${{ inputs.chunk_gate }} filesystem: ${{ inputs.filesystem }} workspace: ${{ inputs.workspace }} + workspace_track: ${{ inputs.workspace_track }} instructions: ${{ inputs.instructions }} - force_cancel_in_progress: true + tor: ${{ inputs.tor }} secrets: inherit diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index 80b593540d..36d4aa63ee 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -23,10 +23,7 @@ concurrency: cancel-in-progress: true permissions: - actions: write contents: read - packages: write - security-events: write jobs: detect-pr-scope: @@ -48,44 +45,19 @@ jobs: PR_NUMBER: ${{ github.event.pull_request.number }} run: ./scripts/meta/resolve/pr/scope.sh - validate-pr-branch-prefix: - name: 🧭 Validate PR branch prefix + validation: + name: 🧭 PR scope needs: detect-pr-scope if: ${{ github.event_name == 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository }} - runs-on: ubuntu-latest - steps: - - name: ⬇️ Checkout - uses: actions/checkout@v7.0.0 - - - name: ✅ Validate branch prefix for detected scope - env: - PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} - PR_SCOPE: ${{ needs.detect-pr-scope.outputs.scope }} - run: ./scripts/meta/resolve/pr/branch_prefix.sh - - assert-main-merged: - name: 🔀 Assert main is merged - needs: detect-pr-scope - if: ${{ github.event_name == 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository }} - runs-on: ubuntu-latest - steps: - - name: ⬇️ Checkout PR head - uses: actions/checkout@v7.0.0 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 0 - - - name: ✅ Assert the base branch is fully merged into the PR head - env: - INFINITO_MAIN_REMOTE: origin - INFINITO_MAIN_BRANCH: ${{ github.event.pull_request.base.ref }} - run: bash scripts/git/assert/main_merged.sh + uses: ./.github/workflows/call-validation.yml + with: + pr_scope: ${{ needs.detect-pr-scope.outputs.scope }} pr-scope-gate: name: 🚦 Gate PR scope needs: - detect-pr-scope - - validate-pr-branch-prefix + - validation if: ${{ needs.detect-pr-scope.outputs.run_ci_orchestrator == 'false' }} runs-on: ubuntu-latest steps: @@ -97,7 +69,9 @@ jobs: detect-affected-roles: name: 🧭 Detect affected roles - needs: detect-pr-scope + needs: + - detect-pr-scope + - validation if: ${{ needs.detect-pr-scope.outputs.run_ci_orchestrator == 'true' }} runs-on: ubuntu-latest outputs: @@ -130,11 +104,11 @@ jobs: ci-orchestrator: needs: - detect-pr-scope - - validate-pr-branch-prefix + - validation - detect-affected-roles if: ${{ github.event_name == 'pull_request' && needs.detect-pr-scope.outputs.run_ci_orchestrator == 'true' }} permissions: - actions: write + actions: read contents: read packages: write security-events: write @@ -148,7 +122,7 @@ jobs: prepare-fork-merge-ref: needs: - detect-pr-scope - - validate-pr-branch-prefix + - validation if: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository && needs.detect-pr-scope.outputs.run_ci_orchestrator == 'true' }} runs-on: ubuntu-latest outputs: @@ -168,6 +142,9 @@ jobs: build-ci-images-fork: needs: prepare-fork-merge-ref + permissions: + contents: read + packages: write uses: ./.github/workflows/call-images-build-ci.yml with: distros: "arch debian ubuntu fedora centos" @@ -179,6 +156,9 @@ jobs: images-mirror-missing-fork: needs: prepare-fork-merge-ref + permissions: + contents: read + packages: write uses: ./.github/workflows/call-images-mirror-missing.yml with: repo_root: _pr_source diff --git a/.github/workflows/entry-pr-closed-cancel-workflows.yml b/.github/workflows/entry-pr-closed-cancel-workflows.yml index 9b486b6360..2fa6071c79 100644 --- a/.github/workflows/entry-pr-closed-cancel-workflows.yml +++ b/.github/workflows/entry-pr-closed-cancel-workflows.yml @@ -6,9 +6,14 @@ on: - closed - converted_to_draft +concurrency: + group: pr-ci-${{ github.repository }}-pull_request-pr-${{ github.event.pull_request.number }} + cancel-in-progress: true + permissions: actions: write contents: read + pull-requests: read jobs: cancel-pr-runs: diff --git a/.github/workflows/entry-push-latest.yml b/.github/workflows/entry-push-latest.yml index dc2894153e..171be265b0 100644 --- a/.github/workflows/entry-push-latest.yml +++ b/.github/workflows/entry-push-latest.yml @@ -2,7 +2,7 @@ name: "📤 Push" concurrency: group: global-ci-${{ github.repository }}-${{ github.ref_name }} - cancel-in-progress: ${{ vars.CI_CANCEL_IN_PROGRESS != 'false' }} + cancel-in-progress: ${{ github.ref_name != 'main' }} on: push: @@ -16,16 +16,14 @@ on: - "alert-autofix-*" permissions: - contents: write - packages: write - actions: write - security-events: write - issues: write + contents: read jobs: sync-main: name: 🔄 Sync main runs-on: ubuntu-latest + permissions: + contents: write steps: - name: ⬇️ Checkout repository uses: actions/checkout@v7.0.0 @@ -44,6 +42,9 @@ jobs: name: 🧭 Decide CI policy needs: sync-main runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read outputs: should_run: ${{ steps.decide.outputs.should_run }} skip_reason: ${{ steps.decide.outputs.skip_reason }} @@ -83,13 +84,12 @@ jobs: echo "Skipping CI for commit ${GITHUB_SHA}." echo "Reason: ${{ needs.run-policy.outputs.skip_reason }}" - pick-distro: + detect-release: if: needs.run-policy.outputs.should_run == 'true' needs: run-policy - name: 🎲 Pick distro(s) + name: 🏷️ Detect release tag runs-on: ubuntu-latest outputs: - distros: ${{ steps.pick.outputs.distros }} is_version: ${{ steps.pick.outputs.is_version }} version_tag: ${{ steps.pick.outputs.version_tag }} steps: @@ -101,7 +101,7 @@ jobs: - id: pick shell: bash - run: bash scripts/github/resolve/pick_distro.sh + run: bash scripts/github/resolve/release/tag.sh resolve-priority: if: needs.run-policy.outputs.should_run == 'true' @@ -127,20 +127,25 @@ jobs: name: 🎶 Orchestrate CI needs: - run-policy - - pick-distro + - detect-release - resolve-priority + permissions: + actions: read + contents: read + packages: write + security-events: write + issues: write uses: ./.github/workflows/call-orchestrator.yml with: - distros: ${{ needs.pick-distro.outputs.distros }} priority: ${{ needs.resolve-priority.outputs.priority }} secrets: inherit release-guard: name: "🛡️ Guard release" - if: needs.run-policy.outputs.should_run == 'true' && needs.pick-distro.outputs.is_version == 'true' + if: needs.run-policy.outputs.should_run == 'true' && needs.detect-release.outputs.is_version == 'true' needs: - run-policy - - pick-distro + - detect-release - ci-orchestrator runs-on: ubuntu-latest outputs: @@ -162,17 +167,20 @@ jobs: id: guard shell: bash env: - VERSION_TAG: ${{ needs.pick-distro.outputs.version_tag }} + VERSION_TAG: ${{ needs.detect-release.outputs.version_tag }} run: bash scripts/github/release/guard.sh release-version: name: 🚀 Release version needs: - run-policy - - pick-distro + - detect-release - release-guard if: needs.run-policy.outputs.should_run == 'true' && needs.release-guard.outputs.allowed == 'true' + permissions: + contents: read + packages: write uses: ./.github/workflows/call-release-version.yml with: - tag: ${{ needs.pick-distro.outputs.version_tag }} + tag: ${{ needs.detect-release.outputs.version_tag }} secrets: inherit diff --git a/.gitignore b/.gitignore index de4f7e28df..16bbaa26aa 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ # NEVER TOUCH THE .dockerignore, BECAUSE IT ANYHOW WILL BE OVERWRITTEN site.retry +.cache +.ansible/ +.stack-torn-down *__pycache__ compose.cache.override.yml venv @@ -20,12 +23,16 @@ build/* .claude-* collections/ .env +.onion-identity/ custom.env logs/ job-logs.txt *.lock node_modules/ +vendor/ +.phpunit.result.cache inventories/production/ +/core.* # No-op for Git (ignored implicitly), but Docker needs .git in its ignore-list — keeps make dockerignore as a pure cat of this file. .git diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index 2a34f895d9..06f5549299 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -29,6 +29,8 @@ ], "ignores": [ "node_modules/**", + "vendor/**", + ".cache/**", ".git/**", "venv/**", ".venv/**", diff --git a/.sqlfluff b/.sqlfluff new file mode 100644 index 0000000000..21e374f1f4 --- /dev/null +++ b/.sqlfluff @@ -0,0 +1,11 @@ +[sqlfluff] +# Postgres is the majority engine. A role whose meta/services.yml declares +# `mariadb:` instead overrides this with its own .sqlfluff beside the files. +dialect = postgres +templater = placeholder + +# The shipped SQL is executed through psycopg, so `%(name)s` parameter markers +# are the driver's, not SQL. Without this the parser rejects every file that +# takes an argument. +[sqlfluff:templater:placeholder] +param_style = pyformat diff --git a/.stylelintrc.json b/.stylelintrc.json new file mode 100644 index 0000000000..90d8894e28 --- /dev/null +++ b/.stylelintrc.json @@ -0,0 +1,3 @@ +{ + "rules": {} +} diff --git a/CHANGELOG.md b/CHANGELOG.md index db1af5103b..3ccaf1302e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,152 @@ # Changelog +## [13.0.0] - 2026-08-26 + +* **Tor as a first-class deployment axis.** The new *svc-net-tor* role routes onion + names through Tor via DNS instead of per-app proxies, offers a chutney flavor for + private-net test deployments, and ties its dnsmasq listener to ownership rather than + the deploy mode. Applications follow: server-side OIDC discovery and token exchange + reach plaintext onion issuers through the SOCKS proxy (WordPress, Joomla, PeerTube, + Mobilizon, EspoCRM, Nextcloud), session cookies drop the *Secure* flag where an onion + cannot carry it (Taiga, Pixelfed, Joomla), and mail authenticates on the submission + port the onion relay actually serves. The deploy matrix gained a tor axis with an + onion marker plus enforced and exclusive modes, and lint now requires the onion in + every variant. See the [svc-net-tor](roles/svc-net-tor/README.md) README. + +* **Single sign-on across protocols and domains.** Keycloak imports a SAML client for + every app that asks for one; SuiteCRM authenticates against it via SAML instead of a + proxy, and Shopware provisions its admin through AdminOpenAuth with the front and + back channel split. Sessions are shared across app domains, the issuer is pinned to + the canonical OIDC URL, each consumer's redirect scheme resolves on its own side, and + the logout sweep runs where the visitor is looking. Directory users are read through + one lookup so seeding cannot diverge. + +* **One CI chain instead of four workflows.** The deploy workflows collapse into a + single chunk chain gated by one validation job, with every variant getting its own + row and rotating distro, filesystem and tor axes. Selection tokens pin deploy axes, + retriggers reproduce the exact selection of the source run in every mode, and the + regular line resumes where the source stopped. Fork code no longer runs with the base + repository token, workflow tokens are scoped to the jobs that need them, superseded + runs are force-cancelled, and a mid-run budget SIGKILL is counted as skipped rather + than green. Apt call sites are bounded so a stalled mirror cannot burn a job budget. + +* **Restore verified against real dumps.** The *recover* CLI replays a generation's + database and cluster dumps, reads the generation's own layout instead of guessing it, + and places each dump by the engine the backup observed rather than by name alone. The + *svc-bkp-volume-2-local* drill now empties every volume it claims to test, fails on a + database that was never dumped, and stops the backup timers before it goes + destructive. Baudolo is pinned per host, its contract read from baudolo itself. + +* **A probe for every container.** Health checks are composed from prefixes and are + mandatory: every declared image either carries a probe or states why it cannot have + one, enforced from both sides. Probes hit the port the container actually binds, no + longer derive an HTTP Host from a kernel hostname, and are defined once instead of per + proxy. Rescue diagnostics pin the dnsmasq listener loss to its moment, sample what the + resolver answers rather than just its socket, probe the daemon.json upstreams, and + record the whole boot instead of the last 10 000 lines. + +* **Single points of truth, enforced by lint.** The new *sys-lint* role pins the + GitHub-release lint tools. Every mount target has one spot in *meta/volumes.yml* and + container paths are derived from it, *default.env* is the enforced source of the + primary domain, *container_backup* is rejected where no volume exists, and role + credentials live at *meta/secrets.yml*. Linters no longer read gitignored build + output, comments are checked in every file rather than only changed ones, and every + shipped script requires a mirrored unit test. + +* **Tests in every language the project ships.** The quality gate parses each shipped + language and runs its unit suite; the PHP and Ruby interpreters are baked into the + image, and the JavaScript, PHP and Ruby suites are reported in the CI summary + alongside Python. Playwright stages the persona flows once per run and mounts them + read-only, and the workspace environment suite splits into base, compose and swarm + tracks. + +* **Swarm and proxy operation.** Convergence gates read one budget sized for a real + stack, print every task row when a stack fails to converge, and give up on a terminal + task; the deployment mode a stack was deployed with is resolved instead of assumed. + OpenResty reloads a vhost, lua or redirect config instead of redeploying the task. + GitLab ships its config trees as swarm configs rather than host binds, and role + templates expand through a lookup instead of inline Jinja. + +* **New and reshaped roles.** *sys-svc-nss* is split out of *sys-hostname*, + *web-svc-mirror* serves frontend assets as a privacy proxy, PeerTube becomes + clearnet-only, and roles that could not run were deleted rather than repaired. CLI + tools install via pip instead of pkgmgr. + +* **Image and dependency version jumps (net since 12.0.0):** + + *Applications* + * *web-app-erpnext*: v16.26.2 to v16.32.3 + * *web-app-gitlab*: v19.1.2 to v19.3.0 (all six CNG component images) + * *web-app-semaphore*: v2.18.25 to v2.19.8 + * *web-app-nextcloud*: PHP 33-fpm-alpine to 34-fpm-alpine, nginx 1.31.2 to 1.31.3 + * *web-app-shopware*: 6.7.8.2 to 6.7.13.0, OpenSearch 3.7.0 to 3.8.0 + * *web-app-matomo*: 5.11.2 to 5.13.0 + * *web-app-matrix*: Synapse v1.156.0 to v1.159.0, Element v1.12.23 to v1.12.26 + * *web-app-mattermost*: 11.9.0 to 11.10.1 + * *web-app-keycloak*: 26.7.0 to 26.7.2, oauth2-proxy v7.15.3 to v7.15.4 + * *web-app-gitea*: 1.26.4 to 1.27.2 + * *web-app-funkwhale*: 2.0.6 to 2.0.9 (api and front) + * *web-app-penpot*: 2.16.2 to 2.17.1 (frontend, backend, exporter) + * *web-app-espocrm*: 10.0.2 to 10.0.6 + * *web-app-opencloud*: 7.2.1 to 7.2.4 + * *web-app-seaweedfs*: 4.39 to 4.44 + * *web-app-snipe-it*: v8.6.3-alpine to v8.7.2-alpine + * *web-app-wordpress*: 7.0.1 to 7.1.0 + * *web-app-peertube*: v8.2.2 to v8.2.4 + * *web-app-joomla*: 6.1.2-php8.3-apache to 6.1.3-php8.3-apache + * *web-app-jira*: 11.3.8 to 11.3.10 + * *web-app-confluence*: 10.2.14 to 10.2.15 + * *web-app-baserow*: 2.3.1 to 2.3.3 + * *web-app-flowise*: 3.1.3 to 3.1.4 + * *web-app-mailu*: 1.5.3 to 1.5.4 + * *web-app-pgadmin*: 9.16 to 9.17 + * *web-app-prometheus*: Prometheus v3.13.1 to v3.14.0, Alertmanager v0.33.1 to + v0.34.0, node-exporter v1.12.0 to v1.12.1 + * *web-app-opentalk*: LiveKit v1.13.3 to v1.13.5, RabbitMQ 4.3.2 to 4.3.4; the + frontend (v2.9.0), controller (v0.34.1) and recorder (v0.16.2) stay pinned until + the set is released as a bundle and *recorder.toml* is migrated + * *web-app-magento*: OpenSearch 3.7.0 to 3.8.0; PHP held at 8.4-fpm and MariaDB at + 11.4, both deliberately fenced against the image bot + * *web-app-socialhome*: newly pinned to 2026.6.16 + * *web-app-bluesky* and *web-app-bridgy-fed*: upstream git refs pinned to commits + + *Services and infrastructure* + * *svc-ai-ollama*: 0.31.2 to 0.32.15 + * *svc-db-elasticsearch*: 9.4.3 to 9.5.2 + * *svc-db-qdrant*: v1.18.2 to v1.19.0 + * *svc-runner*: Ubuntu 24.04 to 26.04 + * *sys-ctl-hlth-csp*: 2.1.2 to 2.2.1 + * *web-svc-coturn*: 4.14.0 to 4.17.2 + * *web-svc-logout*: *latest* to universal-logout v1.3.1 + * *web-svc-xmpp*: 26.04 to 26.07 + * *test-e2e-playwright*: v1.61.1-noble to v1.62.1-noble + * *svc-net-tor*: newly on debian trixie-slim + * *svc-bkp-volume-2-local*: newly on alpine 3.24 + + *Toolchain and dependencies* + * *backup-docker-to-local* (*baudolo*): pinned to 7.0.1, via 6.0.0 and 7.0.0 + * *ruff*: 0.16.0 to 0.16.4 + * *@playwright/test*: ^1.61.1 to ^1.62.1 + * *eslint*: ^10.6.0 to ^10.9.0, *globals*: ^17.7.0 to ^17.9.0 + * *stylelint*: ^16.0.0 added + * *brace-expansion*: overridden to ^5.0.9, past three DoS advisories + * *keycloak-js*: 24.0.5 to 26.2.4, loaded as an ES module + * *bootstrap*: 5.3.3 to 5.3.8, *@fortawesome/fontawesome-free*: 6.5.1 to 7.3.1 + * *roles/sys-lint* pins the GitHub-release tools: actionlint v1.7.12, + hadolint v2.15.1, shfmt v3.13.1 + +**Renamed** + +* Role credential declarations move from *meta/credentials.yml* to *meta/secrets.yml*, + addressed at *secrets.credentials* like every other meta file. +* The NSS half of *sys-hostname* becomes its own role, *sys-svc-nss*. + +**Contributors** + +* [Kevin Veen-Birkenbach](https://veen.world): Tor deployment axis, SAML and + cross-domain SSO, CI chunk chain, generation-level recovery, health-check and + lint enforcement, multi-language test suites + ## [12.0.0] - 2026-08-08 * **Docker Swarm as a second deployment mode.** Roles can now be deployed across diff --git a/Dockerfile b/Dockerfile index afed3c9609..f61529fc35 100644 --- a/Dockerfile +++ b/Dockerfile @@ -30,11 +30,12 @@ COPY . ${INFINITO_SRC_DIR} # hadolint ignore=DL3008,DL3033,DL3041,SC1090 RUN set -euo pipefail; \ - source <(grep -hE '^INFINITO_(PYTHON|DOCKER_CLI|PACKAGE|FILESYSTEM)_INSTALL_SCRIPT=' "${INFINITO_SRC_DIR}/default.env"); \ + source <(grep -hE '^INFINITO_(PYTHON|DOCKER_CLI|PACKAGE|FILESYSTEM|INTERPRETERS)_INSTALL_SCRIPT=' "${INFINITO_SRC_DIR}/default.env"); \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PYTHON_INSTALL_SCRIPT:?}"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?}"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PACKAGE_INSTALL_SCRIPT:?}"; \ - /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_FILESYSTEM_INSTALL_SCRIPT:?}" + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_FILESYSTEM_INSTALL_SCRIPT:?}"; \ + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_INTERPRETERS_INSTALL_SCRIPT:?}" RUN set -euo pipefail; \ systemctl mask systemd-firstboot.service first-boot-complete.target || true; \ diff --git a/Makefile b/Makefile index 0ef344aad4..4e1c82181f 100644 --- a/Makefile +++ b/Makefile @@ -118,7 +118,7 @@ clean-cache: @bash scripts/system/cache/clean.sh .PHONY: clean-container-owned -# Remove container-owned generated artefacts (build/, tasks/groups/*.yml). +# Remove container-owned generated artefacts (build/). # Note: these files are created inside the compose container with the in-container UID (typically `nobody`); the host cannot rm them directly. # Note: the helper auto-starts a stopped infinito container before deleting; safe no-op when the targets do not exist. clean-container-owned: @@ -348,6 +348,16 @@ install-lint: install-lint-force: @bash scripts/install/wrapper.sh --force +.PHONY: install-node +# Install the Node.js runtime the JavaScript unit suite runs on. +install-node: + @bash scripts/install/node.sh + +.PHONY: install-php +# Install PHP, Composer and the vendor tree the PHP unit suite runs on. +install-php: + @bash scripts/install/php.sh + .PHONY: install-python # Install Python tooling. install-python: install-venv @@ -359,6 +369,11 @@ install-python-dev: install-python @bash scripts/install/python.sh dev @bash scripts/install/pre-commit.sh +.PHONY: install-ruby +# Install the Ruby interpreter the Ruby unit suite runs on. +install-ruby: + @bash scripts/install/ruby.sh + .PHONY: install-skills # Install the agent skills from INFINITO_SKILLS_REPOSITORY into this project. install-skills: @@ -374,21 +389,31 @@ install-system-python: install-venv: install-system-python @bash scripts/install/venv.sh +.PHONY: kernel-loop-load +# Load the kernel loop driver the swarm backup DR drill needs. +# Note: run this on the host; container environments have no modprobe. +kernel-loop-load: + @sudo bash scripts/system/kernel/loop/load.sh + .PHONY: lint # Run all lint checks in parallel. # Note: each check runs on host or in docker per INFINITO_LINT_RUNNER. lint: install-lint @bash scripts/make/parallel.sh lint-action \ lint-ansible \ + lint-css \ lint-dockerfile \ lint-javascript \ lint-makefile \ lint-markdown \ lint-mermaid \ lint-packages \ + lint-php \ lint-playwright \ lint-python \ - lint-shellcheck + lint-ruby \ + lint-shellcheck \ + lint-sql .PHONY: lint-action # Run the GitHub Actions lint checks. @@ -401,6 +426,12 @@ lint-action: install-lint lint-ansible: install-lint setup @bash scripts/lint/wrapper.sh ansible +.PHONY: lint-css +# Check that every CSS file parses, via stylelint with an empty rule set. +lint-css: install-lint + @bash scripts/install/wrapper.sh css + @bash scripts/lint/wrapper.sh css + .PHONY: lint-dockerfile # Run hadolint over the root Dockerfile. lint-dockerfile: install-lint @@ -434,6 +465,13 @@ lint-packages: install-lint @bash scripts/install/wrapper.sh packages @bash scripts/lint/wrapper.sh packages +.PHONY: lint-php +# Check that every PHP file parses, via `php -l`. +# Note: provisions the PHP CLI explicitly; an absent interpreter is skipped. +lint-php: install-lint + @bash scripts/install/wrapper.sh php + @bash scripts/lint/wrapper.sh php + .PHONY: lint-playwright # Verify every role's Playwright spec parses + resolves its helpers. # Note: stages the spec like test-e2e-playwright does and runs `npx playwright test --list`. @@ -445,11 +483,25 @@ lint-playwright: install-lint lint-python: install-lint @bash scripts/lint/wrapper.sh python +.PHONY: lint-ruby +# Check that every Ruby file parses, via `ruby -c`. +# Note: provisions the Ruby CLI explicitly; an absent interpreter is skipped. +lint-ruby: install-lint + @bash scripts/install/wrapper.sh ruby + @bash scripts/lint/wrapper.sh ruby + .PHONY: lint-shellcheck # Run shellcheck lint checks. lint-shellcheck: install-lint @bash scripts/lint/wrapper.sh shellcheck +.PHONY: lint-sql +# Check that every SQL file parses, via `sqlfluff parse`. +# Note: dialect comes from the nearest .sqlfluff; absent tooling is skipped. +lint-sql: install-lint + @bash scripts/install/wrapper.sh sql + @bash scripts/lint/wrapper.sh sql + .PHONY: meta-list # Print the repository role list. meta-list: @@ -549,8 +601,9 @@ requirements-archive: # Param apps: space-separated role ids; default = one role per base cluster, most-complex first (complexity --unique). # Param modes: optional mode sequence (default "compose swarm"; append k8s once it exists). # Param keep: true keeps each validated swarm cluster instead of releasing it. +# Param disable: optional comma-separated provider keys removed from the test inventory (e.g. matomo,dashboard,prometheus,email,css). roundtrip: - @apps='$(apps)' modes='$(modes)' keep='$(keep)' bash scripts/tests/deploy/roundtrip.sh + @apps='$(apps)' modes='$(modes)' keep='$(keep)' disable='$(disable)' bash scripts/tests/deploy/roundtrip.sh .PHONY: runner-ci-deploy # Provision self-hosted CI runner instances on a remote host. @@ -697,6 +750,7 @@ SWARM_DISTROS = $(or $(distros),$${INFINITO_DISTRO:?}) # Note: Use `make swarm-exec` / `make swarm-shell` to inspect, `make swarm-down` to release. swarm-zombie: install-act @test -n '$(app)' || { echo 'usage: make swarm-zombie app= [distros=] [variant=] [name=] [disable=]'; exit 2; } + @"$${PYTHON}" -m cli.meta.ci.validate --modes swarm --whitelist '$(app)#$(or $(variant),0)@swarm' @SWARM_NAME='$(or $(name),$(app))' INFINITO_KEEP_SWARM_NODES=false bash scripts/tests/deploy/swarm/utils/clean/teardown.sh @bash scripts/tests/deploy/act/down_act_outer.sh @ACT_RM=false \ @@ -708,10 +762,10 @@ swarm-zombie: install-act SWARM_NAME=$(or $(name),$(app)); \ INFINITO_SWARM_STEP_TIMEOUT_MINUTES=$(or $(step_timeout),690); \ INFINITO_DISTROS=$(SWARM_DISTROS)" \ - ACT_WORKFLOW=.github/workflows/call-test-deploy-swarm.yml \ - ACT_JOB=swarm \ - ACT_MATRIX='apps:$(app);variant:$(or $(variant),0)' \ - ACT_INPUTS="whitelist=$(app) distros=$(SWARM_DISTROS)" \ + ACT_WORKFLOW=.github/workflows/call-test-deploy.yml \ + ACT_JOB=deploy \ + ACT_MATRIX="apps:$(app);variant:$(or $(variant),0);mode:swarm" \ + ACT_INPUTS="whitelist=$(app) distros=$(SWARM_DISTROS) index=0 sweep=0 modes=swarm disable=$(disable)" \ bash scripts/tests/deploy/act/workflow.sh .PHONY: system-purge @@ -733,21 +787,21 @@ test: install test-external: install @INFINITO_TEST_TYPE="external" \ INFINITO_COMPILE=0 \ - bash scripts/tests/code/wrapper.sh + bash scripts/tests/code/wrapper.sh scripts/tests/code/run.sh .PHONY: test-integration # Run the integration test suite. test-integration: install @INFINITO_TEST_TYPE="integration" \ INFINITO_COMPILE=0 \ - bash scripts/tests/code/wrapper.sh + bash scripts/tests/code/wrapper.sh scripts/tests/code/run.sh .PHONY: test-lint # Run the lint test suite. test-lint: install @INFINITO_TEST_TYPE="lint" \ INFINITO_COMPILE=0 \ - bash scripts/tests/code/wrapper.sh + bash scripts/tests/code/wrapper.sh scripts/tests/code/run.sh .PHONY: test-main-merged # Verify upstream main is fully merged into HEAD (pre-push gate); fetches and fails if the branch lags main. @@ -764,7 +818,7 @@ test-merge-signed: test-performance: install @INFINITO_TEST_TYPE="performance" \ INFINITO_COMPILE=0 \ - bash scripts/tests/code/wrapper.sh + bash scripts/tests/code/wrapper.sh scripts/tests/code/run.sh .PHONY: test-signed # Verify HEAD is signed. @@ -778,11 +832,33 @@ test-signed: echo "✅ HEAD commit signature status: $$status" .PHONY: test-unit -# Run the unit test suite. -test-unit: install +# Run the unit test suite (every language). +test-unit: test-unit-python test-unit-javascript test-unit-php test-unit-ruby + +.PHONY: test-unit-javascript +# Run the JavaScript unit test suite (node:test, no npm dependency). +test-unit-javascript: + @INFINITO_TEST_TYPE="unit-javascript" \ + bash scripts/tests/code/wrapper.sh scripts/tests/unit/javascript.sh + +.PHONY: test-unit-php +# Run the PHP unit test suite (PHPUnit). +test-unit-php: + @INFINITO_TEST_TYPE="unit-php" \ + bash scripts/tests/code/wrapper.sh scripts/tests/unit/php.sh + +.PHONY: test-unit-python +# Run the Python unit test suite. +test-unit-python: install @INFINITO_TEST_TYPE="unit" \ INFINITO_COMPILE=0 \ - bash scripts/tests/code/wrapper.sh + bash scripts/tests/code/wrapper.sh scripts/tests/code/run.sh + +.PHONY: test-unit-ruby +# Run the Ruby unit test suite (minitest, stdlib). +test-unit-ruby: + @INFINITO_TEST_TYPE="unit-ruby" \ + bash scripts/tests/code/wrapper.sh scripts/tests/unit/ruby.sh .PHONY: worktree-down # Stop a branch worktree's stack, release the checkout and free its slot. diff --git a/README.md b/README.md index f7c32f89ba..36f1685e3e 100644 --- a/README.md +++ b/README.md @@ -60,123 +60,127 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | Name | Status | Description | More | Integrated with | |---|---|---|---|---| -| [Akaunting](roles/web-app-akaunting/) | beta | Self-hosted platform for online accounting, bookkeeping, and business finance management | [🌐](https://akaunting.com/) [🎬](https://www.youtube.com/akaunting) [🛠️](roles/web-app-akaunting/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Assets Server](roles/web-svc-asset/) | beta | Nginx-based server for hosting static assets copied from a source directory to the web data path | [🛠️](roles/web-svc-asset/README.md#quick-setup) | [File Server](roles/web-svc-file/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | +| [Akaunting](roles/web-app-akaunting/) | beta | Self-hosted platform for online accounting, bookkeeping, and business finance management | [🌐](https://akaunting.com/) [🎬](https://www.youtube.com/akaunting) [🛠️](roles/web-app-akaunting/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | alpha | Nginx-based privacy proxy that mirrors whitelisted third-party assets under a first-party domain | [🛠️](roles/web-svc-mirror/README.md#quick-setup) | [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Assets Server](roles/web-svc-asset/) | beta | Nginx-based server for hosting static assets copied from a source directory to the web data path | [🛠️](roles/web-svc-asset/README.md#quick-setup) | [File Server](roles/web-svc-file/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | beta | Scheduled deduplicating backup system for Docker container volumes to a local directory, with consistent SQL dumps | [🛠️](roles/svc-bkp-volume-2-local/README.md#quick-setup) | [Backup Host Secrets](roles/svc-bkp-secrets-2-local/) | | [Backup Host Secrets](roles/svc-bkp-secrets-2-local/) | beta | Scheduled deduplicating backup of host secrets, CA, ACME credentials, and node identity to the local backup directory | [🛠️](roles/svc-bkp-secrets-2-local/README.md#quick-setup) | | | [Backup NFS](roles/svc-bkp-nfs-2-local/) | beta | Scheduled backup job for hard-linked differential rsync snapshots of an NFS export into the local backup tree | [🛠️](roles/svc-bkp-nfs-2-local/README.md#quick-setup) | [NFS Server](roles/svc-storage-nfs-server/) | | [Backup Remote Server](roles/svc-bkp-remote-2-local/) | beta | Scheduled pull-style backup replicating remote hosts onto this host over SSH and rsync as hard-linked snapshots | [🛠️](roles/svc-bkp-remote-2-local/README.md#quick-setup) | [Backup to External Device](roles/svc-bkp-local-2-device/) | | [Backup to External Device](roles/svc-bkp-local-2-device/) | beta | Plug-triggered systemd backup for hard-link deduplicated snapshots of the local backup tree onto a swappable USB device | [🛠️](roles/svc-bkp-local-2-device/README.md#quick-setup) | | -| [Baserow](roles/web-app-baserow/) | beta | Self-hosted no-code database platform with a spreadsheet-like interface for building and collaborating on data | [🌐](https://baserow.io/) [🎬](https://www.youtube.com/watch?v=5yFMfP96_4M) [🛠️](roles/web-app-baserow/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | +| [Baserow](roles/web-app-baserow/) | beta | Self-hosted no-code database platform with a spreadsheet-like interface for building and collaborating on data | [🌐](https://baserow.io/) [🎬](https://www.youtube.com/watch?v=5yFMfP96_4M) [🛠️](roles/web-app-baserow/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [BigBlueButton](roles/web-app-bigbluebutton/) | beta | Self-hosted web conferencing platform for virtual classrooms, online meetings, and real-time collaboration | [🌐](https://bigbluebutton.org/) [🎬](https://www.youtube.com/watch?v=YRkQB6MJllI) [🛠️](roles/web-app-bigbluebutton/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Collabora](roles/web-svc-collabora/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Bluesky](roles/web-app-bluesky/) | beta | Self-hosted decentralized social network on the open AT Protocol, with its own Personal Data Server | [🌐](https://bsky.social/) [🛠️](roles/web-app-bluesky/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [BookWyrm](roles/web-app-bookwyrm/) | beta | Self-hosted federated reading platform for book reviews and reading tracking across the Fediverse | [🌐](https://joinbookwyrm.com/) [🛠️](roles/web-app-bookwyrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Bridgy Fed](roles/web-app-bridgy-fed/) | beta | Federation bridge connecting ActivityPub (Fediverse), the AT Protocol (Bluesky), and the IndieWeb | [🌐](https://fed.brid.gy/) [🛠️](roles/web-app-bridgy-fed/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Checkmk](roles/web-app-checkmk/) | beta | Open-source IT and application monitoring server behind SSO with native LDAP user management | [🌐](https://checkmk.com/) [🎬](https://www.youtube.com/watch?v=opO-SOgOJ1I) [🛠️](roles/web-app-checkmk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Chess](roles/web-app-chess/) | beta | Federated chess server for playing and following rule-validated games over ActivityPub across the Fediverse | [🌐](https://castling.club/) [🛠️](roles/web-app-chess/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/) | -| [Collabora](roles/web-svc-collabora/) | beta | Self-hosted online office backend for real-time in-browser editing of documents, spreadsheets, and presentations | [🌐](https://www.collaboraonline.com/) [🎬](https://www.youtube.com/@CollaboraOnline) [🛠️](roles/web-svc-collabora/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Content Delivery Network](roles/web-svc-cdn/) | beta | Nginx-based content delivery network for serving shared static assets to internal web applications | [🛠️](roles/web-svc-cdn/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Corporate Design](roles/web-svc-css/) | beta | Service-registry role owning the canonical `css` flag and redirecting the CSS hostname to the CDN upstream | [🛠️](roles/web-svc-css/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Prometheus](roles/web-app-prometheus/) | +| [Bluesky](roles/web-app-bluesky/) | beta | Self-hosted decentralized social network on the open AT Protocol, with its own Personal Data Server | [🌐](https://bsky.social/) [🛠️](roles/web-app-bluesky/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [BookWyrm](roles/web-app-bookwyrm/) | beta | Self-hosted federated reading platform for book reviews and reading tracking across the Fediverse | [🌐](https://joinbookwyrm.com/) [🛠️](roles/web-app-bookwyrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Bridgy Fed](roles/web-app-bridgy-fed/) | beta | Federation bridge connecting ActivityPub (Fediverse), the AT Protocol (Bluesky), and the IndieWeb | [🌐](https://fed.brid.gy/) [🛠️](roles/web-app-bridgy-fed/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Checkmk](roles/web-app-checkmk/) | beta | Open-source IT and application monitoring server behind SSO with native LDAP user management | [🌐](https://checkmk.com/) [🎬](https://www.youtube.com/watch?v=opO-SOgOJ1I) [🛠️](roles/web-app-checkmk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Chess](roles/web-app-chess/) | beta | Federated chess server for playing and following rule-validated games over ActivityPub across the Fediverse | [🌐](https://castling.club/) [🛠️](roles/web-app-chess/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Collabora](roles/web-svc-collabora/) | beta | Self-hosted online office backend for real-time in-browser editing of documents, spreadsheets, and presentations | [🌐](https://www.collaboraonline.com/) [🎬](https://www.youtube.com/@CollaboraOnline) [🛠️](roles/web-svc-collabora/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Content Delivery Network](roles/web-svc-cdn/) | beta | Nginx-based content delivery network for serving shared static assets to internal web applications | [🛠️](roles/web-svc-cdn/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Corporate Design](roles/web-svc-css/) | beta | Service-registry role owning the canonical `css` flag and redirecting the CSS hostname to the CDN upstream | [🛠️](roles/web-svc-css/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Coturn](roles/web-svc-coturn/) | beta | Free and open-source TURN/STUN relay server for NAT traversal in WebRTC and real-time communication | [🌐](https://github.com/coturn/coturn) [🛠️](roles/web-svc-coturn/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Prometheus](roles/web-app-prometheus/) | -| [Dashboard](roles/web-app-dashboard/) | beta | Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface | [🛠️](roles/web-app-dashboard/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Simple Icons](roles/web-svc-simpleicons/), [Universal Logout](roles/web-svc-logout/) | -| [Decidim](roles/web-app-decidim/) | beta | Open-source participatory democracy platform for public consultations, civic processes, and community voting | [🌐](https://decidim.org/) [🎬](https://www.youtube.com/channel/UCbxXpC5MmKImcGFzUJxdAUw) [🛠️](roles/web-app-decidim/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Discourse](roles/web-app-discourse/) | beta | Open-source discussion and community forum platform with moderation, notifications, and plugin support | [🌐](https://www.discourse.org/) [🎬](https://www.youtube.com/@discourse_) [🛠️](roles/web-app-discourse/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | +| [Dashboard](roles/web-app-dashboard/) | beta | Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface | [🛠️](roles/web-app-dashboard/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Simple Icons](roles/web-svc-simpleicons/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Decidim](roles/web-app-decidim/) | beta | Open-source participatory democracy platform for public consultations, civic processes, and community voting | [🌐](https://decidim.org/) [🎬](https://www.youtube.com/channel/UCbxXpC5MmKImcGFzUJxdAUw) [🛠️](roles/web-app-decidim/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Discourse](roles/web-app-discourse/) | beta | Open-source discussion and community forum platform with moderation, notifications, and plugin support | [🌐](https://www.discourse.org/) [🎬](https://www.youtube.com/@discourse_) [🛠️](roles/web-app-discourse/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Docker Registry](roles/svc-registry-docker/) | beta | Cluster-local container image registry for serving custom-built images to Docker Swarm worker nodes | [🌐](https://distribution.github.io/distribution/) [🛠️](roles/svc-registry-docker/README.md#quick-setup) | [Docker Swarm](roles/svc-swarm-node/) | | [Docker Registry Cache](roles/svc-registry-cache/) | beta | Cluster-local pull-through cache for shared Docker Hub base-image pulls, cutting duplicate transfers and rate limits | [🛠️](roles/svc-registry-cache/README.md#quick-setup) | [Docker Swarm](roles/svc-swarm-node/) | | [Docker Swarm](roles/svc-swarm-node/) | beta | Container orchestration cluster for scheduling services across pooled manager and worker nodes | [🛠️](roles/svc-swarm-node/README.md#quick-setup) | | | [Docker Swarm Manager](roles/svc-swarm-manager/) | beta | Marker role tagging a host as the Docker Swarm manager node, with the init logic delegated to svc-swarm-node | [🛠️](roles/svc-swarm-manager/README.md#quick-setup) | [Docker Swarm](roles/svc-swarm-node/) | -| [Elasticsearch](roles/svc-db-elasticsearch/) | beta | Central search and analytics engine with per-consumer index namespaces isolating tenants in a shared Docker deployment | [🌐](https://www.elastic.co/elasticsearch) [🛠️](roles/svc-db-elasticsearch/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [ERPNext](roles/web-app-erpnext/) | beta | Self-hosted open-source ERP suite for finance, CRM, inventory, manufacturing, HR, sales, and projects | [🌐](https://erpnext.com/) [🎬](https://www.youtube.com/watch?v=JlqE-BfDEUY) [🛠️](roles/web-app-erpnext/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | -| [EspoCRM](roles/web-app-espocrm/) | beta | Open-source CRM platform for managing sales, customer interactions, and business processes across teams | [🌐](https://www.espocrm.com/) [🎬](https://www.youtube.com/watch?v=TH6yJPTPLO0) [🛠️](roles/web-app-espocrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Fediwall](roles/web-app-fediwall/) | beta | Self-hosted Fediverse wall for showing recent public posts by hashtag or account in a live masonry grid | [🌐](https://github.com/defnull/fediwall) [🛠️](roles/web-app-fediwall/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Friendica](roles/web-app-friendica/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Fider](roles/web-app-fider/) | beta | Open-source community feedback platform for collecting, voting on, and prioritizing feature requests and ideas | [🌐](https://www.fider.io/) [🛠️](roles/web-app-fider/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [File Server](roles/web-svc-file/) | beta | Static file server over HTTPS with directory listing, .well-known handling, and automatic TLS certificates | [🛠️](roles/web-svc-file/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Flowise](roles/web-app-flowise/) | beta | Low-code visual builder for creating, testing, and publishing LLM and RAG workflows as HTTP endpoints | [🌐](https://flowiseai.com/) [🎬](https://www.youtube.com/@FlowiseAI) [🛠️](roles/web-app-flowise/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Qdrant](roles/svc-db-qdrant/), [Universal Logout](roles/web-svc-logout/) | -| [Friendica](roles/web-app-friendica/) | beta | Decentralized, federated social-networking platform for peer-to-peer communication and community building | [🌐](https://friendi.ca/) [🛠️](roles/web-app-friendica/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Funkwhale](roles/web-app-funkwhale/) | beta | Self-hosted, federated platform for sharing, hosting, and streaming your own music and audio library | [🌐](https://www.funkwhale.audio/) [🛠️](roles/web-app-funkwhale/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Typesense](roles/svc-db-typesense/), [Universal Logout](roles/web-svc-logout/) | -| [FusionDirectory](roles/web-app-fusiondirectory/) | beta | Web-based LDAP administration interface for managing users, groups, and directory objects | [🌐](https://www.fusiondirectory.org/) [🎬](https://www.youtube.com/watch?v=dThpssnXGyk) [🛠️](roles/web-app-fusiondirectory/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Gitea](roles/web-app-gitea/) | beta | Lightweight self-hosted Git service for code collaboration, version control, and repository management | [🌐](https://about.gitea.com/) [🛠️](roles/web-app-gitea/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [GitLab](roles/web-app-gitlab/) | beta | Self-hosted DevOps platform for Git source-code management, CI/CD pipelines, and issue tracking | [🌐](https://about.gitlab.com/) [🎬](https://www.youtube.com/watch?v=7q9Y1Cv-ib0) [🛠️](roles/web-app-gitlab/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [HTML Server](roles/web-svc-html/) | beta | NGINX vhost for serving static HTML websites over HTTPS with automatic Let's Encrypt certificates | [🛠️](roles/web-svc-html/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Hugo](roles/web-app-hugo/) | beta | Static site generator building HTML from an upstream Git repository at build time and serving it via nginx | [🌐](https://gohugo.io/) [🛠️](roles/web-app-hugo/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Imprint](roles/web-svc-legal/) | beta | NGINX-served static page rendering a legal imprint (Impressum) from a Jinja2 template | [🛠️](roles/web-svc-legal/README.md#quick-setup) | [HTML Server](roles/web-svc-html/), [Prometheus](roles/web-app-prometheus/) | +| [Elasticsearch](roles/svc-db-elasticsearch/) | beta | Central search and analytics engine with per-consumer index namespaces isolating tenants in a shared Docker deployment | [🌐](https://www.elastic.co/elasticsearch) [🛠️](roles/svc-db-elasticsearch/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | +| [ERPNext](roles/web-app-erpnext/) | beta | Self-hosted open-source ERP suite for finance, CRM, inventory, manufacturing, HR, sales, and projects | [🌐](https://erpnext.com/) [🎬](https://www.youtube.com/watch?v=JlqE-BfDEUY) [🛠️](roles/web-app-erpnext/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [EspoCRM](roles/web-app-espocrm/) | beta | Open-source CRM platform for managing sales, customer interactions, and business processes across teams | [🌐](https://www.espocrm.com/) [🎬](https://www.youtube.com/watch?v=TH6yJPTPLO0) [🛠️](roles/web-app-espocrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Fediwall](roles/web-app-fediwall/) | beta | Self-hosted Fediverse wall for showing recent public posts by hashtag or account in a live masonry grid | [🌐](https://github.com/defnull/fediwall) [🛠️](roles/web-app-fediwall/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Friendica](roles/web-app-friendica/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Fider](roles/web-app-fider/) | beta | Open-source community feedback platform for collecting, voting on, and prioritizing feature requests and ideas | [🌐](https://www.fider.io/) [🛠️](roles/web-app-fider/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [File Server](roles/web-svc-file/) | beta | Static file server over HTTPS with directory listing, .well-known handling, and automatic TLS certificates | [🛠️](roles/web-svc-file/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Flowise](roles/web-app-flowise/) | beta | Low-code visual builder for creating, testing, and publishing LLM and RAG workflows as HTTP endpoints | [🌐](https://flowiseai.com/) [🎬](https://www.youtube.com/@FlowiseAI) [🛠️](roles/web-app-flowise/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Qdrant](roles/svc-db-qdrant/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Friendica](roles/web-app-friendica/) | beta | Decentralized, federated social-networking platform for peer-to-peer communication and community building | [🌐](https://friendi.ca/) [🛠️](roles/web-app-friendica/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Funkwhale](roles/web-app-funkwhale/) | beta | Self-hosted, federated platform for sharing, hosting, and streaming your own music and audio library | [🌐](https://www.funkwhale.audio/) [🛠️](roles/web-app-funkwhale/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Typesense](roles/svc-db-typesense/), [Universal Logout](roles/web-svc-logout/) | +| [FusionDirectory](roles/web-app-fusiondirectory/) | beta | Web-based LDAP administration interface for managing users, groups, and directory objects | [🌐](https://www.fusiondirectory.org/) [🎬](https://www.youtube.com/watch?v=dThpssnXGyk) [🛠️](roles/web-app-fusiondirectory/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Gitea](roles/web-app-gitea/) | beta | Lightweight self-hosted Git service for code collaboration, version control, and repository management | [🌐](https://about.gitea.com/) [🛠️](roles/web-app-gitea/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [GitLab](roles/web-app-gitlab/) | beta | Self-hosted DevOps platform for Git source-code management, CI/CD pipelines, and issue tracking | [🌐](https://about.gitlab.com/) [🎬](https://www.youtube.com/watch?v=7q9Y1Cv-ib0) [🛠️](roles/web-app-gitlab/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [HTML Server](roles/web-svc-html/) | beta | NGINX vhost for serving static HTML websites over HTTPS with automatic Let's Encrypt certificates | [🛠️](roles/web-svc-html/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Hugo](roles/web-app-hugo/) | beta | Static site generator building HTML from an upstream Git repository at build time and serving it via nginx | [🌐](https://gohugo.io/) [🛠️](roles/web-app-hugo/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Imprint](roles/web-svc-legal/) | beta | NGINX-served static page rendering a legal imprint (Impressum) from a Jinja2 template | [🛠️](roles/web-svc-legal/README.md#quick-setup) | [HTML Server](roles/web-svc-html/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Intel Driver](roles/drv-intel/) | alpha | Intel VA-API media driver for hardware-accelerated video decode and encode across Linux distributions | [🌐](https://github.com/intel/media-driver) [🛠️](roles/drv-intel/README.md#quick-setup) | | -| [Jellyfin](roles/web-app-jellyfin/) | beta | Self-hosted media server for streaming and organizing movies, TV, music, and photos, with OIDC and LDAP login | [🌐](https://jellyfin.org/) [🎬](https://www.youtube.com/watch?v=0t3lSJL3B_Q) [🛠️](roles/web-app-jellyfin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Jenkins](roles/web-app-jenkins/) | beta | Open-source automation server for CI/CD pipelines, builds, and plugin-driven deployment workflows | [🌐](https://www.jenkins.io/) [🎬](https://www.youtube.com/channel/UC5JBtmoz7ePk-33ZHimGiDQ) [🛠️](roles/web-app-jenkins/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | +| [Jellyfin](roles/web-app-jellyfin/) | beta | Self-hosted media server for streaming and organizing movies, TV, music, and photos, with OIDC and LDAP login | [🌐](https://jellyfin.org/) [🎬](https://www.youtube.com/watch?v=0t3lSJL3B_Q) [🛠️](roles/web-app-jellyfin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Jenkins](roles/web-app-jenkins/) | beta | Open-source automation server for CI/CD pipelines, builds, and plugin-driven deployment workflows | [🌐](https://www.jenkins.io/) [🎬](https://www.youtube.com/channel/UC5JBtmoz7ePk-33ZHimGiDQ) [🛠️](roles/web-app-jenkins/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Jitsi Meet](roles/web-app-jitsi/) | beta | Self-hosted WebRTC platform for end-to-end-encryptable video conferencing with federated authentication | [🌐](https://jitsi.org/) [🎬](https://www.youtube.com/channel/UCyXuxN-aNUpRv0juUXLyjbw) [🛠️](roles/web-app-jitsi/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Joomla](roles/web-app-joomla/) | beta | Open-source content management system for building websites, intranets, and online applications without writing code | [🌐](https://www.joomla.org/) [🎬](https://www.youtube.com/user/joomla) [🛠️](roles/web-app-joomla/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Keycloak](roles/web-app-keycloak/) | beta | Self-hosted identity and access management platform for single sign-on, multi-factor authentication, and user federation | [🌐](https://www.keycloak.org/) [🛠️](roles/web-app-keycloak/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/) | -| [KIX](roles/web-app-kix/) | beta | Open-source ITSM and helpdesk platform (OTRS fork) for ticketing, CMDB, knowledge base, and reporting | [🌐](https://www.kixdesk.com/en/) [🎬](https://www.youtube.com/watch?v=D62emos1FQ8) [🛠️](roles/web-app-kix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [LAM](roles/web-app-lam/) | beta | Web interface for administering LDAP directories: managing users, groups, and other directory objects | [🌐](https://www.ldap-account-manager.org/) [🛠️](roles/web-app-lam/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [LibreTranslate](roles/web-svc-libretranslate/) | beta | Self-hosted open-source machine translation API for translating and detecting text across languages | [🌐](https://libretranslate.com/) [🛠️](roles/web-svc-libretranslate/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | +| [Joomla](roles/web-app-joomla/) | beta | Open-source content management system for building websites, intranets, and online applications without writing code | [🌐](https://www.joomla.org/) [🎬](https://www.youtube.com/user/joomla) [🛠️](roles/web-app-joomla/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Keycloak](roles/web-app-keycloak/) | beta | Self-hosted identity and access management platform for single sign-on, multi-factor authentication, and user federation | [🌐](https://www.keycloak.org/) [🛠️](roles/web-app-keycloak/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [KIX](roles/web-app-kix/) | beta | Open-source ITSM and helpdesk platform (OTRS fork) for ticketing, CMDB, knowledge base, and reporting | [🌐](https://www.kixdesk.com/en/) [🎬](https://www.youtube.com/watch?v=D62emos1FQ8) [🛠️](roles/web-app-kix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [LAM](roles/web-app-lam/) | beta | Web interface for administering LDAP directories: managing users, groups, and other directory objects | [🌐](https://www.ldap-account-manager.org/) [🛠️](roles/web-app-lam/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [LibreTranslate](roles/web-svc-libretranslate/) | beta | Self-hosted open-source machine translation API for translating and detecting text across languages | [🌐](https://libretranslate.com/) [🛠️](roles/web-svc-libretranslate/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [LID Switch Driver](roles/drv-lid-switch/) | alpha | Power-aware systemd logind configuration for predictable laptop lid-close behavior across battery, AC, and docked states | [🛠️](roles/drv-lid-switch/README.md#quick-setup) | | -| [Listmonk](roles/web-app-listmonk/) | beta | Self-hosted platform for newsletters and mailing lists with subscriber segmentation and campaign analytics | [🌐](https://listmonk.app/) [🛠️](roles/web-app-listmonk/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [LittleJS](roles/web-app-littlejs/) | alpha | Self-hosted HTML5 game sandbox for browsing and running lightweight engine demos and games in the browser | [🌐](https://killedbyapixel.github.io/LittleJS/) [🎬](https://youtu.be/chuBzGjv7Ms) [🛠️](roles/web-app-littlejs/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Mailu](roles/web-app-mailu/) | beta | Self-hosted mail server suite with SMTP/IMAP/POP3, webmail, spam filtering, antivirus, DKIM signing, and TLS | [🌐](https://mailu.io/) [🛠️](roles/web-app-mailu/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | -| [MariaDB](roles/svc-db-mariadb/) | beta | Shared relational database server for applications needing central SQL storage, run in Docker | [🌐](https://mariadb.org/) [🎬](https://www.youtube.com/watch?v=YsIJB15fq_c) [🛠️](roles/svc-db-mariadb/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [Mastodon](roles/web-app-mastodon/) | beta | Self-hosted federated social network for microblogging, real-time timelines, and community moderation | [🌐](https://joinmastodon.org/) [🛠️](roles/web-app-mastodon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Matomo](roles/web-app-matomo/) | beta | Self-hosted, privacy-first web analytics platform for real-time visitor tracking and site metrics | [🌐](https://matomo.org/) [🎬](https://www.youtube.com/watch?v=Qc2kooLNDiU) [🛠️](roles/web-app-matomo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [MariaDB](roles/svc-db-mariadb/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Matrix](roles/web-app-matrix/) | beta | Federated, end-to-end-encrypted messaging platform with a web client and protocol bridges to external chat networks | [🌐](https://matrix.org/) [🎬](https://www.youtube.com/watch?v=3AVsNqH_-9M) [🛠️](roles/web-app-matrix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Mattermost](roles/web-app-mattermost/) | beta | Open-source, self-hosted team messaging platform for real-time collaboration via channels, threads, and integrations | [🌐](https://mattermost.com/) [🎬](https://www.youtube.com/watch?v=szfZfQFUSnU) [🛠️](roles/web-app-mattermost/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [MediaWiki](roles/web-app-mediawiki/) | beta | Collaborative wiki platform for user-driven documentation with an extensible extension ecosystem and content management | [🌐](https://www.mediawiki.org/) [🎬](https://www.youtube.com/watch?v=-JnIjpRvgNY) [🛠️](roles/web-app-mediawiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Memcached](roles/svc-db-memcached/) | beta | Central in-memory caching engine with per-consumer key-prefix isolation, usable centrally or as an embedded sidecar | [🌐](https://memcached.org/) [🛠️](roles/svc-db-memcached/README.md#quick-setup) | | -| [MIG](roles/web-app-mig/) | alpha | Interactive graph visualization of all Infinito.Nexus roles and their dependencies for architecture transparency | [🛠️](roles/web-app-mig/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Mini-QR](roles/web-app-mini-qr/) | beta | Self-hosted browser tool for generating QR codes from text or URLs with privacy-friendly local rendering | [🌐](https://github.com/lyqht/mini-qr) [🛠️](roles/web-app-mini-qr/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [Mobilizon](roles/web-app-mobilizon/) | beta | Federated, self-hosted platform for organizing events and building communities and groups | [🌐](https://joinmobilizon.org/) [🎬](https://framatube.org/c/mobilizon/videos) [🛠️](roles/web-app-mobilizon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Moodle](roles/web-app-moodle/) | beta | Open-source learning management system for creating, managing, and delivering online courses and e-learning | [🌐](https://moodle.org/) [🎬](https://www.youtube.com/watch?v=3ORsUGVNxGs) [🛠️](roles/web-app-moodle/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [n8n](roles/web-app-n8n/) | beta | Self-hosted low-code automation platform for connecting services and building workflow integrations visually | [🌐](https://n8n.io/) [🎬](https://youtu.be/4cQWJViybAQ) [🛠️](roles/web-app-n8n/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Nextcloud](roles/web-app-nextcloud/) | beta | Self-hosted cloud platform for file sync, sharing, real-time collaboration, and team workspaces under your own domain | [🌐](https://nextcloud.com/) [🎬](https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC) [🛠️](roles/web-app-nextcloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [BigBlueButton](roles/web-app-bigbluebutton/), [Collabora](roles/web-svc-collabora/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Flowise](roles/web-app-flowise/), [GitLab](roles/web-app-gitlab/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Matrix](roles/web-app-matrix/), [Mattermost](roles/web-app-mattermost/), [OnlyOffice](roles/web-svc-onlyoffice/), [Open WebUI](roles/web-app-openwebui/), [OpenLDAP](roles/svc-db-openldap/), [OpenProject](roles/web-app-openproject/), [PeerTube](roles/web-app-peertube/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/), [XWiki](roles/web-app-xwiki/), [Zammad](roles/web-app-zammad/) | +| [Listmonk](roles/web-app-listmonk/) | beta | Self-hosted platform for newsletters and mailing lists with subscriber segmentation and campaign analytics | [🌐](https://listmonk.app/) [🛠️](roles/web-app-listmonk/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [LittleJS](roles/web-app-littlejs/) | alpha | Self-hosted HTML5 game sandbox for browsing and running lightweight engine demos and games in the browser | [🌐](https://killedbyapixel.github.io/LittleJS/) [🎬](https://youtu.be/chuBzGjv7Ms) [🛠️](roles/web-app-littlejs/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Magento](roles/web-app-magento/) | alpha | Self-hosted e-commerce platform for catalog management, checkout, promotions, and multi-store online retail | [🌐](https://business.adobe.com/products/commerce/magento/open-source.html) [🎬](https://www.youtube.com/user/magentocommerce) [🛠️](roles/web-app-magento/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Mailu](roles/web-app-mailu/) | beta | Self-hosted mail server suite with SMTP/IMAP/POP3, webmail, spam filtering, antivirus, DKIM signing, and TLS | [🌐](https://mailu.io/) [🛠️](roles/web-app-mailu/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [MariaDB](roles/svc-db-mariadb/) | beta | Shared relational database server for applications needing central SQL storage, run in Docker | [🌐](https://mariadb.org/) [🎬](https://www.youtube.com/watch?v=YsIJB15fq_c) [🛠️](roles/svc-db-mariadb/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | +| [Mastodon](roles/web-app-mastodon/) | beta | Self-hosted federated social network for microblogging, real-time timelines, and community moderation | [🌐](https://joinmastodon.org/) [🛠️](roles/web-app-mastodon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Matomo](roles/web-app-matomo/) | beta | Self-hosted, privacy-first web analytics platform for real-time visitor tracking and site metrics | [🌐](https://matomo.org/) [🎬](https://www.youtube.com/watch?v=Qc2kooLNDiU) [🛠️](roles/web-app-matomo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [MariaDB](roles/svc-db-mariadb/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Matrix](roles/web-app-matrix/) | beta | Federated, end-to-end-encrypted messaging platform with a web client and protocol bridges to external chat networks | [🌐](https://matrix.org/) [🎬](https://www.youtube.com/watch?v=3AVsNqH_-9M) [🛠️](roles/web-app-matrix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Mattermost](roles/web-app-mattermost/) | beta | Open-source, self-hosted team messaging platform for real-time collaboration via channels, threads, and integrations | [🌐](https://mattermost.com/) [🎬](https://www.youtube.com/watch?v=szfZfQFUSnU) [🛠️](roles/web-app-mattermost/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [MediaWiki](roles/web-app-mediawiki/) | beta | Collaborative wiki platform for user-driven documentation with an extensible extension ecosystem and content management | [🌐](https://www.mediawiki.org/) [🎬](https://www.youtube.com/watch?v=-JnIjpRvgNY) [🛠️](roles/web-app-mediawiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Memcached](roles/svc-db-memcached/) | beta | Central in-memory caching engine with per-consumer key-prefix isolation, usable centrally or as an embedded sidecar | [🌐](https://memcached.org/) [🛠️](roles/svc-db-memcached/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | +| [MIG](roles/web-app-mig/) | alpha | Interactive graph visualization of all Infinito.Nexus roles and their dependencies for architecture transparency | [🛠️](roles/web-app-mig/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Mini-QR](roles/web-app-mini-qr/) | beta | Self-hosted browser tool for generating QR codes from text or URLs with privacy-friendly local rendering | [🌐](https://github.com/lyqht/mini-qr) [🛠️](roles/web-app-mini-qr/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Mobilizon](roles/web-app-mobilizon/) | beta | Federated, self-hosted platform for organizing events and building communities and groups | [🌐](https://joinmobilizon.org/) [🎬](https://framatube.org/c/mobilizon/videos) [🛠️](roles/web-app-mobilizon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Moodle](roles/web-app-moodle/) | beta | Open-source learning management system for creating, managing, and delivering online courses and e-learning | [🌐](https://moodle.org/) [🎬](https://www.youtube.com/watch?v=3ORsUGVNxGs) [🛠️](roles/web-app-moodle/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [n8n](roles/web-app-n8n/) | beta | Self-hosted low-code automation platform for connecting services and building workflow integrations visually | [🌐](https://n8n.io/) [🎬](https://youtu.be/4cQWJViybAQ) [🛠️](roles/web-app-n8n/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Nextcloud](roles/web-app-nextcloud/) | beta | Self-hosted cloud platform for file sync, sharing, real-time collaboration, and team workspaces under your own domain | [🌐](https://nextcloud.com/) [🎬](https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC) [🛠️](roles/web-app-nextcloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [BigBlueButton](roles/web-app-bigbluebutton/), [Collabora](roles/web-svc-collabora/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Flowise](roles/web-app-flowise/), [GitLab](roles/web-app-gitlab/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Matrix](roles/web-app-matrix/), [Mattermost](roles/web-app-mattermost/), [OnlyOffice](roles/web-svc-onlyoffice/), [Open WebUI](roles/web-app-openwebui/), [OpenLDAP](roles/svc-db-openldap/), [OpenProject](roles/web-app-openproject/), [PeerTube](roles/web-app-peertube/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/), [XWiki](roles/web-app-xwiki/), [Zammad](roles/web-app-zammad/) | | [NFS Client](roles/svc-storage-nfs-client/) | beta | Client-side NFS setup for mounting a remote server export on every swarm node, with a deploy-time reachability probe | [🛠️](roles/svc-storage-nfs-client/README.md#quick-setup) | [NFS Server](roles/svc-storage-nfs-server/) | | [NFS Server](roles/svc-storage-nfs-server/) | beta | Kernel-level NFS server for exporting a shared directory tree with IP-restricted access for swarm-node hosts | [🛠️](roles/svc-storage-nfs-server/README.md#quick-setup) | [Backup NFS](roles/svc-bkp-nfs-2-local/) | -| [Odoo ERP](roles/web-app-odoo/) | beta | Open-source ERP suite for CRM, sales, accounting, inventory, HR, and website management | [🌐](https://www.odoo.com/) [🎬](https://www.odoo.com/slides/getting-started-15) [🛠️](roles/web-app-odoo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | +| [Odoo ERP](roles/web-app-odoo/) | beta | Open-source ERP suite for CRM, sales, accounting, inventory, HR, and website management | [🌐](https://www.odoo.com/) [🎬](https://www.odoo.com/slides/getting-started-15) [🛠️](roles/web-app-odoo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Ollama](roles/svc-ai-ollama/) | beta | Self-hosted model server for running open LLMs locally behind a simple HTTP API | [🌐](https://ollama.com/) [🛠️](roles/svc-ai-ollama/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [OnlyOffice](roles/web-svc-onlyoffice/) | beta | Document server backend for real-time in-browser editing of documents, spreadsheets, and presentations | [🌐](https://www.onlyoffice.com/) [🎬](https://www.youtube.com/channel/UCNxeQm7vVujR8eFPtpVAVNg) [🛠️](roles/web-svc-onlyoffice/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/) | -| [Open WebUI](roles/web-app-openwebui/) | beta | Self-hosted chat interface for interacting with local and private AI models via backends such as Ollama | [🌐](https://openwebui.com/) [🛠️](roles/web-app-openwebui/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [OpenCloud](roles/web-app-opencloud/) | beta | Self-hosted platform for file sync, sharing, and collaboration with Keycloak SSO and central LDAP directory | [🌐](https://opencloud.eu/) [🎬](https://www.youtube.com/watch?v=Cg48rFNY0R4) [🛠️](roles/web-app-opencloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [OpenLDAP](roles/svc-db-openldap/) | beta | Self-hosted LDAP directory service for centralized user, group, and schema management with TLS-secured access | [🌐](https://www.openldap.org/) [🛠️](roles/svc-db-openldap/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [OpenProject](roles/web-app-openproject/) | beta | Self-hosted platform for project management, work-package tracking, Gantt planning, and team collaboration | [🌐](https://www.openproject.org/) [🎬](https://www.youtube.com/watch?v=rvCd0xH7rCs) [🛠️](roles/web-app-openproject/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [OpenResty](roles/svc-prx-openresty/) | beta | NGINX-based web platform and reverse proxy with validated config reloads and Let's Encrypt integration | [🌐](https://openresty.org/) [🎬](https://openresty.org/en/videos.html) [🛠️](roles/svc-prx-openresty/README.md#quick-setup) | | +| [OnlyOffice](roles/web-svc-onlyoffice/) | beta | Document server backend for real-time in-browser editing of documents, spreadsheets, and presentations | [🌐](https://www.onlyoffice.com/) [🎬](https://www.youtube.com/channel/UCNxeQm7vVujR8eFPtpVAVNg) [🛠️](roles/web-svc-onlyoffice/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/) | +| [Open WebUI](roles/web-app-openwebui/) | beta | Self-hosted chat interface for interacting with local and private AI models via backends such as Ollama | [🌐](https://openwebui.com/) [🛠️](roles/web-app-openwebui/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [OpenCloud](roles/web-app-opencloud/) | beta | Self-hosted platform for file sync, sharing, and collaboration with Keycloak SSO and central LDAP directory | [🌐](https://opencloud.eu/) [🎬](https://www.youtube.com/watch?v=Cg48rFNY0R4) [🛠️](roles/web-app-opencloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [OpenLDAP](roles/svc-db-openldap/) | beta | Self-hosted LDAP directory service for centralized user, group, and schema management with TLS-secured access | [🌐](https://www.openldap.org/) [🛠️](roles/svc-db-openldap/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | +| [OpenProject](roles/web-app-openproject/) | beta | Self-hosted platform for project management, work-package tracking, Gantt planning, and team collaboration | [🌐](https://www.openproject.org/) [🎬](https://www.youtube.com/watch?v=rvCd0xH7rCs) [🛠️](roles/web-app-openproject/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [OpenResty](roles/svc-prx-openresty/) | beta | NGINX-based web platform and reverse proxy with validated config reloads and Let's Encrypt integration | [🌐](https://openresty.org/) [🎬](https://openresty.org/en/videos.html) [🛠️](roles/svc-prx-openresty/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | | [OpenTalk](roles/web-app-opentalk/) | beta | Sovereign open-source video conferencing platform for audio/video calls, screen sharing, breakout rooms, and SSO | [🌐](https://opentalk.eu/) [🛠️](roles/web-app-opentalk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | | [Package update](roles/update/) | beta | System-maintenance role for refreshing the package index and upgrading installed packages via the OS package manager | [🛠️](roles/update/README.md#quick-setup) | | | [PeerTube](roles/web-app-peertube/) | beta | Decentralized, federated platform for peer-to-peer video hosting, streaming, and live broadcasting | [🌐](https://joinpeertube.org/) [🎬](https://framatube.org/w/cX4KAPLTwha6hzLZ5xePGZ) [🛠️](roles/web-app-peertube/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Penpot](roles/web-app-penpot/) | beta | Self-hosted design and prototyping platform for UI/UX work, real-time collaboration, and developer handoff | [🌐](https://penpot.app/) [🎬](https://www.youtube.com/watch?v=vAkb4QQmbfk) [🛠️](roles/web-app-penpot/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [pgAdmin](roles/web-app-pgadmin/) | beta | Web-based administration and development platform for managing multiple PostgreSQL servers, with optional OAuth2 login | [🌐](https://www.pgadmin.org/) [🎬](https://www.pgadmin.org/videos/) [🛠️](roles/web-app-pgadmin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [PhpMyAdmin](roles/web-app-phpmyadmin/) | beta | Web-based administration tool for MySQL and MariaDB with schema management, querying, and import/export | [🌐](https://www.phpmyadmin.net/) [🛠️](roles/web-app-phpmyadmin/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Pixelfed](roles/web-app-pixelfed/) | beta | Decentralized, federated platform for photo sharing and image feeds across the fediverse | [🌐](https://pixelfed.org/) [🛠️](roles/web-app-pixelfed/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [PostgreSQL](roles/svc-db-postgres/) | beta | Containerized relational database with automated database, user, and privilege provisioning | [🌐](https://www.postgresql.org/) [🛠️](roles/svc-db-postgres/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [Postmarks](roles/web-app-postmarks/) | beta | Single-user ActivityPub bookmarking site federating public bookmarks to Mastodon and the Fediverse | [🌐](https://github.com/ckolderup/postmarks) [🛠️](roles/web-app-postmarks/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Pretix](roles/web-app-pretix/) | beta | Self-hosted ticketing platform for events with online sales, registration management, and secure payments | [🌐](https://pretix.eu/) [🎬](https://www.youtube.com/channel/UCG1Og1YUpgIJD4geAZLAp5g) [🛠️](roles/web-app-pretix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | -| [Prometheus](roles/web-app-prometheus/) | beta | Open-source monitoring and alerting toolkit for storing metrics as time-series data and querying them with PromQL | [🌐](https://prometheus.io/) [🎬](https://www.youtube.com/c/PrometheusIo) [🛠️](roles/web-app-prometheus/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Universal Logout](roles/web-svc-logout/) | +| [Penpot](roles/web-app-penpot/) | beta | Self-hosted design and prototyping platform for UI/UX work, real-time collaboration, and developer handoff | [🌐](https://penpot.app/) [🎬](https://www.youtube.com/watch?v=vAkb4QQmbfk) [🛠️](roles/web-app-penpot/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [pgAdmin](roles/web-app-pgadmin/) | beta | Web-based administration and development platform for managing multiple PostgreSQL servers, with optional OAuth2 login | [🌐](https://www.pgadmin.org/) [🎬](https://www.pgadmin.org/videos/) [🛠️](roles/web-app-pgadmin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [PhpMyAdmin](roles/web-app-phpmyadmin/) | beta | Web-based administration tool for MySQL and MariaDB with schema management, querying, and import/export | [🌐](https://www.phpmyadmin.net/) [🛠️](roles/web-app-phpmyadmin/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Pixelfed](roles/web-app-pixelfed/) | beta | Decentralized, federated platform for photo sharing and image feeds across the fediverse | [🌐](https://pixelfed.org/) [🛠️](roles/web-app-pixelfed/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [PostgreSQL](roles/svc-db-postgres/) | beta | Containerized relational database with automated database, user, and privilege provisioning | [🌐](https://www.postgresql.org/) [🛠️](roles/svc-db-postgres/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | +| [Postmarks](roles/web-app-postmarks/) | beta | Single-user ActivityPub bookmarking site federating public bookmarks to Mastodon and the Fediverse | [🌐](https://github.com/ckolderup/postmarks) [🛠️](roles/web-app-postmarks/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Pretix](roles/web-app-pretix/) | beta | Self-hosted ticketing platform for events with online sales, registration management, and secure payments | [🌐](https://pretix.eu/) [🎬](https://www.youtube.com/channel/UCG1Og1YUpgIJD4geAZLAp5g) [🛠️](roles/web-app-pretix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Prometheus](roles/web-app-prometheus/) | beta | Open-source monitoring and alerting toolkit for storing metrics as time-series data and querying them with PromQL | [🌐](https://prometheus.io/) [🎬](https://www.youtube.com/c/PrometheusIo) [🛠️](roles/web-app-prometheus/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Proprietary Drivers](roles/drv-non-free/) | alpha | Proprietary GPU driver installer for Arch-based systems via mhwd nonfree hardware detection | [🛠️](roles/drv-non-free/README.md#quick-setup) | | -| [Qdrant](roles/svc-db-qdrant/) | beta | Central vector database engine for storing and searching per-consumer embeddings shared across the stack | [🌐](https://qdrant.tech/) [🎬](https://www.youtube.com/watch?v=_opNdOa48Lc) [🛠️](roles/svc-db-qdrant/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [RabbitMQ](roles/svc-db-rabbitmq/) | beta | Shared message broker for async messaging with per-consumer virtual host and user isolation | [🌐](https://www.rabbitmq.com/) [🛠️](roles/svc-db-rabbitmq/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | +| [Qdrant](roles/svc-db-qdrant/) | beta | Central vector database engine for storing and searching per-consumer embeddings shared across the stack | [🌐](https://qdrant.tech/) [🎬](https://www.youtube.com/watch?v=_opNdOa48Lc) [🛠️](roles/svc-db-qdrant/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | +| [RabbitMQ](roles/svc-db-rabbitmq/) | beta | Shared message broker for async messaging with per-consumer virtual host and user isolation | [🌐](https://www.rabbitmq.com/) [🛠️](roles/svc-db-rabbitmq/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Redirector](roles/web-opt-rdr-domains/) | beta | NGINX glue role for 301 redirects from source to target domains with automatic SSL for the source hosts | [🛠️](roles/web-opt-rdr-domains/README.md#quick-setup) | | -| [Redis](roles/svc-db-redis/) | beta | In-memory key-value cache and store, shared centrally with per-consumer ACL isolation or embedded as a sidecar | [🌐](https://redis.io/) [🛠️](roles/svc-db-redis/README.md#quick-setup) | | -| [Roulette Wheel](roles/web-app-roulette-wheel/) | alpha | Browser-based spinning wheel app for decision making, random selection, and gamification | [🌐](https://github.com/p-wojt/roulette-wheel) [🛠️](roles/web-app-roulette-wheel/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | +| [Redis](roles/svc-db-redis/) | beta | In-memory key-value cache and store, shared centrally with per-consumer ACL isolation or embedded as a sidecar | [🌐](https://redis.io/) [🛠️](roles/svc-db-redis/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | +| [Roulette Wheel](roles/web-app-roulette-wheel/) | alpha | Browser-based spinning wheel app for decision making, random selection, and gamification | [🌐](https://github.com/p-wojt/roulette-wheel) [🛠️](roles/web-app-roulette-wheel/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [SeaweedFS](roles/web-app-seaweedfs/) | beta | Distributed S3-compatible object store for shared, per-consumer bucket provisioning across web-app roles | [🌐](https://seaweedfs.org/) [🛠️](roles/web-app-seaweedfs/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | | [Self-Hosted Runner](roles/svc-runner/) | beta | Self-hosted CI runner infrastructure for executing GitHub Actions workflow jobs in ephemeral Docker containers | [🌐](https://github.com/actions/runner) [🛠️](roles/svc-runner/README.md#quick-setup) | | -| [Semaphore UI](roles/web-app-semaphore/) | beta | Web UI and API for running Ansible, Terraform/OpenTofu, and shell automation on a schedule or on demand | [🌐](https://semaphoreui.com/) [🎬](https://www.youtube.com/watch?v=nzR4yDuZQMU) [🛠️](roles/web-app-semaphore/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Shopware](roles/web-app-shopware/) | beta | Open-source ecommerce platform built on Symfony and Vue.js for building and scaling online storefronts | [🌐](https://www.shopware.com/en/) [🎬](https://www.youtube.com/watch?v=bG57TZPYsyw) [🛠️](roles/web-app-shopware/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Simple Icons](roles/web-svc-simpleicons/) | beta | Containerized icon server for hosting the Simple Icons brand SVG and PNG collection for web and documentation use | [🌐](https://simpleicons.org/) [🛠️](roles/web-svc-simpleicons/README.md#quick-setup) | [Prometheus](roles/web-app-prometheus/) | -| [Snipe‑IT](roles/web-app-snipe-it/) | beta | Open-source IT asset management system for tracking hardware and software inventory | [🌐](https://snipeitapp.com/) [🎬](https://www.youtube.com/watch?v=q0V6FAPc1ls) [🛠️](roles/web-app-snipe-it/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Sphinx](roles/web-app-sphinx/) | beta | Documentation generator that builds HTML from a source repository and serves it through a lightweight HTTP server | [🌐](https://www.sphinx-doc.org/) [🛠️](roles/web-app-sphinx/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | +| [Semaphore UI](roles/web-app-semaphore/) | beta | Web UI and API for running Ansible, Terraform/OpenTofu, and shell automation on a schedule or on demand | [🌐](https://semaphoreui.com/) [🎬](https://www.youtube.com/watch?v=nzR4yDuZQMU) [🛠️](roles/web-app-semaphore/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Shopware](roles/web-app-shopware/) | beta | Open-source ecommerce platform built on Symfony and Vue.js for building and scaling online storefronts | [🌐](https://www.shopware.com/en/) [🎬](https://www.youtube.com/watch?v=bG57TZPYsyw) [🛠️](roles/web-app-shopware/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Simple Icons](roles/web-svc-simpleicons/) | beta | Containerized icon server for hosting the Simple Icons brand SVG and PNG collection for web and documentation use | [🌐](https://simpleicons.org/) [🛠️](roles/web-svc-simpleicons/README.md#quick-setup) | [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Snipe‑IT](roles/web-app-snipe-it/) | beta | Open-source IT asset management system for tracking hardware and software inventory | [🌐](https://snipeitapp.com/) [🎬](https://www.youtube.com/watch?v=q0V6FAPc1ls) [🛠️](roles/web-app-snipe-it/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Social Home](roles/web-app-socialhome/) | alpha | Privacy-first social platform for households, federating peer-to-peer over WebRTC on an embedded SQLite store | [🌐](https://github.com/social-home-io/socialhome) [🛠️](roles/web-app-socialhome/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Sphinx](roles/web-app-sphinx/) | beta | Documentation generator that builds HTML from a source repository and serves it through a lightweight HTTP server | [🌐](https://www.sphinx-doc.org/) [🛠️](roles/web-app-sphinx/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Storage Optimizer](roles/svc-opt-ssd-hdd/) | beta | Tiering role placing Docker volumes on SSD or HDD by workload type, with symlinks keeping paths consistent | [🛠️](roles/svc-opt-ssd-hdd/README.md#quick-setup) | | -| [SuiteCRM](roles/web-app-suitecrm/) | beta | Open-source CRM platform for sales, service, cases, and campaign management with workflow automation | [🌐](https://suitecrm.com/) [🎬](https://suitecrm.com/suitecrm-demo-video/) [🛠️](roles/web-app-suitecrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | +| [SuiteCRM](roles/web-app-suitecrm/) | beta | Open-source CRM platform for sales, service, cases, and campaign management with workflow automation | [🌐](https://suitecrm.com/) [🎬](https://suitecrm.com/suitecrm-demo-video/) [🛠️](roles/web-app-suitecrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Swapfile](roles/svc-opt-swapfile/) | beta | On-target automation for creating and activating swap space via a cloned swapfile script | [🛠️](roles/svc-opt-swapfile/README.md#quick-setup) | | -| [Taiga](roles/web-app-taiga/) | beta | Open-source agile project management platform for Scrum, Kanban, and hybrid team workflows | [🌐](https://taiga.io/) [🎬](https://www.youtube.com/watch?v=TYPX8nQEU5I) [🛠️](roles/web-app-taiga/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | -| [Typesense](roles/svc-db-typesense/) | beta | Central Dockerized search engine shared by multiple apps with per-consumer scoped API keys | [🌐](https://typesense.org/) [🛠️](roles/svc-db-typesense/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | +| [Taiga](roles/web-app-taiga/) | beta | Open-source agile project management platform for Scrum, Kanban, and hybrid team workflows | [🌐](https://taiga.io/) [🎬](https://www.youtube.com/watch?v=TYPX8nQEU5I) [🛠️](roles/web-app-taiga/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Tor Onion Service](roles/svc-net-tor/) | alpha | Tor daemon publishing the node as a v3 onion service | [🛠️](roles/svc-net-tor/README.md#quick-setup) | [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | +| [Typesense](roles/svc-db-typesense/) | beta | Central Dockerized search engine shared by multiple apps with per-consumer scoped API keys | [🌐](https://typesense.org/) [🛠️](roles/svc-db-typesense/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Unbound](roles/svc-dns-unbound/) | beta | Central recursive/forwarding DNSSEC resolver on a static IP for consumer stacks to target as their DNS | [🌐](https://nlnetlabs.nl/projects/unbound/about/) [🛠️](roles/svc-dns-unbound/README.md#quick-setup) | | -| [Universal Logout](roles/web-svc-logout/) | beta | Central logout proxy for single-action sign-out across all OIDC-connected apps, with Nginx snippets and a live status UI | [🛠️](roles/web-svc-logout/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/) | -| [web-app-pihole](roles/web-app-pihole/) | beta | Network-wide DNS sinkhole for blocking ads and trackers across all devices, with DHCP and a web admin dashboard | [🌐](https://pi-hole.net/) [🎬](https://youtu.be/KBXTnrD_Zs4) [🛠️](roles/web-app-pihole/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | +| [Universal Logout](roles/web-svc-logout/) | beta | Central logout proxy for single-action sign-out across all OIDC-connected apps, with Nginx snippets and a live status UI | [🛠️](roles/web-svc-logout/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [web-app-pihole](roles/web-app-pihole/) | beta | Network-wide DNS sinkhole for blocking ads and trackers across all devices, with DHCP and a web admin dashboard | [🌐](https://pi-hole.net/) [🎬](https://youtu.be/KBXTnrD_Zs4) [🛠️](roles/web-app-pihole/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Wireguard](roles/svc-net-wireguard-core/) | alpha | Host-level WireGuard VPN service with wg-quick config, package install, and IP-forwarding sysctl for secure tunnels | [🌐](https://www.wireguard.com/) [🛠️](roles/svc-net-wireguard-core/README.md#quick-setup) | | | [Wireguard Client](roles/svc-net-wireguard-plain/) | alpha | Client-side WireGuard VPN role for stable connectivity with a systemd service and script that tune interface MTU | [🌐](https://www.wireguard.com/) [🛠️](roles/svc-net-wireguard-plain/README.md#quick-setup) | | | [WireGuard Client behind NAT](roles/svc-net-wireguard-firewalled/) | alpha | Networking helper for iptables forwarding and NAT masquerading of a WireGuard client running behind NAT or a firewall | [🛠️](roles/svc-net-wireguard-firewalled/README.md#quick-setup) | | -| [WordPress](roles/web-app-wordpress/) | beta | Content management system for building and managing websites, blogs, and multisite networks with themes and plugins | [🌐](https://wordpress.org/) [🎬](https://www.youtube.com/wordpress) [🛠️](roles/web-app-wordpress/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [World Wide Web](roles/web-opt-rdr-www/) | beta | NGINX server blocks that permanently redirect www subdomains to their non-www apex domains | [🛠️](roles/web-opt-rdr-www/README.md#quick-setup) | | -| [XMPP](roles/web-svc-xmpp/) | beta | Placeholder stub role for a future XMPP server/container deployment, implementation pending | [🌐](https://ejabberd.im/) [🛠️](roles/web-svc-xmpp/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Keycloak](roles/web-app-keycloak/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/) | -| [XWiki](roles/web-app-xwiki/) | beta | Self-hosted enterprise wiki and knowledge-management platform with collaboration and app-based extensibility | [🌐](https://www.xwiki.org/) [🎬](https://www.youtube.com/watch?v=8DePx30dh2g) [🛠️](roles/web-app-xwiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [YOURLS](roles/web-app-yourls/) | beta | Self-hosted URL shortener for creating, tracking, and managing short links with built-in click analytics | [🌐](https://yourls.org/) [🛠️](roles/web-app-yourls/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Zammad](roles/web-app-zammad/) | beta | Open-source helpdesk and ticketing system for handling customer requests via email, chat, phone, and web | [🌐](https://zammad.org/) [🎬](https://www.youtube.com/@zammadhq) [🛠️](roles/web-app-zammad/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Memcached](roles/svc-db-memcached/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Universal Logout](roles/web-svc-logout/) | +| [WordPress](roles/web-app-wordpress/) | beta | Content management system for building and managing websites, blogs, and multisite networks with themes and plugins | [🌐](https://wordpress.org/) [🎬](https://www.youtube.com/wordpress) [🛠️](roles/web-app-wordpress/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [World Wide Web](roles/web-opt-rdr-www/) | beta | NGINX server blocks that permanently redirect www subdomains to their non-www apex domains | [🛠️](roles/web-opt-rdr-www/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | +| [XMPP](roles/web-svc-xmpp/) | beta | Placeholder stub role for a future XMPP server/container deployment, implementation pending | [🌐](https://ejabberd.im/) [🛠️](roles/web-svc-xmpp/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Keycloak](roles/web-app-keycloak/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [XWiki](roles/web-app-xwiki/) | beta | Self-hosted enterprise wiki and knowledge-management platform with collaboration and app-based extensibility | [🌐](https://www.xwiki.org/) [🎬](https://www.youtube.com/watch?v=8DePx30dh2g) [🛠️](roles/web-app-xwiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [YOURLS](roles/web-app-yourls/) | beta | Self-hosted URL shortener for creating, tracking, and managing short links with built-in click analytics | [🌐](https://yourls.org/) [🛠️](roles/web-app-yourls/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Zammad](roles/web-app-zammad/) | beta | Open-source helpdesk and ticketing system for handling customer requests via email, chat, phone, and web | [🌐](https://zammad.org/) [🎬](https://www.youtube.com/@zammadhq) [🛠️](roles/web-app-zammad/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Memcached](roles/svc-db-memcached/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | ## Guides 📚 diff --git a/TODO.md b/TODO.md index 2b842723c8..9f401239e6 100644 --- a/TODO.md +++ b/TODO.md @@ -12,3 +12,97 @@ - run over all distros for each app - msg: can not use content with a dir as dest for NGINX multi distro - split service database to postgres and mariadb + +## Onion e2e (feature/svc-net-tor) — remaining failures + +Status after deploy-matrix run 29657147883 (commit 407b8a8a1). Every fixable +failure class from that run is committed (hlth-csp onion-sibling skip, +onion-aware Playwright request timeouts + lint guard, joomla server-side OIDC +reachability). The items below are the ones that are NOT fixed yet. Runs +31756400129 and 31756560361 have since moved several of them; entries corrected +against those runs say so inline. + +- **https on the onion IdP — investigated and REJECTED, do not re-derive.** OIDC + Discovery / RFC 8414 want an https issuer, and an onion-exclusive Keycloak has + none, so strict client libraries refuse it. Serving TLS on the onion is blocked + on four independent things, in this order: (1) `roles/svc-net-tor/templates/torrc.j2` + publishes only `HiddenServicePort 80`, and no role declares 443 in + `ports.public`/`ports.local`, so `lookup('tor_ports')` can never emit it — + flipping TLS on first makes Keycloak unreachable over Tor entirely, because + `nginx_ssl_header.j2` is one if/else and port 80 disappears; (2) + `roles/sys-front-tls-selfsigned/tasks/00_core.yml` writes an unguarded CN, which + overflows X.509's 64-byte cap on a 62-char v3 onion — `group_vars/all/02_tls.yml` + already guards exactly this for the root CA and nowhere else; (3) + `nginx_ssl_header.j2` emits HSTS in the same branch, and browsers offer no + click-through on an HSTS host with an untrusted chain, so a self-signed interim + locks real users out while staying invisible to Playwright's + `ignoreHTTPSErrors`; (4) it fixes zero libcurl consumers, because RFC 7686 + refusal happens at name resolution and is scheme-independent. Unblocking needs a + CA that issues for v3 `.onion` (HARICA, CA/B Forum ballot 144) — procurement, + not code. Until then the per-consumer fixes stand: SOCKS proxy for libcurl + clients. peertube is no longer among them - it is a clearnet-only role. + +- **dual-family providers** — the one real remaining design gap. On a CI onion + node, tor-enabled providers (e.g. mastodon) are onion-exclusive: their domain + list contains only the `.onion` canonical, no clearnet sibling. The + family-alignment resolver (`utils/tls_common.py:align_domain_to_consumer`, + wired into `plugins/lookup/tls.py`) correctly bails in that case, so a + clearnet-pinned consumer still receives an onion URL it can neither resolve + nor reach. First hard evidence: `web-app-fediwall` variant 2 (tor=false) + renders `microblog.` into `wall-config.json.servers`; the clearnet + browser (no SOCKS) times out waiting for mastodon wall items + (`test-walls-surface-posts.js:24`, deterministic across retries). The same + class is expected to keep `web-app-bigbluebutton`, `web-app-nextcloud`, + `web-app-opentalk` and `web-app-jitsi` red (clearnet-pinned apps whose peer + refs — OIDC/cdn/matomo/logout — resolve onion-primary). Fix direction: + providers must publish BOTH families (clearnet sibling alongside the onion + canonical) so the resolver has something to align to; includes re-applying + the deferred `KC_HOSTNAME` onion-gate for Keycloak that was dropped from the + earlier bundle because it is only needed once dual-family exists. +- **joomla local-login fallback spec** — `test-oidc-fallback.js:52` (the + `?fallback=local` emergency hatch: local Joomla admin form login must reach + the control panel). Root cause UNCONFIRMED. It is independent of the fixed + OIDC-login spec: the fallback path short-circuits before the plugin's + server-side discovery, so the committed `extra_hosts` fix does not cover it. + The `secure => true` sticky-cookie hypothesis was rejected (`.onion` is a + potentially-trustworthy origin and the e2e Firefox sets + `dom.securecontext.allowlist_onions`, so Secure cookies are accepted over + plain-http onion). Next step when it fails again post-fix: isolate the + post-submit URL — Keycloak redirect (cookie lost) vs. form reject vs. slow + control-panel render. +- **matomo container health flake (checkmk batch)** — in the checkmk job the + 4th deploy play failed at `Wait for Matomo container to be healthy` with + `container inspect: map has no entry for key "State"` for the whole retry + window (container started, then vanished — likely crash + prune). Plays 1–3 + in the SAME job deployed matomo healthy, so classified transient + (resource/prune pressure after ~3h). No code fix derivable. If it recurs, + investigate as a real matomo crash/OOM (container logs, mem_limit). +- **server-side OIDC reachability candidates** — joomla failed because its app + container performs server-side OIDC discovery against `http://auth.` + without an `extra_hosts` mapping. Roles with the same mechanic and no + `container_extra_hosts` lookup yet (fix is the same one-line lookup, + apply on CI evidence): wordpress (daggerhart plugin) and mediawiki + (PluggableAuth) are structurally identical PHP in-app plugins (high + likelihood); discourse, jenkins, jira, confluence, odoo, openwebui, + pretix, zammad, semaphore, jellyfin, listmonk, xwiki, mastodon consume the + issuer server-side too (unverified network path). oauth2-proxy-based apps + are NOT affected (proven green: prometheus admin SSO). Two names have left + this list on evidence: mobilizon got the lookup in 0e39f3fad after its + code-to-token call raised OAuth2.Error Connection refused twenty-four times, + and gitlab was NEVER a member - run 31756560361 shows it resolving and + connecting (peeraddr=172.30.0.10:443); its failure was the openid_connect gem + rebuilding the discovery URL over https regardless of the issuer scheme, + fixed in 2389b6e38. +- **baseline exclusions** — `web-app-fider` and `web-app-bookwyrm` (also + keycloak-job, n8n) were red before the tor branch and stay out of scope for + it; bookwyrm fails its oauth2 trusted-header session spec, fider its + baseline. Fix separately from the onion work. espocrm has left this list: its + onion variant failed in the shared admin persona (fixed in b97cf8888) and its + clearnet variant returns HTTP 500 on GET /api/v1/App/user, cause still open. +- **test-development environment jobs** — all 5 distro jobs + (arch, debian, ubuntu, fedora, centos) hit the 4h30m cap under congestion + while still progressing (playwright image pull). Environmental, no code fix - + distinct from the distro sweep's own budget, which did have one: 508669809 + books a budget SIGKILL as skipped, which ad9222630 had only done for SIGTERM; + note that onion e2e inherently lengthens the routine (×5 onion timeouts, + circuit waits), so under congestion these jobs are the first to hit the cap. diff --git a/aliases b/aliases index 0550625e5d..09dff24008 100644 --- a/aliases +++ b/aliases @@ -16,9 +16,9 @@ alias i8ceco='m clean-container-owned' alias i8cepa='m clean-pycache-dirs' alias i8cesa='m clean-stale-nfs' alias i8cesu='m clean-sudo' -alias i8cifail='__i8cifail(){ [ -z "${1:-}" ] && { echo "usage: i8cifail [total|swarm|compose]" >&2; return 2; }; infinito administration deploy ci trigger --failed "${2:-total}" --run "$1"; }; __i8cifail' # retrigger failed and never-deployed priority roles of run $1 (id or url), scope $2 (default total), reproducing that run's configuration -alias i8cifo='__i8cifo(){ [ -z "${1:-}" ] && { echo "usage: i8cifo [total|swarm|compose]" >&2; return 2; }; infinito administration deploy ci trigger --failed "${2:-total}" --strict --run "$1"; }; __i8cifo' # like i8cifail but only hard-failed roles, excluding cancelled/aborted; scope $2 (default total) -alias i8cire='__i8cire(){ make quality && gips && i8cifail "$1" swarm; }; __i8cire' +alias i8cifail='__i8cifail(){ [ -z "${1:-}" ] && { echo "usage: i8cifail " >&2; return 2; }; ghaf "$1" || echo "i8cifail: force-cancel of run $1 reported nothing to cancel; continuing" >&2; infinito administration deploy ci trigger --failed --run "$1"; }; __i8cifail' # retrigger the exact failed selections (role#variant@mode+tor) of run $1 (id or url) across every mode, plus its never-deployed priority entries, reproducing every other input of that run; force-cancels the run first so it stops holding runner slots +alias i8cifo='__i8cifo(){ [ -z "${1:-}" ] && { echo "usage: i8cifo " >&2; return 2; }; ghaf "$1" || echo "i8cifo: force-cancel of run $1 reported nothing to cancel; continuing" >&2; infinito administration deploy ci trigger --failed --strict --run "$1"; }; __i8cifo' # like i8cifail but only hard-failed selections, excluding cancelled/aborted; force-cancels the run first +alias i8cire='__i8cire(){ make quality && gips && i8cifail "$1"; }; __i8cire' alias i8co='m compose-deploy' alias i8co2='m console' alias i8codo='m compose-down' @@ -40,9 +40,11 @@ alias i8dofo='m dotenv-force' alias i8fi='m fix-chmod' alias i8fido='m fix-dockerignore' alias i8he='m help' +alias i8kelo='m kernel-loop-load' alias i8la='m alias' alias i8li='m lint' alias i8lica='m lint-action' +alias i8lics='m lint-css' alias i8lido='m lint-dockerfile' alias i8lija='m lint-javascript' alias i8lima='m lint-makefile' @@ -51,16 +53,20 @@ alias i8lime='m lint-mermaid' alias i8lina='m lint-ansible' alias i8lipa='m lint-packages' alias i8lipa2='m lint-playwright' +alias i8liph='m lint-php' alias i8lipo='m lint-python' +alias i8liru='m lint-ruby' alias i8lise='m lint-shellcheck' -alias i8maco='i8source && python3 -m cli.meta.ci.query --mode compose --matrix' # complexity matrix in compose query order -alias i8maho='i8source && python3 -m cli.meta.ci.query --mode host --matrix' # complexity matrix in host query order -alias i8masa='i8source && python3 -m cli.meta.ci.query --mode swarm --matrix' # complexity matrix in swarm query order +alias i8lisq='m lint-sql' +alias i8maal='i8source && python3 -m cli.meta.ci.query --modes auto --matrix' # complexity matrix of every deployable row, in CI query order +alias i8maco='i8source && python3 -m cli.meta.ci.query --modes compose --matrix' # complexity matrix in compose query order +alias i8maho='i8source && python3 -m cli.meta.ci.query --modes host --matrix' # complexity matrix in host query order +alias i8masa='i8source && python3 -m cli.meta.ci.query --modes swarm --matrix' # complexity matrix in swarm query order alias i8matis='i8matix -s' # variant with symbols -alias i8matiso='clear && i8matis --sort "$INFINITO_DISCOVERY_SORT" --filter "compose == true"' # clear + compose-deploy matrix (whole-role, discovery-sorted, compose-filtered) +alias i8matiso='clear && i8maal --roles' # clear + deploy matrix of every deployable role, in CI query order alias i8mativ='i8matix --variant' # deploy matrix / complexity overview for variants alias i8mativas='i8mativ -s' # variant with symbols -alias i8mativaso='clear && i8mativas --sort "$INFINITO_DISCOVERY_SORT" --filter "compose == true"' # clear + compose-deploy matrix (variants + symbols, discovery-sorted, filtered) +alias i8mativaso='clear && i8maal' # clear + deploy matrix of every deployable variant, in CI query order alias i8matiw='i8matis --sort "desc weight"' # complexity matrix, symbols, heaviest roles first alias i8matix='infinito meta roles applications complexity' # deploy matrix / complexity overview alias i8me='m meta-list' @@ -84,18 +90,23 @@ alias i8nilas='i8nila && source ~/.bashrc' # Install aliases and source them alias i8nili='m install-lint' alias i8nilifo='m install-lint-force' alias i8nina='m install-ansible' +alias i8nino='m install-node' +alias i8niph='m install-php' alias i8nipo='m install-python' alias i8nipode='m install-python-dev' +alias i8niru='m install-ruby' alias i8nise='m install-system-python' alias i8nisi='m install-skills' alias i8nive='m install-venv' alias i8on='m onboard' +alias i8paal='i8source && python3 -m cli.meta.ci.plan --cli --modes auto' # plan table for every deployable row, in CI query order alias i8paco='i8source && python3 -m cli.meta.ci.plan --cli --modes compose' # plan table for the compose line alias i8paho='i8source && python3 -m cli.meta.ci.plan --cli --modes host' # plan table for the host line +alias i8papr='i8source && python3 -m cli.meta.ci.plan --cli --modes auto --priority' # plan table for the priority line given as the next argument alias i8pasa='i8source && python3 -m cli.meta.ci.plan --cli --modes swarm' # plan table for the swarm line alias i8pi='pcd infinito' # cd to the infinito repo -alias i8puci='__i8puci(){ gips && i8cifail "$1" swarm; }; __i8puci' # sign-push + retrigger failed swarm CI jobs of run $1, skipping the quality gate -alias i8pufail='__i8pufail(){ gips && i8cifail "$1"; }; __i8pufail' # sign-push, then retrigger all failed roles (compose+swarm) of run $1 +alias i8puci='__i8puci(){ gips && i8cifail "$1"; }; __i8puci' # sign-push + retrigger the failed selections of run $1, skipping the quality gate +alias i8pufail='__i8pufail(){ gips && i8cifail "$1"; }; __i8pufail' # sign-push, then retrigger the failed selections of run $1 across every mode alias i8pufo='__i8pufo(){ gips && i8cifo "$1"; }; __i8pufo' # sign-push, then retrigger only hard-failed roles of run $1, excluding cancelled/aborted alias i8puma='__i8puma(){ local gates=() ok=1; case "${3:-}" in "") ;; true|false) gates=(-f workspace="$3" -f instructions="$3");; *) ok=0;; esac; { [ -z "${1:-}" ] || [ "$ok" = 0 ]; } && { echo "usage: i8puma [distros] [true|false]" >&2; return 2; }; i8source && gips && gh workflow run entry-manual.yml --repo "$(git remote get-url "$(git config --get remote.pushDefault)")" --ref "$(git rev-parse --abbrev-ref HEAD)" -f priority="$(python3 -m utils.roles.display --encode "$1")" -f distros="${2:-${INFINITO_DISTROS}}" "${gates[@]}"; }; __i8puma' # sign-push, then dispatch a manual CI run on the push remote (remote.pushDefault): priority line $1, distros $2 (default INFINITO_DISTROS), whitelist diff-derived; $3 true forces the workspace and instructions tests, false suppresses them, omitted leaves them on the workflow auto scope alias i8puwl='__i8puwl(){ [ -z "${1:-}" ] && { echo "usage: i8puwl [distros]" >&2; return 2; }; i8source && gh workflow run entry-manual.yml --repo "$(git remote get-url "$(git config --get remote.pushDefault)")" --ref "$(git rev-parse --abbrev-ref HEAD)" -f whitelist="$(python3 -m utils.roles.display --encode "$1")" -f distros="${2:-${INFINITO_DISTROS}}" -f workspace=false -f instructions=false; }; __i8puwl' # dispatch a manual CI run on the push remote (remote.pushDefault) limited to whitelist $1, distros $2 (default INFINITO_DISTROS), with the workspace and instructions tests off; pushes nothing, so the run uses whatever the remote already holds for the current branch @@ -134,6 +145,10 @@ alias i8tema='m test-main-merged' alias i8temesi='m test-merge-signed' alias i8teni='m test-integration' alias i8tenu='m test-unit' +alias i8tenuja='m test-unit-javascript' +alias i8tenuph='m test-unit-php' +alias i8tenupo='m test-unit-python' +alias i8tenuru='m test-unit-ruby' alias i8tepe='m test-performance' alias i8tesi='m test-signed' alias i8texe='m test-external' diff --git a/cli/__main__.py b/cli/__main__.py index fc32e94ea3..267a1b1781 100755 --- a/cli/__main__.py +++ b/cli/__main__.py @@ -4,14 +4,6 @@ from __future__ import annotations import sys from pathlib import Path -# This file is invoked directly as a script (the ``cli`` console-script -# entry-point and the integration help-test), in which case -# ``from . import PROJECT_ROOT`` fails with ``attempted relative import -# with no known parent package``. Compute the repo root -# locally and prepend it to sys.path before any project-package import -# resolves. Without this, sys.path[0] points to ``/cli`` and -# importing ``cli.*`` may accidentally resolve to an installed package -# from site-packages. # nocheck: project-root-import sys.path bootstrap before package imports resolve PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: diff --git a/cli/administration/deploy/ci/gh.py b/cli/administration/deploy/ci/gh.py new file mode 100644 index 0000000000..4e3a69a7b3 --- /dev/null +++ b/cli/administration/deploy/ci/gh.py @@ -0,0 +1,106 @@ +"""Git and ``gh`` plumbing for the CI deploy-run status/trigger commands.""" + +from __future__ import annotations + +import json +import re +import subprocess +import sys + + +def run_id_from_url(url: str) -> str: + match = re.search(r"/runs/(\d+)", url) + if not match: + raise ValueError(f"no run id found in URL: {url}") + return match.group(1) + + +def slug_from_url(url: str) -> str: + """Extract the ``owner/repo`` slug from a github.com URL (https or ssh).""" + match = re.search(r"github\.com[/:]([^/]+)/([^/]+?)(?:\.git)?(?:/|$)", url) + if not match: + raise ValueError(f"no owner/repo found in URL: {url}") + return f"{match.group(1)}/{match.group(2)}" + + +def _run(args: list[str]) -> str: + return subprocess.run( + args, check=True, capture_output=True, text=True + ).stdout.strip() + + +def _branch_remote() -> str: + """The remote the current branch tracks (e.g. a fork), falling back to + ``remote.pushDefault``, then 'origin' or the only configured remote.""" + try: + upstream = _run( + ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"] + ) + if "/" in upstream: + return upstream.split("/", 1)[0] + except subprocess.CalledProcessError: + pass + remotes = _run(["git", "remote"]).split() + try: + push_default = _run(["git", "config", "--get", "remote.pushDefault"]) + if push_default in remotes: + return push_default + except subprocess.CalledProcessError: + pass + if "origin" in remotes: + return "origin" + if not remotes: + raise RuntimeError("no git remote configured") + return remotes[0] + + +def resolve_repo() -> str: + """The ``owner/repo`` the current branch lives on, derived from its + tracking remote (not gh's default repo, which may be the upstream).""" + return slug_from_url(_run(["git", "remote", "get-url", _branch_remote()])) + + +def _gh(args: list[str], repo: str | None = None, check: bool = True) -> str: + """Run ``gh`` and return its stdout. + + Args: + args: the ``gh`` arguments, without the ``gh`` itself. + repo: appended as ``--repo`` when given. + check: abort the command on a non-zero exit. Pass ``False`` for calls + whose failure the caller handles, which then yields ``""``. + """ + cmd = ["gh", *args] + if repo: + cmd += ["--repo", repo] + proc = subprocess.run(cmd, check=False, capture_output=True, text=True) + if proc.returncode != 0: + if not check: + return "" + sys.stderr.write( + proc.stderr or f"gh exited {proc.returncode}: {' '.join(cmd)}\n" + ) + raise SystemExit(proc.returncode) + return proc.stdout + + +def current_branch() -> str: + return _run(["git", "rev-parse", "--abbrev-ref", "HEAD"]) + + +def fetch_jobs(run_id: str, repo: str | None = None) -> list[dict]: + return json.loads(_gh(["run", "view", run_id, "--json", "jobs"], repo=repo)).get( + "jobs", [] + ) + + +def fetch_run(run_id: str, repo: str | None = None) -> dict: + """Jobs plus the run title, in one ``gh`` call. + + The REST API answers ``inputs: null`` for a finished workflow_dispatch, so + the inputs are recovered from the run itself: short ones from the title + (``config_from_title``), the long ones from a called job's log + (``inputs_from_jobs``), which the title truncates. + """ + return json.loads( + _gh(["run", "view", run_id, "--json", "jobs,displayTitle"], repo=repo) + ) diff --git a/cli/administration/deploy/ci/runs.py b/cli/administration/deploy/ci/runs.py index d02ec27a87..ca038f8656 100644 --- a/cli/administration/deploy/ci/runs.py +++ b/cli/administration/deploy/ci/runs.py @@ -21,12 +21,16 @@ from __future__ import annotations import json import re -import subprocess -import sys -from utils.distros import distro_names +from cli.administration.deploy.ci.gh import ( + _gh, + fetch_jobs, +) +from utils.cache import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any from utils.github import run_name -from utils.roles.display import display_names +from utils.github.variant import axes +from utils.roles.display import display_names, split_axes from utils.symbol_glossary import to_emoji PASS = "✅" # noqa: S105 emoji glyph, not a credential @@ -37,25 +41,69 @@ MISSING = "➖" MODES = ("docker", "swarm", "host") +ENTRY_WORKFLOW = ".github/workflows/entry-manual-steer.yml" + +SELECTION_INPUTS = ("priority", "offset") +"""The two inputs a retrigger decides itself rather than carrying over. + +``priority`` IS the retrigger: it names what failed. ``offset`` follows from +it -- the source run already has a verdict for everything up to where its +budget ran out, so the regular line resumes behind that window +(:func:`resume_offset`) instead of repeating it. Everything else is carried +verbatim, including ``whitelist``, so a retrigger of a scoped run stays inside +that scope instead of quietly widening to the whole repository.""" + + +def dispatch_inputs() -> tuple[str, ...]: + """Every ``workflow_dispatch`` input the manual entry declares. + + Read from the workflow rather than listed here, so an input added to the + form is carried over without anyone remembering to teach this module about + it -- the failure mode otherwise is silent: the retrigger runs with that + input on its default and nothing says so. + """ + data = ( + load_yaml_any(str(PROJECT_ROOT / ENTRY_WORKFLOW), default_if_missing={}) or {} + ) + triggers = data.get("on") if isinstance(data.get("on"), dict) else data.get(True) + dispatch = triggers.get("workflow_dispatch") if isinstance(triggers, dict) else None + inputs = dispatch.get("inputs") if isinstance(dispatch, dict) else None + return tuple(inputs or ()) + + +def carried_inputs() -> tuple[str, ...]: + """The inputs a retrigger reproduces: every dispatch input except the + selection it computes itself.""" + return tuple(name for name in dispatch_inputs() if name not in SELECTION_INPUTS) + + CONFIG_INPUTS = ( "distros", - "modes", + "mode", "lifecycles", "filesystem", - "sequencing", - "mode_fail_fast", + "chunk_gate", "workspace", "instructions", ) +LOG_INPUTS = ("tor",) +"""Inputs the retrigger reads from the job log rather than the run title. + +The title renders these as glyphs, so recovering one means translating a +symbol back into a value; the log holds the word the operator picked. Reading +it there keeps the retrigger honest even if the title's marker changes shape. +""" + MODE_GLYPHS = { "docker": to_emoji("compose"), "swarm": to_emoji("swarm"), "host": to_emoji("host"), } -_GLYPH_MODE = {glyph: mode for mode, glyph in MODE_GLYPHS.items()} -_JOB_RE = re.compile(rf"({'|'.join(map(re.escape, MODE_GLYPHS.values()))})\s*(.+?)\s*$") +_STATUS_MODE = {"compose": "docker", "swarm": "swarm", "host": "host"} +"""The status table keeps calling compose 'docker'; the deploy axis calls it +'compose'. Translate at the boundary instead of renaming either vocabulary.""" def _effective(job: dict) -> str: @@ -78,21 +126,21 @@ def cell(state: str) -> str: def _iter_deploy_jobs(jobs: list[dict]): - """Yield ``(app, mode, job)`` for every compose/swarm deploy job.""" + """Yield ``(app, mode, job)`` for every deploy job.""" codec = display_names() for job in jobs: - match = _JOB_RE.search(str(job.get("name", ""))) - if not match: + label = axes.parse_label(str(job.get("name", ""))) + if label is None: continue - app = codec.decode(match.group(2)) + app = codec.decode(label.name) if app is not None: - yield app, _GLYPH_MODE[match.group(1)], job + yield app, _STATUS_MODE[label.mode], job def app_of_job(name: str) -> str | None: """The role id a deploy job ``name`` encodes, or None if it is not one.""" - match = _JOB_RE.search(name) - return display_names().decode(match.group(2)) if match else None + label = axes.parse_label(name) + return display_names().decode(label.name) if label else None _SEVERITY = {"success": 0, "running": 1, "failure": 3} @@ -171,91 +219,26 @@ def failed_roles( return sorted(app for app, modes in statuses.items() if fails(modes)) -def run_id_from_url(url: str) -> str: - match = re.search(r"/runs/(\d+)", url) - if not match: - raise ValueError(f"no run id found in URL: {url}") - return match.group(1) - - -def slug_from_url(url: str) -> str: - """Extract the ``owner/repo`` slug from a github.com URL (https or ssh).""" - match = re.search(r"github\.com[/:]([^/]+)/([^/]+?)(?:\.git)?(?:/|$)", url) - if not match: - raise ValueError(f"no owner/repo found in URL: {url}") - return f"{match.group(1)}/{match.group(2)}" - - -def _run(args: list[str]) -> str: - return subprocess.run( - args, check=True, capture_output=True, text=True - ).stdout.strip() - - -def _branch_remote() -> str: - """The remote the current branch tracks (e.g. a fork), falling back to - 'origin' or the only configured remote.""" - try: - upstream = _run( - ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"] - ) - if "/" in upstream: - return upstream.split("/", 1)[0] - except subprocess.CalledProcessError: - pass - remotes = _run(["git", "remote"]).split() - if "origin" in remotes: - return "origin" - if not remotes: - raise RuntimeError("no git remote configured") - return remotes[0] - - -def resolve_repo() -> str: - """The ``owner/repo`` the current branch lives on, derived from its - tracking remote (not gh's default repo, which may be the upstream).""" - return slug_from_url(_run(["git", "remote", "get-url", _branch_remote()])) - - -def _gh(args: list[str], repo: str | None = None) -> str: - cmd = ["gh", *args] - if repo: - cmd += ["--repo", repo] - proc = subprocess.run(cmd, check=False, capture_output=True, text=True) - if proc.returncode != 0: - sys.stderr.write( - proc.stderr or f"gh exited {proc.returncode}: {' '.join(cmd)}\n" - ) - raise SystemExit(proc.returncode) - return proc.stdout - - -def current_branch() -> str: - return _run(["git", "rev-parse", "--abbrev-ref", "HEAD"]) - - -def fetch_jobs(run_id: str, repo: str | None = None) -> list[dict]: - return json.loads(_gh(["run", "view", run_id, "--json", "jobs"], repo=repo)).get( - "jobs", [] - ) - - -def fetch_run(run_id: str, repo: str | None = None) -> dict: - """Jobs plus the run title, in one ``gh`` call. - - The REST API answers ``inputs: null`` for a finished workflow_dispatch, so - the inputs are recovered from the run itself: short ones from the title - (:func:`config_from_title`), the long ones from a called job's log - (:func:`inputs_from_jobs`), which the title truncates. - """ - return json.loads( - _gh(["run", "view", run_id, "--json", "jobs,displayTitle"], repo=repo) - ) - - _INPUT_RE = re.compile(r"^\S+\s+(?P[A-Za-z_][A-Za-z0-9_]*): ?(?P.*)$") +def _parse_inputs(log: str) -> dict[str, str]: + """The ``##[group] Inputs`` block of a job log, as name -> value.""" + inputs: dict[str, str] = {} + inside = False + for line in log.splitlines(): + if line.endswith("##[group] Inputs"): + inside = True + continue + if inside: + if line.endswith("##[endgroup]"): + break + match = _INPUT_RE.match(line) + if match: + inputs[match["name"]] = match["value"].strip() + return inputs + + def inputs_from_jobs(jobs: list[dict], repo: str) -> dict[str, str]: """The dispatch inputs a called job's log records verbatim. @@ -269,38 +252,45 @@ def inputs_from_jobs(jobs: list[dict], repo: str) -> dict[str, str]: workflow opens its log with an ``##[group] Inputs`` block holding the full values, so that is the SPOT for anything the title cannot hold. + Candidates are read shallowest first, because a depth-1 job records the + orchestrator's own inputs while a deeper one records what its caller + forwarded. Skipped jobs are passed over: they never upload a log blob, so + their log endpoint answers ``BlobNotFound`` as a bare HTTP 404 -- and a + force-cancelled run can leave every depth-1 job skipped, which is why the + deeper jobs are read at all rather than treated as inputs-free. + Args: - jobs: the run's jobs. Only depth-1 jobs are read: a deeper one echoes - its own workflow's inputs, which carry no ``priority``. + jobs: the run's jobs, as ``gh run view --json jobs`` returns them. repo: ``owner/repo`` the run lives in. Returns: - input name -> value, empty when the run has no called job. + input name -> value, empty when no job of the run records an ``Inputs`` + block -- including when the logs have expired. """ - called = next( + candidates = sorted( ( job for job in jobs - if str(job.get("name", "")).count(" / ") == 1 and job.get("databaseId") + if str(job.get("name", "")).count(" / ") >= 1 + and job.get("databaseId") + and job.get("conclusion") != "skipped" ), - None, + key=lambda job: str(job["name"]).count(" / "), ) - if called is None: - return {} - log = _gh(["api", f"repos/{repo}/actions/jobs/{called['databaseId']}/logs"]) - inputs: dict[str, str] = {} - inside = False - for line in log.splitlines(): - if line.endswith("##[group] Inputs"): - inside = True - continue - if inside: - if line.endswith("##[endgroup]"): - break - match = _INPUT_RE.match(line) - if match: - inputs[match["name"]] = match["value"].strip() - return inputs + for job in candidates: + inputs = _parse_inputs( + _gh( + [ + "api", + "--allow-escape-sequences", + f"repos/{repo}/actions/jobs/{job['databaseId']}/logs", + ], + check=False, + ) + ) + if inputs: + return inputs + return {} def dispatched_priority(source: dict, repo: str) -> str: @@ -335,42 +325,35 @@ def untriggered_priority( neither green nor red, it simply never ran. Carrying it into the retrigger is the only way it ever gets deployed. + A priority entry may pin axes (``web-app-zammad#1@compose+tor``), and the + pin rides along into the retrigger: the entry never ran, so the run holds + no evidence that the axes it named were the wrong ones. Only the name in + front of the axis suffix is resolved against the statuses. + Args: priority: the raw ``priority`` input, as :func:`inputs_from_jobs` reads it back. A truncated value would smuggle a half-token into the retrigger's role set, so an undecodable name raises instead. statuses: role -> mode -> state, from :func:`parse_role_statuses`. + + Returns: + the entries whose role has no job at all in the source run, each with + its own axis suffix intact. """ codec = display_names() - named = [] - for name in priority.split(): + untriggered = [] + for token in priority.split(): + name, axes = split_axes(token) role = codec.decode(name) if role is None: raise SystemExit( - f"Cannot resolve priority entry {name!r} to a role. The source " + f"Cannot resolve priority entry {token!r} to a role. The source " f"run's priority input is corrupt or truncated; retriggering " f"with it would deploy a role set that is silently incomplete." ) - named.append(role) - return sorted(role for role in named if role not in statuses) - - -def distros_from_jobs(jobs: list[dict]) -> str: - """Distros the run actually swept, read back from its discover job names. - - A manual run dispatched with no distro list resolves one at random, so its - title records nothing and only the discover jobs — which name the distros - they discovered for — still carry the answer. Matched by content, not by - job-name format: the parenthesised group whose every token is a declared - distro (meta/distros.yml SPOT) is the list. - """ - known = set(distro_names()) - for job in jobs: - for group in re.findall(r"\(([^()]*)\)", str(job.get("name", ""))): - tokens = group.split() - if tokens and set(tokens) <= known: - return " ".join(tokens) - return "" + if role not in statuses: + untriggered.append(role + axes) + return sorted(untriggered) def config_from_title(title: str) -> dict[str, str]: @@ -387,12 +370,27 @@ def config_from_title(title: str) -> dict[str, str]: return {name: recorded[name] for name in CONFIG_INPUTS if name in recorded} -def config_from_run(title: str, jobs: list[dict]) -> dict[str, str]: - """The source run's configuration, with the distros the title does not - record recovered from its jobs (:func:`distros_from_jobs`).""" - config = config_from_title(title) - if not config.get("distros"): - config = {**config, "distros": distros_from_jobs(jobs)} +def config_from_run(title: str, logged: dict[str, str] | None = None) -> dict[str, str]: + """Every input the source run was dispatched with, except the selection. + + The job log is the source: it records all inputs verbatim, including the + ones the title renders as a glyph and the ones it renders not at all. The + title fills the gaps when a log is unreadable. + + An input the source left on its default resolves to empty and is dropped, + so the retrigger leaves it on that same default rather than pinning + today's default into a run that never asked for it. + + Args: + title: the source run's display title. + logged: inputs read verbatim from a called job's log + (:func:`inputs_from_jobs`). + """ + recorded = run_name.values_from_title(title) + config = { + name: (logged or {}).get(name) or recorded.get(name, "") + for name in carried_inputs() + } return {name: value for name, value in config.items() if value} diff --git a/cli/administration/deploy/ci/selections.py b/cli/administration/deploy/ci/selections.py new file mode 100644 index 0000000000..d41adc6515 --- /dev/null +++ b/cli/administration/deploy/ci/selections.py @@ -0,0 +1,136 @@ +"""Turn a run's deploy jobs back into selection tokens. + +A deploy job title carries the whole row it deployed -- role, variant, mode, +onion state, distro, filesystem -- and :mod:`utils.github.variant.selection` +is the grammar that writes it back down. + +The filesystem is the one axis a token built here leaves out. The title states +the kind the matrix *assigned*, which a deploy is allowed to fall back from +when the host cannot serve it, so the title does not prove what the job ran on. +Writing it into a token would also state it as named by a human, which makes it +binding (:func:`utils.github.variant.axes.assign`): a retrigger would then fail +on the very condition the fallback exists to absorb. The retrigger lets the +rotation assign it again and reports what it got. Reading the tokens out of a finished run is what lets a +retrigger replay exactly what failed and start the regular line where that run +stopped, instead of aggregating to role ids and guessing the rest. +""" + +from __future__ import annotations + +from utils.github.variant import axes, selection + +from .runs import _effective, _iter_deploy_jobs + + +def failed_selections(jobs: list[dict], *, strict: bool = False) -> list[str]: + """The selection tokens that reproduce exactly what did not pass. + + A role aggregated to its id loses what actually broke: the retrigger then + redeploys every variant of it, in whatever mode and onion state the sweep + rotation happens to pick, and the combination that failed may not be among + them. Each failed job therefore contributes its own + ``role#variant@mode+tor`` token (:mod:`utils.github.variant.selection`), so + the priority line replays that job and nothing else. + + Every mode is read; there is no scope to narrow to. A run that failed in + swarm and in compose comes back as two tokens for the same role. + + Args: + jobs: the source run's jobs. + strict: only hard failures (❌) count; cancelled, timed out and still + running are left out. + + Returns: + sorted, deduplicated tokens. + """ + tokens = set() + for app, _mode, job in _iter_deploy_jobs(jobs): + state = _effective(job) + if state == "success" or (strict and state != "failure"): + continue + label = axes.parse_label(str(job.get("name", ""))) + tokens.add( + selection.describe( + selection.Pin( + app, + tuple(int(part) for part in label.variant.split(",") if part), + label.mode, + label.tor, + label.distro or None, + ) + ) + ) + return sorted(tokens) + + +def deployed_selections(jobs: list[dict]) -> set[str]: + """Every selection the source run actually deployed, green or red. + + The verdict is irrelevant here: what matters is that the run reached the + row at all, because that is what a retrigger no longer has to repeat. + """ + return { + selection.describe( + selection.Pin( + app, + tuple(int(part) for part in label.variant.split(",") if part), + label.mode, + label.tor, + label.distro or None, + ) + ) + for app, _mode, job in _iter_deploy_jobs(jobs) + if (label := axes.parse_label(str(job.get("name", "")))) is not None + } + + +def resume_offset(regular: list[dict[str, str]], deployed: set[str]) -> str: + """Where a retrigger should pick the regular line up again. + + The source run deployed a window of the ranking and stopped at its budget. + Everything inside that window has a verdict -- the red rows come back on + the priority line anyway -- so the regular line has no reason to walk it a + second time. The answer is the last row of the leading run of deployed + rows, as a selection token: a token still names the same row after the + ranking shifts, a row count does not. + + Stops at the first gap. A hole inside the window means that row was + filtered out, not that the run got further, and resuming past it would skip + whatever follows. + + Args: + regular: the regular line of the retrigger's own discovery, in ranking + order. + deployed: tokens the source run deployed (:func:`deployed_selections`). + + Returns: + the ``role#variant`` token to resume at, or ``''`` when the source run + deployed nothing of this line -- then the retrigger starts at the head, + as it would without an offset. + + The returned token names a place in the ranking, so it carries no axes. + Membership is still tested on the full deploy token, because that is + what the source run recorded; but every axis rotates with the sweep + number, and the retrigger gets a fresh one. An axis-pinned offset would + therefore resolve only in the rare sweep whose rotation happens to + reproduce the source run's combination, and abort the discovery of + every chunk in all the others. + """ + resume = "" + for entry in regular: + variants = tuple( + int(part) for part in str(entry.get("variant", "")).split(",") if part + ) + deployment = selection.describe( + selection.Pin( + entry["apps"], + variants, + entry["mode"], + entry["tor"] == "true", + entry["distro"], + ) + ) + if deployment not in deployed: + break + resume = selection.describe(selection.Pin(entry["apps"], variants)) + return resume diff --git a/cli/administration/deploy/ci/status/__main__.py b/cli/administration/deploy/ci/status/__main__.py index 0ac8541471..6594876ab1 100644 --- a/cli/administration/deploy/ci/status/__main__.py +++ b/cli/administration/deploy/ci/status/__main__.py @@ -5,7 +5,7 @@ from __future__ import annotations import argparse import sys -from cli.administration.deploy.ci import runs +from cli.administration.deploy.ci import gh, runs def _build_rows( @@ -87,12 +87,12 @@ def main(argv: list[str] | None = None) -> int: if args.url: jobs = runs.fetch_jobs( - runs.run_id_from_url(args.url), repo=runs.slug_from_url(args.url) + gh.run_id_from_url(args.url), repo=gh.slug_from_url(args.url) ) source = args.url else: - branch = runs.current_branch() - repo = runs.resolve_repo() + branch = gh.current_branch() + repo = gh.resolve_repo() run = runs.find_last_deploy_run(branch, repo=repo) if run is None: print( diff --git a/cli/administration/deploy/ci/trigger/__main__.py b/cli/administration/deploy/ci/trigger/__main__.py index 1ac5ab9d33..88295a383d 100644 --- a/cli/administration/deploy/ci/trigger/__main__.py +++ b/cli/administration/deploy/ci/trigger/__main__.py @@ -2,6 +2,13 @@ entry-manual-steer.yml reads the "__ALL__" whitelist sentinel as "force a full deploy across all roles". + +A retrigger differs from its source run in the selection and in nothing else: +every other dispatch input is carried over (:func:`runs.carried_inputs`, read +off the workflow itself), and the priority line names the exact selections that +failed -- role, variant, deploy mode, onion state and distro -- rather than the +roles they belong to. The filesystem is left to the rotation +(:mod:`cli.administration.deploy.ci.selections` says why). """ from __future__ import annotations @@ -9,7 +16,9 @@ from __future__ import annotations import argparse import sys -from cli.administration.deploy.ci import runs +from cli.administration.deploy.ci import gh, runs, selections +from cli.meta.ci import matrix, query +from utils.github.variant import pools, tor _WORKFLOW = "entry-manual-steer.yml" _ALL = "__ALL__" @@ -19,8 +28,36 @@ def _fetch(run: str, repo: str) -> dict: """The jobs and title of *run*, given as a URL or a bare id (which resolves against *repo*, the current branch's own).""" if run.isdigit(): - return runs.fetch_run(run, repo=repo) - return runs.fetch_run(runs.run_id_from_url(run), repo=runs.slug_from_url(run)) + return gh.fetch_run(run, repo=repo) + return gh.fetch_run(gh.run_id_from_url(run), repo=gh.slug_from_url(run)) + + +def _resume_offset(source: dict, whitelist: str, config: dict[str, str]) -> str: + """Where the retrigger's regular line should start. + + The source run walked the ranking until its budget ran out. Those rows + have a verdict already -- and the red ones return on the priority line -- + so the regular line resumes behind them instead of redeploying the same + window. The ranking is recomputed under the retrigger's own configuration, + because that is the list the offset will be resolved against. + + The priority line is deliberately left out of that computation: it only + blacklists rows from the regular query, and a token in it that no longer + resolves would abort here, in a helper whose job is to save runner time. + """ + entries = matrix.entries_of( + modes=query.resolve_modes(config.get("mode") or query.ALL_MODES), + whitelist="" if whitelist == _ALL else whitelist, + priority="", + lifecycles=config.get("lifecycles", ""), + sweep=0, + tor_mode=tor.resolve_tor_mode(config.get("tor")), + distros=pools.resolve_distros(config.get("distros")), + filesystems=pools.resolve_filesystems(config.get("filesystem")), + ) + return selections.resume_offset( + entries, selections.deployed_selections(source["jobs"]) + ) def main(argv: list[str] | None = None) -> int: @@ -39,16 +76,16 @@ def main(argv: list[str] | None = None) -> int: group.add_argument( "--failed", nargs="?", - const="total", + const=True, default=None, - choices=("total", "swarm", "compose", "docker", "host"), - metavar="{total,swarm,compose,host}", + metavar="(ignored)", help=( - "Re-trigger roles that were not green in the source run as the " - "priority line, together with the priority roles that run never " - "deployed at all; the remaining roles follow once they succeed. " - "Optional scope: 'total' (default; failed in any mode), " - "'swarm', 'compose', or 'host'." + "Re-trigger what was not green in the source run as the priority " + "line, together with the priority entries that run never deployed " + "at all; the remaining roles follow once they succeed. Every mode " + "is read, and each failed job comes back as the exact selection " + "that failed -- variant, deploy mode and onion state included. A " + "leftover scope argument is accepted and ignored." ), ) group.add_argument( @@ -63,7 +100,7 @@ def main(argv: list[str] | None = None) -> int: metavar="URL|ID", help=( "Run URL or bare run id to reproduce: its configuration (distros, " - "modes, lifecycles, filesystem, sequencing, mode_fail_fast, " + "mode, lifecycles, filesystem, chunk_gate, " "workspace, instructions) is carried over, and with --failed its " "results also pick the apps. A bare id resolves against the current " "branch's repo. With --failed and no --run: the latest deploy run " @@ -82,8 +119,8 @@ def main(argv: list[str] | None = None) -> int: if args.strict and args.failed is None: p.error("--strict only applies with --failed") - branch = runs.current_branch() - repo = runs.resolve_repo() + branch = gh.current_branch() + repo = gh.resolve_repo() source = None if args.run: @@ -106,14 +143,13 @@ def main(argv: list[str] | None = None) -> int: p.error("--apps was empty") whitelist = apps elif args.failed is not None: - scope = "docker" if args.failed == "compose" else args.failed statuses = runs.parse_role_statuses(source["jobs"]) - failed = runs.failed_roles(statuses, scope, strict=args.strict) + failed = selections.failed_selections(source["jobs"], strict=args.strict) untriggered = runs.untriggered_priority( runs.dispatched_priority(source, repo), statuses ) if not failed and not untriggered: - print(f"Nothing failed ({args.failed}) in that run; not triggering.") + print("Nothing failed in that run; not triggering.") return 0 if untriggered: print(f"Priority roles that never deployed: {' '.join(untriggered)}") @@ -123,7 +159,20 @@ def main(argv: list[str] | None = None) -> int: config: dict[str, str] = {} if source is not None: - config = runs.config_from_run(source["displayTitle"], source["jobs"]) + config = runs.config_from_run( + source["displayTitle"], + runs.inputs_from_jobs(source["jobs"], repo), + ) + carried_whitelist = config.pop("whitelist", "") + if not whitelist and carried_whitelist: + whitelist = carried_whitelist + + if args.failed is not None: + config["offset"] = _resume_offset(source, whitelist, config) + if config["offset"]: + print(f"Regular line resumes at: {config['offset']}") + else: + config.pop("offset") if priority: label = f"priority {priority}, then the remaining roles" diff --git a/cli/administration/deploy/container/command.py b/cli/administration/deploy/container/command.py index 82095f4cb3..99d4131fa3 100644 --- a/cli/administration/deploy/container/command.py +++ b/cli/administration/deploy/container/command.py @@ -87,7 +87,6 @@ def wait_for_docker_socket(container: str, timeout: int = 60) -> None: """ print(">>> Waiting for Docker to be usable inside CI container...") - # 0) Verify docker CLI exists which = _docker_exec_capture(container, ["sh", "-lc", "command -v docker || true"]) docker_path = (which.stdout or "").strip() if not docker_path: @@ -106,7 +105,6 @@ def wait_for_docker_socket(container: str, timeout: int = 60) -> None: f"[diag stderr]\n{diag.stderr}\n" ) - # 2) Poll docker info last_out = "" last_err = "" for _ in range(timeout): @@ -118,7 +116,6 @@ def wait_for_docker_socket(container: str, timeout: int = 60) -> None: print(">>> Docker is usable inside container.") return - # capture a bit more detail for later dv = _docker_exec_capture( container, ["sh", "-lc", "docker version 2>&1 || true"] ) @@ -209,7 +206,6 @@ def run_in_container( name=name, ) - # 1) Create CI inventory print( ">>> Creating CI inventory inside container " "(infinito administration inventory provision)..." @@ -231,7 +227,6 @@ def run_in_container( check=True, ) - # 1b) Mock backup authorized_keys file for user-backup print(">>> Mocking backup authorized_keys file inside CI inventory...") mock_key = os.environ.get( "AUTHORIZED_KEYS", @@ -249,7 +244,6 @@ def run_in_container( ) docker_exec(container_name, ["bash", "-lc", mock_cmd], check=True) - # 2) Ensure vault password file exists print(">>> Ensuring CI vault password file exists...") ensure_pw_cmd = ( f"mkdir -p {shlex.quote(inv_root)} && " @@ -262,7 +256,6 @@ def run_in_container( check=True, ) - # 3) Run dedicated deploy cmd = [ "python3", "-m", diff --git a/cli/administration/deploy/dedicated/command.py b/cli/administration/deploy/dedicated/command.py index 8bb8c1a709..3e2a4cfdee 100644 --- a/cli/administration/deploy/dedicated/command.py +++ b/cli/administration/deploy/dedicated/command.py @@ -99,7 +99,6 @@ def build_parser() -> argparse.ArgumentParser: add_help=False, ) - # Custom combined help (-h / --help) parser.add_argument( "-h", "--help", @@ -108,7 +107,6 @@ def build_parser() -> argparse.ArgumentParser: help="Show this help message and ansible-playbook --help.", ) - # Standard arguments parser.add_argument("inventory", help="Path to the inventory file.") parser.add_argument( "-l", "--limit", help="Limit execution to certain hosts or groups." @@ -165,7 +163,6 @@ def _normalize_app_ids(raw_ids: list[str]) -> list[str]: parts = [p.strip() for p in item.split(",") if p.strip()] result.extend(parts) - # remove duplicates while preserving order seen = set() unique: list[str] = [] for app in result: diff --git a/cli/administration/deploy/dedicated/modes.py b/cli/administration/deploy/dedicated/modes.py index 4a421593b5..0f14280492 100644 --- a/cli/administration/deploy/dedicated/modes.py +++ b/cli/administration/deploy/dedicated/modes.py @@ -58,7 +58,7 @@ def load_modes_from_yaml(modes_yaml_path: str) -> list[dict[str, Any]]: modes.append( { "name": key, - "default": default_bool, # True/False/None + "default": default_bool, "help": cmt or f"Toggle {key}", } ) @@ -83,21 +83,18 @@ def add_dynamic_mode_args( short = name.replace("MODE_", "").lower() if default is True: - # MODE_FOO: true → --skip-foo disables it opt = f"--skip-{short}" dest = f"skip_{short}" parser.add_argument(opt, action="store_true", dest=dest, help=desc) spec[name] = {"dest": dest, "default": True, "kind": "bool_true"} elif default is False: - # MODE_BAR: false → --bar enables it opt = f"--{short}" dest = short parser.add_argument(opt, action="store_true", dest=dest, help=desc) spec[name] = {"dest": dest, "default": False, "kind": "bool_false"} else: - # MODE_XYZ: null → --xyz true|false opt = f"--{short}" dest = short parser.add_argument(opt, choices=["true", "false"], dest=dest, help=desc) @@ -118,11 +115,9 @@ def build_modes_from_args( value = getattr(args_namespace, dest, None) if kind == "bool_true": - # if user passed --skip-foo => disable => False, otherwise True modes[mode_name] = not value elif kind == "bool_false": - # if user passed --bar => enable => True, otherwise False modes[mode_name] = bool(value) elif value is not None: diff --git a/cli/administration/deploy/dedicated/runner.py b/cli/administration/deploy/dedicated/runner.py index ba4d23773d..e388d7555f 100644 --- a/cli/administration/deploy/dedicated/runner.py +++ b/cli/administration/deploy/dedicated/runner.py @@ -34,19 +34,19 @@ def run_ansible_playbook( ) -> None: """Run ansible-playbook with the given parameters and execution modes.""" start_time = datetime.datetime.now(tz=datetime.UTC) - print(f"\n▶️ Script started at: {start_time.isoformat()}\n") + print(f"\n▶️ Script started at: {start_time.isoformat()}\n", flush=True) if modes.get("MODE_CLEANUP", False): print("\n🧹 Cleaning up...\n", flush=True) run_make(repo_root, "clean") else: - print("\n🧹 Cleanup skipped (MODE_CLEANUP not set or False)\n") + print("\n🧹 Cleanup skipped (MODE_CLEANUP not set or False)\n", flush=True) if not skip_build: - print("\n🛠️ Running project build (make setup)...\n") + print("\n🛠️ Running project build (make setup)...\n", flush=True) run_make(repo_root, "setup") else: - print("\n🛠️ Build skipped (--skip-build)\n") + print("\n🛠️ Build skipped (--skip-build)\n", flush=True) try: assert_services_disabled_inventory_consistency_from_env( @@ -58,9 +58,12 @@ def run_ansible_playbook( sys.exit(1) if modes.get("MODE_ASSERT") is False: - print("\n🔍 Inventory assertion explicitly disabled (MODE_ASSERT=false)\n") + print( + "\n🔍 Inventory assertion explicitly disabled (MODE_ASSERT=false)\n", + flush=True, + ) else: - print("\n🔍 Validating inventory before deployment...\n") + print("\n🔍 Validating inventory before deployment...\n", flush=True) try: run( [sys.executable, inventory_validator_path, str(Path(inventory).parent)], @@ -111,7 +114,7 @@ def run_ansible_playbook( except OSError: log_offset_before = 0 - print("\n🚀 Launching Ansible Playbook...\n") + print("\n🚀 Launching Ansible Playbook...\n", flush=True) result = subprocess.run(cmd, cwd=repo_root, check=False) if result.returncode != 0: diff --git a/cli/administration/deploy/development/README.md b/cli/administration/deploy/development/README.md index 960d6ce255..80214597b4 100644 --- a/cli/administration/deploy/development/README.md +++ b/cli/administration/deploy/development/README.md @@ -111,6 +111,7 @@ flowchart LR | ------------------------------------- | ------------------ | | literal `true` | yes | | `"{{ '' in group_names }}"` | yes | +| `"{{ '' not in group_names }}"` | yes | | literal `false` | no | So a conditional `"{{ 'web-app-matomo' in group_names }}"` edge pulls its diff --git a/cli/administration/deploy/development/cli.py b/cli/administration/deploy/development/cli.py index 122802de67..686cb52fe9 100644 --- a/cli/administration/deploy/development/cli.py +++ b/cli/administration/deploy/development/cli.py @@ -42,7 +42,6 @@ def _build_parser(base_pkg: str) -> argparse.ArgumentParser: ) sub = p.add_subparsers(dest="command", required=True) - # Keep this list explicit (predictable UX), but tolerate missing modules. command_names = [ "up", "down", @@ -73,7 +72,6 @@ def main(argv: list[str] | None = None) -> int: handler = getattr(args, "_handler", None) if handler is None: - # This should not happen if each subparser sets _handler, but keep it safe. raise SystemExit( f"Command '{getattr(args, 'command', '')}' has no handler" ) diff --git a/cli/administration/deploy/development/compose.py b/cli/administration/deploy/development/compose.py index 91539db02c..682c955d3a 100644 --- a/cli/administration/deploy/development/compose.py +++ b/cli/administration/deploy/development/compose.py @@ -201,7 +201,7 @@ class Compose: if self.profile.owns_cache_stack(): self._bootstrap_package_cache(env) - if self.profile.registry_cache_active(): + if self.profile.cache_stack_enabled(): self._install_package_frontend_ca_in_runner() if run_entry_init: diff --git a/cli/administration/deploy/development/down.py b/cli/administration/deploy/development/down.py index e955e288df..2bd29871d6 100644 --- a/cli/administration/deploy/development/down.py +++ b/cli/administration/deploy/development/down.py @@ -38,7 +38,9 @@ def _wipe_docker_root(docker_root: Path) -> None: def _should_wipe_docker_root() -> bool: - if os.environ.get("INFINITO_RUNNING_ON_GITHUB") != "true": + from .profile import Profile + + if not Profile().docker_root_ephemeral(): return False return os.environ.get("INFINITO_PRESERVE_DOCKER_CACHE") != "true" diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py index 19464f5582..f22b27622f 100644 --- a/cli/administration/deploy/development/env.py +++ b/cli/administration/deploy/development/env.py @@ -21,7 +21,7 @@ def compose_file_args() -> list[str]: out = ["-f", "compose.yml"] if profile.shared_git_dir(): out += ["-f", "compose/worktree.override.yml"] - if profile.registry_cache_active(): + if profile.cache_stack_enabled(): out += ["-f", "compose/cache.override.yml"] if profile.shared_cache_network(): out += ["-f", "compose/cache.shared.override.yml"] diff --git a/cli/administration/deploy/development/exec.py b/cli/administration/deploy/development/exec.py index 2c29a70506..08418ef9f9 100644 --- a/cli/administration/deploy/development/exec.py +++ b/cli/administration/deploy/development/exec.py @@ -55,8 +55,6 @@ def handler(args: argparse.Namespace) -> int: if services_disabled: extra_env["disable"] = services_disabled - # Caller-supplied --env entries win over implicit ones (current convention - # in the dev CLI: explicit user input overrides implicit defaults). extra_env.update(_parse_env_pairs(args.env or [])) r = compose.exec(cmd, check=False, extra_env=extra_env or None) diff --git a/cli/administration/deploy/development/inventory/builder.py b/cli/administration/deploy/development/inventory/builder.py index fd904da912..78124c142b 100644 --- a/cli/administration/deploy/development/inventory/builder.py +++ b/cli/administration/deploy/development/inventory/builder.py @@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, Any from cli.administration.deploy.development.common import DEV_INVENTORY_VARS_FILE from cli.administration.deploy.development.mirrors import ( generate_ci_mirrors_file, - should_use_mirrors_on_ci, + should_use_mirrors, ) from .payload import _bake_overrides, _resolve_variant_payloads @@ -66,7 +66,7 @@ def build_dev_inventory(compose: Compose, spec: DevInventorySpec) -> None: if variant_selectors: cmd += ["--app-variants", json.dumps(variant_selectors, sort_keys=True)] - if should_use_mirrors_on_ci(): + if should_use_mirrors(): mirrors_file = generate_ci_mirrors_file(compose, inventory_dir=inv_root) cmd += ["--mirror", mirrors_file] diff --git a/cli/administration/deploy/development/inventory/payload.py b/cli/administration/deploy/development/inventory/payload.py index 38d87f3662..588decaec3 100644 --- a/cli/administration/deploy/development/inventory/payload.py +++ b/cli/administration/deploy/development/inventory/payload.py @@ -64,9 +64,6 @@ def _bake_overrides( if not isinstance(existing_apps, Mapping): existing_apps = {} apps: dict[str, Any] = dict(variant_payloads.items()) - # Caller-supplied `applications.*` entries deep-overlay the variant - # payload so overrides like `applications.web-app-foo.feature_flag` from - # `--vars` still take precedence. for app_id, override in existing_apps.items(): base_payload = apps.get(app_id) if isinstance(base_payload, Mapping) and isinstance(override, Mapping): diff --git a/cli/administration/deploy/development/inventory/planner.py b/cli/administration/deploy/development/inventory/planner.py index a6e78a87d4..8dcfdff18d 100644 --- a/cli/administration/deploy/development/inventory/planner.py +++ b/cli/administration/deploy/development/inventory/planner.py @@ -67,7 +67,6 @@ def plan_dev_inventory_matrix( total_rounds = max(primary_variant_counts.values(), default=1) base = str(base_inventory_dir).rstrip("/") - # WHY split: per-round include is variant-specific; purge_set is the union so the inter-round wipe clears every variant's footprint, not just the previous round's slice. per_variant_includes: list[tuple[str, ...]] = [] primary_round_variants_per_round: list[dict[str, int]] = [] for round_index in range(total_rounds): diff --git a/cli/administration/deploy/development/inventory/spec.py b/cli/administration/deploy/development/inventory/spec.py index 8b26be56b5..7ad92e5095 100644 --- a/cli/administration/deploy/development/inventory/spec.py +++ b/cli/administration/deploy/development/inventory/spec.py @@ -15,7 +15,6 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import Mapping -# (round_index, inventory_dir, round_variants, include, purge_set) — include is the round's variant-closure (what to deploy); purge_set is the union over all rounds (what the inter-round wipe clears). PlanEntry = tuple[int, str, dict[str, int], tuple[str, ...], tuple[str, ...]] diff --git a/cli/administration/deploy/development/mirrors.py b/cli/administration/deploy/development/mirrors.py index 1771e9975f..8d7b14f034 100644 --- a/cli/administration/deploy/development/mirrors.py +++ b/cli/administration/deploy/development/mirrors.py @@ -14,22 +14,11 @@ def _require_env(name: str) -> str: return str(val).strip() -def _require_bool_env(name: str) -> bool: - raw = _require_env(name) - if raw == "true": - return True - if raw == "false": - return False - raise RuntimeError( - f"Environment variable {name} must be 'true' or 'false', got {raw!r}" - ) +def should_use_mirrors() -> bool: + """True iff image references should be rewritten to the GHCR mirror.""" + from .profile import Profile - -def should_use_mirrors_on_ci() -> bool: - """ - Mirrors are enabled strictly based on INFINITO_RUNNING_ON_GITHUB. - """ - return _require_bool_env("INFINITO_RUNNING_ON_GITHUB") + return Profile().image_mirror_enabled() def _exec_env() -> dict[str, str]: diff --git a/cli/administration/deploy/development/proc.py b/cli/administration/deploy/development/proc.py index 115da733d3..e7d905dc53 100644 --- a/cli/administration/deploy/development/proc.py +++ b/cli/administration/deploy/development/proc.py @@ -43,11 +43,9 @@ def run_streaming( stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, - bufsize=1, # line buffered (best effort) + bufsize=1, ) - # Type-narrowing asserts so the type checker sees the streams as - # non-None below (PIPE was passed); these never fire at runtime. assert p.stdout is not None # noqa: S101 assert p.stderr is not None # noqa: S101 @@ -67,7 +65,6 @@ def run_streaming( rc = p.wait() - # Process is finished; drain threads should finish quickly too. t_out.join() t_err.join() diff --git a/cli/administration/deploy/development/profile.py b/cli/administration/deploy/development/profile.py index 756bddbd7e..04d8203807 100644 --- a/cli/administration/deploy/development/profile.py +++ b/cli/administration/deploy/development/profile.py @@ -5,8 +5,18 @@ from __future__ import annotations import os +def _declared(name: str) -> bool | None: + """Explicit capability declaration, or None when it is left to the default.""" + raw = (os.environ.get(name) or "").strip() + if raw == "true": + return True + if raw == "false": + return False + return None + + class Profile: - """Runtime-context flags consumed by the compose wrapper.""" + """Runtime identity and the capability decisions derived from it.""" def is_ci(self) -> bool: """True when any standard CI signal is set.""" @@ -16,9 +26,22 @@ class Profile: or os.environ.get("CI") == "true" ) - def registry_cache_active(self) -> bool: - """True iff the cache stack should be loaded (local dev only).""" - return not self.is_ci() + def runs_on_github(self) -> bool: + """True on a real GitHub runner; act and generic CI are not that.""" + return os.environ.get("INFINITO_RUNNING_ON_GITHUB") == "true" + + def cache_stack_enabled(self) -> bool: + """True iff the pull-through cache stack should be loaded.""" + declared = _declared("INFINITO_CACHE_STACK") + return (not self.is_ci()) if declared is None else declared + + def image_mirror_enabled(self) -> bool: + """True iff image references should be rewritten to the GHCR mirror.""" + return self.runs_on_github() + + def docker_root_ephemeral(self) -> bool: + """True iff the docker data root may be wiped when the stack goes down.""" + return self.runs_on_github() def instance(self) -> int: """Slot index of this checkout; 0 is the primary one. @@ -40,4 +63,4 @@ class Profile: def owns_cache_stack(self) -> bool: """True iff this instance runs the cache stack rather than sharing it.""" - return self.registry_cache_active() and not self.shared_cache_network() + return self.cache_stack_enabled() and not self.shared_cache_network() diff --git a/cli/administration/deploy/development/restart.py b/cli/administration/deploy/development/restart.py index 2b61cab767..957a600bd2 100644 --- a/cli/administration/deploy/development/restart.py +++ b/cli/administration/deploy/development/restart.py @@ -22,14 +22,12 @@ def add_parser(sub: argparse._SubParsersAction) -> None: def handler(args: argparse.Namespace) -> int: - # 1) stop (best-effort) stop_rc = stop_handler(argparse.Namespace()) if stop_rc != 0: print(f">>> WARNING: stop returned rc={stop_rc}, continuing with up") - # 2) up (normal behavior, no force unless flags provided) up_args = argparse.Namespace( skip_entry_init=bool(args.skip_entry_init), - when_down=False, # REQUIRED by up.handler() + when_down=False, ) return int(up_handler(up_args)) diff --git a/cli/administration/deploy/development/up.py b/cli/administration/deploy/development/up.py index fe5b20cbb8..b65f69ace6 100644 --- a/cli/administration/deploy/development/up.py +++ b/cli/administration/deploy/development/up.py @@ -23,7 +23,6 @@ def add_parser(sub: argparse._SubParsersAction) -> None: def _maybe_build_missing() -> int: - # CI: never build (image is pulled). Local: build if missing. if os.environ["INFINITO_BUILD"] != "1": return 0 @@ -52,7 +51,6 @@ def _stack_is_running() -> bool: def handler(args: argparse.Namespace) -> int: - # when-down: skip if already running if args.when_down and _stack_is_running(): print(">>> Stack already running — skipping up") return 0 diff --git a/cli/administration/inventory/credentials/__main__.py b/cli/administration/inventory/credentials/__main__.py index 766ee3d848..418287f581 100755 --- a/cli/administration/inventory/credentials/__main__.py +++ b/cli/administration/inventory/credentials/__main__.py @@ -9,7 +9,7 @@ Usage example:: --role-path roles/web-app-akaunting \\ --inventory-file host_vars/echoserver.yml \\ --vault-password-file .pass/echoserver.txt \\ - --set credentials.database_password=mysecret + --set secrets.credentials.database_password=mysecret Snippet mode (no file changes, YAML printed to stdout):: @@ -30,8 +30,13 @@ from ruamel.yaml.comments import CommentedMap from utils.manager.inventory import InventoryManager -from .emit import emit_credentials, ensure_map -from .overrides import parse_overrides +from .emit import ( + credentials_map, + declared_credentials, + emit_credentials, + ensure_map, +) +from .overrides import parse_overrides, split_override_key from .prompts import ask_for_confirmation from .vault import to_vault_block @@ -131,17 +136,16 @@ def _run_snippet_mode( for app_id, app_block in schema_apps.items(): if not isinstance(app_block, dict): continue - schema_creds = app_block.get("credentials", {}) + schema_creds = declared_credentials(app_block) if not isinstance(schema_creds, dict) or not schema_creds: continue app_block_snip = ensure_map(apps_snip, app_id) - creds_snip = ensure_map(app_block_snip, "credentials") + creds_snip = credentials_map(app_block_snip) emit_credentials( schema_creds, creds_snip, app_id=app_id, - primary_app_id=manager.app_id, key_path="", overrides=overrides, vault_handler=manager.vault_handler, @@ -178,18 +182,17 @@ def _run_default_mode( for app_id, app_block_schema in schema_apps.items(): if not isinstance(app_block_schema, dict): continue - schema_creds = app_block_schema.get("credentials", {}) + schema_creds = declared_credentials(app_block_schema) if not isinstance(schema_creds, dict) or not schema_creds: continue app_block = ensure_map(apps, app_id) - creds = ensure_map(app_block, "credentials") + creds = credentials_map(app_block) added = newly_added_keys.setdefault(app_id, set()) emit_credentials( schema_creds, creds, app_id=app_id, - primary_app_id=manager.app_id, key_path="", overrides=overrides, vault_handler=manager.vault_handler, @@ -235,27 +238,17 @@ def _apply_force_overrides( inventory. Only fires under ``--force``; freshly-added keys are skipped because they were already populated from the same override.""" for ov_key, ov_val in overrides.items(): - if ov_key.startswith("applications.") and ".credentials." in ov_key: - rest = ov_key[len("applications.") :] - app_id, tail = rest.split(".credentials.", 1) - key = tail - elif ".credentials." in ov_key: - app_id, key = ov_key.split(".credentials.", 1) - else: - app_id = manager.app_id - key = ( - ov_key.split(".", 1)[1] if ov_key.startswith("credentials.") else ov_key - ) + app_id, key = split_override_key(ov_key) if app_id not in apps: continue app_block = ensure_map(apps, app_id) - creds = ensure_map(app_block, "credentials") + creds = credentials_map(app_block) if key in creds: if key in newly_added_keys.get(app_id, set()): continue - if args.yes or ask_for_confirmation(f"{app_id}.credentials.{key}"): + if args.yes or ask_for_confirmation(f"{app_id}.secrets.credentials.{key}"): creds[key] = to_vault_block(manager.vault_handler, ov_val, key) diff --git a/cli/administration/inventory/credentials/emit.py b/cli/administration/inventory/credentials/emit.py index d49afab62a..6f45b47d8d 100644 --- a/cli/administration/inventory/credentials/emit.py +++ b/cli/administration/inventory/credentials/emit.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Any from ruamel.yaml.comments import CommentedMap +from utils.manager.credential_key import CREDENTIALS_KEY, SECRETS_KEY + from .overrides import override_for from .vault import is_vault_encrypted, to_vault_block @@ -21,12 +23,30 @@ def ensure_map(node: CommentedMap, key: str) -> CommentedMap: return node[key] +def credentials_map(app_block: CommentedMap) -> CommentedMap: + """The writable ``secrets.credentials`` node of one application block. + + Args: + app_block: the ``applications.`` map. + """ + return ensure_map(ensure_map(app_block, SECRETS_KEY), CREDENTIALS_KEY) + + +def declared_credentials(app_block: dict) -> dict: + """The credentials an application block declares, empty when it declares + none. Reading a malformed ``secrets`` raises rather than resolving empty. + + Args: + app_block: the ``applications.`` map. + """ + return app_block.get(SECRETS_KEY, {}).get(CREDENTIALS_KEY, {}) + + def emit_credentials( schema_node: dict, dest_node: CommentedMap, *, app_id: str, - primary_app_id: str, key_path: str, overrides: dict[str, str], vault_handler: VaultHandler, @@ -35,12 +55,11 @@ def emit_credentials( ) -> None: """Walk a (possibly nested) credentials schema and emit one vault block per scalar leaf into ``dest_node``. Nested dicts (e.g. - ``credentials.recaptcha = {key, secret}``) recurse into nested + ``secrets.credentials.recaptcha = {key, secret}``) recurse into nested CommentedMaps so each leaf becomes its own vault-encrypted entry instead of being collapsed via ``str(dict)`` into a Python-repr blob (the regression that broke run 26428080957 jobs 77797371397 and 77797371442 for web-app-espocrm and web-app-listmonk).""" - is_primary = app_id == primary_app_id for key, default_val in schema_node.items(): full_key = f"{key_path}.{key}" if key_path else key @@ -50,7 +69,6 @@ def emit_credentials( default_val, sub, app_id=app_id, - primary_app_id=primary_app_id, key_path=full_key, overrides=overrides, vault_handler=vault_handler, @@ -62,7 +80,7 @@ def emit_credentials( if skip_existing and key in dest_node: continue - ov = override_for(app_id, full_key, overrides, is_primary=is_primary) + ov = override_for(app_id, full_key, overrides) value_for_key: str | Any = ov if ov is not None else default_val if is_vault_encrypted(value_for_key): diff --git a/cli/administration/inventory/credentials/overrides.py b/cli/administration/inventory/credentials/overrides.py index 682cfc398f..160512dcf9 100644 --- a/cli/administration/inventory/credentials/overrides.py +++ b/cli/administration/inventory/credentials/overrides.py @@ -2,40 +2,47 @@ from __future__ import annotations +from utils.manager.credential_key import ( + OVERRIDE_ROOT, + OVERRIDE_SECTION, + override_key, + split_override_key, +) + +__all__ = ["override_for", "override_key", "parse_overrides", "split_override_key"] + def parse_overrides(pairs: list[str]) -> dict[str, str]: - """Parse ``--set key=value`` pairs into a dict. Supports both - ``credentials.key=val`` and ``key=val`` (short) forms.""" + """Parse ``--set =`` pairs into a dict. + + Args: + pairs: raw ``key=value`` strings from the command line. + + Every key MUST be the fully qualified form :func:`override_key` builds; a + short form is rejected rather than guessed at, because the same short key + names different credentials on different apps. + """ out: dict[str, str] = {} + prefix = f"{OVERRIDE_ROOT}." + section = f".{OVERRIDE_SECTION}." for pair in pairs: - k, v = pair.split("=", 1) - out[k.strip()] = v.strip() + raw_key, value = pair.split("=", 1) + key = raw_key.strip() + if not key.startswith(prefix) or section not in key: + raise SystemExit( + f"--set {key}: expected " + f"{OVERRIDE_ROOT}..{OVERRIDE_SECTION}.=" + ) + out[key] = value.strip() return out -def override_for( - app_id: str, key: str, overrides: dict[str, str], *, is_primary: bool -) -> str | None: - """Resolve overrides for a credential key. +def override_for(app_id: str, key: str, overrides: dict[str, str]) -> str | None: + """The override value for one credential, or None when unset. - Supported forms: - - ``applications..credentials.=...`` - - ``.credentials.=...`` - Backwards compatible (PRIMARY app only): - - ``credentials.=...`` - - ``=...`` + Args: + app_id: application the credential belongs to. + key: dotted path inside the schema's ``credentials`` node. + overrides: parsed ``--set`` pairs. """ - v = overrides.get(f"applications.{app_id}.credentials.{key}") - if v is not None: - return v - v = overrides.get(f"{app_id}.credentials.{key}") - if v is not None: - return v - if is_primary: - v = overrides.get(f"credentials.{key}") - if v is not None: - return v - v = overrides.get(key) - if v is not None: - return v - return None + return overrides.get(override_key(app_id, key)) diff --git a/cli/administration/inventory/onion/__init__.py b/cli/administration/inventory/onion/__init__.py new file mode 100644 index 0000000000..58bcb35a31 --- /dev/null +++ b/cli/administration/inventory/onion/__init__.py @@ -0,0 +1,86 @@ +"""Node Tor v3 onion identity for the harness. + +:func:`ensure_node_onion` pre-mints (or reuses) the node's onion and returns its +address, storing the authoritative hidden-service key files at the repo root. The +``svc-net-tor`` role copies those keys into the running daemon so it serves exactly +that address; the inventory provisioner writes the address into +``applications.svc-net-tor.services.tor.node``. The onion is a deploy-time input; +there is no in-deploy minting (a random mint would not match the provisioned node). +""" + +from __future__ import annotations + +import contextlib +import os +from pathlib import Path + +from utils.tor_onion import IDENTITY_DIRNAME, identity_hs_dir, mint + +__all__ = ["IDENTITY_DIRNAME", "ensure_node_onion", "identity_hs_dir"] + +HS_FILE_MODES = { + "hostname": 0o600, + "hs_ed25519_public_key": 0o600, + "hs_ed25519_secret_key": 0o600, +} + + +def _write_files(directory: Path, files: dict[str, bytes]) -> None: + directory.mkdir(parents=True, exist_ok=True) + for name, content in files.items(): + path = directory / name + fd = os.open( + str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, HS_FILE_MODES[name] + ) + with os.fdopen(fd, "wb") as handle: + handle.write(content) + + +def _hand_to_checkout_owner(base_dir: Path) -> None: + """Give the identity tree back to whoever owns the checkout. + + The provisioner may run privileged -- as root inside the DiD on a bind + mount, or under sudo -- while the swarm playbook's `tar` that packs the + repo for the nodes runs as the workspace user. Keys minted 0600 and owned + by root make that tar abort with EACCES on all three files, so ownership + has to follow the tree, not the process that happened to mint them. A + no-op unless we are root and the checkout belongs to somebody else. + + ``lchown`` rather than ``chown``: ``rglob`` yields symlinks too, and + following one would hand ownership of its target away instead. A path that + vanishes between the walk and the call is skipped rather than aborting the + provisioner -- the identity we care about is the one we just wrote. + """ + if os.geteuid() != 0: + return + owner = base_dir.stat() + if owner.st_uid == 0: + return + identity = base_dir / IDENTITY_DIRNAME + for path in (identity, *identity.rglob("*")): + with contextlib.suppress(FileNotFoundError): + os.lchown(path, owner.st_uid, owner.st_gid) + + +def ensure_node_onion(base_dir: str | Path) -> str: + """Mint (or reuse) the node onion identity and return its ``.onion`` address. + + Dual-stack model: the node keeps its clearnet ``DOMAIN_PRIMARY``; the node + onion is an ADDITIVE address opted-in apps (``services.tor.enabled``) are also + reachable under as ``.`` over Tor. Idempotent: an existing key + at ``/.onion-identity/hs`` is reused so the address is stable across + runs. The key files are the single source of truth — the ``svc-net-tor`` role + copies them into the daemon so it serves exactly this address, and the + inventory provisioner writes the returned address into + ``applications.svc-net-tor.services.tor.node`` (no env indirection). + """ + base = Path(base_dir) + hs = identity_hs_dir(base) + hostname_file = hs / "hostname" + if hostname_file.exists(): + _hand_to_checkout_owner(base) + return hostname_file.read_text(encoding="ascii").strip() # nocheck: cache-read + key = mint() + _write_files(hs, key.files()) + _hand_to_checkout_owner(base) + return key.address diff --git a/cli/administration/inventory/onion/__main__.py b/cli/administration/inventory/onion/__main__.py new file mode 100755 index 0000000000..b62e4c0688 --- /dev/null +++ b/cli/administration/inventory/onion/__main__.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""CLI: pre-mint the node Tor v3 onion identity (key files) and print its address.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from cli.administration.inventory.onion import ensure_node_onion + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Pre-mint the node Tor v3 onion identity for an onion deploy." + ) + sub = parser.add_subparsers(dest="command", required=True) + env_parser = sub.add_parser( + "init-env", + help="Mint (or reuse) the node onion key files and print the .onion address.", + ) + env_parser.add_argument("--env-file", default=".env") + + args = parser.parse_args() + if args.command == "init-env": + print(ensure_node_onion(Path(args.env_file).parent)) + return 0 + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cli/administration/inventory/provision/cli.py b/cli/administration/inventory/provision/cli.py index 44232e2f5f..e92832d76a 100644 --- a/cli/administration/inventory/provision/cli.py +++ b/cli/administration/inventory/provision/cli.py @@ -20,6 +20,7 @@ from .mirror_overrides import apply_mirror_overrides from .passwords import generate_random_password from .project import build_env_with_project_root, detect_project_root from .services_disabler import apply_services_disabled_from_env +from .tor_node import apply_tor_node_onion from .yaml_io import dump_yaml, load_yaml @@ -289,6 +290,12 @@ def main(argv: list[str] | None = None) -> int: print(f"[INFO] Applying mirror overrides from: {mirrors_file}") apply_mirror_overrides(host_vars_file=host_vars_file, mirrors_file=mirrors_file) + apply_tor_node_onion( + host_vars_file=host_vars_file, + application_ids=application_ids, + base_dir=project_root, + ) + apply_services_disabled_from_env( host_vars_file=host_vars_file, inventory_file=inventory_file, diff --git a/cli/administration/inventory/provision/credentials_generator.py b/cli/administration/inventory/provision/credentials_generator.py index 037a032e03..c71484ad1c 100644 --- a/cli/administration/inventory/provision/credentials_generator.py +++ b/cli/administration/inventory/provision/credentials_generator.py @@ -8,6 +8,12 @@ from typing import TYPE_CHECKING from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap +from cli.administration.inventory.credentials.emit import ( + credentials_map, + declared_credentials, + ensure_map, +) + from .role_resolver import resolve_role_path if TYPE_CHECKING: @@ -18,12 +24,6 @@ def _fatal(msg: str) -> None: raise SystemExit(f"[FATAL] {msg}") -def _ensure_ruamel_map(node: CommentedMap, key: str) -> CommentedMap: - if key not in node or not isinstance(node.get(key), CommentedMap): - node[key] = CommentedMap() - return node[key] - - def _generate_credentials_snippet_for_app( app_id: str, roles_dir: Path, @@ -38,7 +38,6 @@ def _generate_credentials_snippet_for_app( return None cmd = [ - # Use current interpreter so utils + deps match the runtime sys.executable, "-m", "cli.administration.inventory.credentials", @@ -148,14 +147,14 @@ def generate_credentials_for_roles( for snippet in snippets: apps_snip = snippet.get("applications", {}) or {} if isinstance(apps_snip, dict): - apps_doc = _ensure_ruamel_map(doc, "applications") + apps_doc = ensure_map(doc, "applications") for app_id, app_block_snip in apps_snip.items(): if not isinstance(app_block_snip, dict): continue - app_doc = _ensure_ruamel_map(apps_doc, app_id) - creds_doc = _ensure_ruamel_map(app_doc, "credentials") + app_doc = ensure_map(apps_doc, app_id) + creds_doc = credentials_map(app_doc) - creds_snip = app_block_snip.get("credentials", {}) or {} + creds_snip = declared_credentials(app_block_snip) or {} if not isinstance(creds_snip, dict): continue diff --git a/cli/administration/inventory/provision/host_vars.py b/cli/administration/inventory/provision/host_vars.py index b48c34298e..20d1532d8c 100644 --- a/cli/administration/inventory/provision/host_vars.py +++ b/cli/administration/inventory/provision/host_vars.py @@ -155,7 +155,6 @@ def ensure_become_password( current_value = doc.get("ansible_become_password") - # Respect existing value if user didn't request a new one if become_password is None and current_value is not None: return diff --git a/cli/administration/inventory/provision/mirror_overrides.py b/cli/administration/inventory/provision/mirror_overrides.py index 2d629211c8..166e68feb6 100644 --- a/cli/administration/inventory/provision/mirror_overrides.py +++ b/cli/administration/inventory/provision/mirror_overrides.py @@ -65,7 +65,7 @@ def apply_mirror_overrides(host_vars_file: Path, mirrors_file: Path) -> None: mirrors_apps = mirrors_raw.get("applications", {}) or {} has_applications = isinstance(mirrors_apps, dict) and bool(mirrors_apps) if not has_applications: - return # no-op + return yaml_rt = YAML(typ="rt") yaml_rt.preserve_quotes = True @@ -129,7 +129,6 @@ def apply_mirror_overrides(host_vars_file: Path, mirrors_file: Path) -> None: changed = True continue - # if_missing (default) if _is_blank(svc_doc.get("image")): svc_doc["image"] = image changed = True diff --git a/cli/administration/inventory/provision/tor_node.py b/cli/administration/inventory/provision/tor_node.py new file mode 100644 index 0000000000..7f89a6d92e --- /dev/null +++ b/cli/administration/inventory/provision/tor_node.py @@ -0,0 +1,44 @@ +"""Provision the node onion address into ``services.tor.node``. + +The onion identity (key files) is minted/reused by +``cli.administration.inventory.onion``; this provisioner is the single spot that +writes the resulting address into +``applications.svc-net-tor.services.tor.node`` of the host_vars — so consumers +read it via ``lookup('config', 'svc-net-tor', 'services.tor.node')`` with no env +indirection. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from cli.administration.inventory.onion import ensure_node_onion + +from .yaml_io import dump_yaml, load_yaml + +if TYPE_CHECKING: + from pathlib import Path + +_PROVIDER = "svc-net-tor" + + +def apply_tor_node_onion( + *, + host_vars_file: Path, + application_ids: list[str], + base_dir: Path, +) -> None: + """When ``svc-net-tor`` is in the deploy, mint (or reuse) the node onion and + set ``applications.svc-net-tor.services.tor.node`` in the host_vars.""" + if _PROVIDER not in application_ids: + return + address = ensure_node_onion(base_dir) + data = load_yaml(host_vars_file) if host_vars_file.exists() else {} + if not isinstance(data, dict): + data = {} + apps = data.setdefault("applications", {}) + svc = apps.setdefault(_PROVIDER, {}) + services = svc.setdefault("services", {}) + tor = services.setdefault("tor", {}) + tor["node"] = address + dump_yaml(host_vars_file, data) diff --git a/cli/administration/inventory/validate/applications.py b/cli/administration/inventory/validate/applications.py index de53bc77d6..99498dcd96 100644 --- a/cli/administration/inventory/validate/applications.py +++ b/cli/administration/inventory/validate/applications.py @@ -2,6 +2,8 @@ from __future__ import annotations +from utils.manager.credential_key import OVERRIDE_SECTION, SECRETS_KEY + from .keys import recursive_keys @@ -22,7 +24,7 @@ def compare_application_keys(applications, application_defaults, source, variant for variant in variants.get(app_id, []): legal_keys |= recursive_keys(variant) for key in recursive_keys(conf): - if key.startswith("credentials"): + if key == SECRETS_KEY or key.startswith(OVERRIDE_SECTION): continue if key not in legal_keys: errs.append(f"{source}: Missing default for {app_id}: {key}") diff --git a/cli/administration/recover/README.md b/cli/administration/recover/README.md index 5d56b7d814..64aa753e32 100644 --- a/cli/administration/recover/README.md +++ b/cli/administration/recover/README.md @@ -1,7 +1,7 @@ # recover Uniform recovery for the `svc-bkp-*` backup roles. One command wraps each -role's `files/recover.py` behind a single grammar and drives a full +role's `files/python/recover.py` behind a single grammar and drives a full disaster recovery in the correct order. ## Usage diff --git a/cli/administration/recover/full.py b/cli/administration/recover/full.py index 264f38effc..63e90ea3f9 100644 --- a/cli/administration/recover/full.py +++ b/cli/administration/recover/full.py @@ -19,6 +19,7 @@ import sys from pathlib import Path from cli.administration.recover import paths, recoverers, remote +from utils.recovery import manifest _REPOS: tuple[tuple[str, str], ...] = ( ("nfs", "backup-nfs-to-local"), @@ -34,18 +35,39 @@ def _newest_gen(root: Path, repo: str) -> Path | None: return generations[-1] if generations else None -def plan(root: Path) -> list[tuple[str, str]]: - """(type, source-files-dir) for each present repo, in order; volume per-volume.""" +def plan(root: Path) -> tuple[list[tuple[str, str]], list[str]]: + """(type, source) for each present repo, in order; volume per-volume. + + The volume repo contributes a database step after its file steps: the + dumps have to land once the volumes are back and while the consumers are + still down, which is where the caller has them. + + Returns: + The steps, and the repos whose manifest could not be read. A repo that + cannot state its layout is skipped rather than guessed at, but it must + not take the others with it: recovering two repos of three beats + recovering none because one manifest is corrupt. + """ steps: list[tuple[str, str]] = [] + unreadable: list[str] = [] for rtype, repo in _REPOS: generation = _newest_gen(root, repo) if generation is None: continue + try: + names = manifest.layout_of(generation) + except ValueError as error: + unreadable.append(f"{repo}: {error}") + continue + files_glob, dump_glob = manifest.globs_of(names) + files_dir = names["files_dir"] if rtype == "volume": - steps += [(rtype, str(vol)) for vol in sorted(generation.glob("*/files"))] - elif (generation / "files").is_dir(): - steps.append((rtype, str(generation / "files"))) - return steps + steps += [(rtype, str(vol)) for vol in sorted(generation.glob(files_glob))] + if any(generation.glob(dump_glob)): + steps.append(("database", str(generation))) + elif (generation / files_dir).is_dir(): + steps.append((rtype, str(generation / files_dir))) + return steps, unreadable def _pull_cmd(source: str) -> list[str]: @@ -70,20 +92,22 @@ def _device_restore_root(source: str) -> str: def _recover_under( root: Path, target: str, *, preview: bool, service_backup: bool ) -> int: - steps = plan(root) + steps, unreadable = plan(root) + for problem in unreadable: + print(f"# full: SKIPPED {problem}", file=sys.stderr) if not steps: print(f"# full: no backup repos found under {root}") return 1 - returncode = 0 + returncode = 2 if unreadable else 0 for rtype, files_dir in steps: cmd = recoverers.RECOVERERS[rtype].command( files_dir, service_backup=service_backup, target=target ) print(f"# full {rtype} {target}: {shlex.join(cmd)}") if not preview: - returncode = subprocess.run(cmd, check=False).returncode - if returncode != 0: - return returncode + failed = subprocess.run(cmd, check=False).returncode + if failed != 0: + return failed return returncode diff --git a/cli/administration/recover/recoverers.py b/cli/administration/recover/recoverers.py index 9ea60dcbfd..47f3dd737f 100644 --- a/cli/administration/recover/recoverers.py +++ b/cli/administration/recover/recoverers.py @@ -1,7 +1,7 @@ """Recoverer classes: one per svc-bkp-* recovery type. Each Recoverer parses and validates its own colon-encoded ``source`` and -builds the role's ``files/recover.py`` invocation. Colon segments are +builds the role's ``files/python/recover.py`` invocation. Colon segments are classified by shape: an ABSOLUTE path is the restore destination (replacing a --target flag); for device a RELATIVE segment is the on-device snapshot subpath and an all-digit ``YYYYMMDDHHMMSS`` segment is the generation to @@ -47,7 +47,7 @@ def remote_target(target: str) -> bool: class Recoverer(ABC): - """One recovery type backed by a role's ``files/recover.py``.""" + """One recovery type backed by a role's ``files/python/recover.py``.""" name: str role: str @@ -55,7 +55,9 @@ class Recoverer(ABC): no_backup_flag: bool = True def script(self) -> str: - return str(PROJECT_ROOT / "roles" / self.role / "files" / "recover.py") + return str( + PROJECT_ROOT / "roles" / self.role / "files" / "python" / "recover.py" + ) @abstractmethod def args(self, source: str, target: str) -> list[str]: @@ -154,6 +156,26 @@ class VolumeRecoverer(Recoverer): return argv +class DatabaseRecoverer(Recoverer): + name = "database" + role = "svc-bkp-volume-2-local" + summary = "Generation's sql dumps -> their databases (consumers must be down)" + + def args(self, source: str, target: str) -> list[str]: + if is_remote(source): + raise ValueError( + "database: remote source not supported; pull first or use 'full'" + ) + if not source: + raise ValueError("database: empty source") + if remote_target(target): + raise ValueError( + "database: remote target not supported; the credentials live in " + f"the target's own databases.csv, so run the replay on {target}" + ) + return ["--databases", source] + + class SecretsRecoverer(Recoverer): name = "secrets" role = "svc-bkp-secrets-2-local" @@ -176,6 +198,7 @@ _RECOVERERS: tuple[Recoverer, ...] = ( DeviceRecoverer(), NfsRecoverer(), VolumeRecoverer(), + DatabaseRecoverer(), SecretsRecoverer(), ) RECOVERERS: dict[str, Recoverer] = {r.name: r for r in _RECOVERERS} diff --git a/cli/administration/recover/schema.yml b/cli/administration/recover/schema.yml index e5b0cbe370..8a14dda950 100644 --- a/cli/administration/recover/schema.yml +++ b/cli/administration/recover/schema.yml @@ -1,6 +1,6 @@ --- # Recovery schema for `infinito administration recover`. -# One uniform command wraps each svc-bkp-* role's files/recover.py. +# One uniform command wraps each svc-bkp-* role's files/python/recover.py. command: "recover [--preview] [--no-safety-backup]" target: "host to restore onto (positional label)" diff --git a/cli/administration/secrets/seal/__main__.py b/cli/administration/secrets/seal/__main__.py index 4e7fce70df..5363817c1d 100644 --- a/cli/administration/secrets/seal/__main__.py +++ b/cli/administration/secrets/seal/__main__.py @@ -34,10 +34,8 @@ def encrypt_recursively( for i, item in enumerate(data): data[i] = encrypt_recursively(item, vault_handler, ask_confirmation, prefix) elif isinstance(data, str): # noqa: SIM102 outer guard, inner ask_confirmation block has independent siblings - # Only encrypt if it's not already vaulted if not data.lstrip().startswith("$ANSIBLE_VAULT"): if ask_confirmation: # noqa: SIM102 combining changes semantics: encrypted_value below must run regardless of ask_confirmation - # Ask for confirmation before encrypting if not `--all` if not ask_for_confirmation(prefix): print(f"Skipping encryption for '{prefix}'.") return data @@ -45,7 +43,7 @@ def encrypt_recursively( lines = encrypted_value.splitlines() indent = len(lines[1]) - len(lines[1].lstrip()) body = "\n".join(line[indent:] for line in lines[1:]) - return VaultScalar(body) # Store encrypted value as VaultScalar + return VaultScalar(body) return data @@ -64,18 +62,13 @@ def main(): ) args = parser.parse_args() - # Initialize the VaultHandler and load the inventory vault_handler = VaultHandler(vault_password_file=args.vault_password_file) updated_inventory = YamlHandler.load_yaml(Path(args.inventory_file)) - # 1) Encrypt all fields recursively updated_inventory = encrypt_recursively( updated_inventory, vault_handler, ask_confirmation=not args.all ) - # 2) Save the updated inventory to file. The custom SafeDumper - # subclass emits !vault literal blocks; the cached dump_yaml writes - # plain YAML which is the wrong output here. with Path(args.inventory_file).open("w", encoding="utf-8") as f: yaml.dump( # nocheck: direct-yaml updated_inventory, f, sort_keys=False, Dumper=SafeDumper diff --git a/cli/build/graph/__init__.py b/cli/build/graph/__init__.py index 6b8769f60d..05b0b86134 100644 --- a/cli/build/graph/__init__.py +++ b/cli/build/graph/__init__.py @@ -12,8 +12,6 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[3] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 __all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 diff --git a/cli/build/graph/__main__.py b/cli/build/graph/__main__.py index 2256e7253a..1a22a3cbde 100644 --- a/cli/build/graph/__main__.py +++ b/cli/build/graph/__main__.py @@ -12,10 +12,8 @@ from utils.cache.yaml import load_yaml, load_yaml_any from . import PROJECT_ROOT -# Regex used to ignore Jinja expressions inside include/import statements JINJA_PATTERN = re.compile(r'{{.*}}') -# All dependency types the graph builder supports ALL_DEP_TYPES = [ "run_after", "dependencies", @@ -25,10 +23,8 @@ ALL_DEP_TYPES = [ "import_role", ] -# Graph directions: outgoing edges ("to") vs incoming edges ("from") ALL_DIRECTIONS = ["to", "from"] -# Combined keys: e.g. "include_role_to", "dependencies_from", etc. ALL_KEYS = [f"{dep}_{direction}" for dep in ALL_DEP_TYPES for direction in ALL_DIRECTIONS] @@ -87,7 +83,6 @@ def load_tasks(path: str, dep_type: str) -> List[str]: Parse include_tasks/import_tasks from tasks/main.yml. Only accepts simple, non-Jinja names. """ - # `tasks/main.yml` root is a list, not a mapping. data = load_yaml_any(path) if not isinstance(data, list): data = [] @@ -144,7 +139,6 @@ def build_single_graph( if role in nodes: return - # Try retrieving cached meta; fallback: lazy load meta = meta_cache.get(role) if meta is None: try: @@ -191,7 +185,7 @@ def build_single_graph( if tgt not in path: traverse(tgt, depth + 1, path | {tgt}) - else: # direction == "from" + else: for src in incoming(role): ensure_node(src) links.append({"source": src, "target": role, "type": dep_type}) @@ -229,16 +223,12 @@ def build_mappings( if os.path.isdir(os.path.join(roles_dir, r)) ] - # Pre-caches meta_cache: Dict[str, Dict[str, Any]] = {} deps_cache: Dict[str, Dict[str, List[str]]] = {dep: {} for dep in ALL_DEP_TYPES} rev_cache: Dict[str, Dict[str, Set[str]]] = {dep: {} for dep in ALL_DEP_TYPES} resolver = RoleDependencyResolver(roles_dir) - # -------------------------------------------------------- - # Step 1: Preload meta-based deps (run_after, dependencies) - # -------------------------------------------------------- for role in roles: try: meta = load_meta(find_role_meta(roles_dir, role)) @@ -256,9 +246,6 @@ def build_mappings( if isinstance(tgt, str) and tgt.strip(): rev_cache[dep_key].setdefault(tgt.strip(), set()).add(role) - # -------------------------------------------------------- - # Step 2: Preload include_role/import_role (resolver) - # -------------------------------------------------------- for role in roles: role_path = os.path.join(roles_dir, role) inc, imp = resolver._scan_tasks(role_path) @@ -275,9 +262,6 @@ def build_mappings( for tgt in imp_list: rev_cache["import_role"].setdefault(tgt, set()).add(role) - # -------------------------------------------------------- - # Step 3: Preload include_tasks/import_tasks - # -------------------------------------------------------- for role in roles: try: tasks_path = find_role_tasks(roles_dir, role) @@ -298,9 +282,6 @@ def build_mappings( "rev": rev_cache, } - # -------------------------------------------------------- - # Step 4: Build all graphs from caches - # -------------------------------------------------------- for key in ALL_KEYS: dep_type, direction = key.rsplit("_", 1) try: diff --git a/cli/build/include/__init__.py b/cli/build/include/__init__.py deleted file mode 100644 index fd6cbc7d5f..0000000000 --- a/cli/build/include/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Compatibility wrapper. - -The implementation lives in ``cli/build/include/__main__.py``; this package -re-exports its public API so ``from cli.build.include import ...`` works. -""" - -from __future__ import annotations - -from . import __main__ as _main -__all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) -globals().update({name: getattr(_main, name) for name in __all__}) - -# Prefer explicit __all__ if the original module defined it. -__all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) diff --git a/cli/build/include/__main__.py b/cli/build/include/__main__.py deleted file mode 100644 index bc228d7278..0000000000 --- a/cli/build/include/__main__.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 - -import os -import sys -import argparse -from collections import defaultdict, deque - -from utils.cache.yaml import load_yaml -from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_VARS_MAIN - -def find_roles(roles_dir, prefixes=None): - """ - Find all roles in the given directory whose names start with - any of the provided prefixes. If prefixes is empty or None, - include all roles. - """ - for entry in os.listdir(roles_dir): - if prefixes: - if not any(entry.startswith(pref) or entry == pref.rstrip("-") for pref in prefixes): - continue - path = os.path.join(roles_dir, entry) - meta_file = os.path.join(path, ROLE_FILE_META_MAIN) - if os.path.isdir(path) and os.path.isfile(meta_file): - yield path, meta_file - -def load_run_after(meta_file): - from utils.roles.meta_lookup import get_role_run_after - - role_path = os.path.abspath(os.path.dirname(os.path.dirname(meta_file))) - role_name = os.path.basename(role_path) - try: - return get_role_run_after(role_path, role_name=role_name) - except Exception: - return [] - -def load_application_id(role_path): - """Load the application_id from the vars/main.yml of the role.""" - vars_file = os.path.join(role_path, ROLE_FILE_VARS_MAIN) - if os.path.exists(vars_file): - data = load_yaml(vars_file) - return data.get('application_id') - return None - -def build_dependency_graph(roles_dir, prefixes=None): - """ - Build a dependency graph where each key is a role name and - its value is a list of roles that depend on it. - Also return in_degree counts and the roles metadata map. - """ - graph = defaultdict(list) - in_degree = defaultdict(int) - roles = {} - - in_scope: set[str] = set() - role_entries = list(find_roles(roles_dir, prefixes)) - for role_path, _meta_file in role_entries: - in_scope.add(os.path.basename(role_path)) - - for role_path, meta_file in role_entries: - run_after = load_run_after(meta_file) - application_id = load_application_id(role_path) - role_name = os.path.basename(role_path) - - in_scope_deps = [d for d in run_after if d in in_scope] - - roles[role_name] = { - 'role_name': role_name, - 'run_after': in_scope_deps, - 'application_id': application_id, - 'path': role_path - } - - for dependency in in_scope_deps: - graph[dependency].append(role_name) - in_degree[role_name] += 1 - - if role_name not in in_degree: - in_degree[role_name] = 0 - - return graph, in_degree, roles - -def find_cycle(roles): - """ - Detect a cycle in the run_after relations: - roles: dict mapping role_name -> { 'run_after': [...], ... } - Returns a list of role_names forming the cycle (with the start repeated at end), or None. - """ - visited = set() - stack = set() - - def dfs(node, path): - visited.add(node) - stack.add(node) - path.append(node) - for dep in roles.get(node, {}).get('run_after', []): - if dep not in visited: - res = dfs(dep, path) - if res: - return res - elif dep in stack: - idx = path.index(dep) - return path[idx:] + [dep] - stack.remove(node) - path.pop() - return None - - for role in roles: - if role not in visited: - cycle = dfs(role, []) - if cycle: - return cycle - return None - -def topological_sort(graph, in_degree, roles=None): - """ - Perform topological sort on the dependency graph. - If a cycle is detected, raise an Exception with detailed debug info. - """ - - queue = deque([r for r, d in in_degree.items() if d == 0]) - sorted_roles = [] - local_in = dict(in_degree) - - while queue: - role = queue.popleft() - sorted_roles.append(role) - for nbr in graph.get(role, []): - local_in[nbr] -= 1 - if local_in[nbr] == 0: - queue.append(nbr) - - if len(sorted_roles) != len(in_degree): - cycle = find_cycle(roles or {}) - unsorted = [r for r in in_degree if r not in sorted_roles] - - header = "❌ Dependency resolution failed" - if cycle: - reason = f"Circular dependency detected: {' -> '.join(cycle)}" - else: - reason = "Unresolved dependencies among roles (possible cycle or missing role)." - - details = [] - if unsorted: - details.append("Unsorted roles and their declared run_after dependencies:") - for r in unsorted: - deps = roles.get(r, {}).get('run_after', []) - details.append(f" - {r} depends on {deps!r}") - - graph_repr = f"Full dependency graph: {dict(graph)!r}" - - raise Exception("\n".join([header, reason] + details + [graph_repr])) - - return sorted_roles - -def print_dependency_tree(graph): - """Print the dependency tree visually on the console.""" - def print_node(role, indent=0): - print(" " * indent + role) - for dep in graph.get(role, []): - print_node(dep, indent + 1) - - all_roles = set(graph.keys()) - dependent = {r for deps in graph.values() for r in deps} - roots = all_roles - dependent - - for root in roots: - print_node(root) - -def gen_condi_role_incl(roles_dir, prefixes=None): - """ - Generate playbook entries based on the sorted order. - Raises a ValueError if application_id is missing. - """ - graph, in_degree, roles = build_dependency_graph(roles_dir, prefixes) - sorted_names = topological_sort(graph, in_degree, roles) - - entries = [] - for role_name in sorted_names: - role = roles[role_name] - - if role.get('application_id') is None: - vars_file = os.path.join(role['path'], ROLE_FILE_VARS_MAIN) - raise ValueError(f"'application_id' missing in {vars_file}") - - app_id = role['application_id'] - entries.append( - f"- name: 🔧 setup {app_id}\n" - f" when: ('{app_id}' | application_allowed(group_names, lookup('deployment').whitelist))\n" - f" include_role:\n" - f" name: {role_name}\n" - ) - entries.append( - f"- name: 🚿 flush handlers after {app_id}\n" - f" meta: flush_handlers\n" - ) - - return entries - -def main(): - parser = argparse.ArgumentParser( - description='Generate an Ansible playbook include file from Docker roles, sorted by run_after order.' - ) - parser.add_argument('roles_dir', help='Path to directory containing role folders') - parser.add_argument( - '-p', '--prefix', - action='append', - help='Only include roles whose names start with any of these prefixes; can be specified multiple times' - ) - parser.add_argument('-o', '--output', default=None, - help='Output file path (default: stdout)') - parser.add_argument('-t', '--tree', action='store_true', - help='Display the dependency tree of roles and exit') - - args = parser.parse_args() - prefixes = args.prefix or [] - - if args.tree: - graph, _, _ = build_dependency_graph(args.roles_dir, prefixes) - print_dependency_tree(graph) - sys.exit(0) - - entries = gen_condi_role_incl(args.roles_dir, prefixes) - output = ''.join(entries) - - if args.output: - os.makedirs(os.path.dirname(args.output), exist_ok=True) - if os.path.exists(args.output) and not os.access(args.output, os.W_OK): - try: - os.unlink(args.output) - except OSError: - pass - with open(args.output, 'w') as f: - f.write(output) - print(f"Playbook entries written to {args.output}") - else: - print(output) - -if __name__ == '__main__': - main() diff --git a/cli/build/list/__init__.py b/cli/build/list/__init__.py index b6a394fc1e..235595dafd 100644 --- a/cli/build/list/__init__.py +++ b/cli/build/list/__init__.py @@ -10,8 +10,6 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[3] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 __all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 diff --git a/cli/build/list/__main__.py b/cli/build/list/__main__.py index 79ff28dc2a..4167014b57 100644 --- a/cli/build/list/__main__.py +++ b/cli/build/list/__main__.py @@ -54,7 +54,6 @@ def main(): roles = find_roles(args.roles_dir) if args.output.lower() == 'console': - # Print JSON to stdout print(json.dumps(roles, indent=2)) else: write_roles_list(roles, args.output) diff --git a/cli/build/readme/cosmos.py b/cli/build/readme/cosmos.py index aee9dcb130..3f2abcc2d0 100644 --- a/cli/build/readme/cosmos.py +++ b/cli/build/readme/cosmos.py @@ -4,8 +4,9 @@ The role box lists EVERY service the role declares. Around it: Dependencies roles this role consumes, on the left. A consumption is a service whose ``enabled``/``shared`` flag names another role - (``'' in group_names``) or whose key matches another - role's ``provides`` (provision) name. + (``'' in group_names``), whose key matches another + role's ``provides`` (provision) name, or whose key is another + role's own primary service key while both flags are on. Dependents roles that consume THIS role, on the right. The mirror of the above: another role names this one, or declares a service keyed by this role's ``provides`` name (e.g. web-app-keycloak @@ -15,8 +16,16 @@ The role box lists EVERY service the role declares. Around it: ``provides: ldap``) is picked up even when the consuming flag uses a ``groups[...]`` form the ``group_names`` regex cannot read. +Primary-key matching covers the mandatory relationship, where the consumer +pins the provider on unconditionally (``enabled: true, shared: true``) and no +``group_names`` reference is left to read — web-svc-asset consuming +web-svc-file's ``file`` is the canonical case. + Edge style encodes the flag: a solid edge is a fixed (literal ``true``) -relationship, a dashed edge is variable (a ``{{ ... }}`` conditional). +relationship, a dashed edge is variable (a ``{{ ... }}`` conditional), and a +red ``0..0`` edge is one the role turns off (``enabled`` and ``shared`` both +literally ``false``) — the relationship exists in the metadata but carries +nothing at deploy time. ``run_after`` is deliberately NOT read: it is a deploy-ordering hint, not a runtime dependency. The wider cosmos (federation peers, external bridged @@ -30,12 +39,18 @@ import re from pathlib import Path from utils.cache.yaml import load_yaml_any +from utils.roles.applications.services.registry import ( + build_role_to_primary_service_key, + build_service_registry_from_roles_dir, + is_explicit_truth, +) from utils.roles.deploy import role_deploy_modes from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_META_SERVICES from utils.symbol_glossary import to_emoji _GROUP_DEP_RE = re.compile(r"'([a-z0-9][a-z0-9-]*)'\s+in\s+group_names") _DEPENDENTS_CAP = 12 +_OFF_STROKE = "red" _MERMAID_RESERVED = { "call", "class", @@ -103,6 +118,23 @@ def _roles_meta(roles_root_str: str) -> dict[str, dict]: return meta +@functools.lru_cache(maxsize=1) +def _primary_key_providers(roles_root_str: str) -> dict[str, str]: + """Map each role's own primary service key to that role.""" + registry = build_service_registry_from_roles_dir(Path(roles_root_str)) + return { + key: role for role, key in build_role_to_primary_service_key(registry).items() + } + + +def _pins_provider_on(entry: dict) -> bool: + """True when a consumer keeps a service on unconditionally, the shape a + mandatory dependency takes once no ``group_names`` reference is left.""" + return is_explicit_truth(entry.get("enabled")) and is_explicit_truth( + entry.get("shared") + ) + + @functools.lru_cache(maxsize=1) def _roles_ansible_deps(roles_root_str: str) -> dict[str, set[str]]: """Every role's ``meta/main.yml`` ``dependencies`` (string or @@ -125,35 +157,60 @@ def _roles_ansible_deps(roles_root_str: str) -> dict[str, set[str]]: return deps +def _entry_kind(entry: dict) -> str: + """Classify one consumed service: ``off`` when the consumer turns it off, + otherwise the flag's own fixed/variable shape.""" + if _service_stopped(entry): + return "off" + return _flag_kind(entry) or "fixed" + + def _consumption_kind( - services: dict, provider_role: str, provider_provides: set[str] + services: dict, + provider_role: str, + provider_provides: set[str], + provider_primary_key: str | None = None, ) -> str | None: - """Return how ``services`` consumes ``provider_role`` (fixed/variable/None).""" + """Return how ``services`` consumes ``provider_role`` (fixed/variable/off/None).""" kinds: list[str] = [] for key, entry in services.items(): if not isinstance(entry, dict): continue if provider_role in _group_refs(entry): kinds.append("variable") - elif key in provider_provides: - kinds.append(_flag_kind(entry) or "fixed") + elif key in provider_provides or ( + key == provider_primary_key and _pins_provider_on(entry) + ): + kinds.append(_entry_kind(entry)) if not kinds: return None - return "fixed" if all(k == "fixed" for k in kinds) else "variable" + for kind in ("variable", "fixed"): + if kind in kinds: + return kind + return "off" def _edge(src: str, dst: str, kind: str) -> str: if kind == "variable": return f' {src} -. "0..1" .-> {dst}' + if kind == "off": + return f' {src} -- "0..0" --> {dst}' return f' {src} -- "1:1" --> {dst}' +_EDGE_PRECEDENCE = {"off": 0, "fixed": 1, "variable": 2} + + def _merge_edges(edges: list[tuple[str, str, str]]) -> dict[tuple[str, str], str]: - """Collapse duplicate ``(src, dst)`` edges; a variable edge wins over fixed.""" + """Collapse duplicate ``(src, dst)`` edges; the liveliest kind wins, so a + relationship one service turns off still shows as on where another keeps it.""" merged: dict[tuple[str, str], str] = {} for src, dst, kind in edges: pair = (src, dst) - if pair not in merged or kind == "variable": + if ( + pair not in merged + or _EDGE_PRECEDENCE[kind] > _EDGE_PRECEDENCE[merged[pair]] + ): merged[pair] = kind return merged @@ -199,6 +256,8 @@ def derive_cosmos_mermaid(role_dir: Path, role_name: str) -> str: provides_map = {name: _provides_of(svc) for name, svc in meta.items()} my_provides = _provides_of(services) + providers = _primary_key_providers(str(role_dir.parent)) + my_primary_key = next((k for k, r in providers.items() if r == role_name), None) ansible_deps = _roles_ansible_deps(str(role_dir.parent)) dep_edges: list[tuple[str, str, str]] = [] @@ -213,7 +272,16 @@ def derive_cosmos_mermaid(role_dir: Path, role_name: str) -> str: for provider, provs in provides_map.items(): if provider != role_name and key in provs: dep_roles.add(provider) - dep_edges.append((provider, key, _flag_kind(entry) or "fixed")) + dep_edges.append((provider, key, _entry_kind(entry))) + pinned = providers.get(key) + if ( + pinned + and pinned != role_name + and pinned in meta + and _pins_provider_on(entry) + ): + dep_roles.add(pinned) + dep_edges.append((pinned, key, _entry_kind(entry))) gear_deps = { dep @@ -233,7 +301,7 @@ def derive_cosmos_mermaid(role_dir: Path, role_name: str) -> str: for other, other_services in meta.items(): if other == role_name: continue - kind = _consumption_kind(other_services, role_name, my_provides) + kind = _consumption_kind(other_services, role_name, my_provides, my_primary_key) if role_name in ansible_deps.get(other, set()): gear_dependents.add(other) kind = kind or "fixed" @@ -293,10 +361,16 @@ def derive_cosmos_mermaid(role_dir: Path, role_name: str) -> str: for s in anchor ] if overflow: - dpt_edge_list.extend((f"svc_{_node_id(s)}", "dpt_more", "fixed") for s in anchor) + dpt_edge_list.extend( + (f"svc_{_node_id(s)}", "dpt_more", "fixed") for s in anchor + ) dpt_pairs = _merge_edges(dpt_edge_list) - for (src, dst), kind in sorted(dep_pairs.items()): - lines.append(_edge(src, dst, kind)) - for (src, dst), kind in sorted(dpt_pairs.items()): - lines.append(_edge(src, dst, kind)) + emitted: list[str] = [] + for pairs in (dep_pairs, dpt_pairs): + for (src, dst), kind in sorted(pairs.items()): + lines.append(_edge(src, dst, kind)) + emitted.append(kind) + off_edges = [str(i) for i, kind in enumerate(emitted) if kind == "off"] + if off_edges: + lines.append(f" linkStyle {','.join(off_edges)} stroke:{_OFF_STROKE};") return "\n".join(lines) diff --git a/cli/build/readme/generate.py b/cli/build/readme/generate.py index 76b62b04b2..cc26fa6ca2 100644 --- a/cli/build/readme/generate.py +++ b/cli/build/readme/generate.py @@ -54,7 +54,11 @@ def _role_author(role_dir) -> str: meta = load_yaml(role_dir / ROLE_FILE_META_MAIN, default_if_missing={}) galaxy = meta.get("galaxy_info") if isinstance(meta, dict) else None author = galaxy.get("author") if isinstance(galaxy, dict) else None - return author.strip() if isinstance(author, str) and author.strip() else _DEFAULT_AUTHOR + return ( + author.strip() + if isinstance(author, str) and author.strip() + else _DEFAULT_AUTHOR + ) def _app_name(preamble: str, role_name: str) -> str: @@ -88,7 +92,8 @@ def _cosmos_legend() -> str: symbol glossary so a glyph means the same thing everywhere.""" return ( f"Solid `1:1` edges are fixed relationships; dashed `0..1` edges are " - f"conditional (enabled only in matching deployments). Node markers " + f"conditional (enabled only in matching deployments); red `0..0` edges " + f"are turned off in this role. Node markers " f"show the role's deploy modes ({to_emoji('host')} host, " f"{to_emoji('compose')} compose, {to_emoji('swarm')} swarm); " f"{to_emoji('disabled')} marks a service that is explicitly turned " @@ -105,9 +110,7 @@ def _managed_blocks( ) parsed = parse_readme(rendered) return { - title: block - for title, block in parsed.sections - if title in MANAGED_SECTIONS + title: block for title, block in parsed.sections if title in MANAGED_SECTIONS } diff --git a/cli/build/tree/__init__.py b/cli/build/tree/__init__.py index 5d349af055..189667f78b 100644 --- a/cli/build/tree/__init__.py +++ b/cli/build/tree/__init__.py @@ -4,11 +4,8 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[3] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 -# Expose patchable symbols for unit tests build_mappings = _main.build_mappings output_graph = _main.output_graph @@ -16,7 +13,6 @@ def find_roles(*args, **kwargs): return _main.find_roles(*args, **kwargs) def process_role(*args, **kwargs): - # sync patched callables into the implementation module _main.build_mappings = build_mappings _main.output_graph = output_graph return _main.process_role(*args, **kwargs) diff --git a/cli/build/tree/__main__.py b/cli/build/tree/__main__.py index 02401523c3..d38c03344c 100644 --- a/cli/build/tree/__main__.py +++ b/cli/build/tree/__main__.py @@ -28,10 +28,10 @@ def process_role( output: str, preview: bool, verbose: bool, - no_include_role: bool, # currently unused, kept for CLI compatibility - no_import_role: bool, # currently unused, kept for CLI compatibility - no_dependencies: bool, # currently unused, kept for CLI compatibility - no_run_after: bool, # currently unused, kept for CLI compatibility + no_include_role: bool, + no_import_role: bool, + no_dependencies: bool, + no_run_after: bool, ) -> None: """ Worker function: build graphs and (optionally) write meta/tree.json for a single role. @@ -45,23 +45,19 @@ def process_role( if verbose: print(f"[worker] Processing role: {role_name}") - # Build the full graph structure (all dep types / directions) for this role graphs: Dict[str, Any] = build_mappings( start_role=role_name, roles_dir=roles_dir, max_depth=depth, ) - # Preview mode: dump graphs to console instead of writing tree.json if preview: for key, data in graphs.items(): if verbose: print(f"[worker] Previewing graph '{key}' for role '{role_name}'") - # In preview mode we always output as console output_graph(data, "console", role_name, key) return - # Non-preview: write meta/tree.json for this role if shadow_folder: tree_file = os.path.join(shadow_folder, role_name, "meta", "tree.json") else: @@ -120,7 +116,6 @@ def main(): help="Enable verbose logging", ) - # Toggles (kept for CLI compatibility, currently only meaningful for future extensions) parser.add_argument( "--no-include-role", action="store_true", @@ -153,7 +148,6 @@ def main(): roles = [role_name for role_name, _ in find_roles(args.role_dir)] - # For preview, run sequentially to avoid completely interleaved output. if args.preview: for role_name in roles: process_role( @@ -171,7 +165,6 @@ def main(): ) return - # Non-preview: roles are processed in parallel with ProcessPoolExecutor() as executor: futures = { executor.submit( @@ -181,7 +174,7 @@ def main(): args.depth, args.shadow_folder, args.output, - False, # preview=False in parallel mode + False, args.verbose, args.no_include_role, args.no_import_role, @@ -196,7 +189,6 @@ def main(): try: future.result() except Exception as exc: - # Do not crash the whole run; report the failing role instead. print(f"[ERROR] Role '{role_name}' failed: {exc}") diff --git a/cli/console/constants.py b/cli/console/constants.py index b9e641d65f..77152a8f2a 100644 --- a/cli/console/constants.py +++ b/cli/console/constants.py @@ -17,7 +17,6 @@ LS_DESC_LIMIT = 30 HELP_ALIASES = frozenset({"help", "?", "h"}) PROMPT_PREFIX = "🖥️ " -# REPL needs the on-disk cli/ root to resolve category/command paths. # nocheck: project-root-import not a project-root walk; resolves cli/ for category dispatch CLI_ROOT = Path(__file__).resolve().parents[1] RESERVED_DIRS = frozenset({"core", "__pycache__"}) diff --git a/cli/console/ls.py b/cli/console/ls.py index 85e05863fd..642a334807 100644 --- a/cli/console/ls.py +++ b/cli/console/ls.py @@ -18,8 +18,6 @@ def do_ls(current: list[str]) -> None: if not entries: print(color_text("(empty)", Style.DIM)) return - # Folders (categories) first, then commands; within each group keep - # the alphabetical order `iter_dir_entries` already established. ordered = sorted(entries, key=lambda e: (e.is_command, e.name)) max_name = max(len(entry.name) for entry in ordered) for entry in ordered: diff --git a/cli/console/navigation.py b/cli/console/navigation.py index 1bb7a7559d..1c6831da7f 100644 --- a/cli/console/navigation.py +++ b/cli/console/navigation.py @@ -14,9 +14,6 @@ from .constants import ( def is_category(segments: list[str]) -> bool: - # A category is a sub-package without its own `__main__.py`; once a - # package becomes directly executable it is a leaf command and the - # console runs it instead of cd-ing into it. if not segments: return True candidate = CLI_ROOT.joinpath(*segments) diff --git a/cli/console/repl.py b/cli/console/repl.py index 135f938f05..1f3cc39ebb 100644 --- a/cli/console/repl.py +++ b/cli/console/repl.py @@ -58,7 +58,6 @@ from .runner import ( with contextlib.suppress(ImportError): import readline # noqa: F401 -# Re-exports + the test surface stays addressable as `repl.`. __all__ = [ "AUTHOR", "AUTHOR_URL", diff --git a/cli/console/runner.py b/cli/console/runner.py index e675f21117..6be87d619b 100644 --- a/cli/console/runner.py +++ b/cli/console/runner.py @@ -10,10 +10,6 @@ from .navigation import prompt def clear_screen() -> None: if not sys.stdout.isatty(): return - # 2J clears the visible viewport, 3J wipes the scrollback buffer - # (xterm extension supported by every modern terminal), H homes the - # cursor. Together they leave a fresh frame for the next command's - # output instead of a stack of prior runs. print("\033[3J\033[2J\033[H", end="", flush=True) diff --git a/cli/contributing/changelog/archive/__main__.py b/cli/contributing/changelog/archive/__main__.py index 4cd6cbdbdf..f8551898cc 100644 --- a/cli/contributing/changelog/archive/__main__.py +++ b/cli/contributing/changelog/archive/__main__.py @@ -89,10 +89,6 @@ def main(argv: list[str] | None = None) -> int: verb = "would write" if args.dry_run else "wrote" - # CHANGELOG.md is the SPOT. Parse it once to capture the kept - # entries (which become the package-changelog source); the trim - # call writes new archive files, then the package mirror reads the - # archive directory to populate its trailing notice. content = changelog_path.read_text( encoding="utf-8" ) # nocheck: cache-read — CLI entry; downstream trim_and_archive rewrites changelog_path in same flow diff --git a/cli/contributing/mirror/cleanup/__main__.py b/cli/contributing/mirror/cleanup/__main__.py index ca880c1fb4..3bb0f7c863 100644 --- a/cli/contributing/mirror/cleanup/__main__.py +++ b/cli/contributing/mirror/cleanup/__main__.py @@ -28,9 +28,6 @@ if TYPE_CHECKING: def _gh_request(method: str, url: str, token: str) -> dict | list | None: - # All call sites build URLs from `https://api.github.com/…` literals - # plus a project-controlled `namespace`/`package` segment, so no - # arbitrary scheme can slip in. req = urllib.request.Request( # noqa: S310 url, headers={ diff --git a/cli/contributing/mirror/sync/__main__.py b/cli/contributing/mirror/sync/__main__.py index 41d507b74e..b7a892c9cf 100644 --- a/cli/contributing/mirror/sync/__main__.py +++ b/cli/contributing/mirror/sync/__main__.py @@ -81,7 +81,6 @@ def main() -> int: last_start_ts: float | None = None for img in iter_role_images(repo_root): - # Optional throttling (only when --images-per-hour is set) last_start_ts = _throttle_before_next_copy( images_per_hour=args.images_per_hour, last_start_ts=last_start_ts, @@ -104,7 +103,6 @@ def main() -> int: provider.mirror(img) except subprocess.CalledProcessError as e: - # keep going, but remember the failure msg = ( f"{label}: FAILED (exit={e.returncode})\n" f" cmd: {' '.join(map(str, e.cmd))}" diff --git a/cli/contributing/mirror/wait/__main__.py b/cli/contributing/mirror/wait/__main__.py index bbd5bba804..9f3d911ccd 100644 --- a/cli/contributing/mirror/wait/__main__.py +++ b/cli/contributing/mirror/wait/__main__.py @@ -46,7 +46,6 @@ def main() -> int: provider = GHCRProvider.from_args(args) repo_root = Path(args.repo_root).resolve() - # Deduplicate by destination ref, keeping one ImageRef per ref to probe with. refs: dict[str, ImageRef] = {} for img in iter_role_images(repo_root): refs.setdefault(f"{provider.image_base(img)}:{img.version}", img) diff --git a/cli/contributing/network/address/suggest/__main__.py b/cli/contributing/network/address/suggest/__main__.py index bc7ef0b28f..b8ab134482 100755 --- a/cli/contributing/network/address/suggest/__main__.py +++ b/cli/contributing/network/address/suggest/__main__.py @@ -24,8 +24,6 @@ from utils.meta.scan import iter_subnets if TYPE_CHECKING: from collections.abc import Iterable -# Prefix length thresholds — smallest prefix that still fits N clients. -# Each entry is (max_clients, prefix_length). _PREFIX_THRESHOLDS: tuple[tuple[int, int], ...] = ( (2, 30), (6, 29), @@ -62,8 +60,6 @@ def umbrella_blocks_for(prefix: int) -> list[ipaddress.IPv4Network]: return [] umbrellas: set[ipaddress.IPv4Network] = set() for net in occupied: - # The umbrella block is the closest enclosing /24 (or coarser). - # For prefixes <= 24 the umbrella is the network itself. umbrella_prefix = min(prefix, 24) umbrellas.add(net.supernet(new_prefix=umbrella_prefix)) return sorted(umbrellas, key=lambda n: int(n.network_address)) diff --git a/cli/contributing/network/diagnose/config.py b/cli/contributing/network/diagnose/config.py index 23848c6e68..a9575f6d68 100644 --- a/cli/contributing/network/diagnose/config.py +++ b/cli/contributing/network/diagnose/config.py @@ -2,6 +2,8 @@ from __future__ import annotations +from utils.paths import read_group_paths + DEFAULT_HOSTS: tuple[str, ...] = ( "github.com", "objects.githubusercontent.com", @@ -58,12 +60,7 @@ PROXY_ENV_KEYS: tuple[str, ...] = ( "CA_TRUST_NAME", ) -CA_BUNDLE_CANDIDATES: tuple[str, ...] = ( - "/etc/ssl/certs/ca-certificates.crt", - "/etc/pki/tls/certs/ca-bundle.crt", - "/etc/ssl/ca-bundle.pem", - "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", -) +CA_BUNDLE_CANDIDATES: tuple[str, ...] = tuple(read_group_paths("CA_BUNDLE_CANDIDATES")) PMTU_PROBE_SIZES: tuple[int, ...] = (1472, 1452, 1400, 1300, 1200, 1024, 576, 256) diff --git a/cli/contributing/network/diagnose/report.py b/cli/contributing/network/diagnose/report.py index 91a176e3d3..d8d9da21a0 100644 --- a/cli/contributing/network/diagnose/report.py +++ b/cli/contributing/network/diagnose/report.py @@ -110,5 +110,5 @@ def has_ipv6_default_route() -> bool: if len(parts) >= 10 and parts[0] == "0" * 32 and parts[-1] != "lo": return True except OSError: - pass # best-effort: treat unreadable /proc/net/ipv6_route as no default route + pass return False diff --git a/cli/contributing/network/diagnose/tools.py b/cli/contributing/network/diagnose/tools.py index aa16b51e08..5637cef544 100644 --- a/cli/contributing/network/diagnose/tools.py +++ b/cli/contributing/network/diagnose/tools.py @@ -19,7 +19,7 @@ def detect_distro_id(*, os_release_path: str = "/etc/os-release") -> str: if raw.startswith("ID="): return raw.split("=", 1)[1].strip().strip('"').lower() except OSError: - pass # best-effort: return empty distro id when /etc/os-release is unreadable + pass return "" diff --git a/cli/core/app.py b/cli/core/app.py index da961cb264..85cdb38d5b 100644 --- a/cli/core/app.py +++ b/cli/core/app.py @@ -27,7 +27,7 @@ class Flags: infinite: bool = False help_all: bool = False tree: bool = False - tree_depth: int | None = None # None = unbounded + tree_depth: int | None = None version: bool = False @@ -40,9 +40,7 @@ def _first_non_flag_token(argv: list[str]) -> str | None: while i < len(argv): token = argv[i] - # Skip flags and their args if token == "--log": # noqa: S105 `token` is a CLI argv element, not a credential - # Skip '--log' and its argument if present i += 2 continue @@ -86,13 +84,10 @@ def _parse_log_dir(argv: list[str]) -> Path | None: ) raise SystemExit(1) - # Determine the first command token (skipping '--log ' properly) first_cmd = _first_non_flag_token(argv) - # Always remove '--log ' from argv del argv[i : i + 2] - # Keep previous behavior: only enable logging for "deploy" if first_cmd != "deploy": return None @@ -143,13 +138,11 @@ def _resolve_version() -> str: def main() -> None: - argv = sys.argv[:] # keep sys.argv for external tools, but parse on a copy + argv = sys.argv[:] flags = parse_flags(argv) args = argv[1:] cli_dir = PROJECT_ROOT / "cli" - # sanity: cli_dir should contain __init__.py and __main__.py of dispatcher - # but we do not hard-fail here if flags.version: print(f"infinito {_resolve_version()}") @@ -158,7 +151,6 @@ def main() -> None: if flags.git_clean: git_clean_repo() - # Global "show help for all commands" mode if flags.help_all: print_global_help(cli_dir) print(color_text("Full detailed help for all subcommands:", Style.BRIGHT)) @@ -166,7 +158,6 @@ def main() -> None: show_full_help_for_all(cli_dir) raise SystemExit(0) - # Tree view: optional path prefix + optional depth limit if flags.tree: tree_path_args = [a for a in args if a not in ("-h", "--help")] candidate = cli_dir.joinpath(*tree_path_args) if tree_path_args else cli_dir @@ -181,31 +172,24 @@ def main() -> None: print_tree(cli_dir, tree_path_args, max_depth=flags.tree_depth) raise SystemExit(0) - # Global help: no args or top-level help flag if not args or args[0] in ("-h", "--help"): print_global_help(cli_dir) raise SystemExit(0) - # Directory-specific help: " -h" / " --help" if len(args) > 1 and args[-1] in ("-h", "--help"): - # First: if "" is a real command, forward help to its argparse. module, remaining = resolve_command_module(cli_dir, args[:-1]) if module and not remaining: subprocess.run([sys.executable, "-m", module, "--help"], check=False) raise SystemExit(0) - # Otherwise: category-folder overview if the path exists on disk. dir_parts = args[:-1] candidate = cli_dir.joinpath(*dir_parts) if candidate.is_dir(): print_dir_overview(cli_dir, dir_parts) raise SystemExit(0) - # Resolve command module by package folders with __main__.py module, remaining = resolve_command_module(cli_dir, args) if not module: - # If the literal argv path exists on disk as a category folder - # (no __main__.py), navigate into it instead of failing. candidate = cli_dir.joinpath(*args) if candidate.is_dir(): print_dir_overview(cli_dir, args) @@ -213,7 +197,6 @@ def main() -> None: print(color_text(f"Error: command '{' '.join(args)}' not found.", Fore.RED)) raise SystemExit(1) - # If user requested help for the resolved command, forward directly if remaining and remaining[0] in ("-h", "--help"): subprocess.run([sys.executable, "-m", module, remaining[0]], check=False) raise SystemExit(0) diff --git a/cli/core/discovery.py b/cli/core/discovery.py index 1b8e2de506..9e53e3e6d2 100644 --- a/cli/core/discovery.py +++ b/cli/core/discovery.py @@ -102,7 +102,6 @@ def discover_commands(cli_dir: Path) -> list[Command]: commands: list[Command] = [] for root, dirnames, filenames in os.walk(cli_dir): - # prune __pycache__ eagerly dirnames[:] = [d for d in dirnames if d != "__pycache__"] if "__main__.py" not in filenames: @@ -114,7 +113,6 @@ def discover_commands(cli_dir: Path) -> list[Command]: rel = root_path.relative_to(cli_dir) if rel.parts == (): - # cli/ itself is NOT a command; cli/__main__.py is the dispatcher continue parts = tuple(rel.parts) @@ -140,18 +138,12 @@ def resolve_command_module( argv_parts=["deploy","container","--foo","bar"] -> ("cli.administration.deploy.container", ["--foo","bar"]) """ - # Subcommand path is always BEFORE the first flag (CLI convention) and - # cannot contain absolute paths or path separators. Capping the search - # window at the first "non-subcommand-shaped" arg keeps the loop from - # building paths that contain huge `--vars` JSON or absolute `--vars-file` - # values, which previously triggered ENAMETOOLONG inside `is_dir()`. max_prefix = len(argv_parts) for i, part in enumerate(argv_parts): if not part or part.startswith("-") or "/" in part or "\\" in part: max_prefix = i break - # We resolve by checking for cli//__main__.py existing. for n in range(max_prefix, 0, -1): candidate_dir = cli_dir.joinpath(*argv_parts[:n]) try: @@ -159,8 +151,5 @@ def resolve_command_module( module = "cli." + ".".join(argv_parts[:n]) return module, argv_parts[n:] except OSError: - # stat() may legitimately fail (ENAMETOOLONG, ENOENT on broken - # symlinks, EACCES, ...); none of these mean "this is the - # command", so just keep trying shorter prefixes. continue return None, argv_parts diff --git a/cli/core/run.py b/cli/core/run.py index a6099eb307..75b00971a7 100644 --- a/cli/core/run.py +++ b/cli/core/run.py @@ -29,7 +29,6 @@ def open_log_file(log_dir: Path) -> tuple[TextIO, Path]: log_dir = log_dir.expanduser() log_dir.mkdir(parents=True, exist_ok=True) - # Best-effort permission hardening (ignore failures on non-POSIX / special FS). with contextlib.suppress(Exception): log_dir.chmod(0o700) diff --git a/cli/make/__init__.py b/cli/make/__init__.py index b6f1a4eed3..0d52a6a896 100644 --- a/cli/make/__init__.py +++ b/cli/make/__init__.py @@ -12,8 +12,6 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[2] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 __all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 diff --git a/cli/make/__main__.py b/cli/make/__main__.py index f9400e0abf..6074e88754 100755 --- a/cli/make/__main__.py +++ b/cli/make/__main__.py @@ -22,20 +22,17 @@ def main(): ) args = parser.parse_args() - # Default to 'build' if no target is specified make_args = args.targets or ["build"] from . import PROJECT_ROOT repo_root = str(PROJECT_ROOT) - # Check for Makefile makefile_path = str(Path(repo_root) / "Makefile") if not Path(makefile_path).is_file(): print(f"Error: Makefile not found in {repo_root}", file=sys.stderr) sys.exit(1) - # Invoke make in repo root cmd = ["make", *make_args] try: result = subprocess.run(cmd, cwd=repo_root, check=False) diff --git a/cli/meta/ci/chunks.py b/cli/meta/ci/chunks.py new file mode 100644 index 0000000000..498a5004b1 --- /dev/null +++ b/cli/meta/ci/chunks.py @@ -0,0 +1,80 @@ +"""Split the ordered discovery rows into the serial chunks of one sweep. + +A *sweep* is one orchestrator run. It deploys its rows in serial chunk +blocks, each small enough that its last runner wave still starts inside the +queue window (:mod:`cli.meta.ci.slots` sizes them). Two rules shape the split: + +* **Priority first, never mixed.** Priority rows sort to the head of the list + and the split forces a chunk boundary at the priority/regular seam, so a + chunk is either all priority or all regular. The seam chunk stays short + rather than being topped up with regular rows -- that is what guarantees + every priority row is done before the first regular one starts. Priority is + never subject to the sweep offset: it leads every sweep. + +* **The head leads unless an operator says otherwise.** Chunk 0 starts at the + top of the ranking. The list is ordered coverage-first, so its head is what a + run most needs proven, and a sweep that cannot afford the whole list leaves + the tail behind rather than sliding a window over it. + + ``offset`` moves that start deliberately: it is how an operator reaches the + tail without waiting for anything. It defaults to 0, so every run that does + not ask for it deploys the same head and can be compared against the last + one. This used to be derived from the sweep number instead, which bought tail + coverage at the price of the head -- chunk 0 began wherever the arithmetic + pointed, the rows that matter most ran only every few sweeps, and no two runs + were comparable. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence + from typing import TypeVar + + T = TypeVar("T") + + +def slice_chunks(rows: Sequence[T], size: int) -> list[list[T]]: + """Cut *rows* into consecutive blocks of at most *size*.""" + if size < 1: + raise ValueError(f"chunk size must be >= 1, got {size}") + return [list(rows[start : start + size]) for start in range(0, len(rows), size)] + + +def plan( + priority: Sequence[T], + regular: Sequence[T], + *, + size: int, + blocks: int, + budget: int, + offset: int = 0, +) -> list[list[T]]: + """The chunks one sweep deploys, priority blocks first. + + Args: + priority: rows of the priority line, in query order. + regular: rows of the regular line, in query order. + size: rows one chunk may hold (``slots.chunk_size``). + blocks: chunk blocks the workflow declares (``slots.chunk_count``). + budget: rows the run job cap allows in total (``slots.available``). + offset: how many regular rows to skip before filling the chunks. ``0`` + (the default) starts at the head of the ranking. A value past the + end of the list leaves the regular chunks empty rather than + wrapping: an operator who asks for a window beyond the tail gets an + empty run, not a silent restart at the top. + + Returns: + at most *blocks* chunks, none larger than *size*, together holding at + most *budget* rows. Priority chunks come first and are never topped up + with regular rows. + """ + priority_chunks = slice_chunks(priority[:budget], size)[:blocks] + spent = sum(len(chunk) for chunk in priority_chunks) + capacity = max(min((blocks - len(priority_chunks)) * size, budget - spent), 0) + if not capacity or not regular: + return priority_chunks + start = max(offset, 0) + return priority_chunks + slice_chunks(regular[start : start + capacity], size) diff --git a/cli/meta/ci/dev_runtime.py b/cli/meta/ci/dev_runtime.py index 59bb021002..ff4f248163 100644 --- a/cli/meta/ci/dev_runtime.py +++ b/cli/meta/ci/dev_runtime.py @@ -5,6 +5,7 @@ matrix entry, without embedding a python one-liner per question. python3 -m cli.meta.ci.dev_runtime images python3 -m cli.meta.ci.dev_runtime distro --image fedora:latest + python3 -m cli.meta.ci.dev_runtime matrix --mode rotate --run 42 """ from __future__ import annotations @@ -18,6 +19,58 @@ from utils.distros import ( dev_runtime_images, distro_of_dev_runtime_image, ) +from utils.symbol_glossary import to_emoji + +TRACKS = ("compose", "swarm") + + +def image_label(image: str) -> str: + """Shorten a dev-runtime image to its last two registry segments. + + ``quay.io/centos/centos:latest`` becomes ``centos:latest``; a two-segment + image such as ``debian:bookworm`` is returned unchanged. + + Args: + image: full image reference. + + Returns: + The last two segments, joined by the separator that preceded the last. + """ + head, sep, tail = image.rpartition(":") + if not sep: + head, sep, tail = image.rpartition("/") + if not sep: + return image + return f"{head.rpartition('/')[2]}{sep}{tail}" + + +def workspace_matrix(images: list[str], mode: str, run: int) -> list[dict[str, str]]: + """Assign exactly one workspace track to every dev-runtime image. + + Args: + images: dev-runtime images, in SPOT order. + mode: ``compose`` or ``swarm`` to pin every image to that track, + ``rotate`` to split the images across both. + run: run number; its parity flips a rotated split, so two consecutive + runs cover both tracks on every image. + + Returns: + One ``{"image", "track", "icon", "label"}`` entry per image. + """ + tracks = ( + [mode] * len(images) + if mode in TRACKS + else [TRACKS[(index + run) % len(TRACKS)] for index in range(len(images))] + ) + return [ + { + "image": image, + "track": track, + "icon": to_emoji(track), + "label": image_label(image), + } + for image, track in zip(images, tracks, strict=True) + ] def main(argv: list[str] | None = None) -> int: @@ -30,9 +83,21 @@ def main(argv: list[str] | None = None) -> int: distro.add_argument( "--image", required=True, help="Matrix image, e.g. fedora:latest." ) + matrix = commands.add_parser( + "matrix", help="Print {image, track} pairs for the workspace matrix." + ) + matrix.add_argument( + "--mode", + required=True, + choices=(*TRACKS, "rotate"), + help="Pin every image to one track, or rotate the split by run parity.", + ) + matrix.add_argument( + "--run", required=True, type=int, help="Run number; its parity flips a rotate." + ) args = parser.parse_args(argv) - if args.command == "images": + if args.command in ("images", "matrix"): images = list(dev_runtime_images()) if not images: print( @@ -41,7 +106,10 @@ def main(argv: list[str] | None = None) -> int: file=sys.stderr, ) return 1 - print(json.dumps(images)) + if args.command == "images": + print(json.dumps(images)) + else: + print(json.dumps(workspace_matrix(images, args.mode, args.run))) return 0 print(distro_of_dev_runtime_image(args.image)) diff --git a/cli/meta/ci/logs/download/__main__.py b/cli/meta/ci/logs/download/__main__.py index 2de5f04186..73cb6a3d42 100644 --- a/cli/meta/ci/logs/download/__main__.py +++ b/cli/meta/ci/logs/download/__main__.py @@ -63,7 +63,6 @@ def _build_parser() -> argparse.ArgumentParser: def _download_logs(owner, repo, run, jobs, args, dest, workers, delay_max): want = _selected_conclusions(args) - # In-progress jobs (conclusion=null) have no log endpoint yet; skip them. sel = [ j for j in jobs diff --git a/cli/meta/ci/logs/download/fetch.py b/cli/meta/ci/logs/download/fetch.py index 4ec29ab4b2..7ae399a9b8 100644 --- a/cli/meta/ci/logs/download/fetch.py +++ b/cli/meta/ci/logs/download/fetch.py @@ -25,7 +25,13 @@ def download_log( ) -> tuple[str, bool]: jitter(delay_max) safe = _SAFE.sub("-", job["name"]).strip("-") - proc = gh_proc(["api", f"repos/{owner}/{repo}/actions/jobs/{job['id']}/logs"]) + proc = gh_proc( + [ + "api", + "--allow-escape-sequences", + f"repos/{owner}/{repo}/actions/jobs/{job['id']}/logs", + ] + ) if proc.returncode != 0 or not proc.stdout: return job["name"], False (dest / f"{job['id']}__{safe}.log").write_text(proc.stdout, encoding="utf-8") @@ -37,7 +43,6 @@ def download_artifact( ) -> tuple[str, bool]: jitter(delay_max) target = dest / name - # gh refuses to extract over existing files, so clear the dir for re-runs. shutil.rmtree(target, ignore_errors=True) proc = gh_proc( ["run", "download", run, "-R", f"{owner}/{repo}", "-n", name, "-D", str(target)] diff --git a/cli/meta/ci/matrix.py b/cli/meta/ci/matrix.py new file mode 100644 index 0000000000..ba20407b99 --- /dev/null +++ b/cli/meta/ci/matrix.py @@ -0,0 +1,252 @@ +"""Build the CI deploy matrix of one sweep, chunk by chunk. + +Usage: + python -m cli.meta.ci.matrix --index N [--sweep S] [--modes auto] + [--whitelist "..."] [--priority "..."] [--lifecycles "..."] [--tor auto] + [--distros "..."] [--filesystem "..."] + +This is the pipeline the deploy jobs discover through, and the single place +the run's shape is decided: + +1. Two discovery queries, keeping today's filter semantics: the priority line + is queried on its own whitelist so priority roles run even when the + diff-derived whitelist would not have selected them, and the regular line + is queried on the effective whitelist with the priority rows withdrawn. + Concatenated, they are the sweep's ordered candidate list. Both lists are + selection tokens (:mod:`utils.github.variant.selection`): what a token pins + narrows the row, what it leaves open the line decides as it always did. +2. Every row is assigned its deploy mode, tor state, distro and filesystem by + its position in that list (:mod:`utils.github.variant.axes`). +3. The list is cut into serial chunks with a hard boundary at the + priority/regular seam (:mod:`cli.meta.ci.chunks`), sized by the run's job + and queue budget (:mod:`cli.meta.ci.slots`). + +``--index`` then prints one chunk as the matrix JSON. Every chunk block runs +the same computation and takes its own slice, so the blocks agree without +passing state between them. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +from cli.meta.ci import chunks, query, slots +from utils.cache.applications import get_variants +from utils.github.variant import axes, pools, selection, tor +from utils.roles.display import display_names + +DROPPED = ("priority", "weight", "id", "covered", "clone") +"""Entry keys the plan table reads but the matrix JSON withholds, so a deploy +job cannot reference one: they describe the row's rank, not its deployment.""" + + +def candidates( + *, + modes: tuple[str, ...], + whitelist: str, + priority: str, + lifecycles: str, +) -> list[dict]: + """The sweep's ordered candidate rows: priority line first, then the + regular line, each annotated with the modes it offers and whether it is + priority.""" + leading = selection.parse_list(priority) + keep = selection.parse_list(whitelist) + rows: list[dict] = [] + if leading: + rows += [ + {**row, "priority": True} + for row in selection.apply( + query.discover_rows( + modes, whitelist=selection.names(leading), lifecycles=lifecycles + ), + leading, + ) + ] + pinned = {(pin.app, variant) for pin in leading for variant in pin.variants} + regular = [ + row + for row in query.discover_rows( + modes, + whitelist=selection.names(keep), + blacklist=selection.names(pin for pin in leading if not pin.variants), + lifecycles=lifecycles, + ) + if (row["name"], row.get("variant")) not in pinned + ] + rows += [{**row, "priority": False} for row in selection.apply(regular, keep)] + return [{**row, "modes": query.row_modes(row, modes)} for row in rows] + + +def entries_of( + *, + modes: tuple[str, ...], + whitelist: str, + priority: str, + lifecycles: str, + sweep: int, + tor_mode: str, + distros: tuple[str, ...], + filesystems: tuple[str, ...], +) -> list[dict[str, str]]: + """Every candidate row of the sweep, axes assigned, in global order.""" + return axes.assign( + candidates( + modes=modes, + whitelist=whitelist, + priority=priority, + lifecycles=lifecycles, + ), + sweep=sweep, + tor_mode=tor_mode, + distros=distros, + filesystems=filesystems, + variants_per_app=get_variants(), + ) + + +def resolve_offset(raw: int | str | None = None) -> str: + """The offset a run was given, as written. ``None`` reads + ``INFINITO_CI_OFFSET``; :func:`offset_index` decides what it means.""" + if raw is None: + raw = os.environ.get("INFINITO_CI_OFFSET") + return "" if raw is None else str(raw).strip() + + +def offset_index(raw: int | str | None, regular: list[dict[str, str]]) -> int: + """Where the regular chunks start reading. + + A number is that many rows; anything else is a selection token + (:mod:`utils.github.variant.selection`) and the start is the first regular + row it names. Resuming at a role beats counting rows by hand: the ranking + shifts whenever a variant is added, so the index that meant 'carry on + behind nextcloud' yesterday means something else today, while the token + still says it. + + Args: + raw: the ``offset`` input, a count or a token. + regular: the regular line in ranking order. + + Raises: + SystemExit: a token that names no regular row. Starting at 0 instead + would silently redeploy the head an operator meant to skip. + """ + text = "" if raw is None else str(raw).strip() + if not text: + return 0 + if text.lstrip("+-").isdigit(): + return max(int(text), 0) + pin = selection.parse(text) + for index, entry in enumerate(regular): + if selection.covers(pin, entry): + return index + raise SystemExit( + f"offset {selection.describe(pin)!r} names no row of the regular line; " + f"it is on the priority line, outside the run's filters, or gone" + ) + + +def redundant(entry: dict[str, str]) -> bool: + """Whether the sweep drops this row as coverage an earlier row already has.""" + if entry["priority"] == "true": + return False + return entry["clone"] == "true" or entry["covered"] != "0" + + +def chunks_of( + entries: list[dict[str, str]], offset: int | str | None = 0 +) -> list[list[dict[str, str]]]: + """Cut the sweep's entries into its chunks, priority blocks first. + + Chunk 0 holds the head of the ranking unless *offset* moves it; the order + *inside* a chunk is then sorted + (:func:`utils.github.variant.axes.sort_key`), so the job list reads by role + rather than by rank.""" + regular = [ + entry + for entry in entries + if entry["priority"] != "true" and not redundant(entry) + ] + return [ + sorted(chunk, key=axes.sort_key) + for chunk in chunks.plan( + [entry for entry in entries if entry["priority"] == "true"], + regular, + size=slots.chunk_size(), + blocks=slots.chunk_count(), + budget=slots.available(), + offset=offset_index(offset, regular), + ) + ] + + +def build_sweep( + *, + modes: tuple[str, ...], + whitelist: str, + priority: str, + lifecycles: str, + sweep: int, + tor_mode: str, + distros: tuple[str, ...], + filesystems: tuple[str, ...], + offset: int = 0, +) -> list[list[dict[str, str]]]: + """Every chunk of the sweep, priority blocks first.""" + return chunks_of( + entries_of( + modes=modes, + whitelist=whitelist, + priority=priority, + lifecycles=lifecycles, + sweep=sweep, + tor_mode=tor_mode, + distros=distros, + filesystems=filesystems, + ), + offset, + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Build the CI deploy matrix of one sweep chunk." + ) + parser.add_argument("--index", type=int, required=True) + parser.add_argument("--sweep", type=int, default=None) + parser.add_argument("--modes", default=query.ALL_MODES) + parser.add_argument("--whitelist", default="") + parser.add_argument("--priority", default="") + parser.add_argument("--lifecycles", default="") + parser.add_argument("--tor", default=None) + parser.add_argument("--distros", default="") + parser.add_argument("--filesystem", default="") + parser.add_argument("--offset", default=None) + args = parser.parse_args(argv) + + codec = display_names() + if args.lifecycles.strip(): + os.environ["INFINITO_LIFECYCLES"] = args.lifecycles + + sweep = axes.resolve_sweep() if args.sweep is None else args.sweep + plan = build_sweep( + modes=query.resolve_modes(args.modes), + whitelist=codec.decode_list(args.whitelist), + priority=codec.decode_list(args.priority), + lifecycles=args.lifecycles, + sweep=sweep, + tor_mode=tor.resolve_tor_mode(args.tor), + distros=pools.resolve_distros(args.distros), + filesystems=pools.resolve_filesystems(args.filesystem), + offset=resolve_offset(args.offset), + ) + chunk = plan[args.index] if 0 <= args.index < len(plan) else [] + print(json.dumps([{k: v for k, v in e.items() if k not in DROPPED} for e in chunk])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cli/meta/ci/plan.py b/cli/meta/ci/plan.py index 257de3bc4a..f7c3294a82 100644 --- a/cli/meta/ci/plan.py +++ b/cli/meta/ci/plan.py @@ -1,22 +1,24 @@ -"""Render the plan of a CI run, one section per deploy mode. +"""Render the plan of one CI sweep: every candidate row, and where it lands. Usage: - python -m cli.meta.ci.plan --distros "debian" [--whitelist "..."] - [--priority "..."] [--modes "swarm compose host"] [--lifecycles "..."] - [--cli] + python -m cli.meta.ci.plan [--distros "debian"] [--filesystem "zfs"] + [--whitelist "..."] [--priority "..."] [--modes auto] + [--lifecycles "..."] [--sweep N] [--cli] -Every section runs the production discovery query (cli.meta.ci.query, -the same SPOT scripts/meta/resolve/apps.sh uses) three times: the -priority line, the capped regular line, and the uncapped candidate list. -Rows keep the query's own order on the mode's own row basis, so the -plan mirrors the ``--matrix`` view exactly: swarm rows are per-variant -``role#variant`` selections (per-variant weight, the budget cut can -split a role), compose and host rows are whole-role with the bundled -variants listed in the variant cell (query.expands_variants SPOT). -Status per row: ⭐ priority line, ✅ triggered, ❌ fell behind the cap -or the coverage dedup. +The plan runs the same pipeline the deploy jobs discover through +(``cli.meta.ci.matrix``), so what the table shows and what CI deploys cannot +diverge. One row per ``role#variant`` candidate in global query order, with +the chunk it falls into and the axes it was assigned. +Status per row: ⭐ a priority row, ✅ deployed by this sweep, ❌ beyond the +sweep's budget (raise ``--offset`` to reach it), ✂️ cut as redundant coverage — +a clone or a row an earlier one already embeds, which no sweep deploys. ``--cli`` renders fixed-width terminal tables instead of Markdown. + +🆔 numbers the rows of this table, 1..n, and 🔰 names the 🆔 of the earlier row +that already embeds this one -- empty when nothing does. A row with a 🔰 is +redundant coverage: whatever it would prove, the row it points at proves first. 🐑 marks the other reason a row is cut: it +shares its service set with an earlier role, which stands in for it. """ from __future__ import annotations @@ -25,119 +27,122 @@ import argparse import os import sys -from cli.meta.ci.query import MODES, discover, expands_variants, max_jobs -from cli.meta.roles.applications.complexity.model import ( - compute_complexity_rows, - compute_variant_complexity_rows, -) +from cli.meta.ci import matrix, query, slots from cli.meta.roles.applications.complexity.render import _dwidth -from utils.cache.files import PROJECT_ROOT +from utils.github.variant import axes, pools, tor from utils.roles.display import display_names from utils.symbol_glossary import to_emoji _STAR = to_emoji("priority") _OK = to_emoji("enabled") _OFF = to_emoji("disabled") +_CUT = to_emoji("redundant") -_COLUMNS = ("id", "name", "weight", "variant", "distros") -_HEADERS = ( - *(f"{to_emoji(key)} {key.capitalize()}" for key in _COLUMNS), - f"{to_emoji('enabled')} Triggered", +_COLUMNS = ( + "id", + "chunk", + "name", + "variant", + "mode", + "distro", + "filesystem", + "tor", + "triggered", + "covered_by", + "weight", + "clone", +) +_GLYPH = {"triggered": "enabled", "distro": "distros"} +_HEADERS = tuple( + f"{to_emoji(_GLYPH.get(key, key))} {key.replace('_', ' ').capitalize()}" + for key in _COLUMNS ) -def collect_mode_plan( - mode: str, *, whitelist: str, priority: str, lifecycles: str = "" -) -> list[tuple[str, str]]: - """Ordered ``(selection, status)`` pairs for one mode in query order - (selection is a role name, or ``role#variant`` on swarm): priority-line - selections first (⭐), then every uncapped candidate with ✅ when the - capped regular query triggers it, ❌ otherwise.""" - rows: list[tuple[str, str]] = [] - if priority.strip(): - rows += [ - (role, _STAR) - for role in discover( - mode, whitelist=priority, lifecycles=lifecycles, capped=True - ) - ] - triggered = set( - discover( - mode, - whitelist=whitelist, - blacklist=priority, - lifecycles=lifecycles, - capped=True, - ) +def _key(entry: dict[str, str]) -> tuple[str, ...]: + """What identifies one deploy row: every axis it was assigned. + + A priority role runs every combination of its variant, and a selection can + ask for one variant on two distros, so app+variant alone matches several + rows and would report the first one's chunk for all of them -- including + for rows the budget never reaches, which the table would then mark as + deployed. + """ + return ( + entry["apps"], + entry["variant"], + entry["mode"], + entry["tor"], + entry["distro"], + entry["filesystem"], ) - rows += [ - (role, _OK if role in triggered else _OFF) - for role in discover( - mode, - whitelist=whitelist, - blacklist=priority, - lifecycles=lifecycles, - capped=False, + + +def _chunk_of(entry: dict[str, str], plan: list[list[dict[str, str]]]) -> int | None: + """Index of the chunk *entry* landed in, or ``None`` when this sweep + leaves it to the next one.""" + key = _key(entry) + for index, chunk in enumerate(plan): + if any(_key(row) == key for row in chunk): + return index + return None + + +def cells( + entries: list[dict[str, str]], + plan: list[list[dict[str, str]]], +) -> list[tuple[str, ...]]: + rows = [] + positions: dict[str, str] = {} + for counter, entry in enumerate(entries, start=1): + positions.setdefault(entry.get("id", ""), str(counter)) + for counter, entry in enumerate(entries, start=1): + chunk = _chunk_of(entry, plan) + if matrix.redundant(entry): + status, where = _CUT, "" + elif chunk is None: + status, where = _OFF, "" + else: + status = _STAR if entry["priority"] == "true" else _OK + where = str(chunk) + covered = entry.get("covered", "0") + rows.append( + ( + str(counter), + where, + entry["apps"], + entry["variant"], + to_emoji(entry["mode"]), + to_emoji(entry["distro"]), + to_emoji(entry["filesystem"]), + to_emoji("tor" if entry["tor"] == "true" else "clearnet"), + status, + positions.get(covered, covered) if covered not in ("", "0") else "", + entry["weight"], + to_emoji("clone") if entry.get("clone") == "true" else "", + ) ) - ] return rows -def role_facts(lifecycles: str = "") -> tuple[dict[str, int], dict[str, int]]: - """Weights keyed by role name (whole-role weight) and by - ``role#variant`` token (per-variant weight), plus variant counts.""" - envelope = set(lifecycles.replace(",", " ").split()) or None - weights: dict[str, int] = {} - variants: dict[str, int] = {} - for row in compute_complexity_rows(PROJECT_ROOT / "roles", lifecycles=envelope): - weights[row.name] = row.weight - variants[row.name] = row.variants - for row in compute_variant_complexity_rows( - PROJECT_ROOT / "roles", lifecycles=envelope - ): - weights[f"{row.name}#{row.variant}"] = row.weight - return weights, variants +def _title(plan: list[list[dict[str, str]]], sweep: int) -> str: + sizes = ", ".join(str(len(chunk)) for chunk in plan) or "-" + return ( + f"sweep {sweep} · chunk size {slots.chunk_size()} " + f"· {len(plan)} chunk(s) [{sizes}] · budget {slots.available()}" + ) -def _cells( - mode: str, - rows: list[tuple[str, str]], - weights: dict[str, int], - variants: dict[str, int], - *, - distros: str, -) -> list[tuple[str, ...]]: - cells = [] - for counter, (selection, status) in enumerate(rows, start=1): - role, _, variant = selection.partition("#") - if not expands_variants(mode): - variant = ",".join(str(v) for v in range(variants.get(role, 1))) - cells.append( - ( - str(counter), - role, - str(weights.get(selection, weights.get(role, 0))), - variant, - distros, - status, - ) - ) - return cells - - -def render_markdown( - sections: list[tuple[str, int, list[tuple[str, ...]]]], -) -> str: - lines = ["## Plan 🗺️"] - for mode, budget, cells in sections: - lines += [ - "", - f"### {to_emoji(mode)} {mode} (max jobs: {budget})", - "", - "| " + " | ".join(_HEADERS) + " |", - "|" + "---|" * len(_HEADERS), - ] - lines += ["| " + " | ".join(cell) + " |" for cell in cells] +def render_markdown(title: str, rows: list[tuple[str, ...]]) -> str: + lines = [ + "## Plan 🗺️", + "", + f"### {title}", + "", + "| " + " | ".join(_HEADERS) + " |", + "|" + "---|" * len(_HEADERS), + ] + lines += ["| " + " | ".join(cell) + " |" for cell in rows] return "\n".join(lines) @@ -145,71 +150,54 @@ def _pad(value: str, width: int) -> str: return value + " " * max(width - _dwidth(value), 0) -def render_cli( - sections: list[tuple[str, int, list[tuple[str, ...]]]], -) -> str: +def render_cli(title: str, rows: list[tuple[str, ...]]) -> str: widths = [ - max( - [ - _dwidth(header), - *(_dwidth(cell[i]) for _, _, cells in sections for cell in cells), - ] - ) + max([_dwidth(header), *(_dwidth(cell[i]) for cell in rows)]) for i, header in enumerate(_HEADERS) ] - blocks = [] - for mode, budget, cells in sections: - title = f"{to_emoji(mode)} {mode} (max jobs: {budget})" - header = " ".join(_pad(h, w) for h, w in zip(_HEADERS, widths, strict=True)) - rule = " ".join("-" * w for w in widths) - rows = [ - " ".join(_pad(value, w) for value, w in zip(cell, widths, strict=True)) - for cell in cells - ] - blocks.append("\n".join([title, header, rule, *rows])) - return "\n\n".join(blocks) + header = " ".join(_pad(h, w) for h, w in zip(_HEADERS, widths, strict=True)) + rule = " ".join("-" * w for w in widths) + body = [ + " ".join(_pad(value, w) for value, w in zip(cell, widths, strict=True)) + for cell in rows + ] + return "\n".join([title, header, rule, *body]) def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - description="Render the CI plan, one section per deploy mode." - ) + parser = argparse.ArgumentParser(description="Render the plan of one CI sweep.") parser.add_argument("--distros", default="") parser.add_argument("--whitelist", default="") parser.add_argument("--priority", default="") - parser.add_argument("--modes", default="") + parser.add_argument("--modes", default=query.ALL_MODES) parser.add_argument("--lifecycles", default="") + parser.add_argument("--sweep", type=int, default=None) + parser.add_argument("--tor", default=None) + parser.add_argument("--filesystem", default="") + parser.add_argument("--offset", default=None) parser.add_argument("--cli", action="store_true") args = parser.parse_args(argv) codec = display_names() - args.whitelist = codec.decode_list(args.whitelist) - args.priority = codec.decode_list(args.priority) - if args.lifecycles.strip(): os.environ["INFINITO_LIFECYCLES"] = args.lifecycles - active = [m for m in MODES if m in args.modes.split()] or list(MODES) - weights, variants = role_facts(args.lifecycles) - sections = [] - for mode in active: - rows = collect_mode_plan( - mode, - whitelist=args.whitelist, - priority=args.priority, - lifecycles=args.lifecycles, - ) - cells = _cells(mode, rows, weights, variants, distros=args.distros) - sections.append( - ( - mode, - max_jobs(mode, blacklist=args.priority, lifecycles=args.lifecycles), - cells, - ) - ) + sweep = axes.resolve_sweep() if args.sweep is None else args.sweep + entries = matrix.entries_of( + modes=query.resolve_modes(args.modes), + whitelist=codec.decode_list(args.whitelist), + priority=codec.decode_list(args.priority), + lifecycles=args.lifecycles, + sweep=sweep, + tor_mode=tor.resolve_tor_mode(args.tor), + distros=pools.resolve_distros(args.distros), + filesystems=pools.resolve_filesystems(args.filesystem), + ) + plan = matrix.chunks_of(entries, matrix.resolve_offset(args.offset)) + rows = cells(entries, plan) render = render_cli if args.cli else render_markdown - print(render(sections)) + print(render(_title(plan, sweep), rows)) return 0 diff --git a/cli/meta/ci/query.py b/cli/meta/ci/query.py index 8f23e37d33..84e94ef8f0 100644 --- a/cli/meta/ci/query.py +++ b/cli/meta/ci/query.py @@ -1,241 +1,221 @@ """Single source of truth for the CI app-discovery query. Usage: - python -m cli.meta.ci.query --mode compose|swarm|host [--matrix] [--format json] + python -m cli.meta.ci.query [--modes "swarm compose host"] [--matrix] + [--format json] -Both the production discovery (scripts/meta/resolve/apps.sh) and the -plan table (cli.meta.ci.plan) resolve role lists through this -module, so the plan shows exactly the query the run executes. One query -per mode, sharing filter (mode + INFINITO_WHITELIST + INFINITO_BLACKLIST), -INFINITO_DISCOVERY_SORT order, lifecycle envelope and the -INFINITO_MAX_JOBS cap ('auto' resolves per mode via cli.meta.ci.slots): +One query per run, not one per deploy mode. Every row is a ``role#variant`` +selection, so the row basis, the ranking and the budget cut all speak the +same unit and the cut can select a subset of a role's variants. Which deploy +mode a row actually runs in is decided afterwards by the rotation in +``utils.github.variant.bundles``; the query only decides which rows exist. - compose whole-role rows, clones sorted last, variants packed into - size/storage bundles for the job count - host whole-role rows, clones and tested-elsewhere roles sorted - last, bundled like compose - swarm one row per variant (``role#variant`` tokens), ranked and - budget-cut on per-variant metrics; the cut can select a - subset of a role's variants +The mode selection is a *filter*, not an axis: ``--modes swarm`` keeps the +rows whose role can be deployed as a swarm stack, ``--modes "compose swarm"`` +keeps the rows at least one of the two can take. The shared filter is +mode-clause + INFINITO_WHITELIST + INFINITO_BLACKLIST, the order is +INFINITO_DISCOVERY_SORT, whose first key sorts clones last (one representative +per dna cluster stays ahead of the budget cut, so redundant same-service-set +variants fall behind it first), and the lifecycle envelope is +INFINITO_LIFECYCLES. -``--matrix`` renders exactly the row basis the mode's selection runs -on, so the matrix order IS the selection priority. ``capped=False`` -returns the full ordered candidate list so callers can show what fell -behind the budget cut. +``--matrix`` renders the full ordered candidate list, so the matrix order IS +the selection priority. Every human-facing view of that list goes through here +rather than re-deriving the sort and the filter: hand-rolling +``--sort "$INFINITO_DISCOVERY_SORT" --filter "compose == true"`` reads the +wrong column (``compose`` is what a role can do, ``test_compose`` is what CI +tests), which silently shows an order no run will ever take. """ from __future__ import annotations import argparse import json -import os import subprocess import sys -from cli.meta.ci import slots -from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.files import PROJECT_ROOT +from utils.env.parser import env_setting +from utils.github.variant.axes import MODES from utils.roles.display import display_names -MODES = ("compose", "swarm", "host") +ALL_MODES = "auto" -def expands_variants(mode: str) -> bool: - """Whether *mode* queries, ranks and triggers one CI job per variant. - Swarm does (``role#variant`` tokens through the whole chain); compose - and host bundle every variant into whole-role jobs (variant.bundles - SPOT), so their query rows stay whole-role too.""" - return mode == "swarm" +def resolve_modes(raw: str) -> tuple[str, ...]: + """The deploy modes a run may draw from. ``auto`` (or empty) means every + mode; anything else is the listed subset, in :data:`MODES` order. + + Raises: + SystemExit: a token that names no known mode -- a typo must not + silently narrow the run to nothing. + """ + tokens = raw.replace(",", " ").split() + if not tokens or tokens == [ALL_MODES]: + return MODES + unknown = [token for token in tokens if token not in MODES] + if unknown: + raise SystemExit( + f"unknown deploy mode(s): {' '.join(unknown)}; expected " + f"{', '.join(MODES)} or {ALL_MODES!r}" + ) + return tuple(mode for mode in MODES if mode in tokens) def build_filter( - mode: str, - whitelist: str = "", - blacklist: str = "", - covered: tuple[str, ...] = (), + modes: tuple[str, ...], whitelist: str = "", blacklist: str = "" ) -> str: - parts = [f"test_{mode} == true"] + """The complexity ``--filter`` expression for one run.""" + clause = " or ".join(f"test_{mode} == true" for mode in modes) + parts = [f"({clause})" if len(modes) > 1 else clause] include = ",".join(whitelist.split()) if include: parts.append(f"name %% {{{include}}}") exclude = ",".join(blacklist.split()) if exclude: parts.append(f"not (name %% {{{exclude}}})") - if covered: - parts.append(f"not (name %% {{{','.join(covered)}}})") return " and ".join(parts) -def compose_covered( - mode: str, *, whitelist: str, blacklist: str, lifecycles: str -) -> tuple[str, ...]: - """Roles the same run's compose line already triggers; the host line - drops them instead of redeploying them in a second single-node mode. - Active only when the caller signals a co-running compose line via - INFINITO_HOST_EXCLUDE_COMPOSE.""" - if mode != "host": - return () - flag = os.environ["INFINITO_HOST_EXCLUDE_COMPOSE"].strip().lower() - if flag not in ("1", "true", "yes"): - return () - return tuple( - discover( - "compose", - whitelist=whitelist, - blacklist=blacklist, - lifecycles=lifecycles, - ) - ) - - -def _sort_spec(mode: str) -> str: - """The discovery sort for *mode*. Every mode prepends clones-last (one - representative per dna cluster stays ahead of the budget cut, so redundant - same-service-set variants fall behind it first); host additionally sorts - tested-elsewhere roles down so its slots go to roles no compose or swarm - matrix already covers.""" - spec = os.environ["INFINITO_DISCOVERY_SORT"] - if not spec.strip(): - for line in read_text(str(PROJECT_ROOT / "default.env")).splitlines(): - if line.startswith("INFINITO_DISCOVERY_SORT="): - spec = line.split("=", 1)[1].strip().strip('"') - break - prefixes = { - "compose": "asc clone", - "swarm": "asc clone", - "host": "asc clone,asc tested_elsewhere", - } - prefix = prefixes.get(mode) - if prefix: - return f"{prefix},{spec}" if spec.strip() else prefix - return spec - - -def max_jobs(mode: str, *, blacklist: str = "", lifecycles: str = "") -> int: - """The mode's slot budget minus the jobs the run's priority line - already occupies (the priority whitelist arrives here as the regular - line's blacklist), floored at 0.""" - raw = os.environ["INFINITO_MAX_JOBS"].strip() - budget = slots.mode_slots()[mode] if raw in ("", "auto") else int(raw) - if blacklist.strip(): - budget -= len(discover(mode, whitelist=blacklist, lifecycles=lifecycles)) - return max(budget, 0) +def sort_spec() -> str: + """The discovery sort as declared in default.env.""" + return env_setting("INFINITO_DISCOVERY_SORT").strip() def _query_argv( - mode: str, + modes: tuple[str, ...], *, whitelist: str, blacklist: str, lifecycles: str, - job_cap: int | None, fmt: list[str], - covered: tuple[str, ...] = (), + variant: bool = True, ) -> list[str]: + """The complexity call this run discovers through. + + Args: + variant: ``False`` collapses the rows to whole roles. Only ``--matrix`` + renders that view; discovery itself is always per ``role#variant``, + because that is the unit the budget cut and the deploy speak. + """ args = [ sys.executable, "-m", "cli.meta.roles.applications.complexity", - "--deploy-mode", - mode, + *(["--variant"] if variant else []), "--filter", - build_filter(mode, whitelist, blacklist, covered), + build_filter(modes, whitelist, blacklist), "--sort", - _sort_spec(mode), + sort_spec(), *fmt, ] - if expands_variants(mode): - args.append("--variant") - envelope = lifecycles or os.environ["INFINITO_LIFECYCLES"] + envelope = lifecycles or env_setting("INFINITO_LIFECYCLES") if envelope.strip(): args += ["--lifecycles", envelope] - if job_cap is not None: - args += ["--max-jobs", str(job_cap)] return args -def discover( - mode: str, +def discover_rows( + modes: tuple[str, ...] = MODES, *, whitelist: str = "", blacklist: str = "", lifecycles: str = "", - capped: bool = True, -) -> list[str]: - """The ordered selection the discovery query yields for *mode*: - role names for compose and host, ``role#variant`` tokens for swarm.""" - job_cap = None - if capped: - job_cap = max_jobs(mode, blacklist=blacklist, lifecycles=lifecycles) - if job_cap == 0: - return [] - covered = compose_covered( - mode, whitelist=whitelist, blacklist=blacklist, lifecycles=lifecycles - ) +) -> list[dict]: + """The ordered candidate rows, each the complexity payload of one + ``role#variant``. Uncapped: the chunker decides what a sweep spends.""" out = subprocess.run( _query_argv( - mode, + modes, whitelist=whitelist, blacklist=blacklist, lifecycles=lifecycles, - job_cap=job_cap, - fmt=["--format", "string"], - covered=covered, + fmt=["--format", "json"], ), cwd=PROJECT_ROOT, capture_output=True, text=True, check=True, ).stdout - return [line.strip() for line in out.splitlines() if line.strip()] + return json.loads(out) if out.strip() else [] + + +def token(row: dict) -> str: + """The ``role#variant`` selection token of one query row.""" + return f"{row['name']}#{row['variant']}" + + +def row_modes(row: dict, modes: tuple[str, ...] = MODES) -> tuple[str, ...]: + """The selected deploy modes this row can actually run in. Never empty + for a row the query returned -- the filter kept it precisely because at + least one selected mode claims it.""" + return tuple(mode for mode in modes if row.get(f"test_{mode}")) + + +def discover( + modes: tuple[str, ...] = MODES, + *, + whitelist: str = "", + blacklist: str = "", + lifecycles: str = "", +) -> list[str]: + """The ordered ``role#variant`` tokens the query yields.""" + return [ + token(row) + for row in discover_rows( + modes, whitelist=whitelist, blacklist=blacklist, lifecycles=lifecycles + ) + ] def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( - description="Run the CI app-discovery query for one deploy mode." + description="Run the CI app-discovery query for one workflow run." ) - parser.add_argument("--mode", required=True, choices=MODES) + parser.add_argument("--modes", default=ALL_MODES) parser.add_argument( "--matrix", action="store_true", help=( - "Render the full complexity matrix in query order (uncapped) " - "on the mode's own row basis: per-variant rows for swarm, " - "whole-role rows for compose and host. The matrix order is " - "the selection priority." + "Render the full complexity matrix in query order: one row per " + "role#variant. The matrix order is the selection priority." + ), + ) + parser.add_argument( + "--roles", + action="store_true", + help=( + "With --matrix: one row per role instead of per role#variant, in " + "the same query order." ), ) parser.add_argument("--format", choices=("json",), dest="fmt") args = parser.parse_args(argv) codec = display_names() - whitelist = codec.decode_list(os.environ["INFINITO_WHITELIST"]) - blacklist = codec.decode_list(os.environ["INFINITO_BLACKLIST"]) + whitelist = codec.decode_list(env_setting("INFINITO_WHITELIST")) + blacklist = codec.decode_list(env_setting("INFINITO_BLACKLIST")) + modes = resolve_modes(args.modes) if args.matrix: return subprocess.run( _query_argv( - args.mode, + modes, whitelist=whitelist, blacklist=blacklist, lifecycles="", - job_cap=None, fmt=["-s"], - covered=compose_covered( - args.mode, - whitelist=whitelist, - blacklist=blacklist, - lifecycles="", - ), + variant=not args.roles, ), cwd=PROJECT_ROOT, check=False, ).returncode - roles = discover(args.mode, whitelist=whitelist, blacklist=blacklist) + tokens = discover(modes, whitelist=whitelist, blacklist=blacklist) if args.fmt == "json": - print(json.dumps(roles)) + print(json.dumps(tokens)) else: - print("\n".join(roles)) + print("\n".join(tokens)) return 0 diff --git a/cli/meta/ci/report_failures.py b/cli/meta/ci/report_failures.py index af692dd726..b8721a80a7 100644 --- a/cli/meta/ci/report_failures.py +++ b/cli/meta/ci/report_failures.py @@ -4,43 +4,79 @@ from __future__ import annotations import argparse import json -import re import subprocess import sys from pathlib import Path +from typing import NamedTuple from utils.cache.files import read_text -from utils.symbol_glossary import to_emoji, to_word +from utils.github.variant import axes +from utils.roles.display import display_names -_MODES = ("swarm", "compose", "host") -_ROLE_RE = re.compile( - r"(" + "|".join(re.escape(to_emoji(m)) for m in _MODES) + r")️?\s+" - r"((?:web-app|web-svc|svc|sys)-[a-z0-9-]+?)(?:\s+([0-9,]+))?\s*$" -) _DECISIVE_FILES = ("error-context.md", "meta.txt", "containers.txt") _TITLE = "CI failure: {role}" _LABEL = "ci-failure" -def failed_roles(jobs: list[dict]) -> dict[str, list[tuple[str, str]]]: - """Map role -> [(mode, variant)] for every failed deploy job in *jobs*.""" - out: dict[str, list[tuple[str, str]]] = {} +class Failure(NamedTuple): + """The combination one red deploy job died on -- everything the artifact + name is built from, so the reporter downloads the run it is reporting.""" + + mode: str + variant: str + tor: bool + distro: str + filesystem: str + + +def failed_roles(jobs: list[dict]) -> dict[str, list[Failure]]: + """Map role -> [:class:`Failure`] for every failed deploy job. + + A deploy job is titled `` `` with an optional trailing ⭐ for a + priority row. The middle is resolved through the display-name codec rather + than matched as a raw role id: job names carry display names, so a regex + over ``web-app-…`` silently matched nothing and every failure went + unreported. + """ + codec = display_names() + out: dict[str, list[Failure]] = {} for job in jobs: if job.get("conclusion") not in ("failure", "timed_out"): continue - match = _ROLE_RE.search(job.get("name", "")) - if match is None: + label = axes.parse_label(str(job.get("name", ""))) + if label is None: continue - mode = to_word(match.group(1)) - role = match.group(2) - variant = (match.group(3) or "").replace(",", "-") - out.setdefault(role, []).append((mode, variant)) + role = codec.decode(label.name) + if role is None: + continue + out.setdefault(role, []).append( + Failure( + label.mode, + label.variant.replace(",", "-"), + label.tor, + label.distro, + label.filesystem, + ) + ) return out -def artifact_name(mode: str, role: str, variant: str) -> str: - suffix = f"-{variant}" if variant else "" - return f"rescue-diagnostics-{mode}-{role}{suffix}" +def artifact_name(role: str, failure: Failure) -> str: + """The rescue-diagnostics artifact one deploy job uploads. + + The slug comes from :func:`axes.artifact_slug`, the same call the matrix + entry carries into the workflow, so the name this looks for and the name + CI uploads cannot drift apart. + """ + return "rescue-diagnostics-" + axes.artifact_slug( + failure.mode, + role, + failure.variant, + failure.tor, + failure.distro, + failure.filesystem, + ) def decisive_excerpt(rescue_dir: Path, *, max_lines: int = 40) -> str: @@ -60,16 +96,19 @@ def decisive_excerpt(rescue_dir: Path, *, max_lines: int = 40) -> str: def issue_body( role: str, - failures: list[tuple[str, str]], + failures: list[Failure], *, run_url: str, excerpt: str, ) -> str: rows = "\n".join( - f"- `{mode}`" - + (f" variant `{variant}`" if variant else "") - + f" — artifact `{artifact_name(mode, role, variant)}`" - for mode, variant in failures + f"- `{failure.mode}`" + + (f" variant `{failure.variant}`" if failure.variant else "") + + (" behind the onion" if failure.tor else "") + + (f" on `{failure.distro}`" if failure.distro else "") + + (f"/`{failure.filesystem}`" if failure.filesystem else "") + + f" — artifact `{artifact_name(role, failure)}`" + for failure in failures ) return ( f"Role **{role}** failed on `main`.\n\n" @@ -169,10 +208,10 @@ def report(run_id: str, repo: str) -> int: def _download_excerpt( - repo: str, run_id: str, role: str, failures: list[tuple[str, str]], dest: Path + repo: str, run_id: str, role: str, failures: list[Failure], dest: Path ) -> str: - for mode, variant in failures: - name = artifact_name(mode, role, variant) + for failure in failures: + name = artifact_name(role, failure) try: _gh( ["run", "download", run_id, "--repo", repo, "-n", name, "-D", str(dest)] diff --git a/cli/meta/ci/roles/runtime/logparse.py b/cli/meta/ci/roles/runtime/logparse.py index fe1e6db3dd..e0a1d7b393 100644 --- a/cli/meta/ci/roles/runtime/logparse.py +++ b/cli/meta/ci/roles/runtime/logparse.py @@ -4,6 +4,8 @@ import re from collections import defaultdict from pathlib import Path +from utils.ansible_log import LOG_PREFIX_RE + from .model import HOST_EXECUTED, HOST_FAILED, HOST_SKIPPED, RoleRuntime ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") @@ -125,7 +127,9 @@ def parse_log(log_path: str | Path) -> list[RoleRuntime]: current_role: str | None = None in_roles_recap = not has_sections for raw in text.splitlines(): - line = RUNNER_TS_RE.sub("", ANSI_RE.sub("", raw).rstrip()) + line = LOG_PREFIX_RE.sub( + "", RUNNER_TS_RE.sub("", ANSI_RE.sub("", raw).rstrip()) + ) marker = SEGMENT_RE.search(line) if marker: meta = ( diff --git a/cli/meta/ci/sequencing.py b/cli/meta/ci/sequencing.py deleted file mode 100644 index 2edff440a4..0000000000 --- a/cli/meta/ci/sequencing.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Decide whether a CI line deploys its modes in sequence or in parallel. - -Usage: - python -m cli.meta.ci.sequencing [--modes "swarm compose host"] - [--whitelist "..."] [--blacklist "..."] [--lifecycles "..."] - [--choice auto|serial|parallel] - -A *line* is the priority (⭐) or the regular (🔁) half of an orchestrator -run. Its job count is the sum of the deploy-matrix entries every active -mode contributes, counted on the row basis the discover steps use: swarm -selections are ``role#variant`` tokens mapping 1:1 onto jobs, compose and -host selections are whole roles whose variants pack into bundles -(utils.github.variant.bundles, the same packing the matrix runs). - -GitHub cancels a job that sat queued for 24 hours. A line that starts every -mode at once floods the runner pool, so the tail of its matrix waits past -that cut and dies unrun. ``auto`` therefore serialises the modes -- swarm, -then compose, then host, heaviest first -- once the line exceeds -``INFINITO_CI_SEQUENTIAL_THRESHOLD`` jobs, which restarts the queue clock -per mode. Below the threshold the modes run in parallel for wall-clock. - -The count omits the runner-storage filter scripts/meta/resolve/apps.sh -applies inside GitHub Actions, so it can only overestimate, erring towards -the sequential layout that cannot be cancelled. - -Writes ``jobs=`` and ``sequencing=``, ready to append to -``$GITHUB_OUTPUT``. -""" - -from __future__ import annotations - -import argparse -import os -import sys - -from cli.meta.ci.query import MODES, discover, expands_variants -from utils.cache.applications import get_variants -from utils.github.variant.bundles import compose_bundle_counts -from utils.roles.display import display_names - -CHOICES = ("auto", "serial", "parallel") - - -def mode_jobs(mode: str, *, whitelist: str, blacklist: str, lifecycles: str) -> int: - """Deploy-matrix jobs *mode* contributes to the line.""" - selection = discover( - mode, whitelist=whitelist, blacklist=blacklist, lifecycles=lifecycles - ) - if expands_variants(mode): - return len(selection) - return sum(compose_bundle_counts(selection, get_variants()).values()) - - -def line_jobs(modes: str, *, whitelist: str, blacklist: str, lifecycles: str) -> int: - return sum( - mode_jobs(mode, whitelist=whitelist, blacklist=blacklist, lifecycles=lifecycles) - for mode in MODES - if mode in modes.split() - ) - - -def threshold() -> int: - return int(os.environ["INFINITO_CI_SEQUENTIAL_THRESHOLD"]) - - -def decide(jobs: int | None, choice: str) -> str: - """``choice`` verbatim unless it is ``auto``, which compares *jobs* - against the threshold.""" - if choice != "auto": - return choice - return "serial" if jobs > threshold() else "parallel" - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - description="Decide serial or parallel deploy modes for one CI line." - ) - parser.add_argument("--modes", default=" ".join(MODES)) - parser.add_argument("--whitelist", default="") - parser.add_argument("--blacklist", default="") - parser.add_argument("--lifecycles", default="") - parser.add_argument("--choice", default="auto", choices=CHOICES) - args = parser.parse_args(argv) - - codec = display_names() - args.whitelist = codec.decode_list(args.whitelist) - args.blacklist = codec.decode_list(args.blacklist) - - if args.lifecycles.strip(): - os.environ["INFINITO_LIFECYCLES"] = args.lifecycles - - jobs = None - if args.choice == "auto": - jobs = line_jobs( - args.modes, - whitelist=args.whitelist, - blacklist=args.blacklist, - lifecycles=args.lifecycles, - ) - - print(f"jobs={'' if jobs is None else jobs}") - print(f"sequencing={decide(jobs, args.choice)}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/cli/meta/ci/slots.py b/cli/meta/ci/slots.py index b3fe49711b..ed4e3cb795 100644 --- a/cli/meta/ci/slots.py +++ b/cli/meta/ci/slots.py @@ -1,30 +1,41 @@ -"""Derive the deploy-matrix job slots per mode from the CI workflow chain. +"""Derive the deploy-chunk budget of one CI workflow run. Usage: - python -m cli.meta.ci.slots [--mode compose|swarm|host] [--matrix] [--format json] + python -m cli.meta.ci.slots [--matrix] [--format json] [--field ] -GitHub caps a workflow run's job matrix at 256 jobs -(INFINITO_CI_JOB_LIMIT). Every non-deploy job the orchestrator chain -spawns in the same run eats into that budget, so this module statically -and CONSERVATIVELY counts them: +A *chunk* is one serial block of deploy jobs in the orchestrator. Two +independent ceilings bound it, and the smaller one wins: -* every orchestrator job reserves its full job count -- reusable - workflows are opened and summed, static matrices multiplied out, - dynamic (``fromJson``) matrices estimated at - ``_DYNAMIC_MATRIX_ESTIMATE``; -* the deploy callers themselves reserve only their static jobs (the - discover steps); their dynamic per-app matrices are exactly the slots - being budgeted. +* **Queue clock.** GitHub cancels a job that sat queued for + ``INFINITO_CI_QUEUE_HOURS``. With ``INFINITO_CI_CONCURRENCY`` runners free + and every job assumed to burn its full ``timeout-minutes``, a chunk drains + in waves, and the last wave that still starts inside the queue window is + ``floor(queue_hours / job_timeout)``. A chunk therefore holds at most + ``concurrency * waves`` jobs. Assuming every job runs to its timeout is + deliberately pessimistic -- no job can outlast it -- so the drain estimate + can only overshoot, never undershoot. -The worst entry point (``entry-*.yml``) adds its own jobs to the same -run before calling the orchestrator; that overhead is subtracted too. +* **Run job cap.** GitHub caps a workflow run at ``INFINITO_CI_JOB_LIMIT`` + matrix jobs, counted across the whole run. Every non-deploy job the + orchestrator chain spawns eats into that budget, so this module statically + and CONSERVATIVELY counts them: -The remaining slots are split between the deploy matrices by the -``_SHARES`` weights (compose bundles variants and turns over fastest; -swarm jobs are the heaviest; host roles are few), with a floor of -``_MIN_MODE_SLOTS`` per mode because tiny budgets make the complexity -report emit an empty matrix. ``_SLOT_OVERRIDES`` pins a mode to a fixed -value and wins over every derived number. + - every orchestrator job reserves its full job count -- reusable workflows + are opened and summed, static matrices multiplied out, dynamic + (``fromJson``) matrices estimated at ``_DYNAMIC_MATRIX_ESTIMATE``; + - the chunk blocks themselves reserve only their static jobs (the discover + step); their dynamic per-row matrices are exactly the slots being + budgeted. + + The worst entry point (``entry-*.yml``) adds its own jobs to the same run + before calling the orchestrator; that overhead is subtracted too. + +What is left is :func:`available`, the rows one sweep can deploy. It is spent +by :func:`chunk_count` blocks of :func:`chunk_size` rows. Because the +orchestrator cannot generate a variable number of jobs, the block count is +also capped by ``INFINITO_CI_MAX_CHUNKS``, the number of chunk blocks the +workflow YAML actually declares; a sweep that would need more rows than those +blocks hold leaves the rest to the next sweep's offset. """ from __future__ import annotations @@ -32,37 +43,26 @@ from __future__ import annotations import argparse import json import math -import os import sys from typing import TYPE_CHECKING from utils.cache.files import PROJECT_ROOT from utils.cache.yaml import load_yaml_any +from utils.env.parser import env_setting if TYPE_CHECKING: from pathlib import Path -_SHARES = {"compose": 7, "swarm": 9, "host": 1} - -_SLOT_OVERRIDES: dict[str, int] = {} - -_DEPLOY_CALLERS = frozenset( - { - "test-deploy-single-node", - "test-deploy-single-node-priority", - "test-deploy-compose", - "test-deploy-compose-priority", - "test-deploy-host", - "test-deploy-host-priority", - "test-deploy-swarm", - "test-deploy-swarm-priority", - } -) - _ORCHESTRATOR = ".github/workflows/call-orchestrator.yml" +_DEPLOY_WORKFLOW = ".github/workflows/call-test-deploy.yml" +_DEPLOY_JOB = "deploy" +_CHUNK_JOB_PREFIX = "test-deploy-chunk-" _DYNAMIC_MATRIX_ESTIMATE = 5 -_DEFAULT_JOB_LIMIT = 256 -_MIN_MODE_SLOTS = 3 + + +def setting(key: str) -> int: + """One integer CI setting, read through the shared env SPOT.""" + return int(env_setting(key)) def _load_workflow(path: Path) -> dict: @@ -119,14 +119,43 @@ def _job_slots(repo_root: Path, job: dict, *, count_dynamic: bool) -> int: return _matrix_size(job) +def job_timeout_minutes(repo_root: Path | None = None) -> int: + """The deploy job's own ``timeout-minutes``, read straight out of the + workflow so the wave arithmetic cannot drift from the value CI enforces.""" + root = repo_root or PROJECT_ROOT + job = _jobs(_load_workflow(root / _DEPLOY_WORKFLOW)).get(_DEPLOY_JOB) or {} + timeout = job.get("timeout-minutes") + if not isinstance(timeout, int): + raise SystemExit( + f"{_DEPLOY_WORKFLOW}: job {_DEPLOY_JOB!r} declares no integer " + f"'timeout-minutes'; the chunk size is derived from it." + ) + return timeout + + +def waves(repo_root: Path | None = None) -> int: + """Runner waves that still start inside the queue window. Floored at 1: + a job timeout at or above the window means one wave, never zero.""" + window = setting("INFINITO_CI_QUEUE_HOURS") * 60 + return max(window // job_timeout_minutes(repo_root), 1) + + +def chunk_size(repo_root: Path | None = None) -> int: + """Rows one chunk may hold before its tail risks the queue cancel.""" + return setting("INFINITO_CI_CONCURRENCY") * waves(repo_root) + + def reserved_breakdown(repo_root: Path | None = None) -> list[tuple[str, int]]: """Per orchestrator job: the job count it reserves in the run budget. - Deploy callers contribute only their static jobs (the discover steps); - their dynamic per-app matrices are the budgeted slots themselves.""" + Chunk blocks contribute only their static jobs (the discover step); their + dynamic per-row matrices are the budgeted slots themselves.""" root = repo_root or PROJECT_ROOT jobs = _jobs(_load_workflow(root / _ORCHESTRATOR)) return [ - (name, _job_slots(root, job, count_dynamic=name not in _DEPLOY_CALLERS)) + ( + name, + _job_slots(root, job, count_dynamic=not name.startswith(_CHUNK_JOB_PREFIX)), + ) for name, job in jobs.items() ] @@ -155,65 +184,69 @@ def entry_overhead(repo_root: Path | None = None) -> int: return max(totals) -def mode_slots(repo_root: Path | None = None) -> dict[str, int]: - """Deploy slots per mode: (run job limit - reserved - worst entry - overhead) split by _SHARES, then pinned values from _SLOT_OVERRIDES.""" - limit = int(os.environ.get("INFINITO_CI_JOB_LIMIT") or _DEFAULT_JOB_LIMIT) - available = max( - limit - reserved_slots(repo_root) - entry_overhead(repo_root), len(_SHARES) - ) - total_shares = sum(_SHARES.values()) - slots = { - mode: max(available * share // total_shares, _MIN_MODE_SLOTS) - for mode, share in _SHARES.items() +def available(repo_root: Path | None = None) -> int: + """Deploy rows one run may spend across all its chunks.""" + limit = setting("INFINITO_CI_JOB_LIMIT") + return max(limit - reserved_slots(repo_root) - entry_overhead(repo_root), 1) + + +def chunk_count(repo_root: Path | None = None) -> int: + """Chunk blocks a sweep fills, capped by the blocks the YAML declares.""" + needed = math.ceil(available(repo_root) / chunk_size(repo_root)) + return max(min(needed, setting("INFINITO_CI_MAX_CHUNKS")), 1) + + +def rows_per_sweep(repo_root: Path | None = None) -> int: + """Rows one sweep covers: the chunk blocks it fills, bounded by the run + job cap. Rows beyond this roll into the next sweep via its offset.""" + return min(chunk_count(repo_root) * chunk_size(repo_root), available(repo_root)) + + +def budget(repo_root: Path | None = None) -> dict[str, int]: + return { + "reserved": reserved_slots(repo_root), + "entry_overhead": entry_overhead(repo_root), + "available": available(repo_root), + "job_timeout_minutes": job_timeout_minutes(repo_root), + "waves": waves(repo_root), + "chunk_size": chunk_size(repo_root), + "chunk_count": chunk_count(repo_root), + "rows_per_sweep": rows_per_sweep(repo_root), } - slots.update(_SLOT_OVERRIDES) - return slots def render_matrix() -> str: - """The budget as a CLI table: per-job reservations, then the totals - and the per-mode share split.""" + """The budget as a CLI table: per-job reservations, then the totals and + the chunk arithmetic they leave room for.""" breakdown = reserved_breakdown() - reserved = sum(count for _, count in breakdown) - overhead = entry_overhead() - limit = int(os.environ.get("INFINITO_CI_JOB_LIMIT") or _DEFAULT_JOB_LIMIT) - slots = mode_slots() - width = max( - len(name) - for name, _ in [ - *breakdown, - ("job limit (INFINITO_CI_JOB_LIMIT)", 0), - ("entry overhead (worst entry-*.yml)", 0), - ] - ) + rows = [ + *breakdown, + ("reserved", reserved_slots()), + ("entry overhead (worst entry-*.yml)", entry_overhead()), + ("job limit (INFINITO_CI_JOB_LIMIT)", setting("INFINITO_CI_JOB_LIMIT")), + ("available", available()), + ("concurrency (INFINITO_CI_CONCURRENCY)", setting("INFINITO_CI_CONCURRENCY")), + ("queue window (INFINITO_CI_QUEUE_HOURS)", setting("INFINITO_CI_QUEUE_HOURS")), + ("job timeout (minutes)", job_timeout_minutes()), + ("waves", waves()), + ("chunk size", chunk_size()), + ("chunk blocks (INFINITO_CI_MAX_CHUNKS)", setting("INFINITO_CI_MAX_CHUNKS")), + ("chunks filled", chunk_count()), + ("rows per sweep", rows_per_sweep()), + ] + width = max(len(name) for name, _ in rows) lines = [f"{'job':<{width}} jobs", f"{'-' * width} ----"] lines += [f"{name:<{width}} {count:>4}" for name, count in breakdown] - lines += [ - f"{'-' * width} ----", - f"{'reserved':<{width}} {reserved:>4}", - f"{'entry overhead (worst entry-*.yml)':<{width}} {overhead:>4}", - f"{'job limit (INFINITO_CI_JOB_LIMIT)':<{width}} {limit:>4}", - f"{'available':<{width}} {max(limit - reserved - overhead, len(_SHARES)):>4}", - f"{'-' * width} ----", - ] - lines += [ - f"{_mode_label(mode):<{width}} {slots[mode]:>4}" for mode in sorted(_SHARES) - ] + lines.append(f"{'-' * width} ----") + lines += [f"{name:<{width}} {count:>4}" for name, count in rows[len(breakdown) :]] return "\n".join(lines) -def _mode_label(mode: str) -> str: - if mode in _SLOT_OVERRIDES: - return f"{mode} (override)" - return f"{mode} (share {_SHARES[mode]})" - - def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( - description="Derive deploy-matrix job slots per mode from the CI chain." + description="Derive the deploy-chunk budget of one CI workflow run." ) - parser.add_argument("--mode", choices=sorted(_SHARES)) + parser.add_argument("--field", choices=sorted(budget())) parser.add_argument( "--matrix", action="store_true", @@ -225,15 +258,11 @@ def main(argv: list[str] | None = None) -> int: if args.matrix: print(render_matrix()) return 0 - slots = mode_slots() - if args.mode: - print(slots[args.mode]) + values = budget() + if args.field: + print(values[args.field]) return 0 - print( - json.dumps( - {"reserved": reserved_slots(), "entry_overhead": entry_overhead(), **slots} - ) - ) + print(json.dumps(values) if args.fmt == "json" else json.dumps(values, indent=2)) return 0 diff --git a/cli/meta/ci/validate.py b/cli/meta/ci/validate.py new file mode 100644 index 0000000000..d54d5f9b29 --- /dev/null +++ b/cli/meta/ci/validate.py @@ -0,0 +1,161 @@ +"""Check a run's selection inputs against the branch before anything deploys. + +Usage: + python -m cli.meta.ci.validate [--whitelist "..."] [--priority "..."] + [--modes auto] [--tor auto] [--distros "..."] [--filesystem "..."] + [--lifecycles "..."] + +A selection token names a row that has to exist *on this branch* +(:mod:`utils.github.variant.selection`). Nothing else in the chain can tell +the operator that early: the matrix builder raises on the first bad token, one +per chunk job, so a stale list costs one full CI round per entry and reports +the second problem only after the first is fixed. Every problem is collected +here instead, and the exit code gates the run. + +What makes a token bad, in the order this checks it: + +* it does not parse, or names a mode or onion state that does not exist; +* it names a role the discovery query does not return -- a typo, a role + outside the run's lifecycle envelope, or a role that no longer exists; +* it pins a variant the role does not declare (any more): the usual case is a + list carried over from an older run whose variants have since been renumbered; +* it pins a mode the row cannot take, an onion state the row, the mode or the + run's own tor axis rules out, or a distro or filesystem the run's own pool + does not hold. + +A bare role name that matches nothing is reported too, but as a warning: the +diff-derived whitelist legitimately names roles the envelope filters out. +""" + +from __future__ import annotations + +import argparse +import sys + +from cli.meta.ci import query +from utils.cache.applications import get_variants +from utils.github.variant import axes, pools, selection, tor +from utils.roles.display import display_names + + +def problems( + tokens: str, + *, + modes: tuple[str, ...], + tor_mode: str, + distros: tuple[str, ...], + filesystems: tuple[str, ...], + lifecycles: str, + label: str, +) -> tuple[list[str], list[str]]: + """Every reason the tokens of one input cannot deploy on this branch. + + Args: + tokens: the raw ``whitelist``/``priority`` value. + modes: the run's selected deploy modes. + tor_mode: the run's tor axis. + distros: the distro pool the run draws from. + filesystems: the filesystem pool the run draws from. + lifecycles: the run's lifecycle envelope. + label: the input's name, for the messages. + + Returns: + ``(errors, warnings)``. + """ + pins = selection.parse_list(display_names().decode_list(tokens)) + if not pins: + return [], [] + + rows = { + (row["name"], row["variant"]): query.row_modes(row, modes) + for row in query.discover_rows( + modes, whitelist=selection.names(pins), lifecycles=lifecycles + ) + } + declared = get_variants() + errors: list[str] = [] + warnings: list[str] = [] + for pin in pins: + token = selection.describe(pin) + variants = pin.variants or (None,) + for variant in variants: + offered = rows.get((pin.app, variant)) + if offered is None: + count = len(declared.get(pin.app) or []) + reason = ( + f"role declares {count} variant(s)" + if pin.variants + else "no row in this run's mode and lifecycle envelope" + ) + message = f"{label}: {token!r} matches no discovered row ({reason})" + (errors if pin.pinned else warnings).append(message) + continue + try: + axes.check_pins( + pin.app, + "" if variant is None else str(variant), + offered, + pin_mode=pin.mode, + pin_tor=pin.tor, + pin_distro=pin.distro, + pin_filesystem=pin.filesystem, + capable=tor.tor_capable(pin.app, variant, declared), + tor_mode=tor_mode, + distros=distros, + filesystems=filesystems, + ) + except SystemExit as refusal: + errors.append(f"{label}: {token!r} {str(refusal).split(': ', 1)[-1]}") + return errors, warnings + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Validate a run's selection inputs against this branch." + ) + parser.add_argument("--whitelist", default="") + parser.add_argument("--priority", default="") + parser.add_argument("--modes", default=query.ALL_MODES) + parser.add_argument("--tor", default=None) + parser.add_argument("--distros", default="") + parser.add_argument("--filesystem", default="") + parser.add_argument("--lifecycles", default="") + args = parser.parse_args(argv) + + modes = query.resolve_modes(args.modes) + tor_mode = tor.resolve_tor_mode(args.tor) + distros = pools.resolve_distros(args.distros) + filesystems = pools.resolve_filesystems(args.filesystem) + + errors: list[str] = [] + warnings: list[str] = [] + for label, tokens in (("whitelist", args.whitelist), ("priority", args.priority)): + found, warned = problems( + tokens, + modes=modes, + tor_mode=tor_mode, + distros=distros, + filesystems=filesystems, + lifecycles=args.lifecycles, + label=label, + ) + errors += found + warnings += warned + + for warning in warnings: + print(f"::warning::{warning}") + for error in errors: + print(f"::error::{error}", file=sys.stderr) + if errors: + print( + f"\n{len(errors)} unusable selection(s). Every one of them would abort a " + f"chunk's discovery, so the run is refused here instead.", + file=sys.stderr, + ) + return 1 + print("Selection inputs are valid for this branch.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/cli/meta/domains/__main__.py b/cli/meta/domains/__main__.py index ce5e287fb6..0ec97542ed 100755 --- a/cli/meta/domains/__main__.py +++ b/cli/meta/domains/__main__.py @@ -11,6 +11,7 @@ if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) import utils.domains.list as domain_list +from utils.domains.default_primary import default_domain_primary def parse_args(argv: list[str] | None = None) -> argparse.Namespace: @@ -19,7 +20,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: ) parser.add_argument( "--domain-primary", - default=os.environ.get("DOMAIN", "infinito.test"), + default=os.environ.get("DOMAIN") or default_domain_primary(), help="Value used for DOMAIN_PRIMARY rendering", ) parser.add_argument( diff --git a/cli/meta/j2/compiler/__init__.py b/cli/meta/j2/compiler/__init__.py index 5ddd444799..ab8b6632e5 100644 --- a/cli/meta/j2/compiler/__init__.py +++ b/cli/meta/j2/compiler/__init__.py @@ -12,8 +12,6 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 __all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 diff --git a/cli/meta/j2/compiler/__main__.py b/cli/meta/j2/compiler/__main__.py index a6979b40f5..18b2a0ac62 100755 --- a/cli/meta/j2/compiler/__main__.py +++ b/cli/meta/j2/compiler/__main__.py @@ -34,7 +34,6 @@ def expand_includes(rel_path, seen=None): output_lines.append(line.rstrip("\n")) else: indent, inc_rel = m.group(1), m.group(2) - # rekursiver Aufruf output_lines.extend( indent + inc_line for inc_line in expand_includes(inc_rel, seen) ) diff --git a/cli/meta/roles/applications/complexity/cli.py b/cli/meta/roles/applications/complexity/cli.py index cf1278f8d4..8d1ea4b3e9 100644 --- a/cli/meta/roles/applications/complexity/cli.py +++ b/cli/meta/roles/applications/complexity/cli.py @@ -13,6 +13,7 @@ from .filter import FilterError, compile_predicate from .model import ( TESTED_LIFECYCLES, ComplexityRow, + attach_siblings, compute_complexity_rows, compute_variant_complexity_rows, ) @@ -26,10 +27,8 @@ _SORT_KEYS = { "random": lambda r: r.random, "variant": lambda r: r.variant if r.variant is not None else -1, "variants": lambda r: r.variants, - "bundles": lambda r: r.bundles, "id": lambda r: r.id, "covered_by": lambda r: r.covered_by, - "jobs": lambda r: r.jobs, "lifecycle": lambda r: r.lifecycle, "compose": lambda r: int(r.compose), "swarm": lambda r: int(r.swarm), @@ -39,7 +38,6 @@ _SORT_KEYS = { "test_swarm": lambda r: int(r.test_swarm), "test_host": lambda r: int(r.test_host), "integrated": lambda r: int(r.integrated), - "tested_elsewhere": lambda r: int(r.test_compose or r.test_swarm), "clone": lambda r: int(r.clone), } @@ -58,7 +56,6 @@ def _row_fields(r: ComplexityRow) -> dict[str, Any]: "consumers_direct": r.consumers_direct, "weight": r.weight, "variants": r.variants, - "bundles": r.bundles, "id": r.id, "covered_by": r.covered_by, "variant": r.variant if r.variant is not None else -1, @@ -163,9 +160,8 @@ def build_parser() -> argparse.ArgumentParser: "role embeds), 'consumers' (roles that embed this one), " "'weight' (sum of direct + transitive in both directions), " "'name' (alphabetical), 'random' (the per-row nonce), 'variant' / " - "'variants' (the variant index / the role's variant count), " - "'bundles' (the role's compose bundle/job count), 'id', " - "'covered_by' and 'jobs' (assigned after the coverage pass, so " + "'variants' (the variant index / the role's variant count), 'id' " + "and 'covered_by' (assigned after the coverage pass, so " "sorting by them reorders within the ties of the more significant " f"keys). Default: {DEFAULT_SORT!r}." ), @@ -191,7 +187,7 @@ def build_parser() -> argparse.ArgumentParser: "combined with 'and' 'or' 'xor' 'not' and parentheses; set " "literals like {alpha,beta} are allowed. Fields: name, " "lifecycle, base, embeds, embeds_direct, consumers, " - "consumers_direct, weight, variants, bundles, id, covered_by, " + "consumers_direct, weight, variants, id, covered_by, " "variant, siblings, random, compose, swarm, stack. " "compose/swarm/stack are " "booleans (compare with ==true / ==false). 'stack' is True when the " @@ -205,17 +201,6 @@ def build_parser() -> argparse.ArgumentParser: "rows are filtered." ), ) - p.add_argument( - "--deploy-mode", - choices=("compose", "swarm", "host"), - default="compose", - help=( - "Deploy mode the 'bundles'/'jobs' columns count CI runners for " - "(whole-role mode only): 'compose' (default) packs variants into " - "size/storage bundles; 'swarm' counts one runner per deployable " - "variant. Drives the --max-jobs budget per mode." - ), - ) p.add_argument( "--lifecycles", nargs="+", @@ -230,20 +215,6 @@ def build_parser() -> argparse.ArgumentParser: f"built-in default ({' '.join(sorted(TESTED_LIFECYCLES))})." ), ) - p.add_argument( - "--max-jobs", - type=int, - default=None, - metavar="N", - help=( - "Hard-cut the output once the cumulative 'jobs' (running sum of " - "'bundles' down the sorted/filtered rows) reaches N: keep only the " - "leading rows whose cumulative job count stays below N. Use to cap " - "a CI run's total deploy jobs. Combine with a coverage-first sort " - "(e.g. 'asc covered_by, desc weight') to keep the highest-value " - "jobs under the budget." - ), - ) p.add_argument( "--no-group-names", action="store_true", @@ -346,9 +317,6 @@ def main(argv: list[str] | None = None) -> int: if args.level is not None and args.level < 1: p.error("--level/-L must be >= 1") - if args.max_jobs is not None and args.max_jobs < 1: - p.error("--max-jobs must be >= 1") - try: sort_spec = parse_sort_spec(args.sort) except ValueError as exc: @@ -373,30 +341,22 @@ def main(argv: list[str] | None = None) -> int: roles_dir, include_group_names=not args.no_group_names, max_level=args.level, - deploy_mode=args.deploy_mode, lifecycles=lifecycles, ) - _apply_sort(rows, sort_spec) - rows = _mark_covered(rows) - _apply_sort(rows, sort_spec) - if args.filter: try: predicate = compile_predicate(args.filter, FILTER_FIELDS) except FilterError as exc: p.error(f"--filter: {exc}") rows = [r for r in rows if predicate(_row_fields(r))] + rows = attach_siblings(rows) - numbered: list[ComplexityRow] = [] - running = 0 - for line, r in enumerate(rows, start=1): - running += r.bundles - numbered.append(r._replace(row=line, jobs=running)) - rows = numbered + _apply_sort(rows, sort_spec) + rows = _mark_covered(rows) + _apply_sort(rows, sort_spec) - if args.max_jobs is not None: - rows = [r for r in rows if r.jobs < args.max_jobs] + rows = [r._replace(row=line) for line, r in enumerate(rows, start=1)] if args.format == "json": rendered = render_json(rows) diff --git a/cli/meta/roles/applications/complexity/model.py b/cli/meta/roles/applications/complexity/model.py index 5cae153b7f..5ce71b6783 100644 --- a/cli/meta/roles/applications/complexity/model.py +++ b/cli/meta/roles/applications/complexity/model.py @@ -8,7 +8,7 @@ import subprocess from typing import TYPE_CHECKING, Any, NamedTuple from utils.cache.applications import get_variants -from utils.github.variant.bundles import compose_bundle_counts +from utils.env.parser import env_setting from utils.roles.lifecycle import tested_lifecycles from utils.roles.meta_lookup import ( MetaServicesShapeError, @@ -63,12 +63,7 @@ class ComplexityRow(NamedTuple): ``covered_by`` scrambles ``id``. ``variants`` is the number of ``meta/variants.yml`` variants of the role in whole-role mode; under ``--variant`` each row already is a single variant, so it is ``1``. - ``bundles`` is the number of CI jobs the row maps to in the target - ``deploy_mode``: compose and host pack variants into size/storage - bundles (``compose_bundle_counts`` SPOT), swarm runs one job per - variant; under ``--variant`` it is ``1`` per row (one variant = one - bundle). ``jobs`` is the - running sum of ``bundles`` down the rendered rows. ``lifecycle`` is the + ``lifecycle`` is the role's ``meta/services.yml`` lifecycle stage (alpha/beta/pre/…). ``compose`` / ``swarm`` are True when the CI test-deploy matrix exercises the role in that mode, honouring the discovery skip logic: invokable + @@ -110,8 +105,6 @@ class ComplexityRow(NamedTuple): covered_by: int = 0 row: int = -1 variants: int = 1 - bundles: int = 1 - jobs: int = 0 lifecycle: str = "" compose: bool = False swarm: bool = False @@ -125,6 +118,32 @@ class ComplexityRow(NamedTuple): clone: bool = False +def _tiebreaker(name: str, variant: int | None) -> int: + """The row's last-resort sort key, stable across processes when seeded. + + Discovery and the plan renderer run as separate processes, so a per-process + draw lets the rendered plan describe a different assignment than the one + deployed. ``INFINITO_DISCOVERY_SEED`` derives the key from the row's own + identity instead, which survives a different construction order and still + rotates the assignment whenever the seed changes. + + Args: + name: the role the row belongs to. + variant: its variant index, or None for a variant-free role. + + Returns: + A value in the same range the unseeded draw uses, so the sort spec + behaves identically either way. + """ + seed = env_setting("INFINITO_DISCOVERY_SEED") + if not seed: + return random.randint(100000, 999999) # noqa: S311 - sort tie-breaker, not cryptographic + digest = hashlib.sha1( + f"{seed}\n{name}\n{variant}".encode(), usedforsecurity=False + ).digest() + return 100000 + int.from_bytes(digest[:4], "big") % 900000 + + def _dna_hash(name: str, services: list[str]) -> str: members = sorted({name, *services}) return hashlib.sha1( @@ -132,7 +151,14 @@ def _dna_hash(name: str, services: list[str]) -> str: ).hexdigest() -def _attach_siblings(rows: list[ComplexityRow]) -> list[ComplexityRow]: +def attach_siblings(rows: list[ComplexityRow]) -> list[ComplexityRow]: + """Group *rows* by dna and elect the heaviest of each group the original, + marking the rest ``clone`` so the budget cut keeps one representative. + + Election is relative to the rows handed in, so a caller that filters MUST + call this again on the survivors: a stand-in the filter dropped is not + deployed, and the row deferring to it is cut in favour of nothing. + """ by_dna: dict[str, list[ComplexityRow]] = {} for row in rows: by_dna.setdefault(row.dna, []).append(row) @@ -209,7 +235,7 @@ def _build_row( weight=weight, dna=_dna_hash(name, services), siblings=[], - random=random.randint(100000, 999999), # noqa: S311 - sort tie-breaker, not cryptographic + random=_tiebreaker(name, variant), variant=variant, integrated=any(provider != name for provider in services_direct), ) @@ -246,7 +272,6 @@ def compute_complexity_rows( *, include_group_names: bool = True, max_level: int | None = None, - deploy_mode: str = "compose", lifecycles: set[str] | None = None, ) -> list[ComplexityRow]: tested = set(lifecycles) if lifecycles else set(TESTED_LIFECYCLES) @@ -258,10 +283,6 @@ def compute_complexity_rows( for role_dir in sorted(p for p in roles_dir.iterdir() if p.is_dir()) if is_application_role(role_dir) ] - if deploy_mode == "swarm": - bundles = {name: len(variants.get(name) or []) or 1 for name in names} - else: - bundles = compose_bundle_counts(names, variants, roles_dir=roles_dir) compose_apps = _tested_apps("compose", tested) swarm_apps = _tested_apps("swarm", tested) host_apps = _tested_apps("host", tested) @@ -281,7 +302,6 @@ def compute_complexity_rows( rows.append( _build_row(name, forward, reverse, max_level)._replace( variants=len(variants.get(name) or []) or 1, - bundles=bundles.get(name, 1), lifecycle=_role_lifecycle(variants.get(name)), compose=compose, swarm=swarm, @@ -293,7 +313,7 @@ def compute_complexity_rows( in_main=main_roles is None or name in main_roles, ) ) - return _attach_siblings(rows) + return attach_siblings(rows) def _variant_services_map(variant_config: Any) -> dict[str, Any]: @@ -363,4 +383,4 @@ def compute_variant_complexity_rows( test_host=host and "host" not in skips, ) ) - return _attach_siblings(rows) + return attach_siblings(rows) diff --git a/cli/meta/roles/applications/complexity/render.py b/cli/meta/roles/applications/complexity/render.py index 6ea5c50465..96c4702a55 100644 --- a/cli/meta/roles/applications/complexity/render.py +++ b/cli/meta/roles/applications/complexity/render.py @@ -62,8 +62,6 @@ _HEADER_NAMES = ( "variant", "integrated", "variants", - "bundles", - "jobs", "compose", "swarm", "stack", @@ -111,8 +109,6 @@ _COLUMN_DOC: dict[str, str] = { "variant": "meta/variants.yml index of this row", "integrated": "row's service map keeps at least one foreign service enabled", "variants": "number of variants the role has", - "bundles": "CI jobs this row maps to in the deploy mode", - "jobs": "running total of bundles down the rows", "compose": "exercised by the compose test-deploy matrix", "swarm": "exercised by the swarm test-deploy matrix", "stack": "ships its own container stack (compose template)", @@ -204,8 +200,6 @@ def render_table(rows: list[ComplexityRow], *, symbol: bool = False) -> str: ), ("integrated", ">", [_bool_cell(r.integrated, symbol=symbol) for r in rows]), ("variants", ">", [str(r.variants) for r in rows]), - ("bundles", ">", [str(r.bundles) for r in rows]), - ("jobs", ">", [str(r.jobs) for r in rows]), ("compose", ">", [_bool_cell(r.compose, symbol=symbol) for r in rows]), ("swarm", ">", [_bool_cell(r.swarm, symbol=symbol) for r in rows]), ("host", ">", [_bool_cell(r.host, symbol=symbol) for r in rows]), @@ -261,8 +255,6 @@ def _payload(rows: list[ComplexityRow]) -> list[dict]: "variant": r.variant, "integrated": r.integrated, "variants": r.variants, - "bundles": r.bundles, - "jobs": r.jobs, "compose": r.compose, "swarm": r.swarm, "host": r.host, diff --git a/cli/meta/roles/applications/dynamic_services.py b/cli/meta/roles/applications/dynamic_services.py new file mode 100644 index 0000000000..23e94f047a --- /dev/null +++ b/cli/meta/roles/applications/dynamic_services.py @@ -0,0 +1,72 @@ +"""Print the group-conditional service keys, comma-separated for ``disable=``. + +A service key is group-conditional when some role declares it with a Jinja +``enabled`` expression rather than a literal, i.e. the shape +``tests/integration/roles/meta/services/test_dynamic_flags.py`` enforces. +Those keys are the ones a test deploy may drop without changing what the +role under test is: their providers are co-deployed only because a host +happens to be in the provider's group. + +Keys without a provider role are omitted — ``disable=`` cannot act on them. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from cli.administration.inventory.provision.services_disabler import find_provider_roles +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + + +def dynamic_service_keys(roles_dir: Path) -> list[str]: + """Return every group-conditional service key that has a provider role.""" + keys: set[str] = set() + for role_dir in sorted(roles_dir.iterdir()): + if not role_dir.is_dir(): + continue + services = load_yaml_any( + str(role_dir / ROLE_FILE_META_SERVICES), default_if_missing={} + ) + if not isinstance(services, dict): + continue + for key, conf in services.items(): + if not isinstance(conf, dict): + continue + if any( + isinstance(conf.get(flag), str) and "{{" in conf[flag] + for flag in ("enabled", "shared") + ): + keys.add(str(key)) + if not keys: + return [] + providers = find_provider_roles(sorted(keys), roles_dir) + return sorted(k for k in keys if k in providers) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--roles-dir", + default="roles", + help="roles directory to scan (default: roles)", + ) + parser.add_argument( + "--exclude", + nargs="*", + default=[], + metavar="KEY", + help="service keys to keep enabled, e.g. the key the deploy is testing", + ) + args = parser.parse_args(sys.argv[1:] if argv is None else argv) + + excluded = {k for k in args.exclude if k} + keys = [k for k in dynamic_service_keys(Path(args.roles_dir)) if k not in excluded] + print(",".join(keys)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/meta/roles/applications/in_group_deps/__init__.py b/cli/meta/roles/applications/in_group_deps/__init__.py index a2dce83c31..604c9c9364 100644 --- a/cli/meta/roles/applications/in_group_deps/__init__.py +++ b/cli/meta/roles/applications/in_group_deps/__init__.py @@ -12,8 +12,6 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 __all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 diff --git a/cli/meta/roles/applications/resolution/combined/__init__.py b/cli/meta/roles/applications/resolution/combined/__init__.py index 242eed122d..9f69c70b47 100644 --- a/cli/meta/roles/applications/resolution/combined/__init__.py +++ b/cli/meta/roles/applications/resolution/combined/__init__.py @@ -1,5 +1,3 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] - -# Intentionally empty; executable via: python -m cli.meta.roles.applications.combined_resolution diff --git a/cli/meta/roles/applications/resolution/combined/role_introspection.py b/cli/meta/roles/applications/resolution/combined/role_introspection.py index dde7af7c72..8f97ce091f 100644 --- a/cli/meta/roles/applications/resolution/combined/role_introspection.py +++ b/cli/meta/roles/applications/resolution/combined/role_introspection.py @@ -109,15 +109,11 @@ def load_shared_service_roles_for_app( if not cfg_path.exists(): return [] services_map = load_yaml_file(cfg_path) - # Per the meta/services.yml file root IS the services map. - # resolve_direct_service_roles_from_config still expects the legacy - # `{"services": {...}}` envelope, so wrap accordingly. cfg = {"services": services_map} if isinstance(services_map, dict) else {} try: includes = resolve_direct_service_roles_from_config(cfg) except ServicesResolutionError as exc: - # Keep combined's error type for consistent UX raise CombinedResolutionError(str(exc)) from exc for r in includes: diff --git a/cli/meta/roles/applications/resolution/dependencies/__init__.py b/cli/meta/roles/applications/resolution/dependencies/__init__.py index 8c07980f2b..9f69c70b47 100644 --- a/cli/meta/roles/applications/resolution/dependencies/__init__.py +++ b/cli/meta/roles/applications/resolution/dependencies/__init__.py @@ -1,5 +1,3 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] - -# Intentionally empty; module is executable via -m. diff --git a/cli/meta/roles/applications/resolution/dependencies/__main__.py b/cli/meta/roles/applications/resolution/dependencies/__main__.py index 7c68228b4f..db4dbe3331 100755 --- a/cli/meta/roles/applications/resolution/dependencies/__main__.py +++ b/cli/meta/roles/applications/resolution/dependencies/__main__.py @@ -172,7 +172,6 @@ def resolve_dependencies_transitively(start_role: str) -> list[str]: stack.pop() - # Only include if it is an application role if node != start_role and has_application_id(node): out.append(node) diff --git a/cli/meta/roles/applications/resolution/run_after/__main__.py b/cli/meta/roles/applications/resolution/run_after/__main__.py index b2f2847bfd..2165879274 100755 --- a/cli/meta/roles/applications/resolution/run_after/__main__.py +++ b/cli/meta/roles/applications/resolution/run_after/__main__.py @@ -68,12 +68,10 @@ def resolve_run_after_transitively(start_role: str) -> list[str]: f"Unknown role: {start_role!r} (missing folder {rdir / start_role})" ) - # Cache run_after lists per role for speed and consistent error reporting cache: dict[str, list[str]] = {} def ra(role: str) -> list[str]: if role not in cache: - # Validate role existence when it is referenced if not (rdir / role).is_dir(): raise RunAfterResolutionError( f"Invalid run_after reference: {role!r} (missing folder {rdir / role})" @@ -87,7 +85,6 @@ def resolve_run_after_transitively(start_role: str) -> list[str]: def dfs(node: str) -> None: if node in stack: - # Cycle: show a readable path: A -> B -> C -> A idx = stack.index(node) cycle = [*stack[idx:], node] raise RunAfterResolutionError( @@ -105,7 +102,6 @@ def resolve_run_after_transitively(start_role: str) -> list[str]: stack.pop() - # Post-order append yields a valid prerequisites-first ordering. if node != start_role: out.append(node) diff --git a/cli/meta/roles/applications/role_name/__init__.py b/cli/meta/roles/applications/role_name/__init__.py index ee8c3b4b10..846c994817 100644 --- a/cli/meta/roles/applications/role_name/__init__.py +++ b/cli/meta/roles/applications/role_name/__init__.py @@ -12,8 +12,6 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. from . import __main__ as _main # noqa: E402 __all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 diff --git a/cli/meta/roles/applications/sufficient_storage/__main__.py b/cli/meta/roles/applications/sufficient_storage/__main__.py index dbcd682985..9083cb82e6 100755 --- a/cli/meta/roles/applications/sufficient_storage/__main__.py +++ b/cli/meta/roles/applications/sufficient_storage/__main__.py @@ -5,7 +5,6 @@ import argparse import json import sys -# Ensure repo root is in PYTHONPATH from . import PROJECT_ROOT sys.path.insert(0, str(PROJECT_ROOT)) @@ -60,11 +59,9 @@ def main() -> int: ) if args.format == "json": - # Always output valid JSON print(json.dumps(matching, indent=2)) return 0 - # text: one role per line (robust for shell pipelines) for role in matching: print(role) diff --git a/cli/meta/roles/lifecycle/__main__.py b/cli/meta/roles/lifecycle/__main__.py index 5d405e45ee..dbfaf0cbc3 100644 --- a/cli/meta/roles/lifecycle/__main__.py +++ b/cli/meta/roles/lifecycle/__main__.py @@ -37,14 +37,13 @@ def filter_roles( try: lifecycle_value = get_role_lifecycle(role_dir, role_name=role_name) except Exception: - # Best-effort: never fail discovery on a single broken role. lifecycle_value = None lifecycle = (lifecycle_value or "").strip().lower() if mode == "whitelist": if lifecycle in statuses: matched.append(role_name) - else: # blacklist + else: if lifecycle == "": if include_missing_lifecycle_on_blacklist: matched.append(role_name) @@ -127,7 +126,6 @@ def main(argv: list[str] | None = None) -> int: print(str(exc), file=sys.stderr) return 1 - # Output: role names separated by whitespaces sys.stdout.write(" ".join(role_names) + "\n") return 0 diff --git a/cli/meta/roles/mapping/__main__.py b/cli/meta/roles/mapping/__main__.py index 98bdc7c042..cbb59f0541 100644 --- a/cli/meta/roles/mapping/__main__.py +++ b/cli/meta/roles/mapping/__main__.py @@ -335,7 +335,6 @@ def main(argv: list[str] | None = None) -> int: sys.stdout.write("\n") return 0 - # text if args.command == "files": _print_lines(_render_files_text(args.role_type)) elif args.command == "types": diff --git a/cli/meta/roles/order/README.md b/cli/meta/roles/order/README.md index b4d9b505e4..7ee4995cd4 100644 --- a/cli/meta/roles/order/README.md +++ b/cli/meta/roles/order/README.md @@ -1,3 +1,3 @@ # Order 📜 -Show role execution order from both scheduling layers: `run` prints the group-file call order of the main pass (`tasks/groups/*.yml`), `preload` prints the sys-service-loader preload order (run_after topological sort over the service registry). +Show role execution order from both scheduling layers: `run` prints the group call order of the main pass, `preload` prints the sys-service-loader preload order (run_after topological sort over the service registry). diff --git a/cli/meta/roles/services/called/__init__.py b/cli/meta/roles/services/called/__init__.py index d13cf1f6b8..4cb12795c5 100644 --- a/cli/meta/roles/services/called/__init__.py +++ b/cli/meta/roles/services/called/__init__.py @@ -45,6 +45,7 @@ import subprocess import sys from pathlib import Path +from utils.ansible_log import LOG_PREFIX_RE from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_SERVICES @@ -53,10 +54,6 @@ _NON_SKIP_RE = re.compile( r"^\s*(?:ok|changed|fatal|included):\s+", re.MULTILINE, ) -_LOG_PREFIX_RE = re.compile( - r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d,\d+ p=\d+ u=\S+ n=\S+ \w+\| ", - re.MULTILINE, -) def categories_of(role_id: str) -> set[str]: @@ -204,7 +201,7 @@ def _role_body_executed(log_content: str, role_id: str) -> bool: `skipping:` status line, so a header alone is insufficient evidence that the role's body ran — we must see at least one non-skip outcome. """ - clean = _LOG_PREFIX_RE.sub("", _ANSI_RE.sub("", log_content)) + clean = LOG_PREFIX_RE.sub("", _ANSI_RE.sub("", log_content)) marker = f"TASK [{role_id} :" pos = 0 while True: diff --git a/cli/meta/runtime/__init__.py b/cli/meta/runtime/__init__.py index 63734fabab..105048b62c 100644 --- a/cli/meta/runtime/__init__.py +++ b/cli/meta/runtime/__init__.py @@ -24,21 +24,17 @@ def detect_runtime() -> str: 3) github 4) host """ - # 1) explicit override wins v = (os.getenv("RUNTIME") or "").strip() if v: return v - # 2) act (must be before GitHub) if os.getenv("ACT") == "true" or os.getenv("ACT_RUNNER"): return "act" - # 3) GitHub Actions if ( os.getenv("GITHUB_ACTIONS") == "true" or os.getenv("INFINITO_RUNNING_ON_GITHUB") == "true" ): return "github" - # 4) default return "host" diff --git a/compose.yml b/compose.yml index f0210bf42a..778ee135b5 100644 --- a/compose.yml +++ b/compose.yml @@ -83,8 +83,11 @@ services: INFINITO_MAIL_PRODUCTION_HOST: ${INFINITO_MAIL_PRODUCTION_HOST} INFINITO_MAIL_PRODUCTION_RESOLVER: ${INFINITO_MAIL_PRODUCTION_RESOLVER} INFINITO_PLAYWRIGHT_KEEP: ${INFINITO_PLAYWRIGHT_KEEP} + INFINITO_PLAYWRIGHT_REPORTS_BASE_DIR: ${INFINITO_PLAYWRIGHT_REPORTS_BASE_DIR} + INFINITO_PLAYWRIGHT_STAGE_BASE_DIR: ${INFINITO_PLAYWRIGHT_STAGE_BASE_DIR} INFINITO_SRC_DIR: ${INFINITO_SRC_DIR} INFINITO_SWARM_MGR_IP: ${INFINITO_SWARM_MGR_IP} + INFINITO_TOR_SOCKS_PORT: ${INFINITO_TOR_SOCKS_PORT} PYTHONHTTPSVERIFY: "1" GIT_SSL_NO_VERIFY: "0" diff --git a/compose/package-cache-frontend/cert-gen.sh b/compose/package-cache-frontend/cert-gen.sh index 318c50fdb2..0ca2f501fc 100755 --- a/compose/package-cache-frontend/cert-gen.sh +++ b/compose/package-cache-frontend/cert-gen.sh @@ -65,7 +65,6 @@ ensure_leaf() { key="/certs/${hostname}.key" if cert_still_valid "${crt}" && [ -s "${key}" ]; then - # Reject leaf if it no longer chains to the current CA. if openssl verify -CAfile "${CA_CRT}" "${crt}" >/dev/null 2>&1; then return 0 fi @@ -76,7 +75,6 @@ ensure_leaf() { openssl genrsa -out "${key}" 2048 >/dev/null 2>&1 chmod 0600 "${key}" - # Modern TLS clients require SAN; CN-as-host is no longer honoured. extfile="$(mktemp)" { printf 'subjectAltName = DNS:%s\n' "${hostname}" diff --git a/compose/swarm/playbook.yml b/compose/swarm/playbook.yml index 4058195301..f1d3f0431a 100644 --- a/compose/swarm/playbook.yml +++ b/compose/swarm/playbook.yml @@ -23,6 +23,7 @@ lab_export_base: "{{ lookup('env', 'NFS_EXPORT_BASE') }}" lab_node_src: "{{ lookup('env', 'INFINITO_NODE_SRC_DIR') }}" lab_runner_temp: "{{ lookup('env', 'RUNNER_TEMP') }}" + lab_sampler_log: "{{ lookup('env', 'INFINITO_DNS53_SAMPLER_LOG') }}" lab_systemd_timeout: "{{ lookup('env', 'SWARM_PILOT_SYSTEMD_TIMEOUT') | default('180', true) }}" lab_is_mgr: "{{ inventory_hostname == lab_mgr }}" lab_is_worker: "{{ inventory_hostname in [lab_wrk1, lab_wrk2] }}" @@ -188,3 +189,14 @@ src: "{{ lab_runner_temp }}/infinito-src.tar" dest: "{{ lab_node_src }}" timeout: 300 + + - name: sample what the resolver answers, not just whether it listens + shell: | + set -eu + sampler={{ lab_node_src }}/scripts/tests/deploy/ci/dns53-sampler.sh + INFINITO_DNS53_SAMPLER_LOG={{ lab_sampler_log }} \ + setsid sh "${sampler}" /dev/null 2>&1 & + args: + creates: "{{ lab_sampler_log }}" + timeout: 30 + when: lab_dns_node diff --git a/compose/swarm/templates/dnsmasq.conf.j2 b/compose/swarm/templates/dnsmasq.conf.j2 index f5340d8434..ef198a34b5 100644 --- a/compose/swarm/templates/dnsmasq.conf.j2 +++ b/compose/swarm/templates/dnsmasq.conf.j2 @@ -4,3 +4,4 @@ server=/{{ lab_mgr }}/{{ lab_wrk1 }}/{{ lab_wrk2 }}/{{ lab_nfs }}/{{ NETWORK_DOC server={{ resolver }} {% endfor %} address=/{{ lab_domain }}/{{ lab_domain_target }} +local=/{{ lab_domain }}/ diff --git a/composer.json b/composer.json new file mode 100644 index 0000000000..f18dac2f6e --- /dev/null +++ b/composer.json @@ -0,0 +1,15 @@ +{ + "name": "infinito-nexus/core", + "description": "PHPUnit dependencies for the PHP shipped in roles/*/files/php/.", + "type": "project", + "license": "MIT", + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "config": { + "sort-packages": true + }, + "scripts": { + "test": "phpunit" + } +} diff --git a/default.env b/default.env index 31c19bfdca..e8aa256d8d 100644 --- a/default.env +++ b/default.env @@ -82,14 +82,32 @@ INFINITO_CACHE_REGISTRY_IP=172.30.0.6 # Bind-mounted registry-cache proxy configuration consumed by the cache container. INFINITO_CACHE_REGISTRY_PROXY_CONF=./compose/registry-cache/proxy.conf +# True where a persistent pull-through cache stack pays off (local dev). +INFINITO_CACHE_STACK=true + +# Index of the deploy chunk the discovery emits; each chunk block of call-orchestrator.yml passes its own. +INFINITO_CI_CHUNK=0 + +# Runner slots a deploy chunk may assume are free; with the job timeout it sizes a chunk in cli.meta.ci.slots. +INFINITO_CI_CONCURRENCY=20 + # Budget distros.sh spends before skipping the rest; stays under the 350-min step cap, which stays under the 355-min job cap. INFINITO_CI_DISTRO_BUDGET_SECONDS=20400 -# Job budget per workflow run cli.meta.ci.slots divides between the deploy matrices (GitHub matrix cap: 256). +# Job budget per workflow run cli.meta.ci.slots spends on the deploy chunks (GitHub matrix cap: 256). INFINITO_CI_JOB_LIMIT=256 -# Deploy jobs a CI line may queue at once before cli.meta.ci.sequencing serialises its modes (GitHub cancels a job queued for 24h). -INFINITO_CI_SEQUENTIAL_THRESHOLD=65 +# Chunk job blocks call-orchestrator.yml declares; cli.meta.ci.slots must never plan more than these exist in the YAML. +INFINITO_CI_MAX_CHUNKS=3 + +# Regular rows a run skips before filling its chunks; a count or a selection token, 0 starts at the head of the ranking. +INFINITO_CI_OFFSET=0 + +# Hours a job may sit queued before GitHub cancels it; the ceiling a single chunk's waves must start within. +INFINITO_CI_QUEUE_HOURS=24 + +# Sweep number driving the deploy mode/tor rotation; CI passes the run number. +INFINITO_CI_SWEEP=0 # Compose service container name; generator overrides as infinito_nexus_${INFINITO_DISTRO}. INFINITO_CONTAINER=infinito_nexus_debian @@ -106,8 +124,11 @@ INFINITO_DEBUG=true # Deploy mode the discovery matrix targets (compose|swarm) for per-mode services.yml skip; empty disables it. INFINITO_DEPLOY_MODE= -# Sort spec the CI app-discovery (scripts/meta/resolve/apps.sh) orders roles by before the --max-jobs budget cut. -INFINITO_DISCOVERY_SORT="desc integrated,asc covered_by,desc embeds,desc consumers,asc variant,asc random" +# Seed the discovery sort's tie-breaker derives from; empty draws it per process, so the rendered plan can differ from the deploy. +INFINITO_DISCOVERY_SEED= + +# Sort spec the CI app-discovery (scripts/meta/resolve/apps.sh) orders roles by; the order decides which rows a chunk takes first. +INFINITO_DISCOVERY_SORT="asc clone,asc covered_by,desc integrated,desc embeds,desc consumers,asc variant,asc random" # Distro the build/test matrix is currently iterating over (generator may override). INFINITO_DISTRO=debian @@ -122,15 +143,21 @@ INFINITO_DNS_HOSTS_FILE=/etc/hosts INFINITO_DNS_IP=172.30.0.53 # Repo-relative path of the docker CLI install script. -INFINITO_DOCKER_CLI_INSTALL_SCRIPT=roles/sys-svc-container/files/install-cli.sh +INFINITO_DOCKER_CLI_INSTALL_SCRIPT=roles/sys-svc-container/files/shell/install-cli.sh -# Filesystem the docker data root runs on; empty until the per-distro draw in scripts/tests/deploy/utils/filesystem/resolve.sh fills it. +# Filesystem the docker data root runs on; empty until scripts/tests/deploy/utils/filesystem/resolve.sh settles the row's kind. INFINITO_DOCKER_FILESYSTEM= -# Space-separated subset of ext4/btrfs/zfs the per-distro draw may use; empty draws from all three. +# Space-separated subset of ext4/btrfs/zfs the pick may use; empty draws from all three. INFINITO_DOCKER_FILESYSTEM_ALLOWED= -# `true` when INFINITO_DOCKER_FILESYSTEM_ALLOWED narrowed the draw; a host that cannot deliver the pick then fails instead of declining. +# `true` when a human named the pick, so it binds: a host that cannot deliver it fails instead of falling back. +INFINITO_DOCKER_FILESYSTEM_ENFORCED= + +# The filesystem the deploy matrix assigned one row; empty draws from INFINITO_DOCKER_FILESYSTEM_ALLOWED. +INFINITO_DOCKER_FILESYSTEM_PICK= + +# `true` when the pick binds, because a human named it or nothing permitted is servable; the applying step then fails instead of declining. INFINITO_DOCKER_FILESYSTEM_REQUIRED= # Mount point inside the infinito container where INFINITO_DOCKER_VOLUME lands. @@ -160,15 +187,15 @@ INFINITO_GHCR_MIRROR_PREFIX=mirror # Shared .git directory a worktree checkout points at; empty on the primary instance, which carries its own. INFINITO_GIT_COMMON_DIR= -# Run-context flag like INFINITO_DEPLOY_MODE: the single-node workflow sets 'true' so host discovery drops compose-covered roles. -INFINITO_HOST_EXCLUDE_COMPOSE= - # Image tag used to address the published infinito image (CI publishes 'latest' on push). INFINITO_IMAGE_TAG=latest # Slot index isolating a parallel checkout: 0 owns the cache stack, 1..255 shift subnet, bind IP and container names. INFINITO_INSTANCE=0 +# Repo-relative path of the PHP/Ruby unit-suite toolchain install script. +INFINITO_INTERPRETERS_INSTALL_SCRIPT=scripts/install/interpreters.sh + # Optional JSON object merged into the generated dev-inventory vars. INFINITO_INVENTORY_EXTRA_VARS= @@ -202,8 +229,6 @@ INFINITO_MAIL_PRODUCTION_HOST= # Resolver the production mail-facts check queries (e.g. 1.1.1.1 for the public view); empty uses /etc/resolv.conf. INFINITO_MAIL_PRODUCTION_RESOLVER= -# CI job budget the app-discovery hard-caps at (apps.sh --max-jobs); 'auto' derives it per mode via cli.meta.ci.slots. -INFINITO_MAX_JOBS=auto # memswap_limit cap applied to the infinito container; 0 means "unlimited". INFINITO_MEMSWAP_LIMIT=0 @@ -211,6 +236,9 @@ INFINITO_MEMSWAP_LIMIT=0 # mem_limit cap applied to the infinito container; 0 means "unlimited". INFINITO_MEM_LIMIT=0 +# Deploy modes CI rows may be drawn from: 'auto' for every mode a role offers, or a subset of 'host compose swarm'. +INFINITO_MODES=auto + # Repo checkout path on act-swarm DinD test nodes. INFINITO_NODE_SRC_DIR=/opt/infinito-nexus @@ -235,6 +263,9 @@ INFINITO_PLAYWRIGHT_KEEP=false # When `true`, the CI down-handler skips wiping the Docker volume so layer cache survives across jobs. INFINITO_PRESERVE_DOCKER_CACHE=false +# App ids leading the CI deploy list; they get chunks of their own ahead of the regular rows. +INFINITO_PRIORITY= + # When `false`, the dev-stack container publishes no host ports (nested runner deploys share the outer daemon via DooD). INFINITO_PUBLISH_PORTS=true @@ -242,7 +273,7 @@ INFINITO_PUBLISH_PORTS=true INFINITO_PULL_POLICY=never # Repo-relative path of the system python install script. -INFINITO_PYTHON_INSTALL_SCRIPT=roles/dev-python/files/install.sh +INFINITO_PYTHON_INSTALL_SCRIPT=roles/dev-python/files/shell/install.sh # The compose deploy runs the recover drill between PASS 1 and PASS 2 (backup/recover verification); set `false` to skip. INFINITO_RECOVER_DRILL=true @@ -340,6 +371,12 @@ INFINITO_TEST_RUNNER=docker # Integer multiplier applied to Ansible retry/delay values on slow self-hosted hardware; 1 = no scaling. INFINITO_TIMEOUT_MULTIPLIER=1 +# Tor axis of the CI deploy matrix: auto | enforced | exclusive | disabled. exclusive also drops the variants that cannot take an onion. +INFINITO_TOR=auto + +# Node Tor SOCKS port; set by the env handler from svc-net-tor services.tor.ports.local.socks (SPOT). +INFINITO_TOR_SOCKS_PORT= + # Variant overlay (applications. services/credentials) baked per round by the swarm matrix orchestrator; empty elsewhere. INFINITO_VARS_PAYLOAD= @@ -354,3 +391,6 @@ INFINITO_WHITELIST= # Master toggle for the worker SPOT chain (INFINITO_WORKER_CPU / _FETCH); falsy values: 0/false/no/off. INFINITO_WORKER_ENABLED=true + +# Track directories scripts/tests/workspace/00_orchestrator.sh runs, in the order given. +INFINITO_WORKSPACE_TRACKS=base compose swarm diff --git a/docs/administration/ci-runners.md b/docs/administration/ci-runners.md index c72ff87512..045c32bd79 100644 --- a/docs/administration/ci-runners.md +++ b/docs/administration/ci-runners.md @@ -10,7 +10,7 @@ Every push runs the same gate you can run locally: make test # lint + unit + integration + external ``` -On GitHub Actions this is followed by the **deploy-test matrix** — real app deploys across Debian/Ubuntu/Arch/Fedora in throwaway containers, with Playwright/CLI end-to-end checks (`.github/workflows/call-test-deploy-*.yml`). This is the heavy part and the reason self-hosted runners exist. +On GitHub Actions this is followed by the **deploy-test matrix** — real app deploys across Debian/Ubuntu/Arch/Fedora in throwaway containers, with Playwright/CLI end-to-end checks (`.github/workflows/call-test-deploy.yml`). This is the heavy part and the reason self-hosted runners exist. ## Self-hosted runners (opt-in overflow) diff --git a/docs/administration/installation.md b/docs/administration/installation.md index 24df53fe7d..c9d0776970 100644 --- a/docs/administration/installation.md +++ b/docs/administration/installation.md @@ -27,7 +27,7 @@ This prepares the repository for local development. `make environment-bootstrap` also installs the repository's local `pre-commit` hooks for this checkout. All available `make` commands are documented in the [Makefile Commands](../contributing/tools/make.md) reference. -For a worked example of how these commands interact (including build, bootstrap, test, deploy, and teardown), see the [environment test suite](../../scripts/tests/environment/README.md). +For a worked example of how these commands interact (including build, bootstrap, test, deploy, and teardown), see the [environment test suite](../../scripts/tests/workspace/README.md). For further information on setting up a local development environment, see [CONTRIBUTING.md](../../CONTRIBUTING.md). For inventory creation and deployment, continue with the [Deploy Guide](deploy.md). diff --git a/docs/agents/action/iteration/runner.md b/docs/agents/action/iteration/runner.md index e3a38b1350..077e9caf5b 100644 --- a/docs/agents/action/iteration/runner.md +++ b/docs/agents/action/iteration/runner.md @@ -17,14 +17,14 @@ Key facts an agent must hold before acting: - `RUNNER_GITHUB_OWNER` and `RUNNER_GITHUB_REPO` resolve from `GITHUB_REPOSITORY_OWNER` / `GITHUB_REPOSITORY` env vars when set (CI context), falling back to `meta/services.yml` for production deploys. - `GH_TOKEN` must be available on the Ansible control node (`delegate_to: localhost`) for the `gh api` registration call to succeed. In CI this is forwarded into the DinD container by `cli/administration/deploy/development/deploy/run.py`. -- The systemd services installed by `svc.sh` require a host with a real init system. Registration, service install, and service start are skipped when `DOCKER_IN_CONTAINER=true`; the role can be fully deployed in DinD (binary extraction and `.env` file work). The nested `deploy-fresh-purged-apps` call in `test.sh` is also skipped when `DOCKER_IN_CONTAINER=true` — in DinD, `make up` does not start the package-cache proxy (`registry_cache_active()` returns false in CI), so apt inside the fresh container cannot resolve the proxy hostname and package installs fail. Structural checks (binary + `.env`) are sufficient proof of a correct deploy in DinD; the full end-to-end deploy only runs on a real host. +- The systemd services installed by `svc.sh` require a host with a real init system. Registration, service install, and service start are skipped when `DOCKER_IN_CONTAINER=true`; the role can be fully deployed in DinD (binary extraction and `.env` file work). The nested `deploy-fresh-purged-apps` call in `test.sh` is also skipped when `DOCKER_IN_CONTAINER=true` — in DinD, `make up` does not start the package-cache proxy (`cache_stack_enabled()` returns false in CI), so apt inside the fresh container cannot resolve the proxy hostname and package installs fail. Structural checks (binary + `.env`) are sufficient proof of a correct deploy in DinD; the full end-to-end deploy only runs on a real host. - `runner_count` defaults to `ansible_processor_vcpus // runner_cpus` (auto-scaled to hardware). Override explicitly when debugging a specific count. ## The loop - You MUST NOT register runners against `infinito-nexus/core` from fork CI — the `GITHUB_TOKEN` there lacks organisation-level `administration` scope. The env-var override in `vars/main.yml` handles this automatically. - When iterating on the role tasks, deploy to a real Debian, Ubuntu, Arch Linux, or Fedora/EL host, or a systemd-enabled container. Running against the standard DinD test image will fail at the `svc.sh install` step. -- The `test-e2e-cli` framework runs `files/test.sh` sourcing variables from `templates/test.env.j2` after each deploy cycle. Check both the deploy output and the CLI test output before declaring a fix complete. +- The `test-e2e-cli` framework runs `files/test/test.sh` sourcing variables from `templates/test.env.j2` after each deploy cycle. Check both the deploy output and the CLI test output before declaring a fix complete. - When bumping `runner_count`, re-run the full deploy cycle so `test.sh` can run its end-to-end app deploy against the updated runner environment. - `runner_docker_base` defaults to `/mnt/docker`. Override via inventory `host_vars` for non-standard machines. @@ -34,7 +34,7 @@ Iteration steps: 2. Run `make test` — all linting and unit tests must pass before deploy. 3. Deploy to the target host via the standard role deploy path. 4. Inspect systemd service status: `systemctl is-active actions.runner.*`. -5. Check `files/test.sh` output from the `test-e2e-cli` run in the deploy log. +5. Check `files/test/test.sh` output from the `test-e2e-cli` run in the deploy log. 6. If the runner registered correctly, verify it appears in the GitHub repository's runner list. ## Recovery & gotchas diff --git a/docs/agents/action/iteration/workflow.md b/docs/agents/action/iteration/workflow.md index 56a9b2a486..49d6bbca62 100644 --- a/docs/agents/action/iteration/workflow.md +++ b/docs/agents/action/iteration/workflow.md @@ -27,3 +27,13 @@ For the swarm deploy loop, see [Swarm Loop](swarm.md). `make act-*` aborts with `failed to copy content to container: mkdirat var/run...` because the stock runner image's `/var/run` symlink trips Docker 28/29's stricter `docker cp`. Fix: run `make act-runner-image` once, then prefix any act target with `ACT_PLATFORM_IMAGE=local/act-runner-fixed:latest` (e.g. `ACT_PLATFORM_IMAGE=local/act-runner-fixed:latest make swarm-zombie app=`). + +### A green local workspace run does not clear CI + +Two properties of the workspace suite differ between `make act-workflow` and a GitHub runner, so a class of defects is structurally invisible locally. + +**Nested Docker state does not survive a teardown locally, but does in CI.** `INFINITO_DOCKER_VOLUME` is the named volume `docker` ([default.env](../../../../default.env)) and a host path (`/mnt/docker`) on GitHub. `compose down -v` removes a named volume and cannot remove a bind mount, so every workspace track starts on a clean inner daemon locally while CI carries the previous track's containers into the next one. Defects that need a container, network, or bind source to outlive a teardown cannot reproduce under act. + +**The runtime identity differs.** act sets `ACT=true`, so `detect_gha_act()` in [runtime.py](../../../../utils/env/runtime.py) resolves `INFINITO_RUNNING_ON_GITHUB=false` where a real runner resolves `true`. Anything keyed off that fact behaves differently, and act cannot prove a fix to it either way. + +Run the local loop to iterate quickly; treat CI as the only authority for both classes. diff --git a/docs/agents/files/group_vars/applications.md b/docs/agents/files/group_vars/applications.md index b1fbd59354..4b03a604ba 100644 --- a/docs/agents/files/group_vars/applications.md +++ b/docs/agents/files/group_vars/applications.md @@ -4,7 +4,7 @@ This page describes how agents handle application defaults after the removal of ## Rules -- Application defaults are discovered directly from each role's per-topic meta files: `roles/*/meta/services.yml`, `roles/*/meta/server.yml`, `roles/*/meta/rbac.yml`, `roles/*/meta/volumes.yml`, plus `roles/*/meta/schema.yml` (post-`apply_schema()`). Variants in `roles/*/meta/variants.yml` deep-merge over the assembled per-role payload. See [layout.md](../../../contributing/design/role/services/layout.md). +- Application defaults are discovered directly from each role's per-topic meta files: `roles/*/meta/services.yml`, `roles/*/meta/server.yml`, `roles/*/meta/rbac.yml`, `roles/*/meta/volumes.yml`, plus `roles/*/meta/secrets.yml` (post-`apply_schema()`). Variants in `roles/*/meta/variants.yml` deep-merge over the assembled per-role payload. See [layout.md](../../../contributing/design/role/services/layout.md). - Agents MUST edit role-local meta sources, not recreate repository-wide generated application dictionaries. - Runtime consumers MUST access merged application data via `lookup('applications')` or a wrapper built on top of it. - Inventory overrides still belong in the normal `applications` variable path under inventories, group vars, host vars, or role vars. diff --git a/docs/agents/files/role/javascript.js.md b/docs/agents/files/role/javascript.js.md index 1fe4b86b2b..100400bdba 100644 --- a/docs/agents/files/role/javascript.js.md +++ b/docs/agents/files/role/javascript.js.md @@ -13,7 +13,7 @@ For injector wiring, activation, and repository-wide behavior rules, see [Contri ## Implement - You MUST use `templates/javascript.js.j2` when runtime values from the inventory or role variables must be rendered into the browser code. -- You MUST use `files/javascript.js` when the script is static and does not depend on templating. +- You MUST use `files/javascript/javascript.js` when the script is static and does not depend on templating. - You MUST wait for the DOM before touching elements, and guard missing elements so unrelated pages do not break. - You MUST keep event handlers, observers, and DOM mutations idempotent because injected scripts may run on dynamic pages or be triggered repeatedly. - You MUST prefer stable selectors and narrow hooks over text matching or timing-based hacks. diff --git a/docs/architecture/backup.md b/docs/architecture/backup.md index 0176e7c5a3..f5e5b6d6e8 100644 --- a/docs/architecture/backup.md +++ b/docs/architecture/backup.md @@ -2,7 +2,7 @@ End-to-end flow of the backup chain and its recover counterparts. Solid arrows run on schedule (systemd units + pull); dashed arrows are the -recover direction (`files/recover.py` of each role, enforced by +recover direction (`files/python/recover.py` of each role, enforced by `tests/lint/ansible/roles/test_bkp_roles_have_recover.py`). The swarm test pipeline exercises the full chain in `scripts/tests/deploy/swarm/routine/backup/base.sh`. @@ -47,12 +47,25 @@ flowchart TB bkp_backups -.->|"operator rsync
(backup user is pull-only)"| src_backups src_backups -.->|"nfs-2-local recover.py
backup unit first, then rsync --delete"| export src_backups -.->|"volume-2-local recover.py
backup unit first, then rsync --delete
into the volume mountpoint"| volumes + src_backups -.->|"volume-2-local recover.py --databases
baudolo-restore <engine> --empty per dump,
consumers must be down"| volumes src_backups -.->|"secrets-2-local recover.py
backup unit first, then rsync --delete
per subtree to its fixed system path"| secrets ``` +Databases travel as sql dumps, not as a file tree (`--dump-only-sql`), so +they have their own recover leg: `recover database `, which +`recover full` plans right after the volume steps. That leg is the one part +of the chain that cannot run on a bare host: a dump is replayed through +`docker exec`, so the database service has to be deployed and up, with its +consumers stopped. The engine of a dump is +resolved from the consuming role's `meta/services.yml` service key in +`utils/recovery/databases.py` — the same value the backup seed used — and a +replay refuses to run while a consumer of that database is up, because +`--empty` pre-cleans the schema and a booting consumer would recreate it +underneath the replay. + Per-role recover procedures live in each role's `## Recover` README section; `svc-bkp-remote-2-local` documents its one-way opt-out in -`files/recover.py.nocheck`. +`files/python/recover.py.nocheck`. ## Deploy-time trigger flow diff --git a/docs/architecture/central-engines.md b/docs/architecture/central-engines.md index e465638893..3bf5fd8c63 100644 --- a/docs/architecture/central-engines.md +++ b/docs/architecture/central-engines.md @@ -8,7 +8,7 @@ engines are the only `placement: manager` (node-local) services. ## Problem this solves NFS placement is derived from `placement` (see -`plugins/filter/compose_volumes.py`): an unpinned role's volumes are bound to the +`plugins/lookup/compose_volumes.py`): an unpinned role's volumes are bound to the shared NFS mount (survive a reschedule), a pinned role keeps its volumes node-local. Engine on-disk state (redis/rabbitmq/elasticsearch/sqlite/postfix-queue) **cannot live on NFS** (fsync + locking corruption), so a role that *embeds* such an engine diff --git a/docs/architecture/decisions/0001-ci-deploy-matrix-axes.md b/docs/architecture/decisions/0001-ci-deploy-matrix-axes.md new file mode 100644 index 0000000000..f3563fb0f9 --- /dev/null +++ b/docs/architecture/decisions/0001-ci-deploy-matrix-axes.md @@ -0,0 +1,114 @@ +# 0001: Distro and filesystem are deploy-matrix axes 🧭 + +**Status:** accepted + +## Context 🎯 + +The CI deploy matrix turns the role catalogue into deploy jobs. +Each row is one `role#variant` selection, and each row must state everything that makes its deployment reproducible, because a red job is only useful if an operator can replay exactly it. + +Two properties decide what a deploy actually exercises and neither is a property of the role: the distribution the node runs, and the filesystem the docker data root sits on. +The snapshot mode of `svc-bkp-volume-2-local` engages only on btrfs and zfs, and package behaviour differs per distribution family, so a run that proves a role on one combination proves little about the others. + +A run-wide choice cannot cover them. +Five distributions and three filesystems are fifteen combinations, and a sweep that fixes one pair for all of its rows would need fifteen sweeps to say anything about the rest, while reporting green the whole time. + +## Decision ✅ + +`distro` and `filesystem` are axes of the matrix row, assigned per row by [axes.py](../../../utils/github/variant/axes.py), exactly as `mode` and `tor` already are. + +- **Assignment reads the row's position like an odometer.** The distro is the low digit and the filesystem the high one, so consecutive rows walk every pairing instead of a diagonal through it. Turning both on the position directly covers only `n` of the `n x m` pairs whenever the two pools are the same length, and the sweep number does not unlock it, because it shifts both by the same amount. + + Three distros and three filesystems make the difference visible: + + | Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Pairs reached | + |---|---|---|---|---|---|---|---|---|---|---| + | Both on the position | a·1 | b·2 | c·3 | a·1 | b·2 | c·3 | a·1 | b·2 | c·3 | 3 of 9 | + | Odometer | a·1 | b·1 | c·1 | a·2 | b·2 | c·2 | a·3 | b·3 | c·3 | 9 of 9 | + +- **Assignment is deterministic, never random.** It follows the row's index in the global discovery order and the sweep number, so re-running a sweep reproduces the run. Discovery order itself is stabilised by `INFINITO_DISCOVERY_SEED`, which CI sets to the run id, so the plan table, the discover job and every chunk block of one run agree without passing state between them. +- **The axes are part of a row's identity.** They appear in the job label as glyphs, in the plan table as columns, and in the artifact name. Two rows that differ only in distro are two deploys and MUST NOT share an artifact name. +- **The axes are selectable.** `%distro` and `/filesystem` narrow a `whitelist` or `priority` token the same way `@mode` and `+tor` do. A retrigger reads the distro back off a failed job's title, so a red row returns on the distribution it died on. It does not read the filesystem back: the title states the kind the matrix assigned, which a deploy may have fallen back from, and writing it into a token would state it as named by a human and make it binding. +- **The pools are narrowable per run.** The `distros` and `filesystem` inputs default to empty, which means every declared value. Narrowing is for chasing one distribution or one filesystem. + +One row is decided once and then read by three consumers that MUST agree on it: + +```mermaid +flowchart LR + Q["discovery query
ordered candidate rows"] --> A["axes.assign
mode · tor · distro · filesystem"] + A --> J["matrix JSON
one entry per deploy"] + + J --> L["job label
glyph prefix"] + J --> P["plan table
run summary"] + J --> T["artifact name"] + J --> E["deploy job env
INFINITO_DISTROS
INFINITO_DOCKER_FILESYSTEM_PICK"] + + E --> R["resolve.sh decides
docker_dataroot.sh applies"] + L --> F["parse_label
failure report and retrigger"] + F --> S["selection token
replays the same combination"] + S -.-> Q +``` + +The dotted edge is the property the axes exist for: a red job's title carries enough to rebuild the selection that reproduces it. + +### The filesystem is a preference unless a human names it 🗄️ + +The matrix hands every row exactly one filesystem, so the value a deploy job sees is always narrow. +Reading that narrowness as a demand would turn every condition the applying step is built to tolerate into a red row: a loop device it could not claim, a pool another job still holds, a kernel without the module. + +An entry therefore carries `enforce_filesystem`, true when a human left the row no choice: a `/filesystem` selection token, or a run whose `filesystem` input names exactly one kind. + +| `enforce_filesystem` | A host that cannot serve the assigned kind | +|---|---| +| false | falls back inside what the run permits, and reports the substitution in the step summary | +| true | fails the row | + +A run that permits two or more kinds is a preference, not a demand. +The matrix has already narrowed each row to one kind out of that pool, so falling back to another kind the run allowed stays inside what the operator asked for, while failing the row does not. +A run whose whole permitted pool is unservable fails rather than leaving the pool. + +A fallback MUST stay inside the permitted set, and a run whose whole permitted set is unservable MUST fail rather than leave it. +The job title and the artifact name carry the kind the matrix assigned; the step summary carries the effective one. + +```mermaid +flowchart TD + START["row assigned a filesystem"] --> ENF{"did a human name it?
run input of one kind, or selection token"} + ENF -->|yes| KEEP["take it, REQUIRED=true"] + KEEP --> CAN{"can the host deliver it?"} + CAN -->|yes| DEPLOY["deploy on the assigned kind"] + CAN -->|no| FAIL["the row fails"] + ENF -->|no| SERVED{"does the host serve it?"} + SERVED -->|yes| DEPLOY + SERVED -->|no| REST{"does the host serve
anything the run permits?"} + REST -->|yes| BACK["fall back inside the permitted set
report the substitution"] + REST -->|no| LOUD["keep the assignment, REQUIRED=true
the row fails"] +``` + +Every path either deploys on the assigned kind, reports the substitution, or fails. +None of them substitutes in silence. + +## Consequences 📉 + +- Across the rows a sweep deploys, every distribution and every filesystem is exercised instead of one pair, at no extra job count. +- The redundancy cut does not follow the axes. `covered_by` is a role-level claim discovery computes from the service closure, so the row that covers a cut row now usually lands on a different distribution: on a full sweep, 6 of 44 cut rows share their coverer's distro. The cut therefore asserts that the services were exercised, not that they were exercised on that row's distribution. Reaching a cut row on its own axes means naming it on the priority line, which is what `⭐` exists for. +- A job title states its whole combination, which lets `--failed` replay the mode, onion state and distribution, and makes a plan table row comparable to the job it predicts. +- Both pools feed the assignment, so narrowing `distros` to one value pins every row to it rather than reducing the run. +- Two selection tokens that pin different axes of one row can resolve to the same deploy. They collapse into one entry, and the stronger `enforce_filesystem` claim survives the collapse. +- The resume offset a retrigger computes names a `role#variant` and carries no axes, because every axis rotates with the sweep number and a retrigger receives a fresh one. +- CI images MUST exist for every declared distribution on every run, since any row may draw any of them. + +## Alternatives weighed 🔀 + +| Alternative | Why it lost | +|---|---| +| Keep a run-wide distro, drawn once before the orchestrator starts | One sweep proves one distribution and claims nothing about the other four, while reporting green. | +| Keep the per-distro loop inside each deploy job | Multiplies every job's wall clock by the number of distributions and forces a shared time budget that silently skips the tail. | +| Make the assigned filesystem binding in every case | Promotes each transient condition the applying step tolerates into a red row, on every deploy job of every sweep. | +| Leave the filesystem a preference in every case | A run that names a kind to chase a filesystem-dependent path could go green on a different one. | +| Draw the axes at random per row | A red job could not be reproduced by re-running its sweep, which is the property the whole rotation exists to provide. | + +## See also 🔗 + +- [README.md](../../../.github/workflows/README.md) for the selection-token grammar and the per-axis rotation table. +- [variants.md](../../contributing/design/variants.md) for what a `role#variant` row is. +- [deployment-modes.md](../../contributing/design/deployment-modes.md) for the `mode` axis. diff --git a/docs/architecture/decisions/README.md b/docs/architecture/decisions/README.md new file mode 100644 index 0000000000..71d78ec75e --- /dev/null +++ b/docs/architecture/decisions/README.md @@ -0,0 +1,12 @@ +# Architecture Decisions 🧭 + +This directory holds the architecture decision records of Infinito.Nexus. +A record states one decision that shapes the system, the forces that constrain it, and what living with it costs. + +## Scope 📋 + +- A record MUST cover a decision whose reversal would be expensive: a contract between components, a data or naming shape other code depends on, or a rule that governs a whole subsystem. +- A record MUST NOT be written for a choice that a reader can recover from the code alone, such as a helper's signature or a local refactoring. +- A record MUST describe the decision as it stands today, including the alternatives that were weighed and why they lost, so a later reader can tell a deliberate constraint from an accident. +- A record MUST be numbered in the order it was accepted, and its number MUST NOT be reused. +- A superseded record MUST stay in place with its status changed and a link to the record that replaces it, because the reasoning it carries is what makes the replacement legible. diff --git a/docs/contributing/actions/testing/lint.md b/docs/contributing/actions/testing/lint.md index 87ca8f551b..111df6ce90 100644 --- a/docs/contributing/actions/testing/lint.md +++ b/docs/contributing/actions/testing/lint.md @@ -11,7 +11,7 @@ You MUST use these linting and quality tools where applicable: You MUST apply these repo-wide rules when you add, move, or review files: - Keep broad folders shallow when that helps readability. Direct children SHOULD stay at 12 or fewer items per folder. -- Treat structural hubs such as `roles/`, `cli/`, `tests/unit/plugins/filter`, `tests/unit/roles`, `inventories/bundles/servers`, `inventories/bundles/workstations`, `plugins/filter`, `plugins/lookup`, `group_vars/all`, and `.github/workflows` as intentional exceptions when they are used to organize the tree. +- Treat structural hubs such as `roles/`, `cli/`, `tests/unit/python/plugins/filter`, `tests/unit/python/roles`, `inventories/bundles/servers`, `inventories/bundles/workstations`, `plugins/filter`, `plugins/lookup`, `group_vars/all`, and `.github/workflows` as intentional exceptions when they are used to organize the tree. - You SHOULD prefer smaller, more focused folders over dumping many unrelated files into one directory. For refactoring guidance, see [Refactoring](../refactoring.md). diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index 5e20e3d933..f55f3fd857 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -46,6 +46,7 @@ The placement rule is per check. The catalog "Position" column uses these labels | `url` | same or above | [test_urls_reachable.py](../../../../tests/external/repository/test_urls_reachable.py) | Skips probing the literal HTTP(S) URL. Use for CDN roots and API base URLs that 4xx without a path. | | `docker-version` | same or above | [test_image_versions.py](../../../../tests/external/update/docker/test_image_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live version-update warning and the non-semver-pin lint for that image's `version:` key. | | `repository-version` | same or above | [test_repository_versions.py](../../../../tests/external/update/repository/test_repository_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live ref-update warning and the non-semver-pin lint for that entity's `ref:` key. | +| `dockerfile-arg-default` | same or above | [test_arg_without_default.py](../../../../tests/lint/docker/dockerfile/test_arg_without_default.py) | Allows the marked `ARG` to carry a default. The caller normally supplies every build argument so a missing one fails the build instead of selecting a base image nobody chose. | | `direct-yaml` | same line / span | [test_no_direct_calls.py](../../../../tests/lint/repository/yaml/test_no_direct_calls.py) | Allows the marked `yaml.safe_load` / `safe_dump` call to bypass `utils.cache.yaml`. MUST use `nocheck:`, not `noqa:`. | | `curl-timeout` | same or above | [test_curl_via_filter.py](../../../../tests/lint/repository/test_curl_via_filter.py) | Allows a bare curl invocation without the `curl` filter or inline `--max-time`. | | `redundant-bool-ternary` | same line | [test_no_redundant_bool_patterns.py](../../../../tests/lint/filesystem/python/test_no_redundant_bool_patterns.py) | Allows the redundant `\| bool \| ternary('true','false')` pattern when a consumer requires the lowercase tokens. | @@ -67,8 +68,8 @@ The placement rule is per check. The catalog "Position" column uses these labels | `hardcoded-dns-resolver` | same or above | [test_no_hardcoded_dns_resolvers.py](../../../../tests/lint/repository/network/test_no_hardcoded_dns_resolvers.py) | Marks a line that needs a literal IP from `NETWORK_PUBLIC_DNS_RESOLVERS` where the substitution point cannot consume the variable (CoreDNS non-Jinja templates, host-bootstrap shell, doc examples). | | `dynamic-flag` | same line OR comment block above key | [test_dynamic_flags.py](../../../../tests/integration/roles/meta/services/test_dynamic_flags.py) | Marks a `roles/*/meta/services.yml` flag whose value stays literal. Per-flag (same line) for databases. Block-level (comment block above) when both flags stay literal. | | `native-metrics` | comment block above | [test_native_metrics_contract.py](../../../../tests/integration/roles/meta/services/prometheus/test_native_metrics_contract.py) | Marks a role whose `services.prometheus.native_metrics.enabled` and `templates/prometheus.yml.j2` presence are intentionally inconsistent. Reserved for prepared-but-default-off scrape fragments (operator opt-in). | -| `prometheus-scrape` | same or above | [test_roles_with_service.py](../../../../tests/unit/plugins/lookup/test_roles_with_service.py) | Documents a `services.prometheus.scrape: false` opt-out in `roles//meta/services.yml`. The role keeps `services.prometheus.{enabled,shared}: true` (so the role-wiring contract stays satisfied) but `roles_with_service('prometheus')` drops it from `PROMETHEUS_TARGET_ROLES_JSON`. Reserved for 301-redirect-only vhosts that never serve a request through lua-resty-prometheus, so they emit no `app=""` label and have no scrape target. The marker accompanies the `scrape:` data flag the lookup honors. | -| `matomo-track` | same or above | [test_roles_with_service.py](../../../../tests/unit/plugins/lookup/test_roles_with_service.py) | Documents a `services.matomo.track: false` opt-out in `roles//meta/services.yml`. The role keeps `services.matomo.{enabled,shared}: true` (so the role-wiring contract stays satisfied) but `roles_with_service('matomo')` drops it from `MATOMO_TARGET_ROLES_JSON` and the matomo tracker e2e contract. Reserved for static-file (autoindex) and 301-redirect vhosts that carry no user-facing HTML page worth a `_paq` tracker. The marker accompanies the `track:` data flag the lookup honors. | +| `prometheus-scrape` | same or above | [test_roles_with_service.py](../../../../tests/unit/python/plugins/lookup/test_roles_with_service.py) | Documents a `services.prometheus.scrape: false` opt-out in `roles//meta/services.yml`. The role keeps `services.prometheus.{enabled,shared}: true` (so the role-wiring contract stays satisfied) but `roles_with_service('prometheus')` drops it from `PROMETHEUS_TARGET_ROLES_JSON`. Reserved for 301-redirect-only vhosts that never serve a request through lua-resty-prometheus, so they emit no `app=""` label and have no scrape target. The marker accompanies the `scrape:` data flag the lookup honors. | +| `matomo-track` | same or above | [test_roles_with_service.py](../../../../tests/unit/python/plugins/lookup/test_roles_with_service.py) | Documents a `services.matomo.track: false` opt-out in `roles//meta/services.yml`. The role keeps `services.matomo.{enabled,shared}: true` (so the role-wiring contract stays satisfied) but `roles_with_service('matomo')` drops it from `MATOMO_TARGET_ROLES_JSON` and the matomo tracker e2e contract. Reserved for static-file (autoindex) and 301-redirect vhosts that carry no user-facing HTML page worth a `_paq` tracker. The marker accompanies the `track:` data flag the lookup honors. | | `variants-static-override` | same line | [test_variants_no_static_override.py](../../../../tests/integration/roles/meta/services/test_variants_no_static_override.py) | Allows a `roles/*/meta/variants.yml` leaf override of an attribute whose base value in `meta/services.yml` is a static literal. Place on the override line in `variants.yml`. Use only when the consumer chain is provably immune to the variant-merge propagation gap; the default is to make the base value dynamic via `"{{ '' in group_names }}"`. | | `variants-shared-false-once` | same or above | [test_variants_shared_false_once.py](../../../../tests/lint/ansible/services/test_variants_shared_false_once.py) | Exempts one `roles/*/meta/variants.yml` `services..shared: false` pin from the one-local-provider-variant limit for a service whose base `meta/services.yml` uses literal `enabled: true` and dynamic `shared`. Place on the extra `shared: false` line or service key line. Place above the service key in `meta/services.yml` to exempt the service. | | `variants-services-match` | same or above | [test_services_match.py](../../../../tests/integration/roles/meta/variants/test_services_match.py) | Allows a `roles/*/meta/variants.yml` `services.` entry to reference a service key that is NOT declared as a top-level entry in `meta/services.yml`. Reserved for resolver-only matrix hooks (typically on invokable infrastructure roles) whose variant entries pin the round's companion topology via service-key flags the resolver maps to provider roles, with no real consumer contract in the base meta. | @@ -89,11 +90,16 @@ The placement rule is per check. The catalog "Position" column uses these labels | `restart-key` | same or above | [test_mode_incompatible_keys.py](../../../../tests/lint/ansible/jinja/test_mode_incompatible_keys.py) | Allows a raw `restart:` key in a `roles/*/templates/**/*.j2` template. Default path: route through the `compose_restart` lookup so swarm-mode does not silently drop the operator's `docker_restart_policy`. | | `compose-structure` | same or above; head (first 30 lines) | [test_compose_template_structure.py](../../../../tests/lint/ansible/jinja/test_compose_template_structure.py) | Exempts a `roles/*/templates/*compose.yml.j2` line, or the whole file (head marker), from the canonical compose skeleton: base-include header, `{{ service_name }}:` service keys each preceded by their `{% set service_name %}`, all per-service `{% set %}` knobs on two-space-indented dash-free lines above the key, `{% include %}` at four spaces inside the service body, and column-0 `compose_volumes` / `compose_networks` at the tail. The layout renders correctly because the `stack_host_template` action plugin sets `lstrip_blocks=True` for `compose.yml.j2`. Reserved for legitimate deviations that genuinely cannot follow the skeleton. | | `seaweedfs-required` | head (first 30 lines) | [test_database_requires_seaweedfs.py](../../../../tests/integration/roles/meta/services/test_database_requires_seaweedfs.py) | Exempts a database-backed `web-app-*` role from the requirement to declare a seaweedfs object-store service. Place in the head of `roles//meta/services.yml`. Use only when the application genuinely needs no object storage. | +| `tor-contract` | anywhere in file | [test_tor_contract.py](../../../../tests/lint/ansible/roles/meta/test_tor_contract.py) | Exempts a domain-serving role (`web-`/`svc-db-` prefix or explicit `domains.canonical`) from the "must declare a `tor:` block in `meta/services.yml`" contract. Reserved for roles with no onion surface, e.g. pure redirect helpers. | | `templated-conditional` | same or above | [test_no_templated_conditionals.py](../../../../tests/lint/ansible/test_no_templated_conditionals.py) | Exempts a `when` / `failed_when` / `changed_when` / `until` value that legitimately carries `{{ }}` / `{% %}`. Reserved for genuine edge cases; the default path is a bare expression. Per-item render/apply data guards belong on a `condition:` data field (honored by the sys-svc-compose render helper and `LISTMONK_SETTINGS`), not `when:`. | | `container-address-quote` | same or above | [test_address_never_quoted.py](../../../../tests/lint/ansible/shell/container/test_address_never_quoted.py) | Allows `*_CONTAINER_ADDRESS \| quote` in a role task file. Reserved for sites that never see the swarm `$(...)` fragment (`DEPLOYMENT_MODE == 'compose'`-gated tasks, `compose_mode_force` roles) or consumers that re-evaluate the argument themselves. | | `container-exec-resolver` | same or above; `argv:` target item | [test_exec_uses_resolver.py](../../../../tests/lint/ansible/shell/container/test_exec_uses_resolver.py) | Allows a `container exec` / `container inspect` target that does not route through the `container_address` lookup. Reserved for a container ID already resolved at `delegate_to` runtime (`*_LOCAL_CID`), where the lookup would return a manager-only subshell, and for deliberate bare-name partner probes gated on compose co-location. | | `container-inspect-type` | same or above; `argv:` inspect item | [test_inspect_pins_type.py](../../../../tests/lint/ansible/shell/container/test_inspect_pins_type.py) | Allows an untyped `container inspect` under `roles/`. Default path: pin `--type container`, because a role's overlay network carries the same entity name as its main container, so an untyped inspect can resolve the network and report `map has no entry for key "State"`. Use the typed subcommand (`container volume inspect` etc.) when the target genuinely is not a container. | +| `container-healthcheck-unused` | same or above the service key or its `healthcheck:` line | [test_container_healthcheck_declared_is_used.py](../../../../tests/lint/ansible/jinja/test_container_healthcheck_declared_is_used.py) | Allows a `services..healthcheck` that no `lookup('container_healthcheck', …)` call renders. Default path: add the lookup to the service block, because an unrendered declaration reads like the service is watched while the compose file carries no probe. Reserved for a call the static resolver cannot attribute — mastodon renders every service through a macro whose `service_name` is a macro parameter. | +| `image-healthcheck` | same or above the service key | [test_image_healthcheck_declared.py](../../../../tests/integration/roles/test_image_healthcheck_declared.py) | Allows a `roles/*/meta/services.yml` entry whose image ships no `HEALTHCHECK` to declare none either. Default path: add `healthcheck:` to the entry, because a container without a probe counts as healthy the moment its process starts — which is how a service that came back empty passes a restore drill. Reserved for containers nothing can probe: a one-shot process that exits, or an image with neither a port nor a shell. | +| `csp-unsafe` | same line | [test_csp_unsafe_requires_justification.py](../../../../tests/lint/ansible/roles/meta/test_csp_unsafe_requires_justification.py) | Documents an `unsafe-*: true` flag in `roles/*/meta/csp.yml`. MUST be paired with a `Reason:` on the same line naming what breaks without the relaxation. `unsafe-inline` re-admits the inline execution an XSS needs and `unsafe-eval` re-admits string-to-code, so the flag has to be verified against the running app, not copied from another role. | | `min-storage-headroom` | same line OR comment block above key | [test_min_storage_headroom.py](../../../../tests/external/update/docker/test_min_storage_headroom.py) | Allows a `roles/*/meta/services.yml` `min_storage` to exceed the measured compressed size of its own `image:`/`version:` by more than 1 GB. MUST be paired with a `Reason:` on the same comment line naming what occupies the space. Reserved for services whose data volume genuinely dominates the footprint; the default path is to lower the value, because an over-declared budget makes a host look too small and prunes a cache the deploy did not need to lose. | +| `galaxy-git-parity` | same or above | [test_galaxy_entries_have_git_source.py](../../../../tests/lint/repository/dependencies/test_galaxy_entries_have_git_source.py) | Exempts a `requirements/requirements.galaxy.yml` collection from the requirement to also carry a `type: git` entry in `requirements/requirements.git.yml`. Reserved for collections that publish no usable git remote; without the git entry a `galaxy.ansible.com` outage fails `make install`, because the fallback in `scripts/install/ansible.sh` cannot resolve the collection either. | ## Tool-Native `noqa` Codes 🧹 diff --git a/docs/contributing/actions/testing/unit.md b/docs/contributing/actions/testing/unit.md index cc9894c07d..457a009f07 100644 --- a/docs/contributing/actions/testing/unit.md +++ b/docs/contributing/actions/testing/unit.md @@ -7,7 +7,7 @@ Run unit tests with `make test-unit`. - You MUST use Python `unittest` as the test framework. - Tests MUST live under `tests/unit/`. -- Mirror the source tree: a file at `plugins/lookup/service.py` gets its tests at `tests/unit/plugins/lookup/test_service.py`. +- Mirror the source tree: a file at `plugins/lookup/service.py` gets its tests at `tests/unit/python/plugins/lookup/test_service.py`. ## Requirements 📋 diff --git a/docs/contributing/artefact/files/github/workflow.md b/docs/contributing/artefact/files/github/workflow.md index abbbe0a9ed..383e8e7961 100644 --- a/docs/contributing/artefact/files/github/workflow.md +++ b/docs/contributing/artefact/files/github/workflow.md @@ -6,12 +6,13 @@ For the script placement rule that applies to extracted shell helpers, see [scri ## Naming 🏷️ -Every workflow MUST follow the schema `"[Emoji] Category: Subject (Qualifier)"`. +Every workflow MUST follow the schema `"[Emoji] Category: Subject (Qualifier)"`, except a scheduled one — see [Scheduled runs](#scheduled-runs-). - You MUST quote the `name:` value in double quotes because the colon (`:`) in the name is a reserved YAML character. - You MUST place the emoji before the category, never after. - You MUST NOT add emojis to `docs/agents/` files, but workflow `name:` fields are not agent files and MUST use emojis. - The qualifier in parentheses is OPTIONAL. Use it only when two workflows share the same category and subject. +- A workflow with a `workflow_dispatch` trigger MUST keep its `name:` at or below 25 characters, enforced by [test_workflow_dispatch_name_length.py](../../../../../tests/lint/repository/test_workflow_dispatch_name_length.py). The dispatch menu lists those names in one narrow column, where a longer one is truncated. Move the explanatory wording into `run-name:`, which carries no such limit. ### Emoji legend 📋 @@ -25,7 +26,7 @@ Every workflow MUST follow the schema `"[Emoji] Category: Subject (Qualifier)"`. | `🔒` | Scan | Security scanning | | `⚡` | CI | CI entry points (push, pull request, manual) | | `🎵` | CI | CI orchestration and coordination workflows | -| `🚫` | Cancel | Run cancellation on PR close or branch delete | +| `🚫` | Cancel | Run cancellation on PR close, branch delete, or a superseding commit | | `🧪` | Test | Code tests (unit, integration, lint) | | `💻` | Test | Development environment tests | | `💬` | Test | DNS and network resolution tests | @@ -41,6 +42,19 @@ name: "🪞 Mirror: Docker Hub → GHCR (only missing)" name: "🚫 Cancel: PR Runs on Close" ``` +### Scheduled runs ⏰ + +A scheduled workflow (`cron-*.yml`) drops the `Category:` schema: its `name:` MUST read as one short sentence saying what the run does, because the Actions list shows scheduled runs next to each other with no PR or branch to tell them apart. + +It MUST NOT carry ⏰ in its `name:`, and MUST carry a `run-name:` that prefixes ⏰ only when the schedule started the run, so a dispatched run is not mislabelled as scheduled: + +```yaml +name: "🔄 Update versions" +run-name: "${{ github.event_name == 'schedule' && '⏰ ' || '' }}🔄 Update versions" +``` + +Enforced by [test_workflow_trigger_prefix.py](../../../../../tests/lint/repository/test_workflow_trigger_prefix.py), which also owns the `entry-` / `call-` / `cron-` file-name rule. + ## Shell execution 📜 - Multi-line shell logic in workflow `run:` blocks MUST be extracted into dedicated `.sh` files under `scripts/`. diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index 7a7d709411..58186bf903 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -23,7 +23,7 @@ The `applications` lookup is the ONLY supported runtime entry point for merged a The lookup merges exactly two sources: -1. **Defaults** discovered from each role's per-topic meta files: `roles/*/meta/server.yml`, `roles/*/meta/rbac.yml`, `roles/*/meta/services.yml`, `roles/*/meta/volumes.yml`, plus `roles/*/meta/schema.yml` (post-`apply_schema()`). Variants from `roles/*/meta/variants.yml` deep-merge over the assembled per-role payload. See [layout.md](../../../../design/role/services/layout.md). +1. **Defaults** discovered from each role's per-topic meta files: `roles/*/meta/server.yml`, `roles/*/meta/rbac.yml`, `roles/*/meta/services.yml`, `roles/*/meta/volumes.yml`, plus `roles/*/meta/secrets.yml` (post-`apply_schema()`). Variants from `roles/*/meta/variants.yml` deep-merge over the assembled per-role payload. See [layout.md](../../../../design/role/services/layout.md). 2. **Overrides** supplied through the normal Ansible variable `applications` in inventory, group vars, host vars, or role vars. No intermediate merged `applications` fact exists. No other source is consulted. @@ -32,7 +32,7 @@ No intermediate merged `applications` fact exists. No other source is consulted. You MUST add new application defaults in the owning role: -1. Create or edit the appropriate `roles//meta/.yml` files (`services.yml`, `server.yml`, `rbac.yml`, `volumes.yml`, `schema.yml`). See [layout.md](../../../../design/role/services/layout.md) for the per-topic content. +1. Create or edit the appropriate `roles//meta/.yml` files (`services.yml`, `server.yml`, `rbac.yml`, `volumes.yml`, `secrets.yml`). See [layout.md](../../../../design/role/services/layout.md) for the per-topic content. 2. The role directory name is the `application_id`. For example `roles/web-app-mailu/meta/services.yml` is exposed as `applications['web-app-mailu'].services`, `roles/web-app-mailu/meta/server.yml` as `applications['web-app-mailu'].server`, and so on. 3. Keep all application-scoped defaults (services, server settings, RBAC, volumes, credentials schema) inside those role-local meta files. @@ -69,7 +69,7 @@ applications: |---|---| | [applications.py](../../../../../../plugins/lookup/applications.py) | Runtime entry point for the `applications` lookup. | | [applications.py (cache)](../../../../../../utils/cache/applications.py) | Shared aggregation helper that builds and caches defaults (`get_application_defaults`, `get_variants`, `get_merged_applications`). | -| [test_applications.py](../../../../../../tests/unit/plugins/lookup/test_applications.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | +| [test_applications.py](../../../../../../tests/unit/python/plugins/lookup/test_applications.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | For the related users pattern see [users.md](users.md). For the per-role matrix-variant list that backs `applications` when more than one shape exists, see [variants.md](../../../../design/variants.md) (deploy-time mechanism) and [variants.md](../../role/variants.md) (file format). diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index 03d592235c..c3ab7ffcb9 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -82,6 +82,6 @@ users: |---|---| | [users.py](../../../../../../plugins/lookup/users.py) | Runtime entry point for the `users` lookup. | | [users/ (cache)](../../../../../../utils/cache/users/) | Shared aggregation helper package that builds and caches defaults, handles reserved users, UID/GID allocation, and uniqueness validation. Placeholder substitution (DOMAIN_PRIMARY / ORGANIZATION / SOFTWARE_NAME) lives in [users/placeholders.py](../../../../../../utils/cache/users/placeholders.py). | -| [test_users.py](../../../../../../tests/unit/plugins/lookup/test_users.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | +| [test_users.py](../../../../../../tests/unit/python/plugins/lookup/test_users.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | For the related applications pattern see [applications.md](applications.md). diff --git a/docs/contributing/artefact/files/role/javascript.js.md b/docs/contributing/artefact/files/role/javascript.js.md index ccfaa3c64c..2f5763d160 100644 --- a/docs/contributing/artefact/files/role/javascript.js.md +++ b/docs/contributing/artefact/files/role/javascript.js.md @@ -7,10 +7,10 @@ For browser-side validation requirements after visible behavior changes, see [Pl ## `javascript.js.j2` ⚙️ -- `sys-front-inj-javascript` loads `templates/javascript.js.j2` when it exists and otherwise falls back to `files/javascript.js`. +- `sys-front-inj-javascript` loads `templates/javascript.js.j2` when it exists and otherwise falls back to `files/javascript/javascript.js`. - The injector runs when `services.javascript.enabled` is enabled. - The loaded script is collapsed into a one-liner before injection and added to the CSP hash list so inline execution remains consistent with the generated policy. -- You MUST use `javascript.js.j2` when the script depends on role variables or inventory values, and use `files/javascript.js` when the script is static. +- You MUST use `javascript.js.j2` when the script depends on role variables or inventory values, and use `files/javascript/javascript.js` when the script is static. ## Inventory 📋 diff --git a/docs/contributing/artefact/files/role/variants.md b/docs/contributing/artefact/files/role/variants.md index f382cbc68a..5c59c1d66f 100644 --- a/docs/contributing/artefact/files/role/variants.md +++ b/docs/contributing/artefact/files/role/variants.md @@ -8,14 +8,14 @@ For how the file is consumed at runtime (folder-per-round model, `--variant` / ` - The file MUST live at `roles//meta/variants.yml`. - It MUST NOT be named `meta/inventory.yml`. The Ansible language server auto-applies the inventory schema to that filename, and the variant list does not satisfy it. -- A role MAY omit the file entirely. The loader then exposes exactly one variant equal to the assembled per-role meta payload (`meta/services.yml` + `meta/server.yml` + `meta/rbac.yml` + `meta/volumes.yml` + `apply_schema()`'d `meta/schema.yml`) unchanged. +- A role MAY omit the file entirely. The loader then exposes exactly one variant equal to the assembled per-role meta payload (`meta/services.yml` + `meta/server.yml` + `meta/rbac.yml` + `meta/volumes.yml` + `apply_schema()`'d `meta/secrets.yml`) unchanged. ## File Format 📋 - The top-level node MUST be a YAML list. A non-list root is a hard error. - Each list entry MUST be either: - the empty mapping `{}` (the canonical no-override entry), or - - a YAML mapping that mirrors the assembled application payload, so it can override anything reachable under `applications..{server,rbac,services,volumes,credentials}` (see [layout.md](../../../design/role/services/layout.md)). + - a YAML mapping that mirrors the assembled application payload, so it can override anything reachable under `applications..` (see [layout.md](../../../design/role/services/layout.md)). Every root is the name of a `meta/` topic — `services`, `server`, `rbac`, `volumes`, `secrets`, `addons`, `csp`, `domains`, `networks`, `info`, `users` — because the entry is baked into `host_vars` raw, which makes its top-level key the inventory path. A key no `meta/.yml` produces lands where nothing reads it and the override is silently discarded; `TestVariantTopLevelKeys` in [test_layout.py](../../../../../tests/lint/ansible/roles/meta/test_layout.py) rejects it. - The literal `null` is normalised to `{}` so a bare `- ` list item stays valid. - Scalars at entry level (numbers, strings, lists) are rejected. - Variants are addressed by their **zero-based index** in the list. @@ -83,7 +83,7 @@ This declares two variants. Variant 0 pins every dynamic service-key from `meta/ 2. Make sure variant 0 pins every dynamic service-key from `meta/services.yml` to `enabled: true, shared: true`. 3. Append a list entry for the new variant. For every dynamic service-key variant 0 enables, the new entry MUST either keep it on (re-pin `enabled: true, shared: true`) or explicitly disable it (`enabled: false, shared: false`). Add the variant-specific overrides that justify the new entry. 4. If the new variant relies on cleanup steps that the standard inter-round entity purge does not cover, extend the role's purge handling. The matrix wrapper invokes the standard purge between rounds for every app whose variant changed. -5. Add or extend the deep-merge edge-case tests in [test_variants.py](../../../../../tests/unit/utils/cache/test_variants.py) when the new variant exercises behaviour beyond the existing fixtures (for example list replacement vs. nested scalar override). +5. Add or extend the deep-merge edge-case tests in [test_variants.py](../../../../../tests/unit/python/utils/cache/test_variants.py) when the new variant exercises behaviour beyond the existing fixtures (for example list replacement vs. nested scalar override). ## What Not To Do 🚫 diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 9b661ded15..e5d8a4f3d2 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -72,7 +72,7 @@ The two deploy-test workflows listed in the `Infrastructure tests` table of [wor #### Diff-driven app selection 🎯 -Both [call-test-deploy-compose.yml](../../../../.github/workflows/call-test-deploy-compose.yml) and [call-test-deploy-swarm.yml](../../../../.github/workflows/call-test-deploy-swarm.yml) narrow their app matrix to the set of roles actually impacted by the branch's diff against `origin/main`. The `discover` job resolves an effective whitelist before [output_apps.sh](../../../../scripts/github/resolve/output_apps.sh) runs, using the following precedence: +[call-test-deploy.yml](../../../../.github/workflows/call-test-deploy.yml) narrows its app matrix to the set of roles actually impacted by the branch's diff against `origin/main`. The `discover` job resolves an effective whitelist before [output_apps.sh](../../../../scripts/github/resolve/output_apps.sh) runs, using the following precedence: 1. **Sentinel `__ALL__` in the `whitelist` input** (case-insensitive). The diff logic MUST be skipped and an empty whitelist MUST be emitted, which deploys everything in the workflow's scope. This is the explicit opt-out from diff narrowing for manual dispatch. 2. **Any other non-empty `whitelist`** (forwarded from `entry-manual-steer.yml` and similar). The explicit value MUST win over the diff and is passed through verbatim. @@ -126,9 +126,9 @@ The final `done` job aggregates all deploy, install, and development gates. CI i ## Concurrency 🔀 -- PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. -- The orchestrator and the push entry workflow (`entry-push-latest.yml`) default to `cancel-in-progress: true` and both respect the repository variable `CI_CANCEL_IN_PROGRESS`. -- The manual entry workflow (`entry-manual-steer.yml`) sets `cancel-in-progress: true` on its own group and passes `force_cancel_in_progress: true` into the orchestrator, so a manual run cancels on both levels regardless of `CI_CANCEL_IN_PROGRESS`. +- PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. The group does not always reap a long orchestrator sweep, which then leaves the newer run parked on `pending`; [entry-cancel-superseded.yml](../../../../.github/workflows/entry-cancel-superseded.yml) cancels those leftovers through the API, see [cancel/README.md](../../../../scripts/github/cancel/README.md). +- The orchestrator and the push entry workflow (`entry-push-latest.yml`) cancel in-progress runs on every ref except `main`, which no automatic trigger cancels. A `pull_request_target` run inherits `refs/heads/main` as its ref, so the orchestrator does not cancel there either; per-PR supersession is handled by the entry workflow's own `pr-ci-*` group. See [configuration.md](../../tools/github/actions/configuration.md). +- The manual entry workflow (`entry-manual-steer.yml`) sets `cancel-in-progress: true` on its own group, and the orchestrator's group cancels for `workflow_dispatch` regardless of ref, so a manual sweep supersedes on both levels, `main` included. See [configuration.md](../../tools/github/actions/configuration.md) for all repository variables that control CI behaviour. diff --git a/docs/contributing/design/iam/oidc.md b/docs/contributing/design/iam/oidc.md index 453c9f395f..2116e650d5 100644 --- a/docs/contributing/design/iam/oidc.md +++ b/docs/contributing/design/iam/oidc.md @@ -7,13 +7,19 @@ For LDAP-side details see [ldap.md](ldap.md). ## Variable Tree 🌳 +The `OIDC` tree is a lazy group_var: it resolves in the consuming role's +context, so the issuer family-aligns to that consumer (clearnet page → +clearnet issuer, onion page → onion issuer). Inventory overrides therefore +live under `OIDC_OVERRIDE:` — an inventory-level `OIDC:` block would shadow +the lazy resolution and is rejected by a constructor assert. + The keys consumers care about: | Key | Meaning | |---|---| | `OIDC.URL` | Base URL of the Keycloak instance | | `OIDC.CLIENT.ID` | Client identifier, defaults to `SOFTWARE_DOMAIN` | -| `OIDC.CLIENT.SECRET` | Client secret, MUST come from the inventory | +| `OIDC.CLIENT.SECRET` | Client secret, MUST come from the inventory (`OIDC_OVERRIDE.CLIENT.SECRET`) | | `OIDC.CLIENT.REALM` | Realm the client is registered in | | `OIDC.CLIENT.ISSUER_URL` | Issuer URL, equal to discovery `issuer` | | `OIDC.CLIENT.DISCOVERY_DOCUMENT` | `.well-known/openid-configuration` URL | diff --git a/docs/contributing/design/role/services/README.md b/docs/contributing/design/role/services/README.md index 8adfe6fda4..b0d786b24c 100644 --- a/docs/contributing/design/role/services/README.md +++ b/docs/contributing/design/role/services/README.md @@ -9,6 +9,6 @@ and consumers MUST follow. | Page | Purpose | |---|---| -| [layout.md](layout.md) | Per-role `meta/.yml` shape, file-root convention, services-inlining rule, `meta/schema.yml` (incl. the `default:` field), per-role `networks:` and per-entity `ports` shape, `run_after`/`lifecycle` placement. | +| [layout.md](layout.md) | Per-role `meta/.yml` shape, file-root convention, services-inlining rule, `meta/secrets.yml` (incl. the `default:` field), per-role `networks:` and per-entity `ports` shape, `run_after`/`lifecycle` placement. | | [base.md](base.md) | Service registration, discovery, load order, injection model, lookup plugins. | | [email.md](email.md) | `email` lookup plugin contract. | diff --git a/docs/contributing/design/role/services/base.md b/docs/contributing/design/role/services/base.md index 16e4c4747f..c089f599da 100644 --- a/docs/contributing/design/role/services/base.md +++ b/docs/contributing/design/role/services/base.md @@ -220,8 +220,8 @@ The `lookup('database', ...)` API is the convenience accessor for database conne | [load_service.yml](../../../../../roles/sys-service-loader/tasks/load_service.yml) | Per-service load helper used by the central service loader | | [01_constructor.yml](../../../../../tasks/stages/01_constructor.yml) | Calls the service loader during constructor | | [load/app.yml](../../../../../tasks/utils/load/app.yml) | Run-once role loader | -| [test_service_registry.py](../../../../../tests/unit/utils/roles/applications/services/test_registry.py) | Unit tests for discovery, buckets, and `run_after` ordering | -| [test_service.py](../../../../../tests/unit/plugins/lookup/test_service.py) | Unit tests for `lookup('service', ...)` | +| [test_service_registry.py](../../../../../tests/unit/python/utils/roles/applications/services/test_registry.py) | Unit tests for discovery, buckets, and `run_after` ordering | +| [test_service.py](../../../../../tests/unit/python/plugins/lookup/test_service.py) | Unit tests for `lookup('service', ...)` | | [test_resolvable.py](../../../../../tests/integration/infrastructure/services/test_resolvable.py) | Integration checks for discovered service resolution | | [test_canonical.py](../../../../../tests/integration/infrastructure/services/test_canonical.py) | Canonical alias consistency checks | | [test_transitive_dependencies.py](../../../../../tests/integration/infrastructure/services/test_transitive_dependencies.py) | Integration coverage for transitive dependency resolution | diff --git a/docs/contributing/design/role/services/email.md b/docs/contributing/design/role/services/email.md index 9227d95e4f..aff9f0f663 100644 --- a/docs/contributing/design/role/services/email.md +++ b/docs/contributing/design/role/services/email.md @@ -6,7 +6,7 @@ For administrator-facing configuration (keys, override variables, precedence), s Primary files: - [email.py](../../../../../plugins/lookup/email.py) for the plugin. -- [test_email.py](../../../../../tests/unit/plugins/lookup/test_email.py) for unit tests. +- [test_email.py](../../../../../tests/unit/python/plugins/lookup/test_email.py) for unit tests. ## Call Shapes 📞 diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index 19452dd1bb..3ac1b7c16e 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -14,7 +14,7 @@ All role-owned metadata lives under `roles//meta/.yml`. | `meta/volumes.yml` | Compose volumes. File root IS the volumes map keyed by volume name. No `compose:` and no `volumes:` wrapper. | | `meta/addons/.yml` | Optional. One file per addon (file root IS the addon spec; filename stem = addon id). See [Unified Addons](#unified-addons-metaaddons-) below. | | `meta/users.yml` | Role-local user definitions. File root IS the users map (no `users:` wrapper). | -| `meta/schema.yml` | Credential schema definitions and runtime credential values. | +| `meta/secrets.yml` | Credential schema definitions and runtime credential values. | | `meta/info.yml` | Optional. Descriptive role-level metadata (`logo`, `homepage`, `video`, `display`). File root IS `applications..info` (no `info:` wrapper). | | `meta/variants.yml` | Optional. Variant overrides deep-merged over the assembled application payload (used by `svc-ai-ollama`, `web-app-phpmyadmin`). | @@ -23,7 +23,7 @@ Every other `meta/.yml` is read by the project's own loaders (`utils/cach ## File-Root Convention 🧷 -Every `meta/.yml` (except `meta/main.yml`, which keeps Galaxy semantics, and `meta/schema.yml`, which is processed by `apply_schema()`) follows the rule: +Every `meta/.yml` (except `meta/main.yml`, which keeps Galaxy semantics, and `meta/secrets.yml`, which is processed by `apply_schema()`) follows the rule: > **The file's content IS the value of `applications..`. There is NO wrapping key matching the filename.** @@ -42,7 +42,11 @@ The paths are: | `meta/volumes.yml.` | `volumes.` | | `meta/services.yml...<…>` | `services...<…>` | -`credentials.*` paths are populated by `apply_schema()` at `applications..credentials.<…>`. +| `meta/secrets.yml.credentials.` | `secrets.credentials.` | + +`secrets.credentials.*` paths are populated by `apply_schema()` at +`applications..secrets.credentials.<…>`, so the credential file obeys the +same file-root rule as every other `meta/.yml`. ## Services Inlining Rule 📥 @@ -72,9 +76,9 @@ matomo: data: matomo_data ``` -## Schema Format: `meta/schema.yml` 🗝️ +## Schema Format: `meta/secrets.yml` 🗝️ -`meta/schema.yml` consolidates two structures under the `credentials:` top-level key: +`meta/secrets.yml` consolidates two structures under the `credentials:` top-level key: 1. The credential **schema definitions** (flat keys, e.g. `alerting_telegram_bot_token: { description, algorithm, validation }`). 2. The credential **runtime values** (nested keys, e.g. `recaptcha.key`, `recaptcha.secret`). @@ -88,10 +92,10 @@ The unified schema supports: - `default:` values are **NOT validated.** `validation:` only applies to user-provided values, so the schema default is exempt. - When `default:` is present, the credential generator MUST NOT generate a new value via `algorithm:`. It writes the literal `default:` string verbatim. -### Worked Example: runtime credentials in `meta/schema.yml` +### Worked Example: runtime credentials in `meta/secrets.yml` ```yaml -# roles/web-app-keycloak/meta/schema.yml +# roles/web-app-keycloak/meta/secrets.yml credentials: recaptcha: key: @@ -107,7 +111,7 @@ credentials: Flat schema entries keep the same shape: ```yaml -# roles/web-app-prometheus/meta/schema.yml +# roles/web-app-prometheus/meta/secrets.yml credentials: alerting_telegram_bot_token: description: "Telegram bot token for Alertmanager notifications." @@ -344,10 +348,10 @@ config: {} # optional, opaque, role-interpreted runtime payload | `version` | no | string | `""` | A pin MUST be a quoted string, never an unquoted number. `""` tracks the app default. | | `group` | no | string | — | Free grouping label (e.g. Odoo `core`/`optional`). MUST NOT affect enablement. | | `update` | no | map | — | `monitored` (bool, default `false`), `catalog` (a supported adapter), `upstream_id` (defaults to the addon id). | -| `config` | no | map | — | Opaque, role-interpreted runtime payload. Lint does not constrain its inner shape beyond requiring a mapping. Secrets inside `config` MUST resolve through `lookup('config', application_id, 'credentials.')` and MUST NOT be inlined literally. | +| `config` | no | map | — | Opaque, role-interpreted runtime payload. Lint does not constrain its inner shape beyond requiring a mapping. Secrets inside `config` MUST resolve through `lookup('config', application_id, 'secrets.credentials.')` and MUST NOT be inlined literally. | -Any credential an addon needs is declared in `meta/schema.yml` `credentials:` -and read via `lookup('config', application_id, 'credentials.')`. There +Any credential an addon needs is declared in `meta/secrets.yml` `credentials:` +and read via `lookup('config', application_id, 'secrets.credentials.')`. There is no new secret store. ### Bridges: in-repo dependency vs network bridge diff --git a/docs/contributing/design/variants.md b/docs/contributing/design/variants.md index 32bde60be3..fc018bece1 100644 --- a/docs/contributing/design/variants.md +++ b/docs/contributing/design/variants.md @@ -17,7 +17,7 @@ The development deploy CLI uses a **folder-per-round model** that splits cleanly 5. **Cleanup between rounds.** Before each non-first iteration the wrapper runs [entity.sh](../../../scripts/tests/deploy/local/purge/entity.sh) for **every** app in the previous round's include set. The next round therefore boots from an empty host, which guarantees cross-round state coherence: nothing the previous round deployed (whether it stays in the current round's closure or falls out) can leak into round R, so variants are free to disagree on which deps they pull in. The final round is followed by no purge so the last state remains available for inspection or follow-up specs. 6. **`--full-cycle` (async update pass).** When set (or `full_cycle=true` on `make compose-deploy`), the wrapper runs each round's deploy TWICE: first the regular sync pass, then immediately a second pass with `-e ASYNC_ENABLED=true` overriding the host_var, against the SAME variant's folder, BEFORE moving to the next round. The two passes are therefore always co-located on the same host state; the async pass never accidentally targets a host that a previous round's variant left behind. 7. **Pinning rounds (single or bundle).** Both init and deploy accept `--variant ` (same semantics as the `variant=` make arg): a single index (`1`) pins one round, a comma-separated list (`0,1,2`) iterates that subset, and empty/unset is the full matrix. When the selection is a single round no inter-round cleanup runs (no previous round to diff against); out-of-range indices raise a clean error. The `make compose-deploy mode=update` flows honour the same `variant=` arg by suffixing `INFINITO_INVENTORY_DIR` / `INFINITO_INVENTORY_FILE` to `-` (single index), so a redeploy can target one specific variant without iterating the full matrix. -8. **CI runner-split.** The deploy-matrix discovery ([bundles.py](../../../utils/github/variant/bundles.py), wired via [output_apps.sh](../../../scripts/github/resolve/output_apps.sh)) splits any role with more than `INFINITO_VARIANT_BUNDLE_SIZE` (default 3) variants into bundles of consecutive indices — one matrix entry (runner) per bundle, e.g. a 5-variant role becomes `0,1,2` + `3,4`. Each runner receives its slice through the `variant` env (consumed by `--variant`) and runs every variant in its bundle to completion (no time-based cutting). +8. **CI runner-split.** The deploy-matrix discovery ([axes.py](../../../utils/github/variant/axes.py), wired via [output_apps.sh](../../../scripts/github/resolve/output_apps.sh)) gives every variant its own matrix entry (runner): a 5-variant role becomes five rows `0`…`4`, each carrying the deploy mode and tor state the sweep rotation assigned it. Each runner receives its variant through the `variant` env (consumed by `--variant`). Which rows a given run deploys is decided by the chunker ([chunks.py](../../../cli/meta/ci/chunks.py)), not by bundling. The in-play loader (`utils.cache.applications.get_merged_applications`) uses each role's variant-free base config (the assembled `meta/.yml` payload) as the default and lets the inventory's `applications.` overrides win via deep merge: the inventory itself is the source of truth for what variant a round runs against. Variant 0 enumerates every dynamic service-key from `meta/services.yml` with `enabled: true, shared: true` so the "all flags on" baseline is explicit and deep-merge with a non-baseline override yields the expected variant-N shape (see [variants.md](../artefact/files/role/variants.md) for the file-format rule and [test_non_baseline_explicit_disables.py](../../../tests/integration/roles/meta/variants/test_non_baseline_explicit_disables.py) for the lint guard). @@ -34,7 +34,7 @@ The dev-deploy CLI threads the variant index through three layers so a variant's 2. The provision CLI parses the JSON and forwards the per-app index as `--variant ` to each `infinito administration inventory credentials` subprocess call. 3. `InventoryManager` resolves the root role's config via `get_variants(roles_dir)[app_id][N]` so `resolve_schema_includes_recursive` sees the variant-merged `services` map and discovers every shared provider the variant enables. -The resulting snippets cover every shared provider in the variant's closure, so the deploy stage finds the required `applications..credentials` block in the inventory and `lookup('config', 'credentials', '')` succeeds. +The resulting snippets cover every shared provider in the variant's closure, so the deploy stage finds the required `applications..secrets.credentials` block in the inventory and `lookup('config', '', 'secrets.credentials.')` succeeds. The variant only affects inventory generation; the Ansible deploy itself reads `applications.` overrides from the variant-resolved inventory and MUST NOT consult variant data at runtime. @@ -66,9 +66,9 @@ Apps without a `meta/variants.yml` file collapse to a single empty overlay in `_ | [init.py](../../../cli/administration/deploy/development/init.py) | Dev CLI entry that drives `build_dev_inventory_matrix` to materialise `-` folders. | | [deploy/cli.py](../../../cli/administration/deploy/development/deploy/cli.py) | Dev CLI entry that re-derives the matrix plan and iterates one deploy per folder, with per-app cleanup between rounds. | | [entity.sh](../../../scripts/tests/deploy/local/purge/entity.sh) | Cleanup script invoked between rounds for every app in the previous round's include set. | -| [test_variants.py](../../../tests/unit/utils/cache/test_variants.py) | Unit tests covering parser edge cases, deep-merge semantics, caching, and the variant-zero default path. | -| [tests/.../inventory/](../../../tests/unit/cli/administration/deploy/development/inventory/__init__.py) | Unit-test package mirroring the source split: [`test_spec.py`](../../../tests/unit/cli/administration/deploy/development/inventory/test_spec.py), [`test_payload.py`](../../../tests/unit/cli/administration/deploy/development/inventory/test_payload.py), [`test_planner.py`](../../../tests/unit/cli/administration/deploy/development/inventory/test_planner.py), [`test_builder.py`](../../../tests/unit/cli/administration/deploy/development/inventory/test_builder.py). | -| [test_matrix_deploy.py](../../../tests/unit/cli/administration/deploy/development/test_matrix_deploy.py) | Wrapper-level tests covering the per-round folder iteration and cleanup logic. | +| [test_variants.py](../../../tests/unit/python/utils/cache/test_variants.py) | Unit tests covering parser edge cases, deep-merge semantics, caching, and the variant-zero default path. | +| [tests/.../inventory/](../../../tests/unit/python/cli/administration/deploy/development/inventory/__init__.py) | Unit-test package mirroring the source split: [`test_spec.py`](../../../tests/unit/python/cli/administration/deploy/development/inventory/test_spec.py), [`test_payload.py`](../../../tests/unit/python/cli/administration/deploy/development/inventory/test_payload.py), [`test_planner.py`](../../../tests/unit/python/cli/administration/deploy/development/inventory/test_planner.py), [`test_builder.py`](../../../tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py). | +| [test_matrix_deploy.py](../../../tests/unit/python/cli/administration/deploy/development/test_matrix_deploy.py) | Wrapper-level tests covering the per-round folder iteration and cleanup logic. | | [cli.py (provision)](../../../cli/administration/inventory/provision/cli.py) | Parses `--app-variants ` and forwards the per-app variant index to `generate_credentials_for_roles`. | | [credentials_generator.py](../../../cli/administration/inventory/provision/credentials_generator.py) | Issues one credentials subprocess per app, appending `--variant ` when the app's variant is set. | | [credentials/](../../../cli/administration/inventory/credentials/__main__.py) | `InventoryManager`-backed credential generator; `--variant N` selects which `variants.yml` overlay applies. | diff --git a/docs/contributing/environment/cache.md b/docs/contributing/environment/cache.md index 1b4b5bd5bc..d7fabe358a 100644 --- a/docs/contributing/environment/cache.md +++ b/docs/contributing/environment/cache.md @@ -23,7 +23,7 @@ Pulls only. Pushes are not intercepted. | `rubygems` | `gem-proxy` | `rubygems.org` | | `go` | `go-proxy` | `proxy.golang.org` | | `helm` | `helm-bitnami` | `charts.bitnami.com/bitnami` | -| `yum` | `yum-rocky`, `yum-fedora` | `download.rockylinux.org`, `dl.fedoraproject.org` | +| `yum` | `yum-rocky`, `yum-fedora` | `download.rockylinux.org`, `download.fedoraproject.org` | | `raw` | `raw-githubusercontent`, `raw-codeload-github`, `raw-packagist`, `raw-alpine` | `raw.githubusercontent.com`, `codeload.github.com`, `repo.packagist.org`, `dl-cdn.alpinelinux.org` | A proxy repo that holds a cached copy serves it when its remote is unreachable, regardless of `metadataMaxAge` (measured). `autoBlock` is therefore off: while a remote is auto-blocked Nexus answers `404 Remote Auto Blocked` instead of falling back to that cached copy. The mirror repos below only come into play when nothing is cached either. @@ -45,7 +45,7 @@ Cert generation runs in a throw-away alpine container driven by [package-fronten ## Activation 🎚️ -The `cache` decision is exposed via `Profile.registry_cache_active()` in [profile.py](../../../cli/administration/deploy/development/profile.py). When active: +The `cache` decision is exposed via `Profile.cache_stack_enabled()` in [profile.py](../../../cli/administration/deploy/development/profile.py). When active: - [compose/cache.override.yml](../../../compose/cache.override.yml) is layered on top of the base [compose.yml](../../../compose.yml) by [compose.py](../../../cli/administration/deploy/development/compose.py) and [down.py](../../../cli/administration/deploy/development/down.py) via [common.py](../../../cli/administration/deploy/development/common.py)`compose_file_args`. - The cache services are added. @@ -78,7 +78,7 @@ The HTTPS-only inner-build gap requires per-image CA-trust bootstrap, which is o ## Compose Wrapper Auto-Detection 🪄 -The runner's `compose` wrapper at [roles/sys-svc-compose/files/compose.py](../../../roles/sys-svc-compose/files/compose.py) auto-detects compose files when invoked from per-app directories under `/opt/compose//`: +The runner's `compose` wrapper at [roles/sys-svc-compose/files/python/compose.py](../../../roles/sys-svc-compose/files/python/compose.py) auto-detects compose files when invoked from per-app directories under `/opt/compose//`: | File | When | |---|---| @@ -87,7 +87,7 @@ The runner's `compose` wrapper at [roles/sys-svc-compose/files/compose.py](../.. | `compose.ca.override.yml` | when present (TLS self-signed CA-inject runs) | | `compose.cache.override.yml` | generated on the fly when `INFINITO_CACHE_PACKAGE_FRONTEND_IP` is set; emits `build.extra_hosts` for every service that has a `build:` key | -[pull.py](../../../roles/sys-svc-compose/files/pull.py) delegates to the same wrapper so `pull` and `build --pull` operations see the identical `-f` set. +[pull.py](../../../roles/sys-svc-compose/files/python/pull.py) delegates to the same wrapper so `pull` and `build --pull` operations see the identical `-f` set. ## Environment Variables 🌳 @@ -119,7 +119,7 @@ When a new package manager or upstream needs caching: 2. If the upstream uses HTTPS, add it to `HOSTNAMES` in [package-frontend-certs.sh](../../../scripts/docker/cache/package-frontend/certs.sh) so a leaf cert is issued. 3. Add a server-block in [upstreams.conf](../../../compose/package-cache-frontend/upstreams.conf) that reverse-proxies onto the new Nexus repo path (rewrite if upstream URL prefix differs from the Nexus repo path). 4. Add an `extra_hosts` entry on the `infinito` service in [compose/cache.override.yml](../../../compose/cache.override.yml) for runner-side traffic. -5. If the upstream is HTTP-only and inner-`dockerd` builds need it, also add it to `_CACHE_HTTP_HOSTNAMES` in [compose.py](../../../roles/sys-svc-compose/files/compose.py) so the per-app `compose.cache.override.yml` includes it in `build.extra_hosts`. +5. If the upstream is HTTP-only and inner-`dockerd` builds need it, also add it to `_CACHE_HTTP_HOSTNAMES` in [compose.py](../../../roles/sys-svc-compose/files/python/compose.py) so the per-app `compose.cache.override.yml` includes it in `build.extra_hosts`. ## Background 📚 diff --git a/docs/contributing/environment/setup.md b/docs/contributing/environment/setup.md index 49e6c8a8cb..92bc1c12da 100644 --- a/docs/contributing/environment/setup.md +++ b/docs/contributing/environment/setup.md @@ -60,7 +60,7 @@ make environment-teardown ### Full Development Flow 🔁 -The repository already contains a modular environment test suite at [scripts/tests/environment/](../../../scripts/tests/environment/README.md). The commands from that suite are explained here as the intended end-to-end flow. +The repository already contains a modular environment test suite at [scripts/tests/workspace/](../../../scripts/tests/workspace/README.md). The commands from that suite are explained here as the intended end-to-end flow. #### Flow Summary 📋 diff --git a/docs/contributing/tools/agents/cheatsheet.md b/docs/contributing/tools/agents/cheatsheet.md index 6a4ad7389d..2456f72e73 100644 --- a/docs/contributing/tools/agents/cheatsheet.md +++ b/docs/contributing/tools/agents/cheatsheet.md @@ -25,10 +25,12 @@ from its procedure file. Run `make install-skills` to (re)install them. | Writing or updating a Playwright spec for a `web-*` role | `i8-iterate-playwright` | | Running or validating tests for a specific scope | `i8-test` | | Running the quality gate (`make quality`) to green | `i8-quality` | +| Running the full gate (`make quality-high`: quality plus every lint) to green | `i8-quality-high` | | Cleaning up code, docs, or roles after a change | `i8-refactor` | | 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` | +| Pulling a sibling feature branch and merging it into the current one | `i8-merge-sibling` | | Staged changes are ready to be committed | `i8-commit` | | A branch is ready to be opened as a pull request | `i8-pull-request` | | Pushing a branch through the manual-CI draft → ready-for-review cycle | `i8-push-trigger-pull` | diff --git a/docs/contributing/tools/github/actions/configuration.md b/docs/contributing/tools/github/actions/configuration.md index 361fcc1162..e6d8cd29e8 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -8,46 +8,26 @@ Repository variables are set under **Settings → Secrets and variables → Acti | Variable | Workflow | Default (unset) | Set to activate | |---|---|---|---| -| `CI_CANCEL_IN_PROGRESS` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml), [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml) | Cancels in-progress runs on new push | `false` to keep in-progress runs alive | | `CI_SYNC_MAIN_SOURCE_REPOSITORY` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Syncs `main` from `infinito-nexus/core` before CI scope discovery | `/` to use another source, or `false`, empty, or the current repository to skip | | `CI_RUN_ON_MAIN` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Pushes to `main` skip CI | `true` to run CI on `main` pushes too | | `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml) | Update jobs skipped; Dependabot PRs auto-closed | `true` to allow update PRs (workflow-driven and Dependabot) | -| `INFINITO_PLAYWRIGHT_KEEP` | [call-test-deploy-compose.yml](../../../../../.github/workflows/call-test-deploy-compose.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included) | -| `CI_RERUN_INTERVAL_MINUTES` | [cron-rerun-cancelled.yml](../../../../../.github/workflows/cron-rerun-cancelled.yml) | Sweeps for cancelled runs every full hour | Minutes between two sweeps, rounded up to whole hours | -| `CI_RERUN_MAX_ATTEMPTS` | [cron-rerun-cancelled.yml](../../../../../.github/workflows/cron-rerun-cancelled.yml) | Revives a run however often it is cancelled | Attempt count at which a run is left alone; `0` for no ceiling | -| `CI_RERUN_MAX_AGE_HOURS` | [cron-rerun-cancelled.yml](../../../../../.github/workflows/cron-rerun-cancelled.yml) | Ignores runs untouched for more than 24 hours | Age in hours beyond which a cancelled run is left alone | +| `INFINITO_PLAYWRIGHT_KEEP` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included) | -## `CI_CANCEL_IN_PROGRESS` 🛑 +## Cancelling in-progress runs 🛑 -Controls whether a new run cancels an already-running CI pipeline on the same ref. Applies to the push entry workflow and to the orchestrator's own concurrency group, which every entry workflow shares. The manual entry workflow overrides the variable on both levels: its own group is `cancel-in-progress: true`, and it passes `force_cancel_in_progress: true` into the orchestrator. - -**Default behaviour (variable not set or set to any value other than `false`):** -In-progress runs are cancelled when a new push arrives. This is the recommended setting for most workflows. - -**To disable cancellation:** - -1. Open the repository on GitHub. -2. Go to **Settings → Secrets and variables → Actions**. -3. Switch to the **Variables** tab. -4. Click **New repository variable**. -5. Set **Name** to `CI_CANCEL_IN_PROGRESS` and **Value** to `false`. -6. Save. - -**To re-enable cancellation:** - -Delete the variable or change its value to anything other than `false` (e.g. `true`). - -**How it works:** +Not a variable: cancellation is derived from the trigger. Every automatic run on a branch other than `main` is cancelled by a newer run in the same concurrency group; automatic runs on `main` are not, because a half-finished pipeline on the default branch is worse than a queued one. A manual dispatch always supersedes, `main` included: someone typed it, so it is the intent that counts, not the ref. ```yaml -cancel-in-progress: ${{ vars.CI_CANCEL_IN_PROGRESS != 'false' }} +cancel-in-progress: ${{ github.ref_name != 'main' }} ``` -| Variable value | Expression result | Behaviour | -|---|---|---| -| *(not set / empty)* | `'' != 'false'` → `true` | Cancels in-progress runs ✓ | -| `false` | `'false' != 'false'` → `false` | Does **not** cancel ✓ | -| `true` | `'true' != 'false'` → `true` | Cancels in-progress runs ✓ | +`entry-push-latest.yml` declares exactly that expression, and it fires only on `push`, where `github.ref_name` is always the pushed branch. [entry-cancel-superseded.yml](../../../../../.github/workflows/entry-cancel-superseded.yml) carries no concurrency group of its own — it is the API fallback for that group — but its push job repeats the same predicate as a job `if`, so it never touches `main` either. + +> ⚠️ **Do not paste that expression into a workflow that listens on `pull_request_target`.** There `github.ref` is the *base* branch, so `github.ref_name` is literally `main` and the rule collapses to a constant `false` — every pull request would stop cancelling its predecessor. `entry-pr-change-orchestrate.yml` therefore declares `cancel-in-progress: true` outright. + +[call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml) compares `github.ref` for the same reason: a called workflow inherits the caller's ref, which is `refs/pull//merge` for a `pull_request` caller but `refs/heads/main` for a `pull_request_target` one. The `ci-orchestrator` job of `entry-pr-change-orchestrate.yml` is fenced to `github.event_name == 'pull_request'`, so the ref the orchestrator sees from that caller is always the merge ref; widening that fence would silently put fork runs into main's group. + +`entry-manual-steer.yml` declares `cancel-in-progress: true` outright on its own group, and the orchestrator reads `github.event_name` — which a called workflow inherits from its caller — so a manual sweep supersedes on both levels without an input to pass down. ## `CI_SYNC_MAIN_SOURCE_REPOSITORY` 🔄 @@ -154,7 +134,7 @@ Dependabot cannot read repository variables itself, so [entry-pr-open-dependabot ## `INFINITO_PLAYWRIGHT_KEEP` 🎬 -Controls whether Playwright keeps trace, screenshot, and video for every test or only for failing tests in the compose deploy-test workflow ([call-test-deploy-compose.yml](../../../../../.github/workflows/call-test-deploy-compose.yml)). +Controls whether Playwright keeps trace, screenshot, and video for every test or only for failing tests in the deploy-test workflow ([call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml)). For the full propagation chain, the inventory override, and the local equivalents, see [Playwright Tests](../../../actions/testing/playwright.md#artefact-retention-). **Default behaviour (variable not set or set to any value other than `true`):** @@ -186,27 +166,3 @@ INFINITO_PLAYWRIGHT_KEEP: ${{ vars.INFINITO_PLAYWRIGHT_KEEP }} | *(not set / empty)* | Trace / screenshot / video kept only on failure ✓ | | `true` | Trace / screenshot / video kept for every test ✓ | | any other value | Trace / screenshot / video kept only on failure ✓ | - -## `CI_RERUN_*` 🔁 - -Three variables tune [cron-rerun-cancelled.yml](../../../../../.github/workflows/cron-rerun-cancelled.yml), the sweep that restarts the failed jobs of a branch whose latest run was cancelled. - -| Variable | Unset | Effect when set | -|---|---|---| -| `CI_RERUN_INTERVAL_MINUTES` | `60` | Minutes between two sweeps | -| `CI_RERUN_MAX_ATTEMPTS` | `0` | A run at or above this attempt count is left alone; `0` means no ceiling, a run is revived however often it is cancelled | -| `CI_RERUN_MAX_AGE_HOURS` | `24` | A run untouched for longer than this is left alone, so a sweep does not resurrect abandoned branches | - -**How the interval works:** - -A cron expression cannot read a repository variable, so the workflow is triggered every full hour and a gate lets only the hours that open the configured window through: - -```yaml -INTERVAL_MINUTES: ${{ vars.CI_RERUN_INTERVAL_MINUTES || '60' }} -``` - -The interval is rounded up to whole hours and counted from 00:00 UTC, so `60` sweeps every hour, `180` at 00:00, 03:00, 06:00 and so on, and `1440` once a day at 00:00. One hour is the floor: anything below it sweeps hourly. Anything above 24 hours collapses to a daily sweep. Manual dispatch skips the gate entirely and always sweeps. - -The gate reads the hour, not the minute, so a scheduled run that GitHub starts a few minutes late still counts for its hour. - -**On the missing ceiling:** with `CI_RERUN_MAX_ATTEMPTS` unset, a run that is cancelled again after every revival is revived again, indefinitely. `CI_RERUN_MAX_AGE_HOURS` does not bound this, because each new attempt refreshes the run's `updatedAt` and so keeps it inside the age window. Set the variable to a positive number if a run should eventually be given up on. diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index d917c0e6b9..ad9c4ff858 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -26,8 +26,9 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| | [entry-pr-change-orchestrate.yml](../../../../../.github/workflows/entry-pr-change-orchestrate.yml): `🔀 Pull Request` | Detects PR scope from changed files + branch prefix, then conditionally calls the orchestrator. A maintainer `🛡️ Trusted` label builds the privileged images from the PR head — see [pipeline.md](../../../artefact/git/pipeline.md#trusted-fork-prs-). A `🧩 Subset` label pins the deploy matrix to the roles listed in the PR body — see [pipeline.md](../../../artefact/git/pipeline.md#subset-label-). | auto (`pull_request` & `pull_request_target`: opened, synchronize, reopened, ready_for_review, labeled) | none | -| [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml): `📤 Push` | Syncs `main` from the configured source repository, then runs the orchestrator on pushes to `main`, `feature/**`, `hotfix/**`, `fix/**`, `chore/**`, `alert-autofix-*`; on tagged `main` it also calls `call-release-version.yml`. Respects the `CI_CANCEL_IN_PROGRESS`, `CI_SYNC_MAIN_SOURCE_REPOSITORY`, and `CI_RUN_ON_MAIN` repository variables, see [configuration.md](configuration.md). | auto (`push`) | none | -| [entry-manual-steer.yml](../../../../../.github/workflows/entry-manual-steer.yml): `🕹️ Manual` | Manual dispatch of the full orchestrator for a chosen distro set and app whitelist. The `whitelist` input accepts the `__ALL__` sentinel for forced full deploy; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). | manual | `distros` (default `debian`), `whitelist` (optional; `__ALL__` forces full deploy, empty triggers diff derivation, any other value is verbatim), `lifecycles`, `modes` (default `swarm compose`), `priority` (optional; priority line first, regular line runs the rest after it succeeds) | +| [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml): `📤 Push` | Syncs `main` from the configured source repository, then runs the orchestrator on pushes to `main`, `feature/**`, `hotfix/**`, `fix/**`, `update/**`, `chore/**`, `alert-autofix-*`; on tagged `main` it also calls `call-release-version.yml`. Respects the `CI_SYNC_MAIN_SOURCE_REPOSITORY` and `CI_RUN_ON_MAIN` repository variables, see [configuration.md](configuration.md). | auto (`push`) | none | +| [entry-manual-steer.yml](../../../../../.github/workflows/entry-manual-steer.yml): `🕹️ Manual` | Manual dispatch of the full orchestrator for a chosen app whitelist. The `whitelist` input accepts the `__ALL__` sentinel for forced full deploy; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). | manual | `distros` (optional; empty spreads the rows over every declared distro), `filesystem` (optional; empty spreads them over `zfs`, `btrfs`, `ext4`), `whitelist` (optional; `__ALL__` forces full deploy, empty triggers diff derivation, any other value is verbatim), `lifecycles`, `mode` (default `auto`), `priority` (optional; priority rows get chunks of their own, the regular chunks run after them), `offset` (default `0`; a row count or a selection token naming where the regular line resumes), `chunk_gate` (default `true`), `sweep` (optional; empty means the run number) | +| [entry-cancel-superseded.yml](../../../../../.github/workflows/entry-cancel-superseded.yml): `🚫 Cancel: Superseded Runs` | Cancels the runs superseded by a newer one on the same branch or PR via the API, for the case where the concurrency group fails to reap its occupant and the newer run parks on `pending` behind it — see [cancel/README.md](../../../../../scripts/github/cancel/README.md). Carries no concurrency group of its own, otherwise it would queue behind the run it has to free, and only touches the workflows that share the group it backs up. The push job skips `main` like the `global-ci-*` group it backs up, see [configuration.md](configuration.md). | auto (`push` except `main`, `pull_request_target`: opened, synchronize, reopened, ready_for_review, labeled) | none | | [entry-pr-closed-cancel-workflows.yml](../../../../../.github/workflows/entry-pr-closed-cancel-workflows.yml): `🚫 Cancel: PR Runs on Close` | Cancels active workflow runs for a PR when it is closed or converted to draft. | auto (`pull_request_target`: closed, converted_to_draft) | none | | [entry-delete-branch.yml](../../../../../.github/workflows/entry-delete-branch.yml): `🚫 Cancel: Runs on Branch Delete` | Enters the push-entry concurrency group for the deleted branch so that any in-flight run on it is cancelled; a fallback step cancels remaining runs via the API. | auto (`delete`) | none | @@ -35,13 +36,13 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| -| [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml): `🎵 CI: Orchestrator` | Central coordinator. Runs fork-prereq wait, security, linting, CI image build, code tests, code-quality gate, DNS tests, mirror, deploy tests (optionally split into a priority line and a regular line via `priority`; each mode's discover job renders its own plan table via `cli.meta.ci.plan` into the run summary), install tests, `test-workspace`, `test-instructions`, final `done` gate. | reusable | `distros` (required), `whitelist` (optional), `priority` (optional; app ids deployed first per mode, then excluded from the regular line, which only starts after every priority job succeeded), `image_wait_attempts` (default `1980`), `image_wait_sleep_seconds` (default `10`), `workspace` (default `auto`), `instructions` (default `auto`) | +| [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml): `🎵 CI: Orchestrator` | Central coordinator. Runs fork-prereq wait, security, linting, CI image build, code tests, code-quality gate, DNS tests, mirror, deploy tests as a serial chain of chunk blocks (each chunk's discover job renders the sweep's plan table via `cli.meta.ci.plan` into the run summary), install tests, `test-workspace`, `test-instructions`, final `done` gate. | reusable | `distros` (optional; empty spreads the rows over every declared distro), `filesystem` (optional; empty spreads them over `zfs`, `btrfs`, `ext4`), `whitelist` (optional), `priority` (optional; app ids sorted to the head of the list and cut into chunks of their own, so every priority row is deployed before the first regular one starts, and deployed in every combination it can take: each variant × each offered mode × Tor and clearnet, in one sweep), `mode` (default `auto`), `sweep`, `resume_from_chunk` (default `0`), `chunk_gate` (default `true`), `image_wait_attempts` (default `1980`), `image_wait_sleep_seconds` (default `10`), `workspace` (default `auto`), `instructions` (default `auto`) | ### Security and linting 🛡️🔍 | Workflow | Description | Trigger | Inputs | |---|---|---|---| -| [cron-security-codeql.yml](../../../../../.github/workflows/cron-security-codeql.yml): `⏰ Scan: CodeQL (Advanced)` | CodeQL static analysis. Invoked by [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml) so every CI run produces a single scan; additionally runs on a weekly cron so coverage does not drop when no pushes land on `main`. See [pipeline.md](../../../artefact/git/pipeline.md) for the gating behaviour. | reusable, auto (`schedule`: weekly Mon 00:00 UTC) | none | +| [cron-security-codeql.yml](../../../../../.github/workflows/cron-security-codeql.yml): `🔐 Scan with CodeQL` | CodeQL static analysis. Invoked by [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml) so every CI run produces a single scan; additionally runs on a weekly cron so coverage does not drop when no pushes land on `main`. See [pipeline.md](../../../artefact/git/pipeline.md) for the gating behaviour. | reusable, auto (`schedule`: weekly Mon 00:00 UTC) | none | | [call-lint.yml](../../../../../.github/workflows/call-lint.yml): `🧹 Lint` | Runs `make lint` (every lint check in parallel: action, ansible, javascript, makefile, markdown, mermaid, packages, playwright, python, shellcheck) plus a hadolint SARIF job on `Dockerfile`. | reusable, manual | none | ### CI images 🐳 @@ -49,15 +50,15 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| | [call-images-build-ci.yml](../../../../../.github/workflows/call-images-build-ci.yml): `🖼️ Build: CI Images (all distros)` | Builds the per-distro CI base images consumed by all test jobs. | reusable | `distros` (required), `checkout_ref` (optional), `image_tag` (default `ci-${github.sha}`), `concurrency_channel` (default `default`) | -| [cron-images-cleanup-ci.yml](../../../../../.github/workflows/cron-images-cleanup-ci.yml): `⏰ Images: Cleanup CI (GHCR)` | Deletes CI images from GHCR older than N days. | auto (`schedule`: weekly Mon 00:00 UTC), manual | `days` (default `7`) | +| [cron-images-cleanup-ci.yml](../../../../../.github/workflows/cron-images-cleanup-ci.yml): `🧹 Prune CI images` | Deletes CI images from GHCR older than N days. | auto (`schedule`: weekly Mon 00:00 UTC), manual | `days` (default `7`) | ### Image mirroring 🪞 | Workflow | Description | Trigger | Inputs | |---|---|---|---| | [call-images-mirror-missing.yml](../../../../../.github/workflows/call-images-mirror-missing.yml): `🪞 Mirror: Docker Hub → GHCR (only missing)` | Mirrors only the upstream images that are not yet in GHCR. Called from the orchestrator before deploy tests. | reusable | `ghcr_namespace`, `ghcr_prefix` (default `mirror`), `repo_root` (default `.`), `source_repository`, `source_ref`, plus throttling knobs | -| [cron-images-mirror-all.yml](../../../../../.github/workflows/cron-images-mirror-all.yml): `⏰ Mirror: Docker Hub → GHCR` | Full nightly mirror of every referenced upstream image into GHCR. | auto (`schedule`: daily 00:00 UTC), manual | `ghcr_namespace`, `ghcr_prefix` (default `mirror`), `repo_root` (default `.`), `images_per_hour` (throttle) | -| [entry-manual-mirror-cleanup.yml](../../../../../.github/workflows/entry-manual-mirror-cleanup.yml): `🧹 Images: Cleanup GHCR (Private)` | Deletes GHCR mirror packages by prefix and visibility. Supports `dry_run`. | manual | `ghcr_namespace`, `ghcr_prefix` (default `mirror`), `visibility` (`private`/`public`/`internal`, default `private`), `dry_run` | +| [cron-images-mirror-all.yml](../../../../../.github/workflows/cron-images-mirror-all.yml): `🪞 Mirror all images` | Full nightly mirror of every referenced upstream image into GHCR. | auto (`schedule`: daily 00:00 UTC), manual | `ghcr_namespace`, `ghcr_prefix` (default `mirror`), `repo_root` (default `.`), `images_per_hour` (throttle) | +| [entry-manual-mirror-cleanup.yml](../../../../../.github/workflows/entry-manual-mirror-cleanup.yml): `🧹 Images: Cleanup GHCR` | Deletes GHCR mirror packages by prefix and visibility. Supports `dry_run`. | manual | `ghcr_namespace`, `ghcr_prefix` (default `mirror`), `visibility` (`private`/`public`/`internal`, default `private`), `dry_run` | ### Code tests 🧪 @@ -70,10 +71,7 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| | [call-test-dns.yml](../../../../../.github/workflows/call-test-dns.yml): `💬 Test: DNS` | Validates DNS resolution across target distributions. | reusable, manual | `distros` (required on call; default `debian` on manual) | -| [call-test-deploy-single-node.yml](../../../../../.github/workflows/call-test-deploy-single-node.yml): `🏝️ Test: Deploy (single-node)` | Single point of truth for the non-swarm deploy tests: fans out to `call-test-deploy-compose.yml` and `call-test-deploy-host.yml`, gated per mode via the `modes` input. Called from the orchestrator. | reusable | `distros` (required), `whitelist`, `lifecycles`, `modes` (default `compose host`), `blacklist` (optional; app ids dropped from discovery) | -| [call-test-deploy-compose.yml](../../../../../.github/workflows/call-test-deploy-compose.yml): `📦 Test: Deploy (compose)` | Deploy test (compose mode) across all deployment types (`INFINITO_DISCOVER_ALL`; lifecycle-filtered to the `INFINITO_LIFECYCLES` envelope, so `server`/`universal`/`workstation` scopes but not just `web-*`). When `whitelist` is empty, the discover job derives one from the branch's diff vs `origin/main`; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). | reusable | `distros` (required), `whitelist` (optional; explicit value wins over diff), `lifecycles`, `blacklist` (optional) | -| [call-test-deploy-host.yml](../../../../../.github/workflows/call-test-deploy-host.yml): `🖥️ Test: Deploy (host)` | Deploy test (host mode) for invokable non-stack roles that configure the host instead of shipping a container stack. Same diff-driven whitelist resolution as `call-test-deploy-compose.yml`; no Playwright stage (host roles have no web UI). | reusable | `distros` (required), `whitelist` (optional; explicit value wins over diff), `lifecycles`, `blacklist` (optional) | -| [call-test-deploy-swarm.yml](../../../../../.github/workflows/call-test-deploy-swarm.yml): `🐝 Test: Deploy (swarm)` | Deploy test (swarm mode) across the full application matrix; each app gets a simulated 3-node DinD cluster with an NFS server, then a drain/reschedule state-survival assertion. Same diff-driven whitelist resolution as `call-test-deploy-compose.yml`. | reusable, manual | `distros` (required), `whitelist` (optional; explicit value wins over diff), `lifecycles`, `blacklist` (optional; reusable trigger only) | +| [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml): `🚀 Test: Deploy` | Deploys one chunk of the sweep. Every matrix row is a single `role#variant` carrying the deploy mode, onion state, distro and filesystem the rotation assigned it: `swarm` rows get a simulated 3-node DinD cluster with an NFS server plus a drain/reschedule state-survival assertion, `compose` and `host` rows run the single-node drill. When `whitelist` is empty, the discover job derives one from the branch's diff vs `origin/main`; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). | reusable | `index`, `sweep` (required), `distros` (optional pool), `filesystem` (optional pool), `whitelist` (optional; explicit value wins over diff), `priority`, `lifecycles`, `modes` (default `auto`), `tor`, `marker` | | [call-test-instructions.yml](../../../../../.github/workflows/call-test-instructions.yml): `📖 Test: Instructions` | Extracts the `### Production` command from a role README (a random role when `role` is empty) and executes it against the runner: `` becomes `localhost` (ansible_connection local) and the Docker socket replaces the TTY flag. Verifies the documented one-command deploy actually works, seeding the run´s freshly built CI image (needs `call-images-build-ci.yml`) instead of the published default. Gates the final `done` job. | reusable, manual | `distros` (required), `role` (optional; empty picks one at random), `priority` (optional), `whitelist` (optional) | | [call-test-install-make.yml](../../../../../.github/workflows/call-test-install-make.yml): `📥 Test: Install Make` | Validates the `make install` entry points. | reusable | none | | [call-test-install-pkgmgr.yml](../../../../../.github/workflows/call-test-install-pkgmgr.yml): `📥 Test: Install Package Manager` | Validates installation via the upstream package manager. | reusable | none | @@ -84,11 +82,10 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| | [call-release-version.yml](../../../../../.github/workflows/call-release-version.yml): `🚀 Release: Version Logic` | Releases a specific version tag (build + publish). Called from `entry-push-latest.yml` on tagged pushes. | reusable, manual | `tag` (required, e.g. `v1.2.3`) | -| [cron-release-highest.yml](../../../../../.github/workflows/cron-release-highest.yml): `⏰ Release: Highest Missing Version` | Scheduled backfill: finds the highest tag without a release and triggers `call-release-version.yml` for it. | auto (`schedule`: daily 00:00 UTC), manual | none | -| [cron-cleanup-stale.yml](../../../../../.github/workflows/cron-cleanup-stale.yml): `⏰ Cleanup: Stale Repository Data` | Marks and closes stale issues and PRs, deletes inactive branches, and prunes old GHCR CI image versions. | auto (`schedule`: daily 00:00 UTC), manual | none | -| [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `⏰ Update: Versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | +| [cron-release-highest.yml](../../../../../.github/workflows/cron-release-highest.yml): `🚀 Release missing tag` | Scheduled backfill: finds the highest tag without a release and triggers `call-release-version.yml` for it. | auto (`schedule`: daily 00:00 UTC), manual | none | +| [cron-cleanup-stale.yml](../../../../../.github/workflows/cron-cleanup-stale.yml): `🧹 Prune stale data` | Marks and closes stale issues and PRs, deletes inactive branches, and prunes old GHCR CI image versions. | auto (`schedule`: daily 00:00 UTC), manual | none | +| [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `🔄 Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | | [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml): `🚫 Dependabot: Close while auto-updates disabled` | Auto-closes Dependabot PRs while `CI_ENABLE_AUTO_UPDATES` is not set to `true`, so Dependabot honours the same gate as the workflow-driven update jobs. See [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened) | none | -| [cron-rerun-cancelled.yml](../../../../../.github/workflows/cron-rerun-cancelled.yml): `⏰ Rerun: Cancelled Branch Runs` | Sweeps every branch: when its latest run ended `cancelled`, the failed jobs are rerun via `gh run rerun --failed` while the successful ones are kept, so a concurrency cancellation costs a resume instead of a full pipeline. The attempt ceiling, the age cutoff, and the sweep interval come from `CI_RERUN_MAX_ATTEMPTS`, `CI_RERUN_MAX_AGE_HOURS` and `CI_RERUN_INTERVAL_MINUTES`, see [configuration.md](configuration.md). Sweeps hourly by default, with no attempt ceiling. A new trigger cancels a sweep that is still running. Manual dispatch always sweeps, ignoring the interval. | auto (`schedule`: hourly, gated to the configured interval), manual | none | ## Changing workflows ✍️ diff --git a/docs/requirements/014-svc-runner-ci.md b/docs/requirements/014-svc-runner-ci.md index fd059c07f1..8791fa1106 100644 --- a/docs/requirements/014-svc-runner-ci.md +++ b/docs/requirements/014-svc-runner-ci.md @@ -12,7 +12,7 @@ Add an `svc-runner` role that provisions a dedicated machine as an Infinito.Nexu ### Role: `svc-runner` -- [x] A new role at `roles/svc-runner/` (path to be created) exists and follows the role-meta layout in `docs/contributing/design/services/layout.md` (including `meta/services.yml` with a `lifecycle` key, `meta/schema.yml`, and `tasks/main.yml`). +- [x] A new role at `roles/svc-runner/` (path to be created) exists and follows the role-meta layout in `docs/contributing/design/services/layout.md` (including `meta/services.yml` with a `lifecycle` key, `meta/secrets.yml`, and `tasks/main.yml`). - [x] When applied to a host, `svc-runner` brings up an Infinito.Nexus-capable CI runner on that host (the runner is the execution environment in which subsequent Infinito.Nexus deploys and tests run). - [x] The role is compatible with — and exercised by — the CLI script described under **CLI: `cli/administration/deploy/runner/`** below; deploying through that script against a fresh host MUST yield a working runner without manual post-steps. - [x] `make test` passes with the new role in place. diff --git a/docs/requirements/023-docker-swarm-nfs.md b/docs/requirements/023-docker-swarm-nfs.md index adb3ed68d4..ca78cb31d6 100644 --- a/docs/requirements/023-docker-swarm-nfs.md +++ b/docs/requirements/023-docker-swarm-nfs.md @@ -25,7 +25,7 @@ The implementation MUST keep a clean abstraction line between the render backend ### Role: `svc-swarm-node` -- [x] A new role at `roles/svc-swarm-node/` exists and follows the role-meta layout in [layout.md](../contributing/design/role/services/layout.md) (including `meta/services.yml` with a `lifecycle` key, `meta/schema.yml`, and `tasks/main.yml`). +- [x] A new role at `roles/svc-swarm-node/` exists and follows the role-meta layout in [layout.md](../contributing/design/role/services/layout.md) (including `meta/services.yml` with a `lifecycle` key, `meta/secrets.yml`, and `tasks/main.yml`). - [x] On first application against the host in `svc-swarm-manager`, the role initialises the cluster (`docker swarm init`) with the configured `advertise_addr`, persists the resulting worker and manager join tokens to a documented secret store, and is idempotent on re-runs. - [x] On application against any host in `svc-swarm-node` that is NOT in `svc-swarm-manager`, the role joins the cluster as a worker using the persisted worker token. Joining is idempotent. - [x] v1 scope is single-manager. Multi-manager Raft-quorum HA (3+ managers) is explicitly out of scope for this requirement and tracked under [Future Extensions](#future-extensions). @@ -122,7 +122,7 @@ The implementation MUST keep a clean abstraction line between the render backend This 3-node topology (1 manager + 2 workers) is also the minimum exercised by the CI pilot workflow — see [CI: pilot validation workflow](#ci-pilot-validation-workflow). Any host in `svc-swarm-manager` MUST also be in `svc-swarm-node`. A deploy with a host in `svc-swarm-manager` but missing from `svc-swarm-node` MUST fail at inventory-validation time. -- [ ] All blocks above (`storage`, `swarm`) have schema validation entries in the relevant role's `meta/schema.yml`. A missing or malformed block fails the deploy at variable-load time with a precise error, not at runtime. +- [ ] All blocks above (`storage`, `swarm`) have schema validation entries in the relevant role's `meta/secrets.yml`. A missing or malformed block fails the deploy at variable-load time with a precise error, not at runtime. ### Cluster validation diff --git a/docs/requirements/023-setup-penpot.md b/docs/requirements/023-setup-penpot.md index a5cbfe7cbe..b708d6c124 100644 --- a/docs/requirements/023-setup-penpot.md +++ b/docs/requirements/023-setup-penpot.md @@ -8,7 +8,7 @@ As a Infinito.Nexus platform operator, I want to provide a fully integrated, pro [Penpot](https://penpot.app/) is an open-source design and prototyping platform (a self-hostable Figma alternative). This requirement tracks a new `web-app-penpot` Ansible role that deploys Penpot's containerized stack and wires it into the Infinito.Nexus ecosystem (identity, reverse proxy, marketplace, backup). -The role MUST follow the standard role-meta layout described in [layout.md](../contributing/design/role/services/layout.md) (`meta/services.yml`, `meta/schema.yml`, `meta/volumes.yml`, `meta/variants.yml`, `meta/info.yml`, `meta/main.yml`). [web-app-openproject](../../roles/web-app-openproject/) is the closest structural model — it combines PostgreSQL, a Redis `cache` service, background workers, an internal proxy, Keycloak SSO and LDAP — and SHOULD be used as the primary reference; [web-app-taiga](../../roles/web-app-taiga/) and [web-app-confluence](../../roles/web-app-confluence/) are secondary references. +The role MUST follow the standard role-meta layout described in [layout.md](../contributing/design/role/services/layout.md) (`meta/services.yml`, `meta/secrets.yml`, `meta/volumes.yml`, `meta/variants.yml`, `meta/info.yml`, `meta/main.yml`). [web-app-openproject](../../roles/web-app-openproject/) is the closest structural model — it combines PostgreSQL, a Redis `cache` service, background workers, an internal proxy, Keycloak SSO and LDAP — and SHOULD be used as the primary reference; [web-app-taiga](../../roles/web-app-taiga/) and [web-app-confluence](../../roles/web-app-confluence/) are secondary references. Penpot's upstream stack is **frontend + backend + exporter + PostgreSQL + Redis**. The exporter container is mandatory: it backs the export (SVG/PDF) and developer-handoff features required below. @@ -18,7 +18,7 @@ Penpot's upstream stack is **frontend + backend + exporter + PostgreSQL + Redis* - [x] A new role exists at `roles/web-app-penpot/` and follows the role-meta layout in [layout.md](../contributing/design/role/services/layout.md). - [x] `meta/services.yml` declares every container service and a `lifecycle` key (starting tier `beta`). -- [x] `meta/schema.yml` defines the role's configurable variables. +- [x] `meta/secrets.yml` defines the role's configurable variables. - [x] `meta/volumes.yml` declares the role's named volumes. - [x] `meta/variants.yml` declares the matrix-deploy variants (see **Variants** below). - [x] `meta/info.yml` and `meta/main.yml` are present and valid. diff --git a/docs/requirements/024-web-app-erpnext.md b/docs/requirements/024-web-app-erpnext.md index 21a723ed9e..d0adeb2676 100644 --- a/docs/requirements/024-web-app-erpnext.md +++ b/docs/requirements/024-web-app-erpnext.md @@ -55,7 +55,7 @@ roles/web-app-erpnext/ │ ├── info.yml │ ├── server.yml │ ├── services.yml -│ ├── schema.yml +│ ├── secrets.yml │ ├── users.yml │ ├── variants.yml │ └── volumes.yml @@ -200,11 +200,11 @@ DB numbers (0 / 1 / 2) are stable for v1; if `svc-db-redis` later partitions ten - [x] `roles/web-app-erpnext/` exists with the layout in the [Target Schema](#role-layout) above. - [x] `meta/services.yml` pins `frappe/erpnext` to a concrete stable v15.x semver (no `:latest`, no `:edge`, no v14, no v16). -- [x] `meta/info.yml`, `meta/server.yml`, `meta/main.yml`, `meta/schema.yml`, `meta/users.yml`, `meta/volumes.yml`, `meta/rbac.yml`, `meta/variants.yml` exist and pass the repo's standard role-meta lint (per [008](README.md#archive)). +- [x] `meta/info.yml`, `meta/server.yml`, `meta/main.yml`, `meta/secrets.yml`, `meta/users.yml`, `meta/volumes.yml`, `meta/rbac.yml`, `meta/variants.yml` exist and pass the repo's standard role-meta lint (per [008](README.md#archive)). ### Central-service reuse (Decision #7) -- [x] When `services.mariadb.shared=true` (V1 + matching `group_names`), Frappe connects to the central `svc-db-mariadb` via the in-stack `mariadb` network alias using svc-db-mariadb's `credentials.root_password` for `bench new-site`; when `shared=false` (V2/V3) `sys-svc-rdbms` templates a per-role MariaDB container and bench uses the consumer's per-role db password as root. +- [x] When `services.mariadb.shared=true` (V1 + matching `group_names`), Frappe connects to the central `svc-db-mariadb` via the in-stack `mariadb` network alias using svc-db-mariadb's `secrets.credentials.root_password` for `bench new-site`; when `shared=false` (V2/V3) `sys-svc-rdbms` templates a per-role MariaDB container and bench uses the consumer's per-role db password as root. - [x] Frappe's three Redis logical roles share one instance via DB-number split (`cache=0`, `queue=1`, `socketio=2`) using the in-compose `redis` alias. - [x] When `services.mariadb.enabled` (always true for ERPNext) is unsatisfiable, `sys-stk-full` fails the deploy at the database-readiness gate before bench-bootstrap runs. diff --git a/docs/requirements/025-mcp-role-integration.md b/docs/requirements/025-mcp-role-integration.md index e5823cae47..1bbe1f3771 100644 --- a/docs/requirements/025-mcp-role-integration.md +++ b/docs/requirements/025-mcp-role-integration.md @@ -24,7 +24,7 @@ These choices are settled at requirement creation time and bound the implementat 1. **Implementation precedence.** `native` > `plugin` > `sidecar` > `external`. A lower-precedence path is allowed only when the higher one is unavailable upstream and the role README documents why. 2. **Discovery reuses existing infrastructure.** Client roles discover servers through the existing [`roles_with_service`](../../plugins/lookup/roles_with_service.py) lookup (backed by `utils.cache.applications.get_merged_applications`), extended to filter by `services.mcp.direction` and to surface endpoint metadata. No new generated repository-wide application dictionary is introduced. -3. **Secrets reuse the credentials mechanism.** MCP tokens, app-passwords, and OAuth client secrets are declared in each role's [`meta/schema.yml`](../../roles/web-app-baserow/meta/schema.yml) `credentials:` block and read via `lookup('config', application_id, 'credentials.')`. No new secret store is introduced. +3. **Secrets reuse the credentials mechanism.** MCP tokens, app-passwords, and OAuth client secrets are declared in each role's [`meta/secrets.yml`](../../roles/web-app-baserow/meta/secrets.yml) `credentials:` block and read via `lookup('config', application_id, 'secrets.credentials.')`. No new secret store is introduced. 4. **MCP state is a variant axis.** Roles that gain an MCP surface MUST express the enabled/disabled split through `meta/variants.yml` so CI matrix runs cover both states. 5. **Lint reuses the suppression model.** New MCP lint rules live under [`tests/lint/ansible/services/`](../../tests/lint/ansible/services/) and honour the existing `# nocheck:` marker convention (see [suppression docs](../contributing/actions/testing/suppression.md)). 6. **First slice.** The first end-to-end slice is `web-app-baserow` (server) plus `web-app-openwebui` (client). @@ -165,7 +165,7 @@ The lookup MUST remain backed by `utils.cache.applications.get_merged_applicatio - [ ] No deployed role launches arbitrary user-provided stdio MCP commands by default. - [ ] Every MCP server endpoint is protected by OIDC, app-password, bearer-token, upstream-session auth, or an explicitly documented internal-only exception. -- [ ] MCP credentials (tokens, app-passwords, OAuth client secrets) are declared in the role's [`meta/schema.yml`](../../roles/web-app-baserow/meta/schema.yml) `credentials:` block and consumed via `lookup('config', application_id, 'credentials.')`; they are never written into `README.md`, Playwright traces, or non-secret env vars. +- [ ] MCP credentials (tokens, app-passwords, OAuth client secrets) are declared in the role's [`meta/secrets.yml`](../../roles/web-app-baserow/meta/secrets.yml) `credentials:` block and consumed via `lookup('config', application_id, 'secrets.credentials.')`; they are never written into `README.md`, Playwright traces, or non-secret env vars. - [ ] Every MCP server role documents whether MCP calls execute as the requesting user, a service account, or an administrator, and the implementation enforces that subject consistently. - [ ] Client roles MUST NOT register service-account or administrator-scoped MCP servers as globally enabled default tools unless the server advertises read-only tools only. - [ ] Public MCP exposure includes proxy routing, TLS, request-size limits, timeout limits, and rate-limit guidance. diff --git a/docs/requirements/026-unified-addon-syntax.md b/docs/requirements/026-unified-addon-syntax.md index 9828b97a32..e8d5d66038 100644 --- a/docs/requirements/026-unified-addon-syntax.md +++ b/docs/requirements/026-unified-addon-syntax.md @@ -28,8 +28,8 @@ These choices are settled at requirement creation time and bound the implementat 1. **One file per addon.** Addon definitions live under `roles//meta/addons/`, one file per addon at `meta/addons/.yml`. The file-root convention applies per file: the file content IS the addon spec, with no wrapping `:` key (the filename stem supplies the addon id); all files are collected into `applications..addons` keyed by `` (see [layout.md](../contributing/design/role/services/layout.md)). The materialised path is `applications..addons.`, read via `lookup('config', application_id, 'addons.')`. 2. **Unified schema, native mechanism preserved.** Every addon entry uses one schema across all roles. The app-native term is retained only as the `mechanism` field (`addon`, `plugin`, `mu_plugin`, `extension`, `module`, `bridge`). Tasks keep using the upstream installer for that mechanism; only the *declaration* is unified. App-specific runtime configuration is carried under an opaque `config:` mapping that only the owning role's tasks interpret, so the surrounding schema stays uniform while each addon keeps its full per-addon payload. Each `meta/addons/.yml` is therefore the single source for both the declaration and the runtime config: where a role previously split the enable/disable declaration from a per-addon config payload (e.g. Nextcloud's `vars/plugins/`), both move into that addon's `meta/addons/.yml` file and the superseded per-addon config files are deleted by the migration. 3. **Bridges are explicit and validated.** When an addon itself integrates with another role, it MUST list the bridged service key under `bridges:`. Each listed key MUST resolve to a service block already declared in the same role's `meta/services.yml`. Lint fails otherwise. Front-door auth gates such as oauth2-proxy are not addon bridges unless the addon itself talks to that service. **Two distinct meanings of "bridge" exist and MUST NOT be conflated:** the `bridges:` *field* names an in-repo cross-role service dependency (e.g. an addon that talks to `svc-db-openldap`), whereas `mechanism: bridge` marks an addon that *is* a network/appservice bridge to an external system (e.g. a Matrix mautrix bridge to WhatsApp/Telegram). A single addon MAY be both: a `mechanism: bridge` addon MAY also declare a `bridges:` dependency on an in-repo service it relies on. -4. **No new secret store.** Any credential an addon needs continues to be declared in [`meta/schema.yml`](../contributing/design/role/services/layout.md) `credentials:` and read via `lookup('config', application_id, 'credentials.')`. -5. **Enable state defaults to off; deliberately-wired integrations auto-enable with their partner.** `enabled` is optional and defaults to `false` unless `required: true` is set. An addon that bridges a service MUST derive its effective enablement from that service's `enabled` flag (never a duplicated group-membership expression), so a deliberately-wired cross-role integration activates automatically whenever its partner role is co-deployed (`services..enabled` is true) and stays off otherwise. Any credential an addon needs is declared in `meta/schema.yml` `credentials:` and read via `lookup('config', application_id, 'credentials.')` (Decision 4): auto-generated where possible, or supplied through the same credentials mechanism's manual-entry path where the operator must enter the secret. There is no separate opt-in exception: auto-enable-with-partner holds, and an operator-entered credential resolves through `credentials` like any other. This auto-enable-with-partner rule is distinct from update-automation-discovered addons (Decision 10), which are added hard-off. +4. **No new secret store.** Any credential an addon needs continues to be declared in [`meta/secrets.yml`](../contributing/design/role/services/layout.md) `credentials:` and read via `lookup('config', application_id, 'secrets.credentials.')`. +5. **Enable state defaults to off; deliberately-wired integrations auto-enable with their partner.** `enabled` is optional and defaults to `false` unless `required: true` is set. An addon that bridges a service MUST derive its effective enablement from that service's `enabled` flag (never a duplicated group-membership expression), so a deliberately-wired cross-role integration activates automatically whenever its partner role is co-deployed (`services..enabled` is true) and stays off otherwise. Any credential an addon needs is declared in `meta/secrets.yml` `credentials:` and read via `lookup('config', application_id, 'secrets.credentials.')` (Decision 4): auto-generated where possible, or supplied through the same credentials mechanism's manual-entry path where the operator must enter the secret. There is no separate opt-in exception: auto-enable-with-partner holds, and an operator-entered credential resolves through `credentials` like any other. This auto-enable-with-partner rule is distinct from update-automation-discovered addons (Decision 10), which are added hard-off. 6. **Required addons are explicit, and install failure is gated by `required`.** Every addon carries a boolean `required` field (default `false`). Core components that are part of the deployed app contract, such as Odoo's core modules, use `required: true`: they are always installed, MAY omit `enabled`, and MUST NOT set `enabled: false`. The field also governs install-failure behaviour: when an addon's installation fails, a `required: true` addon MUST hard-fail the play (the deploy stops), while a `required: false` addon MUST only emit a warning, skip that addon, and let the play continue. 7. **Workload-neutral contract.** The `meta/addons/` contract applies to any role type that declares role-level extensions, including desktop roles such as `desk-gnome-extensions`. The materialised path still uses the role's assembled application entry, `applications..addons`. 8. **First slice.** The first end-to-end migration is `web-app-friendica` (`ldapauth`, bridges `ldap` to `svc-db-openldap`), because it already exercises the bridge rule and the service-flag enablement path. @@ -37,7 +37,7 @@ These choices are settled at requirement creation time and bound the implementat 10. **Update PR behaviour.** The scheduled update workflow MAY open or refresh an update pull request for addon version bumps and newly discovered catalog entries. Addon entries *discovered by update automation* MUST be added disabled by default (`enabled: false`) and MUST NOT silently enable new runtime behaviour. This hard-off default applies to auto-discovered addons only; it does NOT override the auto-enable-with-partner rule for deliberately-wired integrations (Decision 5). 11. **Every addon ships a Playwright test.** Each addon with a user-facing surface MUST add a matching Playwright spec under `roles//files/playwright/` that exercises that addon's behaviour (e.g. an `ldapauth`/`sociallogin` login path, a `wp-discourse` round-trip, an enabled Odoo module's UI entry point). Desktop roles (`desk-*`) drive no web surface a Playwright test could exercise and therefore NEVER ship addon specs — the lint forbids spec files under `desk-*` roles. For every web-facing role there is no per-addon exemption: an addon is considered migrated only once its Playwright spec is present and green. Cross-role integration specs (proving two roles are actually connected) run under a dedicated **integration-pair deploy variant** that co-deploys both partner roles, and are added incrementally as each ✅ pair is wired rather than all upfront. 12. **Addon state is a variant axis.** Optional addons (`required: false`) MUST express their enabled/disabled split through the role's [`meta/variants.yml`](../contributing/design/role/services/layout.md) so CI matrix runs exercise both states, mirroring requirement 025's MCP variant axis. Required addons (`required: true`) are not a variant axis because they are always installed. -13. **Network bridges are addons.** Appservice / network bridges (e.g. the Matrix `mautrix` bridges to WhatsApp, Telegram, Signal, Slack, Facebook, Instagram) are addons declared under `meta/addons/` with `mechanism: bridge`, one file per bridged network. Each bridge owns its credentials in [`meta/schema.yml`](../contributing/design/role/services/layout.md) and is `required: false` and disabled by default. The role's former bridge declarations (e.g. `web-app-matrix`'s `vars/bridges.yml`) are absorbed into `meta/addons/`. +13. **Network bridges are addons.** Appservice / network bridges (e.g. the Matrix `mautrix` bridges to WhatsApp, Telegram, Signal, Slack, Facebook, Instagram) are addons declared under `meta/addons/` with `mechanism: bridge`, one file per bridged network. Each bridge owns its credentials in [`meta/secrets.yml`](../contributing/design/role/services/layout.md) and is `required: false` and disabled by default. The role's former bridge declarations (e.g. `web-app-matrix`'s `vars/bridges.yml`) are absorbed into `meta/addons/`. 14. **The integration matrix is the cross-role addon backlog.** The full role×role capability map lives in the generated companion [027-integration-matrix.md](027-integration-matrix.md) (source of truth: [027-integration-matrix.gen.py](027-integration-matrix.gen.py)). ☑️ cells are integrations **already wired** through an infinito-native service flag in the row role's `meta/services.yml` (e.g. `sso`→keycloak, `matomo`, `prometheus`, `email`→mailu), derived by scanning the repo, no action required. ✅ cells are verified **upstream app↔app plugins not yet declared** as addons, the backlog this requirement commits to wire. 🪙 cells are the same as ✅ but gated behind a commercial tier (opt-in, operator-enabled). ❌ cells have no known integration. The matrix MUST be regenerated (not hand-edited) whenever a role or an integration is added; the `meta/addons/` migrations turn ✅ into ☑️ over time. 15. **Scope is the full backlog, executed in phases.** The definition of done is the FULL set: every ✅ cell in the matrix wired as an addon, and an exhaustive per-`web-app-*`-role upstream-plugin survey completed so the ✅ layer is exhaustive rather than hub-biased. Delivery is phased: the shared contract plus the first-slice roles land first (see [Implementation Strategy](#implementation-strategy)), then the remaining roles and ✅ wirings sweep incrementally, but no phase reduces scope. The requirement is not complete until the full ✅ set is wired and every `web-app-*` role surveyed. 16. **The integration matrix is a generated artifact with a sanctioned generator.** `027-integration-matrix.gen.py` stays under `docs/requirements/` but MUST be refactored to satisfy the repo lints: its `EDGES` data moves into a sibling data module so the entrypoint stays under the 500-line limit, it uses the shared project-root helper instead of a local `__file__` upward walk, and it carries no self-path literal or `requirement NNN` token. The generated `027-integration-matrix.md` carries a `generated-artifact / not-a-requirement` head marker so the requirements-completeness/archival lint skips it. Dead upstream URLs in `EDGES` are fixed or dropped on regeneration. @@ -121,7 +121,7 @@ Field rules: - `version` (optional) MUST be a string. `""` means "track the app's default". A concrete pin MUST be a string, never an unquoted number. - `group` (optional) is a free label used by roles that partition addons (e.g. Odoo `core` vs `optional`). It MUST NOT affect enablement. - `update` (optional) controls live upstream monitoring. `update.monitored` defaults to `false`; `update.catalog` MUST name a supported external-test catalog adapter; `update.upstream_id` defaults to ``. -- `config` (optional) is an opaque, role-interpreted mapping holding the addon's full runtime configuration payload (e.g. Nextcloud `occ config:app` key/value sets, OIDC provider blocks). Lint MUST NOT constrain its inner shape beyond requiring a mapping; only the owning role's tasks read it. Secrets inside `config` MUST resolve through `lookup('config', application_id, 'credentials.')` and MUST NOT be inlined literally. Lint enforces this with a bounded heuristic: any `config` value whose key matches a secret-name pattern (`*secret*`, `*password*`, `*token*`, `*client_secret*`, `*api_key*`, case-insensitive) MUST be a `lookup(..., 'credentials.')` expression; a bare literal under such a key fails lint. +- `config` (optional) is an opaque, role-interpreted mapping holding the addon's full runtime configuration payload (e.g. Nextcloud `occ config:app` key/value sets, OIDC provider blocks). Lint MUST NOT constrain its inner shape beyond requiring a mapping; only the owning role's tasks read it. Secrets inside `config` MUST resolve through `lookup('config', application_id, 'secrets.credentials.')` and MUST NOT be inlined literally. Lint enforces this with a bounded heuristic: any `config` value whose key matches a secret-name pattern (`*secret*`, `*password*`, `*token*`, `*client_secret*`, `*api_key*`, case-insensitive) MUST be a `lookup(..., 'credentials.')` expression; a bare literal under such a key fails lint. #### Worked example: absorbing per-addon config @@ -162,10 +162,10 @@ config: bridge_name: telegram database_username: mautrix_telegram_bridge database_name: mautrix_telegram_bridge - database_password: "{{ lookup('config', application_id, 'credentials.mautrix_telegram_bridge_database_password') }}" + database_password: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_telegram_bridge_database_password') }}" ``` -The bridge's database password stays declared in [meta/schema.yml](../../roles/web-app-matrix/meta/schema.yml) `credentials:` and is referenced, never inlined. Each additional network (`whatsapp`, `signal`, `slack`, `facebook`, `instagram`) is its own `mechanism: bridge` addon. +The bridge's database password stays declared in [meta/secrets.yml](../../roles/web-app-matrix/meta/secrets.yml) `credentials:` and is referenced, never inlined. Each additional network (`whatsapp`, `signal`, `slack`, `facebook`, `instagram`) is its own `mechanism: bridge` addon. ### Install-failure handling @@ -267,7 +267,7 @@ Rules: - [ ] [web-app-mediawiki](../../roles/web-app-mediawiki/) declares `PluggableAuth` and `OpenIDConnect` in `meta/addons/` with `mechanism: extension`; `OpenIDConnect` bridges `sso`. - [ ] [web-app-xwiki](../../roles/web-app-xwiki/) declares its three plugins in `meta/addons/`, preserving `version` pins; bridges `sso`, `ldap`, and `matomo` resolve to service blocks. - [ ] [web-app-joomla](../../roles/web-app-joomla/) declares `plg_system_keycloak` in `meta/addons/` with `mechanism: plugin`, `source: built`, and `bridges: [sso]`. -- [ ] [web-app-matrix](../../roles/web-app-matrix/) declares each mautrix network bridge in `meta/addons/` with `mechanism: bridge`, `required: false`, `enabled: false` by default, and its DB credential referenced from `meta/schema.yml`; `vars/bridges.yml` is absorbed and deleted. +- [ ] [web-app-matrix](../../roles/web-app-matrix/) declares each mautrix network bridge in `meta/addons/` with `mechanism: bridge`, `required: false`, `enabled: false` by default, and its DB credential referenced from `meta/secrets.yml`; `vars/bridges.yml` is absorbed and deleted. - [ ] [web-app-discourse](../../roles/web-app-discourse/) declares its plugins in `meta/addons/` with `mechanism: plugin`; `discourse-ldap-auth` carries `bridges: [ldap]` resolving to the `ldap` service block, while `docker_manager`, `discourse-activity-pub`, and `discourse-akismet` carry no `bridges`. - [ ] [web-app-pretix](../../roles/web-app-pretix/) declares its `oidc` plugin in `meta/addons/` with `mechanism: plugin`, the `2.3.1` pin preserved as a string `version`, and `bridges: [sso]`. - [ ] [web-app-mattermost](../../roles/web-app-mattermost/) declares its plugins in `meta/addons/` with `mechanism: plugin`; the plugin volumes remain in `meta/volumes.yml`. diff --git a/docs/requirements/027-integration-matrix.gen.py b/docs/requirements/027-integration-matrix.gen.py index 1db7ef8b4d..4aa9bf986e 100755 --- a/docs/requirements/027-integration-matrix.gen.py +++ b/docs/requirements/027-integration-matrix.gen.py @@ -14,7 +14,6 @@ in the COLUMN role: """ # nocheck: file-size — curated EDGES data table plus matrix renderers; the data -# and the renderer read together, splitting them only adds indirection. import re from pathlib import Path @@ -22,10 +21,6 @@ from pathlib import Path # nocheck: project-root-import — standalone docs generator, no package container to import PROJECT_ROOT from. ROLES_DIR = Path(__file__).resolve().parent.parent.parent / "roles" -# Top-level meta/services.yml integration keys -> the in-axis target entity they -# wire the role into. These are infinito-native service flags (already wired, -# group-gated), distinct from the curated upstream app<->app plugins in EDGES. -# Skipped on purpose: ldap/redis/mariadb/database -> svc-db-* (not on the axes). FRAMEWORK = { "sso": "keycloak", "matomo": "matomo", @@ -41,7 +36,6 @@ FRAMEWORK = { "libretranslate": "libretranslate", } -# Entity names = role suffix of every web-app-*/web-svc-* role. WEB_APP = [ "akaunting", "baserow", @@ -130,10 +124,7 @@ WEB_SVC = [ ] ENTITIES = WEB_APP + WEB_SVC -# (source, target, url, kind). kind: "check" or "coin". -# Verified upstream plugin/integration pages. EDGES = [ - # --- Nextcloud integration_* family + office/auth/analytics --- ( "nextcloud", "openproject", @@ -198,7 +189,6 @@ EDGES = [ ), ("nextcloud", "keycloak", "https://github.com/nextcloud/user_oidc", "check"), ("nextcloud", "matomo", "https://apps.nextcloud.com/apps/matomo", "check"), - # --- Mattermost plugins --- ( "mattermost", "gitlab", @@ -241,7 +231,6 @@ EDGES = [ "https://docs.mattermost.com/onboard/sso-saml.html", "coin", ), - # --- GitLab native integrations --- ( "gitlab", "mattermost", @@ -263,7 +252,6 @@ EDGES = [ "check", ), ("gitlab", "keycloak", "https://docs.gitlab.com/integration/saml/", "check"), - # --- Discourse plugins --- ( "discourse", "mattermost", @@ -308,7 +296,6 @@ EDGES = [ "https://github.com/discourse/discourse-activity-pub", "check", ), - # --- Matrix (Synapse / hookshot / Element) --- ("matrix", "gitlab", "https://github.com/matrix-org/matrix-hookshot", "check"), ("matrix", "jira", "https://github.com/matrix-org/matrix-hookshot", "check"), ( @@ -329,7 +316,6 @@ EDGES = [ "https://github.com/element-hq/element-web/blob/develop/docs/jitsi.md", "check", ), - # --- Moodle plugins --- ( "moodle", "bigbluebutton", @@ -342,13 +328,11 @@ EDGES = [ ("moodle", "jitsi", "https://moodle.org/plugins/mod_jitsi", "check"), ("moodle", "matomo", "https://moodle.org/plugins/tool_webanalytics", "check"), ("moodle", "openwebui", "https://moodle.org/plugins/aiprovider_openwebui", "check"), - # --- Jenkins plugins --- ("jenkins", "gitlab", "https://plugins.jenkins.io/gitlab-plugin", "check"), ("jenkins", "gitea", "https://plugins.jenkins.io/gitea/", "check"), ("jenkins", "mattermost", "https://plugins.jenkins.io/mattermost/", "check"), ("jenkins", "prometheus", "https://plugins.jenkins.io/prometheus", "check"), ("jenkins", "keycloak", "https://plugins.jenkins.io/oic-auth/", "check"), - # --- OpenProject --- ( "openproject", "nextcloud", @@ -367,7 +351,6 @@ EDGES = [ "https://www.openproject.org/docs/system-admin-guide/authentication/openid-providers/", "coin", ), - # --- WordPress plugins --- ("wordpress", "matomo", "https://wordpress.org/plugins/matomo/", "check"), ("wordpress", "mastodon", "https://wordpress.org/plugins/activitypub/", "check"), ("wordpress", "discourse", "https://wordpress.org/plugins/wp-discourse/", "check"), @@ -395,7 +378,6 @@ EDGES = [ "https://wordpress.org/plugins/video-manager-for-peertube/", "check", ), - # --- MediaWiki extensions --- ( "mediawiki", "keycloak", @@ -428,7 +410,6 @@ EDGES = [ "https://www.mediawiki.org/wiki/Extension:AIEditingAssistant", "check", ), - # --- XWiki extensions --- ( "xwiki", "keycloak", @@ -441,7 +422,6 @@ EDGES = [ "https://extensions.xwiki.org/xwiki/bin/view/Extension/Piwiki%20Integration", "check", ), - # --- Joomla --- ( "joomla", "keycloak", @@ -454,30 +434,25 @@ EDGES = [ "https://extensions.joomla.org/extension/itcs-matomo/", "check", ), - # --- Friendica --- ("friendica", "matomo", "https://github.com/friendica/friendica-addons", "check"), - # --- Pretix --- ( "pretix", "keycloak", "https://docs.pretix.eu/en/latest/admin/installation/index.html", "check", ), - # --- PeerTube --- ( "peertube", "keycloak", "https://www.npmjs.com/package/peertube-plugin-auth-openid-connect", "check", ), - # --- BigBlueButton (Greenlight) --- ( "bigbluebutton", "keycloak", "https://docs.bigbluebutton.org/greenlight/v3/external-authentication/", "check", ), - # --- CRM / ERP: auth + email --- ( "zammad", "keycloak", @@ -539,7 +514,6 @@ EDGES = [ "https://docs.frappe.io/erpnext/user/manual/en/setting-up-email-account", "check", ), - # --- Other SSO-to-Keycloak (covered centrally today via the sso service) --- ( "baserow", "keycloak", @@ -587,14 +561,11 @@ def scan_framework_edges(): def build(): - # Framework (infinito-native) edges first; curated upstream EDGES override - # them so an explicit plugin link wins over the generic services.yml link. by_pair = {(s, d): (url, kind) for (s, d, url, kind) in scan_framework_edges()} by_pair.update({(s, d): (url, kind) for (s, d, url, kind) in EDGES}) corner = "↓ row wires → col" def render_row(label, cells): - # Repeat the row-label column every 10 columns for readability. out = [label] for j, cell in enumerate(cells): out.append(cell) @@ -618,7 +589,6 @@ def build(): else: cells.append(CROSS) rows.append(render_row(f"**{src}**", cells)) - # Repeat the column header every 10 data rows for readability. if (i + 1) % 10 == 0 and (i + 1) < len(ENTITIES): rows.append(header) return "\n".join(rows) diff --git a/docs/requirements/028-web-app-atmo-events.md b/docs/requirements/028-web-app-atmo-events.md index 4c5bed85cb..12aa1d6d5c 100644 --- a/docs/requirements/028-web-app-atmo-events.md +++ b/docs/requirements/028-web-app-atmo-events.md @@ -71,7 +71,7 @@ roles/web-app-atmo/ │ ├── info.yml │ ├── server.yml # canonical: rsvp.{{ DOMAIN_PRIMARY }} │ ├── services.yml -│ ├── schema.yml +│ ├── secrets.yml │ ├── users.yml │ ├── variants.yml │ └── volumes.yml diff --git a/docs/requirements/028-web-app-semaphore.md b/docs/requirements/028-web-app-semaphore.md index a561d22717..1bc579617f 100644 --- a/docs/requirements/028-web-app-semaphore.md +++ b/docs/requirements/028-web-app-semaphore.md @@ -61,7 +61,7 @@ roles/web-app-semaphore/ │ ├── info.yml │ ├── server.yml │ ├── services.yml -│ ├── schema.yml +│ ├── secrets.yml │ ├── users.yml │ ├── rbac.yml │ ├── variants.yml @@ -127,7 +127,7 @@ V1 = `sso` + `ldap` both enabled; V2 = all dynamic flags `false`; V3 = `ldap` on - [ ] `roles/web-app-semaphore/` exists with the layout in [Target Schema](#role-layout). - [ ] `meta/services.yml` pins `semaphoreui/semaphore` to a concrete stable `2.x` semver (no `:latest`). -- [ ] `meta/info.yml`, `server.yml`, `main.yml`, `schema.yml`, `users.yml`, `rbac.yml`, `variants.yml`, `volumes.yml` exist and pass the repo's role-meta lint. +- [ ] `meta/info.yml`, `server.yml`, `main.yml`, `secrets.yml`, `users.yml`, `rbac.yml`, `variants.yml`, `volumes.yml` exist and pass the repo's role-meta lint. ### Database (Decision #3 — central PostgreSQL) diff --git a/docs/requirements/031-svc-net-tor-onion.md b/docs/requirements/031-svc-net-tor-onion.md new file mode 100644 index 0000000000..a2ea10251a --- /dev/null +++ b/docs/requirements/031-svc-net-tor-onion.md @@ -0,0 +1,250 @@ +# 031 - svc-net-tor: Full Tor Onion Node + +## User Story + +As a self-hoster running Infinito.Nexus behind NAT/CGNAT/dynamic IP (Raspberry Pi, edge node, home server), I want a `svc-net-tor` role that makes the node's primary domain a Tor v3 `.onion` address so that the entire stack (web, SSO, LDAP, CA) is reachable over Tor without public IP, port forwarding, VPS, or DynDNS — while individual apps can still attach extra public domains with their own TLS. + +## Model + +**`DOMAIN_PRIMARY` = the node's `.onion` address.** Everything derives from `DOMAIN_PRIMARY`, so the whole node becomes Tor-native with **zero domain-transform code**: + +- Vhosts: `next.cloud.{{ DOMAIN_PRIMARY }}` → `next.cloud..onion` +- OIDC issuer, redirect URIs, web-origins: onion — one realm, one issuer, consistent +- `LDAP_DN_BASE`, user/admin emails, oauth2-proxy `email_domains`, CA identity: all onion, mutually consistent (users `@.onion` pass the oauth2-proxy email filter) + +The `.onion` is a **deploy-time input**: a CLI helper mints the v3 key offline during inventory build, vaults it, and sets `DOMAIN_PRIMARY`. It must NOT be a runtime fact — `DOMAIN_PRIMARY` is consumed at build time (LDAP base, CA, applications cache). The role restores the minted key into the hidden-service volume before Tor starts. + +**All-or-nothing:** a partial shift (web onion, identity clearnet) breaks oauth2-proxy email matching ([oauth2-proxy-keycloak.cfg.j2:32](../../roles/web-app-keycloak/templates/sso_proxy/oauth2-proxy-keycloak.cfg.j2) sets `email_domains = "{{ DOMAIN_PRIMARY }}"`). Fresh onion nodes only; migrating an existing clearnet node is out of scope (base DN + all identities would shift). + +## Codebase facts (verified; build on these) + +| Fact | Where | +|---|---| +| OpenResty runs `network_mode: host`, binds 80/443, `proxy_pass http://127.0.0.1:` | [`roles/svc-prx-openresty/templates/compose.yml.j2`](../../roles/svc-prx-openresty/templates/compose.yml.j2), [`roles/sys-svc-proxy/templates/location/html.conf.j2`](../../roles/sys-svc-proxy/templates/location/html.conf.j2) | +| TLS-disabled vhosts serve plain HTTP on `:80`; the http→https 301 exists only in the TLS layer | [`roles/sys-front-tls/templates/http.conf.j2`](../../roles/sys-front-tls/templates/http.conf.j2) | +| TLS is resolved per `(domain\|application_id)` with `TLS_MODE`/`TLS_ENABLED` defaults, flavors in `AVAILABLE_FLAVORS` | [`plugins/lookup/tls.py`](../../plugins/lookup/tls.py), `utils/tls_common` | +| `DOMAIN_PRIMARY` defined once; `LDAP_DN_BASE`, CA identity, contact email derive from it | [`group_vars/all/00_general.yml:50`](../../group_vars/all/00_general.yml), [`group_vars/all/12_ldap.yml`](../../group_vars/all/12_ldap.yml), [`group_vars/all/02_tls.yml`](../../group_vars/all/02_tls.yml), [`group_vars/all/14_about.yml`](../../group_vars/all/14_about.yml) | +| Keycloak redirect URIs/web-origins are computed from `lookup('domains')` at deploy | [`plugins/lookup/redirect_uris.py`](../../plugins/lookup/redirect_uris.py), [`roles/web-app-keycloak/vars/main.yml`](../../roles/web-app-keycloak/vars/main.yml) | +| Apps register one vhost per domain via `include_role: sys-stk-front-proxy` with `domain` + `http_port`; multi-domain is established practice | [`roles/sys-stk-front-proxy/tasks/main.yml`](../../roles/sys-stk-front-proxy/tasks/main.yml), [`roles/web-app-matrix/tasks/flavor/compose/03_webserver.yml`](../../roles/web-app-matrix/) | +| Extra app domains live in `applications..server.domains.{canonical,aliases}` (str/list/dict) | [`utils/domains/application_domain_index.py`](../../utils/domains/application_domain_index.py), [`plugins/filter/canonical_domains_map.py`](../../plugins/filter/canonical_domains_map.py) | +| Inventory build/secrets tooling (mint-helper integration point) | [`cli/administration/inventory/credentials/`](../../cli/administration/inventory/) | +| Container-service role archetype (compose sidecar, `meta/services.yml` entity, `run_once_` guard) | [`roles/svc-ai-ollama/`](../../roles/svc-ai-ollama/) | +| Role file/entry policy enforced by lint (mandatory files, galaxy_info canon, README sections + exact Credits block, lifecycle values, service bond) | `utils/roles/mapping.py`, `tests/lint/ansible/roles/`, `tests/integration/roles/meta/test_mapping.py` | +| No prior server-side Tor art in the repo (`desk-torbrowser` is desktop client only) | repo-wide grep | + +## Tor facts (verified upstream) + +- **Subdomains:** `sub..onion` routes to the **same** hidden service; the client sends the full `Host:` header → vhost routing works exactly like clearnet. ([address-spec](https://spec.torproject.org/address-spec), [RFC 7686 §2](https://www.rfc-editor.org/rfc/rfc7686.html)) +- **v3 address algorithm** (needed for offline mint): `address = base32(PUBKEY ‖ CHECKSUM ‖ VERSION) + ".onion"`, `CHECKSUM = SHA3-256(".onion checksum" ‖ PUBKEY ‖ VERSION)[:2]`, `VERSION = 0x03`, PUBKEY = 32-byte ed25519 master pubkey. +- **Key-file formats** in `HiddenServiceDir`: `hostname` (address + `\n`), `hs_ed25519_public_key` (`== ed25519v1-public: type0 ==` header + 32-byte key), `hs_ed25519_secret_key` (`== ed25519v1-secret: type0 ==` header + **64-byte expanded** secret key = SHA-512(seed) clamped). +- **`http://*.onion` is a Secure Context** → `Secure` cookies + secure-context APIs work over plain-HTTP onion; hence forward `X-Forwarded-Proto: https`. ([W3C Secure Contexts](https://www.w3.org/TR/secure-contexts/)) +- **`.onion` is in the Public Suffix List** → `user@x.onion` passes most validators. +- **No Let's Encrypt for `.onion`** (ACME needs public DNS). Onion transport is already encrypted + server-authenticated (address = pubkey). + +## Decisions (operator-confirmed; do not re-litigate) + +| # | Decision | +|---|---| +| 1 | Role `svc-net-tor`, container-service archetype ([`svc-ai-ollama`](../../roles/svc-ai-ollama/) pattern), `application_id: svc-net-tor`. Category `svc-net-*` per [`meta/categories.yml`](../../meta/categories.yml). | +| 2 | **Full onion node**: `DOMAIN_PRIMARY` = node `.onion`; entire stack shifts together. No web/identity split, no domain-transform lookup. | +| 3 | **One node key + per-app subdomains** (`..onion`), Host-header-routed. No per-app onions in MVP. | +| 4 | **Tor = compose sidecar**, `network_mode: host`, keys on a named volume, restored from the vaulted mint **before** Tor starts. Backup via `svc-bkp-container-2-local`. | +| 5 | **HTTP on the onion side** (TLS forced off for `.onion`), vhosts on `:80`, upstream gets `X-Forwarded-Proto: https`. | +| 6 | **Offline Python mint** at inventory build: ed25519 → address → exact Tor key-file formats → vault → `DOMAIN_PRIMARY`. Idempotent (existing key is reused, never regenerated). No Docker/Tor needed at build time. | +| 7 | SSO needs no special handling: Keycloak domain is onion ⇒ one onion issuer/realm; onion emails match `email_domains`. | +| 8 | **Tor image built via `files/Dockerfile`** from a pinned Debian `tor` package (`deb.debian.org`; no sandbox-allowlist change). `deb.torproject.org` = documented alternative requiring an allowlist entry. | +| 9 | **Per-domain TLS via app-level override**: extra public domains under `applications..server.domains` deploy as additional HTTPS vhosts; flavor from `applications..tls.mode` (default `TLS_MODE`). `.onion` → always HTTP. No per-domain TLS map. | +| 10 | **`TOR_EGRESS_ENABLED: false` default.** Flag + plumbing in MVP (SOCKS `127.0.0.1:9050` reachable for containers when enabled, documented); transparent egress torification out of scope. Inbound is always onion. | +| 11 | **CI runs a real Tor E2E** (`torsocks curl` against the minted onion) with retry logic; unit tests remain the merge-blocking base. | + +## Target Schema + +### Role layout + +``` +roles/svc-net-tor/ +├── README.md # lint-conform (sections, exact Credits block, no heading emojis) +├── files/Dockerfile # Debian base + pinned `tor` +├── meta/ +│ ├── main.yml # canonical galaxy_info (author/license/company/platforms exact canon) +│ ├── services.yml # `tor` entity (below) +│ └── volumes.yml # tor_data -> HiddenServiceDir +├── tasks/ +│ ├── main.yml # run_once_svc_net_tor guard +│ ├── 01_restore_key.yml # vaulted hostname + hs_ed25519_* -> volume, strict perms, never overwrite +│ └── 02_core.yml # network routine + compose up + render torrc (handler-driven reload) +├── templates/ +│ ├── compose.yml.j2 # sidecar: network_mode host, tor_data volume, base/container includes +│ └── torrc.j2 +└── vars/main.yml # application_id + lookup('config', ...) resolved vars +``` + +No onion vhost template, no domain lookup changes: onion domains fall out of `DOMAIN_PRIMARY`; the standard vhost serves them on `:80` because TLS resolves disabled. + +### `meta/services.yml` + +```yaml +tor: + bond: 1 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: "{{ 'svc-net-tor' in group_names }}" + build: true + image: svc-net-tor + version: "" + name: tor + backup: + no_stop_required: false # stop for consistent key-volume copy + lifecycle: alpha + # no public ports; SocksPort/ControlPort bind 127.0.0.1 only +``` + +### `torrc.j2` + +``` +SocksPort 127.0.0.1:9050 +ControlPort 127.0.0.1:9051 +DataDirectory /var/lib/tor +HiddenServiceDir /var/lib/tor/infinito/node/ +HiddenServiceVersion 3 +HiddenServicePort 80 127.0.0.1:80 +``` + +One `HiddenServicePort` covers all apps: every `..onion` request arrives on `127.0.0.1:80` where OpenResty routes by `Host`. + +### CLI mint helper + +Location: under [`cli/administration/inventory/`](../../cli/administration/inventory/), integrated with `credentials/{emit,vault}.py`; runs automatically during inventory build when `svc-net-tor` is in the target groups. + +1. If a vaulted key exists → reuse (idempotent, address stability is the contract). +2. Else: generate ed25519 seed → compute expanded secret key (SHA-512(seed), clamp) → derive address per the algorithm above → write the three Tor key files byte-exact. +3. Vault `hostname` + both key files; emit `DOMAIN_PRIMARY:
.onion` into the generated inventory. +4. Unit tests: known seed → known address test vector; idempotent reuse; file-format byte-exactness (headers + lengths). + +`tasks/01_restore_key.yml` writes the vaulted files into the volume-backed `HiddenServiceDir` (owner = in-container tor UID, `0700` dir, `0600` secret) before the Tor container starts. Existing on-disk keys are never overwritten. + +### Per-domain TLS (extend `tls.py` / `utils/tls_common`) + +- Domain ends `.onion` → `enabled=false`, `protocols.web=http`, `ports.web=80`, no ACME. Overrides `TLS_MODE` unconditionally. +- Non-onion domain → flavor from `applications..tls.mode`, else `TLS_MODE`. +- Foreign domains under `applications..server.domains` register as separate HTTPS vhosts (existing per-domain `sys-stk-front-proxy` calls), same upstream as the onion vhost. + +### Config + +```yaml +DOMAIN_PRIMARY: ".onion" # written by the mint helper +TOR_EGRESS_ENABLED: false # Decision #10 + +applications: + : + server: + domains: + canonical: [ "app.example.org" ] # optional extra public domain + tls: + mode: letsencrypt # flavor for that app's non-onion domains +``` + +## Acceptance Criteria + +### Scaffolding & lint + +- [ ] `roles/svc-net-tor/` matches the layout; `application_id: svc-net-tor`; `run_once_svc_net_tor` guard; all meta lint green (mapping, galaxy canon, layout, bond, README). +- [ ] `files/Dockerfile` pins `tor` (no `:latest`); image builds in the stack. + +### Mint helper & key persistence + +- [ ] Helper mints offline, vaults `hostname` + `hs_ed25519_{public,secret}_key`, emits `DOMAIN_PRIMARY`; re-running reuses the key (address unchanged). +- [ ] Unit tests: known-vector address determinism, idempotent reuse, byte-exact file formats. +- [ ] `01_restore_key.yml` restores keys with strict perms before Tor starts; never overwrites existing keys; Tor serves exactly the minted address. +- [ ] Address survives redeploy, update, full-cycle reinstall; restoring the vault on a fresh box reproduces the same address; key volume covered by `svc-bkp-container-2-local`. + +### Serving + +- [ ] Tor sidecar bootstraps (`network_mode: host`); 9050/9051 bind `127.0.0.1` only; zero published ports. +- [ ] `lookup('tls', '.onion')` → http/disabled/80, no ACME attempted; app vhosts serve onion `server_name`s on `:80`; every app reachable at `..onion` through `HiddenServicePort 80 → 127.0.0.1:80`. +- [ ] Onion requests reach upstreams with `X-Forwarded-Proto: https`; no `.onion` request is 301'd to https; alias/www canonicalization stays onion-internal; CSP origins (CDN, Matomo, Keycloak, logout) resolve onion — no clearnet leak. + +### SSO / identity consistency + +- [ ] OIDC login completes end-to-end over `.onion`: issuer, redirect URIs, web-origins all onion; no redirect-URI/issuer mismatch. +- [ ] oauth2-proxy `email_domains` matches provisioned `@.onion` users; `LDAP_DN_BASE` + CA identity resolve consistently. + +### Per-domain TLS + +- [ ] Extra domain under `applications..server.domains` + `tls.mode` deploys as a separate HTTPS vhost (correct flavor) alongside the onion vhost, same upstream. +- [ ] `tls.py` unit tests: onion→forced off; foreign→app-level flavor; unset→`TLS_MODE`. + +### Egress + +- [ ] `TOR_EGRESS_ENABLED` defaults `false` (outbound untouched); `true` exposes SOCKS to containers, documented. + +### CI / E2E + +- [ ] CI job: Tor bootstraps, `torsocks curl -I http://..onion` returns the app response; retried against transient Tor-network failures; unit tests independent of Tor-network availability. + +### Quality + +- [ ] Whole flow idempotent (second run: no changes); reloads handler-driven; clear failure if Tor cannot bootstrap. +- [ ] `make test` green tree-wide. +- [ ] README documents: model, mint helper usage, key backup/restore, limitations — no LE for `.onion`; outbound public mail undeliverable from `@onion` senders; fresh-node only (no clearnet migration); extra public domains = per-app opt-in. + +## Onion service extensions (phase 2, layered on a green onion core) + +These build on the working onion node and are implemented after the web core is verified. + +### Mailu listening on the onion (operator: "if possible") + +- The node hidden service exposes Mailu's mail ports in addition to `80`, via extra `HiddenServicePort` entries: `HiddenServicePort 25`, `587`, `465`, `143`, `993` → Mailu's local front binds on `127.0.0.1`. Mailu is then reachable at `.onion` for SMTP/submission/IMAP. +- Mechanism: `torrc.j2` renders extra ports from `TOR_ONION_EXTRA_PORTS` (list of `{onion_port, target}`), populated when `web-app-mailu` is deployed. Mailu's front is bound to `127.0.0.1` in the onion node. +- [ ] With Mailu deployed on an onion node, `.onion:993` / `:587` accept connections over Tor; the extra `HiddenServicePort` lines are rendered only when Mailu is present. + +### Mail egress over Tor (operator: "must") + +- Outbound mail to `.onion` recipient domains is routed through Tor's SOCKS proxy (`127.0.0.1:9050`) instead of clearnet DNS/MX — enabling onion-to-onion / federated mail without public MX/rDNS. +- Mechanism: a Postfix transport for `.onion` next-hops via a SOCKS-aware delivery path (e.g. a `torsocks`-wrapped transport or a SOCKS relay), gated on `svc-net-tor` being active. Public-Internet mail to non-onion domains stays on the normal path. +- [ ] On an onion node, mail addressed to a `*.onion` domain is delivered via the Tor SOCKS proxy; delivery to non-onion domains is unaffected. + +### Playwright over Tor (operator: "probably") + +- When the target under test is an `.onion` domain, the Playwright browser routes through Tor's SOCKS proxy so specs exercise the real onion path (aligns with Decision #11's real-Tor E2E). +- Mechanism: the `test-e2e-playwright` runner sets the browser proxy to `socks5://127.0.0.1:9050` (with `socks5` remote DNS for `.onion` resolution) when the resolved domain ends in `.onion`. +- [ ] A Playwright spec against a `..onion` surface passes through the Tor SOCKS proxy on an onion node; clearnet targets are unaffected. + +## Out of scope + +Dual clearnet+onion with `Onion-Location` bridge and mirrored SSO realms; per-app dedicated onions / Tor Client Authorization; distributed backups over onion; transparent full-egress torification (only `.onion`-destination mail egress is in phase 2); migration of existing clearnet nodes. + +## Validation + +```bash +# mint runs during inventory build (sets DOMAIN_PRIMARY), then: +INFINITO_APPS="svc-net-tor,web-app-keycloak,web-app-nextcloud" make deploy-fresh-purged-apps INFINITO_FULL_CYCLE=true +torsocks curl -I http://next.cloud..onion # app over Tor, no public ports +# complete an SSO login over .onion; redeploy; confirm address unchanged +``` + +## Prerequisites + +Read [AGENTS.md](../../AGENTS.md), then [Role Loop](../agents/action/iteration/README.md) and the [Playwright contract](../contributing/artefact/files/role/playwright.specs.js.md). Verify key-file byte formats and vhost/TLS behavior **in the DiD container first**, then redeploy. + +## Implementation order + +1. Mint helper + unit tests (address vector, formats, idempotency). +2. Role scaffold: Dockerfile, compose, torrc, key restore, volume + backup wiring. +3. `tls.py`/`tls_common`: onion branch + app-level flavor override + unit tests. +4. E2E CI job (torsocks, retries). +5. README + cross-link the implementing PR here. + +## Commit Policy + +- No `git commit` until every Acceptance Criterion is checked. +- When green, operator runs `git-sign-push` outside the sandbox; the agent MUST NOT push. + +## Context + +- — v3 address + key formats +- — `.onion` special-use domain +- — subdomain hidden-service reference +- — `.onion` secure context +- [`roles/svc-ai-ollama/`](../../roles/svc-ai-ollama/) — archetype +- [`plugins/lookup/tls.py`](../../plugins/lookup/tls.py) — TLS resolution +- [`cli/administration/inventory/`](../../cli/administration/inventory/) — mint integration point diff --git a/docs/requirements/README.md b/docs/requirements/README.md index 25ca493284..a6c98e1f82 100644 --- a/docs/requirements/README.md +++ b/docs/requirements/README.md @@ -30,3 +30,4 @@ Its scope is user stories and acceptance criteria that define what the project m - 023 - Setup Penpot - 025 - Matrix Role Ansible Flavor (matrix-docker-ansible-deploy) - 028 - atmo.rsvp (AT Protocol Events) Role + Mobilizon/ActivityPub Bridge +- 031 - svc-net-tor: Tor Onion-Service Provider (injected alongside the clearnet domain) diff --git a/docs/requirements/integration_matrix_data.py b/docs/requirements/integration_matrix_data.py index ce33dd6e5b..ef6a92c8df 100644 --- a/docs/requirements/integration_matrix_data.py +++ b/docs/requirements/integration_matrix_data.py @@ -17,9 +17,6 @@ and the curated edge data has one obvious home. The generator reads: from __future__ import annotations -# Top-level meta/services.yml integration keys -> the in-axis target entity -# they wire the role into. Skipped on purpose: -# ldap/redis/mariadb/database -> svc-db-* (not on the axes). FRAMEWORK: dict[str, str] = { "sso": "keycloak", "matomo": "matomo", @@ -35,7 +32,6 @@ FRAMEWORK: dict[str, str] = { "libretranslate": "libretranslate", } -# Entity names = role suffix of every web-app-* role. WEB_APP: list[str] = [ "akaunting", "baserow", @@ -124,10 +120,7 @@ WEB_SVC: list[str] = [ ] ENTITIES: list[str] = WEB_APP + WEB_SVC -# (source, target, url, kind). kind: "check" or "coin". -# Verified upstream plugin/integration pages. EDGES: list[tuple[str, str, str, str]] = [ - # --- Nextcloud integration_* family + office/auth/analytics --- ( "nextcloud", "openproject", @@ -192,7 +185,6 @@ EDGES: list[tuple[str, str, str, str]] = [ ), ("nextcloud", "keycloak", "https://github.com/nextcloud/user_oidc", "check"), ("nextcloud", "matomo", "https://apps.nextcloud.com/apps/matomo", "check"), - # --- Mattermost plugins --- ( "mattermost", "gitlab", @@ -235,7 +227,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://docs.mattermost.com/onboard/sso-saml.html", "coin", ), - # --- GitLab native integrations --- ( "gitlab", "mattermost", @@ -257,7 +248,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "check", ), ("gitlab", "keycloak", "https://docs.gitlab.com/integration/saml/", "check"), - # --- Discourse plugins --- ( "discourse", "mattermost", @@ -302,7 +292,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://github.com/discourse/discourse-activity-pub", "check", ), - # --- Matrix (Synapse / hookshot / Element) --- ("matrix", "gitlab", "https://github.com/matrix-org/matrix-hookshot", "check"), ("matrix", "jira", "https://github.com/matrix-org/matrix-hookshot", "check"), ( @@ -323,7 +312,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://github.com/element-hq/element-web/blob/develop/docs/jitsi.md", "check", ), - # --- Moodle plugins --- ( "moodle", "bigbluebutton", @@ -336,13 +324,11 @@ EDGES: list[tuple[str, str, str, str]] = [ ("moodle", "jitsi", "https://moodle.org/plugins/mod_jitsi", "check"), ("moodle", "matomo", "https://moodle.org/plugins/tool_webanalytics", "check"), ("moodle", "openwebui", "https://moodle.org/plugins/aiprovider_openwebui", "check"), - # --- Jenkins plugins --- ("jenkins", "gitlab", "https://plugins.jenkins.io/gitlab-plugin", "check"), ("jenkins", "gitea", "https://plugins.jenkins.io/gitea/", "check"), ("jenkins", "mattermost", "https://plugins.jenkins.io/mattermost/", "check"), ("jenkins", "prometheus", "https://plugins.jenkins.io/prometheus", "check"), ("jenkins", "keycloak", "https://plugins.jenkins.io/oic-auth/", "check"), - # --- OpenProject --- ( "openproject", "nextcloud", @@ -361,7 +347,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://www.openproject.org/docs/system-admin-guide/authentication/openid-providers/", "coin", ), - # --- WordPress plugins --- ("wordpress", "matomo", "https://wordpress.org/plugins/matomo/", "check"), ("wordpress", "mastodon", "https://wordpress.org/plugins/activitypub/", "check"), ("wordpress", "discourse", "https://wordpress.org/plugins/wp-discourse/", "check"), @@ -389,7 +374,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://wordpress.org/plugins/video-manager-for-peertube/", "check", ), - # --- MediaWiki extensions --- ( "mediawiki", "keycloak", @@ -422,7 +406,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://www.mediawiki.org/wiki/Extension:AIEditingAssistant", "check", ), - # --- XWiki extensions --- ( "xwiki", "keycloak", @@ -435,7 +418,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://extensions.xwiki.org/xwiki/bin/view/Extension/Piwiki%20Integration", "check", ), - # --- Joomla --- ( "joomla", "keycloak", @@ -448,30 +430,25 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://extensions.joomla.org/extension/itcs-matomo/", "check", ), - # --- Friendica --- ("friendica", "matomo", "https://github.com/friendica/friendica-addons", "check"), - # --- Pretix --- ( "pretix", "keycloak", "https://docs.pretix.eu/en/latest/admin/installation/index.html", "check", ), - # --- PeerTube --- ( "peertube", "keycloak", "https://www.npmjs.com/package/peertube-plugin-auth-openid-connect", "check", ), - # --- BigBlueButton (Greenlight) --- ( "bigbluebutton", "keycloak", "https://docs.bigbluebutton.org/greenlight/v3/external-authentication/", "check", ), - # --- CRM / ERP: auth + email --- ( "zammad", "keycloak", @@ -533,7 +510,6 @@ EDGES: list[tuple[str, str, str, str]] = [ "https://docs.frappe.io/erpnext/user/manual/en/setting-up-email-account", "check", ), - # --- Other SSO-to-Keycloak (covered centrally today via the sso service) --- ( "baserow", "keycloak", diff --git a/eslint.config.js b/eslint.config.js index adb914ba45..449b3dc033 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -11,7 +11,7 @@ module.exports = [ "**/__pycache__/**", // Jinja2-templated JS — not valid JS until rendered. "roles/*/templates/**/*.js", - "roles/web-app-bigbluebutton/files/ep_redis_publisher_index.js", + "roles/web-app-bigbluebutton/files/javascript/ep_redis_publisher_index.js", ], }, { diff --git a/group_vars/all/02_tls.yml b/group_vars/all/02_tls.yml index abdecc72aa..89b900a6b3 100644 --- a/group_vars/all/02_tls.yml +++ b/group_vars/all/02_tls.yml @@ -23,7 +23,7 @@ CA_ROOT: C: "DE" O: "{{ DOMAIN_PRIMARY }}" OU: "Infinito.Nexus Root CA" - CN: "{{ DOMAIN_PRIMARY }} Root CA" + CN: "{{ (DOMAIN_PRIMARY ~ ' Root CA') if ((DOMAIN_PRIMARY ~ ' Root CA') | length <= 64) else DOMAIN_PRIMARY }}" CA_TRUST: cert_host: "{{ CA_ROOT.cert_host }}" cert_container: "/etc/ssl/certs/infinito-ca.pem" diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index ee585133f1..b0af51f9eb 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -10,9 +10,6 @@ WEBSERVER_CPUS_EFFECTIVE: >- ] | min }} -# Nginx requires an integer for worker_processes: -# - if cpus < 1 → 1 -# - else → floor to int WEBSERVER_WORKER_PROCESSES: >- {{ 1 if (WEBSERVER_CPUS_EFFECTIVE | float) < 1 @@ -27,5 +24,3 @@ WEBSERVER_WORKER_CONNECTIONS: >- (lookup('applications') | resource_filter(application_id, 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT)) | int ] | min }} - -# @todo It propably makes sense to distinguish between target and source mount path, so that the config files can be stored in the openresty volumes folder diff --git a/group_vars/all/05_paths.yml b/group_vars/all/05_paths.yml index 576f538d73..270384ce19 100644 --- a/group_vars/all/05_paths.yml +++ b/group_vars/all/05_paths.yml @@ -27,5 +27,13 @@ FILE_TOKENS: "{{ [DIR_SECRETS, 'tokens.yml'] | path_join }}" FILE_DATABASE_SECRETS: "{{ [DIR_SECRETS, 'databases.csv'] | path_join }}" DIR_RESCUE_DIAGNOSTICS: "/tmp/infinito-rescue-diagnostics" +FILE_DNS53_SAMPLER_LOG: "/var/log/infinito/dns53-sampler.log" FILE_ENVIRONMENT: "/etc/environment" # File to safe environment variables in + +CA_BUNDLE_CANDIDATES: # Where the distributions keep the extracted CA bundle, most likely first + - "/etc/ssl/certs/ca-certificates.crt" + - "/etc/pki/tls/certs/ca-bundle.crt" + - "/etc/ssl/ca-bundle.pem" + - "/etc/pki/tls/cacert.pem" + - "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" diff --git a/group_vars/all/08_networks.yml b/group_vars/all/08_networks.yml index 858137c1ef..6226ee22fc 100644 --- a/group_vars/all/08_networks.yml +++ b/group_vars/all/08_networks.yml @@ -68,6 +68,15 @@ PORT_BANDS: # nocheck: unused-var # consumed by the port-allocation plugin outs registry: start: 5000 end: 5001 + socks: + start: 9050 + end: 9050 + trans: + start: 9040 + end: 9040 + dns: + start: 9053 + end: 9053 public: ssh: start: 2201 diff --git a/group_vars/all/11_oidc.yml b/group_vars/all/11_oidc.yml index 6d578e6803..8c3c1b5e3f 100644 --- a/group_vars/all/11_oidc.yml +++ b/group_vars/all/11_oidc.yml @@ -12,10 +12,13 @@ # @see https://en.wikipedia.org/wiki/OpenID_Connect # Helper Variables: -_oidc_client_realm: "{{ OIDC.CLIENT.REALM if OIDC.CLIENT is defined and OIDC.CLIENT.REALM is defined else SOFTWARE_DOMAIN }}" -_oidc_url: "{{ ( OIDC.URL if (OIDC is defined and OIDC.URL is defined) else (lookup('tls', 'web-app-keycloak', 'url.base')) ).rstrip('/') }}" +_oidc_client_realm: "{{ OIDC_OVERRIDE.CLIENT.REALM if OIDC_OVERRIDE is defined and OIDC_OVERRIDE.CLIENT is defined and OIDC_OVERRIDE.CLIENT.REALM is defined else + SOFTWARE_DOMAIN }}" +_oidc_url: "{{ ( OIDC_OVERRIDE.URL if (OIDC_OVERRIDE is defined and OIDC_OVERRIDE.URL is defined) else (lookup('tls', 'web-app-keycloak', 'url.base')) ).rstrip('/') + }}" _oidc_client_issuer_url: "{{ _oidc_url ~ '/realms/' ~ _oidc_client_realm }}" -_oidc_client_id: "{{ OIDC.CLIENT.ID if OIDC.CLIENT is defined and OIDC.CLIENT.ID is defined else SOFTWARE_DOMAIN }}" +_oidc_client_id: "{{ OIDC_OVERRIDE.CLIENT.ID if OIDC_OVERRIDE is defined and OIDC_OVERRIDE.CLIENT is defined and OIDC_OVERRIDE.CLIENT.ID is defined else SOFTWARE_DOMAIN + }}" _oidc_account_url: "{{ _oidc_client_issuer_url ~ '/account' }}" _oidc_protocol_oidc: "{{ _oidc_client_issuer_url ~ '/protocol/openid-connect' }}" @@ -23,7 +26,7 @@ defaults_oidc: URL: "{{ _oidc_url }}" CLIENT: ID: "{{ _oidc_client_id }}" # Client identifier, typically matching your primary domain - SECRET: "{{ lookup('config', 'web-app-keycloak', 'credentials.oidc_client_secret', '') }}" # Defaults to the generated Keycloak credential; set OIDC.CLIENT.SECRET in the inventory to override + SECRET: "{{ lookup('config', 'web-app-keycloak', 'secrets.credentials.oidc_client_secret', '') }}" # Defaults to the generated Keycloak credential; set OIDC.CLIENT.SECRET in the inventory to override REALM: "{{ _oidc_client_realm }}" # The realm to which the client belongs in the OIDC provider ISSUER_URL: "{{ _oidc_client_issuer_url }}" # Issuer URL (must match discovery issuer) DISCOVERY_DOCUMENT: "{{ _oidc_client_issuer_url ~ '/.well-known/openid-configuration' }}" # URL for fetching the provider's configuration details @@ -44,3 +47,5 @@ defaults_oidc: GIVEN_NAME: "givenName" FAMILY_NAME: "surname" EMAIL: "email" + +OIDC: "{{ defaults_oidc | combine(OIDC_OVERRIDE | default({}, true), recursive=True) }}" diff --git a/group_vars/all/12_ldap.yml b/group_vars/all/12_ldap.yml index 08e5a9971a..03cb2ef62e 100644 --- a/group_vars/all/12_ldap.yml +++ b/group_vars/all/12_ldap.yml @@ -19,51 +19,19 @@ _ldap_user_id: "uid" _ldap_filters_users_all: "(|(objectclass=inetOrgPerson))" LDAP: - # Distinguished Names (DN) DN: - # ------------------------------------------------------------------------- - # Base DN / Suffix - # This is the top-level naming context for your directory, used as the - # default search base for most operations (e.g. adding users, groups). - # Example: “dc=example,dc=com” ROOT: "{{ LDAP_DN_BASE }}" ADMINISTRATOR: - # ------------------------------------------------------------------------- - # Data-Tree Administrator Bind DN - # The DN used to authenticate for regular directory operations under - # the data tree (adding users, modifying attributes, creating OUs, etc.). - # Typically: “cn=admin,dc=example,dc=com” DATA: "cn={{ lookup('users', 'administrator').username }},{{ LDAP_DN_BASE }}" - # ------------------------------------------------------------------------- - # Config-Tree Administrator Bind DN - # The DN used to authenticate against the cn=config backend when you - # need to load or modify schema, overlays, modules, or other server- - # level settings. - # Typically: “cn=admin,cn=config” CONFIGURATION: "cn={{ lookup('users', 'administrator').username }},cn=config" OU: - # ------------------------------------------------------------------------- - # Organizational Units (OUs) - # Pre-created containers in the directory tree to logically separate entries: - # – users: Contains all user objects (person/posixAccount entries). - # – groups: Contains organizational or business groups (e.g., departments, teams). - # – roles: Contains application-specific RBAC roles - # (e.g., "cn=app1-user", "cn=yourls-admin"). USERS: "ou=users,{{ LDAP_DN_BASE }}" GROUPS: "ou=groups,{{ LDAP_DN_BASE }}" ROLES: "ou=roles,{{ LDAP_DN_BASE }}" - # ------------------------------------------------------------------------- - # Additional Notes - # – Always bind as data_admin for CRUD on entries under your base DN. - # – Always bind as config_admin when you push schema-level LDIFs via ldapi:/// - # – Keeping these distinct prevents accidental use of config credentials - # for ordinary user/group operations, and vice versa. - - # Password to access dn.bind - BIND_CREDENTIAL: "{{ lookup('config','svc-db-openldap', 'credentials.administrator_database_password') }}" + BIND_CREDENTIAL: "{{ lookup('config','svc-db-openldap', 'secrets.credentials.administrator_database_password') }}" SERVER: DOMAIN: "{{ _ldap_name if _ldap_docker_network_enabled else _ldap_domain }}" # Mapping for public or locale access PORT: "{{ _ldap_server_port }}" @@ -75,19 +43,12 @@ LDAP: OBJECTS: STRUCTURAL: - person # Structural Classes define the core identity of an entry: - # • Specify mandatory attributes (e.g. sn, cn) - # • Each entry must have exactly one structural class - inetOrgPerson # An extension of person adding internet-related attributes - # (e.g. mail, employeeNumber) - posixAccount # Provides UNIX account attributes (uidNumber, gidNumber, - # homeDirectory) AUXILIARY: NEXTCLOUD_USER: "nextcloudUser" # Auxiliary Classes attach optional attributes without - # changing the entry’s structural role. Here they add - # nextcloudQuota and nextcloudEnabled for Nextcloud. SSH_PUBLIC_KEY: "ldapPublicKey" # Allows storing SSH public keys for services like Gitea. ATTRIBUTES: - # Attribut to identify the user ID: "{{ _ldap_user_id }}" MAIL: "mail" FULLNAME: "cn" @@ -101,7 +62,5 @@ LDAP: ALL: "{{ _ldap_filters_users_all }}" RBAC: FLAVORS: - # Valid values posixGroup, groupOfNames - groupOfNames - # - posixGroup EMPTY_MEMBER_DN: "cn=__empty__,{{ LDAP.DN.ROOT }}" diff --git a/group_vars/all/18_swarm.yml b/group_vars/all/18_swarm.yml index c20522d2fe..3a3d32edc3 100644 --- a/group_vars/all/18_swarm.yml +++ b/group_vars/all/18_swarm.yml @@ -3,6 +3,11 @@ DEPLOYMENT_MODE: "{{ 'swarm' if (groups['svc-swarm-node'] | default([]) | length SWARM_CLUSTER_AVAILABLE: "{{ (groups['svc-swarm-node'] | default([]) | length) > 0 }}" +# Exception: a role default would be invisible to the by-path include in +# roles/svc-db-openldap/tasks/01_docker.yml, which reaches into +# roles/sys-svc-compose/tasks/utils/post_deploy.yml after the role has finished. +swarm_stack_converge_retries: 600 + IS_STACK_HOST: >- {{ DEPLOYMENT_MODE == 'compose' or inventory_hostname in (groups['svc-swarm-manager'] | default([])) }} @@ -13,6 +18,8 @@ IS_BACKUP_HOST: >- STACK_HOST: >- {{ (groups['svc-swarm-manager'] | default([]))[0] | default(inventory_hostname) }} +swarm_stack_fatal_grace: 180 + swarm: manager: advertise_addr: "" diff --git a/group_vars/all/19_tor.yml b/group_vars/all/19_tor.yml new file mode 100644 index 0000000000..cab8b62d08 --- /dev/null +++ b/group_vars/all/19_tor.yml @@ -0,0 +1,7 @@ +--- +TOR_ONION_SSH_ENABLED: true + +TOR_EGRESS_ROUTER_ENABLED: true +TOR_EGRESS_VIRTUAL_NET_IPV4: "10.192.0.0/10" + +TOR_ONION_EXTRA_PORTS: "{{ ([{'onion_port': 22, 'target': '127.0.0.1:22'}] if (TOR_ONION_SSH_ENABLED | bool) else []) + lookup('tor_ports') }}" diff --git a/inventories/development/default.yml b/inventories/development/default.yml index 7cf77c4901..8df4658e11 100644 --- a/inventories/development/default.yml +++ b/inventories/development/default.yml @@ -37,7 +37,7 @@ design: colors: base: "#FFA500" -OIDC: +OIDC_OVERRIDE: CLIENT: SECRET: VERYUNSAFESAMPLEPASSWORD1234 users: diff --git a/library/database_query.py b/library/database_query.py index d05d725896..5cf6971b15 100755 --- a/library/database_query.py +++ b/library/database_query.py @@ -100,18 +100,9 @@ returns: _READ_ONLY_PREFIXES = ("SELECT ", "SHOW ", "EXPLAIN ", "WITH ", "VALUES ") _REQUIRED_CONFIG_KEYS = ("type", "container", "username", "name", "password") -# Match psycopg-style placeholders: %(identifier)s. The identifier must -# be a valid Python identifier so we don't chew through legitimate -# `%(` byte sequences inside SQL string literals. _NAMED_ARG_RE = re.compile(r"%\(([A-Za-z_][A-Za-z0-9_]*)\)s") -# Per-engine command-line + escape dialect. Each entry is consumed by -# `_build_cmd()` and `_escape_value()`. Adding a new backend = one -# entry here; the rest of the module is engine-agnostic. -# `binaries`: ordered preferred→fallback; only retried on rc=127 + -# "executable file not found" for the exact binary we tried (handles -# MariaDB ≥11 images that dropped the `mysql` symlink). _ENGINES: dict[str, dict[str, object]] = { "postgres": { "binaries": ("psql",), @@ -189,8 +180,6 @@ def _resolve_exec_target(config: dict) -> str: def _binary_missing(proc: subprocess.CompletedProcess[str], binary: str) -> bool: - # Match narrowly on the OCI message naming the exact binary we tried — - # otherwise an engine-side rc=127 would silently mask real failures. if proc.returncode != 127: return False combined = (proc.stdout or "") + (proc.stderr or "") @@ -209,7 +198,6 @@ def _escape_value(value: Any, db_type: str) -> str: if value is None: return "NULL" if isinstance(value, bool): - # bool is a subclass of int; check before the int branch below. return str(engine["bool_true"] if value else engine["bool_false"]) if isinstance(value, (int, float)): return repr(value) diff --git a/meta/packages.yml b/meta/packages.yml index a34e574fa7..c8edf26784 100644 --- a/meta/packages.yml +++ b/meta/packages.yml @@ -117,7 +117,7 @@ java-jdk: Archlinux: - jdk11-openjdk Debian: - - openjdk-11-jdk + - default-jdk RedHat: - java-21-openjdk-devel fedora: @@ -298,6 +298,6 @@ wireshark-gui: Archlinux: - wireshark-qt Debian: - - wireshark-qt + - wireshark RedHat: - wireshark diff --git a/package-lock.json b/package-lock.json index 481f6b1d42..7726171f79 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,258 @@ "devDependencies": { "@eslint/js": "^10.0.1", "@playwright/test": "^1.62.1", - "eslint": "^10.8.1", + "eslint": "^10.9.1", "eslint-plugin-playwright": "^2.10.5", - "globals": "^17.9.0" + "globals": "^17.9.0", + "stylelint": "^17.14.1" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@cacheable/memory": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", + "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/utils": "^2.5.0", + "@keyv/bigmap": "^1.3.1", + "hookified": "^1.15.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/memory/node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/memory/node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/@cacheable/utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", + "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.5.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/utils/node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.3.0.tgz", + "integrity": "sha512-c5ihYsPkdG6JCkU2zTMm4+k6r7RXuGxtWYhu5DHMIiF1FHzrfmHL5so11AoFpUv/tu61xfcmT4AmKoFfMPoqdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz", + "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.8.tgz", + "integrity": "sha512-CpMLjAvwQg3BL5S0IeqsZNMH7EQrEWi0kLKOC13ZBF0ZwERiLWlibNPJr8G1kdU3Ms/r2KiNrF81pUh2HwAHdg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz", + "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/media-query-list-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@csstools/media-query-list-parser/-/media-query-list-parser-5.0.0.tgz", + "integrity": "sha512-T9lXmZOfnam3eMERPsszjY5NK0jX8RmThmmm99FZ8b7z8yMaFZWKwLWGZuTwdO3ddRY5fy13GmmEYZXB4I98Eg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + } + }, + "node_modules/@csstools/selector-resolve-nested": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@csstools/selector-resolve-nested/-/selector-resolve-nested-4.0.1.tgz", + "integrity": "sha512-j3vdQu0XwLME5qOTWxm8cnmvsf423R2YL6DbKklCHZwkDm7UdKNu6RPlw4REIJhSlKBICY3B70/7QZdicLqZgg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "postcss-selector-parser": "^7.1.1" + } + }, + "node_modules/@csstools/selector-specificity": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@csstools/selector-specificity/-/selector-specificity-6.0.0.tgz", + "integrity": "sha512-4sSgl78OtOXEX/2d++8A83zHNTgwCJMaR24FvsYL7Uf/VS8HZk9PTwR51elTbGqMuwH3szLvvOXEaVnqn0Z3zA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "postcss-selector-parser": "^7.1.1" } }, "node_modules/@eslint-community/eslint-utils": { @@ -209,6 +458,51 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/@playwright/test": { "version": "1.62.1", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz", @@ -225,6 +519,19 @@ "node": ">=20" } }, + "node_modules/@sindresorhus/merge-streams": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", + "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@types/esrecurse": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", @@ -286,6 +593,49 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/balanced-match": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", @@ -309,6 +659,107 @@ "node": "20 || >=22" } }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", + "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/memory": "^2.2.0", + "@cacheable/utils": "^2.5.0", + "hookified": "^1.15.0", + "keyv": "^5.6.0", + "qified": "^0.10.1" + } + }, + "node_modules/cacheable/node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/colord": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/colord/-/colord-2.10.0.tgz", + "integrity": "sha512-AidJptpBJmjTclAp9BkLwJi0T93fo5epJnbaZslpg6QVzpHjAiveF55mE9AcUJiGMqRHgMDY8soMsQtuNYMHfw==", + "dev": true, + "license": "MIT" + }, + "node_modules/cosmiconfig": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz", + "integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -324,6 +775,43 @@ "node": ">= 8" } }, + "node_modules/css-functions-list": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/css-functions-list/-/css-functions-list-3.3.3.tgz", + "integrity": "sha512-8HFEBPKhOpJPEPu70wJJetjKta86Gw9+CCyCnB3sui2qQfOvRyqBy4IKLKKAwdMpWb2lHXWk9Wb4Z6AmaUT1Pg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -349,6 +837,33 @@ "dev": true, "license": "MIT" }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -363,9 +878,9 @@ } }, "node_modules/eslint": { - "version": "10.8.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.8.1.tgz", - "integrity": "sha512-wqA7W2jbsC/BnV9Iv1UZpKVFkO1AdNoSmYW8NWG4HNOBbkAMvIqDZ27pI2f07dqn583NcIC44ckjAcOXDL1QbQ==", + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.9.1.tgz", + "integrity": "sha512-9VaAkDURekixUQJy0oJYl2DcN6oKMfxay7XzaGYAWQwsb6qfKf+x76R2k1L8kb1boc+FyCAaTA9GmiKaaiaF+A==", "dev": true, "license": "MIT", "workspaces": [ @@ -540,6 +1055,36 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", @@ -554,6 +1099,43 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-uri": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", + "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastest-levenshtein": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", + "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4.9.1" + } + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -567,6 +1149,19 @@ "node": ">=16.0.0" } }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -620,6 +1215,19 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/get-east-asian-width": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -633,6 +1241,47 @@ "node": ">=10.13.0" } }, + "node_modules/global-modules": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-2.0.0.tgz", + "integrity": "sha512-NGbfmJBp9x8IxyJSd1P+otYK8vonoJactOogrVfFRIAEY1ukil8RSKDz2Yo7wh1oihl51l/r6W4epkeKJHqL8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "global-prefix": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/global-prefix": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-3.0.0.tgz", + "integrity": "sha512-awConJSVCHVGND6x3tmMaKcQvwXLhjdkmomy2W+Goaui8YPgYgXJZewhg3fWC+DlfqqQuWg8AwqjGTD2nAPVWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "^1.3.5", + "kind-of": "^6.0.2", + "which": "^1.3.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/global-prefix/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, "node_modules/globals": { "version": "17.9.0", "resolved": "https://registry.npmjs.org/globals/-/globals-17.9.0.tgz", @@ -646,6 +1295,91 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/globby": { + "version": "16.2.4", + "resolved": "https://registry.npmjs.org/globby/-/globby-16.2.4.tgz", + "integrity": "sha512-c8B/VNLmxRcmqqenRA9t+9IyOjf9+V6lTxPaUJLqOCONdQkWZ0ETYgX0qbtJqPsgCNusT9MZ5Jeidw8Eb9tn2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/merge-streams": "^4.0.0", + "fast-glob": "^3.3.3", + "ignore": "^7.0.5", + "is-path-inside": "^4.0.0", + "micromatch": "^4.0.8", + "slash": "^5.1.0", + "unicorn-magic": "^0.4.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globby/node_modules/ignore": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz", + "integrity": "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/globjoin": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/globjoin/-/globjoin-0.1.4.tgz", + "integrity": "sha512-xYfnw62CKG8nLkZBfWbhWwDw02CHty86jfPcc2cr3ZfeuK9ysoVPPEUxf21bAD/rWAgk52SuBrLJlefNy8mvFg==", + "dev": true, + "license": "MIT" + }, + "node_modules/has-flag": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-5.0.1.tgz", + "integrity": "sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hashery": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", + "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^1.15.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/hookified": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", + "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/html-tags": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/html-tags/-/html-tags-5.1.0.tgz", + "integrity": "sha512-n6l5uca7/y5joxZ3LUePhzmBFUJ+U2YWzhMa8XUTecSeSlQiZdF5XAd/Q3/WUl0VsXgUwWi8I7CNIwdI5WN1SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -656,6 +1390,44 @@ "node": ">= 4" } }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/import-meta-resolve": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", @@ -666,6 +1438,20 @@ "node": ">=0.8.19" } }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -676,6 +1462,16 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -689,6 +1485,29 @@ "node": ">=0.10.0" } }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-path-inside": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-4.0.0.tgz", + "integrity": "sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -696,6 +1515,36 @@ "dev": true, "license": "ISC" }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", + "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", @@ -703,6 +1552,13 @@ "dev": true, "license": "MIT" }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -727,6 +1583,16 @@ "json-buffer": "3.0.1" } }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", @@ -741,6 +1607,13 @@ "node": ">= 0.8.0" } }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -757,6 +1630,68 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/lodash.truncate": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", + "integrity": "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw==", + "dev": true, + "license": "MIT" + }, + "node_modules/mathml-tag-names": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mathml-tag-names/-/mathml-tag-names-4.0.0.tgz", + "integrity": "sha512-aa6AU2Pcx0VP/XWnh8IGL0SYSgQHDT6Ucror2j2mXeFAlN3ahaNs8EZtG1YiticMkSLj3Gt6VPFfZogt7G5iFQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/meow": { + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/meow/-/meow-14.1.0.tgz", + "integrity": "sha512-EDYo6VlmtnumlcBCbh1gLJ//9jvM/ndXHfVXIFrZVr6fGcwTUyCTFNTLCKuY3ffbK8L/+3Mzqnd58RojiZqHVw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, "node_modules/minimatch": { "version": "10.2.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", @@ -780,6 +1715,25 @@ "dev": true, "license": "MIT" }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -787,6 +1741,16 @@ "dev": true, "license": "MIT" }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -837,6 +1801,38 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -857,6 +1853,26 @@ "node": ">=8" } }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/playwright": { "version": "1.62.1", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", @@ -889,6 +1905,83 @@ "node": ">=20" } }, + "node_modules/postcss": { + "version": "8.5.26", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz", + "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.17", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-safe-parser": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/postcss-safe-parser/-/postcss-safe-parser-7.0.1.tgz", + "integrity": "sha512-0AioNCJZ2DPYz5ABT6bddIqlhgwhpHZ/l65YAYo0BCIn0xiDpsnTHz0gnoTGk0OXZW0JRs+cDwL8u/teRdz+8A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss-safe-parser" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "engines": { + "node": ">=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/postcss-selector-parser": { + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.5.tgz", + "integrity": "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -909,6 +2002,92 @@ "node": ">=6" } }, + "node_modules/qified": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", + "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^2.1.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/qified/node_modules/hookified": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", + "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", + "dev": true, + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -932,6 +2111,316 @@ "node": ">=8" } }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slash": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", + "integrity": "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/stylelint": { + "version": "17.14.1", + "resolved": "https://registry.npmjs.org/stylelint/-/stylelint-17.14.1.tgz", + "integrity": "sha512-xVQwyiuxALUBNB2fBe0tmNemg9KqLtdj3T64mioFDar79B2cU8LIyz+3KL6LdiHs9NkeNfwxpKSaIVOY8f112g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/stylelint" + }, + { + "type": "github", + "url": "https://github.com/sponsors/stylelint" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.2.1", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-syntax-patches-for-csstree": "^1.1.6", + "@csstools/css-tokenizer": "^4.0.0", + "@csstools/media-query-list-parser": "^5.0.0", + "@csstools/selector-resolve-nested": "^4.0.0", + "@csstools/selector-specificity": "^6.0.0", + "colord": "^2.9.3", + "cosmiconfig": "^9.0.2", + "css-functions-list": "^3.3.3", + "css-tree": "^3.2.1", + "debug": "^4.4.3", + "fast-glob": "^3.3.3", + "fastest-levenshtein": "^1.0.16", + "file-entry-cache": "^11.1.5", + "global-modules": "^2.0.0", + "globby": "^16.2.1", + "globjoin": "^0.1.4", + "html-tags": "^5.1.0", + "ignore": "^7.0.5", + "import-meta-resolve": "^4.2.0", + "mathml-tag-names": "^4.0.0", + "meow": "^14.1.0", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.5.16", + "postcss-safe-parser": "^7.0.1", + "postcss-selector-parser": "^7.1.4", + "postcss-value-parser": "^4.2.0", + "string-width": "^8.2.1", + "supports-hyperlinks": "^4.5.0", + "svg-tags": "^1.0.0", + "table": "^6.9.0", + "write-file-atomic": "^7.0.1" + }, + "bin": { + "stylelint": "bin/stylelint.mjs" + }, + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/stylelint/node_modules/ansi-regex": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", + "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/stylelint/node_modules/file-entry-cache": { + "version": "11.1.5", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^6.1.23" + } + }, + "node_modules/stylelint/node_modules/flat-cache": { + "version": "6.1.23", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cacheable": "^2.5.0", + "flatted": "^3.4.2", + "hookified": "^1.15.0" + } + }, + "node_modules/stylelint/node_modules/ignore": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.6.tgz", + "integrity": "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/stylelint/node_modules/string-width": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.2.tgz", + "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/stylelint/node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/supports-hyperlinks": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-4.5.0.tgz", + "integrity": "sha512-ZW2OvfeCXrNTbLakPUzjQG922EeGCOteFSVoek5DKStTh898wf7zgtuFlzQN8HfZCxC3Eh02yJVrRW51hADf+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^5.0.1", + "supports-color": "^10.2.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" + } + }, + "node_modules/svg-tags": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/svg-tags/-/svg-tags-1.0.0.tgz", + "integrity": "sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==", + "dev": true + }, + "node_modules/table": { + "version": "6.9.0", + "resolved": "https://registry.npmjs.org/table/-/table-6.9.0.tgz", + "integrity": "sha512-9kY+CygyYM6j02t5YFHbNz2FN5QmYGv9zAjVp4lCDjlCw7amdckXlEt/bjMhUIfj4ThGRE4gCUH5+yGnNuPo5A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "ajv": "^8.0.1", + "lodash.truncate": "^4.4.2", + "slice-ansi": "^4.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/table/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/table/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -945,6 +2434,19 @@ "node": ">= 0.8.0" } }, + "node_modules/unicorn-magic": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.4.0.tgz", + "integrity": "sha512-wH590V9VNgYH9g3lH9wWjTrUoKsjLF6sGLjhR4sH1LWpLmCOH0Zf7PukhDA8BiS7KHe4oPNkcTHqYkj7SOGUOw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", @@ -955,6 +2457,13 @@ "punycode": "^2.1.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -981,6 +2490,19 @@ "node": ">=0.10.0" } }, + "node_modules/write-file-atomic": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-7.0.1.tgz", + "integrity": "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg==", + "dev": true, + "license": "ISC", + "dependencies": { + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index e6750e99d6..5fcbd18638 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,12 @@ "devDependencies": { "@eslint/js": "^10.0.1", "@playwright/test": "^1.62.1", - "eslint": "^10.8.1", + "eslint": "^10.9.1", "eslint-plugin-playwright": "^2.10.5", - "globals": "^17.9.0" + "globals": "^17.9.0", + "stylelint": "^17.14.1" + }, + "overrides": { + "brace-expansion": "^5.0.9" } } diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index d334c54434..16e17e6341 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -1,7 +1,7 @@ # Maintainer: Kevin Veen-Birkenbach pkgname=infinito-nexus -pkgver=12.0.0 +pkgver=13.0.0 pkgrel=1 pkgdesc="Meta package for Infinito.Nexus host dependencies (dev + CI)." arch=('any') diff --git a/packaging/debian/changelog b/packaging/debian/changelog index a51bdfea27..f42e064389 100644 --- a/packaging/debian/changelog +++ b/packaging/debian/changelog @@ -1,3 +1,152 @@ +infinito-nexus (13.0.0-1) unstable; urgency=medium + + * **Tor as a first-class deployment axis.** The new *svc-net-tor* role routes onion + names through Tor via DNS instead of per-app proxies, offers a chutney flavor for + private-net test deployments, and ties its dnsmasq listener to ownership rather than + the deploy mode. Applications follow: server-side OIDC discovery and token exchange + reach plaintext onion issuers through the SOCKS proxy (WordPress, Joomla, PeerTube, + Mobilizon, EspoCRM, Nextcloud), session cookies drop the *Secure* flag where an onion + cannot carry it (Taiga, Pixelfed, Joomla), and mail authenticates on the submission + port the onion relay actually serves. The deploy matrix gained a tor axis with an + onion marker plus enforced and exclusive modes, and lint now requires the onion in + every variant. See the [svc-net-tor](roles/svc-net-tor/README.md) README. + + * **Single sign-on across protocols and domains.** Keycloak imports a SAML client for + every app that asks for one; SuiteCRM authenticates against it via SAML instead of a + proxy, and Shopware provisions its admin through AdminOpenAuth with the front and + back channel split. Sessions are shared across app domains, the issuer is pinned to + the canonical OIDC URL, each consumer's redirect scheme resolves on its own side, and + the logout sweep runs where the visitor is looking. Directory users are read through + one lookup so seeding cannot diverge. + + * **One CI chain instead of four workflows.** The deploy workflows collapse into a + single chunk chain gated by one validation job, with every variant getting its own + row and rotating distro, filesystem and tor axes. Selection tokens pin deploy axes, + retriggers reproduce the exact selection of the source run in every mode, and the + regular line resumes where the source stopped. Fork code no longer runs with the base + repository token, workflow tokens are scoped to the jobs that need them, superseded + runs are force-cancelled, and a mid-run budget SIGKILL is counted as skipped rather + than green. Apt call sites are bounded so a stalled mirror cannot burn a job budget. + + * **Restore verified against real dumps.** The *recover* CLI replays a generation's + database and cluster dumps, reads the generation's own layout instead of guessing it, + and places each dump by the engine the backup observed rather than by name alone. The + *svc-bkp-volume-2-local* drill now empties every volume it claims to test, fails on a + database that was never dumped, and stops the backup timers before it goes + destructive. Baudolo is pinned per host, its contract read from baudolo itself. + + * **A probe for every container.** Health checks are composed from prefixes and are + mandatory: every declared image either carries a probe or states why it cannot have + one, enforced from both sides. Probes hit the port the container actually binds, no + longer derive an HTTP Host from a kernel hostname, and are defined once instead of per + proxy. Rescue diagnostics pin the dnsmasq listener loss to its moment, sample what the + resolver answers rather than just its socket, probe the daemon.json upstreams, and + record the whole boot instead of the last 10 000 lines. + + * **Single points of truth, enforced by lint.** The new *sys-lint* role pins the + GitHub-release lint tools. Every mount target has one spot in *meta/volumes.yml* and + container paths are derived from it, *default.env* is the enforced source of the + primary domain, *container_backup* is rejected where no volume exists, and role + credentials live at *meta/secrets.yml*. Linters no longer read gitignored build + output, comments are checked in every file rather than only changed ones, and every + shipped script requires a mirrored unit test. + + * **Tests in every language the project ships.** The quality gate parses each shipped + language and runs its unit suite; the PHP and Ruby interpreters are baked into the + image, and the JavaScript, PHP and Ruby suites are reported in the CI summary + alongside Python. Playwright stages the persona flows once per run and mounts them + read-only, and the workspace environment suite splits into base, compose and swarm + tracks. + + * **Swarm and proxy operation.** Convergence gates read one budget sized for a real + stack, print every task row when a stack fails to converge, and give up on a terminal + task; the deployment mode a stack was deployed with is resolved instead of assumed. + OpenResty reloads a vhost, lua or redirect config instead of redeploying the task. + GitLab ships its config trees as swarm configs rather than host binds, and role + templates expand through a lookup instead of inline Jinja. + + * **New and reshaped roles.** *sys-svc-nss* is split out of *sys-hostname*, + *web-svc-mirror* serves frontend assets as a privacy proxy, PeerTube becomes + clearnet-only, and roles that could not run were deleted rather than repaired. CLI + tools install via pip instead of pkgmgr. + + * **Image and dependency version jumps (net since 12.0.0):** + + *Applications* + * *web-app-erpnext*: v16.26.2 to v16.32.3 + * *web-app-gitlab*: v19.1.2 to v19.3.0 (all six CNG component images) + * *web-app-semaphore*: v2.18.25 to v2.19.8 + * *web-app-nextcloud*: PHP 33-fpm-alpine to 34-fpm-alpine, nginx 1.31.2 to 1.31.3 + * *web-app-shopware*: 6.7.8.2 to 6.7.13.0, OpenSearch 3.7.0 to 3.8.0 + * *web-app-matomo*: 5.11.2 to 5.13.0 + * *web-app-matrix*: Synapse v1.156.0 to v1.159.0, Element v1.12.23 to v1.12.26 + * *web-app-mattermost*: 11.9.0 to 11.10.1 + * *web-app-keycloak*: 26.7.0 to 26.7.2, oauth2-proxy v7.15.3 to v7.15.4 + * *web-app-gitea*: 1.26.4 to 1.27.2 + * *web-app-funkwhale*: 2.0.6 to 2.0.9 (api and front) + * *web-app-penpot*: 2.16.2 to 2.17.1 (frontend, backend, exporter) + * *web-app-espocrm*: 10.0.2 to 10.0.6 + * *web-app-opencloud*: 7.2.1 to 7.2.4 + * *web-app-seaweedfs*: 4.39 to 4.44 + * *web-app-snipe-it*: v8.6.3-alpine to v8.7.2-alpine + * *web-app-wordpress*: 7.0.1 to 7.1.0 + * *web-app-peertube*: v8.2.2 to v8.2.4 + * *web-app-joomla*: 6.1.2-php8.3-apache to 6.1.3-php8.3-apache + * *web-app-jira*: 11.3.8 to 11.3.10 + * *web-app-confluence*: 10.2.14 to 10.2.15 + * *web-app-baserow*: 2.3.1 to 2.3.3 + * *web-app-flowise*: 3.1.3 to 3.1.4 + * *web-app-mailu*: 1.5.3 to 1.5.4 + * *web-app-pgadmin*: 9.16 to 9.17 + * *web-app-prometheus*: Prometheus v3.13.1 to v3.14.0, Alertmanager v0.33.1 to + v0.34.0, node-exporter v1.12.0 to v1.12.1 + * *web-app-opentalk*: LiveKit v1.13.3 to v1.13.5, RabbitMQ 4.3.2 to 4.3.4; the + frontend (v2.9.0), controller (v0.34.1) and recorder (v0.16.2) stay pinned until + the set is released as a bundle and *recorder.toml* is migrated + * *web-app-magento*: OpenSearch 3.7.0 to 3.8.0; PHP held at 8.4-fpm and MariaDB at + 11.4, both deliberately fenced against the image bot + * *web-app-socialhome*: newly pinned to 2026.6.16 + * *web-app-bluesky* and *web-app-bridgy-fed*: upstream git refs pinned to commits + + *Services and infrastructure* + * *svc-ai-ollama*: 0.31.2 to 0.32.15 + * *svc-db-elasticsearch*: 9.4.3 to 9.5.2 + * *svc-db-qdrant*: v1.18.2 to v1.19.0 + * *svc-runner*: Ubuntu 24.04 to 26.04 + * *sys-ctl-hlth-csp*: 2.1.2 to 2.2.1 + * *web-svc-coturn*: 4.14.0 to 4.17.2 + * *web-svc-logout*: *latest* to universal-logout v1.3.1 + * *web-svc-xmpp*: 26.04 to 26.07 + * *test-e2e-playwright*: v1.61.1-noble to v1.62.1-noble + * *svc-net-tor*: newly on debian trixie-slim + * *svc-bkp-volume-2-local*: newly on alpine 3.24 + + *Toolchain and dependencies* + * *backup-docker-to-local* (*baudolo*): pinned to 7.0.1, via 6.0.0 and 7.0.0 + * *ruff*: 0.16.0 to 0.16.4 + * *@playwright/test*: ^1.61.1 to ^1.62.1 + * *eslint*: ^10.6.0 to ^10.9.0, *globals*: ^17.7.0 to ^17.9.0 + * *stylelint*: ^16.0.0 added + * *brace-expansion*: overridden to ^5.0.9, past three DoS advisories + * *keycloak-js*: 24.0.5 to 26.2.4, loaded as an ES module + * *bootstrap*: 5.3.3 to 5.3.8, *@fortawesome/fontawesome-free*: 6.5.1 to 7.3.1 + * *roles/sys-lint* pins the GitHub-release tools: actionlint v1.7.12, + hadolint v2.15.1, shfmt v3.13.1 + + **Renamed** + + * Role credential declarations move from *meta/credentials.yml* to *meta/secrets.yml*, + addressed at *secrets.credentials* like every other meta file. + * The NSS half of *sys-hostname* becomes its own role, *sys-svc-nss*. + + **Contributors** + + * [Kevin Veen-Birkenbach](https://veen.world): Tor deployment axis, SAML and + cross-domain SSO, CI chunk chain, generation-level recovery, health-check and + lint enforcement, multi-language test suites + + -- Kevin Veen-Birkenbach Wed, 26 Aug 2026 09:39:19 +0200 + infinito-nexus (12.0.0-1) unstable; urgency=medium * **Docker Swarm as a second deployment mode.** Roles can now be deployed across diff --git a/packaging/fedora/infinito-nexus.spec b/packaging/fedora/infinito-nexus.spec index e4fc1ec6ff..51e99a8f89 100644 --- a/packaging/fedora/infinito-nexus.spec +++ b/packaging/fedora/infinito-nexus.spec @@ -1,5 +1,5 @@ Name: infinito-nexus -Version: 12.0.0 +Version: 13.0.0 Release: 1%{?dist} Summary: Meta package for Infinito.Nexus host dependencies @@ -22,7 +22,7 @@ Requires: openssh-clients # # EL9 AppStream exposes only python3.9 via the generic python3 capability. # In those environments we still bootstrap Python 3.11+ separately via -# roles/dev-python/files/install.sh, but the RPM metadata must remain +# roles/dev-python/files/shell/install.sh, but the RPM metadata must remain # installable from the stock distro repositories. %if 0%{?rhel} == 9 Requires: python3 @@ -58,6 +58,152 @@ install -d %{buildroot}%{_docdir}/%{name} %doc %{_docdir}/%{name}/DEPENDENCIES %changelog +* Wed Aug 26 2026 Kevin Veen-Birkenbach - 13.0.0-1 +- * **Tor as a first-class deployment axis.** The new *svc-net-tor* role routes onion +- names through Tor via DNS instead of per-app proxies, offers a chutney flavor for +- private-net test deployments, and ties its dnsmasq listener to ownership rather than +- the deploy mode. Applications follow: server-side OIDC discovery and token exchange +- reach plaintext onion issuers through the SOCKS proxy (WordPress, Joomla, PeerTube, +- Mobilizon, EspoCRM, Nextcloud), session cookies drop the *Secure* flag where an onion +- cannot carry it (Taiga, Pixelfed, Joomla), and mail authenticates on the submission +- port the onion relay actually serves. The deploy matrix gained a tor axis with an +- onion marker plus enforced and exclusive modes, and lint now requires the onion in +- every variant. See the [svc-net-tor](roles/svc-net-tor/README.md) README. + +- * **Single sign-on across protocols and domains.** Keycloak imports a SAML client for +- every app that asks for one; SuiteCRM authenticates against it via SAML instead of a +- proxy, and Shopware provisions its admin through AdminOpenAuth with the front and +- back channel split. Sessions are shared across app domains, the issuer is pinned to +- the canonical OIDC URL, each consumer's redirect scheme resolves on its own side, and +- the logout sweep runs where the visitor is looking. Directory users are read through +- one lookup so seeding cannot diverge. + +- * **One CI chain instead of four workflows.** The deploy workflows collapse into a +- single chunk chain gated by one validation job, with every variant getting its own +- row and rotating distro, filesystem and tor axes. Selection tokens pin deploy axes, +- retriggers reproduce the exact selection of the source run in every mode, and the +- regular line resumes where the source stopped. Fork code no longer runs with the base +- repository token, workflow tokens are scoped to the jobs that need them, superseded +- runs are force-cancelled, and a mid-run budget SIGKILL is counted as skipped rather +- than green. Apt call sites are bounded so a stalled mirror cannot burn a job budget. + +- * **Restore verified against real dumps.** The *recover* CLI replays a generation's +- database and cluster dumps, reads the generation's own layout instead of guessing it, +- and places each dump by the engine the backup observed rather than by name alone. The +- *svc-bkp-volume-2-local* drill now empties every volume it claims to test, fails on a +- database that was never dumped, and stops the backup timers before it goes +- destructive. Baudolo is pinned per host, its contract read from baudolo itself. + +- * **A probe for every container.** Health checks are composed from prefixes and are +- mandatory: every declared image either carries a probe or states why it cannot have +- one, enforced from both sides. Probes hit the port the container actually binds, no +- longer derive an HTTP Host from a kernel hostname, and are defined once instead of per +- proxy. Rescue diagnostics pin the dnsmasq listener loss to its moment, sample what the +- resolver answers rather than just its socket, probe the daemon.json upstreams, and +- record the whole boot instead of the last 10 000 lines. + +- * **Single points of truth, enforced by lint.** The new *sys-lint* role pins the +- GitHub-release lint tools. Every mount target has one spot in *meta/volumes.yml* and +- container paths are derived from it, *default.env* is the enforced source of the +- primary domain, *container_backup* is rejected where no volume exists, and role +- credentials live at *meta/secrets.yml*. Linters no longer read gitignored build +- output, comments are checked in every file rather than only changed ones, and every +- shipped script requires a mirrored unit test. + +- * **Tests in every language the project ships.** The quality gate parses each shipped +- language and runs its unit suite; the PHP and Ruby interpreters are baked into the +- image, and the JavaScript, PHP and Ruby suites are reported in the CI summary +- alongside Python. Playwright stages the persona flows once per run and mounts them +- read-only, and the workspace environment suite splits into base, compose and swarm +- tracks. + +- * **Swarm and proxy operation.** Convergence gates read one budget sized for a real +- stack, print every task row when a stack fails to converge, and give up on a terminal +- task; the deployment mode a stack was deployed with is resolved instead of assumed. +- OpenResty reloads a vhost, lua or redirect config instead of redeploying the task. +- GitLab ships its config trees as swarm configs rather than host binds, and role +- templates expand through a lookup instead of inline Jinja. + +- * **New and reshaped roles.** *sys-svc-nss* is split out of *sys-hostname*, +- *web-svc-mirror* serves frontend assets as a privacy proxy, PeerTube becomes +- clearnet-only, and roles that could not run were deleted rather than repaired. CLI +- tools install via pip instead of pkgmgr. + +- * **Image and dependency version jumps (net since 12.0.0):** + +- *Applications* +- * *web-app-erpnext*: v16.26.2 to v16.32.3 +- * *web-app-gitlab*: v19.1.2 to v19.3.0 (all six CNG component images) +- * *web-app-semaphore*: v2.18.25 to v2.19.8 +- * *web-app-nextcloud*: PHP 33-fpm-alpine to 34-fpm-alpine, nginx 1.31.2 to 1.31.3 +- * *web-app-shopware*: 6.7.8.2 to 6.7.13.0, OpenSearch 3.7.0 to 3.8.0 +- * *web-app-matomo*: 5.11.2 to 5.13.0 +- * *web-app-matrix*: Synapse v1.156.0 to v1.159.0, Element v1.12.23 to v1.12.26 +- * *web-app-mattermost*: 11.9.0 to 11.10.1 +- * *web-app-keycloak*: 26.7.0 to 26.7.2, oauth2-proxy v7.15.3 to v7.15.4 +- * *web-app-gitea*: 1.26.4 to 1.27.2 +- * *web-app-funkwhale*: 2.0.6 to 2.0.9 (api and front) +- * *web-app-penpot*: 2.16.2 to 2.17.1 (frontend, backend, exporter) +- * *web-app-espocrm*: 10.0.2 to 10.0.6 +- * *web-app-opencloud*: 7.2.1 to 7.2.4 +- * *web-app-seaweedfs*: 4.39 to 4.44 +- * *web-app-snipe-it*: v8.6.3-alpine to v8.7.2-alpine +- * *web-app-wordpress*: 7.0.1 to 7.1.0 +- * *web-app-peertube*: v8.2.2 to v8.2.4 +- * *web-app-joomla*: 6.1.2-php8.3-apache to 6.1.3-php8.3-apache +- * *web-app-jira*: 11.3.8 to 11.3.10 +- * *web-app-confluence*: 10.2.14 to 10.2.15 +- * *web-app-baserow*: 2.3.1 to 2.3.3 +- * *web-app-flowise*: 3.1.3 to 3.1.4 +- * *web-app-mailu*: 1.5.3 to 1.5.4 +- * *web-app-pgadmin*: 9.16 to 9.17 +- * *web-app-prometheus*: Prometheus v3.13.1 to v3.14.0, Alertmanager v0.33.1 to +- v0.34.0, node-exporter v1.12.0 to v1.12.1 +- * *web-app-opentalk*: LiveKit v1.13.3 to v1.13.5, RabbitMQ 4.3.2 to 4.3.4; the +- frontend (v2.9.0), controller (v0.34.1) and recorder (v0.16.2) stay pinned until +- the set is released as a bundle and *recorder.toml* is migrated +- * *web-app-magento*: OpenSearch 3.7.0 to 3.8.0; PHP held at 8.4-fpm and MariaDB at +- 11.4, both deliberately fenced against the image bot +- * *web-app-socialhome*: newly pinned to 2026.6.16 +- * *web-app-bluesky* and *web-app-bridgy-fed*: upstream git refs pinned to commits + +- *Services and infrastructure* +- * *svc-ai-ollama*: 0.31.2 to 0.32.15 +- * *svc-db-elasticsearch*: 9.4.3 to 9.5.2 +- * *svc-db-qdrant*: v1.18.2 to v1.19.0 +- * *svc-runner*: Ubuntu 24.04 to 26.04 +- * *sys-ctl-hlth-csp*: 2.1.2 to 2.2.1 +- * *web-svc-coturn*: 4.14.0 to 4.17.2 +- * *web-svc-logout*: *latest* to universal-logout v1.3.1 +- * *web-svc-xmpp*: 26.04 to 26.07 +- * *test-e2e-playwright*: v1.61.1-noble to v1.62.1-noble +- * *svc-net-tor*: newly on debian trixie-slim +- * *svc-bkp-volume-2-local*: newly on alpine 3.24 + +- *Toolchain and dependencies* +- * *backup-docker-to-local* (*baudolo*): pinned to 7.0.1, via 6.0.0 and 7.0.0 +- * *ruff*: 0.16.0 to 0.16.4 +- * *@playwright/test*: ^1.61.1 to ^1.62.1 +- * *eslint*: ^10.6.0 to ^10.9.0, *globals*: ^17.7.0 to ^17.9.0 +- * *stylelint*: ^16.0.0 added +- * *brace-expansion*: overridden to ^5.0.9, past three DoS advisories +- * *keycloak-js*: 24.0.5 to 26.2.4, loaded as an ES module +- * *bootstrap*: 5.3.3 to 5.3.8, *@fortawesome/fontawesome-free*: 6.5.1 to 7.3.1 +- * *roles/sys-lint* pins the GitHub-release tools: actionlint v1.7.12, +- hadolint v2.15.1, shfmt v3.13.1 + +- **Renamed** + +- * Role credential declarations move from *meta/credentials.yml* to *meta/secrets.yml*, +- addressed at *secrets.credentials* like every other meta file. +- * The NSS half of *sys-hostname* becomes its own role, *sys-svc-nss*. + +- **Contributors** + +- * [Kevin Veen-Birkenbach](https://veen.world): Tor deployment axis, SAML and +- cross-domain SSO, CI chunk chain, generation-level recovery, health-check and +- lint enforcement, multi-language test suites + * Sat Aug 08 2026 Kevin Veen-Birkenbach - 12.0.0-1 - * **Docker Swarm as a second deployment mode.** Roles can now be deployed across - multiple hosts instead of being limited to a single Compose stack. New diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000000..c4dd29ac38 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,19 @@ + + + + + tests/unit/php + + + + + roles + + + diff --git a/plugins/action/get_url_retry.py b/plugins/action/get_url_retry.py index 7c884d151c..81fd62c7aa 100755 --- a/plugins/action/get_url_retry.py +++ b/plugins/action/get_url_retry.py @@ -11,7 +11,6 @@ from ansible.plugins.action import ActionBase class ActionModule(ActionBase): - # Default policy when no task keywords are provided. DEFAULT_RETRIES = 12 DEFAULT_DELAY = 5 @@ -19,7 +18,6 @@ class ActionModule(ActionBase): if task_vars is None: task_vars = {} - # Respect explicit Ansible until/retry logic to avoid nested loops. if self._task_keyword_is_set("until"): return self._execute_get_url(tmp=tmp, task_vars=task_vars) @@ -56,8 +54,6 @@ class ActionModule(ActionBase): return isinstance(ds, dict) and key in ds def _task_keyword_int(self, key, fallback): - # `retries` can be present on the parsed task object even if it is not - # visible in get_ds(); prefer the task attribute for reliable override. if key == "retries": retries_value = getattr(self._task, "retries", None) if retries_value is None: diff --git a/plugins/action/stack_host_copy.py b/plugins/action/stack_host_copy.py index fa6d185a15..c1be062512 100755 --- a/plugins/action/stack_host_copy.py +++ b/plugins/action/stack_host_copy.py @@ -7,7 +7,6 @@ from ansible.module_utils.parsing.convert_bool import boolean as _to_bool from ansible.plugins.action.copy import ActionModule as CopyActionModule from ansible.template import trust_as_template -# trust_as_template: Ansible 2.19+ refuses to render Python-constructed strings without the TrustedAsTemplate tag. _IS_STACK_HOST_EXPR = trust_as_template("{{ IS_STACK_HOST | bool }}") diff --git a/plugins/action/uri_retry.py b/plugins/action/uri_retry.py index d876529347..a921e06c5c 100755 --- a/plugins/action/uri_retry.py +++ b/plugins/action/uri_retry.py @@ -11,7 +11,6 @@ from ansible.plugins.action.uri import ActionModule as UriActionModule class ActionModule(UriActionModule): - # Default policy when no task keywords are provided. DEFAULT_RETRIES = 30 DEFAULT_DELAY = 2 @@ -19,7 +18,6 @@ class ActionModule(UriActionModule): if task_vars is None: task_vars = {} - # Respect explicit Ansible until/retry logic to avoid nested loops. if self._task_keyword_is_set("until"): return super().run(tmp=tmp, task_vars=task_vars) @@ -48,8 +46,6 @@ class ActionModule(UriActionModule): return isinstance(ds, dict) and key in ds def _task_keyword_int(self, key, fallback): - # `retries` can be present on the parsed task object even if it is not - # visible in get_ds(); prefer the task attribute for reliable override. if key == "retries": retries_value = getattr(self._task, "retries", None) if retries_value is None: diff --git a/plugins/filter/active_docker.py b/plugins/filter/active_docker.py index 7b060dfa71..0bf2528916 100644 --- a/plugins/filter/active_docker.py +++ b/plugins/filter/active_docker.py @@ -17,7 +17,6 @@ from typing import Any def _is_mapping(x: Any) -> bool: - # be liberal: Mapping covers dict-like; fallback to dict check try: return isinstance(x, Mapping) except Exception: @@ -37,12 +36,11 @@ def active_docker_container_count( try: pattern = re.compile(prefix_regex) except re.error: - pattern = re.compile(r"^(web-|svc-).*") # fallback + pattern = re.compile(r"^(web-|svc-).*") count = 0 for app_key, app_val in applications.items(): - # host selection + name prefix if app_key not in group_set: continue if not pattern.match(str(app_key)): @@ -50,19 +48,16 @@ def active_docker_container_count( services = app_val.get("services") if _is_mapping(app_val) else None if not _is_mapping(services): - # sometimes roles define a single service name string; ignore continue for svc_cfg in services.values(): if not _is_mapping(svc_cfg): - # allow shorthand like: service: {} or image string -> counts as enabled count += 1 continue enabled = svc_cfg.get("enabled", True) if isinstance(enabled, bool): if enabled: count += 1 - # non-bool enabled -> treat "truthy" as enabled elif bool(enabled): count += 1 @@ -74,6 +69,5 @@ def active_docker_container_count( class FilterModule: def filters(self): return { - # usage: {{ lookup('applications') | active_docker_container_count(group_names) }} "active_docker_container_count": active_docker_container_count, } diff --git a/plugins/filter/application_allowed.py b/plugins/filter/application_allowed.py index a482d6718a..ce233ae937 100755 --- a/plugins/filter/application_allowed.py +++ b/plugins/filter/application_allowed.py @@ -21,7 +21,6 @@ def application_allowed( Returns: bool: True if this application is allowed to deploy, False otherwise. """ - # Ensure group_names is iterable if allowed_applications is None: allowed_applications = [] if not isinstance(group_names, (list, tuple)): @@ -29,11 +28,9 @@ def application_allowed( f"Expected group_names to be a list, str or tuple, got {type(group_names)}" ) - # Must be part of the host's groups if application_id not in group_names: return False - # If allowed_applications provided, only allow if ID is in that list if allowed_applications: if not isinstance(allowed_applications, (list, tuple, str)): raise AnsibleFilterError( @@ -41,7 +38,6 @@ def application_allowed( ) return application_id in allowed_applications - # No filter provided → allow all in group_names return True diff --git a/plugins/filter/compose_volumes.py b/plugins/filter/compose_volumes.py deleted file mode 100644 index 300b5ce31b..0000000000 --- a/plugins/filter/compose_volumes.py +++ /dev/null @@ -1,305 +0,0 @@ -from __future__ import annotations - -from collections.abc import Mapping, Sequence -from typing import Any - -from ansible.errors import AnsibleFilterError - -from utils.cache.yaml import dump_yaml_str - -try: - from plugins.filter.docker.service_enabled import ( - FilterModule as _DockerServiceEnabledFilter, - ) - from plugins.filter.get.entity_name import get_entity_name - from utils.cache.applications import get_canonical_volumes - from utils.roles.applications.config import get - from utils.roles.applications.mounts import ( - content_hash, - mount_when_passes, - normalize_volumes_meta, - ) - from utils.roles.applications.services.database import ( - get_database_service_config, - resolve_database_service_key, - ) - from utils.roles.applications.services.sso import get_sso_config - from utils.storage.nfs import swarm_nfs_backed -except ModuleNotFoundError: - from docker.service_enabled import FilterModule as _DockerServiceEnabledFilter - from get.entity_name import get_entity_name - - from utils.cache.applications import get_canonical_volumes - from utils.roles.applications.config import get - from utils.roles.applications.mounts import ( - content_hash, - mount_when_passes, - normalize_volumes_meta, - ) - from utils.roles.applications.services.database import ( - get_database_service_config, - resolve_database_service_key, - ) - from utils.roles.applications.services.sso import get_sso_config - from utils.storage.nfs import swarm_nfs_backed - - -def _to_plain(obj: Any) -> Any: - """Convert Ansible/Jinja proxy types into plain Python so PyYAML can serialize.""" - - if obj is None: - return None - - if isinstance(obj, str): - return str(obj) - - if isinstance(obj, (int, float, bool)): - return obj - - if isinstance(obj, Mapping): - return {str(_to_plain(k)): _to_plain(v) for k, v in obj.items()} - - if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)): - return [_to_plain(x) for x in obj] - - return str(obj) - - -def _resolve_database_volume_name( - applications: dict[str, Any], application_id: str, dbtype: str -) -> str: - consumer_entity = get_entity_name(application_id) - db_id = f"svc-db-{dbtype}" - central_name = get( - applications=applications, - application_id=db_id, - config_path=f"services.{dbtype}.name", - strict=False, - default="", - skip_missing_app=True, - ) - central_name = (str(central_name) if central_name is not None else "").strip() - service_cfg = get_database_service_config(applications, application_id) - central_enabled = bool(service_cfg.get("shared", False)) - host = central_name if central_enabled else "database" - volume_prefix = "" if central_enabled else f"{consumer_entity}_" - return f"{volume_prefix}{host}" - - -def _swarm_nfs_driver_opts(dir_var_lib: str, volume_name: str) -> dict[str, Any]: - return { - "driver": "local", - "driver_opts": { - "type": "none", - "o": "bind", - "device": f"{dir_var_lib.rstrip('/')}/{volume_name}", - }, - } - - -def _read_file_for_hash(source: str) -> str: - """Read a file's content for hash-based naming. Returns the path as a - stable fallback when the file isn't materialised yet (lint runs).""" - try: - from utils.cache.files import read_text - - return read_text(source) - except (OSError, ValueError): - return source - - -def _config_secret_name(role_entity: str, user_name: str, source: str) -> str: - """Build a swarm-rotation-safe name: ``{role}_{name}_{sha8(content)}``.""" - digest = content_hash(_read_file_for_hash(source)) - return f"{role_entity}_{user_name}_{digest}" - - -def _maybe_render(value: Any, render_jinja: Any) -> str: - text = str(value) - if render_jinja is None or ("{{" not in text and "{%" not in text): - return text - try: - return str(render_jinja(text)) - except Exception: - return text - - -def compose_volumes( - applications: dict[str, Any], - application_id: str, - *, - extra_volumes: dict[str, dict[str, Any]] | None = None, - extra_configs: dict[str, dict[str, Any]] | None = None, - extra_secrets: dict[str, dict[str, Any]] | None = None, - deployment_mode: str = "compose", - storage: dict[str, Any] | None = None, - dir_var_lib: str, - render_jinja: Any = None, -) -> str: - """Render the top-level ``volumes:`` / ``configs:`` / ``secrets:`` block. - - Reads the canonical dict-of-dicts shape from - ``roles//meta/volumes.yml`` (YAML key = semantic short name; - optional ``name:`` field = docker volume name). Entries with - ``type: config`` / ``type: secret`` emit their respective top-level - sections; everything else flows through the volumes section. - - A ``type: volume`` entry may set ``nfs: false`` to opt out of the - swarm NFS rewrite: the volume then stays a plain node-local named - volume even when ``storage.backend`` is ``nfs`` (e.g. gitaly - repository storage, which upstream forbids on NFS). Any other - ``nfs`` value (absent, ``true``, or the uid/gid/mode dict consumed - by the NFS subdir pre-creation) keeps the rewrite. - """ - - if applications is None: - raise AnsibleFilterError("compose_volumes: 'applications' must not be None") - if not isinstance(applications, dict): - raise AnsibleFilterError("compose_volumes: 'applications' must be a dict") - if not application_id or not isinstance(application_id, str): - raise AnsibleFilterError( - "compose_volumes: 'application_id' must be a non-empty string" - ) - if application_id not in applications: - raise AnsibleFilterError( - f"compose_volumes: unknown application_id '{application_id}'" - ) - - role_entity = get_entity_name(application_id) - volumes: dict[str, Any] = {} - configs: dict[str, Any] = {} - secrets: dict[str, Any] = {} - - try: - database_service_key = resolve_database_service_key( - applications, application_id - ) - except ValueError as exc: - raise AnsibleFilterError( - "compose_volumes: " - f"{exc}. Simultaneous postgres + mariadb on the same role " - "is not supported (the embedded service templates collide " - "on the `database` service key, host name, and volume " - "key); pick one dbtype per role." - ) from exc - database_service = get_database_service_config(applications, application_id) - database_needed = bool(database_service_key) and not bool( - database_service.get("shared", False) - ) - - if database_needed: - volumes["database"] = { - "name": _resolve_database_volume_name( - applications, application_id, database_service_key - ) - } - - for engine in ("seaweedfs", "minio"): - engine_enabled = bool( - get( - applications=applications, - application_id=application_id, - config_path=f"services.{engine}.enabled", - strict=False, - default=False, - ) - ) - engine_shared = bool( - get( - applications=applications, - application_id=application_id, - config_path=f"services.{engine}.shared", - strict=False, - default=False, - ) - ) - if engine_enabled and not engine_shared: - volumes[engine] = {"name": f"{get_entity_name(application_id)}_{engine}"} - - sso = get_sso_config(applications, application_id) - - if ( - _DockerServiceEnabledFilter.is_docker_service_enabled( - applications, application_id, "redis" - ) - or sso["is_proxy_gated"] - ): - volumes["redis"] = {"name": f"{role_entity}_redis"} - - if extra_volumes: - volumes.update(extra_volumes) - if extra_configs: - configs.update(extra_configs) - if extra_secrets: - secrets.update(extra_secrets) - - role_data = applications.get(application_id) or {} - raw_meta_volumes = ( - get_canonical_volumes(application_id) or role_data.get("volumes") or {} - ) - canonical_entries = normalize_volumes_meta(raw_meta_volumes) - - for semantic_name, entry in canonical_entries.items(): - vtype = entry.get("type", "volume") - - if vtype == "volume": - if semantic_name in volumes: - continue - spec: dict[str, Any] = {} - docker_name = entry.get("name") - if docker_name: - spec["name"] = docker_name - if "nfs" in entry: - spec["nfs"] = entry["nfs"] - volumes[semantic_name] = spec - continue - - if vtype in ("config", "secret") and not any( - mount_when_passes(mount, render_jinja) - for mount in entry.get("mounts") or [] - if isinstance(mount, dict) - ): - continue - - if vtype == "config": - source = _maybe_render(entry.get("source", ""), render_jinja) - configs[semantic_name] = { - "name": _maybe_render(entry.get("name", ""), render_jinja) - or _config_secret_name(role_entity, semantic_name, source), - "file": source, - } - continue - - if vtype == "secret": - source = _maybe_render(entry.get("source", ""), render_jinja) - secrets[semantic_name] = { - "name": _maybe_render(entry.get("name", ""), render_jinja) - or _config_secret_name(role_entity, semantic_name, source), - "file": source, - } - continue - - storage_backend = (storage or {}).get("backend", "local") - - for vol_name, vol_spec in list(volumes.items()): - if not isinstance(vol_spec, dict): - continue - nfs_meta = vol_spec.pop("nfs", None) - if swarm_nfs_backed( - {"nfs": nfs_meta}, - application_id=application_id, - deployment_mode=deployment_mode, - storage_backend=storage_backend, - ): - named = vol_spec.get("name", vol_name) - vol_spec.update(_swarm_nfs_driver_opts(dir_var_lib, str(named))) - if isinstance(nfs_meta, dict): - vol_spec["x-infinito-nfs"] = dict(nfs_meta) - - payload: dict[str, Any] = {"volumes": _to_plain(volumes)} - if configs: - payload["configs"] = _to_plain(configs) - if secrets: - payload["secrets"] = _to_plain(secrets) - - return dump_yaml_str(payload).rstrip() diff --git a/plugins/filter/container_volumes.py b/plugins/filter/container_volumes.py deleted file mode 100644 index f3fe83bce3..0000000000 --- a/plugins/filter/container_volumes.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Render the per-service ``volumes:`` / ``configs:`` / ``secrets:`` block -for one compose service, fed from the role's ``meta/volumes.yml``. - -The output starts at column 0; the caller is responsible for indenting -it with ``| indent(4)`` (or whatever depth) so the block sits under the -right service in ``compose.yml.j2``. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -from ansible.errors import AnsibleFilterError, AnsibleUndefinedVariable - -from utils.cache.yaml import dump_yaml_str - -if TYPE_CHECKING: - from collections.abc import Callable - -from utils.cache.applications import get_canonical_volumes -from utils.roles.applications.mounts import ( - mount_default_read_only, - mount_when_passes, - normalize_volumes_meta, -) - - -def _coerce_mode_int(value: Any) -> int: - if isinstance(value, bool): - raise AnsibleFilterError( - f"container_volumes: mode must be an octal int or string, got bool: {value!r}" - ) - if isinstance(value, int): - return value - text = str(value).strip() - if not text: - raise AnsibleFilterError("container_volumes: mode is empty") - try: - return int(text, 8) - except ValueError as exc: - raise AnsibleFilterError( - f"container_volumes: mode {value!r} is not a valid octal: {exc}" - ) from exc - - -def _short_form_volume(source_name: str, target: str, read_only: bool) -> str: - suffix = ":ro" if read_only else "" - return f"{source_name}:{target}{suffix}" - - -def container_volumes( - applications: dict[str, Any], - application_id: str, - service: str, - *, - extra_volumes: list[Any] | None = None, - extra_configs: list[dict[str, Any]] | None = None, - extra_secrets: list[dict[str, Any]] | None = None, - render_jinja: Callable[[str], str] | None = None, -) -> str: - """Return the per-service mount block (``volumes:`` + ``configs:`` + - ``secrets:``) as a YAML string starting at column 0. - """ - if not isinstance(applications, dict): - raise AnsibleFilterError("container_volumes: 'applications' must be a dict") - if not isinstance(application_id, str) or not application_id.strip(): - raise AnsibleFilterError( - "container_volumes: 'application_id' must be a non-empty string" - ) - if not isinstance(service, str) or not service.strip(): - raise AnsibleFilterError( - "container_volumes: 'service' must be a non-empty string" - ) - - role_data = applications.get(application_id) or {} - raw_meta_volumes = ( - get_canonical_volumes(application_id) or role_data.get("volumes") or {} - ) - canonical_entries = normalize_volumes_meta(raw_meta_volumes) - - volumes_block: list[Any] = [] - configs_block: list[dict[str, Any]] = [] - secrets_block: list[dict[str, Any]] = [] - - for semantic_name, entry in canonical_entries.items(): - vtype = entry.get("type", "volume") - volume_level_ro = bool(entry.get("read_only", mount_default_read_only(entry))) - - for mount in entry.get("mounts") or []: - if not isinstance(mount, dict): - continue - if mount.get("service") != service: - continue - if not mount_when_passes(mount, render_jinja): - continue - - target = mount.get("target") - if not target: - continue - target_text = str(target) - if render_jinja is not None and ( - "{{" in target_text or "{%" in target_text - ): - try: - target = str(render_jinja(target_text)) - except AnsibleUndefinedVariable as exc: - raise AnsibleFilterError( - f"container_volumes: failed to render mount target " - f"{target_text!r} for application {application_id!r}, " - f"service {service!r}: {exc}" - ) from exc - - if vtype == "volume": - read_only = bool(mount.get("read_only", volume_level_ro)) - volumes_block.append( - _short_form_volume(semantic_name, target, read_only) - ) - - elif vtype == "bind": - source = str(entry.get("source", "")) - if render_jinja is not None and ("{{" in source or "{%" in source): - try: - source = str(render_jinja(source)) - except AnsibleUndefinedVariable as exc: - raise AnsibleFilterError( - f"container_volumes: failed to render bind source " - f"{source!r} for application {application_id!r}, " - f"service {service!r}: {exc}" - ) from exc - read_only = bool(mount.get("read_only", volume_level_ro)) - volumes_block.append(_short_form_volume(source, target, read_only)) - - elif vtype == "tmpfs": - tmpfs_entry: dict[str, Any] = { - "type": "tmpfs", - "target": target, - } - if mount.get("size") is not None: - tmpfs_entry["tmpfs"] = {"size": mount["size"]} - volumes_block.append(tmpfs_entry) - - elif vtype == "config": - cfg_ref: dict[str, Any] = {"source": semantic_name, "target": target} - mode_value = entry.get("mode") - if mode_value: - cfg_ref["mode"] = _coerce_mode_int(mode_value) - configs_block.append(cfg_ref) - - elif vtype == "secret": - sec_ref: dict[str, Any] = {"source": semantic_name, "target": target} - mode_value = entry.get("mode") - if mode_value: - sec_ref["mode"] = _coerce_mode_int(mode_value) - secrets_block.append(sec_ref) - - if extra_volumes: - volumes_block.extend(extra_volumes) - if extra_configs: - configs_block.extend(extra_configs) - if extra_secrets: - secrets_block.extend(extra_secrets) - - payload: dict[str, Any] = {} - if volumes_block: - payload["volumes"] = volumes_block - if configs_block: - payload["configs"] = configs_block - if secrets_block: - payload["secrets"] = secrets_block - - if not payload: - return "" - - return dump_yaml_str(payload).rstrip() diff --git a/plugins/filter/cookie_scope.py b/plugins/filter/cookie_scope.py index e73daad518..a416f86f27 100644 --- a/plugins/filter/cookie_scope.py +++ b/plugins/filter/cookie_scope.py @@ -1,4 +1,4 @@ -def _domain_strings(domains): +def domain_strings(domains): """Flatten the value returned by lookup('domains', app) into a flat list of domain strings. The lookup yields a dict ({key: domain}), a list, or a bare string depending on the role's domains shape, so normalise all three. @@ -20,7 +20,7 @@ def common_dns_suffix(domains): under one base) collapses to the shared parent that a session cookie can span across all of them. """ - cleaned = _domain_strings(domains) + cleaned = domain_strings(domains) if not cleaned: return "" if len(cleaned) == 1: @@ -38,4 +38,7 @@ def common_dns_suffix(domains): class FilterModule: def filters(self): - return {"common_dns_suffix": common_dns_suffix} + return { + "common_dns_suffix": common_dns_suffix, + "domain_strings": domain_strings, + } diff --git a/plugins/filter/csp_filters.py b/plugins/filter/csp_filters.py index 81261a6c9b..3dc8b72751 100644 --- a/plugins/filter/csp_filters.py +++ b/plugins/filter/csp_filters.py @@ -3,8 +3,23 @@ import hashlib from ansible.errors import AnsibleFilterError -from utils.get_url import get_url +from utils.domains.primary_domain import get_domain from utils.roles.applications.config import get +from utils.tls_common import align_domain_to_consumer, is_onion_domain + + +def _aligned_url(domains, application_id, target_id, protocol): + """Provider URL for CSP tokens, family-aligned to the consuming app. + + The scheme follows the ALIGNED host, not the consumer: onion targets are + plaintext-only (http), so a clearnet consumer falling back to an onion-only + provider gets a token that matches what the asset injection actually loads. + """ + domain = align_domain_to_consumer( + domains, target_id, get_domain(domains, target_id), consumer=application_id + ) + scheme = "http" if is_onion_domain(domain) else protocol + return f"{scheme}://{domain}" def _dedup_preserve(seq): @@ -29,10 +44,8 @@ def _sort_tokens(tokens): if not uniq: return uniq - # Lexicographically sort all tokens uniq = sorted(uniq) - # Ensure "'self'" is always first if present if "'self'" in uniq: uniq.remove("'self'") uniq.insert(0, "'self'") @@ -191,6 +204,7 @@ class FilterModule: web_protocol, extra_whitelist=None, extra_hashes=None, + domain_primary=None, ): """ Builds the Content-Security-Policy header value dynamically based on application settings. @@ -240,7 +254,6 @@ class FilterModule: explicit_flags_by_dir = {} for directive in directives: - # Collect explicit flags (to later respect explicit "False" on base during merge) explicit_flags = get( applications, application_id, @@ -252,40 +265,60 @@ class FilterModule: tokens = ["'self'"] - # Flags (with sane defaults) flags = self.get_csp_flags(applications, application_id, directive) tokens += flags - # Internal CDN defaults for selected directives if directive in ( "script-src-elem", "connect-src", "style-src-elem", "style-src", ): - tokens.append(get_url(domains, "web-svc-cdn", web_protocol)) + tokens.append( + _aligned_url( + domains, application_id, "web-svc-cdn", web_protocol + ) + ) + + if directive in ( + "script-src-elem", + "style-src-elem", + "style-src", + "connect-src", + "font-src", + "media-src", + ) and self.is_feature_enabled(applications, "tor", application_id): + tokens.append( + _aligned_url( + domains, application_id, "web-svc-mirror", web_protocol + ) + ) - # Matomo (if enabled via services.matomo.enabled) if directive in ( "script-src-elem", "connect-src", ) and self.is_feature_enabled(applications, "matomo", application_id): - tokens.append(get_url(domains, "web-app-matomo", web_protocol)) + tokens.append( + _aligned_url( + domains, application_id, "web-app-matomo", web_protocol + ) + ) - # Simpleicons (if enabled via services.simpleicons.enabled) – typically used via connect-src (fetch) if directive == "connect-src" and self.is_feature_enabled( applications, "simpleicons", application_id ): - tokens.append(get_url(domains, "web-svc-simpleicons", web_protocol)) + tokens.append( + _aligned_url( + domains, application_id, "web-svc-simpleicons", web_protocol + ) + ) - # reCAPTCHA (if enabled via services.recaptcha.enabled) – scripts + frames if self.is_feature_enabled( applications, "recaptcha", application_id ) and directive in ("script-src-elem", "frame-src"): tokens.append("https://www.gstatic.com") # nocheck: url tokens.append("https://www.google.com") - # hCaptcha (if enabled via services.hcaptcha.enabled) – scripts + frames if self.is_feature_enabled(applications, "hcaptcha", application_id): if directive == "script-src-elem": tokens.append("https://www.hcaptcha.com") @@ -293,34 +326,38 @@ class FilterModule: if directive == "frame-src": tokens.append("https://newassets.hcaptcha.com/") - # Frame ancestors (dashboard + logout) if directive == "frame-ancestors": if self.is_feature_enabled( applications, "dashboard", application_id ): - # Allow being embedded by the dashboard app domain's site domain = domains.get("web-app-dashboard")[0] tokens.append(f"{domain}") if self.is_feature_enabled(applications, "logout", application_id): - tokens.append(get_url(domains, "web-svc-logout", web_protocol)) tokens.append( - get_url(domains, "web-app-keycloak", web_protocol) + _aligned_url( + domains, application_id, "web-svc-logout", web_protocol + ) + ) + tokens.append( + _aligned_url( + domains, + application_id, + "web-app-keycloak", + web_protocol, + ) ) - # Logout support requires inline handlers (script-src-attr + script-src-elem) if directive in ( "script-src-attr", "script-src-elem", ) and self.is_feature_enabled(applications, "logout", application_id): tokens.append("'unsafe-inline'") - # Custom whitelist tokens += self.get_csp_whitelist( applications, application_id, directive ) tokens += self.get_extra_values(extra_whitelist, directive) - # Inline hashes (only if this directive does NOT include 'unsafe-inline') if "'unsafe-inline'" not in tokens: for snippet in self.get_csp_inline_content( applications, application_id, directive @@ -356,19 +393,45 @@ class FilterModule: attr = tokens_by_dir.get(attr_key, []) union = _dedup_preserve(base + elem + attr) - # Respect explicit disables on the base explicit_base = explicit_flags_by_dir.get(base_key, {}) for flag_name in ("unsafe-inline", "unsafe-eval"): union = _strip_if_disabled(union, explicit_base, flag_name) - tokens_by_dir[base_key] = union # write back only to base + tokens_by_dir[base_key] = union merge_family("style-src", "style-src-elem", "style-src-attr") merge_family("script-src", "script-src-elem", "script-src-attr") - # ---------------------------------------------------------- - # Assemble header - # ---------------------------------------------------------- + _svc_tor = (applications or {}).get("svc-net-tor") + node_onion = "" + if isinstance(_svc_tor, dict): + node_onion = ((_svc_tor.get("services") or {}).get("tor") or {}).get( + "node" + ) or "" + if node_onion and domain_primary and domain_primary != node_onion: + app_domains = [str(d) for d in (domains.get(application_id) or [])] + app_has_onion = any(node_onion in d for d in app_domains) + app_has_clearnet = any(domain_primary in d for d in app_domains) + if app_has_onion: + for directive in list(tokens_by_dir.keys()): + toks = tokens_by_dir[directive] + if app_has_clearnet: + siblings = [ + t.replace(domain_primary, node_onion) + for t in toks + if domain_primary in t + ] + tokens_by_dir[directive] = _dedup_preserve(toks + siblings) + else: + tokens_by_dir[directive] = _dedup_preserve( + [ + t.replace(domain_primary, node_onion) + if domain_primary in t + else t + for t in toks + ] + ) + for directive, toks in list(tokens_by_dir.items()): tokens_by_dir[directive] = _sort_tokens(toks) @@ -379,7 +442,6 @@ class FilterModule: if directive in tokens_by_dir ) - # Keep permissive img-src for data/blob + any host (as before) parts.append("img-src * data: blob:;") return " ".join(parts) diff --git a/plugins/filter/domain_tools.py b/plugins/filter/domain_tools.py index b6a4587e90..17443e8811 100644 --- a/plugins/filter/domain_tools.py +++ b/plugins/filter/domain_tools.py @@ -9,7 +9,6 @@ def to_zone(hostname: str) -> str: parts = hostname.strip(".").split(".") if len(parts) < 2: raise AnsibleFilterError(f"to_zone: '{hostname}' has no TLD part") - # naive default: last two labels -> SLD.TLD return ".".join(parts[-2:]) diff --git a/plugins/filter/mirror_filters.py b/plugins/filter/mirror_filters.py new file mode 100644 index 0000000000..8ba34319ef --- /dev/null +++ b/plugins/filter/mirror_filters.py @@ -0,0 +1,73 @@ +""" +Jinja filter: `external_asset_origins` extracts the third-party asset hosts an +application (or every application) declares in `csp.whitelist.*`. + +The result feeds the web-svc-mirror privacy proxy: the mirror's nginx vhost +whitelists exactly these hosts as proxy upstreams, and the body-filter rewrite +maps `https:///...` to `//...` in served HTML. + +Only literal `https://` tokens count as external assets: + - tokens containing unresolved Jinja (`{{ ... }}`) point at deployment-own + domains and are skipped, + - wildcard tokens (`*`) cannot be mirrored deterministically, + - hosts on the deployment's primary domain (or `.onion`) are already local. +""" + +from urllib.parse import urlsplit + + +def _iter_whitelist_tokens(app_config): + whitelist = ((app_config or {}).get("csp") or {}).get("whitelist", {}) or {} + for raw_tokens in whitelist.values(): + tokens = [raw_tokens] if isinstance(raw_tokens, str) else raw_tokens + if not isinstance(tokens, (list, tuple)): + continue + for token in tokens: + if isinstance(token, str): + yield token.strip() + + +def _external_host(token, primary_domain): + if not token.startswith("https://"): + return None + if "{{" in token or "*" in token: + return None + host = urlsplit(token).hostname or "" + if not host or "." not in host: + return None + if host.endswith(".onion"): + return None + if primary_domain and ( + host == primary_domain or host.endswith("." + primary_domain) + ): + return None + return host.lower() + + +def external_asset_origins(applications, application_id=None, primary_domain=""): + """ + Return the sorted list of external asset hosts. + + application_id: restrict to one application; None aggregates across all. + primary_domain: the deployment's primary domain (its hosts are not external). + """ + if not isinstance(applications, dict): + return [] + if application_id is not None: + selected = {application_id: applications.get(application_id) or {}} + else: + selected = applications + hosts = set() + for app_config in selected.values(): + for token in _iter_whitelist_tokens(app_config): + host = _external_host(token, primary_domain) + if host: + hosts.add(host) + return sorted(hosts) + + +class FilterModule: + def filters(self): + return { + "external_asset_origins": external_asset_origins, + } diff --git a/plugins/filter/on_off.py b/plugins/filter/on_off.py index f0831cc2d3..484c6d7760 100644 --- a/plugins/filter/on_off.py +++ b/plugins/filter/on_off.py @@ -10,10 +10,6 @@ from __future__ import annotations def on_off(value): - # Mirror Ansible's `bool` filter coercion exactly so this is a - # drop-in for the existing `| bool | ternary('on', 'off')` - # idiom: every Ansible-truthy value renders "on", everything - # else "off". if isinstance(value, bool): return "on" if value else "off" if isinstance(value, (int, float)): @@ -25,8 +21,6 @@ def on_off(value): return "on" if s in ("false", "no", "off", "0", "n", "f", ""): return "off" - # Unknown string: be strict. Templates should not pass arbitrary - # strings through this filter. raise ValueError( f"on_off: cannot coerce {value!r} to on/off; expected a bool-like value." ) diff --git a/plugins/filter/sed.py b/plugins/filter/sed.py index 23593f99d7..be8df0046e 100644 --- a/plugins/filter/sed.py +++ b/plugins/filter/sed.py @@ -39,9 +39,8 @@ class FilterModule: s = str(value) - # Escape order matters - s = s.replace("\\", "\\\\") # backslash - s = s.replace("&", "\\&") # sed match reference + s = s.replace("\\", "\\\\") + s = s.replace("&", "\\&") if delimiter: s = s.replace(delimiter, "\\" + delimiter) diff --git a/plugins/filter/split_postgres_connections.py b/plugins/filter/split_postgres_connections.py index c91370def3..40d2164d1e 100644 --- a/plugins/filter/split_postgres_connections.py +++ b/plugins/filter/split_postgres_connections.py @@ -24,10 +24,8 @@ def _is_postgres_role(vars_file): data = load_yaml_any(vars_file, default_if_missing={}) or {} if not isinstance(data, dict): return False - # only count roles with explicit database_type: postgres in VARS return str(data.get("database_type", "")).strip().lower() == "postgres" except Exception: - # ignore unreadable/broken YAML files quietly return False diff --git a/plugins/filter/text_filters.py b/plugins/filter/text_filters.py index 8351981b2f..5ddf1b889c 100644 --- a/plugins/filter/text_filters.py +++ b/plugins/filter/text_filters.py @@ -13,10 +13,8 @@ def to_one_liner(s): if not isinstance(s, str): raise AnsibleFilterError("to_one_liner() expects a string") - # 1) Remove block comments /* ... */ no_block_comments = re.sub(r"/\*.*?\*/", "", s, flags=re.DOTALL) - # 2) Extract string literals to protect them from comment removal string_pattern = re.compile(r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"") literals = [] @@ -27,14 +25,11 @@ def to_one_liner(s): temp = string_pattern.sub(_extract, no_block_comments) - # 3) Remove line comments // ... temp = re.sub(r"//.*$", "", temp, flags=re.MULTILINE) - # 4) Restore string literals for idx, lit in enumerate(literals): temp = temp.replace(f"__STR{idx}__", lit) - # 5) Collapse all whitespace return re.sub(r"\s+", " ", temp).strip() diff --git a/plugins/filter/timeout_start_sec_for_domains.py b/plugins/filter/timeout_start_sec_for_domains.py index 4aa0fd8983..d54cc81aea 100644 --- a/plugins/filter/timeout_start_sec_for_domains.py +++ b/plugins/filter/timeout_start_sec_for_domains.py @@ -37,7 +37,6 @@ class FilterModule: flat.extend(v.values()) return flat - # Accept dict | list | str if isinstance(domains_dict, dict): flat = _flatten_from_dict(domains_dict) elif isinstance(domains_dict, list): @@ -46,7 +45,6 @@ class FilterModule: flat = [domains_dict] else: # nocheck (TRY301 below): re-raised verbatim by the - # AnsibleFilterError handler — intentional pass-through. raise AnsibleFilterError( # noqa: TRY301 "Expected 'domains_dict' to be dict | list | str." ) diff --git a/tests/unit/cli/administration/__init__.py b/plugins/filter/url/__init__.py similarity index 100% rename from tests/unit/cli/administration/__init__.py rename to plugins/filter/url/__init__.py diff --git a/plugins/filter/url_join.py b/plugins/filter/url/join.py similarity index 80% rename from plugins/filter/url_join.py rename to plugins/filter/url/join.py index 6f6214f8b4..ad1ac8cedd 100644 --- a/plugins/filter/url_join.py +++ b/plugins/filter/url/join.py @@ -44,7 +44,6 @@ def url_join(parts): Raises: AnsibleFilterError: with specific, descriptive messages. """ - # --- basic input validation --- if parts is None: raise AnsibleFilterError("url_join: parts must be a non-empty list; got None") if not isinstance(parts, (list, tuple)): @@ -54,7 +53,6 @@ def url_join(parts): if len(parts) == 0: raise AnsibleFilterError("url_join: parts must be a non-empty list") - # --- first element must carry a scheme --- first_raw = parts[0] if first_raw is None: raise AnsibleFilterError( @@ -69,43 +67,35 @@ def url_join(parts): f"got '{first_str}'" ) - scheme = m.group(1) # e.g., 'https://', 'ftp://', 'myapp+v1://' - after_scheme = m.group(2).lstrip( - "/" - ) # strip only leading slashes right after scheme + scheme = m.group(1) + after_scheme = m.group(2).lstrip("/") - # --- iterate parts: collect path parts until first query part; then only query parts allowed --- path_parts = [] query_pairs = [] in_query = False for i, p in enumerate(parts): if p is None: - # skip None silently (consistent with path_join-ish behavior) continue s = _to_str_or_error(p, i) - # disallow additional scheme in later parts if i > 0 and "://" in s: raise AnsibleFilterError( f"url_join: only the first element may contain a scheme; part at index {i} " f"looks like a URL with scheme ('{s}')." ) - # first element: replace with remainder after scheme and continue if i == 0: s = after_scheme - # check if this is a query element (starts with ? or &) if s.startswith(("?", "&")): in_query = True - raw_pair = s[1:] # strip the leading ? or & + raw_pair = s[1:] if raw_pair == "": raise AnsibleFilterError( f"url_join: query element at index {i} is empty; expected '?key=value' or '&key=value'" ) - # Disallow multiple pairs in a single element; enforce exactly one key=value if "&" in raw_pair: raise AnsibleFilterError( f"url_join: query element at index {i} must contain exactly one 'key=value' pair " @@ -117,29 +107,21 @@ def url_join(parts): ) query_pairs.append(raw_pair) else: - # non-query element if in_query: - # once query started, no more path parts allowed raise AnsibleFilterError( f"url_join: path element found at index {i} after query parameters started; " f"query parts must come last" ) - # normal path part: strip slashes to avoid duplicate '/' path_parts.append(s.strip("/")) - # normalize path: remove empty chunks path_parts = [p for p in path_parts if p != ""] - # --- build result --- - # path portion if path_parts: joined_path = "/".join(path_parts) base = scheme + joined_path else: - # no path beyond scheme base = scheme - # query portion if query_pairs: base = base + "?" + "&".join(query_pairs) diff --git a/plugins/filter/url/to_onion.py b/plugins/filter/url/to_onion.py new file mode 100644 index 0000000000..6de7445b7d --- /dev/null +++ b/plugins/filter/url/to_onion.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from urllib.parse import urlsplit, urlunsplit + + +def to_onion_url(url: str, tor_node: str, primary_domain: str) -> str: + """Rewrite a browser-facing clearnet URL to its ``.onion`` mirror. + + When ``tor_node`` is set (svc-net-tor deployed) and the URL's host is the + ``primary_domain`` or a subdomain of it, swap that suffix for ``tor_node`` + and force the ``http`` scheme (onion services are plaintext-only). Anything + else — empty inputs, a host not under ``primary_domain``, an unparseable + value — is returned unchanged, so the filter is a safe no-op on clearnet. + """ + if not url or not tor_node or not primary_domain: + return url + + parts = urlsplit(url if "://" in url else "//" + url) + host = parts.hostname or "" + suffix = "." + primary_domain + + if host == primary_domain: + onion_host = tor_node + elif host.endswith(suffix): + onion_host = host[: -len(primary_domain)] + tor_node + else: + return url + + return urlunsplit(("http", onion_host, parts.path, parts.query, parts.fragment)) + + +class FilterModule: + def filters(self): + return {"to_onion_url": to_onion_url} diff --git a/plugins/lookup/application_gid.py b/plugins/lookup/application_gid.py index 80164969e7..d359e2e593 100644 --- a/plugins/lookup/application_gid.py +++ b/plugins/lookup/application_gid.py @@ -7,20 +7,31 @@ _APPLICATION_MARKER_FILES = ( "server.yml", "rbac.yml", "volumes.yml", - "schema.yml", + "secrets.yml", "users.yml", ) @functools.cache -def _discover_sorted_application_ids(roles_dir_key: str) -> tuple[str, ...]: - discovered: set[str] = set() - for entry in os.listdir(roles_dir_key): - meta_dir = Path(roles_dir_key, entry, "meta") - if not meta_dir.is_dir(): - continue - if any((meta_dir / marker).is_file() for marker in _APPLICATION_MARKER_FILES): - discovered.add(entry) +def _discover_sorted_application_ids(roles_dir_abs: str) -> tuple[str, ...]: + """Sorted application role ids under *roles_dir_abs*, memoised per + process (utils.cache philosophy: CLI/test invocations rescan at most + once; a role added mid-process needs a fresh interpreter or + ``_discover_sorted_application_ids.cache_clear()``). + + An "application role" is identified by the presence of at least one + project-owned ``meta/.yml`` marker file. + """ + discovered: list[str] = [] + with os.scandir(roles_dir_abs) as entries: + for entry in entries: + if not entry.is_dir(): + continue + meta_dir = Path(entry.path) / "meta" + for marker in _APPLICATION_MARKER_FILES: + if (meta_dir / marker).is_file(): + discovered.append(entry.name) + break return tuple(sorted(discovered)) diff --git a/plugins/lookup/asset.py b/plugins/lookup/asset.py index 029106f2e8..fbf74ec125 100644 --- a/plugins/lookup/asset.py +++ b/plugins/lookup/asset.py @@ -10,6 +10,7 @@ from ansible.plugins.lookup import LookupBase from plugins.filter.role_path_by_app_id import abs_role_path_by_application_id from utils.cache.files import read_text +from utils.tls_common import is_onion_domain _JSDELIVR = "https://cdn.jsdelivr.net" @@ -27,7 +28,8 @@ def resolve_host(variables, loader, templar) -> str: domain = lookup_loader.get("domain", loader=loader, templar=templar).run( ["web-svc-cdn"], variables=variables )[0] - return f"https://{domain}" + scheme = "http" if is_onion_domain(domain) else "https" + return f"{scheme}://{domain}" class LookupModule(LookupBase): diff --git a/plugins/lookup/ca_injected.py b/plugins/lookup/ca_injected.py new file mode 100644 index 0000000000..fb7e98f6e6 --- /dev/null +++ b/plugins/lookup/ca_injected.py @@ -0,0 +1,59 @@ +"""Lookup `ca_injected`: whether the self-signed root CA is mounted into an +application's containers. + + {{ lookup('ca_injected', application_id) }} + +The CA override that bind-mounts ``CA_TRUST.inject_cert_container`` is emitted +under three conditions, and anything that reads the mounted file must ask the +same three or it will point at a path that was never mounted. The conditions +lived as four hand-copied expressions - both `sys-svc-compose` handlers, +`sys-svc-compose-ca/vars/main.yml` and the msmtp template - which is one copy +per place that can drift. + +Returns a plain bool, so callers read as a predicate: + + when: lookup('ca_injected', application_id) + {{ CA_TRUST.inject_cert_container if lookup('ca_injected', application_id) else ... }} +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.module_utils.parsing.convert_bool import boolean as _to_bool +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.filter.has.domain import has_domain + +SELF_SIGNED_MODE = "self_signed" + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[bool]: + if not terms or len(terms) != 1: + raise AnsibleError( + "ca_injected lookup requires exactly one term: the application id" + ) + templar = getattr(self, "_templar", None) + raw = templar.template(terms[0]) if templar is not None else terms[0] + application_id = str(raw).strip() + if not application_id: + raise AnsibleError("ca_injected lookup: application id must be non-empty") + + def _run(name: str, args: list[Any]) -> Any: + return lookup_loader.get(name, loader=self._loader, templar=templar).run( + args, variables=variables or {} + )[0] + + if not has_domain(_run("domains", []), application_id): + return [False] + if not _to_bool(_run("tls", [application_id, "enabled"])): + return [False] + return [_run("tls", [application_id, "mode"]) == SELF_SIGNED_MODE] diff --git a/plugins/lookup/canonical_url.py b/plugins/lookup/canonical_url.py new file mode 100644 index 0000000000..2a173ede50 --- /dev/null +++ b/plugins/lookup/canonical_url.py @@ -0,0 +1,111 @@ +# Central onion-aware base-URL resolver. +# +# `lookup('canonical_url', application_id[, canonical_key])` returns the web +# base URL (``scheme://host``, no trailing slash) for an application, or for a +# specific named canonical (e.g. ``element`` / ``synapse`` / ``filer``) when the +# role declares ``server.domains.canonical`` as a dict. +# +# The scheme follows the resolved domain: ``.onion`` targets are plaintext (Tor +# provides the encryption) so they resolve to ``http``; everything else follows +# the deployment TLS setting (``https`` when enabled). Because the domain comes +# from the onion-injected merged-domain map, an app deployed onion-exclusive +# yields its ``.onion`` URL automatically — callers never branch on +# clearnet-vs-onion themselves. +# +# `consumer=` gates the result on the consumer's service +# binding: it returns '' unless ``services..enabled`` is truthy +# on the consuming application. This replaces the recurring +# ``(lookup(...) if lookup('config', application_id, 'services.X.enabled') else '')`` +# template branching. +# +# Primary resolution is family-aligned: a clearnet-primary consumer (via +# ``consumer=`` or the caller's ``application_id``) referencing an +# onion-primary target gets the target's clearnet sibling when one exists. + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.domains.primary_domain import get_primary_domain +from utils.roles.entity.name import get_entity_name +from utils.tls_common import ( + align_domain_to_consumer, + as_str, + require, + resolve_enabled, +) + + +class LookupModule(LookupBase): + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + variables = variables or {} + + if not terms or len(terms) not in (1, 2): + raise AnsibleError( + "canonical_url: one or two terms required: " + "(application_id[, canonical_key])" + ) + + templar = getattr(self, "_templar", None) + app_id = as_str(templar.template(terms[0]) if templar else terms[0]) + if not app_id: + raise AnsibleError("canonical_url: application_id is empty") + key = as_str(terms[1]).strip() if len(terms) == 2 else "" + + applications = lookup_loader.get( + "applications", loader=self._loader, templar=templar + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + consumer = as_str( + templar.template(kwargs["consumer"]) + if templar and "consumer" in kwargs + else kwargs.get("consumer", "") + ) + if consumer: + consumer_app = applications.get(consumer, {}) + if not isinstance(consumer_app, dict): + consumer_app = {} + binding = consumer_app.get("services", {}).get(get_entity_name(app_id), {}) + if not (isinstance(binding, dict) and binding.get("enabled")): + return [""] + + domains = lookup_loader.get( + "domains", loader=self._loader, templar=templar + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + if key: + app_domains = domains.get(app_id) + if not isinstance(app_domains, dict): + raise AnsibleError( + f"canonical_url: '{app_id}' has no named-canonical domains; " + f"cannot resolve key '{key}'" + ) + domain = app_domains.get(key) + if not isinstance(domain, str) or not domain: + raise AnsibleError( + f"canonical_url: '{app_id}' has no canonical '{key}' " + f"(available: {sorted(app_domains)})" + ) + else: + domain = get_primary_domain(domains, app_id) + domain = align_domain_to_consumer( + domains, + app_id, + domain, + consumer=consumer, + variables=variables, + templar=templar, + ) + + app = applications.get(app_id, {}) + if not isinstance(app, dict): + app = {} + + enabled_default = require(variables, "TLS_ENABLED", (bool, int)) + enabled = resolve_enabled(app, bool(enabled_default), primary_domain=domain) + scheme = "https" if enabled else "http" + return [f"{scheme}://{domain}"] diff --git a/plugins/lookup/cert.py b/plugins/lookup/cert.py index 65b245f7ec..53afb3e3ef 100644 --- a/plugins/lookup/cert.py +++ b/plugins/lookup/cert.py @@ -81,8 +81,6 @@ class LookupModule(LookupBase): def run(self, terms, variables: dict | None = None, **kwargs): variables = variables or {} - # New API: want-path is the 2nd positional term. - # Legacy 'want=' kwarg is ignored (no error) to keep tasks noise-free. if not terms or len(terms) not in (1, 2): raise AnsibleError( "cert: one or two terms required: (domain|application_id[, want_path])" @@ -184,10 +182,8 @@ class LookupModule(LookupBase): cert_file = _join(ss_base, cert_id, LE_FULLCHAIN) key_file = _join(ss_base, cert_id, LE_PRIVKEY) - # STRICT: list[str] only san_domains = _require_current_play_domains_all_strict(variables) - # Ensure primary domain is always included if primary_domain: san_domains = uniq_preserve([primary_domain, *san_domains]) diff --git a/plugins/lookup/compose_volumes.py b/plugins/lookup/compose_volumes.py index d310d82bf9..19c297bd19 100644 --- a/plugins/lookup/compose_volumes.py +++ b/plugins/lookup/compose_volumes.py @@ -1,21 +1,302 @@ -"""Lookup `compose_volumes`: render the top-level `volumes:` block for -a given application_id. Auto-wires the `applications` registry, -DEPLOYMENT_MODE, and `storage` mapping from the templating context. +"""Lookup `compose_volumes`: render the top-level `volumes:` / `configs:` / +`secrets:` block. Auto-wires `application_id`, the `applications` registry, +DEPLOYMENT_MODE, and the `storage` mapping from the templating context. """ from __future__ import annotations import contextlib +from collections.abc import Mapping, Sequence from typing import Any -from ansible.errors import AnsibleError +from ansible.errors import AnsibleError, AnsibleFilterError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from plugins.filter.compose_volumes import compose_volumes as _render_compose_volumes +from plugins.filter.docker.service_enabled import ( + FilterModule as _DockerServiceEnabledFilter, +) +from plugins.filter.get.entity_name import get_entity_name + +# nocheck: lookup-cache-import (raw-volume accessor: canonical meta/volumes.yml shape) +from utils.cache.applications import get_canonical_volumes +from utils.cache.yaml import dump_yaml_str +from utils.roles.applications.config import get +from utils.roles.applications.mounts import ( + content_hash, + mount_when_passes, + normalize_volumes_meta, +) +from utils.roles.applications.services.database import ( + get_database_service_config, + resolve_database_service_key, +) +from utils.roles.applications.services.sso import get_sso_config +from utils.storage.nfs import swarm_nfs_backed from utils.templating.ansible import _trust_as_template +def _to_plain(obj: Any) -> Any: + """Convert Ansible/Jinja proxy types into plain Python so PyYAML can serialize.""" + + if obj is None: + return None + + if isinstance(obj, str): + return str(obj) + + if isinstance(obj, (int, float, bool)): + return obj + + if isinstance(obj, Mapping): + return {str(_to_plain(k)): _to_plain(v) for k, v in obj.items()} + + if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)): + return [_to_plain(x) for x in obj] + + return str(obj) + + +def _resolve_database_volume_name( + applications: dict[str, Any], application_id: str, dbtype: str +) -> str: + consumer_entity = get_entity_name(application_id) + db_id = f"svc-db-{dbtype}" + central_name = get( + applications=applications, + application_id=db_id, + config_path=f"services.{dbtype}.name", + strict=False, + default="", + skip_missing_app=True, + ) + central_name = (str(central_name) if central_name is not None else "").strip() + service_cfg = get_database_service_config(applications, application_id) + central_enabled = bool(service_cfg.get("shared", False)) + host = central_name if central_enabled else "database" + volume_prefix = "" if central_enabled else f"{consumer_entity}_" + return f"{volume_prefix}{host}" + + +def _swarm_nfs_driver_opts(dir_var_lib: str, volume_name: str) -> dict[str, Any]: + return { + "driver": "local", + "driver_opts": { + "type": "none", + "o": "bind", + "device": f"{dir_var_lib.rstrip('/')}/{volume_name}", + }, + } + + +def _read_file_for_hash(source: str) -> str: + """Read a file's content for hash-based naming. Returns the path as a + stable fallback when the file isn't materialised yet (lint runs).""" + try: + from utils.cache.files import read_text + + return read_text(source) + except (OSError, ValueError): + return source + + +def _config_secret_name(role_entity: str, user_name: str, source: str) -> str: + """Build a swarm-rotation-safe name: ``{role}_{name}_{sha8(content)}``.""" + digest = content_hash(_read_file_for_hash(source)) + return f"{role_entity}_{user_name}_{digest}" + + +def _maybe_render(value: Any, render_jinja: Any) -> str: + text = str(value) + if render_jinja is None or ("{{" not in text and "{%" not in text): + return text + try: + return str(render_jinja(text)) + except AnsibleError: + return text + + +def compose_volumes( + applications: dict[str, Any], + application_id: str, + *, + extra_volumes: dict[str, dict[str, Any]] | None = None, + extra_configs: dict[str, dict[str, Any]] | None = None, + extra_secrets: dict[str, dict[str, Any]] | None = None, + deployment_mode: str = "compose", + storage: dict[str, Any] | None = None, + dir_var_lib: str, + render_jinja: Any = None, +) -> str: + """Render the top-level ``volumes:`` / ``configs:`` / ``secrets:`` block. + + Reads the canonical dict-of-dicts shape from + ``roles//meta/volumes.yml`` (YAML key = semantic short name; + optional ``name:`` field = docker volume name). Entries with + ``type: config`` / ``type: secret`` emit their respective top-level + sections; everything else flows through the volumes section. + + A ``type: volume`` entry may set ``nfs: false`` to opt out of the + swarm NFS rewrite: the volume then stays a plain node-local named + volume even when ``storage.backend`` is ``nfs`` (e.g. gitaly + repository storage, which upstream forbids on NFS). Any other + ``nfs`` value (absent, ``true``, or the uid/gid/mode dict consumed + by the NFS subdir pre-creation) keeps the rewrite. + """ + + if applications is None: + raise AnsibleFilterError("compose_volumes: 'applications' must not be None") + if not isinstance(applications, dict): + raise AnsibleFilterError("compose_volumes: 'applications' must be a dict") + if not application_id or not isinstance(application_id, str): + raise AnsibleFilterError( + "compose_volumes: 'application_id' must be a non-empty string" + ) + if application_id not in applications: + raise AnsibleFilterError( + f"compose_volumes: unknown application_id '{application_id}'" + ) + + role_entity = get_entity_name(application_id) + volumes: dict[str, Any] = {} + configs: dict[str, Any] = {} + secrets: dict[str, Any] = {} + + try: + database_service_key = resolve_database_service_key( + applications, application_id + ) + except ValueError as exc: + raise AnsibleFilterError( + "compose_volumes: " + f"{exc}. Simultaneous postgres + mariadb on the same role " + "is not supported (the embedded service templates collide " + "on the `database` service key, host name, and volume " + "key); pick one dbtype per role." + ) from exc + database_service = get_database_service_config(applications, application_id) + database_needed = bool(database_service_key) and not bool( + database_service.get("shared", False) + ) + + if database_needed: + volumes["database"] = { + "name": _resolve_database_volume_name( + applications, application_id, database_service_key + ) + } + + for engine in ("seaweedfs", "minio"): + engine_enabled = bool( + get( + applications=applications, + application_id=application_id, + config_path=f"services.{engine}.enabled", + strict=False, + default=False, + ) + ) + engine_shared = bool( + get( + applications=applications, + application_id=application_id, + config_path=f"services.{engine}.shared", + strict=False, + default=False, + ) + ) + if engine_enabled and not engine_shared: + volumes[engine] = {"name": f"{get_entity_name(application_id)}_{engine}"} + + sso = get_sso_config(applications, application_id) + + if ( + _DockerServiceEnabledFilter.is_docker_service_enabled( + applications, application_id, "redis" + ) + or sso["is_proxy_gated"] + ): + volumes["redis"] = {"name": f"{role_entity}_redis"} + + if extra_volumes: + volumes.update(extra_volumes) + if extra_configs: + configs.update(extra_configs) + if extra_secrets: + secrets.update(extra_secrets) + + role_data = applications.get(application_id) or {} + raw_meta_volumes = ( + get_canonical_volumes(application_id) or role_data.get("volumes") or {} + ) + canonical_entries = normalize_volumes_meta(raw_meta_volumes) + + for semantic_name, entry in canonical_entries.items(): + vtype = entry.get("type", "volume") + + if vtype == "volume": + if semantic_name in volumes: + continue + spec: dict[str, Any] = {} + docker_name = entry.get("name") + if docker_name: + spec["name"] = docker_name + if "nfs" in entry: + spec["nfs"] = entry["nfs"] + volumes[semantic_name] = spec + continue + + if vtype in ("config", "secret") and not any( + mount_when_passes(mount, render_jinja) + for mount in entry.get("mounts") or [] + if isinstance(mount, dict) + ): + continue + + if vtype == "config": + source = _maybe_render(entry.get("source", ""), render_jinja) + configs[semantic_name] = { + "name": _maybe_render(entry.get("name", ""), render_jinja) + or _config_secret_name(role_entity, semantic_name, source), + "file": source, + } + continue + + if vtype == "secret": + source = _maybe_render(entry.get("source", ""), render_jinja) + secrets[semantic_name] = { + "name": _maybe_render(entry.get("name", ""), render_jinja) + or _config_secret_name(role_entity, semantic_name, source), + "file": source, + } + continue + + storage_backend = (storage or {}).get("backend", "local") + + for vol_name, vol_spec in list(volumes.items()): + if not isinstance(vol_spec, dict): + continue + nfs_meta = vol_spec.pop("nfs", None) + if swarm_nfs_backed( + {"nfs": nfs_meta}, + application_id=application_id, + deployment_mode=deployment_mode, + storage_backend=storage_backend, + ): + named = vol_spec.get("name", vol_name) + vol_spec.update(_swarm_nfs_driver_opts(dir_var_lib, str(named))) + if isinstance(nfs_meta, dict): + vol_spec["x-infinito-nfs"] = dict(nfs_meta) + + payload: dict[str, Any] = {"volumes": _to_plain(volumes)} + if configs: + payload["configs"] = _to_plain(configs) + if secrets: + payload["secrets"] = _to_plain(secrets) + + return dump_yaml_str(payload).rstrip() + + class LookupModule(LookupBase): def run( self, @@ -23,19 +304,25 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[str]: - if not terms or len(terms) != 1: + if terms: raise AnsibleError( - "compose_volumes lookup requires exactly one term: the application_id" - ) - application_id = str(terms[0]).strip() - if not application_id: - raise AnsibleError( - "compose_volumes lookup: application_id must be non-empty" + "compose_volumes lookup expects no terms; application_id " + "is read from the templating context" ) vars_ = variables or getattr(self._templar, "available_variables", {}) or {} templar = getattr(self, "_templar", None) + application_id = vars_.get("application_id") + if templar is not None and application_id is not None: + application_id = templar.template(application_id) + application_id = str(application_id or "").strip() + if not application_id: + raise AnsibleError( + "compose_volumes lookup: 'application_id' is not set in the " + "templating context" + ) + applications = lookup_loader.get( "applications", loader=self._loader, templar=getattr(self, "_templar", None) ).run([], variables=vars_)[0] @@ -75,7 +362,7 @@ class LookupModule(LookupBase): fail_on_undefined=False, ) - rendered = _render_compose_volumes( + rendered = compose_volumes( applications, application_id, extra_volumes=kwargs.get("extra_volumes"), diff --git a/plugins/lookup/config.py b/plugins/lookup/config.py index 3478be6103..79e32c4b9e 100644 --- a/plugins/lookup/config.py +++ b/plugins/lookup/config.py @@ -118,5 +118,4 @@ class LookupModule(LookupBase): raw_applications=applications, ) - # lookup plugins must return a list return [value] diff --git a/plugins/lookup/container.py b/plugins/lookup/container.py index 66c4346996..b305a5ce0c 100644 --- a/plugins/lookup/container.py +++ b/plugins/lookup/container.py @@ -39,7 +39,6 @@ class LookupModule(LookupBase): raise AnsibleError("lookup('container'): application_id is empty") raw_base = (variables or {}).get("DIR_COMPOSITIONS") - # DIR_COMPOSITIONS is itself a Jinja expression in swarm mode; lookup vars arrive un-templated. if isinstance(raw_base, str) and "{{" in raw_base and self._templar is not None: raw_base = self._templar.template(raw_base) base = _as_str(raw_base) diff --git a/plugins/lookup/container_deploy.py b/plugins/lookup/container_deploy.py new file mode 100644 index 0000000000..5a7a5985eb --- /dev/null +++ b/plugins/lookup/container_deploy.py @@ -0,0 +1,76 @@ +"""Lookup ``container_deploy``: emit the swarm ``deploy:`` head — the replica +count plus, for a role whose primary entity declares one, the placement +constraint. Renders nothing outside swarm mode, so callers need no mode guard +of their own. + + {{ lookup('container_deploy') | indent(4) }} # topology default + {{ lookup('container_deploy', replicas=1) | indent(4) }} # single-writer sidecar + {{ lookup('container_deploy', replicas=n) | indent(4) }} # explicit; '' = default + +Callers that also need ``update_config``, ``restart_policy`` or ``resources`` +append them under the same key. +""" + +from __future__ import annotations + +import contextlib +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.roles.meta_lookup import get_role_placement + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + if terms: + raise AnsibleError( + "container_deploy lookup takes no positional terms; " + "pass the replica count as replicas=" + ) + + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + templar = getattr(self, "_templar", None) + + mode = ( + vars_.get("compose_mode") + or vars_.get("compose_mode_force") + or vars_.get("DEPLOYMENT_MODE", "compose") + ) + if templar is not None: + with contextlib.suppress(Exception): + mode = templar.template(mode) + if str(mode).strip() != "swarm": + return [""] + + application_id = vars_.get("application_id") + if templar is not None and application_id is not None: + with contextlib.suppress(Exception): + application_id = templar.template(application_id) + if not application_id: + raise AnsibleError( + "container_deploy lookup: application_id is required in variables" + ) + + replicas_override = kwargs.get("replicas", "") + override = [replicas_override] if str(replicas_override) != "" else [] + replicas = lookup_loader.get( + "compose_replicas", loader=self._loader, templar=templar + ).run(override, variables={**vars_, "DEPLOYMENT_MODE": "swarm"})[0] + + lines = ["deploy:", f" {replicas}"] + placement = get_role_placement(str(application_id)) + if placement: + lines += [ + " placement:", + " constraints:", + f" - node.role == {placement}", + ] + return ["\n".join(lines)] diff --git a/plugins/lookup/container_dns.py b/plugins/lookup/container_dns.py new file mode 100644 index 0000000000..cf653494cf --- /dev/null +++ b/plugins/lookup/container_dns.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import Any + +from ansible.plugins.lookup import LookupBase + +_TOR_ROLE = "svc-net-tor" + + +def resolve_container_dns(variables: dict[str, Any]) -> list[str]: + """Return the resolver list for the container runtime, most specific first. + + On a Tor node the node dnsmasq resolves ``.onion`` through Tor's DNSPort + and everything else through the clearnet upstream, which is what makes + per-app proxy settings unnecessary. It is only reachable on the docker + bridge address because docker discards loopback resolvers, and it is + absent before docker itself is installed, hence the guard. + + Both deploy modes get the bridge: a Tor node runs the same dnsmasq + listener in compose and in swarm, so both resolve onions alike. + + The clearnet resolver stays as a second entry so that losing dnsmasq costs + onion names rather than all name resolution. Duplicates are dropped: where + the bridge *is* the clearnet resolver, emitting it twice makes daemon.json + differ between a run before and a run after ``docker0`` exists, and that + difference restarts the container runtime underneath a live stack. + """ + facts = variables.get("ansible_facts") or {} + bridge = ((facts.get("docker0") or {}).get("ipv4") or {}).get("address") or "" + on_tor_node = _TOR_ROLE in (variables.get("group_names") or []) + + clearnet = ((variables.get("networks") or {}).get("internet") or {}).get( + "dns" + ) or "" + + resolvers = (bridge if on_tor_node else "", clearnet) + return list(dict.fromkeys(str(r) for r in resolvers if r)) + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('container_dns') }} + + Resolver list for the docker daemon's ``dns`` key. Takes no terms. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if terms: + raise ValueError("lookup('container_dns') takes no positional terms.") + variables = variables or getattr(self._templar, "available_variables", {}) or {} + return [resolve_container_dns(variables)] diff --git a/plugins/lookup/container_extra_hosts.py b/plugins/lookup/container_extra_hosts.py new file mode 100644 index 0000000000..fd96e823ef --- /dev/null +++ b/plugins/lookup/container_extra_hosts.py @@ -0,0 +1,225 @@ +"""Lookup ``container_extra_hosts``: the single emitter of ``extra_hosts:``. + +Compose rejects a mapping that carries the key twice, so nothing else in the +repo may write ``extra_hosts:`` by hand. Everything a service needs pinned goes +through here, from two sources that are both optional: + +1. The SSO back-channel pin, added automatically. On an onion deployment the + OIDC endpoints handed to an application are public ``.onion`` authorities. + That is right for the browser, which reaches them through Tor, but + unroutable for the application's own server-side calls (code-to-token + exchange, JWKS, userinfo): a container resolves ``.onion`` through Tor's + resolver, not through DNS. Pinning the provider to a reachable address sends + those calls over the local network to the proxy that already serves the + vhost. Skipped unless the application has SSO enabled and the provider vhost + is an ``.onion`` name, so it is a no-op on clearnet. +2. ``host_alias=true``, which pins ``host.docker.internal`` at whatever reaches + the host in the effective mode. A container that must talk to a service the + host publishes -- msmtp relaying through the swarm ingress on :587, for + instance -- needs the alias, and it must not hardcode ``host-gateway`` + because that breaks under swarm for the reason below. +3. ``extra_hosts=``, whatever the call site needs on top: a peer's overlay VIP, + or a partner service reachable only on the host. + +Entries are ``"name:address"`` strings and are deduplicated in first-seen +order. With nothing to emit the lookup returns an empty string. + +The automatic pin follows the effective deploy mode, and in swarm it must NOT be +``host-gateway``: that alias resolves per node, while openresty publishes :80 +with ``mode: host`` under ``node.role == manager``, so every replica on a worker +dialled its own gateway and the token exchange died with 'Connection refused' +(7b1839681, measured on penpot in run 31340965955). Swarm therefore gets the +stack host's routable address -- the destination svc-net-tor already sends all +hidden-service traffic to. ``ansible_facts`` carries it because the compose file +is rendered once with the manager as inventory host and swarm applies the same +``extra_hosts`` to every task. + +The mode is read as ``compose_mode_force or DEPLOYMENT_MODE`` rather than the +bare cluster mode, because ``container_networks`` resolves attachments through +that same effective mode: a role with an override must not lose its pin and its +overlay at once. + +Caller-supplied entries are passed through untouched, so a call site that needs +a different address per mode must still decide that itself. + +Usage in any service template: + + {{ lookup('container_extra_hosts') | indent(4) }} + {{ lookup('container_extra_hosts', + extra_hosts=['host.docker.internal:host-gateway']) | indent(4) }} + {{ lookup('container_extra_hosts', application_id='web-app-nextcloud') | indent(4) }} +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.module_utils.parsing.convert_bool import boolean as _to_bool +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.networks.lookup_context import resolve_var + +HOST_GATEWAY = "host-gateway" +DOCKER_INTERNAL_HOST = "host.docker.internal" +SSO_PROVIDER = "web-app-keycloak" + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + if terms: + raise AnsibleError( + "container_extra_hosts lookup takes no positional terms; pass " + "extra_hosts=[...] and application_id= as keyword arguments" + ) + + self._vars = ( + variables or getattr(self._templar, "available_variables", {}) or {} + ) + application_id = self._render( + kwargs.get("application_id") or self._vars.get("application_id") + ) + if not application_id: + raise AnsibleError( + "container_extra_hosts lookup: no application_id in the play vars; " + "pass application_id= explicitly" + ) + + entries = self._sso_pins(application_id) + if _to_bool(self._render(kwargs.get("host_alias", False)), strict=False): + entries.append( + f"{DOCKER_INTERNAL_HOST}:{self._gateway_address(DOCKER_INTERNAL_HOST)}" + ) + entries += self._caller_entries(kwargs.get("extra_hosts")) + merged = list(dict.fromkeys(entries)) + if not merged: + return [""] + + lines = ["extra_hosts:"] + [f' - "{entry}"' for entry in merged] + return ["\n".join(lines)] + + def _sso_pins(self, application_id: str) -> list[str]: + """The provider pin, empty unless this is an onion node running SSO. + + Args: + application_id: the role whose ``services.sso`` gate decides. + + The gate is read with a default rather than strictly, because roles that + declare no ``sso`` entry at all are legitimate call sites here -- they + just have nothing to pin. + """ + if not bool( + self._lookup("config", application_id, "services.sso.enabled", False) + ): + return [] + + provider_host = str(self._lookup("tls", SSO_PROVIDER, "domain") or "").strip() + if not provider_host.endswith(".onion"): + return [] + + return [ + f"{DOCKER_INTERNAL_HOST}:{HOST_GATEWAY}", + f"{provider_host}:{self._gateway_address(provider_host)}", + ] + + def _caller_entries(self, extra_hosts: Any) -> list[str]: + """Normalise the ``extra_hosts=`` argument to a list of mappings. + + Args: + extra_hosts: one ``"name:address"``, a list of them, or None. + Entries that render empty are dropped, so a call site can build + its list with inline conditionals. + + Raises: + AnsibleError: an entry carries no ``:`` separator, which Docker + would reject only at deploy time. + """ + if not extra_hosts: + return [] + if isinstance(extra_hosts, str): + extra_hosts = [extra_hosts] + + entries: list[str] = [] + for entry in extra_hosts: + text = str(self._render(entry) or "").strip() + if not text: + continue + if ":" not in text: + raise AnsibleError( + f"container_extra_hosts: extra_hosts entry '{text}' is not a " + "'name:address' mapping" + ) + entries.append(text) + return entries + + def _gateway_address(self, provider_host: str) -> str: + """Resolve what the provider host must point at in the effective mode. + + Args: + provider_host: only used to name the host in errors. + + Under swarm this is the stack host's address, not the local node's: + the template renders once on the manager and swarm copies the same + ``extra_hosts`` to every task, which is what makes the pin reach the + one node where openresty publishes. + """ + if self._compose_mode() == "compose": + return HOST_GATEWAY + + facts = self._vars.get("ansible_facts") or {} + address = str((facts.get("default_ipv4") or {}).get("address") or "").strip() + if not address: + raise AnsibleError( + f"container_extra_hosts: cannot pin '{provider_host}' outside compose " + "mode because ansible_facts.default_ipv4.address is unset; the swarm " + f"pin must carry the stack host's address, not the '{HOST_GATEWAY}' " + "alias, which resolves per node and misses the manager that publishes " + "the vhost. Gather facts before rendering the service template." + ) + return address + + def _compose_mode(self) -> str: + """Resolve the effective deploy mode the way the network lookups do. + + ``compose_mode_force`` is a per-role override of the cluster + ``DEPLOYMENT_MODE``. Both can still be templates when they reach a + lookup, so both go through ``resolve_var``, which passes a value + through unchanged rather than raising when it cannot render. + """ + templar = getattr(self, "_templar", None) + mode = str(resolve_var(templar, self._vars.get("DEPLOYMENT_MODE", "compose"))) + forced = resolve_var(templar, self._vars.get("compose_mode_force", "")) + return str(forced or mode).strip() + + def _render(self, value: Any) -> Any: + """Template a value read straight out of the play vars. + + Args: + value: raw var value; ``include_role: vars:`` hands these over + unrendered, e.g. ``application_id: "{{ some_other_var }}"``. + + Raises: + AnsibleError: the value stayed a template, which would bake + ``{{ ... }}`` into the compose file. + """ + templar = getattr(self, "_templar", None) + if templar is None or not isinstance(value, str) or "{{" not in value: + return value + rendered = templar.template(value) + if isinstance(rendered, str) and "{{" in rendered: + raise AnsibleError( + f"container_extra_hosts: '{value}' did not render; it reached the " + "lookup untrusted as a template." + ) + return rendered + + def _lookup(self, name: str, *terms: Any) -> Any: + return lookup_loader.get( + name, loader=self._loader, templar=getattr(self, "_templar", None) + ).run(list(terms), variables=self._vars)[0] diff --git a/plugins/lookup/container_healthcheck.py b/plugins/lookup/container_healthcheck.py index 745c6a0d8d..f6f45f9ee4 100644 --- a/plugins/lookup/container_healthcheck.py +++ b/plugins/lookup/container_healthcheck.py @@ -13,7 +13,7 @@ only positional argument, everything else comes from the service's path: health/ready start_period: 20m -``flavor`` picks the probe shape (see utils/docker/healthcheck.py); each +``flavor`` picks the probe shape (see utils/docker/healthcheck/); each flavor brings its own interval, timeout, retries and start_period, and any of those may be overridden next to it. Without a ``flavor`` the entry must carry an explicit ``test`` argv. ``port_key`` selects another entry below @@ -33,7 +33,9 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.docker.healthcheck import PROBES, build, known_flavors +from utils.docker.healthcheck.compose import build, known_flavors, resolve_flavors +from utils.docker.healthcheck.prefixes import PREFIXES +from utils.docker.healthcheck.probes import PROBES class LookupModule(LookupBase): @@ -64,7 +66,12 @@ class LookupModule(LookupBase): config = self._config(f"services.{service}.healthcheck", {}) config = config if isinstance(config, dict) else {} - flavor = str(config.get("flavor", "") or "").strip() + declared = config.get("flavor", "") + flavor: str | list[str] = ( + [str(name).strip() for name in declared if str(name).strip()] + if isinstance(declared, list) + else str(declared or "").strip() + ) where = f"'{self._application_id}' service '{service}'" if not flavor and not config.get("test"): @@ -72,9 +79,14 @@ class LookupModule(LookupBase): f"container_healthcheck: {where} declares no healthcheck.flavor, so " f"healthcheck.test is required. Known flavors: {known_flavors()}." ) - if flavor and flavor not in PROBES: + unknown = [ + name + for name in (resolve_flavors(flavor) if flavor else []) + if name not in PROBES and name not in PREFIXES + ] + if unknown: raise AnsibleError( - f"container_healthcheck: unknown flavor '{flavor}' for {where}. " + f"container_healthcheck: unknown flavor '{unknown[0]}' for {where}. " f"Known flavors: {known_flavors()}." ) @@ -95,9 +107,7 @@ class LookupModule(LookupBase): config: that service's healthcheck entry. kwargs: the call site's keyword arguments. """ - hostname = self._render( - config.get("hostname", self._vars.get("container_hostname")) - ) + hostname = self._render(config.get("hostname")) port_key = str(config.get("port_key", "http") or "http") context = { "test": config.get("test"), @@ -107,7 +117,7 @@ class LookupModule(LookupBase): "hostname": str(hostname) if hostname else None, "samples": int(kwargs.get("samples", config.get("samples", 1)) or 1), } - if flavor == "msmtp_curl": + if "msmtp" in resolve_flavors(flavor): context.update( email_enabled=bool(self._config("services.email.enabled", False)), domain=self._lookup("domain", self._application_id), diff --git a/plugins/lookup/container_hostname.py b/plugins/lookup/container_hostname.py new file mode 100644 index 0000000000..25c28bdb67 --- /dev/null +++ b/plugins/lookup/container_hostname.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.domains.primary_domain import get_domain +from utils.roles.entity.name import get_entity_name + +_HOST_NAME_MAX = 63 + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('container_hostname', application_id) }} + + The Docker/OCI hostname for an application's container: its canonical + primary domain when that fits the kernel's 63-byte limit, otherwise the + short entity name (e.g. ``xwiki``). Centralises the domain-or-entity + choice so onion deployments (long ``.onion`` subdomains that overflow + sethostname(2)) never break container init. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if not terms or len(terms) != 1: + raise AnsibleError( + "lookup('container_hostname', application_id) expects exactly 1 term" + ) + + application_id = terms[0] + if not isinstance(application_id, str) or not application_id.strip(): + raise AnsibleError( + "lookup('container_hostname'): application_id must be a " + f"non-empty string, got {application_id!r}" + ) + application_id = application_id.strip() + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + + domains = lookup_loader.get( + "domains", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + try: + domain = get_domain(domains, application_id) + except Exception as e: + raise AnsibleError( + f"lookup('container_hostname'): failed to resolve domain for " + f"'{application_id}': {e}" + ) from e + + name = str(domain or "") + if 0 < len(name) <= _HOST_NAME_MAX: + return [name] + return [get_entity_name(application_id)] diff --git a/plugins/lookup/container_mail_marker.py b/plugins/lookup/container_mail_marker.py new file mode 100644 index 0000000000..cf460c3738 --- /dev/null +++ b/plugins/lookup/container_mail_marker.py @@ -0,0 +1,31 @@ +"""Lookup `container_mail_marker`: path of the msmtp_curl delivery marker. + +Single SPOT for the file the ``msmtp_curl`` healthcheck touches after msmtp +exits 0. A deploy-time assertion that the relay accepted the startup mail has +to name the same path the probe writes, and a second literal would drift the +moment the probe moves it. + +Usage: + {{ lookup('container_mail_marker') }} -> /tmp/email_sent +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils.docker.healthcheck.prefixes import MAIL_MARKER + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + if terms: + raise AnsibleError("lookup('container_mail_marker') expects no terms.") + return [MAIL_MARKER] diff --git a/plugins/lookup/container_volumes.py b/plugins/lookup/container_volumes.py index a6afe38d97..791af3b8ac 100644 --- a/plugins/lookup/container_volumes.py +++ b/plugins/lookup/container_volumes.py @@ -1,21 +1,181 @@ -"""Lookup ``container_volumes(application_id, service)``: render the -per-service ``volumes:`` / ``configs:`` / ``secrets:`` block fed from -``meta/volumes.yml``. Output starts at column 0; callers add the indent. +"""Lookup ``container_volumes(service)``: render the per-service +``volumes:`` / ``configs:`` / ``secrets:`` block fed from +``meta/volumes.yml``; ``application_id`` comes from the templating +context. Output starts at column 0; callers add the indent +(``| indent(4)`` or whatever depth) so the block sits under the right +service in ``compose.yml.j2``. """ from __future__ import annotations -from typing import Any +from typing import TYPE_CHECKING, Any -from ansible.errors import AnsibleError +from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from plugins.filter.container_volumes import ( - container_volumes as _render_container_volumes, +# nocheck: lookup-cache-import (raw-volume accessor: canonical meta/volumes.yml shape) +from utils.cache.applications import get_canonical_volumes +from utils.cache.yaml import dump_yaml_str +from utils.roles.applications.mounts import ( + mount_default_read_only, + mount_when_passes, + normalize_volumes_meta, ) from utils.templating.ansible import _trust_as_template +if TYPE_CHECKING: + from collections.abc import Callable + + +def _coerce_mode_int(value: Any) -> int: + if isinstance(value, bool): + raise AnsibleFilterError( + f"container_volumes: mode must be an octal int or string, got bool: {value!r}" + ) + if isinstance(value, int): + return value + text = str(value).strip() + if not text: + raise AnsibleFilterError("container_volumes: mode is empty") + try: + return int(text, 8) + except ValueError as exc: + raise AnsibleFilterError( + f"container_volumes: mode {value!r} is not a valid octal: {exc}" + ) from exc + + +def _short_form_volume(source_name: str, target: str, read_only: bool) -> str: + suffix = ":ro" if read_only else "" + return f"{source_name}:{target}{suffix}" + + +def container_volumes( + applications: dict[str, Any], + application_id: str, + service: str, + *, + extra_volumes: list[Any] | None = None, + extra_configs: list[dict[str, Any]] | None = None, + extra_secrets: list[dict[str, Any]] | None = None, + render_jinja: Callable[[str], str] | None = None, +) -> str: + """Return the per-service mount block (``volumes:`` + ``configs:`` + + ``secrets:``) as a YAML string starting at column 0. + """ + if not isinstance(applications, dict): + raise AnsibleFilterError("container_volumes: 'applications' must be a dict") + if not isinstance(application_id, str) or not application_id.strip(): + raise AnsibleFilterError( + "container_volumes: 'application_id' must be a non-empty string" + ) + if not isinstance(service, str) or not service.strip(): + raise AnsibleFilterError( + "container_volumes: 'service' must be a non-empty string" + ) + + role_data = applications.get(application_id) or {} + raw_meta_volumes = ( + get_canonical_volumes(application_id) or role_data.get("volumes") or {} + ) + canonical_entries = normalize_volumes_meta(raw_meta_volumes) + + volumes_block: list[Any] = [] + configs_block: list[dict[str, Any]] = [] + secrets_block: list[dict[str, Any]] = [] + + for semantic_name, entry in canonical_entries.items(): + vtype = entry.get("type", "volume") + volume_level_ro = bool(entry.get("read_only", mount_default_read_only(entry))) + + for mount in entry.get("mounts") or []: + if not isinstance(mount, dict): + continue + if mount.get("service") != service: + continue + if not mount_when_passes(mount, render_jinja): + continue + + target = mount.get("target") + if not target: + continue + target_text = str(target) + if render_jinja is not None and ( + "{{" in target_text or "{%" in target_text + ): + try: + target = str(render_jinja(target_text)) + except AnsibleUndefinedVariable as exc: + raise AnsibleFilterError( + f"container_volumes: failed to render mount target " + f"{target_text!r} for application {application_id!r}, " + f"service {service!r}: {exc}" + ) from exc + + if vtype == "volume": + read_only = bool(mount.get("read_only", volume_level_ro)) + volumes_block.append( + _short_form_volume(semantic_name, target, read_only) + ) + + elif vtype == "bind": + source = str(entry.get("source", "")) + if render_jinja is not None and ("{{" in source or "{%" in source): + try: + source = str(render_jinja(source)) + except AnsibleUndefinedVariable as exc: + raise AnsibleFilterError( + f"container_volumes: failed to render bind source " + f"{source!r} for application {application_id!r}, " + f"service {service!r}: {exc}" + ) from exc + read_only = bool(mount.get("read_only", volume_level_ro)) + volumes_block.append(_short_form_volume(source, target, read_only)) + + elif vtype == "tmpfs": + tmpfs_entry: dict[str, Any] = { + "type": "tmpfs", + "target": target, + } + if mount.get("size") is not None: + tmpfs_entry["tmpfs"] = {"size": mount["size"]} + volumes_block.append(tmpfs_entry) + + elif vtype == "config": + cfg_ref: dict[str, Any] = {"source": semantic_name, "target": target} + mode_value = entry.get("mode") + if mode_value: + cfg_ref["mode"] = _coerce_mode_int(mode_value) + configs_block.append(cfg_ref) + + elif vtype == "secret": + sec_ref: dict[str, Any] = {"source": semantic_name, "target": target} + mode_value = entry.get("mode") + if mode_value: + sec_ref["mode"] = _coerce_mode_int(mode_value) + secrets_block.append(sec_ref) + + if extra_volumes: + volumes_block.extend(extra_volumes) + if extra_configs: + configs_block.extend(extra_configs) + if extra_secrets: + secrets_block.extend(extra_secrets) + + payload: dict[str, Any] = {} + if volumes_block: + payload["volumes"] = volumes_block + if configs_block: + payload["configs"] = configs_block + if secrets_block: + payload["secrets"] = secrets_block + + if not payload: + return "" + + return dump_yaml_str(payload).rstrip() + class LookupModule(LookupBase): def run( @@ -24,23 +184,28 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[str]: - if not terms or len(terms) != 2: + if not terms or len(terms) != 1: raise AnsibleError( - "container_volumes lookup requires exactly two terms: " - "(application_id, service)" - ) - application_id = str(terms[0]).strip() - service = str(terms[1]).strip() - if not application_id: - raise AnsibleError( - "container_volumes lookup: application_id must be non-empty" + "container_volumes lookup requires exactly one term: the " + "service; application_id is read from the templating context" ) + service = str(terms[0]).strip() if not service: raise AnsibleError("container_volumes lookup: service must be non-empty") vars_ = variables or getattr(self._templar, "available_variables", {}) or {} templar = getattr(self, "_templar", None) + application_id = vars_.get("application_id") + if templar is not None and application_id is not None: + application_id = templar.template(application_id) + application_id = str(application_id or "").strip() + if not application_id: + raise AnsibleError( + "container_volumes lookup: 'application_id' is not set in the " + "templating context" + ) + applications = lookup_loader.get( "applications", loader=self._loader, templar=getattr(self, "_templar", None) ).run([], variables=vars_)[0] @@ -58,7 +223,7 @@ class LookupModule(LookupBase): fail_on_undefined=False, ) - rendered = _render_container_volumes( + rendered = container_volumes( applications, application_id, service, diff --git a/plugins/lookup/current_play_redirect_domains.py b/plugins/lookup/current_play_redirect_domains.py index 8c1801c759..e4317a0297 100644 --- a/plugins/lookup/current_play_redirect_domains.py +++ b/plugins/lookup/current_play_redirect_domains.py @@ -122,7 +122,14 @@ class LookupModule(LookupBase): 2. ``{DOMAIN_PRIMARY -> DOMAIN_HOMEPAGE}`` (skipped when equal); non-empty result triggers ``sys-stk-front-base`` to auto-load ``web-opt-rdr-domains`` so openresty has an SNI match for - DOMAIN_PRIMARY even when no app claims it. + DOMAIN_PRIMARY even when no app claims it. On onion nodes + (``svc-net-tor`` in ``group_names`` with a provisioned + ``services.tor.node``) the bare node-onion apex is scheduled as an + additional source targeting the same ``DOMAIN_HOMEPAGE``, which is + already family-correct there (onion-injected domain lookup); both + entries require ``web-opt-rdr-domains`` in + ``lookup('deployment').deployed`` so isolated CI variants do not + schedule a redirect whose target is not served. 3. per-app alias-to-canonical mappings from ``lookup('applications_current_play')``, gated by ``AUTO_BUILD_ALIASES``. @@ -140,6 +147,21 @@ class LookupModule(LookupBase): result = plugin.run([], variables=variables) return result[0] if result else None + def _node_onion(self, vars_: Mapping[str, Any]) -> str: + """Return the node onion address when this host is an onion node + (``svc-net-tor`` in ``group_names`` with a provisioned + ``services.tor.node`` in the ``applications`` override), else ``""``.""" + if "svc-net-tor" not in (vars_.get("group_names") or []): + return "" + apps = vars_.get("applications") + svc_tor = apps.get("svc-net-tor") if isinstance(apps, Mapping) else None + if not isinstance(svc_tor, Mapping): + return "" + services = svc_tor.get("services") + tor = services.get("tor") if isinstance(services, Mapping) else None + node = tor.get("node") if isinstance(tor, Mapping) else None + return self._resolve_str(node).strip() + def _resolve_str(self, value: Any) -> str: """Template a possibly Jinja-tagged inventory value through ``self._templar`` before string-coercion; bare ``str()`` would @@ -170,12 +192,28 @@ class LookupModule(LookupBase): merged = merge_mapping([], list(user_mappings), "source") - if domain_primary and domain_homepage and domain_primary != domain_homepage: - merged = merge_mapping( - merged, - [{"source": domain_primary, "target": domain_homepage}], - "source", - ) + if domain_primary and domain_homepage: + node_onion = self._node_onion(vars_) + allowed = True + if node_onion: + deployment = self._run_lookup("deployment", vars_) + deployed = ( + list(deployment.get("deployed") or []) + if isinstance(deployment, Mapping) + else [] + ) + allowed = "web-opt-rdr-domains" in deployed + if allowed: + primary_redirects = [] + if domain_primary != domain_homepage: + primary_redirects.append( + {"source": domain_primary, "target": domain_homepage} + ) + if node_onion and node_onion != domain_homepage: + primary_redirects.append( + {"source": node_onion, "target": domain_homepage} + ) + merged = merge_mapping(merged, primary_redirects, "source") current_play_apps = self._run_lookup("applications_current_play", vars_) if isinstance(current_play_apps, Mapping): diff --git a/plugins/lookup/database.py b/plugins/lookup/database.py index ac74f1f5b2..5d1f14e47f 100644 --- a/plugins/lookup/database.py +++ b/plugins/lookup/database.py @@ -8,6 +8,7 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.manager.credential_key import OVERRIDE_SECTION from utils.roles.applications.config import get from utils.roles.applications.services.database import ( get_database_service_config, @@ -130,17 +131,29 @@ class LookupModule(LookupBase): ) central_name = (str(central_name) if central_name is not None else "").strip() + declared_name = get( + applications, + consumer_id, + f"services.{dbtype}.name", + strict=False, + default="", + ) + declared_name = ( + str(declared_name) if declared_name is not None else "" + ).strip() + name = consumer_entity instance = central_name if central_enabled else name host = central_name if central_enabled else "database" - container = dbtype if central_enabled else f"{consumer_entity}-database" + dedicated_container = declared_name or f"{consumer_entity}-database" + container = dbtype if central_enabled else dedicated_container network = dbtype if central_enabled else consumer_entity username = consumer_entity password = get( applications, consumer_id, - "credentials.database_password", + f"{OVERRIDE_SECTION}.database_password", strict=False, default="", ) @@ -200,12 +213,17 @@ class LookupModule(LookupBase): volume_prefix = f"{consumer_entity}_" if not central_enabled else "" volume = f"{volume_prefix}{host}" - raw_mode = vars_.get("DEPLOYMENT_MODE", "compose") templar = getattr(self, "_templar", None) - if templar is not None: - with contextlib.suppress(Exception): - raw_mode = templar.template(raw_mode) - deployment_mode = str(raw_mode).strip() + + def _templated(value: Any) -> str: + if templar is not None: + with contextlib.suppress(Exception): + value = templar.template(value) + return str(value or "").strip() + + cluster_mode = _templated(vars_.get("DEPLOYMENT_MODE", "compose")) + forced = _templated(vars_.get("compose_mode_force", "")) + deployment_mode = cluster_mode if central_enabled else (forced or cluster_mode) db_stack = dbtype if central_enabled else consumer_entity db_service_key = dbtype if central_enabled else "database" diff --git a/plugins/lookup/depends_on.py b/plugins/lookup/depends_on.py index 6a81daea70..d20e7c804a 100644 --- a/plugins/lookup/depends_on.py +++ b/plugins/lookup/depends_on.py @@ -172,12 +172,6 @@ def _render(entries: dict[str, str], mode: str, indent: int) -> str: lines = body.splitlines() if indent <= 0 or len(lines) <= 1: return body - # Line 1 stays unindented so the caller can place - # `{{ lookup('depends_on', …) }}` at their preferred template - # column and the surrounding leading whitespace becomes the line-1 - # indent at render time. Jinja does not propagate that leading - # whitespace to continuation lines, so we bake it into lines 2+ - # ourselves. return lines[0] + "\n" + textwrap.indent("\n".join(lines[1:]), " " * indent) diff --git a/plugins/lookup/deployment.py b/plugins/lookup/deployment.py index 8192062f4e..ad7eb96a8a 100644 --- a/plugins/lookup/deployment.py +++ b/plugins/lookup/deployment.py @@ -16,7 +16,6 @@ def _reset_cache_for_tests() -> None: def _coerce_to_list(raw: Any) -> list[str]: - # CSV input (`-e APPLICATIONS_WHITELIST=a,b`) → tokenise; `list(str)` would yield chars. if raw is None: return [] if isinstance(raw, str): diff --git a/plugins/lookup/email.py b/plugins/lookup/email.py index 2bc840b380..56aaacb80e 100644 --- a/plugins/lookup/email.py +++ b/plugins/lookup/email.py @@ -23,10 +23,11 @@ RESOLUTION_ORDER = ( "external", "environment", "domain", + "host", "tls", "port", - "host", "auth", + "auth_mechanism", "start_tls", "smtp", "from", @@ -154,14 +155,18 @@ class LookupModule(LookupBase): external = _as_bool(resolved.get("external")) if not external: return False + mail_host = str(resolved.get("host") or "").lower() + if mail_host.endswith(".onion"): + return False return _as_bool(variables.get("TLS_ENABLED")) if short_key == "port": external = _as_bool(resolved.get("external")) - tls = _as_bool(resolved.get("tls")) # SSO relay: port 25 is the only listener not requiring SMTP AUTH. if self._provider_uses_sso_relay(variables): return 25 - return 465 if (external and tls) else 25 + if not external: + return 25 + return 465 if _as_bool(resolved.get("tls")) else 587 if short_key == "host": env = resolved.get("environment") # `environment` folds TLS_ENABLED into its "external" base, so a @@ -182,7 +187,11 @@ class LookupModule(LookupBase): return False if self._provider_uses_sso_relay(variables): return False - return _as_bool(resolved.get("tls")) + return _as_bool(resolved.get("external")) + if short_key == "auth_mechanism": + if not _as_bool(resolved.get("auth")): + return "off" + return "on" if _as_bool(resolved.get("tls")) else "plain" if short_key == "start_tls": # SSO relay uses STARTTLS on port 25. return self._provider_uses_sso_relay(variables) diff --git a/plugins/lookup/engine.py b/plugins/lookup/engine.py index 40fb2c0077..afae03a98a 100644 --- a/plugins/lookup/engine.py +++ b/plugins/lookup/engine.py @@ -21,6 +21,7 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.manager.credential_key import OVERRIDE_SECTION from utils.roles.applications.config import get from utils.roles.applications.services.engines import ( ENGINES, @@ -101,7 +102,7 @@ class LookupModule(LookupBase): or get( applications, consumer_id, - f"credentials.{engine}_password", + f"{OVERRIDE_SECTION}.{engine}_password", strict=False, default="", ) @@ -119,7 +120,7 @@ class LookupModule(LookupBase): get( applications, svc_id, - "credentials.REDIS_PASSWORD", + f"{OVERRIDE_SECTION}.REDIS_PASSWORD", strict=False, default="", skip_missing_app=True, diff --git a/plugins/lookup/fediwall_active.py b/plugins/lookup/fediwall_active.py index 0e7ce3e668..6e8b222ac8 100644 --- a/plugins/lookup/fediwall_active.py +++ b/plugins/lookup/fediwall_active.py @@ -109,21 +109,19 @@ class LookupModule(LookupBase): if want == "siblings": return [select_active(siblings, group_names)] - if want == "domains": - domain_lookup = lookup_loader.get( - "domain", loader=self._loader, templar=self._templar - ) - - def _resolve_domain(sibling: str) -> str: - return str(domain_lookup.run([sibling], variables=variables)[0]).strip() - - return [resolve_for_want(siblings, group_names, want, _resolve_domain)] - - # want == "url_bases" tls_lookup = lookup_loader.get( "tls", loader=self._loader, templar=self._templar ) + if want == "domains": + + def _resolve_domain(sibling: str) -> str: + return str( + tls_lookup.run([sibling, "domain"], variables=variables)[0] + ).strip() + + return [resolve_for_want(siblings, group_names, want, _resolve_domain)] + def _resolve_url_base(sibling: str) -> str: return str( tls_lookup.run([sibling, "url.base"], variables=variables)[0] diff --git a/plugins/lookup/group_roles.py b/plugins/lookup/group_roles.py new file mode 100644 index 0000000000..65df86a0bf --- /dev/null +++ b/plugins/lookup/group_roles.py @@ -0,0 +1,43 @@ +"""Lookup `group_roles`: the roles of a role group in run_after order. + +Returns one ``{'role': …, 'app': …}`` mapping per role, so a stage can loop +over the group instead of including a generated task file per group: + + loop: "{{ lookup('group_roles', 'web-app') }}" + +`role` is the directory under ``roles/``, `app` the role's application_id -- +the value the deployment whitelist and `application_allowed` speak in. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils.roles.order import ordered_roles + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[dict[str, str]]]: + if not terms or len(terms) != 1: + raise AnsibleError( + "group_roles lookup requires exactly one term: the group" + ) + + group = str(terms[0]).strip() + if not group: + raise AnsibleError("group_roles lookup: the group must not be empty") + + roles_dir = str(kwargs.get("roles_dir") or Path.cwd() / "roles") + try: + return [[dict(entry) for entry in ordered_roles(roles_dir, group)]] + except Exception as exc: + raise AnsibleError(f"group_roles: {exc}") from exc diff --git a/plugins/lookup/local_mtime_qs.py b/plugins/lookup/local_mtime_qs.py index 0b3a5aabe5..f7cbc3ff51 100644 --- a/plugins/lookup/local_mtime_qs.py +++ b/plugins/lookup/local_mtime_qs.py @@ -37,7 +37,6 @@ class LookupModule(LookupBase): for term in terms: path = str(Path(str(Path(str(term)).expanduser())).resolve()) - # Fail fast if path is missing or not a regular file if not Path(path).exists(): raise AnsibleError(f"local_mtime_qs: file does not exist: {path}") if not Path(path).is_file(): @@ -50,7 +49,7 @@ class LookupModule(LookupBase): if mode == "qs": results.append(f"?{param}={mtime}") - else: # mode == 'epoch' + else: results.append(str(mtime)) return results diff --git a/plugins/lookup/minio.py b/plugins/lookup/minio.py index ec1c905c17..509ba6ded0 100644 --- a/plugins/lookup/minio.py +++ b/plugins/lookup/minio.py @@ -6,6 +6,7 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.manager.credential_key import OVERRIDE_SECTION from utils.roles.applications.config import get from utils.roles.entity.name import get_entity_name @@ -143,7 +144,7 @@ class LookupModule(LookupBase): secret_key = get( applications, consumer_id, - "credentials.objstore_secret_key", + f"{OVERRIDE_SECTION}.objstore_secret_key", strict=False, default="", ) diff --git a/plugins/lookup/nginx.py b/plugins/lookup/nginx.py index 97ebde9a66..c833e1348d 100644 --- a/plugins/lookup/nginx.py +++ b/plugins/lookup/nginx.py @@ -124,7 +124,6 @@ class LookupModule(LookupBase): data_cdn_dir = _ensure_trailing_slash(_join(www_dir, "public_cdn")) data_global_dir = _ensure_trailing_slash(_join(www_dir, "global")) - # Container-internal nginx cache paths; not user-controllable. cache_general_dir = "/tmp/cache_nginx_general/" # noqa: S108 cache_image_dir = "/tmp/cache_nginx_image/" # noqa: S108 diff --git a/plugins/lookup/objstore.py b/plugins/lookup/objstore.py index 5b9f2b4d44..22254fd1a6 100644 --- a/plugins/lookup/objstore.py +++ b/plugins/lookup/objstore.py @@ -6,6 +6,7 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.manager.credential_key import OVERRIDE_SECTION from utils.roles.applications.config import get from utils.roles.entity.name import get_entity_name from utils.tls_common import resolve_enabled @@ -162,7 +163,7 @@ class LookupModule(LookupBase): secret_key = get( applications, consumer_id, - "credentials.objstore_secret_key", + f"{OVERRIDE_SECTION}.objstore_secret_key", strict=False, default="", ) diff --git a/plugins/lookup/prometheus_integration_active.py b/plugins/lookup/prometheus_integration_active.py index 2788edcb55..88538c3905 100644 --- a/plugins/lookup/prometheus_integration_active.py +++ b/plugins/lookup/prometheus_integration_active.py @@ -39,7 +39,6 @@ class LookupModule(LookupBase): templar=getattr(self, "_templar", None), ).run([], variables=vars_)[0] - # application_id may be passed explicitly (term 0) or read from available_variables. if terms and isinstance(terms[0], str): application_id: str = terms[0] else: @@ -54,8 +53,6 @@ class LookupModule(LookupBase): return [True] try: - # Per services live at applications..services - # (no `compose.services` wrapper). enabled = bool( applications.get(application_id, {}) .get("services", {}) diff --git a/plugins/lookup/redirect_uris.py b/plugins/lookup/redirect_uris.py new file mode 100644 index 0000000000..17553b5ed2 --- /dev/null +++ b/plugins/lookup/redirect_uris.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.get_url import get_url +from utils.roles.applications.config import ( + AppConfigKeyError, + ConfigEntryNotSetError, + get, +) +from utils.tls_common import resolve_enabled + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + +DEFAULT_FEATURES = ("services.sso.enabled",) +DEFAULT_WILDCARD = "/*" + + +def _stable_dedup(items: Sequence[str]) -> list[str]: + seen = set() + out: list[str] = [] + for x in items: + if x not in seen: + seen.add(x) + out.append(x) + return out + + +def _iter_domains(value: Any) -> Iterable[str]: + """Yield domains from str | list/tuple[str] | dict[*, str|list|tuple].""" + if value is None: + return + if isinstance(value, str): + yield value + elif isinstance(value, dict): + for val in value.values(): + yield from _iter_domains(val) + elif isinstance(value, (list, tuple)): + for val in value: + yield from _iter_domains(val) + else: + raise AnsibleError( + "redirect_uris: domain value must be str, list/tuple[str], or dict mapping to those" + ) + + +def build_redirect_uris( + domains: dict, + applications: dict, + tls_enabled: bool, + *, + wildcard: str = DEFAULT_WILDCARD, + features: Iterable[str] = DEFAULT_FEATURES, + dedup: bool = True, +) -> list[str]: + """Registered redirect URIs for every SSO consumer, one per domain. + + Args: + domains: app_id -> domain, list of domains, or nested mapping of those. + applications: merged applications view, used for feature gating and for + each consumer's ``server.tls.enabled`` override. + tls_enabled: global TLS default, overridden per consumer by + ``resolve_enabled``; an .onion domain always resolves to plaintext. + wildcard: suffix appended to every URI. + features: config paths ORed together to decide whether an app gets a URI. + dedup: drop repeated URIs, preserving first-seen order. + """ + if not isinstance(domains, dict): + raise AnsibleError( + "redirect_uris: 'domains' must be a dict mapping app_id -> domain or list of domains" + ) + + uris: list[str] = [] + for app_id, domain_value in domains.items(): + try: + has_feature = any( + bool(get(applications, app_id, f, False)) for f in features + ) + except (AppConfigKeyError, ConfigEntryNotSetError): + has_feature = False + if not has_feature: + continue + + for domain in _iter_domains(domain_value): + proto = ( + "https" + if resolve_enabled( + applications.get(app_id) or {}, tls_enabled, primary_domain=domain + ) + else "http" + ) + try: + url = get_url({app_id: domain}, app_id, proto) + except Exception as exc: + raise AnsibleError( + f"redirect_uris: get_url failed for app '{app_id}' " + f"with domain '{domain}': {exc}" + ) from exc + uris.append(f"{url}{wildcard}") + + return _stable_dedup(uris) if dedup else uris + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('redirect_uris') }} + {{ lookup('redirect_uris', wildcard='/cb') }} + + Returns the redirect URIs Keycloak must whitelist: one per domain of every + application whose config enables SSO. Each URI's scheme is resolved for the + CONSUMER -- its own ``server.tls.enabled`` over the global ``TLS_ENABLED``, + and always plaintext for an .onion -- never from Keycloak's own TLS state. + + - parameters: + wildcard: suffix appended to every URI (default '/*') + features: config paths ORed to gate an application (default services.sso.enabled) + dedup: drop repeated URIs (default true) + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + if terms: + raise AnsibleError("lookup('redirect_uris') expects no terms.") + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + if "TLS_ENABLED" not in variables: + raise AnsibleError("redirect_uris: TLS_ENABLED is not defined.") + + loader = getattr(self, "_loader", None) + templar = getattr(self, "_templar", None) + domains = lookup_loader.get("domains", loader=loader, templar=templar).run( + [], variables=variables + )[0] + applications = lookup_loader.get( + "applications", loader=loader, templar=templar + ).run([], variables=variables)[0] + + features = kwargs.get("features") or DEFAULT_FEATURES + return [ + build_redirect_uris( + domains, + applications, + bool(variables["TLS_ENABLED"]), + wildcard=kwargs.get("wildcard", DEFAULT_WILDCARD), + features=features, + dedup=bool(kwargs.get("dedup", True)), + ) + ] diff --git a/plugins/lookup/role_templates_expanded.py b/plugins/lookup/role_templates_expanded.py new file mode 100644 index 0000000000..609c5d0e0f --- /dev/null +++ b/plugins/lookup/role_templates_expanded.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import glob +from pathlib import Path +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils import PROJECT_ROOT + +DEFAULTS: dict[str, Any] = { + "owner": "root", + "group": "root", + "mode": "0640", + "condition": True, + "notify": ["compose-up"], +} + + +def _glob_files(pattern: str) -> list[str]: + """Paths matching *pattern*, files only, sorted. + + Args: + pattern: an absolute glob pattern. + + Returns: + Sorted absolute paths; directories are dropped, mirroring Ansible's + ``fileglob``. + """ + return sorted(path for path in glob.glob(pattern) if Path(path).is_file()) + + +def _strip_j2(name: str) -> str: + """*name* without a trailing ``.j2``.""" + return name.removesuffix(".j2") + + +def _expand_glob_entry(entry: dict, application_id: str) -> list[dict]: + """One ``src_glob`` entry turned into one dict per matched template. + + Args: + entry: the role_templates entry carrying ``src_glob`` and ``dest_dir``. + application_id: role whose ``templates/`` directory is globbed. + + Returns: + One rendered-template spec per match, sorted by source path. + + Raises: + AnsibleError: ``dest_dir`` is missing or not a string. + """ + dest_dir = entry.get("dest_dir") + if not isinstance(dest_dir, str) or not dest_dir: + raise AnsibleError( + "role_templates_expanded: an entry with 'src_glob' requires a " + f"non-empty string 'dest_dir', got {dest_dir!r}" + ) + + templates_dir = PROJECT_ROOT / "roles" / application_id / "templates" + out: list[dict] = [] + for path in _glob_files(str(templates_dir / str(entry["src_glob"]))): + item = {key: entry.get(key, value) for key, value in DEFAULTS.items()} + item["src"] = path + item["dest"] = dest_dir.rstrip("/") + "/" + _strip_j2(Path(path).name) + out.append(item) + return out + + +class LookupModule(LookupBase): + def run(self, terms, variables: dict | None = None, **kwargs): + """Expand ``role_templates`` into one spec per template to render. + + Args: + terms: ``[application_id, role_templates]``. + + Returns: + A single-element list holding the expanded spec list, so the caller + receives the list itself rather than its first element. + + Raises: + AnsibleError: wrong term count, empty application_id, or an entry + that is not a dict. + """ + if not terms or len(terms) != 2: + raise AnsibleError( + "role_templates_expanded: exactly two terms required " + "(application_id, role_templates)" + ) + + application_id = str(terms[0] or "").strip() + if not application_id: + raise AnsibleError("role_templates_expanded: application_id is empty") + + entries = terms[1] + if entries is None: + return [[]] + if not isinstance(entries, list): + raise AnsibleError( + f"role_templates_expanded: role_templates must be a list, got {type(entries)}" + ) + + out: list[dict] = [] + for entry in entries: + if not isinstance(entry, dict): + raise AnsibleError( + f"role_templates_expanded: every entry must be a dict, got {type(entry)}" + ) + if "src_glob" in entry: + out.extend(_expand_glob_entry(entry, application_id)) + continue + item = dict(entry) + for key, value in DEFAULTS.items(): + item.setdefault(key, value) + out.append(item) + return [out] diff --git a/plugins/lookup/smtp_host.py b/plugins/lookup/smtp_host.py index 62d7518e09..b3ed83d117 100644 --- a/plugins/lookup/smtp_host.py +++ b/plugins/lookup/smtp_host.py @@ -7,24 +7,36 @@ from ansible.module_utils.parsing.convert_bool import boolean as _to_bool from ansible.plugins.lookup import LookupBase LOOPBACK = "127.0.0.1" +CONTAINER_HOST_ALIAS = "host.docker.internal" NODE_GROUP = "svc-swarm-node" MANAGER_GROUP = "svc-swarm-manager" -def resolve_smtp_host(variables: dict[str, Any], email: dict[str, Any]) -> Any: +def resolve_smtp_host( + variables: dict[str, Any], email: dict[str, Any], *, in_container: bool = False +) -> Any: """Return the SMTP endpoint msmtp relays through. Args: variables: the play's variable namespace. email: the resolved ``lookup('email')`` mapping. + in_container: the rendered config is mounted INTO a container rather + than read by the host's own msmtp. Returns: - The configured relay host, the loopback address, or a swarm manager. + The configured relay host, the loopback address, the container's alias + for its host, or a swarm manager. Outside the containerised test rig the configured relay is used unchanged. Inside it that relay domain has neither DNS nor a route: a host carrying the stack itself reaches mail on loopback, while a bare infra node has nothing listening there and has to enter through the manager's routing mesh. + + ``in_container`` exists because one template serves two consumers. The host's + /root/.msmtprc is read by the host and loopback is right for it; the copy + mounted at /etc/msmtprc is read inside a container, where 127.0.0.1 is that + container's own loopback and nothing listens on it. Such a service must also + emit ``lookup('container_extra_hosts')`` so the alias resolves. """ relay = email.get("host") in_rig = _to_bool(email.get("external"), strict=False) and _to_bool( @@ -33,6 +45,9 @@ def resolve_smtp_host(variables: dict[str, Any], email: dict[str, Any]) -> Any: if not in_rig: return relay + if in_container: + return CONTAINER_HOST_ALIAS + if variables.get("DEPLOYMENT_MODE") == "compose" or NODE_GROUP in ( variables.get("group_names") or [] ): @@ -46,8 +61,11 @@ class LookupModule(LookupBase): """ Usage: {{ lookup('smtp_host', email) }} + {{ lookup('smtp_host', email, in_container=true) }} SMTP endpoint for the msmtp relay config. Takes the resolved email mapping. + Pass in_container=true when the rendered file is mounted into a container + instead of being read by the host's own msmtp. """ def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): @@ -59,4 +77,5 @@ class LookupModule(LookupBase): if not isinstance(email, dict): raise AnsibleError("smtp_host: the term must be the email mapping.") variables = variables or getattr(self._templar, "available_variables", {}) or {} - return [resolve_smtp_host(variables, email)] + in_container = _to_bool(kwargs.get("in_container", False), strict=False) + return [resolve_smtp_host(variables, email, in_container=in_container)] diff --git a/plugins/lookup/sso.py b/plugins/lookup/sso.py index 23274c9091..98455fb33d 100644 --- a/plugins/lookup/sso.py +++ b/plugins/lookup/sso.py @@ -11,7 +11,7 @@ API (STRICT): Wraps ``utils.roles.applications.services.sso.get_sso_config`` so templates and tasks share one source of truth with Python callers -(notably ``plugins/filter/compose_volumes.py``). +(notably ``plugins/lookup/compose_volumes.py``). """ from __future__ import annotations diff --git a/plugins/lookup/sso_oidc_plugin.py b/plugins/lookup/sso_oidc_plugin.py index 85174b46df..3e895dffc2 100644 --- a/plugins/lookup/sso_oidc_plugin.py +++ b/plugins/lookup/sso_oidc_plugin.py @@ -40,11 +40,6 @@ class LookupModule(LookupBase): templar = getattr(self, "_templar", None) variables = variables or getattr(self._templar, "available_variables", {}) or {} - # Use the same merged+rendered applications payload that lookup('config') - # consumes. The raw `variables["applications"]` that Ansible hands the - # lookup is the pre-merge override slice, so nested defaults like - # services.ldap.enabled are not yet visible there and the flavor - # would silently fall back to 'sociallogin'. applications = lookup_loader.get( "applications", loader=self._loader, templar=templar ).run([], variables=variables)[0] diff --git a/plugins/lookup/sso_proxy_consumers.py b/plugins/lookup/sso_proxy_consumers.py index fa14929af6..1773d3a120 100644 --- a/plugins/lookup/sso_proxy_consumers.py +++ b/plugins/lookup/sso_proxy_consumers.py @@ -10,7 +10,7 @@ Usage: No positional terms are accepted. Predicate logic delegates to ``utils.roles.applications.services.sso.get_sso_config`` so callers share one source of truth with ``lookup('sso', ..., 'is_proxy_gated')`` -and ``plugins/filter/compose_volumes.py``. +and ``plugins/lookup/compose_volumes.py``. """ from __future__ import annotations diff --git a/plugins/lookup/stage_groups.py b/plugins/lookup/stage_groups.py index a4d7ebca63..1a62c06531 100644 --- a/plugins/lookup/stage_groups.py +++ b/plugins/lookup/stage_groups.py @@ -1,5 +1,5 @@ -"""Lookup `stage_groups`: the ordered role-group names -(``tasks/groups/-roles.yml``) that belong to a deploy stage, in intra-stage +"""Lookup `stage_groups`: the ordered role-group names that belong to a +deploy stage, in intra-stage call order. The stage plays loop over it so group membership follows ``meta/categories.yml`` instead of a hardcoded list: diff --git a/plugins/lookup/tls.py b/plugins/lookup/tls.py index 452f7cf78f..03de01439a 100644 --- a/plugins/lookup/tls.py +++ b/plugins/lookup/tls.py @@ -13,8 +13,10 @@ from ansible.plugins.lookup import LookupBase from utils.tls_common import ( AVAILABLE_FLAVORS, + align_domain_to_consumer, as_str, collect_domains_for_app, + norm_domain, require, resolve_enabled, resolve_mode, @@ -28,8 +30,6 @@ class LookupModule(LookupBase): def run(self, terms, variables: dict | None = None, **kwargs): variables = variables or {} - # New API: want-path is the 2nd positional term. - # Legacy 'want=' kwarg is ignored (no error) to keep tasks noise-free. if not terms or len(terms) not in (1, 2): raise AnsibleError( "tls: one or two terms required: (domain|application_id[, want_path])" @@ -66,6 +66,17 @@ class LookupModule(LookupBase): err_prefix="tls", ) + if forced_mode == "app" or (forced_mode == "auto" and "." not in term): + primary_domain = norm_domain( + align_domain_to_consumer( + domains, + app_id, + primary_domain, + variables=variables, + templar=templar, + ) + ) + all_domains = collect_domains_for_app(domains, app_id, err_prefix="tls") all_domains = ( uniq_preserve([primary_domain, *all_domains]) @@ -77,7 +88,9 @@ class LookupModule(LookupBase): if not isinstance(app, dict): app = {} - enabled = resolve_enabled(app, bool(enabled_default)) + enabled = resolve_enabled( + app, bool(enabled_default), primary_domain=primary_domain + ) mode = resolve_mode(app, enabled, mode_default, err_prefix="tls") if mode not in {"off"} | AVAILABLE_FLAVORS: diff --git a/plugins/lookup/tor_ports.py b/plugins/lookup/tor_ports.py new file mode 100644 index 0000000000..ec24f33741 --- /dev/null +++ b/plugins/lookup/tor_ports.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from pathlib import Path + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.cache.base import _resolve_roles_dir +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +_UDP_ONLY_CATEGORIES = frozenset({"relay", "media"}) + + +def _as_bool(value: object) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, str): + return value.strip().lower() in ("true", "1", "yes", "on") + return bool(value) + + +def _collect_local_tcp_ports(port_categories: Any, into: set[int]) -> None: + """Add single-int TCP ports of the loopback-published ``ports.local`` group + only. An exposed service publishes just its local plaintext port to + 127.0.0.1, so the onion HiddenServicePort must target that; forwarding a + ``public`` TLS port (e.g. ldaps 636) would be a dead loopback target (nothing + listens there in the exposed variant) and plaintext-into-TLS.""" + if not isinstance(port_categories, dict): + return + local = port_categories.get("local") + if not isinstance(local, dict): + return + for category, value in local.items(): + if category in _UDP_ONLY_CATEGORIES: + continue + if isinstance(value, int): + into.add(value) + + +def collect_public_ports( + deployed_roles: list[str], + roles_dir: Path, +) -> list[int]: + """Single-int TCP ``ports.public`` entries of the deployed roles, sorted.""" + ports: set[int] = set() + for role in deployed_roles: + services_yml = roles_dir / role / ROLE_FILE_META_SERVICES + if not services_yml.is_file(): + continue + data = load_yaml_any(str(services_yml), default_if_missing={}) + if not isinstance(data, dict): + continue + tor = data.get("tor") + if not (isinstance(tor, dict) and _as_bool(tor.get("enabled"))): + continue + for entity in data.values(): + if not isinstance(entity, dict): + continue + public = (entity.get("ports") or {}).get("public") + if not isinstance(public, dict): + continue + for category, value in public.items(): + if category in _UDP_ONLY_CATEGORIES: + continue + if isinstance(value, int): + ports.add(value) + return sorted(ports) + + +def collect_exposed_ports( + applications: dict[str, Any], + deployed_roles: list[str], +) -> list[int]: + """Single-int TCP ports of every deployed service flagged ``exposed: true`` + in the variant-merged ``applications`` view, sorted. + + ``exposed`` is an explicit per-service opt-in (default false) that makes the + service reachable over the node onion: its port gets a dedicated + ``HiddenServicePort``. Because ``applications`` is the variant-merged config + (base ``meta/services.yml`` deep-merged with the round's ``meta/variants.yml`` + override), a service is forwarded only in the variant/config where it sets + ``exposed: true`` — which is exactly what lets the two DB variants be tested + over Tor (v0 exposed -> reachable, v1 not -> refused). + """ + ports: set[int] = set() + deployed = set(deployed_roles) + if not isinstance(applications, dict): + return [] + for app_id, cfg in applications.items(): + if app_id not in deployed: + continue + services = (cfg or {}).get("services") if isinstance(cfg, dict) else None + if not isinstance(services, dict): + continue + for entity in services.values(): + if not isinstance(entity, dict) or not _as_bool(entity.get("exposed")): + continue + _collect_local_tcp_ports(entity.get("ports"), ports) + return sorted(ports) + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('tor_ports') }} + + Returns the HiddenServicePort mappings for the roles in the current deploy + (``group_names``): a list of ``{'onion_port': , 'target': + '127.0.0.1:'}`` dicts, sorted by port. Two sources are unioned: + + * every ``ports.public`` TCP port of tor-enabled roles, and + * every port of a service that opts in with ``exposed: true`` (resolved + against the variant-merged applications view, so per-variant). + + Public/exposed ports bind the host interface, so the loopback target reaches + them from svc-net-tor's host-network container. Consumed by + ``TOR_ONION_EXTRA_PORTS`` (group_vars/all/19_tor.yml) and rendered as + ``HiddenServicePort`` lines in svc-net-tor's torrc. + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if terms: + raise AnsibleError("lookup('tor_ports') expects no terms.") + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + group_names = variables.get("group_names") or [] + if not isinstance(group_names, list): + group_names = [] + deployed = [str(g) for g in group_names] + + roles_dir = _resolve_roles_dir(roles_dir=kwargs.get("roles_dir")) + ports = set(collect_public_ports(deployed, roles_dir)) + + try: + applications = lookup_loader.get( + "applications", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + except Exception: # noqa: BLE001 no merged view -> exposed ports simply unavailable + applications = {} + ports.update(collect_exposed_ports(applications, deployed)) + + return [ + [ + {"onion_port": port, "target": f"127.0.0.1:{port}"} + for port in sorted(ports) + ] + ] diff --git a/plugins/lookup/tor_reachable.py b/plugins/lookup/tor_reachable.py new file mode 100644 index 0000000000..870083d3cb --- /dev/null +++ b/plugins/lookup/tor_reachable.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.lookup.tor_ports import _as_bool, collect_exposed_ports + + +def is_reachable(applications: dict[str, Any], application_id: str) -> bool: + """True when *application_id* is reachable over the node onion, i.e. when + svc-net-tor is deployed for it (``services.tor.enabled``) AND at least one + of its services opts in with ``exposed: true``, which is what earns a + ``HiddenServicePort`` (``collect_exposed_ports``). + + Both halves are required: ``tor.enabled`` is the dependency edge, not the + port forward, so a client picking the Tor transport from that flag alone + dials a port with no HiddenServicePort and no host publish. + """ + config = (applications or {}).get(application_id) or {} + services = config.get("services") if isinstance(config, dict) else None + if not isinstance(services, dict): + return False + tor = services.get("tor") + if not (isinstance(tor, dict) and _as_bool(tor.get("enabled"))): + return False + return bool(collect_exposed_ports(applications, [application_id])) + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('tor_reachable', application_id) }} + + Returns whether *application_id* is reachable over the node onion in the + current (variant-merged) applications view -- see ``is_reachable``. + + - parameters: + 1) application_id + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[bool]: + if not terms or len(terms) != 1: + raise AnsibleError( + "lookup('tor_reachable', application_id) expects exactly 1 term." + ) + application_id = str(terms[0]).strip() + if not application_id: + raise AnsibleError( + "lookup('tor_reachable', application_id): application_id is empty." + ) + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + applications = lookup_loader.get( + "applications", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + return [is_reachable(applications, application_id)] diff --git a/plugins/lookup/tor_socks.py b/plugins/lookup/tor_socks.py new file mode 100644 index 0000000000..e39ccd5d2e --- /dev/null +++ b/plugins/lookup/tor_socks.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +_DEFAULT_HOST = "127.0.0.1" + + +def resolve_socks_endpoint(applications: dict[str, Any], host: str) -> str: + """Return ``:`` for the node Tor SOCKS proxy. + + The port is the single source of truth + ``svc-net-tor services.tor.ports.local.socks``; only the host varies by + caller context (loopback for host-network consumers, ``host.docker.internal`` + for a bridged sibling container, ``0.0.0.0`` for the daemon bind). + """ + tor = ((applications.get("svc-net-tor") or {}).get("services") or {}).get( + "tor" + ) or {} + port = ((tor.get("ports") or {}).get("local") or {}).get("socks") + if port is None: + raise AnsibleError( + "tor_socks: svc-net-tor services.tor.ports.local.socks is not set." + ) + return f"{host}:{port}" + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('tor_socks') }} -> 127.0.0.1: + {{ lookup('tor_socks', 'host.docker.internal') }} -> host.docker.internal: + {{ lookup('tor_socks', '0.0.0.0') }} -> 0.0.0.0: + + Single spot for the node Tor SOCKS endpoint so ``127.0.0.1:`` and its + siblings are never hand-composed: the port comes from + ``svc-net-tor services.tor.ports.local.socks`` and callers only pass the + host (default 127.0.0.1). + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + terms = terms or [] + if len(terms) > 1: + raise AnsibleError("lookup('tor_socks'[, host]) takes at most one term.") + host = str(terms[0]) if terms else _DEFAULT_HOST + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + applications = lookup_loader.get( + "applications", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + return [resolve_socks_endpoint(applications, host)] diff --git a/plugins/lookup/tor_socks_proxy.py b/plugins/lookup/tor_socks_proxy.py new file mode 100644 index 0000000000..41465df6e5 --- /dev/null +++ b/plugins/lookup/tor_socks_proxy.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import contextlib +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.lookup.tor_socks import resolve_socks_endpoint + +_SWARM_HOST = "tor" +_COMPOSE_HOST = "host.docker.internal" + + +def resolve_proxy_url(applications: dict[str, Any], deployment_mode: str) -> str: + """Return the ``socks5h://`` URL a sibling container uses to reach Tor: + the ``tor`` overlay alias in swarm, the host gateway in compose. + """ + host = _SWARM_HOST if str(deployment_mode).strip() == "swarm" else _COMPOSE_HOST + return f"socks5h://{resolve_socks_endpoint(applications, host)}" + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('tor_socks_proxy') }} -> socks5h://tor: (swarm) + -> socks5h://host.docker.internal: (compose) + + Single spot for the outbound Tor SOCKS proxy URL of a containerised client, + so the swarm/compose split is not restated per consuming role. + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + if terms: + raise AnsibleError("lookup('tor_socks_proxy') expects no terms.") + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + applications = lookup_loader.get( + "applications", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + raw_mode = variables.get("DEPLOYMENT_MODE", "compose") + templar = getattr(self, "_templar", None) + if templar is not None: + with contextlib.suppress(Exception): + raw_mode = templar.template(raw_mode) + + return [resolve_proxy_url(applications, str(raw_mode).strip())] diff --git a/plugins/lookup/unit_name.py b/plugins/lookup/unit_name.py index 6ed2bcaee9..1aecd539c6 100644 --- a/plugins/lookup/unit_name.py +++ b/plugins/lookup/unit_name.py @@ -32,7 +32,6 @@ def _render_if_template(templar, value, var_name: str): try: rendered = templar.template(value) except TypeError: - # Unit tests can inject a minimal templar without Ansible's full signature. rendered = templar.template(value) except Exception as exc: raise AnsibleError( @@ -47,21 +46,16 @@ def _render_if_template(templar, value, var_name: str): def _resolve_version(templar, variables): - # Try the canonical lookup call first. try: version = templar.template("{{ lookup('version') }}") except TypeError: - # Unit tests can inject a minimal templar without Ansible's full signature. version = templar.template("{{ lookup('version') }}") - # Some Ansible contexts keep nested lookups unresolved here. Fallback to direct plugin call. if _looks_like_template(version): try: try: - # Preferred when imported as Python package (tests, local scripts). from plugins.lookup.version import LookupModule as VersionLookupModule except ModuleNotFoundError: - # Fallback when loaded by Ansible plugin loader from lookup_plugins path. from version import LookupModule as VersionLookupModule version_lookup = VersionLookupModule() @@ -133,8 +127,6 @@ def _build_unit_name( sw = _lower_required(software_domain, "SOFTWARE_DOMAIN") sfx = _normalize_suffix(suffix) - # Keep template semantics compatible with your previous filter: - # If id ends with "@", drop it and return "..@" (e.g., "...@.service"). if sid.endswith("@"): base = sid[:-1] return f"{base}.{ver}.{sw}@{sfx}" @@ -152,7 +144,6 @@ class LookupModule(LookupBase): """ def run(self, terms, variables=None, **kwargs): - # Make variables accessible via templar self.set_options(var_options=variables, direct=kwargs) if not terms: @@ -160,7 +151,6 @@ class LookupModule(LookupBase): "unit_name lookup: at least one term (systemctl_id) is required." ) - # Read SOFTWARE_DOMAIN from current variable context available = getattr(self._templar, "available_variables", {}) or {} software_domain = available.get("SOFTWARE_DOMAIN") if not software_domain: @@ -171,8 +161,6 @@ class LookupModule(LookupBase): self._templar, software_domain, "SOFTWARE_DOMAIN" ) - # Resolve version via lookup('version'). Fall back to direct lookup plugin invocation - # if nested lookup templating remains unresolved in this context. version = _resolve_version(self._templar, variables) if not version or not str(version).strip(): raise AnsibleError( diff --git a/plugins/lookup/users_non_reserved.py b/plugins/lookup/users_non_reserved.py new file mode 100644 index 0000000000..4e3d83280e --- /dev/null +++ b/plugins/lookup/users_non_reserved.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.filter.reserved_users import non_reserved_users + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('users_non_reserved') }} + + Returns the users an identity directory provisions -- those carrying + ``identity`` in ``accounts`` -- as the same dict shape ``lookup('users')`` + yields. Every consumer that provisions or references directory users must + read this, so no two of them can disagree about who exists. + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[dict[str, Any]]: + if terms: + raise AnsibleError("lookup('users_non_reserved') expects no terms.") + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + users = lookup_loader.get( + "users", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, **kwargs)[0] + + return [non_reserved_users(users)] diff --git a/plugins/lookup/version.py b/plugins/lookup/version.py index 9ff9dc3baa..7beaedbcbd 100644 --- a/plugins/lookup/version.py +++ b/plugins/lookup/version.py @@ -20,7 +20,7 @@ from ansible.plugins.lookup import LookupBase from plugins.lookup import PROJECT_ROOT try: - import tomllib # Python 3.11+ + import tomllib except Exception: try: import tomli as tomllib @@ -42,7 +42,6 @@ def _get_nested(data: dict, path: list[str]): class LookupModule(LookupBase): def run(self, terms, variables=None, **kwargs): - # Intentionally ignore terms/kwargs — no parameters supported pyproject_path = str(PROJECT_ROOT / "pyproject.toml") diff --git a/plugins/lookup/volume.py b/plugins/lookup/volume.py index 62c8a135e6..155ca10339 100644 --- a/plugins/lookup/volume.py +++ b/plugins/lookup/volume.py @@ -16,6 +16,19 @@ Two call forms: - ``source`` for binds / configs / secrets, ``''`` if absent - ``nfs`` NFS opt-in (bool or dict), ``None`` if absent - ``mounts`` the raw mounts list, ``[]`` if absent + - ``targets`` ``{service: container path}`` built from ``mounts`` + - ``target`` the one container path this entry mounts at, present + only when every mount agrees. An entry that lands at + different paths per service omits the key rather than + picking one; read ``targets[service]`` there. + + ``target`` is what lets ``meta/volumes.yml`` stay the single source of a + container path: a role defines its constant from the registry + + PROMETHEUS_CONFIG_FILE: "{{ lookup('volume', application_id, 'config').target }}" + + rather than repeating the literal, which nothing keeps in step with the + mount it describes. ``lookup('volume', application_id)`` — return the WHOLE canonical registry as a dict keyed by semantic name. Useful for tasks that loop @@ -52,11 +65,6 @@ class LookupModule(LookupBase): canonical = get_canonical_volumes(application_id) if not canonical: - # The canonical-volumes registry fills lazily as a side effect of - # building the application defaults; force it on a miss so a lookup - # that runs before any consumer built this role (e.g. nfs_prep's - # pre-create loop) does not see an empty registry and silently skip - # the subdir. Guarded so the populated hot path skips the deepcopy. get_application_defaults() canonical = get_canonical_volumes(application_id) @@ -81,15 +89,38 @@ class LookupModule(LookupBase): ) docker_name = entry.get("name", "") - return [ - { - "name": entry.get("name") or name, - "semantic_name": name, - "docker_name": docker_name, - "path": entry.get("path", ""), - "type": entry.get("type", "volume"), - "source": entry.get("source", ""), - "nfs": entry.get("nfs", None), - "mounts": entry.get("mounts", []), - } - ] + mounts = entry.get("mounts", []) + resolved = { + "name": entry.get("name") or name, + "semantic_name": name, + "docker_name": docker_name, + "path": entry.get("path", ""), + "type": entry.get("type", "volume"), + "source": entry.get("source", ""), + "nfs": entry.get("nfs", None), + "mounts": mounts, + "targets": _targets(mounts), + } + distinct = {t for t in resolved["targets"].values() if t} + if len(distinct) == 1: + resolved["target"] = next(iter(distinct)) + return [resolved] + + +def _targets(mounts: Any) -> dict[str, str]: + """Map each mounting service to the container path it receives. + + Args: + mounts: the entry's raw ``mounts`` list. + """ + if not isinstance(mounts, list): + return {} + out: dict[str, str] = {} + for mount in mounts: + if not isinstance(mount, dict): + continue + service = str(mount.get("service", "") or "").strip() + target = str(mount.get("target", "") or "").strip() + if service and target: + out[service] = target + return out diff --git a/pyproject.toml b/pyproject.toml index 8e883bbfcc..f4e7bf2c2f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,16 +4,22 @@ build-backend = "setuptools.build_meta" [project] name = "infinito-nexus" -version = "12.0.0" +version = "13.0.0" description = "Infinito.Nexus" readme = "README.md" requires-python = ">=3.11" license = { file = "LICENSE.md" } dependencies = [ + # Pinned: utils/recovery reads the generation layout from baudolo's own + # BackupPaths, so the version here and in svc-bkp-volume-2-local must match. + "backup-docker-to-local==7.0.1", "bcrypt", "cryptography", "humanfriendly", + "PyMySQL", + "psycopg2-binary", + "ldap3", "PyYAML", "ruamel.yaml", ] @@ -27,7 +33,7 @@ deploy = [ "requests", ] dev = [ - "ruff==0.16.2", + "ruff==0.16.4", "import-linter", "pre-commit", "git-maintainer-tools", @@ -188,8 +194,8 @@ ignore = [ # ``patch.object(sut, "os")`` replacements). Converting these call # sites to ``pathlib.Path`` would require rewriting every coupled # test in lockstep — out of scope for the use-pathlib pass. -"roles/sys-ctl-rpr-container-hard/files/script.py" = ["PTH"] -"roles/sys-ctl-rpr-container-soft/files/script.py" = ["PTH"] +"roles/sys-ctl-rpr-container-hard/files/python/script.py" = ["PTH"] +"roles/sys-ctl-rpr-container-soft/files/python/script.py" = ["PTH"] # BLE001 (flake8-blind-except) ratchet. # Broad `except Exception:` is now selected project-wide so NEW code is @@ -224,7 +230,6 @@ ignore = [ "cli/meta/roles/services/called/__init__.py" = ["BLE001"] "library/docker_bridge_gateway.py" = ["BLE001"] "plugins/filter/active_docker.py" = ["BLE001"] -"plugins/filter/compose_volumes.py" = ["BLE001"] "plugins/filter/docker/service_enabled.py" = ["BLE001"] "plugins/filter/dotenv.py" = ["BLE001"] "plugins/filter/get/all/application_ids.py" = ["BLE001"] @@ -259,7 +264,7 @@ ignore = [ "cli/administration/deploy/development/deploy.py" = ["N806"] "cli/administration/deploy/development/init.py" = ["N806"] "cli/administration/deploy/development/inventory.py" = ["N806"] -"tests/unit/cli/administration/deploy/development/test_inventory.py" = ["N806"] +"tests/unit/python/cli/administration/deploy/development/test_inventory.py" = ["N806"] # Lazy-loaded class binding: ``ValueGenerator = _value_generator_cls()`` # rebinds the imported class inside the function. PEP 8 keeps the diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index e54f102b89..31ddb7279d 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -1,18 +1,35 @@ --- collections: - # kewlfft.aur + - name: ansible.posix + source: https://github.com/ansible-collections/ansible.posix.git + type: git + version: main + + - name: ansible.mysql + source: https://github.com/ansible-collections/ansible.mysql.git + type: git + version: main + - name: kewlfft.aur source: https://github.com/kewlfft/ansible-aur.git type: git version: master - # community.general - name: community.general source: https://github.com/ansible-collections/community.general.git type: git version: main - # hetzner.hcloud + - name: community.docker + source: https://github.com/ansible-collections/community.docker.git + type: git + version: main + + - name: community.library_inventory_filtering_v1 + source: https://github.com/ansible-collections/community.library_inventory_filtering.git + type: git + version: stable-1 + - name: hetzner.hcloud source: https://github.com/ansible-collections/hetzner.hcloud.git type: git diff --git a/roles/desk-bluray-player/README.md b/roles/desk-bluray-player/README.md index 7d6171db28..fcbc1ab2ad 100644 --- a/roles/desk-bluray-player/README.md +++ b/roles/desk-bluray-player/README.md @@ -28,7 +28,7 @@ flowchart LR dep_dev_java -- "1:1" --> svc_bluray_player ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-chromium/README.md b/roles/desk-chromium/README.md index 231c4eef80..d4f0e1bb20 100644 --- a/roles/desk-chromium/README.md +++ b/roles/desk-chromium/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-copyq/README.md b/roles/desk-copyq/README.md index df1dd061e6..a3308c7283 100644 --- a/roles/desk-copyq/README.md +++ b/roles/desk-copyq/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-docker/README.md b/roles/desk-docker/README.md index aef25a2c82..c86c0bdccb 100644 --- a/roles/desk-docker/README.md +++ b/roles/desk-docker/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-dotlinker/README.md b/roles/desk-dotlinker/README.md index b20c395754..31d57b9345 100644 --- a/roles/desk-dotlinker/README.md +++ b/roles/desk-dotlinker/README.md @@ -23,7 +23,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-dotlinker/tasks/main.yml b/roles/desk-dotlinker/tasks/main.yml index d754757f7b..1b96503aff 100644 --- a/roles/desk-dotlinker/tasks/main.yml +++ b/roles/desk-dotlinker/tasks/main.yml @@ -3,5 +3,4 @@ - include_tasks: 01_install.yml when: run_once_desk_dotlinker is not defined -# Apply mappings EVERY time the role is included (with whatever dotlinker_mappings the caller passes) - include_tasks: 02_apply.yml diff --git a/roles/desk-firefox/README.md b/roles/desk-firefox/README.md index 6709f49281..dc9e60b2fc 100644 --- a/roles/desk-firefox/README.md +++ b/roles/desk-firefox/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-firefox/meta/packages.yml b/roles/desk-firefox/meta/packages.yml index a5b44dcb11..7066cda34f 100644 --- a/roles/desk-firefox/meta/packages.yml +++ b/roles/desk-firefox/meta/packages.yml @@ -3,6 +3,8 @@ firefox: Archlinux: - firefox Debian: - - firefox + - firefox-esr RedHat: - firefox + ubuntu: + - firefox diff --git a/roles/desk-git/README.md b/roles/desk-git/README.md index 6a8de41fe5..a5b4697c8f 100644 --- a/roles/desk-git/README.md +++ b/roles/desk-git/README.md @@ -23,7 +23,7 @@ flowchart LR svc_git -- "1:1" --> dpt_desk_ssh ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-gnome-caffeine/README.md b/roles/desk-gnome-caffeine/README.md index e1cec2cb19..e65bab1b98 100644 --- a/roles/desk-gnome-caffeine/README.md +++ b/roles/desk-gnome-caffeine/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-gnome-extensions/README.md b/roles/desk-gnome-extensions/README.md index 855f160b92..23ee3350ce 100644 --- a/roles/desk-gnome-extensions/README.md +++ b/roles/desk-gnome-extensions/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-gnome-extensions/meta/services.yml b/roles/desk-gnome-extensions/meta/services.yml index 43996ead4b..d4866b393e 100644 --- a/roles/desk-gnome-extensions/meta/services.yml +++ b/roles/desk-gnome-extensions/meta/services.yml @@ -3,6 +3,8 @@ gnome-extensions: modes: host: enabled: true + repository: https://github.com/kevinveenbirkenbach/cli-gnome-extension-manager.git + ref: v1.0.0 plugins: [] lifecycle: pre-alpha min_storage: "50MB" diff --git a/roles/desk-gnome-extensions/tasks/00_core.yml b/roles/desk-gnome-extensions/tasks/00_core.yml index d6e7c78c29..d3ac5cbedc 100644 --- a/roles/desk-gnome-extensions/tasks/00_core.yml +++ b/roles/desk-gnome-extensions/tasks/00_core.yml @@ -3,11 +3,13 @@ ansible.builtin.shell: gsettings set org.gnome.shell disable-user-extensions false become: false -- name: "📦 pkgmgr install" +- name: 📦 Install cli-gnome-extension-manager system-wide via pip include_role: - name: pkgmgr-install + name: sys-pip-install vars: - package_name: cli-gnome-extension-manager + # TODO: switch to the PyPI name 'cli-gnome-extension-manager' once it is published + package_name: "git+{{ DESK_GNOME_EXTENSIONS_MANAGER_REPO }}@{{ DESK_GNOME_EXTENSIONS_MANAGER_REF }}" + global_install: true - name: ▶️ Execute CLI GNOME Extension manager script ansible.builtin.shell: cli-gnome-extension-manager "{{ item[0] }}" "{{ item[1] }}" "{{ item[2] }}" diff --git a/roles/desk-gnome-extensions/vars/main.yml b/roles/desk-gnome-extensions/vars/main.yml index dc0ac136c0..534de78ceb 100644 --- a/roles/desk-gnome-extensions/vars/main.yml +++ b/roles/desk-gnome-extensions/vars/main.yml @@ -1,2 +1,4 @@ --- application_id: desk-gnome-extensions +DESK_GNOME_EXTENSIONS_MANAGER_REPO: "{{ lookup('config', application_id, 'services.gnome-extensions.repository') }}" +DESK_GNOME_EXTENSIONS_MANAGER_REF: "{{ lookup('config', application_id, 'services.gnome-extensions.ref') }}" diff --git a/roles/desk-gnome-terminal/README.md b/roles/desk-gnome-terminal/README.md index 4dec60f0c2..794f63060b 100644 --- a/roles/desk-gnome-terminal/README.md +++ b/roles/desk-gnome-terminal/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-gnome/README.md b/roles/desk-gnome/README.md index aebd2a2446..717e29573e 100644 --- a/roles/desk-gnome/README.md +++ b/roles/desk-gnome/README.md @@ -23,7 +23,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-gnome/meta/services.yml b/roles/desk-gnome/meta/services.yml index 14b61a238b..fc62bc50e9 100644 --- a/roles/desk-gnome/meta/services.yml +++ b/roles/desk-gnome/meta/services.yml @@ -3,6 +3,8 @@ gnome: modes: host: enabled: true + repository: https://github.com/kevinveenbirkenbach/cli-gnome-extension-manager.git + ref: v1.0.0 lifecycle: pre-alpha min_storage: "2GB" cpus: "1.0" diff --git a/roles/desk-gnome/tasks/01_extensions.yml b/roles/desk-gnome/tasks/01_extensions.yml index 8800e2b22f..95da6f6e27 100644 --- a/roles/desk-gnome/tasks/01_extensions.yml +++ b/roles/desk-gnome/tasks/01_extensions.yml @@ -3,11 +3,13 @@ ansible.builtin.shell: gsettings set org.gnome.shell disable-user-extensions false become: false -- name: "📦 pkgmgr install" +- name: 📦 Install cli-gnome-extension-manager system-wide via pip include_role: - name: pkgmgr-install + name: sys-pip-install vars: - package_name: cli-gnome-extension-manager + # TODO: switch to the PyPI name 'cli-gnome-extension-manager' once it is published + package_name: "git+{{ DESK_GNOME_EXTENSION_MANAGER_REPO }}@{{ DESK_GNOME_EXTENSION_MANAGER_REF }}" + global_install: true - name: ▶️ Execute CLI GNOME Extension manager script ansible.builtin.shell: >- diff --git a/roles/desk-gnome/vars/main.yml b/roles/desk-gnome/vars/main.yml index 1cc63a029c..e25b4c33d7 100644 --- a/roles/desk-gnome/vars/main.yml +++ b/roles/desk-gnome/vars/main.yml @@ -1,2 +1,4 @@ --- application_id: desk-gnome +DESK_GNOME_EXTENSION_MANAGER_REPO: "{{ lookup('config', application_id, 'services.gnome.repository') }}" +DESK_GNOME_EXTENSION_MANAGER_REF: "{{ lookup('config', application_id, 'services.gnome.ref') }}" diff --git a/roles/desk-gnucash/README.md b/roles/desk-gnucash/README.md index 5e26894250..8bf8c999f0 100644 --- a/roles/desk-gnucash/README.md +++ b/roles/desk-gnucash/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-jrnl/README.md b/roles/desk-jrnl/README.md index 4b57ce8230..54228ebb6f 100644 --- a/roles/desk-jrnl/README.md +++ b/roles/desk-jrnl/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-keepassxc/README.md b/roles/desk-keepassxc/README.md index 25370574d2..99b13e6c37 100644 --- a/roles/desk-keepassxc/README.md +++ b/roles/desk-keepassxc/README.md @@ -20,7 +20,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-libreoffice/README.md b/roles/desk-libreoffice/README.md index 65317598af..2ba6db682d 100644 --- a/roles/desk-libreoffice/README.md +++ b/roles/desk-libreoffice/README.md @@ -25,7 +25,7 @@ flowchart LR dep_gen_hunspell -- "1:1" --> svc_libreoffice ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-micro/README.md b/roles/desk-micro/README.md index bea11276ce..bad630294e 100644 --- a/roles/desk-micro/README.md +++ b/roles/desk-micro/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-neovim/README.md b/roles/desk-neovim/README.md index 1ff66d23fc..02982bbc03 100644 --- a/roles/desk-neovim/README.md +++ b/roles/desk-neovim/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-nextcloud/README.md b/roles/desk-nextcloud/README.md index aaf8ff3767..8fb2096355 100644 --- a/roles/desk-nextcloud/README.md +++ b/roles/desk-nextcloud/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-nextcloud/meta/schema.yml b/roles/desk-nextcloud/meta/secrets.yml similarity index 100% rename from roles/desk-nextcloud/meta/schema.yml rename to roles/desk-nextcloud/meta/secrets.yml diff --git a/roles/desk-nextcloud/vars/main.yml b/roles/desk-nextcloud/vars/main.yml index ad098834e1..9ef09b53b9 100644 --- a/roles/desk-nextcloud/vars/main.yml +++ b/roles/desk-nextcloud/vars/main.yml @@ -1,7 +1,7 @@ --- application_id: desk-nextcloud nextcloud_user_home_directory: "/home/{{ lookup('users', WORKSTATION_USER).username }}/" -nextcloud_cloud_fqdn: "{{ lookup('config', application_id, 'credentials.cloud_fqdn') }}" +nextcloud_cloud_fqdn: "{{ lookup('config', application_id, 'secrets.credentials.cloud_fqdn') }}" nextcloud_cloud_directory: "{{ nextcloud_user_home_directory }}Clouds/{{ nextcloud_cloud_fqdn }}/{{ lookup('users', WORKSTATION_USER).username }}/" nextcloud_dotlinker_folders: diff --git a/roles/desk-obs/README.md b/roles/desk-obs/README.md index 882b6b3bbb..a35ef6006b 100644 --- a/roles/desk-obs/README.md +++ b/roles/desk-obs/README.md @@ -20,7 +20,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-qbittorrent/README.md b/roles/desk-qbittorrent/README.md index a43f873df7..c15e6799c0 100644 --- a/roles/desk-qbittorrent/README.md +++ b/roles/desk-qbittorrent/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-retroarch/README.md b/roles/desk-retroarch/README.md index 7f5b7a2344..0cbf6be23a 100644 --- a/roles/desk-retroarch/README.md +++ b/roles/desk-retroarch/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-spotify/README.md b/roles/desk-spotify/README.md index d325eefa35..ab725b8bc2 100644 --- a/roles/desk-spotify/README.md +++ b/roles/desk-spotify/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-ssh/README.md b/roles/desk-ssh/README.md index b48aafd24f..f7936716f4 100644 --- a/roles/desk-ssh/README.md +++ b/roles/desk-ssh/README.md @@ -23,7 +23,7 @@ flowchart LR dep_desk_git -- "1:1" --> svc_ssh ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/desk-ssh/meta/services.yml b/roles/desk-ssh/meta/services.yml index 5f874769c9..22fe676816 100644 --- a/roles/desk-ssh/meta/services.yml +++ b/roles/desk-ssh/meta/services.yml @@ -4,8 +4,6 @@ ssh: host: enabled: true lifecycle: pre-alpha - # Repository URL containing the user's SSH key material; override in the - # inventory under `applications.desk-ssh.services.ssh.repository`. repository: "" min_storage: "50MB" cpus: "0.1" diff --git a/roles/desk-torbrowser/README.md b/roles/desk-torbrowser/README.md index 901c1143bd..30824fd3b5 100644 --- a/roles/desk-torbrowser/README.md +++ b/roles/desk-torbrowser/README.md @@ -22,7 +22,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-virtualbox/README.md b/roles/desk-virtualbox/README.md index 790b4d725c..5ff918e416 100644 --- a/roles/desk-virtualbox/README.md +++ b/roles/desk-virtualbox/README.md @@ -25,7 +25,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/desk-zoom/README.md b/roles/desk-zoom/README.md index d3acb070a3..52c0388439 100644 --- a/roles/desk-zoom/README.md +++ b/roles/desk-zoom/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/dev-arduino/README.md b/roles/dev-arduino/README.md index 6e251114e1..2aaaef451a 100644 --- a/roles/dev-arduino/README.md +++ b/roles/dev-arduino/README.md @@ -25,7 +25,7 @@ flowchart LR dep_dev_core -- "1:1" --> svc_arduino ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-base-devel/README.md b/roles/dev-base-devel/README.md index 93a84ca23b..eed6b9b078 100644 --- a/roles/dev-base-devel/README.md +++ b/roles/dev-base-devel/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/dev-core/README.md b/roles/dev-core/README.md index 9cda9cca3f..a4742d68b9 100644 --- a/roles/dev-core/README.md +++ b/roles/dev-core/README.md @@ -25,7 +25,7 @@ flowchart LR svc_core -- "1:1" --> dpt_dev_python ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-fakeroot/README.md b/roles/dev-fakeroot/README.md index d2edfce148..2ccbb41346 100644 --- a/roles/dev-fakeroot/README.md +++ b/roles/dev-fakeroot/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-gcc/README.md b/roles/dev-gcc/README.md index 83352a55c9..61f822e07c 100644 --- a/roles/dev-gcc/README.md +++ b/roles/dev-gcc/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-git/README.md b/roles/dev-git/README.md index c6b276e1a4..842d0a0a1c 100644 --- a/roles/dev-git/README.md +++ b/roles/dev-git/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-java/README.md b/roles/dev-java/README.md index 2fbc155b43..a9e2a9d421 100644 --- a/roles/dev-java/README.md +++ b/roles/dev-java/README.md @@ -23,7 +23,7 @@ flowchart LR svc_java -- "1:1" --> dpt_desk_bluray_player ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/dev-locales/README.md b/roles/dev-locales/README.md index c0d4ad770a..40075d91e4 100644 --- a/roles/dev-locales/README.md +++ b/roles/dev-locales/README.md @@ -30,7 +30,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/dev-make/README.md b/roles/dev-make/README.md index f5b4800bff..741e951b05 100644 --- a/roles/dev-make/README.md +++ b/roles/dev-make/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-nix/README.md b/roles/dev-nix/README.md index 4203bd9b0f..209c69a2dd 100644 --- a/roles/dev-nix/README.md +++ b/roles/dev-nix/README.md @@ -29,7 +29,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Installation Strategy diff --git a/roles/dev-nix/defaults/main.yml b/roles/dev-nix/defaults/main.yml index de4e6fcce1..0eca2a808f 100644 --- a/roles/dev-nix/defaults/main.yml +++ b/roles/dev-nix/defaults/main.yml @@ -15,8 +15,6 @@ dev_nix_installer_sha256_url: "{{ dev_nix_installer_url }}.sha256" # Path where the installer will be downloaded on the target host dev_nix_installer_dest: "/usr/local/share/nix-install.sh" -# Candidate paths for nix binary across installer/package variants. -# The first existing path is used as source for /usr/local/bin/nix. dev_nix_binary_candidates: - /nix/var/nix/profiles/default/bin/nix - /nix/var/nix/profiles/per-user/root/profile/bin/nix @@ -27,8 +25,6 @@ dev_nix_binary_candidates: # Will be filled at runtime from dev_nix_installer_sha256_url dev_nix_installer_sha256: "" -# Whether to drop a small shell snippet into /etc/profile.d to ensure -# Nix environment is available for login shells. dev_nix_enable_shell_snippet: true # Path of the profile.d snippet @@ -42,10 +38,4 @@ dev_nix_experimental_features: - nix-command - flakes -# Candidate CA bundle paths by distro family. -# The first existing path is used for nix.conf ssl-cert-file. -DEV_NIX_SSL_CERT_FILE_CANDIDATES: - - /etc/ssl/certs/ca-certificates.crt - - /etc/pki/tls/certs/ca-bundle.crt - - /etc/ssl/ca-bundle.pem - - /etc/pki/tls/cacert.pem +DEV_NIX_SSL_CERT_FILE_CANDIDATES: "{{ CA_BUNDLE_CANDIDATES }}" diff --git a/roles/dev-nix/files/aggressive_prune_nix.sh b/roles/dev-nix/files/aggressive_prune_nix.sh deleted file mode 100644 index bf769238ff..0000000000 --- a/roles/dev-nix/files/aggressive_prune_nix.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash -# Aggressively prune Nix data: GC + optimise. CI/Debug cleanup to prevent -# huge disk usage from Nix store + old generations. -# -# Args: -# $1 nix_bin -- absolute path to the nix binary -set -euo pipefail - -nix_bin="${1:?nix binary path required}" -nix_bin_dir="$(dirname "$nix_bin")" -nix_collect="$nix_bin_dir/nix-collect-garbage" -nix_store="$nix_bin_dir/nix-store" - -# Remove old generations for all users + root (aggressive) -if [ -x "$nix_collect" ]; then - "$nix_collect" -d -else - "$nix_bin" store gc || true -fi - -# Additional GC pass (useful on some setups / older nix) -if [ -x "$nix_store" ]; then - "$nix_store" --gc || true -else - "$nix_bin" store gc || true -fi - -# Deduplicate store paths to reduce disk usage (can take a bit). -# Prefer modern CLI; fall back to nix-store on older setups. -if ! "$nix_bin" store optimise; then - if [ -x "$nix_store" ]; then - "$nix_store" --optimise || true - fi -fi diff --git a/roles/dev-nix/files/shell/aggressive_prune_nix.sh b/roles/dev-nix/files/shell/aggressive_prune_nix.sh new file mode 100644 index 0000000000..acda63b099 --- /dev/null +++ b/roles/dev-nix/files/shell/aggressive_prune_nix.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Aggressively prune Nix data: GC + optimise. CI/Debug cleanup to prevent +# huge disk usage from Nix store + old generations. +# +# Args: +# $1 nix_bin -- absolute path to the nix binary +set -euo pipefail + +nix_bin="${1:?nix binary path required}" +nix_bin_dir="$(dirname "$nix_bin")" +nix_collect="$nix_bin_dir/nix-collect-garbage" +nix_store="$nix_bin_dir/nix-store" + +if [ -x "$nix_collect" ]; then + gc_rc=0 + gc_out="$("$nix_collect" -d 2>&1)" || gc_rc=$? + printf '%s\n' "$gc_out" + if [ "$gc_rc" -ne 0 ] && ! printf '%s' "$gc_out" | grep -q 'cannot unlink .*Directory not empty'; then + exit "$gc_rc" + fi +else + "$nix_bin" store gc || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +fi + +if [ -x "$nix_store" ]; then + "$nix_store" --gc || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +else + "$nix_bin" store gc || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +fi + +if ! "$nix_bin" store optimise; then + if [ -x "$nix_store" ]; then + "$nix_store" --optimise || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + fi +fi diff --git a/roles/dev-nix/files/purge_stale_nixbld.sh b/roles/dev-nix/files/shell/purge_stale_nixbld.sh similarity index 100% rename from roles/dev-nix/files/purge_stale_nixbld.sh rename to roles/dev-nix/files/shell/purge_stale_nixbld.sh diff --git a/roles/dev-nix/files/write_nix_shell_snippet.sh b/roles/dev-nix/files/shell/write_nix_shell_snippet.sh similarity index 94% rename from roles/dev-nix/files/write_nix_shell_snippet.sh rename to roles/dev-nix/files/shell/write_nix_shell_snippet.sh index c1e274bc16..21e9718e6a 100644 --- a/roles/dev-nix/files/write_nix_shell_snippet.sh +++ b/roles/dev-nix/files/shell/write_nix_shell_snippet.sh @@ -15,7 +15,6 @@ cleanup() { trap cleanup EXIT cat >"$tmp" <<'EOF' -# Added by dev-nix Ansible role if [ -e /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh fi diff --git a/roles/dev-nix/tasks/00_core.yml b/roles/dev-nix/tasks/00_core.yml index b9d4805f72..bcd81755ae 100644 --- a/roles/dev-nix/tasks/00_core.yml +++ b/roles/dev-nix/tasks/00_core.yml @@ -26,7 +26,7 @@ | map(attribute="item") | list | first - ) | default("/etc/ssl/certs/ca-certificates.crt", true) + ) | default(CA_BUNDLE_CANDIDATES | first, true) }} - name: 📦 Install Nix via package manager on Arch-based systems diff --git a/roles/dev-nix/tasks/01_non_arch_installer.yml b/roles/dev-nix/tasks/01_non_arch_installer.yml index ae74174111..1242e44484 100644 --- a/roles/dev-nix/tasks/01_non_arch_installer.yml +++ b/roles/dev-nix/tasks/01_non_arch_installer.yml @@ -91,7 +91,7 @@ - name: 🗑️ Optionally drop shell snippet for Nix ansible.builtin.script: cmd: >- - {{ role_path }}/files/write_nix_shell_snippet.sh + {{ role_path }}/files/shell/write_nix_shell_snippet.sh {{ dev_nix_shell_snippet_path | quote }} register: dev_nix_shell_snippet_result changed_when: > @@ -105,7 +105,7 @@ - name: 🧹 Aggressively prune Nix data (GC + optimise) become: true ansible.builtin.script: > - aggressive_prune_nix.sh + shell/aggressive_prune_nix.sh {{ dev_nix_binary_path | quote }} changed_when: true when: diff --git a/roles/dev-nix/tasks/01_non_arch_installer/nix_install_only.yml b/roles/dev-nix/tasks/01_non_arch_installer/nix_install_only.yml index 376b6ad134..34ada04c07 100644 --- a/roles/dev-nix/tasks/01_non_arch_installer/nix_install_only.yml +++ b/roles/dev-nix/tasks/01_non_arch_installer/nix_install_only.yml @@ -6,7 +6,7 @@ - name: 🧹 Purge stale nixbld users blocking the multi-user installer ansible.builtin.script: - cmd: "{{ role_path }}/files/purge_stale_nixbld.sh" + cmd: "{{ role_path }}/files/shell/purge_stale_nixbld.sh" register: dev_nix_purge_stale_nixbld_result changed_when: > dev_nix_purge_stale_nixbld_result.stdout is search('\\[CHANGED\\]') diff --git a/roles/dev-nix/tasks/02_install_official.yml b/roles/dev-nix/tasks/02_install_official.yml index 1c33b956c4..2be818f5a0 100644 --- a/roles/dev-nix/tasks/02_install_official.yml +++ b/roles/dev-nix/tasks/02_install_official.yml @@ -1,7 +1,7 @@ --- - name: 🧹 Purge stale nixbld users blocking the multi-user installer ansible.builtin.script: - cmd: "{{ role_path }}/files/purge_stale_nixbld.sh" + cmd: "{{ role_path }}/files/shell/purge_stale_nixbld.sh" register: dev_nix_purge_stale_nixbld_result changed_when: > dev_nix_purge_stale_nixbld_result.stdout is search('\\[CHANGED\\]') diff --git a/roles/dev-nix/templates/nix.conf.j2 b/roles/dev-nix/templates/nix.conf.j2 index 22af2d5e68..493e5059d1 100644 --- a/roles/dev-nix/templates/nix.conf.j2 +++ b/roles/dev-nix/templates/nix.conf.j2 @@ -4,20 +4,12 @@ # Unix group containing the Nix build user accounts build-users-group = nixbld -# Use the system trust store for HTTPS fetches (flakes, binary caches, etc.) ssl-cert-file = {{ dev_nix_ssl_cert_file }} -# Enable experimental features if configured {% if dev_nix_enable_experimental_features %} experimental-features = {{ dev_nix_experimental_features | join(" ") }} {% endif %} -# Keep derivations + outputs of GC roots alive so `nix-collect-garbage -d` -# (run by the aggressive prune step) does not drop the BUILD closure of -# installed flake outputs. Without this, every deploy must re-fetch the -# build inputs (gcc, python toolchain, …) of pkgmgr's flake from -# cache.nixos.org — observed to overshoot pkgmgr's update timeout. keep-derivations = true keep-outputs = true -# (Optional) Add more global nix.conf options below diff --git a/roles/dev-nodejs/README.md b/roles/dev-nodejs/README.md index f714286c1a..df021d25d3 100644 --- a/roles/dev-nodejs/README.md +++ b/roles/dev-nodejs/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/dev-npm/README.md b/roles/dev-npm/README.md index 75c736e24b..6e54f69942 100644 --- a/roles/dev-npm/README.md +++ b/roles/dev-npm/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/dev-python/README.md b/roles/dev-python/README.md index f1456be6cc..0a8f7054cf 100644 --- a/roles/dev-python/README.md +++ b/roles/dev-python/README.md @@ -25,7 +25,7 @@ flowchart LR dep_dev_core -- "1:1" --> svc_python ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/dev-python/files/install.sh b/roles/dev-python/files/shell/install.sh similarity index 76% rename from roles/dev-python/files/install.sh rename to roles/dev-python/files/shell/install.sh index bfbced4f12..961b8d8b7c 100755 --- a/roles/dev-python/files/install.sh +++ b/roles/dev-python/files/shell/install.sh @@ -24,8 +24,8 @@ fi . /etc/os-release ID_LIKE="${ID_LIKE:-}" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" -DOCKER_APT_SANITIZER="${REPO_ROOT}/roles/sys-svc-container/files/apt_repo.sh" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)" +DOCKER_APT_SANITIZER="${REPO_ROOT}/roles/sys-svc-container/files/shell/apt_repo.sh" log() { printf '>>> [dev-python] %s\n' "$*" @@ -77,8 +77,8 @@ find_highest_apt_python_pkg() { find_highest_rpm_python_pkg() { local pm="$1" { - run_privileged "${pm}" -q list installed "python3.[0-9]*" 2>/dev/null || true - run_privileged "${pm}" -q list --available "python3.[0-9]*" 2>/dev/null || true + run_privileged "${pm}" -q list installed "python3.[0-9]*" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + run_privileged "${pm}" -q list --available "python3.[0-9]*" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error } \ | awk '/^python3\.[0-9]+\./ {pkg=$1; sub(/\.[^.]+$/, "", pkg); print pkg}' \ | sort -Vu \ @@ -98,9 +98,9 @@ install_versioned_rpm_python_and_pip() { local py_pkg="$2" local pip_pkg="${py_pkg}-pip" - run_privileged "${pm}" -y install "${py_pkg}" || true + run_privileged "${pm}" -y install "${py_pkg}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error if rpm_pkg_exists "${pm}" "${pip_pkg}"; then - run_privileged "${pm}" -y install "${pip_pkg}" || true + run_privileged "${pm}" -y install "${pip_pkg}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error else log "Skipping unavailable package ${pip_pkg}; using generic python3-pip fallback if present." fi @@ -113,7 +113,7 @@ install_python_packages() { arch | manjaro) run_privileged pacman-key --init run_privileged pacman -Syu --noconfirm --needed python python-pip - run_privileged pacman -Scc --noconfirm || true + run_privileged pacman -Scc --noconfirm || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error ;; debian | ubuntu) @@ -125,9 +125,9 @@ install_python_packages() { run_privileged apt-get install -y --no-install-recommends python3 python3-pip apt_best_pkg="$(find_highest_apt_python_pkg || true)" if [[ "${apt_best_pkg}" =~ ^python3\.([0-9]+)$ ]] && (( BASH_REMATCH[1] >= 11 )); then - run_privileged apt-get install -y --no-install-recommends "${apt_best_pkg}" || true + run_privileged apt-get install -y --no-install-recommends "${apt_best_pkg}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error if apt-cache show "${apt_best_pkg}-venv" >/dev/null 2>&1; then - run_privileged apt-get install -y --no-install-recommends "${apt_best_pkg}-venv" || true + run_privileged apt-get install -y --no-install-recommends "${apt_best_pkg}-venv" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi fi run_privileged rm -rf /var/lib/apt/lists/* @@ -141,8 +141,8 @@ install_python_packages() { if [[ "${dnf_best_pkg}" =~ ^python3\.([0-9]+)$ ]] && (( BASH_REMATCH[1] >= 11 )); then install_versioned_rpm_python_and_pip dnf "${dnf_best_pkg}" fi - run_privileged dnf -y clean all || true - run_privileged rm -rf /var/cache/dnf || true + run_privileged dnf -y clean all || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + run_privileged rm -rf /var/cache/dnf || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error ;; centos | rhel) @@ -153,13 +153,13 @@ install_python_packages() { else PM=yum fi - run_privileged "${PM}" -y install python3 python3-pip || true + run_privileged "${PM}" -y install python3 python3-pip || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error rpm_best_pkg="$(find_highest_rpm_python_pkg "${PM}" || true)" if [[ "${rpm_best_pkg}" =~ ^python3\.([0-9]+)$ ]] && (( BASH_REMATCH[1] >= 11 )); then install_versioned_rpm_python_and_pip "${PM}" "${rpm_best_pkg}" fi - run_privileged "${PM}" -y clean all || true - run_privileged rm -rf "/var/cache/${PM}" || true + run_privileged "${PM}" -y clean all || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + run_privileged rm -rf "/var/cache/${PM}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error ;; *) @@ -171,13 +171,13 @@ install_python_packages() { else PM=yum fi - run_privileged "${PM}" -y install python3 python3-pip || true + run_privileged "${PM}" -y install python3 python3-pip || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error rpm_like_best_pkg="$(find_highest_rpm_python_pkg "${PM}" || true)" if [[ "${rpm_like_best_pkg}" =~ ^python3\.([0-9]+)$ ]] && (( BASH_REMATCH[1] >= 11 )); then install_versioned_rpm_python_and_pip "${PM}" "${rpm_like_best_pkg}" fi - run_privileged "${PM}" -y clean all || true - run_privileged rm -rf "/var/cache/${PM}" || true + run_privileged "${PM}" -y clean all || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + run_privileged rm -rf "/var/cache/${PM}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error else echo "[ERROR] Unsupported distro for Python install: ID=${ID} ID_LIKE=${ID_LIKE}" >&2 exit 1 @@ -290,7 +290,7 @@ configure_defaults() { run_privileged ln -sfn "${versioned_pip}" /usr/local/bin/pip3 else if ! "${pybin}" -m pip --version >/dev/null 2>&1; then - run_privileged "${pybin}" -m ensurepip --upgrade >/dev/null 2>&1 || true + run_privileged "${pybin}" -m ensurepip --upgrade >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi if "${pybin}" -m pip --version >/dev/null 2>&1; then run_privileged tee /usr/local/bin/pip3 >/dev/null <<'EOF' @@ -317,7 +317,7 @@ resolve_python_bin_or_fail() { fi echo "[ERROR] No Python >= 3.11 found after installation attempt." >&2 if command -v python3 >/dev/null 2>&1; then - python3 --version || true + python3 --version || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi exit 1 } @@ -325,7 +325,7 @@ resolve_python_bin_or_fail() { ensure_python_bin() { log "Ensuring highest available Python >=3.11 for ID=${ID} ID_LIKE=${ID_LIKE}" install_python_packages - hash -r || true + hash -r || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error resolve_python_bin_or_fail } diff --git a/roles/dev-python/tasks/00_core.yml b/roles/dev-python/tasks/00_core.yml index 18b0b7554c..d7abeb27f6 100644 --- a/roles/dev-python/tasks/00_core.yml +++ b/roles/dev-python/tasks/00_core.yml @@ -5,7 +5,7 @@ when: run_once_sys_pip is not defined - name: 📦 Install and prefer Python 3.11+ as default - ansible.builtin.script: "{{ role_path }}/files/install.sh" + ansible.builtin.script: "{{ role_path }}/files/shell/install.sh" environment: SKIP_DOCKER_APT_SANITIZER: "1" become: true diff --git a/roles/dev-shell/README.md b/roles/dev-shell/README.md index e2bf860c13..587d7e098a 100644 --- a/roles/dev-shell/README.md +++ b/roles/dev-shell/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/drv-epson-multiprinter/README.md b/roles/drv-epson-multiprinter/README.md index 25e7f00345..926330697c 100644 --- a/roles/drv-epson-multiprinter/README.md +++ b/roles/drv-epson-multiprinter/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/drv-intel/README.md b/roles/drv-intel/README.md index aa38f97616..e8d578c363 100644 --- a/roles/drv-intel/README.md +++ b/roles/drv-intel/README.md @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/drv-lid-switch/README.md b/roles/drv-lid-switch/README.md index 2c9d7f1932..fcb05be69d 100644 --- a/roles/drv-lid-switch/README.md +++ b/roles/drv-lid-switch/README.md @@ -22,7 +22,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/drv-lid-switch/handlers/main.yml b/roles/drv-lid-switch/handlers/main.yml index 1187fe62e6..44fe68656b 100644 --- a/roles/drv-lid-switch/handlers/main.yml +++ b/roles/drv-lid-switch/handlers/main.yml @@ -1,5 +1,6 @@ --- -- name: Restart systemd-logind +- name: 🔄 Restart systemd-logind + listen: restart-systemd-logind become: true systemd: name: systemd-logind diff --git a/roles/drv-lid-switch/tasks/00_core.yml b/roles/drv-lid-switch/tasks/00_core.yml index a82664c6b3..f99ca1662f 100644 --- a/roles/drv-lid-switch/tasks/00_core.yml +++ b/roles/drv-lid-switch/tasks/00_core.yml @@ -20,7 +20,7 @@ regexp: "^#?HandleLidSwitch=" line: "HandleLidSwitch=hibernate" backup: true - notify: Restart systemd-logind + notify: restart-systemd-logind - name: 🔧 Configure systemd to lock session when lid is closed on external power lineinfile: @@ -28,7 +28,7 @@ regexp: "^#?HandleLidSwitchExternalPower=" line: "HandleLidSwitchExternalPower=lock" backup: true - notify: Restart systemd-logind + notify: restart-systemd-logind become: true - name: 🔧 Configure systemd to lock session when lid is closed while docked @@ -37,7 +37,7 @@ regexp: "^#?HandleLidSwitchDocked=" line: "HandleLidSwitchDocked=lock" backup: true - notify: Restart systemd-logind + notify: restart-systemd-logind become: true - include_tasks: utils/once/flag.yml diff --git a/roles/drv-non-free/README.md b/roles/drv-non-free/README.md index 3ffe0fcb12..ee043ae1ee 100644 --- a/roles/drv-non-free/README.md +++ b/roles/drv-non-free/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/gen-hunspell/README.md b/roles/gen-hunspell/README.md index 05d87d0659..b4b98f3cdd 100644 --- a/roles/gen-hunspell/README.md +++ b/roles/gen-hunspell/README.md @@ -23,7 +23,7 @@ flowchart LR svc_hunspell -- "1:1" --> dpt_desk_libreoffice ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/pkgmgr-install/README.md b/roles/pkgmgr-install/README.md index 7e9d28ba55..5683396885 100644 --- a/roles/pkgmgr-install/README.md +++ b/roles/pkgmgr-install/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/pkgmgr/README.md b/roles/pkgmgr/README.md index 129cb98114..190177f0d1 100644 --- a/roles/pkgmgr/README.md +++ b/roles/pkgmgr/README.md @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-ai-ollama/README.md b/roles/svc-ai-ollama/README.md index 1647a69811..a16b53dd83 100644 --- a/roles/svc-ai-ollama/README.md +++ b/roles/svc-ai-ollama/README.md @@ -32,7 +32,7 @@ flowchart LR svc_ollama -. "0..1" .-> dpt_web_app_openwebui ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index 00c778e6c7..b886ceaa11 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -1,5 +1,7 @@ --- ollama: + healthcheck: + flavor: tcp modes: compose: enabled: true @@ -11,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.32.13 + version: 0.33.2 name: ollama min_storage: 3473MB cpus: "4.0" diff --git a/roles/svc-ai-ollama/tasks/01_manager_ops.yml b/roles/svc-ai-ollama/tasks/01_manager_ops.yml index 4ca4c4bbed..c192f0272a 100644 --- a/roles/svc-ai-ollama/tasks/01_manager_ops.yml +++ b/roles/svc-ai-ollama/tasks/01_manager_ops.yml @@ -16,6 +16,11 @@ # rationale: async; model pulls run overlapped, results reaped below before playwright async: "{{ OLLAMA_PRELOAD_ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" + retries: "{{ 0 if ASYNC_ENABLED | bool else 5 }}" + delay: 15 + until: > + (pull_result.rc | default(0)) == 0 or + ('up to date' in (pull_result.stdout | default(''))) changed_when: false failed_when: >- (pull_result.failed | default(false)) diff --git a/roles/svc-ai-ollama/templates/compose.yml.j2 b/roles/svc-ai-ollama/templates/compose.yml.j2 index c4f8ad90b6..47b15d53ed 100644 --- a/roles/svc-ai-ollama/templates/compose.yml.j2 +++ b/roles/svc-ai-ollama/templates/compose.yml.j2 @@ -2,14 +2,15 @@ {% set service_name = 'ollama' %} {{ service_name }}: + {{ lookup('container_healthcheck', service_name) | indent(4) }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'ollama') }} {{ lookup('compose_only', 'container_name', OLLAMA_CONTAINER) }} expose: - "{{ OLLAMA_PORT }}" -{{ lookup('container_volumes', application_id, 'ollama') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {{ lookup('compose_networks') }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} diff --git a/roles/svc-bkp-local-2-device/README.md b/roles/svc-bkp-local-2-device/README.md index 3721cb25ef..40ac057f67 100644 --- a/roles/svc-bkp-local-2-device/README.md +++ b/roles/svc-bkp-local-2-device/README.md @@ -25,7 +25,7 @@ flowchart LR svc_local_2_device -. "0..1" .-> dpt_svc_bkp_remote_2_local ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Schema @@ -90,7 +90,7 @@ infinito administration deploy dedicated "$INVENTORY/devices.yml" \ ## Recover -Run `files/recover.py` on the host with the backup device attached: +Run `files/python/recover.py` on the host with the backup device attached: ``` recover.py /dev/sdX1 /mnt/usb-recover /var/lib/infinito/backup [--snapshot ] diff --git a/roles/svc-bkp-local-2-device/files/recover.py b/roles/svc-bkp-local-2-device/files/python/recover.py similarity index 92% rename from roles/svc-bkp-local-2-device/files/recover.py rename to roles/svc-bkp-local-2-device/files/python/recover.py index dd5534e4c3..beaff5b0b6 100755 --- a/roles/svc-bkp-local-2-device/files/recover.py +++ b/roles/svc-bkp-local-2-device/files/python/recover.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# nocheck: mirrored-unit-test - subclasses utils.recovery.base and is exercised +# collectively by tests/unit/python/utils/recovery/test_role_recover_scripts.py; a +# per-role copy would assert the base class twice over """Restore the local backup root from the encrypted backup device. Opens the LUKS device (interactive passphrase prompt, or stdin with @@ -25,7 +28,7 @@ import subprocess import sys from pathlib import Path -_REPO_ROOT = Path(__file__).resolve().parents[3] # nocheck: project-root-import +_REPO_ROOT = Path(__file__).resolve().parents[4] # nocheck: project-root-import sys.path.insert(0, str(_REPO_ROOT)) from utils.recovery.base import DirectoryRecovery # noqa: E402 diff --git a/roles/svc-bkp-local-2-device/files/script.py b/roles/svc-bkp-local-2-device/files/python/script.py similarity index 91% rename from roles/svc-bkp-local-2-device/files/script.py rename to roles/svc-bkp-local-2-device/files/python/script.py index 8f82112091..bd8ed49054 100755 --- a/roles/svc-bkp-local-2-device/files/script.py +++ b/roles/svc-bkp-local-2-device/files/python/script.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# nocheck: mirrored-unit-test - main() is one straight line of rsync and mount +# subprocess calls against an attached backup device; every branch it has is a return +# code from the host, so the assertions would only restate the mocks import datetime import glob diff --git a/roles/svc-bkp-nfs-2-local/README.md b/roles/svc-bkp-nfs-2-local/README.md index 555026b8ab..6597a1034c 100644 --- a/roles/svc-bkp-nfs-2-local/README.md +++ b/roles/svc-bkp-nfs-2-local/README.md @@ -33,7 +33,7 @@ flowchart LR svc_nfs_2_local -. "0..1" .-> dpt_svc_storage_nfs_server ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Schema @@ -97,7 +97,7 @@ infinito administration deploy dedicated "$INVENTORY/devices.yml" \ ## Recover -Run `files/recover.py` on the host that serves the NFS export: +Run `files/python/recover.py` on the host that serves the NFS export: ``` recover.py //backup-nfs-to-local//files// // diff --git a/roles/svc-bkp-nfs-2-local/files/recover.py b/roles/svc-bkp-nfs-2-local/files/python/recover.py similarity index 84% rename from roles/svc-bkp-nfs-2-local/files/recover.py rename to roles/svc-bkp-nfs-2-local/files/python/recover.py index 15e5a68789..ef159bed13 100755 --- a/roles/svc-bkp-nfs-2-local/files/recover.py +++ b/roles/svc-bkp-nfs-2-local/files/python/recover.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# nocheck: mirrored-unit-test - subclasses utils.recovery.base and is exercised +# collectively by tests/unit/python/utils/recovery/test_role_recover_scripts.py; a +# per-role copy would assert the base class twice over """Restore an NFS export subtree from a backup snapshot. Runs the role's deployed backup unit first (the usual differential @@ -17,7 +20,7 @@ import argparse import sys from pathlib import Path -_REPO_ROOT = Path(__file__).resolve().parents[3] # nocheck: project-root-import +_REPO_ROOT = Path(__file__).resolve().parents[4] # nocheck: project-root-import sys.path.insert(0, str(_REPO_ROOT)) from utils.recovery.base import DirectoryRecovery # noqa: E402 diff --git a/roles/svc-bkp-nfs-2-local/files/script.sh b/roles/svc-bkp-nfs-2-local/files/shell/script.sh similarity index 100% rename from roles/svc-bkp-nfs-2-local/files/script.sh rename to roles/svc-bkp-nfs-2-local/files/shell/script.sh diff --git a/roles/svc-bkp-nfs-2-local/meta/services.yml b/roles/svc-bkp-nfs-2-local/meta/services.yml index 29dbc0c79d..a88ee5987a 100644 --- a/roles/svc-bkp-nfs-2-local/meta/services.yml +++ b/roles/svc-bkp-nfs-2-local/meta/services.yml @@ -1,4 +1,5 @@ --- +# nocheck: variants-coverage — the export is what this role backs up, so the false polarity has no variant to live in: without the server there is no /srv/nfs and the unit's own guard aborts. nfs-server: enabled: "{{ 'svc-storage-nfs-server' in group_names }}" shared: "{{ 'svc-storage-nfs-server' in group_names }}" diff --git a/roles/svc-bkp-nfs-2-local/meta/variants.yml b/roles/svc-bkp-nfs-2-local/meta/variants.yml index 7236734d14..9fba2328ff 100644 --- a/roles/svc-bkp-nfs-2-local/meta/variants.yml +++ b/roles/svc-bkp-nfs-2-local/meta/variants.yml @@ -3,7 +3,3 @@ nfs-server: enabled: true shared: true -- services: - nfs-server: - enabled: false - shared: false diff --git a/roles/svc-bkp-remote-2-local/README.md b/roles/svc-bkp-remote-2-local/README.md index 7661b3f497..ac1323f282 100644 --- a/roles/svc-bkp-remote-2-local/README.md +++ b/roles/svc-bkp-remote-2-local/README.md @@ -28,7 +28,7 @@ flowchart LR dep_sys_ctl_cln_faild_bkps -- "1:1" --> svc_remote_2_local ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Schema @@ -92,7 +92,7 @@ infinito administration deploy dedicated "$INVENTORY/devices.yml" \ ## Recover -This role's direction is one-way by design (`files/recover.py.nocheck`): it pulls provider backups onto this host, so the pulled tree under `////` IS the recovery store and there is no live target here to restore into. +This role's direction is one-way by design (`files/python/recover.py.nocheck`): it pulls provider backups onto this host, so the pulled tree under `////` IS the recovery store and there is no live target here to restore into. To recover a source system, transfer the wanted generation to it (the provider's `backup` user only whitelists pull commands, so pushing requires an explicit operator rsync with a root-capable target) and run the matching role's `recover.py` there (`svc-bkp-volume-2-local` for docker volumes, `svc-bkp-nfs-2-local` for NFS exports). diff --git a/roles/svc-bkp-remote-2-local/files/__init__.py b/roles/svc-bkp-remote-2-local/files/python/__init__.py similarity index 100% rename from roles/svc-bkp-remote-2-local/files/__init__.py rename to roles/svc-bkp-remote-2-local/files/python/__init__.py diff --git a/roles/svc-bkp-remote-2-local/files/pull_specific_host.py b/roles/svc-bkp-remote-2-local/files/python/pull_specific_host.py similarity index 100% rename from roles/svc-bkp-remote-2-local/files/pull_specific_host.py rename to roles/svc-bkp-remote-2-local/files/python/pull_specific_host.py diff --git a/roles/svc-bkp-remote-2-local/files/recover.py.nocheck b/roles/svc-bkp-remote-2-local/files/python/recover.py.nocheck similarity index 100% rename from roles/svc-bkp-remote-2-local/files/recover.py.nocheck rename to roles/svc-bkp-remote-2-local/files/python/recover.py.nocheck diff --git a/roles/svc-bkp-remote-2-local/tasks/00_core.yml b/roles/svc-bkp-remote-2-local/tasks/00_core.yml index 877a284d83..18a2ccea12 100644 --- a/roles/svc-bkp-remote-2-local/tasks/00_core.yml +++ b/roles/svc-bkp-remote-2-local/tasks/00_core.yml @@ -19,7 +19,7 @@ - name: "🚀 Deploy '{{ DOCKER_BACKUP_REMOTE_2_LOCAL_SCRIPT }}'" copy: - src: "{{ DOCKER_BACKUP_REMOTE_2_LOCAL_FILE }}" + src: "python/{{ DOCKER_BACKUP_REMOTE_2_LOCAL_FILE }}" dest: "{{ DOCKER_BACKUP_REMOTE_2_LOCAL_SCRIPT }}" mode: "0755" diff --git a/roles/svc-bkp-secrets-2-local/README.md b/roles/svc-bkp-secrets-2-local/README.md index 2a27c037cc..f145576df0 100644 --- a/roles/svc-bkp-secrets-2-local/README.md +++ b/roles/svc-bkp-secrets-2-local/README.md @@ -39,7 +39,7 @@ flowchart LR svc_secrets_2_local -- "1:1" --> dpt_svc_bkp_volume_2_local ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Schema @@ -108,7 +108,7 @@ infinito administration deploy dedicated "$INVENTORY/devices.yml" \ ## Recover -Run `files/recover.py` on the target host: +Run `files/python/recover.py` on the target host: ``` recover.py //backup-secrets-to-local//files [--restore-node-identity] diff --git a/roles/svc-bkp-secrets-2-local/files/recover.py b/roles/svc-bkp-secrets-2-local/files/python/recover.py similarity index 93% rename from roles/svc-bkp-secrets-2-local/files/recover.py rename to roles/svc-bkp-secrets-2-local/files/python/recover.py index b837d03bdd..d8fe157cb1 100755 --- a/roles/svc-bkp-secrets-2-local/files/recover.py +++ b/roles/svc-bkp-secrets-2-local/files/python/recover.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +# nocheck: mirrored-unit-test - subclasses utils.recovery.base and is exercised +# collectively by tests/unit/python/utils/recovery/test_role_recover_scripts.py; a +# per-role copy would assert the base class twice over """Restore host-generated secret material from a backup snapshot. Runs the role's deployed backup unit first (a fresh differential @@ -24,7 +27,7 @@ import shutil import sys from pathlib import Path -_REPO_ROOT = Path(__file__).resolve().parents[3] # nocheck: project-root-import +_REPO_ROOT = Path(__file__).resolve().parents[4] # nocheck: project-root-import sys.path.insert(0, str(_REPO_ROOT)) from utils.paths import DIR_SECRETS # noqa: E402 diff --git a/roles/svc-bkp-secrets-2-local/files/script.sh b/roles/svc-bkp-secrets-2-local/files/shell/script.sh similarity index 100% rename from roles/svc-bkp-secrets-2-local/files/script.sh rename to roles/svc-bkp-secrets-2-local/files/shell/script.sh diff --git a/roles/svc-bkp-volume-2-local/README.md b/roles/svc-bkp-volume-2-local/README.md index b36d4a51db..103a095777 100644 --- a/roles/svc-bkp-volume-2-local/README.md +++ b/roles/svc-bkp-volume-2-local/README.md @@ -22,6 +22,7 @@ flowchart LR end subgraph role [svc-bkp-volume-2-local 💻] svc_volume_2_local["volume-2-local"] + svc_test["test ❌"] svc_secrets_backup["secrets_backup"] end subgraph dependents [Dependents] @@ -56,7 +57,7 @@ flowchart LR svc_volume_2_local -- "1:1" --> dpt_svc_registry_cache ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Schema @@ -74,7 +75,7 @@ flowchart TD BAUDOLO --> CHECK3B["DR drill [3b]
newest backup-docker-to-local generation
must be fresh + non-empty
(catches over-exclusion)"] EXPORT["svc-bkp-nfs-2-local
on the export host
rsyncs the export tree"] --> TREE["backup-nfs-to-local/<generation>
the single capture"] BAUDOLO -.->|"no second copy
through the mount"| TREE - TREE --> RECOVER["files/recover.py volume
resolves Mountpoint + Options"] + TREE --> RECOVER["files/python/recover.py volume
resolves Mountpoint + Options"] RECOVER -->|"Options set"| PROBE{"mountpoint -q
(ssh for --docker-host)"} PROBE -->|unmounted| REFUSE["SystemExit: a restore would land
on the node disk and be shadowed
on the next mount"] PROBE -->|mounted| RSYNC["rsync -a --delete through the
mounted export onto the server"] @@ -249,7 +250,53 @@ marker on the server's disk. ## Recover -Run `files/recover.py` on the backed-up host to restore a volume's files: +### The databases of a generation + +A generation stores this role's databases as sql dumps, not as a file tree +(`--only-sql`), so they are restored by their own step: + +``` +recover.py --databases //backup-docker-to-local/ +``` + +or, through the chain, `python3 -m cli.administration.recover database localhost`. + +**A dump needs a running engine.** It is replayed through `docker exec`, so +unlike a file tree it cannot be restored onto a bare host. After a total loss +the order is: deploy the stack, stop the consumers, replay, start them again. +The step names which of the two states is missing — a stopped container that +only needs starting, or no container at all. + +It replays every single-database dump with `baudolo-restore --empty`. +Two rules make it safe rather than convenient: + +1. **The consumers must be down.** `--empty` pre-cleans the schema in one psql + session and replays in the next; a booting consumer recreates the schema in + between and the dump's own `CREATE TABLE` then fails. The replay checks the + consumer's compose project and refuses while anything of it runs. +2. **The engine is read, not guessed.** It comes from the service key in the + consuming role's `meta/services.yml`, the same value that fed the backup + seed, resolved through `utils/recovery/databases.py`. A dump whose engine no + role claims aborts the run instead of being replayed with an assumption. +3. **The version has to fit.** The dump states which server it came out of, in + its own header — `-- Dumped from database version 17.11` for postgres, + `-- Server version\t11.8.8-MariaDB` for mariadb. That is compared against + the running engine before the pre-clean touches anything. Restoring forward + across a major version is the upgrade path and stays allowed; backward is + refused, because a newer dump uses syntax an older server rejects and the + schema would already be dropped by then. The version is deliberately not + kept in `databases.csv`: that file is written at seed time and would state + the version deployed back then, not the one the dump came from — and a + generation copied to another host carries its header along, a csv row does + not. + +Cluster dumps (`database = '*'`) are reported and skipped: `baudolo-restore` +has no subcommand that replays them. Database mode is local-only — the +credentials live in the target host's own `databases.csv`. + +### A single volume + +Run `files/python/recover.py` on the backed-up host to restore one volume's files: ``` recover.py //backup-docker-to-local///files @@ -257,7 +304,7 @@ recover.py //backup-docker-to-local// 1. Stop the consuming project (`docker compose down` / `docker stack rm `). 2. Run the script; it first starts the role's deployed backup unit (a fresh differential baudolo generation of every volume and database), resolves the volume's mountpoint and mirrors the snapshot into it (`rsync -a --delete`). `--no-safety-backup` skips the unit run when the target holds nothing worth saving. -3. Restore databases with `baudolo-restore postgres|mariadb ...`, then start the project again; on swarm, NFS-backed volumes are restored via `svc-bkp-nfs-2-local`'s `recover.py` instead (see below). +3. Restore the databases with the `--databases` mode above **while the project is still down**, then start it again; on swarm, NFS-backed volumes are restored via `svc-bkp-nfs-2-local`'s `recover.py` instead (see below). ## Credits diff --git a/roles/svc-bkp-volume-2-local/files/recover.py b/roles/svc-bkp-volume-2-local/files/python/recover.py similarity index 51% rename from roles/svc-bkp-volume-2-local/files/recover.py rename to roles/svc-bkp-volume-2-local/files/python/recover.py index 036b7a5a56..b1ecdc5873 100755 --- a/roles/svc-bkp-volume-2-local/files/recover.py +++ b/roles/svc-bkp-volume-2-local/files/python/recover.py @@ -1,19 +1,25 @@ #!/usr/bin/env python3 -"""Restore a docker volume's files from a backup-docker-to-local -generation. +# nocheck: mirrored-unit-test - subclasses utils.recovery.base and is exercised +# collectively by tests/unit/python/utils/recovery/test_role_recover_scripts.py; a +# per-role copy would assert the base class twice over +"""Restore a backup-docker-to-local generation: a volume's files, or the +generation's database dumps. -Runs the role's deployed backup unit first (the usual baudolo run, -storing a fresh differential generation of every volume and database), -resolves the volume's mountpoint and mirrors the snapshot into it -(``rsync -a --delete``). Stop the consuming project first. Database -restores stay with ``baudolo-restore postgres|mariadb``. +Both modes run the role's deployed backup unit first, unless +``--no-safety-backup`` says the target holds nothing worth saving. -Host-agnostic: with ``--docker-host ssh://user@host`` the volume is -inspected on that host and the snapshot is rsync-pushed onto its -mountpoint over ssh, recovering a volume on a remote machine. +Volume mode mirrors the snapshot into the volume's mountpoint +(``rsync -a --delete``); stop the consuming project first. With +``--docker-host ssh://user@host`` it works on a remote host. + +Database mode (``--databases``) replays every dump with +``baudolo-restore --empty`` - a single database through its engine's +subcommand, a ``pg_dumpall`` dump through ``cluster`` - and refuses while a +consumer runs. Local-only: the credentials live in the target's databases.csv. Usage: recover.py SOURCE_DIR VOLUME [--no-safety-backup] [--docker-host ENDPOINT] + recover.py --databases GENERATION_DIR [--no-safety-backup] """ from __future__ import annotations @@ -23,14 +29,18 @@ import subprocess import sys from pathlib import Path -_REPO_ROOT = Path(__file__).resolve().parents[3] # nocheck: project-root-import +_REPO_ROOT = Path(__file__).resolve().parents[4] # nocheck: project-root-import sys.path.insert(0, str(_REPO_ROOT)) +from utils.paths import FILE_DATABASE_SECRETS # noqa: E402 +from utils.recovery import databases # noqa: E402 from utils.recovery.base import DirectoryRecovery # noqa: E402 +UNIT_PATTERN = "svc-bkp-volume-2-local*.service" + class VolumeRecovery(DirectoryRecovery): - unit_pattern = "svc-bkp-volume-2-local*.service" + unit_pattern = UNIT_PATTERN def __init__( self, @@ -75,13 +85,32 @@ class VolumeRecovery(DirectoryRecovery): super().__init__(source_dir, target, service_backup=service_backup) +class DatabaseRecovery(DirectoryRecovery): + """Replay a generation's sql dumps, with the same safety-backup contract.""" + + unit_pattern = UNIT_PATTERN + + def __init__(self, generation_dir: str, *, service_backup: bool = True) -> None: + self.generation_dir = Path(generation_dir) + super().__init__(generation_dir, generation_dir, service_backup=service_backup) + + def restore(self) -> None: + databases.replay(self.generation_dir, FILE_DATABASE_SECRETS) + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "source_dir", + nargs="?", help="snapshot to restore from (e.g. //backup-docker-to-local///files)", ) - parser.add_argument("volume", help="docker volume name to restore into") + parser.add_argument("volume", nargs="?", help="docker volume name to restore into") + parser.add_argument( + "--databases", + metavar="GENERATION_DIR", + help="replay the generation's sql dumps instead of restoring one volume's files", + ) parser.add_argument( "--no-safety-backup", action="store_true", @@ -92,10 +121,30 @@ def main() -> int: help="remote docker endpoint (e.g. ssh://user@host) to recover the volume on another host", ) args = parser.parse_args() + service_backup = not args.no_safety_backup + + if args.databases: + if args.source_dir or args.volume: + parser.error( + "--databases takes the generation directory and no positionals" + ) + if args.docker_host: + parser.error( + "--databases is local-only: the credentials live in the target host's " + "own databases.csv, so run it on that host" + ) + try: + return DatabaseRecovery(args.databases, service_backup=service_backup).run() + except databases.RecoveryError as error: + print(f"FAIL: {error}", file=sys.stderr) + return 1 + + if not args.source_dir or not args.volume: + parser.error("volume mode needs SOURCE_DIR and VOLUME") return VolumeRecovery( args.source_dir, args.volume, - service_backup=not args.no_safety_backup, + service_backup=service_backup, docker_host=args.docker_host, ).run() diff --git a/roles/svc-bkp-volume-2-local/files/shell/ensure_subject_subvolume.sh b/roles/svc-bkp-volume-2-local/files/shell/ensure_subject_subvolume.sh index c1a268cbe2..5cf3d1c16c 100755 --- a/roles/svc-bkp-volume-2-local/files/shell/ensure_subject_subvolume.sh +++ b/roles/svc-bkp-volume-2-local/files/shell/ensure_subject_subvolume.sh @@ -13,65 +13,74 @@ DAEMON_TIMEOUT=120 report() { echo "ensure-subject-subvolume: $*"; } -command -v docker >/dev/null || { report "docker is not installed, nothing to convert"; exit 0; } # nocheck: raw-docker - runs on a bare host to verify a btrfs layout, where the wrapper does not exist +command -v docker >/dev/null || { + report "docker is not installed, nothing to convert" + exit 0 +} # nocheck: raw-docker - runs on a bare host to verify a btrfs layout, where the wrapper does not exist ROOT="$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || true)" # nocheck: raw-docker - see above -[[ -n "${ROOT}" && -d "${ROOT}" ]] || { report "the docker data root could not be resolved"; exit 0; } +[[ -n "${ROOT}" && -d "${ROOT}" ]] || { + report "the docker data root could not be resolved" + exit 0 +} if [[ "$(stat -c %i "${ROOT}")" == "${BTRFS_SUBVOLUME_INODE}" ]]; then - report "${ROOT} already is a subvolume root" - exit 0 + report "${ROOT} already is a subvolume root" + exit 0 fi if [[ "$(findmnt -no FSTYPE --target "${ROOT}")" != "btrfs" ]]; then - report "${ROOT} is not on btrfs, so no subvolume can carry it" - exit 0 + report "${ROOT} is not on btrfs, so no subvolume can carry it" + exit 0 fi -command -v btrfs >/dev/null || { report "the btrfs command is missing"; exit 0; } +command -v btrfs >/dev/null || { + report "the btrfs command is missing" + exit 0 +} STAGING="${ROOT}.premigration" if [[ -e "${STAGING}" ]]; then - report "FAIL: ${STAGING} exists; an earlier conversion did not finish, resolve it by hand" - exit 1 + report "FAIL: ${STAGING} exists; an earlier conversion did not finish, resolve it by hand" + exit 1 fi restore_and_fail() { - report "FAIL: $1; restoring the original tree" - systemctl stop docker.socket 2>/dev/null || true - systemctl stop docker - rm -rf "${ROOT}" - if [[ -d "${ROOT}" ]]; then - btrfs subvolume delete "${ROOT}" - fi - mv "${STAGING}" "${ROOT}" - systemctl start docker - exit 1 + report "FAIL: $1; restoring the original tree" + systemctl stop docker.socket 2>/dev/null || true # nocheck: shell-or-true -- the socket unit is absent on distros that ship docker without it; the docker unit below is stopped unconditionally + systemctl stop docker + rm -rf "${ROOT}" + if [[ -d "${ROOT}" ]]; then + btrfs subvolume delete "${ROOT}" + fi + mv "${STAGING}" "${ROOT}" + systemctl start docker + exit 1 } daemon_answers() { - local deadline=$(( SECONDS + DAEMON_TIMEOUT )) - while (( SECONDS < deadline )); do - if docker info >/dev/null 2>&1; then # nocheck: raw-docker - see above - return 0 - fi - sleep 2 - done - return 1 + local deadline=$((SECONDS + DAEMON_TIMEOUT)) + while ((SECONDS < deadline)); do + if docker info >/dev/null 2>&1; then # nocheck: raw-docker - see above + return 0 + fi + sleep 2 + done + return 1 } report "converting ${ROOT} into a btrfs subvolume; docker stops for the copy" -systemctl stop docker.socket 2>/dev/null || true +systemctl stop docker.socket 2>/dev/null || true # nocheck: shell-or-true -- the socket unit is absent on distros that ship docker without it; the docker unit below is stopped unconditionally systemctl stop docker mv "${ROOT}" "${STAGING}" btrfs subvolume create "${ROOT}" -cp -a --reflink=always "${STAGING}/." "${ROOT}/" \ - || restore_and_fail "the reflinked copy did not complete" +cp -a --reflink=always "${STAGING}/." "${ROOT}/" || + restore_and_fail "the reflinked copy did not complete" REMAINING="$(rsync -aHAXn --numeric-ids --itemize-changes "${STAGING}/" "${ROOT}/" | wc -l)" -if (( REMAINING > 0 )); then - restore_and_fail "${REMAINING} path(s) differ after the copy" +if ((REMAINING > 0)); then + restore_and_fail "${REMAINING} path(s) differ after the copy" fi systemctl start docker diff --git a/roles/svc-bkp-volume-2-local/files/test/.nocheck b/roles/svc-bkp-volume-2-local/files/test/.nocheck new file mode 100644 index 0000000000..65c4aed432 --- /dev/null +++ b/roles/svc-bkp-volume-2-local/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; grouped by purpose, screened and kept on 2026-08-21. diff --git a/roles/svc-bkp-volume-2-local/files/test/README.md b/roles/svc-bkp-volume-2-local/files/test/README.md index fa44ddb92b..4cc541b728 100644 --- a/roles/svc-bkp-volume-2-local/files/test/README.md +++ b/roles/svc-bkp-volume-2-local/files/test/README.md @@ -14,17 +14,34 @@ probe runs first in both, because it depends on nothing the backup produces. flowchart TD ENV["test-e2e-cli renders test.env.j2
and calls test.sh"] --> HOST{"BKP_TEST_IS_STACK_HOST"} HOST -->|false| SKIP["exit 0
the role deploys on the stack host only"] - HOST -->|true| PROBE["snapshot_probe.sh
runs on every deploy"] + HOST -->|"true, but a swarm node"| SWARMSKIP["probes + backup verification,
then exit 0 before the marker is seeded"] + HOST -->|true| PROBE["probe/snapshot.sh
runs on every deploy"] PROBE --> WAIT["wait for the backup unit to terminate,
then force one post-deploy run"] WAIT --> COUNT{"generations stored"} COUNT -->|none| FAIL["fail: nothing was backed up"] COUNT -->|"some, no backup subjects on the host"| EMPTY["exit 0
a stamped empty generation is the expected outcome"] COUNT -->|some| PASS{"ASYNC_ENABLED"} - PASS -->|true| ASYNC["verify_backup.sh
requires two differential generations"] - PASS -->|false| SYNC["verify_backup.sh
restore_cycle.sh
db_restore.sh"] + PASS -->|true| ASYNC["verify/backup.sh
requires two differential generations"] + PASS -->|false| SYNC["verify/backup.sh
seed/marker.py seed + one more backup
restore_cycle.sh
sys-ctl-hlth-container's own script"] ``` -## `snapshot_probe.sh` +The sync pass is the whole disaster drill against the host this role deploys on +(`BKP_TEST_IS_STACK_HOST`), in one sequence: back up, seed the marker, back up +again so the tested generation carries it, take every project down, restore +through the recover chain, require the marker and every recorded container +back, and finally let the host's own container health service judge. + +That last step is deliberately the deployed +[`sys-ctl-hlth-container` script](../../../sys-ctl-hlth-container/files/shell/script.sh) +rather than a check of the drill's own: it is what watches the host in +production, it knows swarm services, and it dumps 200 log lines per sick +container. It is invoked as a script, not as its systemd unit — the unit's +`OnFailure` starts the soft-repair service, and a drill that repairs what it +found has stopped measuring. It cannot replace the drill's own wait either: a +container that never came back is in no `container ps` filter, so only the +recorded-set check sees it. + +## `probe/snapshot.sh` Drives `baudolo-snapshot`, the launcher that decides per run whether baudolo may capture the volumes from a filesystem snapshot instead of copying the live tree. @@ -37,7 +54,7 @@ touched, and no state survives the run. ```mermaid flowchart TD - START["snapshot_probe.sh"] --> DEPLOYED{"launcher executable?"} + START["probe/snapshot.sh"] --> DEPLOYED{"launcher executable?"} DEPLOYED -->|no| BAD["fail: the unit's ExecStart is missing"] DEPLOYED -->|yes| NEVER["--mode never must hand argv through byte-identically"] NEVER --> TOOLS{"root, mkfs.btrfs, losetup,
a free loop device?"} @@ -62,7 +79,7 @@ It resolves `baudolo-snapshot` from `PATH`, so it tests whatever the role deployed: ```bash -sudo bash roles/svc-bkp-volume-2-local/files/test/snapshot_probe.sh +sudo bash roles/svc-bkp-volume-2-local/files/test/probe/snapshot.sh ``` Without `sudo` the first two assertions still run and the matrix reports `SKIP`, @@ -75,7 +92,7 @@ a throwaway privileged container and run it there. Note that a container's matrix reports `SKIP` unless they are created first (`mknod /dev/loop0 b 7 0`, …) or the host's `/dev` is bind-mounted in. -## `verify_backup.sh` +## `verify/backup.sh` Requires the newest generation to hold real payload — a volume counts when it has a `files/` tree or a non-empty `sql` dump. In the async pass it additionally @@ -100,29 +117,98 @@ flowchart TD The destructive drill, sync pass only. It proves the backup is restorable rather than merely present — the property a backup exists for. +The drill owns the **lifecycle** and nothing else. Every restore is +`python3 -m cli.administration.recover`, the same command an operator runs after +a real loss, so the drill exercises that tool instead of a second implementation +of it. + ```mermaid flowchart TD - SWARM{"swarm node?"} -->|yes| SK["skip: the down/up cycle races the reconciler"] - SWARM -->|no| DOWN["compose down every running project"] - DOWN --> WIPE["wipe each backed-up volume"] - WIPE --> RESTORE["baudolo-restore from the newest generation"] - RESTORE --> UP["compose up the projects again"] - UP --> HEALTH{"every previously running container
healthy, or running when it has no healthcheck?"} + SWARM{"swarm node?"} -->|yes| SK["skip: the compose down/up cycle races the reconciler
swarm is drilled by scripts/tests/deploy/swarm/routine/backup"] + SWARM -->|no| REC["record running containers, their projects and volumes,
plus launcher-run containers holding a backed-up volume"] + REC --> DOWN["compose down every project, stop the launcher containers"] + DOWN --> RM["container volume rm every mounted volume
except the engines' own data directories"] + RM --> CREATE["compose create every project
so the volumes exist again, empty"] + CREATE --> BLANK["seed/marker.py blank:
drop the live marker, only a restore returns it"] + BLANK --> VOL["recover volume <dir> localhost, per files/ tree"] + VOL --> DBUP["compose up only the projects that own a dump volume
wait for their healthcheck"] + DBUP --> DB["recover database <generation> localhost"] + DB --> UP["compose up the remaining projects"] + UP --> HEALTH{"every recorded container
healthy, or running when it has no healthcheck?"} HEALTH -->|no| FAIL["fail: the restore did not bring the host back"] HEALTH -->|yes| DONE["restore cycle passed"] ``` -## `db_restore.sh` +Which project holds a dump is read from the containers themselves, before the +host goes down: each running container's mounts are recorded, and a dump's volume +names its owner. No image is matched, and the database's engine is resolved by +the chain from the repository's service definitions. -Replays the text dumps into the databases the previous step restarted, using the -credentials from `databases.csv`. +**Every mounted volume is discarded**, not only the backed-up ones. A volume +declared `backup: false` claims to be disposable; a drill that spares it never +tests the claim. If its service cannot rebuild it, the health gate goes red — +that is the finding, not a false alarm. The single exception is the data +directory of an engine whose dump is about to be replayed: it carries the +database and its role, which the deploy creates and the container does not, so +wiping it would leave `baudolo-restore --empty -d ` with nothing to connect +to and the drill would fail at itself instead of at a defect. -```mermaid -flowchart TD - CSV["databases.csv
instance;database;username;password"] --> ROWS{"row kind"} - ROWS -->|"database = '*' (cluster dump)"| SKIPPED["skipped visibly
baudolo-restore has no cluster replay path"] - ROWS -->|concrete database| REPLAY["baudolo-restore postgres/mariadb --empty
against the running container"] - REPLAY --> RESULT{"replay exit"} - RESULT -->|non-zero| FAIL["fail: the dump is not replayable"] - RESULT -->|zero| DONE["dump replay passed"] -``` +**A generation holding a cluster dump fails the drill.** `baudolo-restore` has +no subcommand that replays one, so that database cannot be proven restorable — +the honest verdict is a red, not a silent skip. + +**Not every subject is a compose project.** Discourse is built by its own +`./launcher rebuild` ([handlers/stack_host.yml](../../../web-app-discourse/handlers/stack_host.yml)) +and runs as a plain container with no compose label. The drill treats such a +container as a subject whenever it mounts a volume this generation backed up: +it is stopped with everything else and started again at the end, and its return +is asserted like any other. Left running it would take an `rsync --delete` into +its live data directory, and the chain's consumer check — which reads compose +labels — would not see it, so the dump replay would race it exactly like the +zammad failure this whole change came from. + +**An engine inside its consumer's project** — matrix with its own postgres, for +instance — is started service by service rather than as a whole project, because +bringing the project up would start the consumer and the chain refuses to replay +while one runs. The discriminator is the dump's volume name against its project +name: equal for the central engines (`postgres` in project `postgres`), +different for a per-app one (`matrix_database` in project `matrix`). + +**The app volumes are really discarded** (`down --volumes`) and re-created empty +by `compose create`, so what comes back can only come from the backup. The +database projects go down without `--volumes` on purpose: their data directory +carries the database itself, which the deploy creates and the container does +not, so a wiped datadir would leave `baudolo-restore --empty -d ` with +nothing to connect to. The database half loses no proof by it — the pre-clean +drops the schema including the marker table, and only the dump brings it back. + +The order is a precondition, not a preference. `baudolo-restore --empty` +pre-cleans the schema in one psql session and replays in the next; a booting +consumer recreates it in between and the dump's own `CREATE TABLE` fails — which +is how zammad turned this drill red with `relation "ar_internal_metadata" +already exists`. The chain refuses the replay while a consumer runs, so a drill +that got the order wrong would fail loudly instead of flaking. + +Bringing the apps up **after** the replay also means their healthcheck now runs +against the restored dump, rather than against the data the drill is about to +overwrite. + +## `seed/marker.py` + +Health proves the host boots, not that it holds its data. Before the backup the +drill seeds one token into every subject — a `.dr-drill-marker` file at the root +of each backed-up volume, a row in `infinito_dr_marker` in each database with a +dump — then forces one more backup run so the generation under test carries it, +and afterwards requires every one of them back. A volume silently dropped or a +dump replayed empty fails here; before, both passed. + +Verification runs right after the replay and before the apps start, so "the +restore brought it back" stays separate from "an app overwrote it", and a +`clean` pass then takes the token out of the live payload again. + +The marker file carries the same name as the swarm drill's +(`scripts/tests/deploy/swarm/routine/backup/base.sh`) — one name for one +concept. The implementations stay apart on purpose: the swarm drill follows a +single token across five hops on four machines from the controller, which has +nothing in common with marking every subject of one host beyond the three lines +that write a file and read it back. diff --git a/roles/svc-bkp-volume-2-local/files/test/db_restore.sh b/roles/svc-bkp-volume-2-local/files/test/db_restore.sh deleted file mode 100755 index c17a94ddfa..0000000000 --- a/roles/svc-bkp-volume-2-local/files/test/db_restore.sh +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env bash -# Replay the text dumps of the backup generation into the running -# databases via baudolo-restore postgres|mariadb --empty. Requires the -# containers restarted by restore_cycle.sh and credentials from -# databases.csv (semicolon-separated: instance;database;username;password). -# Cluster dumps (.cluster.backup.sql, database='*') are skipped -# visibly: baudolo-restore has no cluster replay path. -set -euo pipefail - -: "${BKP_TEST_BACKUPS_DIR:?}" -: "${BKP_TEST_DATABASES_CSV:?}" -: "${BKP_TEST_RESTORE_BIN:?}" -: "${MACHINE_HASH:?}" -: "${REPO_DIR:?}" -: "${REPO_NAME:?}" -: "${NEWEST_GENERATION:?}" - -GEN_DIR="${REPO_DIR}/${NEWEST_GENERATION}" - -if [[ ! -f "${BKP_TEST_DATABASES_CSV}" ]]; then - echo "FAIL: databases csv missing at ${BKP_TEST_DATABASES_CSV}" - exit 1 -fi - -mapfile -t CLUSTER_DUMPS < <(find "${GEN_DIR}" -mindepth 3 -maxdepth 3 -type f -path '*/sql/*.cluster.backup.sql' | sort) -for cluster_dump in "${CLUSTER_DUMPS[@]}"; do - echo "SKIP: cluster dump ${cluster_dump##*/} (database='*') has no single-db replay path" -done - -mapfile -t SQL_FILES < <(find "${GEN_DIR}" -mindepth 3 -maxdepth 3 -type f -path '*/sql/*.backup.sql' ! -name '*.cluster.backup.sql' | sort) -if (( ${#SQL_FILES[@]} < 1 )); then - echo "OK: generation ${NEWEST_GENERATION} carries no single-db sql dumps; nothing to replay" - exit 0 -fi -echo "Replaying ${#SQL_FILES[@]} sql dump(s) from generation ${NEWEST_GENERATION}" - -RESTORED=0 -for sql_file in "${SQL_FILES[@]}"; do - volume="$(basename "$(dirname "$(dirname "${sql_file}")")")" - db_name="$(basename "${sql_file}" .backup.sql)" - - row="$(awk -F';' -v db="${db_name}" 'NR > 1 && $2 == db { print; exit }' "${BKP_TEST_DATABASES_CSV}")" - if [[ -z "${row}" ]]; then - echo "SKIP: no databases.csv row for '${db_name}' (volume ${volume})" - continue - fi - IFS=';' read -r _instance _database db_user db_password <<<"${row}" - - container="$(container ps --filter "volume=${volume}" --format '{{.Names}}' | head -n1)" - if [[ -z "${container}" ]]; then - echo "SKIP: no running container mounts volume ${volume}" - continue - fi - - image="$(container inspect --type container -f '{{.Config.Image}}' "${container}")" - case "${image}" in - *postgres* | *postgis*) engine="postgres" ;; - *mariadb* | *mysql*) engine="mariadb" ;; - *) - echo "SKIP: cannot derive db engine from image '${image}' (container ${container})" - continue - ;; - esac - - "${BKP_TEST_RESTORE_BIN}" "${engine}" "${volume}" "${MACHINE_HASH}" "${NEWEST_GENERATION}" \ - --backups-dir "${BKP_TEST_BACKUPS_DIR}" \ - --repo-name "${REPO_NAME}" \ - --container "${container}" \ - --db-name "${db_name}" \ - --db-user "${db_user}" \ - --db-password "${db_password}" \ - --empty - echo "OK: replayed ${engine} dump '${db_name}' into ${container}" - RESTORED=$((RESTORED + 1)) -done - -if (( RESTORED < 1 )); then - echo "FAIL: sql dumps present but none could be replayed" - exit 1 -fi -echo "OK: ${RESTORED} database dump(s) replayed" diff --git a/roles/svc-bkp-volume-2-local/files/test/snapshot_probe.sh b/roles/svc-bkp-volume-2-local/files/test/probe/snapshot.sh similarity index 100% rename from roles/svc-bkp-volume-2-local/files/test/snapshot_probe.sh rename to roles/svc-bkp-volume-2-local/files/test/probe/snapshot.sh diff --git a/roles/svc-bkp-volume-2-local/files/test/subvolume_probe.sh b/roles/svc-bkp-volume-2-local/files/test/probe/subvolume.sh similarity index 62% rename from roles/svc-bkp-volume-2-local/files/test/subvolume_probe.sh rename to roles/svc-bkp-volume-2-local/files/test/probe/subvolume.sh index cee3fd4b9c..3b1ed03704 100755 --- a/roles/svc-bkp-volume-2-local/files/test/subvolume_probe.sh +++ b/roles/svc-bkp-volume-2-local/files/test/probe/subvolume.sh @@ -8,28 +8,28 @@ CONVERTER=baudolo-subject-subvolume BTRFS_SUBVOLUME_INODE=256 if ! command -v "${CONVERTER}" >/dev/null; then - echo "FAIL: ${CONVERTER} is not on PATH" - exit 1 + echo "FAIL: ${CONVERTER} is not on PATH" + exit 1 fi echo "OK: ${CONVERTER} is deployed and executable" if [[ "$(id -u)" != "0" ]] || ! command -v mkfs.btrfs >/dev/null || ! command -v losetup >/dev/null; then - echo "SKIP: no root or no btrfs tooling; the conversion needs both" - exit 0 + echo "SKIP: no root or no btrfs tooling; the conversion needs both" + exit 0 fi WORK="$(mktemp -d)" LOOP="" cleanup() { - if mountpoint -q "${WORK}/mnt"; then - umount "${WORK}/mnt" - fi - if [[ -n "${LOOP}" ]]; then - losetup -d "${LOOP}" 2>/dev/null || true - fi - rm -rf "${WORK}" - return 0 + if mountpoint -q "${WORK}/mnt"; then + umount "${WORK}/mnt" + fi + if [[ -n "${LOOP}" ]]; then + losetup -d "${LOOP}" 2>/dev/null || true # nocheck: shell-or-true -- the loop device is already detached when the probe failed before attaching it + fi + rm -rf "${WORK}" + return 0 } trap cleanup EXIT @@ -38,73 +38,73 @@ mkfs.btrfs -q "${WORK}/img" mkdir -p "${WORK}/mnt" "${WORK}/bin" if ! LOOP="$(losetup --find --show "${WORK}/img" 2>/dev/null)"; then - echo "SKIP: no free loop device for the conversion" - exit 0 + echo "SKIP: no free loop device for the conversion" + exit 0 fi mount -t btrfs "${LOOP}" "${WORK}/mnt" ROOT="${WORK}/mnt/docker" mkdir -p "${ROOT}/volumes/probe_vol/_data" "${ROOT}/image/overlay2" -head -c 65536 /dev/urandom > "${ROOT}/volumes/probe_vol/_data/payload.bin" -echo marker > "${ROOT}/image/overlay2/layer.txt" +head -c 65536 /dev/urandom >"${ROOT}/volumes/probe_vol/_data/payload.bin" +echo marker >"${ROOT}/image/overlay2/layer.txt" ln -s payload.bin "${ROOT}/volumes/probe_vol/_data/link" BEFORE="$(find "${ROOT}" | sort | sha256sum)" CHECKSUM="$(sha256sum "${ROOT}/volumes/probe_vol/_data/payload.bin" | cut -d' ' -f1)" -printf '#!/bin/sh\necho %s\n' "${ROOT}" > "${WORK}/bin/docker" -printf '#!/bin/sh\nexit 0\n' > "${WORK}/bin/systemctl" +printf '#!/bin/sh\necho %s\n' "${ROOT}" >"${WORK}/bin/docker" +printf '#!/bin/sh\nexit 0\n' >"${WORK}/bin/systemctl" chmod 755 "${WORK}/bin/docker" "${WORK}/bin/systemctl" export PATH="${WORK}/bin:${PATH}" if [[ "$(stat -c %i "${ROOT}")" == "${BTRFS_SUBVOLUME_INODE}" ]]; then - echo "FAIL: the fixture is already a subvolume, the conversion would be a no-op" - exit 1 + echo "FAIL: the fixture is already a subvolume, the conversion would be a no-op" + exit 1 fi "${CONVERTER}" if [[ "$(stat -c %i "${ROOT}")" != "${BTRFS_SUBVOLUME_INODE}" ]]; then - echo "FAIL: ${ROOT} is still a plain directory after the conversion" - exit 1 + echo "FAIL: ${ROOT} is still a plain directory after the conversion" + exit 1 fi echo "OK: the data root is a btrfs subvolume root now" if [[ "$(find "${ROOT}" | sort | sha256sum)" != "${BEFORE}" ]]; then - echo "FAIL: the tree differs after the conversion" - find "${ROOT}" | sort - exit 1 + echo "FAIL: the tree differs after the conversion" + find "${ROOT}" | sort + exit 1 fi echo "OK: every path survived the conversion" if [[ "$(sha256sum "${ROOT}/volumes/probe_vol/_data/payload.bin" | cut -d' ' -f1)" != "${CHECKSUM}" ]]; then - echo "FAIL: the payload changed during the conversion" - exit 1 + echo "FAIL: the payload changed during the conversion" + exit 1 fi echo "OK: the payload is byte-identical" if [[ ! -L "${ROOT}/volumes/probe_vol/_data/link" ]]; then - echo "FAIL: the symlink was dereferenced instead of copied" - exit 1 + echo "FAIL: the symlink was dereferenced instead of copied" + exit 1 fi echo "OK: the symlink stayed a symlink" if [[ -e "${ROOT}.premigration" ]]; then - echo "FAIL: ${ROOT}.premigration was left behind" - exit 1 + echo "FAIL: ${ROOT}.premigration was left behind" + exit 1 fi echo "OK: no staging tree is left behind" if ! btrfs subvolume snapshot -r "${ROOT}" "${ROOT}/.probe-snapshot" >/dev/null; then - echo "FAIL: the converted root cannot be snapshotted, which was the whole point" - exit 1 + echo "FAIL: the converted root cannot be snapshotted, which was the whole point" + exit 1 fi btrfs subvolume delete "${ROOT}/.probe-snapshot" >/dev/null echo "OK: the converted root can actually be snapshotted" OUTPUT="$("${CONVERTER}")" if [[ "${OUTPUT}" != *"already is a subvolume root"* ]]; then - echo "FAIL: the second run did not report the root as already converted: ${OUTPUT}" - exit 1 + echo "FAIL: the second run did not report the root as already converted: ${OUTPUT}" + exit 1 fi echo "OK: a second run is a no-op" diff --git a/roles/svc-bkp-volume-2-local/files/test/restore_cycle.sh b/roles/svc-bkp-volume-2-local/files/test/restore_cycle.sh index d5abf0429b..92e484dae8 100755 --- a/roles/svc-bkp-volume-2-local/files/test/restore_cycle.sh +++ b/roles/svc-bkp-volume-2-local/files/test/restore_cycle.sh @@ -1,26 +1,62 @@ #!/usr/bin/env bash -# Disaster-recovery drill against the newest backup generation: -# compose-down every running project, wipe each backed-up volume, restore -# it via baudolo-restore, compose-up the projects again and require every -# previously running container healthy (or running when it defines no -# healthcheck). +# Disaster-recovery drill: record what runs, take the host down, hand the +# generation to the recover chain, bring the host back and require each +# recorded container healthy (or running when it defines no healthcheck). +# +# Databases come back last with only their engine service up - the replay +# pre-cleans in one psql session and a booting consumer would recreate the +# schema before the dump's CREATE TABLE lands. The engine's service name comes +# from its compose label: no fixed name covers both `postgres` (project +# postgres, volume postgres_data) and bigbluebutton (project bigbluebutton, +# service postgres). +# +# Every mounted volume is emptied, including those declared `backup: false` - +# that claim of disposability is what the drill tests. Emptied, not removed: +# docker refuses to remove a volume a container still references, and a +# container outside compose is only stopped here; re-creating a removed volume +# would also drop its driver options. An engine volume whose dump is about to +# be replayed is spared, because `pg_dump -d ` writes no CREATE ROLE or +# CREATE DATABASE and initdb would leave nothing to replay into. +# +# Discourse carries no compose label but is a subject when it holds a volume. set -euo pipefail -: "${BKP_TEST_BACKUPS_DIR:?}" -: "${BKP_TEST_RESTORE_BIN:?}" : "${BKP_TEST_HEALTH_TIMEOUT:?}" -: "${MACHINE_HASH:?}" +: "${BKP_TEST_PYTHON:?}" +: "${BKP_TEST_REPO_ROOT:?}" +: "${BKP_TEST_SCRATCH_IMAGE:?}" +: "${DR_TOKEN:?}" : "${REPO_DIR:?}" -: "${REPO_NAME:?}" : "${NEWEST_GENERATION:?}" GEN_DIR="${REPO_DIR}/${NEWEST_GENERATION}" +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +TORN_DOWN_MARKER="${BKP_TEST_REPO_ROOT}/.stack-torn-down" +# shellcheck disable=SC2016 +NETWORK_TEMPLATE='{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}' if [[ "$(container info --format '{{.Swarm.LocalNodeState}}' 2>/dev/null)" == "active" ]]; then - echo "SKIP: swarm node detected; the compose down/up cycle races the orchestrator's reconciler, the drill only supports compose hosts" - exit 0 + echo "FAIL: swarm node; test.sh decides this and stops before seeding, so reaching here means the script was invoked directly - the down/up cycle would race the orchestrator" + exit 1 fi +if [[ ! -d "${BKP_TEST_REPO_ROOT}/cli/administration/recover" ]]; then + echo "FAIL: no repository checkout at ${BKP_TEST_REPO_ROOT} on this host; the drill restores through the recover CLI, which runs from the checkout" + exit 1 +fi + +recover() { + PYTHONPATH="${BKP_TEST_REPO_ROOT}" python3 -m cli.administration.recover \ + "$1" "$2" localhost --no-safety-backup +} + +empty_volume() { + # shellcheck disable=SC2016 + container run --rm --mount "type=volume,src=$1,dst=/subject" \ + "${BKP_TEST_SCRATCH_IMAGE}" \ + sh -c 'find /subject -mindepth 1 -delete && [ -z "$(ls -A /subject)" ]' +} + SELF_NAME="" SELF_PROJECT="" if container inspect --type container "$(hostname)" >/dev/null 2>&1; then @@ -29,28 +65,55 @@ if container inspect --type container "$(hostname)" >/dev/null 2>&1; then echo "OK: excluding own container '${SELF_NAME}' (project '${SELF_PROJECT}') from the cycle" fi -mapfile -t RUNNING < <(container ps --format '{{.Names}}\t{{.Label "com.docker.compose.project"}}' | - awk -F'\t' -v self="${SELF_PROJECT}" -v selfname="${SELF_NAME}" \ - '$1 != selfname && $2 != "" && (self == "" || $2 != self) { print $1 }') +declare -A PROJECT_DIR=() +declare -A VOLUME_PROJECT=() +declare -A VOLUME_CONTAINER=() +declare -A MOUNTED=() +RUNNING=() +while IFS='|' read -r name project workdir; do + if [[ -z "${project}" ]] || [[ "${name}" == "${SELF_NAME}" ]] || [[ "${project}" == "${SELF_PROJECT}" ]]; then + continue + fi + RUNNING+=("${name}") + PROJECT_DIR["${project}"]="${workdir}" + for volume in $(container inspect --type container -f '{{range .Mounts}}{{if .Name}}{{.Name}} {{end}}{{end}}' "${name}"); do + VOLUME_PROJECT["${volume}"]="${project}" + VOLUME_CONTAINER["${volume}"]="${name}" + MOUNTED["${volume}"]=1 + done +done < <(container ps --format '{{.Names}}|{{.Label "com.docker.compose.project"}}|{{.Label "com.docker.compose.project.working_dir"}}') + if (( ${#RUNNING[@]} < 1 )); then echo "FAIL: no running compose containers before the restore cycle" exit 1 fi echo "OK: ${#RUNNING[@]} running container(s) recorded" -declare -A PROJECT_DIR -while IFS=$'\t' read -r project workdir; do - if [[ -z "${project}" ]] || [[ "${project}" == "${SELF_PROJECT}" ]]; then +BACKED_UP_VOLUMES=" $(find "${GEN_DIR}" -mindepth 2 -maxdepth 2 -type d \( -name files -o -name sql \) -printf '%h\n' | xargs -rn1 basename | sort -u | tr '\n' ' ')" +LOOSE=() +while IFS='|' read -r name project; do + if [[ -n "${project}" ]] || [[ "${name}" == "${SELF_NAME}" ]]; then continue fi - PROJECT_DIR["${project}"]="${workdir}" -done < <(container ps --filter label=com.docker.compose.project \ - --format '{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.project.working_dir"}}' | - sort -u) -if (( ${#PROJECT_DIR[@]} < 1 )); then - echo "FAIL: no compose projects found to cycle" - exit 1 + loose_volumes=() + for volume in $(container inspect --type container -f '{{range .Mounts}}{{if .Name}}{{.Name}} {{end}}{{end}}' "${name}"); do + loose_volumes+=("${volume}") + done + for volume in "${loose_volumes[@]-}"; do + if [[ -n "${volume}" ]] && [[ "${BACKED_UP_VOLUMES}" == *" ${volume} "* ]]; then + LOOSE+=("${name}") + RUNNING+=("${name}") + for owned in "${loose_volumes[@]}"; do + MOUNTED["${owned}"]=1 + done + break + fi + done +done < <(container ps --format '{{.Names}}|{{.Label "com.docker.compose.project"}}') +if (( ${#LOOSE[@]} > 0 )); then + echo "OK: ${#LOOSE[@]} container(s) outside compose hold backed-up volumes: ${LOOSE[*]}" fi + mapfile -t PROJECTS < <(printf '%s\n' "${!PROJECT_DIR[@]}" | sort) for project in "${PROJECTS[@]}"; do if [[ ! -d "${PROJECT_DIR[${project}]}" ]]; then @@ -60,72 +123,211 @@ for project in "${PROJECTS[@]}"; do done echo "OK: ${#PROJECTS[@]} compose project(s) recorded: ${PROJECTS[*]}" +DB_PROJECTS=() +declare -A DB_SERVICE=() +while IFS= read -r sql_file; do + dump_volume="$(basename "$(dirname "$(dirname "${sql_file}")")")" + owner="${VOLUME_PROJECT[${dump_volume}]:-}" + if [[ -z "${owner}" ]]; then + echo "FAIL: no running container mounts volume ${dump_volume}, which holds $(basename "${sql_file}"); its database service is not part of this host" + exit 1 + fi + engine_container="${VOLUME_CONTAINER[${dump_volume}]}" + engine_service="$(container inspect --type container -f '{{index .Config.Labels "com.docker.compose.service"}}' "${engine_container}")" + if [[ -z "${engine_service}" ]]; then + echo "FAIL: ${engine_container} mounts ${dump_volume} but carries no compose service label, so the engine cannot be started without its consumers" + exit 1 + fi + DB_SERVICE["${owner}"]="${engine_service}" + if [[ " ${DB_PROJECTS[*]-} " != *" ${owner} "* ]]; then + DB_PROJECTS+=("${owner}") + fi +done < <(find "${GEN_DIR}" -mindepth 3 -maxdepth 3 -type f -path '*/sql/*.backup.sql' | sort) +echo "OK: ${#DB_PROJECTS[@]} database project(s) hold the dumps: ${DB_PROJECTS[*]-none}" +for project in "${DB_PROJECTS[@]}"; do + echo "OK: only service '${DB_SERVICE[${project}]}' of project ${project} comes up for the replay" +done -echo "Stopping compose projects..." +mapfile -t VOLUME_DIRS < <(find "${GEN_DIR}" -mindepth 2 -maxdepth 2 -type d -name files | sort) +RESTORABLE=() +for volume_dir in "${VOLUME_DIRS[@]}"; do + RESTORABLE+=("$(basename "$(dirname "${volume_dir}")")") +done +echo "OK: ${#RESTORABLE[@]} volume(s) come back from this generation: ${RESTORABLE[*]-none}" + +DUMP_VOLUMES=" $(find "${GEN_DIR}" -mindepth 2 -maxdepth 2 -type d -name sql -printf '%h\n' | xargs -rn1 basename | sort -u | tr '\n' ' ')" +DISCARD=() +SPARED=() +for volume in "${!MOUNTED[@]}"; do + if [[ "${DUMP_VOLUMES}" != *" ${volume} "* ]]; then + DISCARD+=("${volume}") + else + SPARED+=("${volume}") + fi +done +mapfile -t DISCARD < <(printf '%s\n' "${DISCARD[@]-}" | grep -v '^$' | sort) +mapfile -t SPARED < <(printf '%s\n' "${SPARED[@]-}" | grep -v '^$' | sort) +echo "OK: ${#DISCARD[@]} volume(s) get emptied: ${DISCARD[*]-none}" +if (( ${#SPARED[@]} > 0 )); then + echo "NOTE: ${#SPARED[@]} engine data director(ies) are NOT emptied: ${SPARED[*]}" + echo "NOTE: their dumps carry no CREATE ROLE and no CREATE DATABASE, so an emptied engine would come back from initdb with nothing to replay into; this drill proves the dump, not the engine's own volume" +fi +UNRESTORABLE=() +for volume in "${DISCARD[@]-}"; do + if [[ -n "${volume}" ]] && [[ " ${RESTORABLE[*]-} " != *" ${volume} "* ]]; then + UNRESTORABLE+=("${volume}") + fi +done +if (( ${#UNRESTORABLE[@]} > 0 )); then + echo "NOTE: ${#UNRESTORABLE[@]} of them are not in the backup and must be rebuilt by their own service: ${UNRESTORABLE[*]}" +fi + +declare -A NETWORKS=() +for name in "${RUNNING[@]}"; do + NETWORKS["${name}"]="$(container inspect --type container -f "${NETWORK_TEMPLATE}" "${name}")" +done +echo "OK: network attachments recorded for ${#NETWORKS[@]} container(s)" + +# Any exit between this teardown and the final restart leaves the host with +# its subjects down, which is why the marker is written from a trap. +mark_torn_down() { + local code=$? + if (( code != 0 )); then + printf 'the backup drill tore this host down and exited %s before restarting it\n' \ + "${code}" >"${TORN_DOWN_MARKER}" + echo "FAIL: subjects are left down; recorded in ${TORN_DOWN_MARKER}" >&2 + fi +} +trap mark_torn_down EXIT + +echo "Stopping every subject of this host..." for project in "${PROJECTS[@]}"; do compose --chdir "${PROJECT_DIR[${project}]}" --project "${project}" down --remove-orphans done +for name in "${LOOSE[@]-}"; do + if [[ -n "${name}" ]]; then + container stop "${name}" + fi +done for name in "${RUNNING[@]}"; do if [[ "$(container inspect --type container -f '{{.State.Status}}' "${name}" 2>/dev/null || echo gone)" == "running" ]]; then - echo "FAIL: ${name} still running after compose down" + echo "FAIL: ${name} still running after the teardown" exit 1 fi done -echo "OK: all compose projects down" +echo "OK: every subject of this host is down" -mapfile -t VOLUMES < <(find "${GEN_DIR}" -mindepth 2 -maxdepth 2 -type d -name files -printf '%h\n' | sort | xargs -rn1 basename) -echo "Restoring ${#VOLUMES[@]} volume(s) from generation ${NEWEST_GENERATION}" - -for volume in "${VOLUMES[@]}"; do - if ! container volume inspect "${volume}" >/dev/null 2>&1; then - echo "SKIP: volume ${volume} does not exist on this host" - continue +for volume in "${DISCARD[@]-}"; do + if [[ -n "${volume}" ]]; then + empty_volume "${volume}" fi - _wipe_mp="$(container volume inspect --format '{{ .Mountpoint }}' "${volume}")" - rm -rf "${_wipe_mp:?}"/* "${_wipe_mp}"/.[!.]* "${_wipe_mp}"/..?* 2>/dev/null || true - if [[ -n "$(find "${_wipe_mp}" -mindepth 1 -print -quit)" ]]; then - echo "FAIL: volume ${volume} not empty after wipe" +done +echo "OK: ${#DISCARD[@]} volume(s) emptied and proven empty" + +for project in "${PROJECTS[@]}"; do + compose --chdir "${PROJECT_DIR[${project}]}" --project "${project}" create +done +for volume in "${RESTORABLE[@]-}"; do + if [[ -n "${volume}" ]] && ! container volume inspect "${volume}" >/dev/null 2>&1; then + echo "FAIL: volume ${volume} is in the generation but does not exist on this host, so its restore would have nowhere to land" exit 1 fi - "${BKP_TEST_RESTORE_BIN}" files "${volume}" "${MACHINE_HASH}" "${NEWEST_GENERATION}" \ - --backups-dir "${BKP_TEST_BACKUPS_DIR}" \ - --repo-name "${REPO_NAME}" - echo "OK: restored ${volume}" done -echo "Starting compose projects..." -up_failed=0 -for round in 1 2 3; do - up_failed=0 - declare -A UP_PID=() - for project in "${PROJECTS[@]}"; do - compose --chdir "${PROJECT_DIR[${project}]}" --project "${project}" up -d & - UP_PID["${project}"]=$! - done - for project in "${!UP_PID[@]}"; do - if ! wait "${UP_PID[${project}]}"; then - echo "WARN: up failed for ${project} (round ${round})" - up_failed=$((up_failed + 1)) +"${BKP_TEST_PYTHON}" "${DIR}/seed/marker.py" blank "${GEN_DIR}" "${DR_TOKEN}" + +echo "Restoring ${#VOLUME_DIRS[@]} volume(s) from generation ${NEWEST_GENERATION}" +for volume_dir in "${VOLUME_DIRS[@]}"; do + recover volume "${volume_dir}" +done + +start_projects() { + local round project up_failed + local -A pids + local -a only + for round in 1 2 3; do + up_failed=0 + pids=() + for project in "$@"; do + only=() + if [[ -n "${DB_SERVICE[${project}]:-}" ]]; then + only=("${DB_SERVICE[${project}]}") + fi + compose --chdir "${PROJECT_DIR[${project}]}" --project "${project}" up -d "${only[@]}" & + pids["${project}"]=$! + done + for project in "${!pids[@]}"; do + if ! wait "${pids[${project}]}"; then + echo "WARN: up failed for ${project} (round ${round})" + up_failed=$((up_failed + 1)) + fi + done + if (( up_failed == 0 )); then + return 0 fi + sleep 60 done - if (( up_failed == 0 )); then - break - fi - sleep 60 -done -if (( up_failed > 0 )); then echo "FAIL: ${up_failed} project(s) failed to start after 3 rounds" exit 1 +} + +if (( ${#DB_PROJECTS[@]} > 0 )); then + echo "Starting the database projects, every consumer stays down..." + start_projects "${DB_PROJECTS[@]}" + db_deadline=$(( $(date +%s) + BKP_TEST_HEALTH_TIMEOUT )) + for project in "${DB_PROJECTS[@]}"; do + for name in $(container ps --filter "label=com.docker.compose.project=${project}" --format '{{.Names}}'); do + while :; do + read -r status health <<<"$(container inspect --type container -f '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "${name}")" + if [[ "${health}" == "healthy" ]]; then + echo "OK: ${name} accepts connections (${status}/${health})" + break + fi + if [[ "${health}" == "none" ]]; then + echo "FAIL: ${name} defines no healthcheck, so nothing states when the engine accepts connections" + exit 1 + fi + if (( $(date +%s) >= db_deadline )); then + echo "FAIL: ${name} is ${status}/${health} after ${BKP_TEST_HEALTH_TIMEOUT}s, the replay would hit an unready engine" + container ps -a --format 'table {{.Names}}\t{{.Status}}' + exit 1 + fi + sleep 5 + done + done + done + recover database "${GEN_DIR}" fi +"${BKP_TEST_PYTHON}" "${DIR}/seed/marker.py" verify "${GEN_DIR}" "${DR_TOKEN}" + +DB_SERVICE=() +echo "Starting every project to completion..." +start_projects "${PROJECTS[@]}" +for name in "${LOOSE[@]-}"; do + if [[ -n "${name}" ]]; then + container start "${name}" + fi +done + +for name in "${!NETWORKS[@]}"; do + attached="$(container inspect --type container -f "${NETWORK_TEMPLATE}" "${name}" 2>/dev/null)" || continue + for network in ${NETWORKS[${name}]}; do + if [[ " ${attached} " != *" ${network} "* ]]; then + container network connect "${network}" "${name}" + echo "OK: re-attached ${name} to ${network}, which compose does not own" + fi + done +done + DEADLINE=$(( $(date +%s) + BKP_TEST_HEALTH_TIMEOUT )) NOHC_NAMES=() NOHC_RESTARTS=() for name in "${RUNNING[@]}"; do while :; do state="$(container inspect --type container -f '{{.State.Status}} {{.State.ExitCode}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "${name}" 2>/dev/null)" || { - echo "GONE: ${name} disappeared during health wait" - break + echo "FAIL: ${name} did not come back after the restore" + exit 1 } read -r status exit_code health <<<"${state}" if [[ "${health}" == "healthy" ]] || { [[ "${health}" == "none" ]] && [[ "${status}" == "running" ]]; }; then @@ -165,4 +367,7 @@ if (( ${#NOHC_NAMES[@]} > 0 )); then done echo "OK: ${#NOHC_NAMES[@]} container(s) without healthcheck stable for 15s" fi + +trap - EXIT +rm -f "${TORN_DOWN_MARKER}" echo "OK: all restored containers healthy" diff --git a/roles/svc-bkp-volume-2-local/files/test/seed/marker.py b/roles/svc-bkp-volume-2-local/files/test/seed/marker.py new file mode 100755 index 0000000000..b186d150ea --- /dev/null +++ b/roles/svc-bkp-volume-2-local/files/test/seed/marker.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Seed a token into the host's payload and prove it came back. + +A drill that only asserts container health proves the host boots, not that it +holds its data. One token goes into every backup subject beforehand - a file +at each volume root, a row in every database of databases.csv - and each has +to carry it again afterwards. The marker table is dropped and recreated on +seed, so a leftover cannot make a later drill pass; ``clean`` removes it. + +Takes the repository root from ``BKP_TEST_REPO_ROOT``, not from its own +location, because it runs from the staged test directory. The marker file +shares its name with the swarm drill's so one grep finds both. + +Usage: + seed/marker.py seed GENERATION_DIR TOKEN + seed/marker.py captured GENERATION_DIR TOKEN + seed/marker.py blank GENERATION_DIR TOKEN + seed/marker.py verify GENERATION_DIR TOKEN + seed/marker.py clean GENERATION_DIR TOKEN +""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +from pathlib import Path + +sys.path.insert(0, os.environ["BKP_TEST_REPO_ROOT"]) + +from utils.paths import FILE_DATABASE_SECRETS +from utils.recovery import databases, manifest +from utils.recovery import docker as recovery_docker + +MARKER_FILE = ".dr-drill-marker" +MARKER_TABLE = "infinito_dr_marker" +TOKEN_COLUMN = {"postgres": "text", "mariadb": "varchar(64)"} +TOKEN_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$") + + +def marker_sql(engine: str, token: str) -> str: + """Statements that reset the marker table to hold exactly this token. + + Args: + engine: postgres or mariadb, which spell the column type differently. + token: the drill's own token, checked against TOKEN_PATTERN first so + nothing that could close the quote reaches the statement. + """ + if not TOKEN_PATTERN.match(token): + raise databases.RecoveryError(f"token '{token}' is not alphanumeric") + column = TOKEN_COLUMN[engine] + create = f"CREATE TABLE {MARKER_TABLE} (token {column});" + insert = f"INSERT INTO {MARKER_TABLE} VALUES ('{token}');" # noqa: S608 - token validated above + return drop_sql() + create + insert + + +def drop_sql() -> str: + """The statement removing the marker table again.""" + return f"DROP TABLE IF EXISTS {MARKER_TABLE};" + + +def read_sql() -> str: + """The statement reading the marker back.""" + return f"SELECT token FROM {MARKER_TABLE};" # noqa: S608 - constant table name + + +CLIENT = { + "postgres": ( + "psql", + "-U", + "{user}", + "-d", + "{database}", + "-v", + "ON_ERROR_STOP=1", + "-tAc", + ), + "mariadb": ("mariadb", "-u{user}", "-p{password}", "-N", "-B", "{database}", "-e"), +} + + +def volume_mountpoint(volume: str) -> Path: + """Where docker keeps a volume's files on this host.""" + return Path( + recovery_docker._run( + [ + recovery_docker.DOCKER_BIN, + "volume", + "inspect", + "--format", + "{{.Mountpoint}}", + volume, + ] + ).strip() + ) + + +def file_volumes(generation_dir: Path) -> list[str]: + """The volumes this generation stores as a file tree.""" + files_glob, _dump_glob = manifest.globs_of(manifest.layout_of(generation_dir)) + return sorted(path.parent.name for path in generation_dir.glob(files_glob)) + + +def sql( + engine: str, container: str, user: str, password: str, database: str, statement: str +) -> str: + """Run one statement through the engine's own client inside its container.""" + client = [ + part.format(user=user, password=password, database=database) + for part in CLIENT[engine] + ] + return recovery_docker._run( + [recovery_docker.DOCKER_BIN, "exec", container, *client, statement], + secret=password, + ).strip() + + +def each_database(generation_dir: Path): + """Yield (dump, engine, container, user, password) for every database. + + A cluster dump holds several databases in one file, so it yields one entry + per database it recreates: the marker has to sit in each of them, or a + replay that brings back only part of an instance would still pass. + """ + engines = databases.engine_by_key(generation_dir=generation_dir) + credentials = databases.credentials_of(FILE_DATABASE_SECRETS) + dumps, clusters = databases.dumps_of(generation_dir) + for dump in dumps: + if dump.database not in credentials: + raise databases.RecoveryError( + f"{FILE_DATABASE_SECRETS} has no row for database '{dump.database}'" + ) + user, password = credentials[dump.database] + engine = databases.engine_of(dump, engines) + container = recovery_docker.container_of_volume(dump.volume) + yield dump, engine, container, user, password + + superusers = databases.cluster_credentials_of(FILE_DATABASE_SECRETS) + for cluster in clusters: + if cluster.instance not in superusers: + raise databases.RecoveryError( + f"{FILE_DATABASE_SECRETS} has no '{databases.CLUSTER_ROW}' row for " + f"instance '{cluster.instance}'" + ) + user, password = superusers[cluster.instance] + container = recovery_docker.container_of_volume(cluster.volume) + for database in databases.databases_in(cluster): + yield ( + databases.Dump(cluster.volume, database, cluster.path), + databases.CLUSTER_ENGINE, + container, + user, + password, + ) + + +def in_file(path: Path, token: str) -> bool: + """Whether a token appears anywhere in a file, without holding it in memory.""" + with path.open(encoding="utf-8", errors="replace") as handle: + return any(token in line for line in handle) + + +def captured(generation_dir: Path, token: str) -> int: + """Require the generation itself to carry the token. + + This is the half of the proof that needs no restore, so it holds in both + deploy modes: it says the backup really read the live payload. A volume + whose tree was skipped, or a dump written from an engine that never saw + the row, fails here - long before anything is torn down. + """ + missing: list[str] = [] + files_dir = manifest.layout_of(generation_dir)["files_dir"] + for volume in file_volumes(generation_dir): + marker = generation_dir / volume / files_dir / MARKER_FILE + if not marker.is_file() or marker.read_text(encoding="utf-8").strip() != token: + missing.append( + f"volume {volume}: the generation holds no current {MARKER_FILE}" + ) + else: + print(f"OK: the generation captured volume {volume}") + + dumps, clusters = databases.dumps_of(generation_dir) + for dump in dumps: + if not in_file(dump.path, token): + missing.append( + f"database {dump.database}: {dump.path.name} carries no marker row" + ) + else: + print(f"OK: the generation captured database {dump.database}") + + for cluster in clusters: + if not in_file(cluster.path, token): + missing.append( + f"instance {cluster.instance}: {cluster.path.name} carries no marker row" + ) + else: + print(f"OK: the generation captured instance {cluster.instance}") + + if missing: + raise databases.RecoveryError( + "the backup did not capture every payload:\n " + "\n ".join(missing) + ) + return 0 + + +def seed(generation_dir: Path, token: str) -> int: + """Write the token into every backed-up volume and database.""" + volumes = file_volumes(generation_dir) + for volume in volumes: + (volume_mountpoint(volume) / MARKER_FILE).write_text(token, encoding="utf-8") + print(f"OK: seeded {MARKER_FILE} into volume {volume}") + + seeded = 0 + for dump, engine, container, user, password in each_database(generation_dir): + sql( + engine, + container, + user, + password, + dump.database, + marker_sql(engine, token), + ) + print(f"OK: seeded {MARKER_TABLE} into {engine} database {dump.database}") + seeded += 1 + + if not volumes and not seeded: + raise databases.RecoveryError( + f"{generation_dir} holds neither a file volume nor a dump to mark; " + "the drill would prove nothing" + ) + return 0 + + +def verify(generation_dir: Path, token: str) -> int: + """Require the token in every backed-up volume and database.""" + missing: list[str] = [] + for volume in file_volumes(generation_dir): + marker = volume_mountpoint(volume) / MARKER_FILE + if not marker.is_file(): + missing.append(f"volume {volume}: {MARKER_FILE} is gone") + elif marker.read_text(encoding="utf-8").strip() != token: + missing.append(f"volume {volume}: {MARKER_FILE} holds a different token") + else: + print(f"OK: volume {volume} carries the marker") + + for dump, engine, container, user, password in each_database(generation_dir): + found = sql(engine, container, user, password, dump.database, read_sql()) + if found.strip() != token: + missing.append( + f"database {dump.database}: {MARKER_TABLE} holds '{found.strip()}' " + f"instead of the seeded token" + ) + else: + print(f"OK: database {dump.database} carries the marker") + + if missing: + raise databases.RecoveryError( + "the restore did not bring every payload back:\n " + "\n ".join(missing) + ) + return 0 + + +def blank(generation_dir: Path, token: str) -> int: + """Remove the marker from the live volumes, so only a restore returns it. + + Without this the file half of the proof is empty: the marker sits in the + volume from the seeding and would still sit there if the restore did + nothing at all. The database half needs no blanking - ``--empty`` + pre-cleans the schema, marker table included. + """ + for volume in file_volumes(generation_dir): + (volume_mountpoint(volume) / MARKER_FILE).unlink(missing_ok=True) + print( + f"OK: blanked {MARKER_FILE} in volume {volume}, only a restore brings it back" + ) + return 0 + + +def clean(generation_dir: Path, token: str) -> int: + """Take the marker back out of the live payload. + + The drill's token has no business outliving the drill: it would sit in + every app database as a foreign table on a dev stack. The copy inside the + backup generation stays, which is harmless and unavoidable. + """ + for volume in file_volumes(generation_dir): + (volume_mountpoint(volume) / MARKER_FILE).unlink(missing_ok=True) + for dump, engine, container, user, password in each_database(generation_dir): + sql(engine, container, user, password, dump.database, drop_sql()) + print(f"OK: marker {token} removed from the live payload") + return 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "action", choices=("seed", "captured", "blank", "verify", "clean") + ) + parser.add_argument("generation_dir", type=Path) + parser.add_argument("token") + args = parser.parse_args() + try: + if args.action == "seed": + return seed(args.generation_dir, args.token) + if args.action == "captured": + return captured(args.generation_dir, args.token) + if args.action == "blank": + return blank(args.generation_dir, args.token) + if args.action == "clean": + return clean(args.generation_dir, args.token) + return verify(args.generation_dir, args.token) + except databases.RecoveryError as error: + print(f"FAIL: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/roles/svc-bkp-volume-2-local/files/test/test.sh b/roles/svc-bkp-volume-2-local/files/test/test.sh index 5a50325400..7164030e7c 100755 --- a/roles/svc-bkp-volume-2-local/files/test/test.sh +++ b/roles/svc-bkp-volume-2-local/files/test/test.sh @@ -1,13 +1,15 @@ #!/usr/bin/env bash # E2E orchestrator for svc-bkp-volume-2-local. -# Waits for the backup service to terminate, then: -# sync pass (ASYNC_ENABLED=false): verify the first backup generation is -# stored, then run the destructive restore drill (stop containers, wipe -# the backed-up volumes, restore, require everything healthy again) and -# replay the sql dumps. -# async pass (ASYNC_ENABLED=true): require two differential backup -# generations, triggering one extra service run when only one exists; -# no destructive steps. +# Runs once, in the sync pass: wait for the backup service to terminate, back +# up, seed a marker and back up again so the tested generation carries it, take +# every project down, restore through the recover chain, require the marker +# back and every recorded container up, then let the host's own container +# health service pass judgement. The health script is run directly rather than +# through its unit: the unit's OnFailure would start the soft-repair service +# and the drill would heal what it is supposed to report. +# The restore half is compose-only, because tearing a swarm stack down races +# the orchestrator; there the token is cleaned up again and +# scripts/tests/deploy/swarm/routine/backup drills the recovery instead. # Variables sourced from test.env.j2 by test-e2e-cli. set -euo pipefail @@ -15,20 +17,30 @@ set -euo pipefail : "${BKP_TEST_IS_STACK_HOST:?}" : "${BKP_TEST_BACKUPS_DIR:?}" : "${BKP_TEST_SERVICE:?}" -: "${BKP_TEST_RESTORE_BIN:?}" +: "${BKP_TEST_HEALTH_SCRIPT:?}" : "${BKP_TEST_HEALTH_TIMEOUT:?}" +: "${BKP_TEST_PYTHON:?}" if [[ "${BKP_TEST_IS_STACK_HOST}" != "true" ]]; then echo "SKIP: not the stack host; svc-bkp-volume-2-local only deploys there" exit 0 fi +if [[ "${ASYNC_ENABLED}" == "true" ]]; then + echo "SKIP: the drill runs once, in the sync pass; repeating it here would tear the host down a second time for the same answer" + exit 0 +fi + DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -bash "${DIR}/subvolume_probe.sh" -bash "${DIR}/snapshot_probe.sh" +bash "${DIR}/probe/subvolume.sh" +bash "${DIR}/probe/snapshot.sh" +# Param $1: when non-empty, a unit already sitting in 'failed' is a verdict +# from an earlier deploy rather than this run's, so clear it and +# carry on instead of reporting a backup this drill never started. wait_service_terminated() { + local stale_failure_ok="${1:-}" local deadline state deadline=$(( $(date +%s) + BKP_TEST_HEALTH_TIMEOUT )) while :; do @@ -42,9 +54,14 @@ wait_service_terminated() { sleep 5 ;; failed) + if [ -n "${stale_failure_ok}" ]; then + echo "OK: clearing a 'failed' state left by an earlier run" + systemctl reset-failed "${BKP_TEST_SERVICE}" + return 0 + fi echo "FAIL: ${BKP_TEST_SERVICE} terminated in state 'failed'" systemctl status "${BKP_TEST_SERVICE}" --no-pager 2>&1 | tail -20 - journalctl -u "${BKP_TEST_SERVICE}" --no-pager -n 100 2>&1 || true + journalctl -u "${BKP_TEST_SERVICE}" --no-pager -n 100 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error exit 1 ;; *) @@ -60,7 +77,7 @@ count_generations() { COUNT="${#GENERATIONS[@]}" } -wait_service_terminated +wait_service_terminated stale_failure_ok echo "Forcing a post-deploy backup run (the service-loader pre-state backup can predate the app volumes and be empty)" if ! timeout "${BKP_TEST_HEALTH_TIMEOUT}" systemctl start "${BKP_TEST_SERVICE}"; then @@ -106,28 +123,46 @@ fi export MACHINE_HASH REPO_DIR REPO_NAME -if [[ "${ASYNC_ENABLED}" == "true" ]]; then - if (( COUNT < 2 )); then - echo "Only ${COUNT} generation(s); triggering one extra backup run for differential coverage" - if ! timeout "${BKP_TEST_HEALTH_TIMEOUT}" systemctl start "${BKP_TEST_SERVICE}"; then - echo "backup unit start returned non-zero; inspecting result" - fi - wait_service_terminated - count_generations - fi - if (( COUNT < 2 )); then - echo "FAIL: async pass expects at least 2 differential backup generations, found ${COUNT}" - exit 1 - fi - export NEWEST_GENERATION="${GENERATIONS[-1]}" - export PREVIOUS_GENERATION="${GENERATIONS[-2]}" - bash "${DIR}/verify_backup.sh" - echo "ASYNC PASS COMPLETE: ${COUNT} differential backup generations verified" +export NEWEST_GENERATION="${GENERATIONS[-1]}" +bash "${DIR}/verify/backup.sh" + +DR_TOKEN="dr-$(date +%s)-$$" +SEEDED_GENERATION="${REPO_DIR}/${NEWEST_GENERATION}" +export DR_TOKEN +"${BKP_TEST_PYTHON}" "${DIR}/seed/marker.py" seed "${SEEDED_GENERATION}" "${DR_TOKEN}" +trap '"${BKP_TEST_PYTHON}" "${DIR}/seed/marker.py" clean "${REPO_DIR}/${NEWEST_GENERATION}" "${DR_TOKEN}"' EXIT + +echo "Backing up once more so the generation under test carries the marker" +if ! timeout "${BKP_TEST_HEALTH_TIMEOUT}" systemctl start "${BKP_TEST_SERVICE}"; then + echo "backup unit start returned non-zero; inspecting result" +fi +wait_service_terminated +count_generations +export NEWEST_GENERATION="${GENERATIONS[-1]}" + +subjects() { + find "$1" -mindepth 2 -maxdepth 2 -type d \( -name files -o -name sql \) -printf '%h\n' | + xargs -rn1 basename | sort -u +} +if ! diff <(subjects "${SEEDED_GENERATION}") <(subjects "${REPO_DIR}/${NEWEST_GENERATION}"); then + echo "FAIL: the generation under test covers different subjects than the one the marker was seeded from; the drill would prove only their intersection" + exit 1 +fi + +"${BKP_TEST_PYTHON}" "${DIR}/seed/marker.py" captured "${REPO_DIR}/${NEWEST_GENERATION}" "${DR_TOKEN}" + +if [[ "$(container info --format '{{.Swarm.LocalNodeState}}' 2>/dev/null)" == "active" ]]; then + echo "SKIP: swarm node; the restore half needs compose lifecycle control, so it is drilled by scripts/tests/deploy/swarm/routine/backup" + echo "SYNC PASS COMPLETE: backup verified and proven to carry the live payload" exit 0 fi -export NEWEST_GENERATION="${GENERATIONS[-1]}" -bash "${DIR}/verify_backup.sh" bash "${DIR}/restore_cycle.sh" -bash "${DIR}/db_restore.sh" -echo "SYNC PASS COMPLETE: backup verified and restore cycle succeeded" + +echo "Asking the host's own container health service for the verdict" +if ! bash "${BKP_TEST_HEALTH_SCRIPT}"; then + echo "FAIL: ${BKP_TEST_HEALTH_SCRIPT} reports the host unhealthy after the restore" + exit 1 +fi + +echo "SYNC PASS COMPLETE: backup verified, restore cycle succeeded, marker survived, host healthy" diff --git a/roles/svc-bkp-volume-2-local/files/test/verify/backup.sh b/roles/svc-bkp-volume-2-local/files/test/verify/backup.sh new file mode 100755 index 0000000000..bae07a2ad0 --- /dev/null +++ b/roles/svc-bkp-volume-2-local/files/test/verify/backup.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Verify the newest backup generation is stored, non-empty, and dumped where a +# dump was owed: a volume counts as payload with a files/ tree or a non-empty +# sql dump, and a volume the run recorded as a database must carry the dump. +# The generation's own manifest is the authority; a generation written before +# baudolo wrote one is judged by the engine's on-disk footprint instead. +# Requires REPO_DIR/NEWEST_GENERATION/BKP_TEST_REPO_ROOT from test.sh. +set -euo pipefail + +: "${REPO_DIR:?}" +: "${NEWEST_GENERATION:?}" +: "${BKP_TEST_REPO_ROOT:?}" +: "${BKP_TEST_PYTHON:?}" + +GEN_DIR="${REPO_DIR}/${NEWEST_GENERATION}" + +mapfile -t VOLUME_DIRS < <(find "${GEN_DIR}" -mindepth 2 -maxdepth 2 -type d \( -name files -o -name sql \) -printf '%h\n' | sort -u) +if (( ${#VOLUME_DIRS[@]} < 1 )); then + echo "FAIL: newest generation ${NEWEST_GENERATION} contains no volume payload" + exit 1 +fi +echo "OK: generation ${NEWEST_GENERATION} stores ${#VOLUME_DIRS[@]} volume(s)" + +DB_ENGINE_MARKERS=( + "postgres:PG_VERSION" + "mariadb:ibdata1" + "mariadb:mysql/user.frm" + "mariadb:mysql/user.ibd" +) + +engine_of() { + local files_dir="$1" marker + for marker in "${DB_ENGINE_MARKERS[@]}"; do + if [[ -e "${files_dir}/${marker#*:}" ]]; then + echo "${marker%%:*}" + return 0 + fi + done + return 1 +} + +MANIFEST_LINES="" +if MANIFEST_LINES="$(PYTHONPATH="${BKP_TEST_REPO_ROOT}" "${BKP_TEST_PYTHON}" -m utils.recovery.manifest "${GEN_DIR}")"; then + FROM_MANIFEST=true + echo "OK: generation ${NEWEST_GENERATION} carries a manifest; reading its verdict" +else + FROM_MANIFEST=false + echo "NOTE: generation ${NEWEST_GENERATION} predates the manifest; judging by the engine footprint" +fi + +EMPTY=0 +UNDUMPED=() +for vol_dir in "${VOLUME_DIRS[@]}"; do + has_files="$(find "${vol_dir}/files" -mindepth 1 -print -quit 2>/dev/null || true)" + has_sql="$(find "${vol_dir}/sql" -mindepth 1 -type f -name '*.backup.sql' -size +0 -print -quit 2>/dev/null || true)" + if [[ -z "${has_files}" ]] && [[ -z "${has_sql}" ]]; then + echo "WARN: ${vol_dir##*/} backed up empty" + EMPTY=$((EMPTY + 1)) + continue + fi + if [[ "${FROM_MANIFEST}" == "false" ]] \ + && engine="$(engine_of "${vol_dir}/files")" \ + && [[ -z "${has_sql}" ]]; then + UNDUMPED+=("${vol_dir##*/} (${engine})") + fi +done + +if [[ "${FROM_MANIFEST}" == "true" ]] && [[ -n "${MANIFEST_LINES}" ]]; then + while IFS=$'\t' read -r volume engine; do + if [[ -n "${volume}" ]]; then + UNDUMPED+=("${volume} (${engine})") + fi + done <<< "${MANIFEST_LINES}" +fi +if (( EMPTY == ${#VOLUME_DIRS[@]} )); then + echo "FAIL: every backed-up volume in ${NEWEST_GENERATION} is empty" + exit 1 +fi +if (( ${#UNDUMPED[@]} > 0 )); then + echo "FAIL: ${#UNDUMPED[@]} volume(s) hold a live database data directory but no sql dump: ${UNDUMPED[*]}" + echo " Usual cause: no row in the databases.csv baudolo reads, so it had no credentials to dump with." + exit 1 +fi +echo "OK: backup payload present ($(( ${#VOLUME_DIRS[@]} - EMPTY )) non-empty volume(s)), every database volume dumped" diff --git a/roles/svc-bkp-volume-2-local/files/test/verify_backup.sh b/roles/svc-bkp-volume-2-local/files/test/verify_backup.sh deleted file mode 100755 index 03a7ff4b79..0000000000 --- a/roles/svc-bkp-volume-2-local/files/test/verify_backup.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash -# Verify the newest backup generation is stored and non-empty (a volume -# counts as payload with a files/ tree or a non-empty sql dump); when -# PREVIOUS_GENERATION is set (async pass) additionally require it to be a -# distinct, newer generation. Requires REPO_DIR/NEWEST_GENERATION from test.sh. -set -euo pipefail - -: "${REPO_DIR:?}" -: "${NEWEST_GENERATION:?}" - -GEN_DIR="${REPO_DIR}/${NEWEST_GENERATION}" - -mapfile -t VOLUME_DIRS < <(find "${GEN_DIR}" -mindepth 2 -maxdepth 2 -type d \( -name files -o -name sql \) -printf '%h\n' | sort -u) -if (( ${#VOLUME_DIRS[@]} < 1 )); then - echo "FAIL: newest generation ${NEWEST_GENERATION} contains no volume payload" - exit 1 -fi -echo "OK: generation ${NEWEST_GENERATION} stores ${#VOLUME_DIRS[@]} volume(s)" - -EMPTY=0 -for vol_dir in "${VOLUME_DIRS[@]}"; do - has_files="$(find "${vol_dir}/files" -mindepth 1 -print -quit 2>/dev/null || true)" - has_sql="$(find "${vol_dir}/sql" -mindepth 1 -type f -name '*.backup.sql' -size +0 -print -quit 2>/dev/null || true)" - if [[ -z "${has_files}" ]] && [[ -z "${has_sql}" ]]; then - echo "WARN: ${vol_dir##*/} backed up empty" - EMPTY=$((EMPTY + 1)) - fi -done -if (( EMPTY == ${#VOLUME_DIRS[@]} )); then - echo "FAIL: every backed-up volume in ${NEWEST_GENERATION} is empty" - exit 1 -fi -echo "OK: backup payload present ($(( ${#VOLUME_DIRS[@]} - EMPTY )) non-empty volume(s))" - -if [[ -n "${PREVIOUS_GENERATION:-}" ]]; then - if [[ "${NEWEST_GENERATION}" == "${PREVIOUS_GENERATION}" ]] || - [[ "${NEWEST_GENERATION}" < "${PREVIOUS_GENERATION}" ]]; then - echo "FAIL: newest generation ${NEWEST_GENERATION} is not newer than ${PREVIOUS_GENERATION}" - exit 1 - fi - echo "OK: second generation ${NEWEST_GENERATION} stored after ${PREVIOUS_GENERATION}" -fi diff --git a/roles/svc-bkp-volume-2-local/meta/services.yml b/roles/svc-bkp-volume-2-local/meta/services.yml index 28d666e14e..f1a80405f8 100644 --- a/roles/svc-bkp-volume-2-local/meta/services.yml +++ b/roles/svc-bkp-volume-2-local/meta/services.yml @@ -19,6 +19,13 @@ volume-2-local: mem_limit: "512m" pids_limit: 256 +# nocheck: dynamic-flag +test: + enabled: false + shared: false + image: alpine + version: "3.24" + # nocheck: dynamic-flag - host secrets must be captured unconditionally wherever container backups run secrets_backup: bond: 1 diff --git a/roles/svc-bkp-volume-2-local/tasks/01_install.yml b/roles/svc-bkp-volume-2-local/tasks/01_install.yml index 7634afc5f7..04b2c88507 100644 --- a/roles/svc-bkp-volume-2-local/tasks/01_install.yml +++ b/roles/svc-bkp-volume-2-local/tasks/01_install.yml @@ -3,7 +3,7 @@ include_role: name: sys-pip-install vars: - package_name: "backup-docker-to-local==3.4.1" + package_name: "backup-docker-to-local==7.0.1" global_install: true - name: ✅ Assert required baudolo commands are available @@ -11,6 +11,7 @@ loop: - baudolo - baudolo-seed + - baudolo-restore loop_control: loop_var: cmd_name changed_when: false diff --git a/roles/svc-bkp-volume-2-local/templates/test.env.j2 b/roles/svc-bkp-volume-2-local/templates/test.env.j2 index ac13b5f88d..e28d7de49c 100644 --- a/roles/svc-bkp-volume-2-local/templates/test.env.j2 +++ b/roles/svc-bkp-volume-2-local/templates/test.env.j2 @@ -1,7 +1,9 @@ ASYNC_ENABLED={{ ASYNC_ENABLED | bool | lower }} BKP_TEST_BACKUPS_DIR={{ DIR_BACKUPS }} -BKP_TEST_DATABASES_CSV={{ FILE_DATABASE_SECRETS }} +BKP_TEST_HEALTH_SCRIPT={{ [ DIR_SCRIPTS_SYSTEMCTL, 'sys-ctl-hlth-container', 'script.sh' ] | path_join }} BKP_TEST_HEALTH_TIMEOUT={{ lookup('timeout', 1200) | int }} BKP_TEST_IS_STACK_HOST={{ IS_STACK_HOST | bool | lower }} -BKP_TEST_RESTORE_BIN=baudolo-restore +BKP_TEST_PYTHON={{ ansible_python_interpreter }} +BKP_TEST_REPO_ROOT={{ playbook_dir }} +BKP_TEST_SCRATCH_IMAGE={{ lookup('config', application_id, 'services.test.image') }}:{{ lookup('config', application_id, 'services.test.version') }} BKP_TEST_SERVICE={{ SYS_SERVICE_BACKUP_VOLUME_2_LOCAL }} diff --git a/roles/svc-bkp-volume-2-local/vars/main.yml b/roles/svc-bkp-volume-2-local/vars/main.yml index 68798a85d0..4a270a27d8 100644 --- a/roles/svc-bkp-volume-2-local/vars/main.yml +++ b/roles/svc-bkp-volume-2-local/vars/main.yml @@ -7,6 +7,7 @@ # - BKP_VOLUME_2_LOCAL_HARD_RESTART: Compose project (entity) names where backup.project_hard_restart is set (for --hard-restart-projects) # - BKP_VOLUME_2_LOCAL_SNAPSHOT_BIN: Launcher that appends --snapshot/--snapshot-subject per run when the mode allows it # - BKP_VOLUME_2_LOCAL_SNAPSHOT_MODE: services.volume-2-local.snapshot_mode normalised; YAML reads a bare off/no/false as a boolean +# - BKP_VOLUME_2_LOCAL_REPO_NAME: Directory under //; MUST match cli/administration/recover/full.py's volume repo # baudolo matches --images-* exactly, so the refs carry the swarm registry prefix. # CLI-ready variables render these lists as argument strings. @@ -14,6 +15,7 @@ application_id: svc-bkp-volume-2-local system_service_id: "{{ application_id }}" BKP_VOLUME_2_LOCAL_BAUDOLO_BIN: baudolo +BKP_VOLUME_2_LOCAL_REPO_NAME: backup-docker-to-local BKP_VOLUME_2_LOCAL_SNAPSHOT_BIN: "{{ [ DIR_BIN, 'baudolo-snapshot' ] | path_join }}" BKP_VOLUME_2_LOCAL_SUBVOLUME_BIN: "{{ [ DIR_BIN, 'baudolo-subject-subvolume' ] | path_join }}" @@ -100,5 +102,6 @@ BKP_VOLUME_2_LOCAL_EXEC: >- --compose-dir {{ DIR_COMPOSITIONS }} --databases-csv {{ FILE_DATABASE_SECRETS }} --backups-dir {{ DIR_BACKUPS }} - --dump-only-sql + --repo-name {{ BKP_VOLUME_2_LOCAL_REPO_NAME }} + --only-sql {{ BKP_VOLUME_2_LOCAL_CLI_ARGS_LIST | select('string') | join(' ') }} diff --git a/roles/svc-db-elasticsearch/README.md b/roles/svc-db-elasticsearch/README.md index b4726f3b6a..1a2b6f3c24 100644 --- a/roles/svc-db-elasticsearch/README.md +++ b/roles/svc-db-elasticsearch/README.md @@ -20,15 +20,18 @@ The diagram places Elasticsearch in the Infinito.Nexus cosmos: the components it flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-elasticsearch 🐳🐝] svc_elasticsearch["elasticsearch"] + svc_tor["tor"] svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-db-elasticsearch/meta/schema.yml b/roles/svc-db-elasticsearch/meta/secrets.yml similarity index 100% rename from roles/svc-db-elasticsearch/meta/schema.yml rename to roles/svc-db-elasticsearch/meta/secrets.yml diff --git a/roles/svc-db-elasticsearch/meta/services.yml b/roles/svc-db-elasticsearch/meta/services.yml index 15ce306c05..7d4cc66b44 100644 --- a/roles/svc-db-elasticsearch/meta/services.yml +++ b/roles/svc-db-elasticsearch/meta/services.yml @@ -12,7 +12,7 @@ elasticsearch: bond: 1 image: elasticsearch name: elasticsearch - version: "9.5.1" + version: "9.5.2" min_storage: 1066MB backup: database_routine: true @@ -26,6 +26,11 @@ elasticsearch: internal: elasticsearch: 9200 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-elasticsearch/meta/variants.yml b/roles/svc-db-elasticsearch/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-db-elasticsearch/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-db-elasticsearch/templates/compose.yml.j2 b/roles/svc-db-elasticsearch/templates/compose.yml.j2 index 76573a8cdf..138ac10ee4 100644 --- a/roles/svc-db-elasticsearch/templates/compose.yml.j2 +++ b/roles/svc-db-elasticsearch/templates/compose.yml.j2 @@ -12,7 +12,7 @@ {% if ELASTICSEARCH_EXPOSE_LOCAL %} {{ lookup('container_ports', ['elasticsearch', 'elasticsearch', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, 'elasticsearch') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} healthcheck: test: @@ -23,5 +23,5 @@ retries: 18 start_period: 120s -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-elasticsearch/vars/main.yml b/roles/svc-db-elasticsearch/vars/main.yml index 06c6f9422b..af2430a228 100644 --- a/roles/svc-db-elasticsearch/vars/main.yml +++ b/roles/svc-db-elasticsearch/vars/main.yml @@ -6,7 +6,7 @@ database_type: "{{ entity_name }}" ELASTICSEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" ELASTICSEARCH_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, ELASTICSEARCH_CONTAINER) }}" -ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'credentials.ELASTIC_PASSWORD') }}" +ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.ELASTIC_PASSWORD') }}" ELASTICSEARCH_EXPOSE_LOCAL: true ELASTICSEARCH_LOCAL_HOST: "127.0.0.1" ELASTICSEARCH_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.elasticsearch.ports.internal.elasticsearch') }}" diff --git a/roles/svc-db-mariadb/README.md b/roles/svc-db-mariadb/README.md index 474eff4e6c..b1ef68b333 100644 --- a/roles/svc-db-mariadb/README.md +++ b/roles/svc-db-mariadb/README.md @@ -16,9 +16,11 @@ The diagram places MariaDB in the Infinito.Nexus cosmos: the components it deplo flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-mariadb 🐳🐝] svc_mariadb["mariadb"] + svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] @@ -37,6 +39,7 @@ flowchart LR dpt_more["..."] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor svc_mariadb -- "1:1" --> dpt_more svc_mariadb -. "0..1" .-> dpt_web_app_akaunting svc_mariadb -. "0..1" .-> dpt_web_app_erpnext @@ -52,7 +55,7 @@ flowchart LR svc_mariadb -. "0..1" .-> dpt_web_app_phpmyadmin ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-db-mariadb/files/sql/.sqlfluff b/roles/svc-db-mariadb/files/sql/.sqlfluff new file mode 100644 index 0000000000..5b702f70c2 --- /dev/null +++ b/roles/svc-db-mariadb/files/sql/.sqlfluff @@ -0,0 +1,6 @@ +[sqlfluff] +dialect = mysql +templater = placeholder + +[sqlfluff:templater:placeholder] +param_style = pyformat diff --git a/roles/svc-db-mariadb/files/test/.nocheck b/roles/svc-db-mariadb/files/test/.nocheck new file mode 100644 index 0000000000..65c4aed432 --- /dev/null +++ b/roles/svc-db-mariadb/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; grouped by purpose, screened and kept on 2026-08-21. diff --git a/roles/svc-db-mariadb/files/test/test.sh b/roles/svc-db-mariadb/files/test/test.sh new file mode 100644 index 0000000000..3a450320eb --- /dev/null +++ b/roles/svc-db-mariadb/files/test/test.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# svc-db-mariadb credential test. Authenticate to the database with real +# credentials and run a trivial query (SELECT 1). The transport depends on the +# variant: +# tor enabled (variant 0, exposed) -> over the Tor network: connect to +# : through the SOCKS proxy (PyMySQL via a +# local SOCKS5 forward) and authenticate. +# tor disabled (variant 1) -> local: authenticate inside the DB +# container over TCP (forces password auth). +# +# Env (rendered into test.env from templates/test.env.j2): +# TOR_ENABLED true|false (lookup('tor_reachable', application_id)) +# TOR_SOCKS SOCKS proxy (set in test.env.j2) +# ONION_HOST node onion host (svc-net-tor services.tor.node) +# DB_PORT onion-forwarded database port +# DB_CONTAINER database container name +# DB_USER database user (root) +# DB_PASSWORD_B64 base64 password (avoids shell-quoting issues) +# RETRIES attempts (default 20) +# SLEEP_SECONDS wait between (default 15) + +set -uo pipefail + +RETRIES="${RETRIES:-20}" +SLEEP_SECONDS="${SLEEP_SECONDS:-15}" + +DB_PASSWORD="$(printf '%s' "${DB_PASSWORD_B64}" | base64 -d 2>/dev/null)" +[ -n "${DB_PASSWORD}" ] || { echo "[FATAL] DB_PASSWORD_B64 missing or undecodable" >&2; exit 2; } + +# Local: authenticate inside the container over TCP (127.0.0.1) so the server +# enforces password auth — a genuine credential check. +auth_local() { + container exec -e MYSQL_PWD="${DB_PASSWORD}" "${DB_CONTAINER}" \ + mariadb -h 127.0.0.1 -u "${DB_USER}" -N -B -e 'SELECT 1' 2>/dev/null | + grep -qx 1 +} + +# Over Tor: PyMySQL (on this controller) connects through a local SOCKS5 -> onion +# forward and authenticates with the credentials. +auth_tor() { + DB_USER="${DB_USER}" DB_PW="${DB_PASSWORD}" \ + python3 - "${TOR_SOCKS}" "${ONION_HOST}" "${DB_PORT}" <<'PY' +import os, socket, sys, threading + +proxy, onion, port = sys.argv[1], sys.argv[2], int(sys.argv[3]) +ph, pp = proxy.rsplit(":", 1) +pp = int(pp) + + +def recvall(s, n): + buf = b"" + while len(buf) < n: + chunk = s.recv(n - len(buf)) + if not chunk: + raise OSError("short read from SOCKS") + buf += chunk + return buf + + +def socks_connect(): + s = socket.create_connection((ph, pp), timeout=120) + s.settimeout(120) + s.sendall(b"\x05\x01\x00") + if recvall(s, 2) != b"\x05\x00": + raise OSError("SOCKS5 no-auth rejected") + host = onion.encode() + s.sendall(b"\x05\x01\x00\x03" + bytes([len(host)]) + host + port.to_bytes(2, "big")) + hdr = recvall(s, 4) + if hdr[1] != 0: + raise OSError("SOCKS5 CONNECT failed rep=%d" % hdr[1]) + atyp = hdr[3] + if atyp == 1: + recvall(s, 4) + elif atyp == 3: + recvall(s, recvall(s, 1)[0]) + elif atyp == 4: + recvall(s, 16) + recvall(s, 2) + s.settimeout(None) + return s + + +def pipe(a, b): + try: + while True: + data = a.recv(65536) + if not data: + break + b.sendall(data) + except OSError: + pass + finally: + try: + b.shutdown(socket.SHUT_WR) + except OSError: + pass + + +def handle(conn): + try: + up = socks_connect() + except OSError as exc: + print("socks connect failed: %s" % exc, file=sys.stderr) + conn.close() + return + threading.Thread(target=pipe, args=(conn, up), daemon=True).start() + pipe(up, conn) + + +lsock = socket.socket() +lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +lsock.bind(("127.0.0.1", 0)) +lsock.listen(4) +lport = lsock.getsockname()[1] + + +def serve(): + while True: + try: + conn, _ = lsock.accept() + except OSError: + return + threading.Thread(target=handle, args=(conn,), daemon=True).start() + + +threading.Thread(target=serve, daemon=True).start() + +import pymysql + +try: + conn = pymysql.connect( + host="127.0.0.1", port=lport, user=os.environ["DB_USER"], + password=os.environ["DB_PW"], connect_timeout=120, read_timeout=120, + ) + with conn.cursor() as cur: + cur.execute("SELECT 1") + row = cur.fetchone() + conn.close() +except Exception as exc: + print("auth error: %s" % exc, file=sys.stderr) + sys.exit(1) +sys.exit(0 if row and row[0] == 1 else 1) +PY +} + +run_auth() { + if [ "${TOR_ENABLED}" = "true" ]; then + auth_tor + else + auth_local + fi +} + +if [ "${TOR_ENABLED}" = "true" ]; then + [ -n "${ONION_HOST}" ] || { echo "[FATAL] ONION_HOST unset but tor enabled" >&2; exit 2; } + mode="over Tor" +else + [ -n "${DB_CONTAINER}" ] || { echo "[FATAL] DB_CONTAINER unset for local auth" >&2; exit 2; } + mode="local" +fi + +attempt=1 +while [ "${attempt}" -le "${RETRIES}" ]; do + if run_auth; then + echo "[OK] mariadb credential auth ${mode} succeeded (SELECT 1)" + exit 0 + fi + attempt=$((attempt + 1)) + [ "${attempt}" -le "${RETRIES}" ] && sleep "${SLEEP_SECONDS}" +done + +echo "[FAIL] mariadb credential auth ${mode} failed after ${RETRIES} attempts" >&2 +exit 1 diff --git a/roles/svc-db-mariadb/meta/schema.yml b/roles/svc-db-mariadb/meta/secrets.yml similarity index 100% rename from roles/svc-db-mariadb/meta/schema.yml rename to roles/svc-db-mariadb/meta/secrets.yml diff --git a/roles/svc-db-mariadb/meta/services.yml b/roles/svc-db-mariadb/meta/services.yml index a5024d0d96..a7144bb80e 100644 --- a/roles/svc-db-mariadb/meta/services.yml +++ b/roles/svc-db-mariadb/meta/services.yml @@ -21,12 +21,18 @@ mariadb: mem_reservation: 2g mem_limit: 4g pids_limit: 1024 + exposed: false ports: local: mariadb: 3306 internal: mariadb: 3306 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-mariadb/meta/variants.yml b/roles/svc-db-mariadb/meta/variants.yml new file mode 100644 index 0000000000..27b699c012 --- /dev/null +++ b/roles/svc-db-mariadb/meta/variants.yml @@ -0,0 +1,9 @@ +--- +- services: + tor: + enabled: true + mariadb: + exposed: true # nocheck: variants-static-override +- services: + tor: + enabled: true diff --git a/roles/svc-db-mariadb/tasks/02_reset_root_password.yml b/roles/svc-db-mariadb/tasks/02_reset_root_password.yml index c5d13a7492..6caf7ce756 100644 --- a/roles/svc-db-mariadb/tasks/02_reset_root_password.yml +++ b/roles/svc-db-mariadb/tasks/02_reset_root_password.yml @@ -66,7 +66,7 @@ - --network - none - -v - - "{{ MARIADB_VOLUME }}:/var/lib/mysql" + - "{{ MARIADB_VOLUME }}:{{ lookup('volume', 'svc-db-mariadb', 'data').target }}" - "{{ MARIADB_RECOVERY_IMAGE }}" - mariadbd - --skip-grant-tables diff --git a/roles/svc-db-mariadb/templates/compose.yml.j2 b/roles/svc-db-mariadb/templates/compose.yml.j2 index 8d4908af57..9de140c8e3 100644 --- a/roles/svc-db-mariadb/templates/compose.yml.j2 +++ b/roles/svc-db-mariadb/templates/compose.yml.j2 @@ -15,7 +15,7 @@ {% if MARIADB_EXPOSE_LOCAL %} {{ lookup('container_ports', ['mariadb', 'mariadb', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, 'mariadb') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} healthcheck: test: @@ -26,5 +26,5 @@ retries: 18 start_period: 90s -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-mariadb/templates/test.env.j2 b/roles/svc-db-mariadb/templates/test.env.j2 new file mode 100644 index 0000000000..4845066e6c --- /dev/null +++ b/roles/svc-db-mariadb/templates/test.env.j2 @@ -0,0 +1,7 @@ +DB_CONTAINER={{ MARIADB_CONTAINER_ADDRESS }} +DB_PASSWORD_B64={{ MARIADB_ROOT_PWD | b64encode }} +DB_PORT={{ MARIADB_PORT }} +DB_USER=root +ONION_HOST={{ lookup('config', 'svc-net-tor', 'services.tor.node') }} +TOR_ENABLED={{ lookup('tor_reachable', application_id) | lower }} +TOR_SOCKS={{ lookup('tor_socks') }} diff --git a/roles/svc-db-mariadb/vars/main.yml b/roles/svc-db-mariadb/vars/main.yml index 63d88ee4e5..e013b1f460 100644 --- a/roles/svc-db-mariadb/vars/main.yml +++ b/roles/svc-db-mariadb/vars/main.yml @@ -3,7 +3,7 @@ application_id: svc-db-mariadb entity_name: "{{ application_id | get_entity_name }}" database_type: "{{ entity_name }}" -MARIADB_ROOT_PWD: "{{ lookup('config', application_id, 'credentials.root_password') }}" +MARIADB_ROOT_PWD: "{{ lookup('config', application_id, 'secrets.credentials.root_password') }}" MARIADB_VOLUME: "{{ lookup('volume', application_id, 'data').name }}" MARIADB_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" MARIADB_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" @@ -17,10 +17,7 @@ MARIADB_RECOVERY_IMAGE: "{{ SWARM_REGISTRY_PREFIX }}{{ MARIADB_CUSTOM_IMAGE }}" MARIADB_SWARM_SERVICE: "{{ entity_name }}_{{ MARIADB_NAME }}" MARIADB_HEALTHCHECK_DB: "{{ SOFTWARE_DOMAIN | regex_replace('[^a-z0-9]+', '_') }}_healthcheck" -# Host behavior stays unchanged (True). -# In CI/act container environments we avoid publishing ports to prevent iptables/nft issues. -MARIADB_EXPOSE_LOCAL: "{{ not DOCKER_IN_CONTAINER | bool }}" +MARIADB_EXPOSED: "{{ lookup('config', application_id, 'services.mariadb.exposed') | bool }}" +MARIADB_EXPOSE_LOCAL: "{{ MARIADB_EXPOSED | bool or not DOCKER_IN_CONTAINER | bool }}" -# If the desired root password doesn't work, allow an automated reset without knowing the previous password. -# This uses a recovery container with --skip-grant-tables (downtime). Keep disabled by default. MARIADB_ALLOW_RESET_WITHOUT_PREVIOUS: true diff --git a/roles/svc-db-memcached/README.md b/roles/svc-db-memcached/README.md index b6f54a514c..f87a627167 100644 --- a/roles/svc-db-memcached/README.md +++ b/roles/svc-db-memcached/README.md @@ -18,16 +18,21 @@ The diagram places Memcached in the Infinito.Nexus cosmos: the components it dep ```mermaid flowchart LR + subgraph deps [Dependencies] + dep_svc_net_tor["svc-net-tor 🐳🐝"] + end subgraph role [svc-db-memcached 🐳🐝] svc_memcached["memcached"] + svc_tor["tor"] end subgraph dependents [Dependents] dpt_web_app_zammad["web-app-zammad 🐳🐝"] end + dep_svc_net_tor -. "0..1" .-> svc_tor svc_memcached -. "0..1" .-> dpt_web_app_zammad ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Per-consumer isolation diff --git a/roles/svc-db-memcached/meta/services.yml b/roles/svc-db-memcached/meta/services.yml index d9914eb027..17de7832dc 100644 --- a/roles/svc-db-memcached/meta/services.yml +++ b/roles/svc-db-memcached/meta/services.yml @@ -26,3 +26,8 @@ memcached: internal: memcached: 11211 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag diff --git a/roles/svc-db-memcached/meta/variants.yml b/roles/svc-db-memcached/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-db-memcached/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-db-memcached/templates/compose.yml.j2 b/roles/svc-db-memcached/templates/compose.yml.j2 index 09344a149c..e4a1fbb1ea 100644 --- a/roles/svc-db-memcached/templates/compose.yml.j2 +++ b/roles/svc-db-memcached/templates/compose.yml.j2 @@ -22,5 +22,5 @@ retries: 18 start_period: 15s -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-openldap/README.md b/roles/svc-db-openldap/README.md index 98a44ca5b7..75774e2d44 100644 --- a/roles/svc-db-openldap/README.md +++ b/roles/svc-db-openldap/README.md @@ -16,9 +16,11 @@ The diagram places OpenLDAP in the Infinito.Nexus cosmos: the components it depl flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-openldap 🐳🐝] svc_openldap["openldap"] + svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] @@ -37,22 +39,24 @@ flowchart LR dpt_more["..."] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor svc_openldap -- "1:1" --> dpt_more - svc_openldap -- "1:1" --> dpt_web_app_akaunting + svc_openldap -- "0..0" --> dpt_web_app_akaunting svc_openldap -- "1:1" --> dpt_web_app_bigbluebutton - svc_openldap -- "1:1" --> dpt_web_app_bluesky + svc_openldap -- "0..0" --> dpt_web_app_bluesky svc_openldap -. "0..1" .-> dpt_web_app_checkmk - svc_openldap -- "1:1" --> dpt_web_app_discourse + svc_openldap -- "0..0" --> dpt_web_app_discourse svc_openldap -. "0..1" .-> dpt_web_app_erpnext svc_openldap -. "0..1" .-> dpt_web_app_espocrm - svc_openldap -- "1:1" --> dpt_web_app_flowise + svc_openldap -- "0..0" --> dpt_web_app_flowise svc_openldap -. "0..1" .-> dpt_web_app_friendica svc_openldap -. "0..1" .-> dpt_web_app_funkwhale svc_openldap -- "1:1" --> dpt_web_app_fusiondirectory svc_openldap -. "0..1" .-> dpt_web_app_gitea + linkStyle 3,5,7,10 stroke:red; ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-db-openldap/files/entrypoint.sh b/roles/svc-db-openldap/files/shell/entrypoint.sh similarity index 86% rename from roles/svc-db-openldap/files/entrypoint.sh rename to roles/svc-db-openldap/files/shell/entrypoint.sh index 9bbbf0134e..77f5ac7520 100644 --- a/roles/svc-db-openldap/files/entrypoint.sh +++ b/roles/svc-db-openldap/files/shell/entrypoint.sh @@ -101,13 +101,13 @@ bootstrap_cn_config_via_slaptest() { write_slapd_conf log "bootstrap slapd.d via slaptest for suffix ${LDAP_SUFFIX}" - slaptest -f "${TMP_CONF}" -F "${SLAPD_D_DIR}" >/dev/null || true + slaptest -f "${TMP_CONF}" -F "${SLAPD_D_DIR}" >/dev/null || true # nocheck: shell-or-true -- see c4bbbba93: slap_startup opens the not-yet-seeded DB and exits 1 after writing a complete slapd.d; has_cn_config below catches every conversion that really failed chown -R openldap:openldap "${SLAPD_D_DIR}" if ! has_cn_config; then log "slaptest did not generate cn=config; listing:" - ls -la "${SLAPD_D_DIR}" || true + ls -la "${SLAPD_D_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fatal "cn=config missing after slaptest" fi @@ -138,7 +138,7 @@ dc: ${dc} EOF chown -R openldap:openldap "${DB_DIR}" - chmod 700 "${DB_DIR}" || true + chmod 700 "${DB_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error if ! has_mdb_files; then fatal "MDB files were not created under ${DB_DIR}" @@ -166,7 +166,7 @@ fi init_mdb_files_if_needed chown -R openldap:openldap /run/slapd "${DB_DIR}" "${SLAPD_D_DIR}" -chmod 700 "${DB_DIR}" || true +chmod 700 "${DB_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error log "starting slapd (foreground; drop privileges to openldap)" exec /usr/sbin/slapd \ diff --git a/roles/svc-db-openldap/files/healthcheck.sh b/roles/svc-db-openldap/files/shell/healthcheck.sh similarity index 78% rename from roles/svc-db-openldap/files/healthcheck.sh rename to roles/svc-db-openldap/files/shell/healthcheck.sh index 5fd91cacf9..2b704f8f67 100644 --- a/roles/svc-db-openldap/files/healthcheck.sh +++ b/roles/svc-db-openldap/files/shell/healthcheck.sh @@ -3,10 +3,8 @@ set -euo pipefail : "${LDAP_HEALTHCHECK_REQUIRE_MEMBEROF:=false}" -# 1) LDAP listener reachable ldapsearch -x -H ldap://127.0.0.1:389 -s base -b "" "(objectClass=*)" dn >/dev/null 2>&1 -# 2) Optional: ensure memberof overlay exists (cn=config via ldapi EXTERNAL) if [ "${LDAP_HEALTHCHECK_REQUIRE_MEMBEROF}" = "true" ]; then ldapsearch -Q -Y EXTERNAL -H ldapi:/// -LLL \ -b "cn=config" "(&(objectClass=olcOverlayConfig)(olcOverlay=memberof))" dn \ diff --git a/roles/svc-db-openldap/files/test/.nocheck b/roles/svc-db-openldap/files/test/.nocheck new file mode 100644 index 0000000000..65c4aed432 --- /dev/null +++ b/roles/svc-db-openldap/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; grouped by purpose, screened and kept on 2026-08-21. diff --git a/roles/svc-db-openldap/files/test/test.sh b/roles/svc-db-openldap/files/test/test.sh new file mode 100644 index 0000000000..44b9f501d9 --- /dev/null +++ b/roles/svc-db-openldap/files/test/test.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# svc-db-openldap credential test. Bind to the directory with the administrator +# DN + password (a real credential check) over the transport chosen by the +# variant: +# tor enabled (variant 0, exposed) -> over the Tor network: bind to +# : through the SOCKS proxy (ldap3 via a +# local SOCKS5 forward). +# tor disabled (variant 1) -> local: bind inside the LDAP container +# (ldapwhoami over TCP). +# +# Env (rendered into test.env from templates/test.env.j2): +# TOR_ENABLED true|false (lookup('tor_reachable', application_id)) +# TOR_SOCKS SOCKS proxy (set in test.env.j2) +# ONION_HOST node onion host (svc-net-tor services.tor.node) +# DB_PORT onion-forwarded LDAP port +# DB_CONTAINER LDAP container name +# BIND_DN_B64 base64 administrator bind DN +# DB_PASSWORD_B64 base64 bind password +# RETRIES attempts (default 20) +# SLEEP_SECONDS wait between (default 15) + +set -uo pipefail + +RETRIES="${RETRIES:-20}" +SLEEP_SECONDS="${SLEEP_SECONDS:-15}" + +BIND_DN="$(printf '%s' "${BIND_DN_B64}" | base64 -d 2>/dev/null)" +DB_PASSWORD="$(printf '%s' "${DB_PASSWORD_B64}" | base64 -d 2>/dev/null)" +[ -n "${BIND_DN}" ] || { echo "[FATAL] BIND_DN_B64 missing or undecodable" >&2; exit 2; } +[ -n "${DB_PASSWORD}" ] || { echo "[FATAL] DB_PASSWORD_B64 missing or undecodable" >&2; exit 2; } + +# Local: bind inside the container over TCP — a genuine credential check. +auth_local() { + printf '%s' "${DB_PASSWORD}" | container exec -i "${DB_CONTAINER}" \ + ldapwhoami -x -H ldap://127.0.0.1:389 -D "${BIND_DN}" -y /dev/stdin \ + >/dev/null 2>&1 +} + +# Over Tor: ldap3 (on this controller) binds through a local SOCKS5 -> onion +# forward with the administrator credentials. +auth_tor() { + BIND_DN="${BIND_DN}" DB_PW="${DB_PASSWORD}" \ + python3 - "${TOR_SOCKS}" "${ONION_HOST}" "${DB_PORT}" <<'PY' +import os, socket, sys, threading + +proxy, onion, port = sys.argv[1], sys.argv[2], int(sys.argv[3]) +ph, pp = proxy.rsplit(":", 1) +pp = int(pp) + + +def recvall(s, n): + buf = b"" + while len(buf) < n: + chunk = s.recv(n - len(buf)) + if not chunk: + raise OSError("short read from SOCKS") + buf += chunk + return buf + + +def socks_connect(): + s = socket.create_connection((ph, pp), timeout=120) + s.settimeout(120) + s.sendall(b"\x05\x01\x00") + if recvall(s, 2) != b"\x05\x00": + raise OSError("SOCKS5 no-auth rejected") + host = onion.encode() + s.sendall(b"\x05\x01\x00\x03" + bytes([len(host)]) + host + port.to_bytes(2, "big")) + hdr = recvall(s, 4) + if hdr[1] != 0: + raise OSError("SOCKS5 CONNECT failed rep=%d" % hdr[1]) + atyp = hdr[3] + if atyp == 1: + recvall(s, 4) + elif atyp == 3: + recvall(s, recvall(s, 1)[0]) + elif atyp == 4: + recvall(s, 16) + recvall(s, 2) + s.settimeout(None) + return s + + +def pipe(a, b): + try: + while True: + data = a.recv(65536) + if not data: + break + b.sendall(data) + except OSError: + pass + finally: + try: + b.shutdown(socket.SHUT_WR) + except OSError: + pass + + +def handle(conn): + try: + up = socks_connect() + except OSError as exc: + print("socks connect failed: %s" % exc, file=sys.stderr) + conn.close() + return + threading.Thread(target=pipe, args=(conn, up), daemon=True).start() + pipe(up, conn) + + +lsock = socket.socket() +lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +lsock.bind(("127.0.0.1", 0)) +lsock.listen(4) +lport = lsock.getsockname()[1] + + +def serve(): + while True: + try: + conn, _ = lsock.accept() + except OSError: + return + threading.Thread(target=handle, args=(conn,), daemon=True).start() + + +threading.Thread(target=serve, daemon=True).start() + +from ldap3 import Connection, Server + +try: + server = Server("127.0.0.1", port=lport, connect_timeout=120) + conn = Connection( + server, + user=os.environ["BIND_DN"], + password=os.environ["DB_PW"], + auto_bind=True, + receive_timeout=120, + ) + who = conn.extend.standard.who_am_i() + conn.unbind() +except Exception as exc: + print("bind error: %s" % exc, file=sys.stderr) + sys.exit(1) +sys.exit(0 if who else 1) +PY +} + +run_auth() { + if [ "${TOR_ENABLED}" = "true" ]; then + auth_tor + else + auth_local + fi +} + +if [ "${TOR_ENABLED}" = "true" ]; then + [ -n "${ONION_HOST}" ] || { echo "[FATAL] ONION_HOST unset but tor enabled" >&2; exit 2; } + mode="over Tor" +else + [ -n "${DB_CONTAINER}" ] || { echo "[FATAL] DB_CONTAINER unset for local auth" >&2; exit 2; } + mode="local" +fi + +attempt=1 +while [ "${attempt}" -le "${RETRIES}" ]; do + if run_auth; then + echo "[OK] openldap credential bind ${mode} succeeded" + exit 0 + fi + attempt=$((attempt + 1)) + [ "${attempt}" -le "${RETRIES}" ] && sleep "${SLEEP_SECONDS}" +done + +echo "[FAIL] openldap credential bind ${mode} failed after ${RETRIES} attempts" >&2 +exit 1 diff --git a/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py b/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py index 76aca230e6..447818f48d 100644 --- a/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py +++ b/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py @@ -207,7 +207,6 @@ def build_ldap_role_entries(applications, users, ldap, group_names=None): (role_cn, role_dn, role_name, member_uids, member_dns) ) - # Tenant containers reference per-tenant role groups. for tenant in tenants: tenant_cn = f"{application_id}-{tenant}" tenant_dn = f"cn={tenant_cn},{role_dn_base}" @@ -221,7 +220,6 @@ def build_ldap_role_entries(applications, users, ldap, group_names=None): ) app_child_dns.append(tenant_dn) - # Emit parent-first: app container → tenant containers → role groups. result[app_container_dn] = _container_entry( cn=app_container_cn, dn=app_container_dn, diff --git a/roles/svc-db-openldap/handlers/main.yml b/roles/svc-db-openldap/handlers/main.yml index e6f2b30901..3c6d934b23 100644 --- a/roles/svc-db-openldap/handlers/main.yml +++ b/roles/svc-db-openldap/handlers/main.yml @@ -1,49 +1,49 @@ --- -- name: Load memberof module in OpenLDAP (cn=config via EXTERNAL) +- name: 🔌 Load memberof module in OpenLDAP (cn=config via EXTERNAL) ansible.builtin.shell: >- container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapmodify -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/01_member_of_configuration.ldif'] | path_join }}" listen: - - "Import configuration LDIF files" + - "import-configuration-ldif-files" register: r failed_when: >- r.rc != 0 and not (r.stderr | default('') | ldap_modify_noop) -- name: Load refint module in OpenLDAP (cn=config via EXTERNAL) +- name: 🔌 Load refint module in OpenLDAP (cn=config via EXTERNAL) ansible.builtin.shell: >- container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapmodify -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/04_refint_module.ldif'] | path_join }}" listen: - - "Import configuration LDIF files" + - "import-configuration-ldif-files" register: r failed_when: >- r.rc != 0 and not (r.stderr | default('') | ldap_modify_noop) -- name: Add memberof overlay (cn=config via EXTERNAL) +- name: ➕ Add memberof overlay (cn=config via EXTERNAL) ansible.builtin.shell: >- container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapadd -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/02_member_of_configuration.ldif'] | path_join }}" listen: - - "Import configuration LDIF files" + - "import-configuration-ldif-files" register: r failed_when: r.rc not in [0, 68] -- name: Add refint overlay (cn=config via EXTERNAL) +- name: ➕ Add refint overlay (cn=config via EXTERNAL) ansible.builtin.shell: >- container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapadd -Q -Y EXTERNAL -H {{ OPENLDAP_CONFIG_URI }} -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'configuration/03_member_of_configuration.ldif'] | path_join }}" listen: - - "Import configuration LDIF files" + - "import-configuration-ldif-files" register: r failed_when: r.rc not in [0, 68] -- name: Import users, groups, etc. to LDAP (data tree) +- name: 📥 Import users, groups, etc. to LDAP (data tree) ansible.builtin.shell: >- container exec -i {{ lookup('container_address', 'svc-db-openldap', 'openldap') }} ldapadd -x -D "{{ OPENLDAP_BIND_DN }}" @@ -51,7 +51,7 @@ -c -f "{{ [OPENLDAP_LDIF_PATH_DOCKER, 'groups', (item | basename | regex_replace('\.j2$', ''))] | path_join }}" listen: - - "Import groups LDIF files" + - "import-groups-ldif-files" register: ldapadd_result changed_when: "'adding new entry' in ldapadd_result.stdout" failed_when: ldapadd_result.rc not in [0, 20, 68, 65] diff --git a/roles/svc-db-openldap/meta/schema.yml b/roles/svc-db-openldap/meta/secrets.yml similarity index 100% rename from roles/svc-db-openldap/meta/schema.yml rename to roles/svc-db-openldap/meta/secrets.yml diff --git a/roles/svc-db-openldap/meta/services.yml b/roles/svc-db-openldap/meta/services.yml index 565938e6ef..08111859de 100644 --- a/roles/svc-db-openldap/meta/services.yml +++ b/roles/svc-db-openldap/meta/services.yml @@ -31,6 +31,7 @@ openldap: users: true groups: true update: true + exposed: false ports: internal: ldap: 389 @@ -39,6 +40,11 @@ openldap: public: ldaps: 636 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-openldap/meta/variants.yml b/roles/svc-db-openldap/meta/variants.yml new file mode 100644 index 0000000000..24d856c03d --- /dev/null +++ b/roles/svc-db-openldap/meta/variants.yml @@ -0,0 +1,9 @@ +--- +- services: + tor: + enabled: true + openldap: + exposed: true # nocheck: variants-static-override +- services: + tor: + enabled: true diff --git a/roles/svc-db-openldap/tasks/00_core.yml b/roles/svc-db-openldap/tasks/00_core.yml index 1428607b39..9a4e8fe8d0 100644 --- a/roles/svc-db-openldap/tasks/00_core.yml +++ b/roles/svc-db-openldap/tasks/00_core.yml @@ -15,7 +15,7 @@ stack_host_template: src: "nginx.stream.conf.j2" dest: "{{ lookup('nginx','directories.configuration.streams') }}{{ lookup('domain',application_id) }}.conf" - notify: restart openresty + notify: restart-openresty when: OPENLDAP_NETWORK_SWITCH_PUBLIC | bool - name: 🧹 Remove {{ lookup('domain',application_id) }}.conf if LDAP not public diff --git a/roles/svc-db-openldap/tasks/01_docker.yml b/roles/svc-db-openldap/tasks/01_docker.yml index 6ad67ddad7..cd3fd51d5a 100644 --- a/roles/svc-db-openldap/tasks/01_docker.yml +++ b/roles/svc-db-openldap/tasks/01_docker.yml @@ -18,8 +18,8 @@ dest: "{{ [ lookup('container', application_id, 'directories.instance'), item.dest ] | path_join }}" mode: "{{ item.mode }}" loop: - - { src: "entrypoint.sh", dest: "entrypoint.sh", mode: "0755" } - - { src: "healthcheck.sh", dest: "healthcheck.sh", mode: "0755" } + - { src: "shell/entrypoint.sh", dest: "entrypoint.sh", mode: "0755" } + - { src: "shell/healthcheck.sh", dest: "healthcheck.sh", mode: "0755" } loop_control: label: "{{ item.dest }}" diff --git a/roles/svc-db-openldap/tasks/_ldifs_creation.yml b/roles/svc-db-openldap/tasks/_ldifs_creation.yml index 02200bc180..b7da7a6fba 100644 --- a/roles/svc-db-openldap/tasks/_ldifs_creation.yml +++ b/roles/svc-db-openldap/tasks/_ldifs_creation.yml @@ -7,4 +7,4 @@ - src_glob: "ldif/{{ folder }}/*.j2" dest_dir: "{{ OPENLDAP_LDIF_PATH_HOST }}{{ folder }}" mode: "0770" - notify: "Import {{ folder }} LDIF files" + notify: "import-{{ folder }}-ldif-files" diff --git a/roles/svc-db-openldap/templates/compose.yml.j2 b/roles/svc-db-openldap/templates/compose.yml.j2 index 991b7181cf..5d15266ad0 100644 --- a/roles/svc-db-openldap/templates/compose.yml.j2 +++ b/roles/svc-db-openldap/templates/compose.yml.j2 @@ -16,10 +16,10 @@ {{ lookup('container_ports', ['openldap', 'ldap', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, OPENLDAP_SERVICE) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-openldap/templates/test.env.j2 b/roles/svc-db-openldap/templates/test.env.j2 new file mode 100644 index 0000000000..b947f17d9f --- /dev/null +++ b/roles/svc-db-openldap/templates/test.env.j2 @@ -0,0 +1,7 @@ +BIND_DN_B64={{ OPENLDAP_BIND_DN | b64encode }} +DB_CONTAINER={{ OPENLDAP_CONTAINER_ADDRESS }} +DB_PASSWORD_B64={{ OPENLDAP_BIND_PW | b64encode }} +DB_PORT={{ OPENLDAP_PORT }} +ONION_HOST={{ lookup('config', 'svc-net-tor', 'services.tor.node') }} +TOR_ENABLED={{ lookup('tor_reachable', application_id) | lower }} +TOR_SOCKS={{ lookup('tor_socks') }} diff --git a/roles/svc-db-openldap/vars/main.yml b/roles/svc-db-openldap/vars/main.yml index a70729f2c9..9d360bac95 100644 --- a/roles/svc-db-openldap/vars/main.yml +++ b/roles/svc-db-openldap/vars/main.yml @@ -2,7 +2,8 @@ application_id: "svc-db-openldap" entity_name: "{{ application_id | get_entity_name }}" -OPENLDAP_SERVER_URI: "ldap://{{ DOCKER_REACH_HOST }}:{{ lookup('config', application_id, 'services.openldap.ports.local.ldap') }}" +OPENLDAP_PORT: "{{ lookup('config', application_id, 'services.openldap.ports.local.ldap') }}" +OPENLDAP_SERVER_URI: "ldap://{{ DOCKER_REACH_HOST }}:{{ OPENLDAP_PORT }}" OPENLDAP_CONFIG_URI: "ldapi:///" @@ -22,7 +23,8 @@ OPENLDAP_BIND_PW: "{{ LDAP.BIND_CREDENTIAL }}" OPENLDAP_NETWORK_SWITCH_PUBLIC: "{{ lookup('config', application_id, 'services.openldap.network.public') }}" OPENLDAP_NETWORK_SWITCH_LOCAL: "{{ lookup('config', application_id, 'services.openldap.network.local') }}" -OPENLDAP_NETWORK_EXPOSE_LOCAL: "{{ OPENLDAP_NETWORK_SWITCH_PUBLIC | bool or OPENLDAP_NETWORK_SWITCH_LOCAL | bool }}" +OPENLDAP_EXPOSED: "{{ lookup('config', application_id, 'services.openldap.exposed') | bool }}" +OPENLDAP_NETWORK_EXPOSE_LOCAL: "{{ OPENLDAP_NETWORK_SWITCH_PUBLIC | bool or OPENLDAP_NETWORK_SWITCH_LOCAL | bool or OPENLDAP_EXPOSED | bool }}" OPENLDAP_PROVISION_CONFIGURATION: "{{ lookup('config', application_id, 'services.openldap.provision.configuration') }}" OPENLDAP_PROVISION_CREDENTIALS: "{{ lookup('config', application_id, 'services.openldap.provision.credentials') }}" @@ -30,7 +32,7 @@ OPENLDAP_PROVISION_SCHEMAS: "{{ lookup('config', application_id, 'services.openl OPENLDAP_PROVISION_USERS: "{{ lookup('config', application_id, 'services.openldap.provision.users') }}" OPENLDAP_PROVISION_GROUPS: "{{ lookup('config', application_id, 'services.openldap.provision.groups') }}" OPENLDAP_PROVISION_UPDATE: "{{ lookup('config', application_id, 'services.openldap.provision.update') }}" -OPENLDAP_USERS: "{{ lookup('users') | non_reserved_users }}" +OPENLDAP_USERS: "{{ lookup('users_non_reserved') }}" OPENLDAP_PYTHON_HEADER_PACKAGE_TEMPLATES_BY_OS_FAMILY: Debian: diff --git a/roles/svc-db-postgres/README.md b/roles/svc-db-postgres/README.md index 54ca54d7ab..aabf1ae47d 100644 --- a/roles/svc-db-postgres/README.md +++ b/roles/svc-db-postgres/README.md @@ -20,9 +20,11 @@ The diagram places PostgreSQL in the Infinito.Nexus cosmos: the components it de flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-postgres 🐳🐝] svc_postgres["postgres"] + svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] @@ -41,6 +43,7 @@ flowchart LR dpt_more["..."] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor svc_postgres -- "1:1" --> dpt_more svc_postgres -. "0..1" .-> dpt_web_app_baserow svc_postgres -. "0..1" .-> dpt_web_app_bookwyrm @@ -56,7 +59,7 @@ flowchart LR svc_postgres -. "0..1" .-> dpt_web_app_keycloak ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-db-postgres/files/boot-entrypoint.sh b/roles/svc-db-postgres/files/shell/boot-entrypoint.sh similarity index 100% rename from roles/svc-db-postgres/files/boot-entrypoint.sh rename to roles/svc-db-postgres/files/shell/boot-entrypoint.sh diff --git a/roles/svc-db-postgres/files/dump_pg_hba.sh b/roles/svc-db-postgres/files/shell/dump_pg_hba.sh similarity index 90% rename from roles/svc-db-postgres/files/dump_pg_hba.sh rename to roles/svc-db-postgres/files/shell/dump_pg_hba.sh index dd2f951947..486f9112a2 100755 --- a/roles/svc-db-postgres/files/dump_pg_hba.sh +++ b/roles/svc-db-postgres/files/shell/dump_pg_hba.sh @@ -37,7 +37,7 @@ runtime() { else echo "hba_file could not be determined" fi -} >"${out}" 2>&1 || true +} >"${out}" 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error echo "🩺 Postgres pg_hba.conf captured to ${out}" exit 0 diff --git a/roles/svc-db-postgres/files/set_postgres_superuser_password.sh b/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh similarity index 86% rename from roles/svc-db-postgres/files/set_postgres_superuser_password.sh rename to roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh index dd9027fb59..cd9babb4d5 100644 --- a/roles/svc-db-postgres/files/set_postgres_superuser_password.sh +++ b/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh @@ -12,9 +12,6 @@ if [[ -z "$container_raw" || -z "$new_pw" ]]; then exit 2 fi -# In swarm mode the lookup emits `"$(/usr/bin/resolve-container-id )"`. -# `eval` makes bash re-evaluate the subshell so we get the live task id; in -# compose mode the arg is a bare name and `eval` is a noop. container="" eval "container=$container_raw" @@ -55,8 +52,8 @@ for _ in {1..30}; do fi cleanup() { - container exec "$container" bash -lc "if [ -f \"$backup\" ]; then cp -a \"$backup\" \"$hba_file\" && rm -f \"$backup\"; fi" >/dev/null 2>&1 || true - pg_exec 'SELECT pg_reload_conf();' >/dev/null 2>&1 || true + container exec "$container" bash -lc "if [ -f \"$backup\" ]; then cp -a \"$backup\" \"$hba_file\" && rm -f \"$backup\"; fi" >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + pg_exec 'SELECT pg_reload_conf();' >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error } trap 'cleanup' EXIT @@ -103,27 +100,22 @@ fi backup="${hba_file}.bak_ansible_pwcheck_$$" -# Backup hba container exec "$container" bash -lc "cp -a \"$hba_file\" \"$backup\"" # shellcheck disable=SC2329,SC2317 restore_hba() { - # Restore on exit (best effort) - container exec "$container" bash -lc "if [ -f \"$backup\" ]; then cp -a \"$backup\" \"$hba_file\" && rm -f \"$backup\"; fi" >/dev/null 2>&1 || true - container exec "$container" bash -lc "psql -U postgres -d postgres -Atc 'SELECT pg_reload_conf();' >/dev/null 2>&1" || true + container exec "$container" bash -lc "if [ -f \"$backup\" ]; then cp -a \"$backup\" \"$hba_file\" && rm -f \"$backup\"; fi" >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + container exec "$container" bash -lc "psql -U postgres -d postgres -Atc 'SELECT pg_reload_conf();' >/dev/null 2>&1" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error } # Register direct function trap so ShellCheck sees the invocation path. trap restore_hba EXIT -# Force password auth for local TCP (127.0.0.1) -# Prepend a strict rule so it matches first. container exec "$container" bash -lc "{ echo 'host all all 127.0.0.1/32 scram-sha-256' cat \"$backup\" } > \"$hba_file\"" -# Reload config container exec "$container" bash -lc "psql -U postgres -d postgres -Atc 'SELECT pg_reload_conf();' >/dev/null" # Helper: test password auth explicitly over TCP @@ -137,7 +129,6 @@ if auth_test; then pre_ok=1 fi -# Set password (socket, no auth dependency) # shellcheck disable=SC2016 container exec -e NEW_POSTGRES_PASSWORD="$new_pw" "$container" bash -lc ' psql -U postgres -d postgres -v ON_ERROR_STOP=1 -v password="$NEW_POSTGRES_PASSWORD" <<'"'"'SQL'"'"' diff --git a/roles/svc-db-postgres/files/test/.nocheck b/roles/svc-db-postgres/files/test/.nocheck new file mode 100644 index 0000000000..65c4aed432 --- /dev/null +++ b/roles/svc-db-postgres/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; grouped by purpose, screened and kept on 2026-08-21. diff --git a/roles/svc-db-postgres/files/test/test.sh b/roles/svc-db-postgres/files/test/test.sh new file mode 100644 index 0000000000..87f706cbf3 --- /dev/null +++ b/roles/svc-db-postgres/files/test/test.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# svc-db-postgres credential test. Authenticate to the database with real +# credentials and run a trivial query (SELECT 1). The transport depends on the +# variant: +# tor enabled (variant 0, exposed) -> over the Tor network: connect to +# : through the SOCKS proxy (psycopg2 via a +# local SOCKS5 forward) and authenticate. +# tor disabled (variant 1) -> local: authenticate inside the DB +# container over TCP (forces password auth via pg_hba). +# +# Env (rendered into test.env from templates/test.env.j2): +# TOR_ENABLED true|false (lookup('tor_reachable', application_id)) +# TOR_SOCKS SOCKS proxy (set in test.env.j2) +# ONION_HOST node onion host (svc-net-tor services.tor.node) +# DB_PORT onion-forwarded database port +# DB_CONTAINER database container name +# DB_USER database user (postgres) +# DB_NAME database name (postgres) +# DB_PASSWORD_B64 base64 password (avoids shell-quoting issues) +# RETRIES attempts (default 20) +# SLEEP_SECONDS wait between (default 15) + +set -uo pipefail + +RETRIES="${RETRIES:-20}" +SLEEP_SECONDS="${SLEEP_SECONDS:-15}" + +DB_PASSWORD="$(printf '%s' "${DB_PASSWORD_B64}" | base64 -d 2>/dev/null)" +[ -n "${DB_PASSWORD}" ] || { echo "[FATAL] DB_PASSWORD_B64 missing or undecodable" >&2; exit 2; } + +# Local: authenticate inside the container over TCP (127.0.0.1) so pg_hba +# enforces password auth — a genuine credential check, not a peer/trust socket. +auth_local() { + container exec -e PGPASSWORD="${DB_PASSWORD}" "${DB_CONTAINER}" \ + psql -h 127.0.0.1 -U "${DB_USER}" -d "${DB_NAME}" -Atqc 'SELECT 1' 2>/dev/null | + grep -qx 1 +} + +# Over Tor: psycopg2 (on this controller) connects through a local SOCKS5 -> onion +# forward and authenticates with the credentials. +auth_tor() { + DB_USER="${DB_USER}" DB_NAME="${DB_NAME}" DB_PW="${DB_PASSWORD}" \ + python3 - "${TOR_SOCKS}" "${ONION_HOST}" "${DB_PORT}" <<'PY' +import os, socket, sys, threading + +proxy, onion, port = sys.argv[1], sys.argv[2], int(sys.argv[3]) +ph, pp = proxy.rsplit(":", 1) +pp = int(pp) + + +def recvall(s, n): + buf = b"" + while len(buf) < n: + chunk = s.recv(n - len(buf)) + if not chunk: + raise OSError("short read from SOCKS") + buf += chunk + return buf + + +def socks_connect(): + s = socket.create_connection((ph, pp), timeout=120) + s.settimeout(120) + s.sendall(b"\x05\x01\x00") + if recvall(s, 2) != b"\x05\x00": + raise OSError("SOCKS5 no-auth rejected") + host = onion.encode() + s.sendall(b"\x05\x01\x00\x03" + bytes([len(host)]) + host + port.to_bytes(2, "big")) + hdr = recvall(s, 4) + if hdr[1] != 0: + raise OSError("SOCKS5 CONNECT failed rep=%d" % hdr[1]) + atyp = hdr[3] + if atyp == 1: + recvall(s, 4) + elif atyp == 3: + recvall(s, recvall(s, 1)[0]) + elif atyp == 4: + recvall(s, 16) + recvall(s, 2) + s.settimeout(None) + return s + + +def pipe(a, b): + try: + while True: + data = a.recv(65536) + if not data: + break + b.sendall(data) + except OSError: + pass + finally: + try: + b.shutdown(socket.SHUT_WR) + except OSError: + pass + + +def handle(conn): + try: + up = socks_connect() + except OSError as exc: + print("socks connect failed: %s" % exc, file=sys.stderr) + conn.close() + return + threading.Thread(target=pipe, args=(conn, up), daemon=True).start() + pipe(up, conn) + + +lsock = socket.socket() +lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +lsock.bind(("127.0.0.1", 0)) +lsock.listen(4) +lport = lsock.getsockname()[1] + + +def serve(): + while True: + try: + conn, _ = lsock.accept() + except OSError: + return + threading.Thread(target=handle, args=(conn,), daemon=True).start() + + +threading.Thread(target=serve, daemon=True).start() + +import psycopg2 + +try: + conn = psycopg2.connect( + host="127.0.0.1", port=lport, user=os.environ["DB_USER"], + password=os.environ["DB_PW"], dbname=os.environ["DB_NAME"], + connect_timeout=120, + ) + cur = conn.cursor() + cur.execute("SELECT 1") + row = cur.fetchone() + cur.close() + conn.close() +except Exception as exc: + print("auth error: %s" % exc, file=sys.stderr) + sys.exit(1) +sys.exit(0 if row and row[0] == 1 else 1) +PY +} + +run_auth() { + if [ "${TOR_ENABLED}" = "true" ]; then + auth_tor + else + auth_local + fi +} + +if [ "${TOR_ENABLED}" = "true" ]; then + [ -n "${ONION_HOST}" ] || { echo "[FATAL] ONION_HOST unset but tor enabled" >&2; exit 2; } + mode="over Tor" +else + [ -n "${DB_CONTAINER}" ] || { echo "[FATAL] DB_CONTAINER unset for local auth" >&2; exit 2; } + mode="local" +fi + +attempt=1 +while [ "${attempt}" -le "${RETRIES}" ]; do + if run_auth; then + echo "[OK] postgres credential auth ${mode} succeeded (SELECT 1)" + exit 0 + fi + attempt=$((attempt + 1)) + [ "${attempt}" -le "${RETRIES}" ] && sleep "${SLEEP_SECONDS}" +done + +echo "[FAIL] postgres credential auth ${mode} failed after ${RETRIES} attempts" >&2 +exit 1 diff --git a/roles/svc-db-postgres/meta/schema.yml b/roles/svc-db-postgres/meta/secrets.yml similarity index 100% rename from roles/svc-db-postgres/meta/schema.yml rename to roles/svc-db-postgres/meta/secrets.yml diff --git a/roles/svc-db-postgres/meta/services.yml b/roles/svc-db-postgres/meta/services.yml index 1ebd2963c5..a950600b68 100644 --- a/roles/svc-db-postgres/meta/services.yml +++ b/roles/svc-db-postgres/meta/services.yml @@ -10,6 +10,8 @@ postgres: bond: 1 enabled: true shared: true + healthcheck: + test: ["CMD-SHELL", "pg_isready -h 127.0.0.1"] image: postgis/postgis name: postgres version: 17-3.5 @@ -21,12 +23,18 @@ postgres: mem_reservation: 3g mem_limit: 6g pids_limit: 1024 + exposed: false ports: local: postgres: 5432 internal: postgres: 5432 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-postgres/meta/variants.yml b/roles/svc-db-postgres/meta/variants.yml new file mode 100644 index 0000000000..94a48206b1 --- /dev/null +++ b/roles/svc-db-postgres/meta/variants.yml @@ -0,0 +1,9 @@ +--- +- services: + tor: + enabled: true + postgres: + exposed: true # nocheck: variants-static-override +- services: + tor: + enabled: true diff --git a/roles/svc-db-postgres/tasks/00_core.yml b/roles/svc-db-postgres/tasks/00_core.yml index cbaa14f072..99f8073936 100644 --- a/roles/svc-db-postgres/tasks/00_core.yml +++ b/roles/svc-db-postgres/tasks/00_core.yml @@ -42,7 +42,7 @@ - name: "✅ POSTGRES | Ensure postgres superuser password matches inventory" ansible.builtin.script: > # nocheck: container-address-quote script evals the fragment itself - set_postgres_superuser_password.sh {{ POSTGRES_CONTAINER_ADDRESS | quote }} {{ POSTGRES_PASSWORD | quote }} + shell/set_postgres_superuser_password.sh {{ POSTGRES_CONTAINER_ADDRESS | quote }} {{ POSTGRES_PASSWORD | quote }} register: postgres_pw_result delegate_to: "{{ STACK_HOST }}" run_once: true diff --git a/roles/svc-db-postgres/tasks/01_init.yml b/roles/svc-db-postgres/tasks/01_init.yml index 056c9b96b0..8a379bcbd2 100644 --- a/roles/svc-db-postgres/tasks/01_init.yml +++ b/roles/svc-db-postgres/tasks/01_init.yml @@ -36,7 +36,7 @@ rescue: - name: "💾 Postgres | Dump pg_hba.conf into the diagnostics folder" # nocheck: rescue-extra-diagnostics pg_hba.conf is postgres-specific auth config the generic rescue script cannot capture, and it is what a failed TCP-auth wait needs - ansible.builtin.script: "{{ lookup('path_absolute', 'roles/svc-db-postgres/files/dump_pg_hba.sh') }}" + ansible.builtin.script: "{{ lookup('path_absolute', 'roles/svc-db-postgres/files/shell/dump_pg_hba.sh') }}" environment: POSTGRES_CONTAINER_ADDRESS: "{{ POSTGRES_LOCAL_CID }}" PGPASSWORD: "{{ POSTGRES_PASSWORD }}" diff --git a/roles/svc-db-postgres/templates/Dockerfile.j2 b/roles/svc-db-postgres/templates/Dockerfile.j2 index 2e7098979c..fea5c158d8 100644 --- a/roles/svc-db-postgres/templates/Dockerfile.j2 +++ b/roles/svc-db-postgres/templates/Dockerfile.j2 @@ -20,7 +20,7 @@ RUN rm -rf /var/lib/apt/lists/* \ {% endif %} COPY <<'BOOT_ENTRYPOINT_EOF' /usr/local/bin/boot-entrypoint.sh -{{ lookup('file', lookup('path_absolute', 'roles/svc-db-postgres/files/boot-entrypoint.sh')) }} +{{ lookup('file', lookup('path_absolute', 'roles/svc-db-postgres/files/shell/boot-entrypoint.sh')) }} BOOT_ENTRYPOINT_EOF RUN chmod +x /usr/local/bin/boot-entrypoint.sh diff --git a/roles/svc-db-postgres/templates/compose.yml.j2 b/roles/svc-db-postgres/templates/compose.yml.j2 index 3c8034e6fa..5b0170dfda 100644 --- a/roles/svc-db-postgres/templates/compose.yml.j2 +++ b/roles/svc-db-postgres/templates/compose.yml.j2 @@ -18,11 +18,12 @@ - "maintenance_work_mem={{ POSTGRES_MAINTENANCE_WORK_MEM }}" {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_healthcheck', service_name) | indent(4) }} {% if POSTGRES_EXPOSE_LOCAL %} {{ lookup('container_ports', ['postgres', 'postgres', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, 'postgres') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-postgres/templates/test.env.j2 b/roles/svc-db-postgres/templates/test.env.j2 new file mode 100644 index 0000000000..473bbe5ad6 --- /dev/null +++ b/roles/svc-db-postgres/templates/test.env.j2 @@ -0,0 +1,8 @@ +DB_CONTAINER={{ POSTGRES_CONTAINER_ADDRESS }} +DB_NAME=postgres +DB_PASSWORD_B64={{ POSTGRES_PASSWORD | b64encode }} +DB_PORT={{ POSTGRES_PORT }} +DB_USER=postgres +ONION_HOST={{ lookup('config', 'svc-net-tor', 'services.tor.node') }} +TOR_ENABLED={{ lookup('tor_reachable', application_id) | lower }} +TOR_SOCKS={{ lookup('tor_socks') }} diff --git a/roles/svc-db-postgres/vars/main.yml b/roles/svc-db-postgres/vars/main.yml index a82a3f9860..ab4253a155 100644 --- a/roles/svc-db-postgres/vars/main.yml +++ b/roles/svc-db-postgres/vars/main.yml @@ -9,7 +9,7 @@ POSTGRES_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, enti POSTGRES_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" POSTGRES_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" POSTGRES_VERSION_MAJOR: "{{ POSTGRES_VERSION | regex_replace('^([0-9]+).*', '\\1') }}" -POSTGRES_PASSWORD: "{{ lookup('config', application_id, 'credentials.POSTGRES_PASSWORD') }}" +POSTGRES_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.POSTGRES_PASSWORD') }}" POSTGRES_PORT: "{{ database_port | default(lookup('config', application_id, 'services.postgres.ports.local.postgres')) }}" POSTGRES_EXPOSE_LOCAL: true POSTGRES_LOCAL_HOST: "127.0.0.1" diff --git a/roles/svc-db-qdrant/README.md b/roles/svc-db-qdrant/README.md index 4f1aa5d25a..c38ec56626 100644 --- a/roles/svc-db-qdrant/README.md +++ b/roles/svc-db-qdrant/README.md @@ -20,19 +20,22 @@ The diagram places Qdrant in the Infinito.Nexus cosmos: the components it deploy flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-qdrant 🐳🐝] svc_qdrant["qdrant"] + svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] dpt_web_app_flowise["web-app-flowise 🐳🐝"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor svc_qdrant -. "0..1" .-> dpt_web_app_flowise ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-db-qdrant/meta/services.yml b/roles/svc-db-qdrant/meta/services.yml index ed644c4e53..c1f9db7240 100644 --- a/roles/svc-db-qdrant/meta/services.yml +++ b/roles/svc-db-qdrant/meta/services.yml @@ -26,6 +26,11 @@ qdrant: internal: qdrant: 6333 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-qdrant/meta/variants.yml b/roles/svc-db-qdrant/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-db-qdrant/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-db-qdrant/templates/compose.yml.j2 b/roles/svc-db-qdrant/templates/compose.yml.j2 index 92f265d2d0..945026cc26 100644 --- a/roles/svc-db-qdrant/templates/compose.yml.j2 +++ b/roles/svc-db-qdrant/templates/compose.yml.j2 @@ -8,7 +8,7 @@ {% if QDRANT_EXPOSE_LOCAL %} {{ lookup('container_ports', ['qdrant', 'qdrant', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, 'qdrant') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} healthcheck: test: @@ -19,5 +19,5 @@ retries: 18 start_period: 60s -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-rabbitmq/README.md b/roles/svc-db-rabbitmq/README.md index 33e20917d0..2720e8d4d1 100644 --- a/roles/svc-db-rabbitmq/README.md +++ b/roles/svc-db-rabbitmq/README.md @@ -22,15 +22,18 @@ The diagram places RabbitMQ in the Infinito.Nexus cosmos: the components it depl flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-rabbitmq 🐳🐝] svc_rabbitmq["rabbitmq"] + svc_tor["tor"] svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-db-rabbitmq/meta/schema.yml b/roles/svc-db-rabbitmq/meta/secrets.yml similarity index 100% rename from roles/svc-db-rabbitmq/meta/schema.yml rename to roles/svc-db-rabbitmq/meta/secrets.yml diff --git a/roles/svc-db-rabbitmq/meta/services.yml b/roles/svc-db-rabbitmq/meta/services.yml index 7df268a63d..fb2f03e172 100644 --- a/roles/svc-db-rabbitmq/meta/services.yml +++ b/roles/svc-db-rabbitmq/meta/services.yml @@ -26,6 +26,11 @@ rabbitmq: internal: rabbitmq: 5672 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-rabbitmq/meta/variants.yml b/roles/svc-db-rabbitmq/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-db-rabbitmq/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-db-rabbitmq/templates/compose.yml.j2 b/roles/svc-db-rabbitmq/templates/compose.yml.j2 index d7bf20b069..d2a108c5d0 100644 --- a/roles/svc-db-rabbitmq/templates/compose.yml.j2 +++ b/roles/svc-db-rabbitmq/templates/compose.yml.j2 @@ -9,7 +9,7 @@ {% if RABBITMQ_EXPOSE_LOCAL %} {{ lookup('container_ports', ['rabbitmq', 'rabbitmq', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, 'rabbitmq') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} healthcheck: test: @@ -20,5 +20,5 @@ retries: 18 start_period: 60s -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-rabbitmq/vars/main.yml b/roles/svc-db-rabbitmq/vars/main.yml index 10539fbb36..dc1aa5ffea 100644 --- a/roles/svc-db-rabbitmq/vars/main.yml +++ b/roles/svc-db-rabbitmq/vars/main.yml @@ -7,7 +7,7 @@ database_type: "{{ entity_name }}" RABBITMQ_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" RABBITMQ_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, RABBITMQ_CONTAINER) }}" RABBITMQ_USER: "admin" -RABBITMQ_PASSWORD: "{{ lookup('config', application_id, 'credentials.RABBITMQ_PASSWORD') }}" +RABBITMQ_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.RABBITMQ_PASSWORD') }}" RABBITMQ_EXPOSE_LOCAL: true RABBITMQ_RETRIES: 30 RABBITMQ_DELAY: 5 diff --git a/roles/svc-db-redis/README.md b/roles/svc-db-redis/README.md index 177a60ff7a..e51b9b20ab 100644 --- a/roles/svc-db-redis/README.md +++ b/roles/svc-db-redis/README.md @@ -28,9 +28,11 @@ The diagram places Redis in the Infinito.Nexus cosmos: the components it deploys flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-redis 🐳🐝] svc_redis["redis"] + svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] @@ -49,6 +51,7 @@ flowchart LR dpt_more["..."] end dep_svc_bkp_volume_2_local -- "1:1" --> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor svc_redis -- "1:1" --> dpt_more svc_redis -. "0..1" .-> dpt_web_app_akaunting svc_redis -. "0..1" .-> dpt_web_app_baserow @@ -64,7 +67,7 @@ flowchart LR svc_redis -. "0..1" .-> dpt_web_app_magento ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-db-redis/meta/schema.yml b/roles/svc-db-redis/meta/secrets.yml similarity index 100% rename from roles/svc-db-redis/meta/schema.yml rename to roles/svc-db-redis/meta/secrets.yml diff --git a/roles/svc-db-redis/meta/services.yml b/roles/svc-db-redis/meta/services.yml index a55ff18f78..622a9948fb 100644 --- a/roles/svc-db-redis/meta/services.yml +++ b/roles/svc-db-redis/meta/services.yml @@ -26,6 +26,11 @@ redis: internal: redis: 6379 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: dynamic-flag - the redis volume is backup-disabled ephemeral cache state, the backup consumer stays permanently off container_backup: diff --git a/roles/svc-db-redis/meta/variants.yml b/roles/svc-db-redis/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-db-redis/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-db-redis/templates/compose.yml.j2 b/roles/svc-db-redis/templates/compose.yml.j2 index 419c35f1cb..d36ae5df10 100644 --- a/roles/svc-db-redis/templates/compose.yml.j2 +++ b/roles/svc-db-redis/templates/compose.yml.j2 @@ -23,8 +23,8 @@ timeout: 5s retries: 30 start_period: 30s - {{ lookup('container_volumes', application_id, 'redis') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index 7b6e314881..70015ed8d6 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -7,7 +7,6 @@ driver: journald volumes: - redis:/data - # Just save in memory and prevent huge redis_volumes command: - redis-server - --appendonly diff --git a/roles/svc-db-redis/vars/main.yml b/roles/svc-db-redis/vars/main.yml index e441db5f4e..43c4c8c831 100644 --- a/roles/svc-db-redis/vars/main.yml +++ b/roles/svc-db-redis/vars/main.yml @@ -6,7 +6,7 @@ database_type: "{{ entity_name }}" REDIS_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" REDIS_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" -REDIS_PASSWORD: "{{ lookup('config', application_id, 'credentials.REDIS_PASSWORD') }}" +REDIS_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.REDIS_PASSWORD') }}" REDIS_EXPOSE_LOCAL: true REDIS_RETRIES: 5 REDIS_DELAY: 5 diff --git a/roles/svc-db-typesense/README.md b/roles/svc-db-typesense/README.md index e143703cfd..22104b79d6 100644 --- a/roles/svc-db-typesense/README.md +++ b/roles/svc-db-typesense/README.md @@ -20,19 +20,22 @@ The diagram places Typesense in the Infinito.Nexus cosmos: the components it dep flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-db-typesense 🐳🐝] svc_typesense["typesense"] + svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] dpt_web_app_funkwhale["web-app-funkwhale 🐳🐝"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor svc_typesense -. "0..1" .-> dpt_web_app_funkwhale ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-db-typesense/meta/schema.yml b/roles/svc-db-typesense/meta/secrets.yml similarity index 100% rename from roles/svc-db-typesense/meta/schema.yml rename to roles/svc-db-typesense/meta/secrets.yml diff --git a/roles/svc-db-typesense/meta/services.yml b/roles/svc-db-typesense/meta/services.yml index 3b567e550a..39741044ff 100644 --- a/roles/svc-db-typesense/meta/services.yml +++ b/roles/svc-db-typesense/meta/services.yml @@ -26,6 +26,11 @@ typesense: internal: typesense: 8108 lifecycle: beta +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer container_backup: # nocheck: bond-baseline backup host joins outside the variant topology diff --git a/roles/svc-db-typesense/meta/variants.yml b/roles/svc-db-typesense/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-db-typesense/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-db-typesense/templates/compose.yml.j2 b/roles/svc-db-typesense/templates/compose.yml.j2 index 1e158f4753..ad2ceace21 100644 --- a/roles/svc-db-typesense/templates/compose.yml.j2 +++ b/roles/svc-db-typesense/templates/compose.yml.j2 @@ -16,7 +16,7 @@ {% if TYPESENSE_EXPOSE_LOCAL %} {{ lookup('container_ports', ['typesense', 'typesense', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, 'typesense') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} healthcheck: test: @@ -27,5 +27,5 @@ retries: 18 start_period: 30s -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-typesense/vars/main.yml b/roles/svc-db-typesense/vars/main.yml index b45ecaebd4..f986dfd1e4 100644 --- a/roles/svc-db-typesense/vars/main.yml +++ b/roles/svc-db-typesense/vars/main.yml @@ -3,7 +3,7 @@ application_id: svc-db-typesense entity_name: "{{ application_id | get_entity_name }}" database_type: "{{ entity_name }}" -TYPESENSE_API_KEY: "{{ lookup('config', application_id, 'credentials.api_key') }}" +TYPESENSE_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.api_key') }}" TYPESENSE_NAME: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" TYPESENSE_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, TYPESENSE_NAME) }}" TYPESENSE_RETRIES: 30 diff --git a/roles/svc-dns-unbound/README.md b/roles/svc-dns-unbound/README.md index f42171069e..83271e0604 100644 --- a/roles/svc-dns-unbound/README.md +++ b/roles/svc-dns-unbound/README.md @@ -28,7 +28,7 @@ flowchart LR dep_svc_bkp_volume_2_local -- "1:1" --> svc_container_backup ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-dns-unbound/templates/compose.yml.j2 b/roles/svc-dns-unbound/templates/compose.yml.j2 index 12750fe03a..f6371fed79 100644 --- a/roles/svc-dns-unbound/templates/compose.yml.j2 +++ b/roles/svc-dns-unbound/templates/compose.yml.j2 @@ -10,10 +10,10 @@ - "{{ DOCKER_BIND_HOST }}:{{ UNBOUND_PORT }}:53/udp" # nocheck: compose-ports-must-use-container-ports - "{{ DOCKER_BIND_HOST }}:{{ UNBOUND_PORT }}:53/tcp" # nocheck: compose-ports-must-use-container-ports {% endif %} - {{ lookup('container_volumes', application_id, 'unbound') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} networks: # nocheck: networks-literal static-IP resolver on its own engine overlay so consumers can point dns: at it {{ UNBOUND_NETWORK_NAME }}: ipv4_address: {{ UNBOUND_RESOLVER_IP }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-dns-unbound/templates/unbound.conf.j2 b/roles/svc-dns-unbound/templates/unbound.conf.j2 index 80439a587d..d9f07c33b3 100644 --- a/roles/svc-dns-unbound/templates/unbound.conf.j2 +++ b/roles/svc-dns-unbound/templates/unbound.conf.j2 @@ -11,7 +11,7 @@ server: access-control: 10.0.0.0/8 allow access-control: 172.16.0.0/12 allow access-control: 192.168.0.0/16 allow - directory: "/etc/unbound" + directory: "{{ lookup('volume', 'svc-dns-unbound', 'data').target }}" username: unbound auto-trust-anchor-file: trusted-key.key root-hints: "/etc/unbound/root.hints" diff --git a/roles/svc-dns-unbound/vars/main.yml b/roles/svc-dns-unbound/vars/main.yml index ef9e636f86..918bac40d0 100644 --- a/roles/svc-dns-unbound/vars/main.yml +++ b/roles/svc-dns-unbound/vars/main.yml @@ -11,6 +11,4 @@ UNBOUND_RESOLVER_IP: "{{ lookup('config', application_id, 'networks.local.dns_re UNBOUND_VOLUMES_DIR: "{{ lookup('container', application_id, 'directories.volumes') }}" UNBOUND_CONF_FILE: "{{ [ UNBOUND_VOLUMES_DIR, 'unbound.conf' ] | path_join }}" -# WSL2/DinD: iterative resolution via root-hints is unsupported in nested Docker; -# forward to public resolvers instead. On bare-metal keep false to preserve DNSSEC. UNBOUND_FORWARD_DNS: "{{ (DOCKER_IN_CONTAINER | bool) or ('microsoft' in lookup('file', '/proc/version') | lower) }}" diff --git a/roles/svc-net-tor/README.md b/roles/svc-net-tor/README.md new file mode 100644 index 0000000000..c36a7d7859 --- /dev/null +++ b/roles/svc-net-tor/README.md @@ -0,0 +1,116 @@ +# Tor Onion Service + +## Description + +Runs a [Tor](https://www.torproject.org/) daemon on the node and publishes a Tor v3 onion service, turning an Infinito.Nexus instance behind NAT/CGNAT into a fully Tor-reachable node without a public IP, port forwarding, VPS, or DynDNS. + +## Overview + +When `svc-net-tor` is deployed, the node's `DOMAIN_PRIMARY` is the minted `.onion` address, so the whole stack (web vhosts, Keycloak SSO, LDAP, CA) resolves onion domains consistently. The Tor daemon runs as a host-network compose sidecar and maps one hidden service to the host OpenResty (`HiddenServicePort 80 -> 127.0.0.1:80`); per-app subdomains (`..onion`) are routed by the `Host` header. TLS is off on the onion side (onion v3 already provides transport encryption + server authentication); apps still receive `X-Forwarded-Proto: https` because `.onion` is a browser Secure Context. + +The onion key is minted offline during inventory build (`cli.administration.inventory.onion`) and stored in the inventory, so the address is stable across redeploys and restorable from a backup. + +## Cosmos + +The diagram places Tor Onion Service in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph deps [Dependencies] + dep_web_svc_mirror["web-svc-mirror 💻"] + end + subgraph role [svc-net-tor 🐳🐝] + svc_mirror["mirror"] + svc_tor["tor"] + end + subgraph dependents [Dependents] + dpt_svc_db_elasticsearch["svc-db-elasticsearch 🐳🐝"] + dpt_svc_db_mariadb["svc-db-mariadb 🐳🐝"] + dpt_svc_db_memcached["svc-db-memcached 🐳🐝"] + dpt_svc_db_openldap["svc-db-openldap 🐳🐝"] + dpt_svc_db_postgres["svc-db-postgres 🐳🐝"] + dpt_svc_db_qdrant["svc-db-qdrant 🐳🐝"] + dpt_svc_db_rabbitmq["svc-db-rabbitmq 🐳🐝"] + dpt_svc_db_redis["svc-db-redis 🐳🐝"] + dpt_svc_db_typesense["svc-db-typesense 🐳🐝"] + dpt_svc_prx_openresty["svc-prx-openresty 🐳🐝"] + dpt_web_app_akaunting["web-app-akaunting 🐳🐝"] + dpt_web_app_baserow["web-app-baserow 🐳🐝"] + dpt_more["..."] + end + dep_web_svc_mirror -- "1:1" --> svc_mirror + svc_mirror -- "1:1" --> dpt_more + svc_mirror -. "0..1" .-> dpt_svc_db_elasticsearch + svc_mirror -. "0..1" .-> dpt_svc_db_mariadb + svc_mirror -. "0..1" .-> dpt_svc_db_memcached + svc_mirror -. "0..1" .-> dpt_svc_db_openldap + svc_mirror -. "0..1" .-> dpt_svc_db_postgres + svc_mirror -. "0..1" .-> dpt_svc_db_qdrant + svc_mirror -. "0..1" .-> dpt_svc_db_rabbitmq + svc_mirror -. "0..1" .-> dpt_svc_db_redis + svc_mirror -. "0..1" .-> dpt_svc_db_typesense + svc_mirror -. "0..1" .-> dpt_svc_prx_openresty + svc_mirror -. "0..1" .-> dpt_web_app_akaunting + svc_mirror -. "0..1" .-> dpt_web_app_baserow +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **Full onion node:** `DOMAIN_PRIMARY` becomes the node `.onion`; the entire stack shifts to Tor with no domain-transform logic. +- **Single key, per-app subdomains:** one hidden service serves every app at `..onion`, Host-routed by OpenResty. +- **Offline deterministic minting:** the v3 key/address is generated without running Tor and pinned in the inventory (stable, backupable, restorable). +- **HTTP on the onion side:** TLS is forced off for `.onion` (no Let's Encrypt possible); onion v3 crypto is the transport auth. +- **Optional public domains:** extra clearnet domains added to an app keep their own TLS flavor and deploy alongside the onion. +- **Configurable egress:** inbound is always onion; outbound torification is on by default (`TOR_EGRESS_ROUTER_ENABLED`). + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy Tor Onion Service onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-net-tor full_cycle=false +``` + +### Production + +Run the published image to provision the inventory and deploy Tor Onion Service to a managed server (the mounted volume persists the inventory): + +```bash +APP=svc-net-tor +HOST= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" + +docker run --rm -it \ + -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ + -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + ghcr.io/infinito-nexus/core/debian bash -c ' + INVENTORY=/etc/infinito.nexus/inventories/production + infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host "$HOST" \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv' +``` + +## Limitations + +- Targets **fresh** onion nodes; converting an existing clearnet node is out of scope (the LDAP base DN and all identities would shift). +- **No Let's Encrypt** for `.onion` (ACME requires public DNS). +- Outbound mail from `@.onion` senders is not deliverable to the public Internet; onion does not replace public Internet email. + +## Credits + +Implemented by **Kevin Veen-Birkenbach**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-net-tor/files/Dockerfile b/roles/svc-net-tor/files/Dockerfile new file mode 100644 index 0000000000..6caf369d0f --- /dev/null +++ b/roles/svc-net-tor/files/Dockerfile @@ -0,0 +1,27 @@ +ARG TOR_BASE_IMAGE +ARG TOR_BASE_VERSION +FROM ${TOR_BASE_IMAGE}:${TOR_BASE_VERSION} + +ARG TOR_FLAVOR +ENV TOR_FLAVOR=${TOR_FLAVOR} + +RUN rm -rf /var/lib/apt/lists/* \ + && apt-get -o Acquire::Retries=3 update \ + && apt-get -o Acquire::Retries=3 install -y --no-install-recommends tor \ + && if [ "${TOR_FLAVOR}" = "chutney" ]; then \ + apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ + git ca-certificates python3 python3-cryptography python3-networkx \ + python3-paramiko python3-rpyc python3-tomli-w python3-typeguard \ + python3-typing-extensions \ + && git clone --depth=1 https://gitlab.torproject.org/tpo/core/chutney /opt/chutney \ + && sed -i 's/^\( *\)self\.controlport_base: int = 8000$/\1self.controlport_base: int = 18000/' \ + /opt/chutney/lib/chutney/TorNet.py \ + && grep -q 'controlport_base: int = 18000' /opt/chutney/lib/chutney/TorNet.py ; \ + fi \ + && rm -rf /var/lib/apt/lists/* + +COPY entrypoint.sh /usr/local/bin/tor-entrypoint.sh +RUN chmod 0755 /usr/local/bin/tor-entrypoint.sh + +ENTRYPOINT ["/usr/local/bin/tor-entrypoint.sh"] +CMD ["-f", "/etc/tor/torrc"] diff --git a/roles/svc-net-tor/files/python/onion_self_reach.py b/roles/svc-net-tor/files/python/onion_self_reach.py new file mode 100755 index 0000000000..fd8558b8c6 --- /dev/null +++ b/roles/svc-net-tor/files/python/onion_self_reach.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Gate svc-net-tor on the node onion answering over the loopback fast path. + +The host resolver short-circuits the node onion (and every app subdomain of +it) to loopback, so host-side deploy steps hit the local OpenResty without a +Tor circuit. urllib is used because libcurl refuses to resolve .onion without +a proxy (RFC 7686). + +Reachability over the real Tor network is gated where it blocks something: +test-e2e-playwright's wait_onion_reachable.sh, which recreates Tor for fresh +circuits between passes. + +Exit 0 when the onion answers; otherwise exit non-zero so the Ansible retry +loop keeps waiting. + +Usage: onion_self_reach.py +""" + +from __future__ import annotations + +import sys +import urllib.error +import urllib.request + +_REACHED_ON_CLOSE = ("closed connection", "RemoteDisconnected", "Connection refused") + + +def check_internal(onion: str) -> str | None: + try: + urllib.request.urlopen(f"http://{onion}/", timeout=15) + except urllib.error.HTTPError: + return None + except Exception as exc: + detail = f"{type(exc).__name__}: {exc}" + if any(token in detail for token in _REACHED_ON_CLOSE): + return None + return f"internal (loopback fast path): {detail}" + return None + + +def main(argv: list[str]) -> None: + if len(argv) < 2: + sys.exit("usage: onion_self_reach.py ") + error = check_internal(argv[1]) + if error: + sys.exit(error) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/roles/svc-net-tor/files/shell/entrypoint.sh b/roles/svc-net-tor/files/shell/entrypoint.sh new file mode 100644 index 0000000000..ccf615aad1 --- /dev/null +++ b/roles/svc-net-tor/files/shell/entrypoint.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# Tor container entrypoint. +# +# public flavor: exec tor directly against the bind-mounted torrc. +# chutney flavor: first bring up a private, offline Tor test network with +# chutney inside this container (all nodes on 127.0.0.1), extract its +# authority/testing lines into the file the rendered torrc %includes, then +# exec the node tor joined to that private net. Descriptor publication and +# rendezvous then run at localhost speed instead of over the public network. +set -eu + +if [ "${TOR_FLAVOR}" = "chutney" ]; then + net="hs-v3-min" + conf=/run/tor/chutney-net.conf + mkdir -p /run/tor + + echo "[tor-entrypoint] bringing up chutney private network '${net}'" + # Exception: chutney creates its net/ state dir relative to the CWD, so + # every call must run from /opt/chutney or the torrc grep below misses. + cd /opt/chutney + CHUTNEY_LISTEN_ADDRESS=127.0.0.1 \ + ./chutney init --net "${net}" + ./chutney configure + ./chutney start + ./chutney wait_for_bootstrap + + grep -hE '^(TestingTorNetwork|DirAuthority|DirServer|AlternateDirAuthority) ' \ + net/nodes/*/torrc | sort -u >"${conf}" + if [ ! -s "${conf}" ]; then + echo "[tor-entrypoint] ERROR: ${conf} is empty — the node would silently join the public Tor network" >&2 + exit 1 + fi + echo "[tor-entrypoint] wrote ${conf} ($(wc -l <"${conf}") line(s))" + cd / +fi + +exec tor "$@" diff --git a/roles/svc-net-tor/files/test/.nocheck b/roles/svc-net-tor/files/test/.nocheck new file mode 100644 index 0000000000..65c4aed432 --- /dev/null +++ b/roles/svc-net-tor/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; grouped by purpose, screened and kept on 2026-08-21. diff --git a/roles/svc-net-tor/files/test/test.sh b/roles/svc-net-tor/files/test/test.sh new file mode 100755 index 0000000000..67bb92e08e --- /dev/null +++ b/roles/svc-net-tor/files/test/test.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# svc-net-tor role test: probe every currently-served domain and assert it +# responds. Onion (.onion) domains are reached through the node's Tor SOCKS +# proxy; any clearnet domains are reached directly. A domain "responds" when the +# reverse proxy returns an HTTP status in 200-499 (5xx or no answer = failure). +# +# Domains are auto-discovered from the deployed OpenResty vhosts +# (/{http,https}/.conf); pass explicit domains as arguments to +# override. +# +# Env (all required; the role's test.env carries them): +# TOR_SOCKS SOCKS proxy for .onion (127.0.0.1:) +# NGINX_SERVERS_DIR the deployed OpenResty servers dir from the nginx lookup +# RETRIES attempts per domain +# SLEEP_SECONDS wait between attempts +# TOR_DNSMASQ_CONF the dnsmasq drop-in path; its directory is scanned for +# upstreams when a probe fails + +set -uo pipefail + +TOR_SOCKS="${TOR_SOCKS:?pass TOR_SOCKS as env (127.0.0.1:)}" +NGINX_SERVERS_DIR="${NGINX_SERVERS_DIR:?pass NGINX_SERVERS_DIR as env (the deployed OpenResty vhost servers dir from the nginx lookup, e.g. /etc/nginx/conf.d/servers)}" +RETRIES="${RETRIES:?pass RETRIES as env (attempts per domain, from svc-net-tor test.env)}" +SLEEP_SECONDS="${SLEEP_SECONDS:?pass SLEEP_SECONDS as env (wait between attempts, from svc-net-tor test.env)}" +TOR_DNSMASQ_CONF="${TOR_DNSMASQ_CONF:?pass TOR_DNSMASQ_CONF as env (the dnsmasq drop-in path, from svc-net-tor vars)}" + +discover_domains() { + find "${NGINX_SERVERS_DIR}/http" "${NGINX_SERVERS_DIR}/https" \ + -maxdepth 1 -type f -name '*.conf' 2>/dev/null | + sed -E 's#.*/##; s#\.conf$##' | sort -u +} + +if [[ "$#" -gt 0 ]]; then + domains=("$@") +else + mapfile -t domains < <(discover_domains) +fi + +if [[ "${#domains[@]}" -eq 0 ]]; then + echo "[FATAL] no domains found under ${NGINX_SERVERS_DIR} and none given as arguments" >&2 + exit 2 +fi + +echo "[INFO] probing ${#domains[@]} domain(s); onion via socks5://${TOR_SOCKS}" + +# Probe one domain with retries. Echoes the final HTTP code; returns 0 on success. +probe() { + local domain="$1" scheme curl_proxy=() attempt=1 code + if [[ "${domain}" == *.onion ]]; then + scheme="http" + curl_proxy=(--socks5-hostname "${TOR_SOCKS}") + else + scheme="https" + fi + while [[ "${attempt}" -le "${RETRIES}" ]]; do + code="$(curl "${curl_proxy[@]}" --silent --show-error --location \ + --insecure --max-time 60 \ + -o /dev/null -w '%{http_code}' \ + "${scheme}://${domain}/")" + if [[ "${code}" =~ ^[234][0-9][0-9]$ ]]; then + echo "${code}" + return 0 + fi + attempt=$((attempt + 1)) + [[ "${attempt}" -le "${RETRIES}" ]] && sleep "${SLEEP_SECONDS}" + done + echo "${code:-000}" + return 1 +} + +diagnose() { + local domain="$1" upstream upstreams=() + echo " resolv: $(grep -v '^#' /etc/resolv.conf 2>/dev/null | tr '\n' ' ')" + grep -F "${domain}" /etc/hosts 2>/dev/null | sed 's/^/ hosts: /' + if ! command -v dig >/dev/null 2>&1; then + echo " dig: not installed" + return + fi + echo " dig: $(dig +short +time=2 +tries=1 "${domain}" A 2>&1 | tr '\n' ' ')" + mapfile -t upstreams < <(sed -nE 's/^server=([0-9.]+)$/\1/p' "$(dirname "${TOR_DNSMASQ_CONF}")"/*.conf 2>/dev/null) + for upstream in "${upstreams[@]}"; do + echo " dig@${upstream}: $(dig +short +time=2 +tries=1 "@${upstream}" "${domain}" A 2>&1 | tr '\n' ' ')" + done +} + +failed=0 +for domain in "${domains[@]}"; do + if code="$(probe "${domain}")"; then + printf '[OK] %-60s HTTP %s\n' "${domain}" "${code}" + else + addr="$(getent hosts "${domain}" 2>/dev/null | head -n1)" + printf '[FAIL] %-60s HTTP %s dns=%s\n' "${domain}" "${code}" "${addr%% *}" + diagnose "${domain}" + failed=$((failed + 1)) + fi +done + +echo "[INFO] ${#domains[@]} probed, ${failed} failed" +[[ "${failed}" -eq 0 ]] diff --git a/roles/svc-net-tor/meta/main.yml b/roles/svc-net-tor/meta/main.yml new file mode 100644 index 0000000000..e369152694 --- /dev/null +++ b/roles/svc-net-tor/meta/main.yml @@ -0,0 +1,35 @@ +--- +# nocheck: info-media no official demo video +galaxy_info: + author: Kevin Veen-Birkenbach + description: Tor daemon publishing the node as a v3 onion service + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - tor + - onion + - privacy + - anonymity + - networking + - self-hosted + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/svc-net-tor/meta/networks.yml b/roles/svc-net-tor/meta/networks.yml new file mode 100644 index 0000000000..663e84fd14 --- /dev/null +++ b/roles/svc-net-tor/meta/networks.yml @@ -0,0 +1,15 @@ +--- +# Tor runs with network_mode: host and has no vhost of its own, but the compose +# role contract still requires a local network entry (see +# test_compose_roles_have_local_network). Kept minimal; not used at runtime. +local: + subnet: 192.168.74.0/24 +overlay: + modes: [swarm] + topology: shared_net + aliases: [tor] + consumer: + kind: onion_sso + key: sso + provider: web-app-keycloak + provider_key: tor diff --git a/roles/svc-net-tor/meta/packages.yml b/roles/svc-net-tor/meta/packages.yml new file mode 100644 index 0000000000..b5bdbd8924 --- /dev/null +++ b/roles/svc-net-tor/meta/packages.yml @@ -0,0 +1,8 @@ +--- +dnsmasq: + Archlinux: + - dnsmasq + Debian: + - dnsmasq + RedHat: + - dnsmasq diff --git a/roles/svc-net-tor/meta/server.yml b/roles/svc-net-tor/meta/server.yml new file mode 100644 index 0000000000..ed97d539c0 --- /dev/null +++ b/roles/svc-net-tor/meta/server.yml @@ -0,0 +1 @@ +--- diff --git a/roles/svc-net-tor/meta/services.yml b/roles/svc-net-tor/meta/services.yml new file mode 100644 index 0000000000..5a3842df7b --- /dev/null +++ b/roles/svc-net-tor/meta/services.yml @@ -0,0 +1,39 @@ +--- +# nocheck: playwright-service-flag — Tor Browser users need third-party assets +# served first-party; deploying tor therefore always deploys the mirror. +# nocheck: dynamic-flag — hard dependency: every tor deployment serves the mirror. +mirror: + bond: 1 + enabled: true + shared: true +tor: # nocheck: category-modes + modes: + compose: + enabled: true + swarm: + enabled: true + # nocheck: default-placement-manager node onion ingress: host-published SOCKS/DNS/Trans ports and the HiddenService loopback forward must live on the stack host + placement: manager + bond: 0.5 + enabled: true + shared: true + exclusive: true + primary: true + image: debian + version: trixie-slim + custom: true + name: tor + node: "" + use_entry_guards: true + flavor: public + ports: + local: + socks: 9050 + trans: 9040 + dns: 9053 + min_storage: 100MB + cpus: "0.25" + mem_reservation: 128m + mem_limit: 256m + pids_limit: 128 + lifecycle: alpha diff --git a/roles/svc-net-tor/meta/tests.yml b/roles/svc-net-tor/meta/tests.yml new file mode 100644 index 0000000000..272c1e148d --- /dev/null +++ b/roles/svc-net-tor/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 7200 diff --git a/roles/svc-net-tor/meta/variants.yml b/roles/svc-net-tor/meta/variants.yml new file mode 100644 index 0000000000..0562bbf44c --- /dev/null +++ b/roles/svc-net-tor/meta/variants.yml @@ -0,0 +1,24 @@ +--- +# Matrix-deploy variant overrides for svc-net-tor. +# See docs/contributing/artefact/files/role/variants.md for the file format. +# +# nocheck: sso-variant-tor — this role IS the onion provider; its tor block is the +# provider definition, not a consumer gate, so there is nothing to pin on. + +# Test deployments run without guard pinning so a single degraded entry guard +# cannot stall the whole node; production keeps the Tor default (true). They +# also join a private chutney Tor net (offline, localhost-speed onion publish +# and rendezvous) whose ~9 extra in-container tor nodes need a larger resource +# footprint than the public flavor. +- services: + tor: + use_entry_guards: false # nocheck: variants-static-override + flavor: chutney + cpus: "1.0" + mem_limit: 2g + pids_limit: 512 + +- services: + tor: + use_entry_guards: false + flavor: public diff --git a/roles/svc-net-tor/meta/volumes.yml b/roles/svc-net-tor/meta/volumes.yml new file mode 100644 index 0000000000..33b97b26ae --- /dev/null +++ b/roles/svc-net-tor/meta/volumes.yml @@ -0,0 +1,15 @@ +--- +tor_data: + type: bind + source: "{{ [ DIR_VAR_LIB, 'svc-net-tor', 'data' ] | path_join }}" + mounts: + - service: tor + target: /var/lib/tor + +tor_torrc: + type: bind + source: "{{ [ DIR_VAR_LIB, 'svc-net-tor', 'config', 'torrc' ] | path_join }}" + read_only: true + mounts: + - service: tor + target: /etc/tor/torrc diff --git a/roles/svc-net-tor/tasks/00_core.yml b/roles/svc-net-tor/tasks/00_core.yml new file mode 100644 index 0000000000..7eaf5a9079 --- /dev/null +++ b/roles/svc-net-tor/tasks/00_core.yml @@ -0,0 +1,118 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "✅ Assert the Tor network flavor is public or chutney" + ansible.builtin.assert: + that: + - TOR_FLAVOR in ['public', 'chutney'] + fail_msg: "services.tor.flavor must be 'public' or 'chutney' (got '{{ TOR_FLAVOR }}')" + quiet: true + +- name: "📤 Dispatch Tor network flavor '{{ TOR_FLAVOR }}'" + ansible.builtin.include_tasks: "flavor/{{ TOR_FLAVOR }}/main.yml" + +- name: "🧅 Ensure Tor config directory exists" + ansible.builtin.file: + path: "{{ TOR_CONFIG_DIR }}" + state: directory + owner: root + group: root + mode: "0755" + become: true + +- name: "🧅 Ensure Tor data + HiddenServiceDir exist" + ansible.builtin.file: + path: "{{ item }}" + state: directory + owner: root + group: root + mode: "0700" + loop: + - "{{ TOR_DATA_DIR }}" + - "{{ TOR_HS_DIR }}" + become: true + +- name: "🔑 Install authoritative hidden-service keys (must match DOMAIN_PRIMARY)" + ansible.builtin.copy: + src: "{{ [ TOR_HS_SRC_DIR, item.name ] | path_join }}" + dest: "{{ [ TOR_HS_DIR, item.name ] | path_join }}" + owner: root + group: root + mode: "{{ item.mode }}" + force: true + loop: + - { name: "hostname", mode: "0600" } + - { name: "hs_ed25519_public_key", mode: "0600" } + - { name: "hs_ed25519_secret_key", mode: "0600" } + become: true + register: _tor_hs_keys + +- name: "📝 Render torrc" + ansible.builtin.template: # nocheck: stack-host-template (per-host torrc under DIR_VAR_LIB; tor is a node-local host-network sidecar) + src: torrc.j2 + dest: "{{ TOR_TORRC_HOST }}" + owner: root + group: root + mode: "0644" + become: true + register: _tor_torrc + +- name: "📁 Ensure the Tor compose instance dir exists (build context)" + ansible.builtin.file: + path: "{{ TOR_INSTANCE_DIR }}" + state: directory + owner: root + group: root + mode: "0755" + become: true + +- name: "🚀 Stage the Tor container entrypoint into the build context" + stack_host_copy: + src: "{{ role_path }}/files/shell/entrypoint.sh" + dest: "{{ TOR_ENTRYPOINT_HOST }}" + mode: "0755" + become: true + register: _tor_entrypoint + +- name: "🧩 For '{{ application_id }}': Load sys-svc-compose" + include_role: + name: sys-svc-compose + vars: + compose_repository_pull: false + compose_handlers_flush: true + application_id: svc-net-tor + +- name: "🔄 Restart Tor to apply hidden-service key / torrc changes" + ansible.builtin.shell: | + set -euo pipefail + compose up -d --force-recreate --remove-orphans + args: + chdir: "{{ lookup('container', application_id, 'directories.instance') }}" + executable: /bin/bash + become: true + when: DEPLOYMENT_MODE == 'compose' and ((_tor_hs_keys is changed) or (_tor_torrc is changed) or (_tor_entrypoint is changed)) + +- name: "🔄 Force Tor service redeploy to apply hidden-service key / torrc changes" + ansible.builtin.command: >- + container service update --force + {{ lookup('container_service', application_id, 'tor') }} + register: _tor_swarm_update + changed_when: _tor_swarm_update.rc == 0 + become: true + when: + - DEPLOYMENT_MODE == 'swarm' + - IS_STACK_HOST | bool + - (_tor_hs_keys is changed) or (_tor_torrc is changed) or (_tor_entrypoint is changed) + +- name: "🧅 Wire the host-level transparent .onion egress router" + include_tasks: + file: router.yml + apply: + become: true + when: TOR_EGRESS_ROUTER_ENABLED | bool + +- name: "🧅 Verify the node onion is reachable" + ansible.builtin.include_tasks: onion_reach.yml + when: + - TOR_EGRESS_ROUTER_ENABLED | bool + - TOR_NODE_ONION | length > 0 diff --git a/roles/svc-net-tor/tasks/flavor/chutney/main.yml b/roles/svc-net-tor/tasks/flavor/chutney/main.yml new file mode 100644 index 0000000000..bb408b9e73 --- /dev/null +++ b/roles/svc-net-tor/tasks/flavor/chutney/main.yml @@ -0,0 +1,11 @@ +--- +- name: "🧪 Tor flavor 'chutney' — join a private in-container Tor test net" + ansible.builtin.debug: + msg: >- + svc-net-tor joins a private chutney Tor network bootstrapped inside the + tor container (all nodes on 127.0.0.1). Descriptor publication and + rendezvous run at localhost speed; the onion is reachable only from + hosts sharing this private net (the node's own SOCKS), which is exactly + the test surface. The heavy lifting is the container entrypoint and the + torrc %include of /run/tor/chutney-net.conf. + changed_when: false diff --git a/roles/svc-net-tor/tasks/flavor/public/main.yml b/roles/svc-net-tor/tasks/flavor/public/main.yml new file mode 100644 index 0000000000..828c570a80 --- /dev/null +++ b/roles/svc-net-tor/tasks/flavor/public/main.yml @@ -0,0 +1,7 @@ +--- +- name: "🌍 Tor flavor 'public' — join the public Tor network" + ansible.builtin.debug: + msg: >- + svc-net-tor runs against the public Tor network; onion descriptor + publication and rendezvous take real-network latency. + changed_when: false diff --git a/roles/svc-net-tor/tasks/main.yml b/roles/svc-net-tor/tasks/main.yml new file mode 100644 index 0000000000..06be3db5c2 --- /dev/null +++ b/roles/svc-net-tor/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_svc_net_tor is not defined + vars: + application_id: svc-net-tor diff --git a/roles/svc-net-tor/tasks/onion_reach.yml b/roles/svc-net-tor/tasks/onion_reach.yml new file mode 100644 index 0000000000..d8c8333fc7 --- /dev/null +++ b/roles/svc-net-tor/tasks/onion_reach.yml @@ -0,0 +1,9 @@ +--- +- name: "⏳ Wait until the node onion answers internally (loopback fast path)" + ansible.builtin.script: + cmd: "{{ role_path }}/files/python/onion_self_reach.py {{ TOR_NODE_ONION }}" + register: _tor_self_reach + retries: 90 + delay: 5 + until: _tor_self_reach.rc == 0 + changed_when: false diff --git a/roles/svc-net-tor/tasks/router.yml b/roles/svc-net-tor/tasks/router.yml new file mode 100644 index 0000000000..2071db3671 --- /dev/null +++ b/roles/svc-net-tor/tasks/router.yml @@ -0,0 +1,74 @@ +--- +- name: "✅ Egress router | Assert a clearnet resolver is configured" + ansible.builtin.assert: + that: networks.internet.dns | length > 0 + fail_msg: >- + networks.internet.dns must be set on a Tor node: dnsmasq runs with + no-resolv and would answer .onion only. +- name: "📦 Egress router | Install dnsmasq (host split-DNS forwarder)" + become: true + package_install: + id: dnsmasq +- name: "📁 Egress router | Ensure the dnsmasq drop-in directory exists" + ansible.builtin.file: + path: "{{ TOR_DNSMASQ_CONF | dirname }}" + state: directory + owner: root + group: root + mode: "0755" +- name: "🔧 Egress router | Ensure dnsmasq reads the drop-in directory" + ansible.builtin.lineinfile: + path: /etc/dnsmasq.conf + regexp: "^conf-dir=" + line: "conf-dir={{ TOR_DNSMASQ_CONF | dirname }}/,*.conf" + create: true + owner: root + group: root + mode: "0644" + register: _tor_dnsmasq_confdir +- name: "🔎 Egress router | Detect foreign dnsmasq drop-ins (shared instance)" + ansible.builtin.find: + paths: "{{ TOR_DNSMASQ_CONF | dirname }}" + patterns: "*.conf" + excludes: "{{ TOR_DNSMASQ_CONF | basename }}" + register: _tor_dnsmasq_foreign +- name: "🔧 Egress router | Decide whether this dnsmasq is ours to reshape" + ansible.builtin.set_fact: + TOR_DNSMASQ_OWNS_LISTENER: "{{ _tor_dnsmasq_foreign.matched == 0 }}" + +- name: "📝 Egress router | Render dnsmasq .onion split-DNS drop-in" + ansible.builtin.template: # nocheck: stack-host-template (per-host dnsmasq system config in /etc/dnsmasq.d) + src: dnsmasq-tor-onion.conf.j2 + dest: "{{ TOR_DNSMASQ_CONF }}" + owner: root + group: root + mode: "0644" + vars: + TOR_DNS_UPSTREAMS: "{{ [ networks.internet.dns ] }}" + register: _tor_dnsmasq_conf +- name: "🚀 Egress router | Enable + (re)start dnsmasq" + ansible.builtin.systemd: + name: dnsmasq + enabled: true + state: "{{ 'restarted' if (_tor_dnsmasq_conf is changed or _tor_dnsmasq_confdir is changed) else 'started' }}" +- name: "🔀 Egress router | Point the host resolver at dnsmasq (127.0.0.1)" + ansible.builtin.copy: + dest: /etc/resolv.conf + content: | + nameserver 127.0.0.1 + nameserver {{ networks.internet.dns }} + options ndots:1 + owner: root + group: root + mode: "0644" + unsafe_writes: true + when: TOR_DNSMASQ_OWNS_LISTENER | bool +- name: "🔀 Egress router | Redirect .onion virtual-IP TCP to Tor TransPort" + ansible.builtin.iptables: + table: nat + chain: OUTPUT + protocol: tcp + destination: "{{ TOR_EGRESS_VIRTUAL_NET_IPV4 }}" + jump: REDIRECT + to_ports: "{{ TOR_TRANS_PORT | string }}" + comment: "Tor egress router: .onion virtual range -> TransPort" diff --git a/roles/svc-net-tor/templates/compose.yml.j2 b/roles/svc-net-tor/templates/compose.yml.j2 new file mode 100644 index 0000000000..7d464c93ec --- /dev/null +++ b/roles/svc-net-tor/templates/compose.yml.j2 @@ -0,0 +1,31 @@ +{% include 'roles/sys-svc-compose/templates/base.yml.j2' %} + {% set service_name = 'tor' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('template', 'roles/sys-svc-container/templates/build.yml.j2') | indent(4) }} + args: + TOR_BASE_IMAGE: "{{ TOR_IMAGE }}" + TOR_BASE_VERSION: "{{ TOR_VERSION }}" + TOR_FLAVOR: "{{ TOR_FLAVOR }}" + {{ lookup('compose_only', 'container_name', TOR_CONTAINER) }} + {{ lookup('container_image', application_id, 'tor') }} + {% if DEPLOYMENT_MODE == 'swarm' %} + ports: + - target: {{ TOR_SOCKS_PORT }} + published: {{ TOR_SOCKS_PORT }} + protocol: tcp + mode: host + {{ lookup('container_networks') | indent(4) }} + {% else %} + network_mode: "host" + {% endif %} + {{ lookup('container_volumes', service_name) | indent(4) }} + healthcheck: + test: ["CMD", "tor", "--verify-config", "-f", "{{ lookup('volume', 'svc-net-tor', 'tor_torrc').target }}"] + interval: 60s + timeout: 10s + retries: 3 + start_period: {{ '150s' if TOR_FLAVOR == 'chutney' else '10s' }} + +{{ lookup('compose_volumes') }} +{{ lookup('compose_networks') }} diff --git a/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 b/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 new file mode 100644 index 0000000000..cf9d9032ef --- /dev/null +++ b/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 @@ -0,0 +1,20 @@ +{% if TOR_DNSMASQ_OWNS_LISTENER %} +listen-address=127.0.0.1 +{% if TOR_CONTAINER_DNS_HOST | length > 0 %} +listen-address={{ TOR_CONTAINER_DNS_HOST }} +{% endif %} +bind-dynamic +no-resolv +{% endif %} +no-hosts +filter-AAAA +{% if TOR_NODE_ONION | length > 0 %} +address=/{{ TOR_NODE_ONION }}/{{ TOR_HS_BACKEND_HOST }} +local=/{{ TOR_NODE_ONION }}/ +{% endif %} +server=/onion/127.0.0.1#{{ TOR_DNS_PORT }} +{% if TOR_DNSMASQ_OWNS_LISTENER %} +{% for _ns in TOR_DNS_UPSTREAMS %} +server={{ _ns }} +{% endfor %} +{% endif %} diff --git a/roles/svc-net-tor/templates/test.env.j2 b/roles/svc-net-tor/templates/test.env.j2 new file mode 100644 index 0000000000..10028ca3a0 --- /dev/null +++ b/roles/svc-net-tor/templates/test.env.j2 @@ -0,0 +1,5 @@ +NGINX_SERVERS_DIR={{ lookup('nginx', 'directories.configuration.servers') }} +RETRIES=5 +SLEEP_SECONDS=10 +TOR_DNSMASQ_CONF={{ TOR_DNSMASQ_CONF }} +TOR_SOCKS={{ lookup('tor_socks') }} diff --git a/roles/svc-net-tor/templates/torrc.j2 b/roles/svc-net-tor/templates/torrc.j2 new file mode 100644 index 0000000000..b2167aeea9 --- /dev/null +++ b/roles/svc-net-tor/templates/torrc.j2 @@ -0,0 +1,35 @@ +# Managed by Infinito.Nexus (roles/svc-net-tor) — do not edit by hand. +RunAsDaemon 0 +Log notice stdout +DataDirectory {{ lookup('volume', 'svc-net-tor', 'tor_data').target }} + +SocksPort {{ lookup('tor_socks', '0.0.0.0') }} +SocksPolicy accept 127.0.0.0/8 +SocksPolicy accept 10.0.0.0/8 +SocksPolicy accept 172.16.0.0/12 +SocksPolicy accept 192.168.0.0/16 +SocksPolicy reject * +ControlPort 127.0.0.1:9051 +CookieAuthentication 1 + +{% if not (TOR_USE_ENTRY_GUARDS | bool) %} +UseEntryGuards 0 +{% endif %} + +{% if TOR_FLAVOR == 'chutney' %} +%include /run/tor/chutney-net.conf +{% endif %} + +{% if TOR_EGRESS_ROUTER_ENABLED | bool %} +AutomapHostsOnResolve 1 +AutomapHostsSuffixes .onion +VirtualAddrNetworkIPv4 {{ TOR_EGRESS_VIRTUAL_NET_IPV4 }} +TransPort 127.0.0.1:{{ TOR_TRANS_PORT }} +DNSPort 127.0.0.1:{{ TOR_DNS_PORT }} +{% endif %} +HiddenServiceDir /var/lib/tor/infinito/node/ +HiddenServiceVersion 3 +HiddenServicePort 80 {{ TOR_HS_BACKEND_HOST }}:80 +{% for _p in TOR_ONION_EXTRA_PORTS %} +HiddenServicePort {{ _p.onion_port }} {{ TOR_HS_BACKEND_HOST }}:{{ _p.target.rsplit(':', 1) | last }} +{% endfor %} diff --git a/roles/svc-net-tor/vars/main.yml b/roles/svc-net-tor/vars/main.yml new file mode 100644 index 0000000000..5a5fb0402b --- /dev/null +++ b/roles/svc-net-tor/vars/main.yml @@ -0,0 +1,28 @@ +--- +# General +application_id: "svc-net-tor" + +TOR_IMAGE: "{{ lookup('config', application_id, 'services.tor.image') }}" +TOR_VERSION: "{{ lookup('config', application_id, 'services.tor.version') }}" +TOR_CONTAINER: "{{ lookup('config', application_id, 'services.tor.name') }}" + +TOR_SOCKS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.socks') }}" +TOR_NODE_ONION: "{{ lookup('config', application_id, 'services.tor.node', '') }}" +TOR_USE_ENTRY_GUARDS: "{{ lookup('config', application_id, 'services.tor.use_entry_guards') | bool }}" +TOR_FLAVOR: "{{ lookup('config', application_id, 'services.tor.flavor') }}" +TOR_TRANS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.trans') }}" +TOR_DNS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.dns') }}" +TOR_DNSMASQ_CONF: "/etc/dnsmasq.d/tor-onion.conf" +TOR_CONTAINER_DNS_HOST: "{{ ansible_facts['docker0']['ipv4']['address'] | default('', true) }}" +TOR_HS_BACKEND_HOST: "{{ ansible_facts['default_ipv4']['address'] if DEPLOYMENT_MODE == 'swarm' else (TOR_CONTAINER_DNS_HOST | ternary(TOR_CONTAINER_DNS_HOST, '127.0.0.1')) + }}" + +TOR_DATA_DIR: "{{ [ DIR_VAR_LIB, application_id, 'data' ] | path_join }}" +TOR_CONFIG_DIR: "{{ [ DIR_VAR_LIB, application_id, 'config' ] | path_join }}" +TOR_TORRC_HOST: "{{ [ TOR_CONFIG_DIR, 'torrc' ] | path_join }}" +TOR_HS_DIR: "{{ [ TOR_DATA_DIR, 'infinito', 'node' ] | path_join }}" + +TOR_HS_SRC_DIR: "{{ lookup('path_absolute', '.onion-identity', 'hs') }}" + +TOR_INSTANCE_DIR: "{{ lookup('container', application_id, 'directories.instance') }}" +TOR_ENTRYPOINT_HOST: "{{ [ TOR_INSTANCE_DIR, 'entrypoint.sh' ] | path_join }}" diff --git a/roles/svc-net-wireguard-core/README.md b/roles/svc-net-wireguard-core/README.md index 3a0938a76b..a49b90c6f9 100644 --- a/roles/svc-net-wireguard-core/README.md +++ b/roles/svc-net-wireguard-core/README.md @@ -28,7 +28,7 @@ flowchart LR svc_wireguard_core -- "1:1" --> dpt_svc_net_wireguard_plain ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-net-wireguard-core/handlers/main.yml b/roles/svc-net-wireguard-core/handlers/main.yml index 78c5f749b0..06ca30b0f1 100644 --- a/roles/svc-net-wireguard-core/handlers/main.yml +++ b/roles/svc-net-wireguard-core/handlers/main.yml @@ -1,10 +1,12 @@ --- -- name: "restart wireguard" +- name: "🔄 restart wireguard" + listen: restart-wireguard systemd: name: wg-quick@wg0.service state: restarted enabled: true daemon_reload: true -- name: "reload sysctl configuration" +- name: "♻️ reload sysctl configuration" + listen: reload-sysctl-configuration shell: "sysctl --load='/etc/sysctl.d/wireguard-ip.conf'" diff --git a/roles/svc-net-wireguard-core/tasks/00_core.yml b/roles/svc-net-wireguard-core/tasks/00_core.yml index 9ff4ad1a2f..b81e957077 100644 --- a/roles/svc-net-wireguard-core/tasks/00_core.yml +++ b/roles/svc-net-wireguard-core/tasks/00_core.yml @@ -9,7 +9,7 @@ dest: /etc/sysctl.d/wireguard-ip.conf owner: root group: root - notify: reload sysctl configuration + notify: reload-sysctl-configuration - name: "🚀 deploy {{ WG0_CONF_DEST }}" copy: @@ -17,6 +17,6 @@ dest: "{{ WG0_CONF_DEST }}" owner: root group: root - notify: restart wireguard + notify: restart-wireguard - include_tasks: utils/once/flag.yml diff --git a/roles/svc-net-wireguard-firewalled/README.md b/roles/svc-net-wireguard-firewalled/README.md index 56f41ca054..4279ac4fd1 100644 --- a/roles/svc-net-wireguard-firewalled/README.md +++ b/roles/svc-net-wireguard-firewalled/README.md @@ -27,7 +27,7 @@ flowchart LR dep_svc_net_wireguard_plain -- "1:1" --> svc_wireguard_firewalled ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-net-wireguard-plain/README.md b/roles/svc-net-wireguard-plain/README.md index 7c9b501b87..994536e79a 100644 --- a/roles/svc-net-wireguard-plain/README.md +++ b/roles/svc-net-wireguard-plain/README.md @@ -31,7 +31,7 @@ flowchart LR svc_wireguard_plain -- "1:1" --> dpt_svc_net_wireguard_firewalled ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-opt-keyboard-color/README.md b/roles/svc-opt-keyboard-color/README.md index 09c2524ade..583c7b8d73 100644 --- a/roles/svc-opt-keyboard-color/README.md +++ b/roles/svc-opt-keyboard-color/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-opt-keyboard-color/files/script.py b/roles/svc-opt-keyboard-color/files/python/script.py similarity index 83% rename from roles/svc-opt-keyboard-color/files/script.py rename to roles/svc-opt-keyboard-color/files/python/script.py index c4236c2793..a5e977eaec 100644 --- a/roles/svc-opt-keyboard-color/files/script.py +++ b/roles/svc-opt-keyboard-color/files/python/script.py @@ -71,25 +71,19 @@ def calculate_transition_ratio(current_time, start_time, end_time): Returns: float: The transition ratio between 0 and 1. """ - # Use the current date for timestamp calculation today = datetime.datetime.now().date() # noqa: DTZ005 user's local "today" for time-of-day color picking - # Calculate timestamps for the start and end of the current period start_timestamp = datetime.datetime.combine(today, start_time).timestamp() end_timestamp = datetime.datetime.combine(today, end_time).timestamp() - # If start and end times are the same, return 0 to indicate no transition if start_timestamp == end_timestamp: return 0 - # Calculate the current timestamp current_timestamp = datetime.datetime.combine(today, current_time).timestamp() - # Calculate the transition ratio transition_duration = end_timestamp - start_timestamp time_since_start = current_timestamp - start_timestamp - # Ratio as the proportion of time elapsed in the total transition duration return time_since_start / transition_duration @@ -111,16 +105,16 @@ def change_keyboard_color(color, device_id): def main(vendor_and_product_id): color_times = { - "22:00": ("990000", "990000"), # Night - "21:00": ("0000ff", "990000"), # Evening Blue to Night - "20:00": ("fdbe51", "0000ff"), # Evening Golden to Blue - "19:30": ("ff4500", "fdbe51"), # Sunset to Golden - "12:00": ("ffffff", "ff4500"), # Noon to Sunset - "07:30": ("ffd700", "ffffff"), # Sunrise to Noon - "07:00": ("f9c80e", "ffd700"), # Morning Golden to Sunrise - "06:00": ("ff7f00", "f9c80e"), # Dawn to Golden - "05:00": ("5bc0eb", "ff7f00"), # Morning Blue to Dawn - "04:00": ("990000", "5bc0eb"), # Night to Blue + "22:00": ("990000", "990000"), + "21:00": ("0000ff", "990000"), + "20:00": ("fdbe51", "0000ff"), + "19:30": ("ff4500", "fdbe51"), + "12:00": ("ffffff", "ff4500"), + "07:30": ("ffd700", "ffffff"), + "07:00": ("f9c80e", "ffd700"), + "06:00": ("ff7f00", "f9c80e"), + "05:00": ("5bc0eb", "ff7f00"), + "04:00": ("990000", "5bc0eb"), } current_time = datetime.datetime.now().time() # noqa: DTZ005 user's local time-of-day for color picking diff --git a/roles/svc-opt-ssd-hdd/README.md b/roles/svc-opt-ssd-hdd/README.md index e52880e9ca..17e0612a9b 100644 --- a/roles/svc-opt-ssd-hdd/README.md +++ b/roles/svc-opt-ssd-hdd/README.md @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-opt-ssd-hdd/files/__init__.py b/roles/svc-opt-ssd-hdd/files/python/__init__.py similarity index 100% rename from roles/svc-opt-ssd-hdd/files/__init__.py rename to roles/svc-opt-ssd-hdd/files/python/__init__.py diff --git a/roles/svc-opt-ssd-hdd/files/script.py b/roles/svc-opt-ssd-hdd/files/python/script.py similarity index 95% rename from roles/svc-opt-ssd-hdd/files/script.py rename to roles/svc-opt-ssd-hdd/files/python/script.py index 141874d4c8..ba59e5caa3 100644 --- a/roles/svc-opt-ssd-hdd/files/script.py +++ b/roles/svc-opt-ssd-hdd/files/python/script.py @@ -1,3 +1,6 @@ +# nocheck: mirrored-unit-test - orchestrates docker stop/start around an rsync move +# between disks; its helpers read live container state through docker inspect and a unit +# test would pin the mock, not the migration import argparse import shutil import subprocess diff --git a/roles/svc-opt-ssd-hdd/meta/schema.yml b/roles/svc-opt-ssd-hdd/meta/secrets.yml similarity index 100% rename from roles/svc-opt-ssd-hdd/meta/schema.yml rename to roles/svc-opt-ssd-hdd/meta/secrets.yml diff --git a/roles/svc-opt-swapfile/README.md b/roles/svc-opt-swapfile/README.md index 3f999f6e47..eb3c79fd82 100644 --- a/roles/svc-opt-swapfile/README.md +++ b/roles/svc-opt-swapfile/README.md @@ -23,7 +23,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/svc-opt-swapfile/meta/services.yml b/roles/svc-opt-swapfile/meta/services.yml index 1b79fbf071..fb77736601 100644 --- a/roles/svc-opt-swapfile/meta/services.yml +++ b/roles/svc-opt-swapfile/meta/services.yml @@ -3,6 +3,8 @@ swapfile: modes: host: enabled: true + repository: https://github.com/kevinveenbirkenbach/swap-forge.git + ref: v1.0.0 swapfile_size: "{{ ansible_facts['memtotal_mb'] | int }}M" lifecycle: beta min_storage: "50MB" diff --git a/roles/svc-opt-swapfile/tasks/00_core.yml b/roles/svc-opt-swapfile/tasks/00_core.yml index 5cc0dc2300..88083b366f 100644 --- a/roles/svc-opt-swapfile/tasks/00_core.yml +++ b/roles/svc-opt-swapfile/tasks/00_core.yml @@ -1,10 +1,11 @@ --- - name: 📦 Install ' include_role: - name: pkgmgr-install + name: sys-pip-install vars: - package_name: "{{ SWAPFILE_PKG }}" - when: run_once_pkgmgr_install is not defined + # TODO: switch to the PyPI name 'swap-forge' once it is published + package_name: "git+{{ SWAPFILE_REPO }}@{{ SWAPFILE_REF }}" + global_install: true - name: ▶️ Execute create swapfile script shell: "{{ SWAPFILE_PKG }} '{{ SWAPFILE_SIZE }}'" diff --git a/roles/svc-opt-swapfile/vars/main.yml b/roles/svc-opt-swapfile/vars/main.yml index 2ee3c3e214..c0efa2bf6e 100644 --- a/roles/svc-opt-swapfile/vars/main.yml +++ b/roles/svc-opt-swapfile/vars/main.yml @@ -3,3 +3,5 @@ application_id: "svc-opt-swapfile" SWAPFILE_SIZE: "{{ lookup('config', application_id, 'services.swapfile.swapfile_size') }}" SWAPFILE_PKG: "swap-forge" +SWAPFILE_REPO: "{{ lookup('config', application_id, 'services.swapfile.repository') }}" +SWAPFILE_REF: "{{ lookup('config', application_id, 'services.swapfile.ref') }}" diff --git a/roles/svc-prx-openresty/README.md b/roles/svc-prx-openresty/README.md index eed4ea09f6..cdb8666be5 100644 --- a/roles/svc-prx-openresty/README.md +++ b/roles/svc-prx-openresty/README.md @@ -24,15 +24,18 @@ The diagram places OpenResty in the Infinito.Nexus cosmos: the components it dep flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_net_tor["svc-net-tor 🐳🐝"] end subgraph role [svc-prx-openresty 🐳🐝] svc_openresty["openresty"] + svc_tor["tor"] svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -- "1:1" --> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-prx-openresty/handlers/main.yml b/roles/svc-prx-openresty/handlers/main.yml index aea48355b0..399b94f75c 100644 --- a/roles/svc-prx-openresty/handlers/main.yml +++ b/roles/svc-prx-openresty/handlers/main.yml @@ -1,4 +1,8 @@ --- -- name: Restart and validate OpenResty - listen: restart openresty - include_tasks: restart_and_validate.yml +- name: 🔄 Restart and validate OpenResty + listen: restart-openresty + include_tasks: restart.yml + +- name: ♻️ Reload OpenResty + listen: reload-openresty + include_tasks: reload.yml diff --git a/roles/svc-prx-openresty/handlers/reload.yml b/roles/svc-prx-openresty/handlers/reload.yml new file mode 100644 index 0000000000..8c7873b25a --- /dev/null +++ b/roles/svc-prx-openresty/handlers/reload.yml @@ -0,0 +1,32 @@ +--- +# Vhosts, redirect configs and body_filter Lua all land under +# directories.configuration.base, which sits inside the conf.d DIRECTORY bind. +# A directory keeps its inode across an atomic file write, so the running +# container already sees the new file and SIGHUP is enough -- unlike +# nginx.conf, which is bound as a FILE and whose inode the task pins at create +# time (see restart.yml). +- name: ✅ Validate OpenResty configuration before reloading + ansible.builtin.shell: > + container exec {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} openresty -t -q + register: openresty_test_reload + changed_when: false + retries: 10 + delay: 3 + until: openresty_test_reload.rc == 0 + failed_when: > + openresty_test_reload.rc != 0 and + ('is not running' not in ((openresty_test_reload.stderr | default('')) | lower)) and + ('no such container' not in ((openresty_test_reload.stderr | default('')) | lower)) and + ('is restarting' not in ((openresty_test_reload.stderr | default('')) | lower)) + +- name: ♻️ Reload OpenResty + ansible.builtin.shell: > + container exec {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} openresty -s reload + register: openresty_reload + changed_when: openresty_reload.rc == 0 + failed_when: > + openresty_reload.rc != 0 and + ('is not running' not in ((openresty_reload.stderr | default('')) | lower)) and + ('no such container' not in ((openresty_reload.stderr | default('')) | lower)) and + ('is restarting' not in ((openresty_reload.stderr | default('')) | lower)) + when: openresty_test_reload.rc == 0 diff --git a/roles/svc-prx-openresty/handlers/restart_and_validate.yml b/roles/svc-prx-openresty/handlers/restart.yml similarity index 88% rename from roles/svc-prx-openresty/handlers/restart_and_validate.yml rename to roles/svc-prx-openresty/handlers/restart.yml index a101164285..48b14ea70e 100644 --- a/roles/svc-prx-openresty/handlers/restart_and_validate.yml +++ b/roles/svc-prx-openresty/handlers/restart.yml @@ -4,10 +4,10 @@ # source inode changes; the running task keeps the old, deleted inode # mounted and `openresty -s reload` reads stale config. Force a task # redeploy on the manager to remount the live inode. -- name: Compose-mode force-recreate (file bind-mount pins the inode; -s reload reads stale config) +- name: 🐳 Compose-mode force-recreate (a file bind-mount pins the inode) when: DEPLOYMENT_MODE == 'compose' block: - - name: Force-recreate OpenResty (remounts the config bind to the live inode) + - name: 🔄 Force-recreate OpenResty (remounts the config bind to the inode) ansible.builtin.shell: | set -euo pipefail compose up -d --force-recreate --remove-orphans @@ -17,7 +17,7 @@ register: openresty_restart changed_when: true - - name: Validate OpenResty configuration (Post-Flight-Check) + - name: ✅ Validate OpenResty configuration (Post-Flight-Check) ansible.builtin.shell: > container exec {{ lookup('container_address', 'svc-prx-openresty', 'openresty') }} openresty -t -q register: openresty_test_post @@ -31,7 +31,7 @@ ('no such container' not in ((openresty_test_post.stderr | default('')) | lower)) and ('is restarting' not in ((openresty_test_post.stderr | default('')) | lower)) -- name: Force OpenResty service redeploy +- name: 🚀 Force OpenResty service redeploy ansible.builtin.command: >- container service update --force {{ lookup('container_service', 'svc-prx-openresty', 'openresty') }} @@ -47,7 +47,7 @@ - DEPLOYMENT_MODE == 'swarm' - IS_STACK_HOST | bool -- name: "MODE_DEBUG: wait + validate OpenResty" +- name: "🐛 MODE_DEBUG: wait + validate OpenResty" when: MODE_DEBUG | bool block: - ansible.builtin.command: container ps -a --format '{{"{{.Names}} {{.Status}}"}}' diff --git a/roles/svc-prx-openresty/meta/services.yml b/roles/svc-prx-openresty/meta/services.yml index 2f89e13f3a..9a88ba83d9 100644 --- a/roles/svc-prx-openresty/meta/services.yml +++ b/roles/svc-prx-openresty/meta/services.yml @@ -23,6 +23,11 @@ openresty: lifecycle: beta pids_limit: 256 +# nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag # nocheck: dynamic-flag - proxy state is fully re-rendered by the deploy (configs, certs via binds), the backup consumer stays permanently off container_backup: bond: 1 diff --git a/roles/svc-prx-openresty/meta/variants.yml b/roles/svc-prx-openresty/meta/variants.yml new file mode 100644 index 0000000000..1576e2511e --- /dev/null +++ b/roles/svc-prx-openresty/meta/variants.yml @@ -0,0 +1,7 @@ +--- +- services: + tor: + enabled: true +- services: + tor: + enabled: true diff --git a/roles/svc-prx-openresty/tasks/00_core.yml b/roles/svc-prx-openresty/tasks/00_core.yml index 33807d31de..ab217ef9eb 100644 --- a/roles/svc-prx-openresty/tasks/00_core.yml +++ b/roles/svc-prx-openresty/tasks/00_core.yml @@ -5,6 +5,7 @@ block: - name: "🔎 Stat the docker socket so the swarm openresty worker can be group-added to it" ansible.builtin.stat: + # nocheck: volumes-path-single-spot this stats the socket on the HOST; it only happens to spell the same string as the container mount target path: /var/run/docker.sock register: _openresty_docker_sock diff --git a/roles/svc-prx-openresty/templates/compose.yml.j2 b/roles/svc-prx-openresty/templates/compose.yml.j2 index ae9011bed7..579fcd075e 100644 --- a/roles/svc-prx-openresty/templates/compose.yml.j2 +++ b/roles/svc-prx-openresty/templates/compose.yml.j2 @@ -23,13 +23,12 @@ published: 443 protocol: tcp mode: host - extra_hosts: - - "host.docker.internal:host-gateway" + {{ lookup('container_extra_hosts', extra_hosts=['host.docker.internal:host-gateway']) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% else %} network_mode: "host" {% endif %} - {{ lookup('container_volumes', application_id, 'openresty') | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} command: ["openresty", "-g", "daemon off;"] healthcheck: test: ["CMD", "openresty", "-t", "-q"] @@ -37,5 +36,5 @@ timeout: 5s retries: 3 -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-registry-cache/README.md b/roles/svc-registry-cache/README.md index 3e4abec390..42dcf68150 100644 --- a/roles/svc-registry-cache/README.md +++ b/roles/svc-registry-cache/README.md @@ -26,6 +26,7 @@ The diagram places Docker Registry Cache in the Infinito.Nexus cosmos: the compo flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_swarm_node["svc-swarm-node 💻"] end subgraph role [svc-registry-cache 🐳] svc_node["node"] @@ -33,9 +34,10 @@ flowchart LR svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -- "1:1" --> svc_container_backup + dep_svc_swarm_node -- "1:1" --> svc_node ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-registry-cache/meta/services.yml b/roles/svc-registry-cache/meta/services.yml index fcbd2ceceb..bba891a9e3 100644 --- a/roles/svc-registry-cache/meta/services.yml +++ b/roles/svc-registry-cache/meta/services.yml @@ -5,6 +5,10 @@ node: shared: true bond: 1 cache: + healthcheck: + flavor: wget + port_key: registry + path: v2/ modes: compose: enabled: true diff --git a/roles/svc-registry-cache/meta/volumes.yml b/roles/svc-registry-cache/meta/volumes.yml index 3dc71c767f..bc99e027e6 100644 --- a/roles/svc-registry-cache/meta/volumes.yml +++ b/roles/svc-registry-cache/meta/volumes.yml @@ -3,6 +3,7 @@ data: type: volume name: docker_registry_cache_data + backup: false mounts: - service: cache target: /var/lib/registry diff --git a/roles/svc-registry-cache/templates/compose.yml.j2 b/roles/svc-registry-cache/templates/compose.yml.j2 index 6279d00837..6d3f9137c7 100644 --- a/roles/svc-registry-cache/templates/compose.yml.j2 +++ b/roles/svc-registry-cache/templates/compose.yml.j2 @@ -8,9 +8,10 @@ environment: REGISTRY_PROXY_REMOTEURL: "{{ REGISTRY_CACHE_PROXY_REMOTE_URL }}" {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_ports', ['cache', 'registry']) | indent(4) }} - {{ lookup('container_volumes', application_id, entity_name) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-registry-docker/README.md b/roles/svc-registry-docker/README.md index f7b3d92460..0dc06f232a 100644 --- a/roles/svc-registry-docker/README.md +++ b/roles/svc-registry-docker/README.md @@ -24,6 +24,7 @@ The diagram places Docker Registry in the Infinito.Nexus cosmos: the components flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local 💻"] + dep_svc_swarm_node["svc-swarm-node 💻"] end subgraph role [svc-registry-docker 🐳] svc_node["node"] @@ -31,9 +32,10 @@ flowchart LR svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -- "1:1" --> svc_container_backup + dep_svc_swarm_node -- "1:1" --> svc_node ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-registry-docker/meta/services.yml b/roles/svc-registry-docker/meta/services.yml index 1340c5d7d9..83afc01131 100644 --- a/roles/svc-registry-docker/meta/services.yml +++ b/roles/svc-registry-docker/meta/services.yml @@ -5,6 +5,10 @@ node: shared: true bond: 1 docker: + healthcheck: + flavor: wget + port_key: registry + path: v2/ modes: compose: enabled: true diff --git a/roles/svc-registry-docker/meta/volumes.yml b/roles/svc-registry-docker/meta/volumes.yml index 6cc75d8274..0d8ff7563a 100644 --- a/roles/svc-registry-docker/meta/volumes.yml +++ b/roles/svc-registry-docker/meta/volumes.yml @@ -3,6 +3,7 @@ data: type: volume name: docker_registry_data + backup: false mounts: - service: docker target: /var/lib/registry diff --git a/roles/svc-registry-docker/templates/compose.yml.j2 b/roles/svc-registry-docker/templates/compose.yml.j2 index d7ca2f8c13..2a8a076403 100644 --- a/roles/svc-registry-docker/templates/compose.yml.j2 +++ b/roles/svc-registry-docker/templates/compose.yml.j2 @@ -8,9 +8,10 @@ environment: REGISTRY_HTTP_ADDR: "{{ REGISTRY_BIND_IP }}:{{ REGISTRY_PORT }}" {% else %} + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_ports', ['docker', 'registry']) | indent(4) }} {% endif %} - {{ lookup('container_volumes', application_id, entity_name) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} {% if DEPLOYMENT_MODE == 'swarm' %} networks: # nocheck: networks-literal hostnet: {} @@ -18,7 +19,7 @@ {{ lookup('container_networks') | indent(4) }} {% endif %} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} {% if DEPLOYMENT_MODE == 'swarm' %} networks: # nocheck: networks-literal hostnet: diff --git a/roles/svc-runner/README.md b/roles/svc-runner/README.md index 4087b32818..fcf9c3dd32 100644 --- a/roles/svc-runner/README.md +++ b/roles/svc-runner/README.md @@ -25,7 +25,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-runner/files/entrypoint.sh b/roles/svc-runner/files/shell/entrypoint.sh similarity index 83% rename from roles/svc-runner/files/entrypoint.sh rename to roles/svc-runner/files/shell/entrypoint.sh index cb9581820b..f2286658fa 100644 --- a/roles/svc-runner/files/entrypoint.sh +++ b/roles/svc-runner/files/shell/entrypoint.sh @@ -15,8 +15,8 @@ if [[ "${DOCKER_IN_CONTAINER:-false}" == "true" ]]; then exec sleep infinity fi -rm -rf ./_work 2>/dev/null || true -find /tmp -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true +rm -rf ./_work 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +find /tmp -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error : "${RUNNER_API_TOKEN:?RUNNER_API_TOKEN must be set}" : "${RUNNER_GITHUB_OWNER:?RUNNER_GITHUB_OWNER must be set}" diff --git a/roles/svc-runner/files/test/.nocheck b/roles/svc-runner/files/test/.nocheck new file mode 100644 index 0000000000..65c4aed432 --- /dev/null +++ b/roles/svc-runner/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; grouped by purpose, screened and kept on 2026-08-21. diff --git a/roles/svc-runner/meta/schema.yml b/roles/svc-runner/meta/secrets.yml similarity index 100% rename from roles/svc-runner/meta/schema.yml rename to roles/svc-runner/meta/secrets.yml diff --git a/roles/svc-runner/meta/services.yml b/roles/svc-runner/meta/services.yml index 638783c100..c02f122847 100644 --- a/roles/svc-runner/meta/services.yml +++ b/roles/svc-runner/meta/services.yml @@ -1,5 +1,6 @@ --- # nocheck: dockerfile-custom +# nocheck: image-healthcheck CI runner, no service port; readiness is the runner's own registration runner: modes: compose: @@ -7,16 +8,14 @@ runner: swarm: enabled: true lifecycle: beta - workload: node-local proxy: service_key: runner-1 github_owner: infinito-nexus github_repo: core docker_base: /mnt/docker image: ubuntu - # todo: bump to the current ubuntu release once download.docker.com publishes a repo for its codename (26.10 "stonking" has none yet) # nocheck: docker-version - version: "24.04" + version: "26.04" docker_gid_fallback: 999 project_prefix: runner sysctl_conf: /etc/sysctl.d/99-github-runner.conf diff --git a/roles/svc-runner/tasks/03_image.yml b/roles/svc-runner/tasks/03_image.yml index cc7b01e5dc..056554acc4 100644 --- a/roles/svc-runner/tasks/03_image.yml +++ b/roles/svc-runner/tasks/03_image.yml @@ -15,7 +15,7 @@ - name: 📄 Copy entrypoint to build context ansible.builtin.copy: # nocheck: stack-host-consumer (include is IS_STACK_HOST-gated) - src: entrypoint.sh + src: shell/entrypoint.sh dest: "{{ RUNNER_INSTALL_DIR }}/build/entrypoint.sh" mode: "0755" diff --git a/roles/svc-runner/templates/compose.yml.j2 b/roles/svc-runner/templates/compose.yml.j2 index 2b87a155c7..c59a1dec11 100644 --- a/roles/svc-runner/templates/compose.yml.j2 +++ b/roles/svc-runner/templates/compose.yml.j2 @@ -24,4 +24,4 @@ {{ lookup('compose_networks', node_local=True) }} -{{ lookup('compose_volumes', application_id) }} +{{ lookup('compose_volumes') }} diff --git a/roles/svc-storage-nfs-client/README.md b/roles/svc-storage-nfs-client/README.md index 9b0f30c995..3586720f91 100644 --- a/roles/svc-storage-nfs-client/README.md +++ b/roles/svc-storage-nfs-client/README.md @@ -32,7 +32,7 @@ flowchart LR dep_svc_storage_nfs_server -. "0..1" .-> svc_nfs_server ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-storage-nfs-client/files/premount_state.sh b/roles/svc-storage-nfs-client/files/shell/premount_state.sh similarity index 100% rename from roles/svc-storage-nfs-client/files/premount_state.sh rename to roles/svc-storage-nfs-client/files/shell/premount_state.sh diff --git a/roles/svc-storage-nfs-client/tasks/main.yml b/roles/svc-storage-nfs-client/tasks/main.yml index 3b0366eb27..1f19f53630 100644 --- a/roles/svc-storage-nfs-client/tasks/main.yml +++ b/roles/svc-storage-nfs-client/tasks/main.yml @@ -66,7 +66,7 @@ - name: "🔍 Detect {{ DIR_VAR_LIB }} pre-mount state" ansible.builtin.script: - cmd: "{{ role_path }}/files/premount_state.sh" + cmd: "{{ role_path }}/files/shell/premount_state.sh" executable: /bin/bash environment: DIR_VAR_LIB: "{{ DIR_VAR_LIB }}" diff --git a/roles/svc-storage-nfs-server/README.md b/roles/svc-storage-nfs-server/README.md index cffb61efdf..f2924e9000 100644 --- a/roles/svc-storage-nfs-server/README.md +++ b/roles/svc-storage-nfs-server/README.md @@ -38,7 +38,7 @@ flowchart LR svc_nfs_server -. "0..1" .-> dpt_svc_storage_nfs_client ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-storage-nfs-server/TODO.md b/roles/svc-storage-nfs-server/TODO.md index bc97f6bbb7..2ebf596e6f 100644 --- a/roles/svc-storage-nfs-server/TODO.md +++ b/roles/svc-storage-nfs-server/TODO.md @@ -1,5 +1,5 @@ # TODO -- [ ] Add `files/test.sh` and run BOTH flavors through it: +- [ ] Add `files/test/test.sh` plus `templates/test.env.j2` and run BOTH flavors through it: - kernel: needs a real host (kernel nfsd wedges in privileged DinD). - ganesha: userspace, runs in the swarm DinD test node. diff --git a/roles/svc-storage-nfs-server/files/nfs-ganesha-restart.conf b/roles/svc-storage-nfs-server/files/nfs-ganesha-restart.conf index f9151bb4a9..5e610340f6 100644 --- a/roles/svc-storage-nfs-server/files/nfs-ganesha-restart.conf +++ b/roles/svc-storage-nfs-server/files/nfs-ganesha-restart.conf @@ -8,3 +8,4 @@ RestartSec=2 Environment="OPTIONS=-L SYSLOG -f /etc/ganesha/ganesha.conf -N NIV_EVENT" ExecStartPost=/usr/bin/timeout 20 /bin/bash -c 'until (exec 3<>/dev/tcp/127.0.0.1/2049) 2>/dev/null; do sleep 1; done' TimeoutStopSec=10 +TimeoutAbortSec=10 diff --git a/roles/svc-storage-nfs-server/files/shell/ganesha-serve.sh b/roles/svc-storage-nfs-server/files/shell/ganesha-serve.sh new file mode 100755 index 0000000000..92d8edbd4c --- /dev/null +++ b/roles/svc-storage-nfs-server/files/shell/ganesha-serve.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Bring nfs-ganesha into a serving state and prove it, or fail with the reason. +# +# Params: +# $1 systemd unit name (without .service) +# $2 TCP port that proves the server is listening +# $3 seconds to wait for that port +# $4 "restart" after a config change, "start" otherwise +# +# Exit: 0 once the port accepts a connection, 1 with the unit's status and +# journal on stderr. +# Stdout: the word CHANGED when the unit's state was actually altered. +set -u + +unit="$1" +port="$2" +budget="$3" +action="$4" + +was_active=false +if systemctl is-active --quiet "$unit"; then + was_active=true +fi + +systemctl_output="$(systemctl "$action" "$unit" 2>&1)" +systemctl_rc=$? + +if [ "$action" = "restart" ] || [ "$was_active" = false ]; then + echo CHANGED +fi + +deadline=$(( $(date +%s) + budget )) +while [ "$(date +%s)" -lt "$deadline" ]; do + if (exec 3<>"/dev/tcp/127.0.0.1/${port}") 2>/dev/null; then + exec 3>&- 3<&- + exit 0 + fi + sleep 1 +done + +{ + echo "nfs-ganesha did not listen on ${port} within ${budget}s after '${action}'." + echo "systemctl ${action} exited ${systemctl_rc}: ${systemctl_output}" + echo "--- systemctl status ---" + systemctl status "$unit" --no-pager --lines=20 2>&1 + echo "--- journal ---" + journalctl -u "$unit" --no-pager --lines=40 2>&1 +} >&2 +exit 1 diff --git a/roles/svc-storage-nfs-server/handlers/main.yml b/roles/svc-storage-nfs-server/handlers/main.yml index ec60f9f260..3a8f8b4480 100644 --- a/roles/svc-storage-nfs-server/handlers/main.yml +++ b/roles/svc-storage-nfs-server/handlers/main.yml @@ -1,8 +1,11 @@ --- -- name: "Reload NFS exports" +- name: "♻️ Reload NFS exports" + listen: reload-nfs-exports ansible.builtin.command: exportfs -ra -- name: "Restart NFS ganesha" - ansible.builtin.systemd: - name: "{{ SVC_STORAGE_NFS_SERVER_SERVICE['ganesha'][ansible_facts['os_family']] }}" - state: restarted +- name: "🔄 Restart NFS ganesha" + listen: restart-nfs-ganesha + ansible.builtin.script: + cmd: "{{ SVC_STORAGE_NFS_SERVER_GANESHA_SERVE }} restart" + register: svc_storage_nfs_server_ganesha_restart + changed_when: "'CHANGED' in svc_storage_nfs_server_ganesha_restart.stdout" diff --git a/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml b/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml index e0db38abb9..e9653e6b47 100644 --- a/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml +++ b/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml @@ -1,7 +1,7 @@ --- - name: "🔍 Detect controller {{ DIR_VAR_LIB }} pre-mount state" ansible.builtin.script: - cmd: "{{ lookup('path_absolute', 'roles/svc-storage-nfs-client/files/premount_state.sh') }}" + cmd: "{{ lookup('path_absolute', 'roles/svc-storage-nfs-client/files/shell/premount_state.sh') }}" executable: /bin/bash environment: DIR_VAR_LIB: "{{ DIR_VAR_LIB }}" diff --git a/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml b/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml index 6be4e99224..a32595baff 100644 --- a/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml +++ b/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml @@ -13,7 +13,7 @@ group: root mode: "0644" when: ansible_facts['os_family'] == 'Archlinux' - notify: "Restart NFS ganesha" + notify: "restart-nfs-ganesha" - name: "🔧 Mask the broken nfs-ganesha-config helper unit" ansible.builtin.systemd: @@ -46,7 +46,7 @@ owner: root group: root mode: "0644" - notify: "Restart NFS ganesha" + notify: "restart-nfs-ganesha" - name: "📁 Ensure the nfs-ganesha systemd drop-in dir exists" ansible.builtin.file: @@ -63,7 +63,7 @@ owner: root group: root mode: "0644" - notify: "Restart NFS ganesha" + notify: "restart-nfs-ganesha" - name: "🔄 Reload systemd so the drop-in is live before ganesha starts" ansible.builtin.systemd: @@ -99,20 +99,8 @@ - name: "🚿 Flush handlers so a pending config change restarts ganesha first" ansible.builtin.meta: flush_handlers -- name: "🟢 Start nfs-ganesha" - ansible.builtin.systemd: - name: "{{ SVC_STORAGE_NFS_SERVER_SERVICE['ganesha'][ansible_facts['os_family']] }}" - state: started - -- name: "✅ Assert ganesha reached listen state" - ansible.builtin.wait_for: - port: 2049 - host: 127.0.0.1 - timeout: "{{ lookup('timeout', 120) | int }}" - msg: >- - Port 2049 never opened within the timeout. Check 'systemctl status - nfs-ganesha' and 'journalctl -u nfs-ganesha': a unit that stays active - but logs nothing after the export CLIENT warnings has wedged before - 'NFS SERVER INITIALIZED'. ExecStartPost now turns that wedge into a - unit failure so Restart=on-failure can recover it; this budget covers - one full recovery cycle. +- name: "🟢 Ensure nfs-ganesha serves on 2049" + ansible.builtin.script: + cmd: "{{ SVC_STORAGE_NFS_SERVER_GANESHA_SERVE }} start" + register: svc_storage_nfs_server_ganesha_start + changed_when: "'CHANGED' in svc_storage_nfs_server_ganesha_start.stdout" diff --git a/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml b/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml index 432d719191..4e58e90b49 100644 --- a/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml +++ b/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml @@ -30,7 +30,7 @@ owner: root group: root mode: "0644" - notify: "Reload NFS exports" + notify: "reload-nfs-exports" - name: "🚿 Flush handlers (exports reload before next step)" ansible.builtin.meta: flush_handlers diff --git a/roles/svc-storage-nfs-server/vars/main.yml b/roles/svc-storage-nfs-server/vars/main.yml index b2cb61e323..48b66a5f26 100644 --- a/roles/svc-storage-nfs-server/vars/main.yml +++ b/roles/svc-storage-nfs-server/vars/main.yml @@ -16,3 +16,9 @@ SVC_STORAGE_NFS_SERVER_STATE_EXPORT_OPTIONS: >- rw,sync,no_subtree_check,no_root_squash,no_all_squash SVC_STORAGE_NFS_SERVER_STATE_ALLOWED_CIDRS: - "*" + +SVC_STORAGE_NFS_SERVER_GANESHA_SERVE: >- + shell/ganesha-serve.sh + {{ SVC_STORAGE_NFS_SERVER_SERVICE['ganesha'][ansible_facts['os_family']] | quote }} + 2049 + {{ lookup('timeout', 120) | int }} diff --git a/roles/svc-swarm-manager/README.md b/roles/svc-swarm-manager/README.md index 8ca7a538a7..6d85784be6 100644 --- a/roles/svc-swarm-manager/README.md +++ b/roles/svc-swarm-manager/README.md @@ -29,7 +29,7 @@ flowchart LR dep_svc_swarm_node -. "0..1" .-> svc_node ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/svc-swarm-node/README.md b/roles/svc-swarm-node/README.md index bc7ad8f97b..63afa17c3e 100644 --- a/roles/svc-swarm-node/README.md +++ b/roles/svc-swarm-node/README.md @@ -26,12 +26,16 @@ flowchart LR svc_node["node"] end subgraph dependents [Dependents] + dpt_svc_registry_cache["svc-registry-cache 🐳"] + dpt_svc_registry_docker["svc-registry-docker 🐳"] dpt_svc_swarm_manager["svc-swarm-manager 💻"] end + svc_node -- "1:1" --> dpt_svc_registry_cache + svc_node -- "1:1" --> dpt_svc_registry_docker svc_node -. "0..1" .-> dpt_svc_swarm_manager ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ca-selfsigned/README.md b/roles/sys-ca-selfsigned/README.md index 6f5db75412..03e4cdfd8e 100644 --- a/roles/sys-ca-selfsigned/README.md +++ b/roles/sys-ca-selfsigned/README.md @@ -26,7 +26,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ca-selfsigned/files/java-with-ca-trust.sh b/roles/sys-ca-selfsigned/files/shell/java-with-ca-trust.sh similarity index 93% rename from roles/sys-ca-selfsigned/files/java-with-ca-trust.sh rename to roles/sys-ca-selfsigned/files/shell/java-with-ca-trust.sh index 615cece747..c4a089e9f4 100644 --- a/roles/sys-ca-selfsigned/files/java-with-ca-trust.sh +++ b/roles/sys-ca-selfsigned/files/shell/java-with-ca-trust.sh @@ -41,7 +41,7 @@ fi CACERTS="${JAVA_DIR}/lib/security/cacerts" if [ -w "${CACERTS}" ]; then "${KEYTOOL}" -importcert -noprompt -trustcacerts -alias "${CA_ALIAS}" \ - -file "${CA_FILE}" -keystore "${CACERTS}" -storepass changeit >/dev/null 2>&1 || true + -file "${CA_FILE}" -keystore "${CACERTS}" -storepass changeit >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error "${KEYTOOL}" -list -keystore "${CACERTS}" -storepass changeit -alias "${CA_ALIAS}" >/dev/null else rm -f /tmp/cacerts diff --git a/roles/sys-ca-selfsigned/files/with-ca-trust.sh b/roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh similarity index 76% rename from roles/sys-ca-selfsigned/files/with-ca-trust.sh rename to roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh index b489af815f..f7152392f4 100644 --- a/roles/sys-ca-selfsigned/files/with-ca-trust.sh +++ b/roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh @@ -89,33 +89,33 @@ install_anchor() { if command -v update-ca-certificates >/dev/null 2>&1; then log "Detected update-ca-certificates" if install_anchor "$CA_TRUST_CERT" "/usr/local/share/ca-certificates/${name}.crt"; then - run update-ca-certificates || true + run update-ca-certificates || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi fi if command -v update-ca-trust >/dev/null 2>&1; then log "Detected update-ca-trust" if install_anchor "$CA_TRUST_CERT" "/etc/pki/ca-trust/source/anchors/${name}.crt"; then - run update-ca-trust extract || true + run update-ca-trust extract || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi fi if command -v trust >/dev/null 2>&1; then log "Detected trust" if install_anchor "$CA_TRUST_CERT" "/etc/ca-certificates/trust-source/anchors/${name}.crt"; then - run trust extract-compat || true + run trust extract-compat || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi fi if [ -n "${CA_TRUST_CERT_EXTRA:-}" ] && [ -r "${CA_TRUST_CERT_EXTRA}" ]; then if command -v update-ca-certificates >/dev/null 2>&1 && install_anchor "$CA_TRUST_CERT_EXTRA" "/usr/local/share/ca-certificates/${name}-extra.crt"; then - run update-ca-certificates || true + run update-ca-certificates || true # nocheck: shell-or-true -- best-effort trust-store refresh; the env-based CA bundle above remains the fallback fi if command -v update-ca-trust >/dev/null 2>&1 && install_anchor "$CA_TRUST_CERT_EXTRA" "/etc/pki/ca-trust/source/anchors/${name}-extra.crt"; then - run update-ca-trust extract || true + run update-ca-trust extract || true # nocheck: shell-or-true -- best-effort trust-store refresh; the env-based CA bundle above remains the fallback fi if command -v trust >/dev/null 2>&1 && install_anchor "$CA_TRUST_CERT_EXTRA" "/etc/ca-certificates/trust-source/anchors/${name}-extra.crt"; then - run trust extract-compat || true + run trust extract-compat || true # nocheck: shell-or-true -- best-effort trust-store refresh; the env-based CA bundle above remains the fallback fi fi @@ -128,15 +128,15 @@ if command -v certutil >/dev/null 2>&1; then nss_db="${home_dir}/.pki/nssdb" log "Detected certutil; importing CA into NSS DB: ${nss_db}" - run mkdir -p "$nss_db" 2>/dev/null || true + run mkdir -p "$nss_db" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error if [ ! -f "$nss_db/cert9.db" ]; then - run certutil -N -d "sql:${nss_db}" --empty-password 2>/dev/null || true + run certutil -N -d "sql:${nss_db}" --empty-password 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi - run certutil -D -d "sql:${nss_db}" -n "$name" >/dev/null 2>&1 || true + run certutil -D -d "sql:${nss_db}" -n "$name" >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - run certutil -A -d "sql:${nss_db}" -n "$name" -t "C,," -i "$CA_TRUST_CERT" 2>/dev/null || true + run certutil -A -d "sql:${nss_db}" -n "$name" -t "C,," -i "$CA_TRUST_CERT" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error log "NSS trust import attempted (best-effort)" else diff --git a/roles/sys-ca-selfsigned/tasks/00_core.yml b/roles/sys-ca-selfsigned/tasks/00_core.yml index 9e4cfd3c91..932fac05a6 100644 --- a/roles/sys-ca-selfsigned/tasks/00_core.yml +++ b/roles/sys-ca-selfsigned/tasks/00_core.yml @@ -90,7 +90,7 @@ - name: "📦 CA | install trust helper script (SPOT) on host" become: true ansible.builtin.copy: - src: "with-ca-trust.sh" + src: "shell/with-ca-trust.sh" dest: "{{ BIN_CA_TRUST }}" owner: root group: root diff --git a/roles/sys-cleanup/README.md b/roles/sys-cleanup/README.md index dbb6f09058..87ea73271d 100644 --- a/roles/sys-cleanup/README.md +++ b/roles/sys-cleanup/README.md @@ -32,7 +32,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-cleanup/files/cleanup_caches.sh b/roles/sys-cleanup/files/cleanup_caches.sh deleted file mode 100644 index 8c6c97e141..0000000000 --- a/roles/sys-cleanup/files/cleanup_caches.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash -# Cross-distro CI/container cleanup: package-manager and language-tool caches. -set -euo pipefail - -echo "=== [cleanup] package manager caches ===" -if command -v apt-get >/dev/null 2>&1; then - apt-get clean || true -fi - -if command -v pacman >/dev/null 2>&1; then - pacman -Scc --noconfirm || true -fi - -if command -v dnf >/dev/null 2>&1; then - dnf clean all || true - rm -rf /var/cache/dnf || true -fi - -if command -v yum >/dev/null 2>&1; then - yum clean all || true - rm -rf /var/cache/yum || true -fi - -echo "=== [cleanup] language/tool caches (best effort) ===" -rm -rf /root/.cache/pip /home/*/.cache/pip 2>/dev/null || true -rm -rf /root/.npm /home/*/.npm 2>/dev/null || true -rm -rf /root/.cache/yarn /home/*/.cache/yarn 2>/dev/null || true -rm -rf /root/.cache/go-build /home/*/.cache/go-build 2>/dev/null || true diff --git a/roles/sys-cleanup/files/shell/cleanup_caches.sh b/roles/sys-cleanup/files/shell/cleanup_caches.sh new file mode 100644 index 0000000000..26de224827 --- /dev/null +++ b/roles/sys-cleanup/files/shell/cleanup_caches.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Cross-distro CI/container cleanup: package-manager and language-tool caches. +set -euo pipefail + +echo "=== [cleanup] package manager caches ===" +if command -v apt-get >/dev/null 2>&1; then + apt-get clean || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +fi + +if command -v pacman >/dev/null 2>&1; then + pacman -Scc --noconfirm || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +fi + +if command -v dnf >/dev/null 2>&1; then + dnf clean all || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + rm -rf /var/cache/dnf || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +fi + +if command -v yum >/dev/null 2>&1; then + yum clean all || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + rm -rf /var/cache/yum || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +fi + +echo "=== [cleanup] language/tool caches (best effort) ===" +rm -rf /root/.cache/pip /home/*/.cache/pip 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +rm -rf /root/.npm /home/*/.npm 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +rm -rf /root/.cache/yarn /home/*/.cache/yarn 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +rm -rf /root/.cache/go-build /home/*/.cache/go-build 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error diff --git a/roles/sys-cleanup/tasks/main.yml b/roles/sys-cleanup/tasks/main.yml index d50269a530..6d3e4a7a24 100644 --- a/roles/sys-cleanup/tasks/main.yml +++ b/roles/sys-cleanup/tasks/main.yml @@ -1,23 +1,18 @@ --- - name: "🧹 Cleanup caches and logs (cross-distro: arch/debian/ubuntu/fedora/centos)" - # CI/container cleanup to prevent disk blow-ups across all supported distros become: true - ansible.builtin.script: cleanup_caches.sh + ansible.builtin.script: shell/cleanup_caches.sh changed_when: true - name: 🧹 Cleanup journald logs (CI/container only) - # Prevent disk blow-ups in CI containers due to journald accumulation become: true ansible.builtin.shell: | set -euo pipefail - # Show current journald usage (best effort) journalctl --disk-usage || true - # Keep a small budget (adjust if you want) journalctl --vacuum-size=100M - # Optional: also cap by age journalctl --vacuum-time=3h || true journalctl --disk-usage || true diff --git a/roles/sys-cli/README.md b/roles/sys-cli/README.md index 3e41003a8b..02c2221ef3 100644 --- a/roles/sys-cli/README.md +++ b/roles/sys-cli/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Usage diff --git a/roles/sys-ctl-alm-compose/README.md b/roles/sys-ctl-alm-compose/README.md index 3e4e92b872..6c8aed1d12 100644 --- a/roles/sys-ctl-alm-compose/README.md +++ b/roles/sys-ctl-alm-compose/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-alm-compose/templates/script.sh.j2 b/roles/sys-ctl-alm-compose/templates/script.sh.j2 index c6e6bd16a6..d9007ff9d5 100644 --- a/roles/sys-ctl-alm-compose/templates/script.sh.j2 +++ b/roles/sys-ctl-alm-compose/templates/script.sh.j2 @@ -3,7 +3,6 @@ err=0 set -u start_timeout="{{ SYSTEMCTL_ALARM_COMPOSER_START_TIMEOUT_SECONDS }}" {% for alarm in SYSTEMCTL_ALARM_COMPOSER_SUBSERVICES %} -# sys-ctl-alm-email.infinito.nexus@.service (no extra dot!) unit="{{ lookup('unit_name', alarm ~ '@', suffix=False) }}$(systemd-escape "$1").service" timeout "${start_timeout}s" /usr/bin/systemctl start -- "$unit" rc=$? diff --git a/roles/sys-ctl-alm-email/README.md b/roles/sys-ctl-alm-email/README.md index 282fcde1c4..095412d997 100644 --- a/roles/sys-ctl-alm-email/README.md +++ b/roles/sys-ctl-alm-email/README.md @@ -23,7 +23,7 @@ flowchart LR dep_web_app_mailu -- "1:1" --> svc_email ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-alm-email/templates/script.sh.j2 b/roles/sys-ctl-alm-email/templates/script.sh.j2 index 75a7eab718..b8b89bf89d 100644 --- a/roles/sys-ctl-alm-email/templates/script.sh.j2 +++ b/roles/sys-ctl-alm-email/templates/script.sh.j2 @@ -3,7 +3,6 @@ set -u # Reverse systemd escaping for human-readable mail subject/body friendly="$(systemd-escape --unescape "$1")" -# Resolve sendmail path across distros (/usr/sbin on EL, /usr/bin on others). sendmail_bin="$(command -v sendmail 2>/dev/null || true)" if [ -z "$sendmail_bin" ] && [ -x /usr/sbin/sendmail ]; then sendmail_bin="/usr/sbin/sendmail" @@ -16,7 +15,6 @@ if [ -z "$sendmail_bin" ]; then exit 1 fi -# Try status with given arg; if empty, also try the escaped version STATUS_OUT="$(systemctl status --full "$1" 2>/dev/null | head -n 30)" if [ -z "$STATUS_OUT" ]; then esc="$(systemd-escape "$1")" diff --git a/roles/sys-ctl-alm-telegram/README.md b/roles/sys-ctl-alm-telegram/README.md index ddef2346b9..3000db3538 100644 --- a/roles/sys-ctl-alm-telegram/README.md +++ b/roles/sys-ctl-alm-telegram/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-cln-anon-volumes/README.md b/roles/sys-ctl-cln-anon-volumes/README.md index cf370b5ea5..3b3aaa20d1 100644 --- a/roles/sys-ctl-cln-anon-volumes/README.md +++ b/roles/sys-ctl-cln-anon-volumes/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-cln-bkps/README.md b/roles/sys-ctl-cln-bkps/README.md index 8af18d488a..05685a7afe 100644 --- a/roles/sys-ctl-cln-bkps/README.md +++ b/roles/sys-ctl-cln-bkps/README.md @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-cln-bkps/files/script.py b/roles/sys-ctl-cln-bkps/files/python/script.py similarity index 93% rename from roles/sys-ctl-cln-bkps/files/script.py rename to roles/sys-ctl-cln-bkps/files/python/script.py index cb1bbc8aa8..3d64c277aa 100644 --- a/roles/sys-ctl-cln-bkps/files/script.py +++ b/roles/sys-ctl-cln-bkps/files/python/script.py @@ -7,7 +7,6 @@ from pathlib import Path import psutil -# Validating arguments parser = argparse.ArgumentParser() parser.add_argument( "--maximum-backup-size-percent", @@ -35,12 +34,10 @@ def print_used_disc_space(backup_dir): def is_directory_used_by_another_process(directory_path): command = "lsof " + directory_path - # directory_path comes from Ansible-templated config (host-trusted), not user input. - process = subprocess.Popen( # noqa: S602 + process = subprocess.Popen( # noqa: S602 - directory_path comes from Ansible-templated config (host-trusted), never user input [command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) process.communicate() - # @See https://stackoverflow.com/questions/29841984/non-zero-exit-code-for-lsof return not process.wait() > bool(0) @@ -125,12 +122,17 @@ def get_amount_of_iteration(versions, average_version_directories_per_applicatio def delete_iteration(backup_dir, average_version_directories_per_application): + """Run one deletion pass over every application. + + Returns: + The number of version directories deleted during this pass. + """ + deleted = 0 for host_backup_directory_name in os.listdir(backup_dir): print(f"Iterating over host: {host_backup_directory_name}") host_backup_directory_path = str(Path(backup_dir) / host_backup_directory_name) for application_directory in os.listdir(host_backup_directory_path): print(f"Iterating over backup application: {application_directory}") - # The directory which contains all backup versions of the application versions_directory = ( str(Path(host_backup_directory_path) / application_directory) + "/" ) @@ -146,7 +148,9 @@ def delete_iteration(backup_dir, average_version_directories_per_application): version_path = str(Path(versions_directory) / version) if is_directory_deletable(version, versions, version_path): delete_version(version_path, backup_dir) + deleted += 1 version_iteration += 1 + return deleted def check_time_left(start_time, time_limit): @@ -162,7 +166,6 @@ def check_time_left(start_time, time_limit): elapsed_time = current_time - start_time remaining_time = time_limit - elapsed_time - # Convert times to readable format start_time_str = time.strftime("%H:%M:%S", time.localtime(start_time)) current_time_str = time.strftime("%H:%M:%S", time.localtime(current_time)) remaining_time_str = time.strftime("%H:%M:%S", time.gmtime(remaining_time)) @@ -205,7 +208,11 @@ while is_larger_than_maximum_backup_size(maximum_backup_size_percent, backup_dir print( f"Average version directories per application directory: {average_version_directories}" ) - delete_iteration(backup_dir, average_version_directories) + if delete_iteration(backup_dir, average_version_directories) == 0: + print( + "No deletable backup versions left; the remaining usage is not backup-driven. Exiting." + ) + break itteration_counter += 1 print_used_disc_space(backup_dir) diff --git a/roles/sys-ctl-cln-certs/README.md b/roles/sys-ctl-cln-certs/README.md index c457e17062..90739dbc95 100644 --- a/roles/sys-ctl-cln-certs/README.md +++ b/roles/sys-ctl-cln-certs/README.md @@ -25,7 +25,7 @@ flowchart LR svc_certs -- "1:1" --> dpt_sys_ctl_mtn_cert_renew ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-cln-certs/tasks/00_core.yml b/roles/sys-ctl-cln-certs/tasks/00_core.yml index 79073f4f2e..c221ba21f6 100644 --- a/roles/sys-ctl-cln-certs/tasks/00_core.yml +++ b/roles/sys-ctl-cln-certs/tasks/00_core.yml @@ -6,11 +6,12 @@ - sys-ctl-alm-compose - sys-daemon -- name: "📦 pkgmgr install" +- name: 📦 Install certreap system-wide via pip include_role: - name: pkgmgr-install + name: sys-pip-install vars: package_name: certreap + global_install: true - include_role: name: sys-service diff --git a/roles/sys-ctl-cln-disc-space/README.md b/roles/sys-ctl-cln-disc-space/README.md index b49a67379e..fb10c6f8ae 100644 --- a/roles/sys-ctl-cln-disc-space/README.md +++ b/roles/sys-ctl-cln-disc-space/README.md @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-cln-disc-space/files/script.sh b/roles/sys-ctl-cln-disc-space/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-cln-disc-space/files/script.sh rename to roles/sys-ctl-cln-disc-space/files/shell/script.sh diff --git a/roles/sys-ctl-cln-docker/README.md b/roles/sys-ctl-cln-docker/README.md index b35b0cd705..fde44c3694 100644 --- a/roles/sys-ctl-cln-docker/README.md +++ b/roles/sys-ctl-cln-docker/README.md @@ -29,7 +29,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-cln-docker/tasks/main.yml b/roles/sys-ctl-cln-docker/tasks/main.yml index 58ee158eab..b085f7ed33 100644 --- a/roles/sys-ctl-cln-docker/tasks/main.yml +++ b/roles/sys-ctl-cln-docker/tasks/main.yml @@ -19,8 +19,6 @@ system_service_tpl_on_failure: "{{ SYS_SERVICE_ON_FAILURE_COMPOSE }}" system_service_force_linear_sync: false - # The following logic is required due to side effects of service roless like MariaDB, OpenLDAP, Ollama etc. - # Networks get otherwise deleted before the deploy took place system_service_suppress_flush: "{{ SYS_CTL_CLN_DOCKER_SERVICE_ROLE_DEPLOY | bool }}" system_service_force_flush_instant: "{{ (SYS_CTL_CLN_DOCKER_SERVICE_ROLE_DEPLOY | bool) if (SYS_CTL_CLN_DOCKER_SERVICE_ROLE_DEPLOY | bool) else (MODE_CLEANUP | bool) }}" diff --git a/roles/sys-ctl-cln-faild-bkps/README.md b/roles/sys-ctl-cln-faild-bkps/README.md index c52446289d..6520ff63d8 100644 --- a/roles/sys-ctl-cln-faild-bkps/README.md +++ b/roles/sys-ctl-cln-faild-bkps/README.md @@ -35,7 +35,7 @@ flowchart LR svc_faild_bkps -- "1:1" --> dpt_svc_bkp_volume_2_local ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-hlth-btrfs/README.md b/roles/sys-ctl-hlth-btrfs/README.md index 251de823ec..89abc15ce4 100644 --- a/roles/sys-ctl-hlth-btrfs/README.md +++ b/roles/sys-ctl-hlth-btrfs/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-hlth-btrfs/files/script.sh b/roles/sys-ctl-hlth-btrfs/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-hlth-btrfs/files/script.sh rename to roles/sys-ctl-hlth-btrfs/files/shell/script.sh diff --git a/roles/sys-ctl-hlth-container/README.md b/roles/sys-ctl-hlth-container/README.md index bda53b8704..207cd1aa24 100644 --- a/roles/sys-ctl-hlth-container/README.md +++ b/roles/sys-ctl-hlth-container/README.md @@ -20,7 +20,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-hlth-container/files/script.sh b/roles/sys-ctl-hlth-container/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-hlth-container/files/script.sh rename to roles/sys-ctl-hlth-container/files/shell/script.sh diff --git a/roles/sys-ctl-hlth-csp/README.md b/roles/sys-ctl-hlth-csp/README.md index 3dcfae2aaa..e2cf45904a 100644 --- a/roles/sys-ctl-hlth-csp/README.md +++ b/roles/sys-ctl-hlth-csp/README.md @@ -20,7 +20,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-hlth-csp/files/script.py b/roles/sys-ctl-hlth-csp/files/python/script.py similarity index 66% rename from roles/sys-ctl-hlth-csp/files/script.py rename to roles/sys-ctl-hlth-csp/files/python/script.py index 787711cd92..654a583a2b 100755 --- a/roles/sys-ctl-hlth-csp/files/script.py +++ b/roles/sys-ctl-hlth-csp/files/python/script.py @@ -9,9 +9,6 @@ from pathlib import Path DOMAIN_FROM_FILENAME_RE = re.compile(r"^([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\.conf$") -# Very small "listen" heuristics: -# - treat as HTTPS if we see "listen ... 443" OR "listen ... ssl" -# - treat as HTTP if we see "listen ... 80" LISTEN_443_RE = re.compile(r"^\s*listen\s+[^;]*\b443\b", re.IGNORECASE) LISTEN_80_RE = re.compile(r"^\s*listen\s+[^;]*\b80\b", re.IGNORECASE) LISTEN_SSL_RE = re.compile(r"^\s*listen\s+[^;]*\bssl\b", re.IGNORECASE) @@ -22,7 +19,7 @@ def extract_domains_from_filenames(config_path: str) -> list[str] | None: Extract domain names from .conf filenames in the given directory. Example: - baserow.infinito.test.conf -> baserow.infinito.test + baserow..conf -> baserow. """ try: out: list[str] = [] @@ -31,13 +28,35 @@ def extract_domains_from_filenames(config_path: str) -> list[str] | None: continue if not DOMAIN_FROM_FILENAME_RE.match(fn): continue - out.append(fn[:-5]) # strip ".conf" + out.append(fn.removesuffix(".conf")) except FileNotFoundError: print(f"Directory {config_path} not found.", file=sys.stderr) return None return out +def split_onion_domains(domains: list[str]) -> tuple[list[str], list[str]]: + """Split into (clearnet, onion): onion vhosts need a SOCKS proxy to probe.""" + clearnet = [d for d in domains if not d.endswith(".onion")] + onion = [d for d in domains if d.endswith(".onion")] + return clearnet, onion + + +def is_skipped_domain(domain: str, skip_set: set[str], skip_labels: set[str]) -> bool: + """Whether a domain should be excluded from the CSP probe. + + A domain is skipped if it is listed explicitly in ``--skip-domain``, or if + it is the ``.onion`` sibling of a skipped clearnet vhost. Clearnet and onion + vhosts of the same app share the leftmost subdomain label (``mirror`` for + both ``mirror.`` and ``mirror..onion``), so a + ``--skip-domain mirror.`` also drops ``mirror..onion`` + — which serves the same 4xx at ``/`` and would otherwise fail the probe. + """ + if domain in skip_set: + return True + return domain.endswith(".onion") and domain.split(".", 1)[0] in skip_labels + + def detect_scheme_from_conf(conf_path: Path) -> str | None: """ Decide whether this conf listens on HTTP or HTTPS. @@ -110,13 +129,15 @@ def build_docker_cmd( short_mode: bool, ignore_network_blocks_from: list[str], use_host_network: bool = True, + proxy: str = "", ) -> list[str]: cmd = ["container", "run", "--rm"] if use_host_network: cmd.extend(["--network", "host"]) - # IMPORTANT: allow with-ca-trust.sh to install CA into container trust store + # Exception: runs as root because with-ca-trust.sh installs the CA into the + # container trust store, which an unprivileged user cannot write to. cmd.extend(["--user", "0:0"]) cmd.append(image) @@ -124,6 +145,9 @@ def build_docker_cmd( if short_mode: cmd.append("--short") + if proxy: + cmd.extend(["--proxy", proxy]) + if ignore_network_blocks_from: cmd.append("--ignore-network-blocks-from") cmd.extend(ignore_network_blocks_from) @@ -140,6 +164,7 @@ def run_checker( ignore_network_blocks_from: list[str], always_pull: bool, use_host_network: bool = True, + proxy: str = "", ) -> int: """ Runs the CSP checker container and returns its exit code. @@ -154,6 +179,7 @@ def run_checker( short_mode=short_mode, ignore_network_blocks_from=ignore_network_blocks_from, use_host_network=use_host_network, + proxy=proxy, ) try: @@ -213,6 +239,15 @@ def main() -> None: "otherwise treat as unreachable." ), ) + parser.add_argument( + "--tor-proxy", + default="", + help=( + "SOCKS proxy for probing .onion vhosts (e.g. " + "socks5://127.0.0.1:9050). Without it, .onion domains are " + "skipped — the checker cannot resolve them over plain DNS." + ), + ) args = parser.parse_args() @@ -226,31 +261,52 @@ def main() -> None: skip_set = {d for d in (args.skip_domain or []) if d} if skip_set: - skipped_present = sorted(skip_set & set(domains)) - domains = [d for d in domains if d not in skip_set] + skip_labels = {d.split(".", 1)[0] for d in skip_set} + skipped_present = sorted( + d for d in domains if is_skipped_domain(d, skip_set, skip_labels) + ) + domains = [ + d for d in domains if not is_skipped_domain(d, skip_set, skip_labels) + ] if skipped_present: print( f"Skipping {len(skipped_present)} domain(s) per " f"--skip-domain: {skipped_present}" ) - if not domains: + clearnet_domains, onion_domains = split_onion_domains(domains) + if onion_domains and not args.tor_proxy: + print( + f"Skipping {len(onion_domains)} .onion domain(s) — no --tor-proxy " + f"given: {sorted(onion_domains)}" + ) + onion_domains = [] + + if not clearnet_domains and not onion_domains: print("No domains left to check after applying --skip-domain.") sys.exit(0) - urls = build_urls_from_nginx_confs(args.nginx_config_dir, domains) - if not urls: - print("No URLs built to check.") - sys.exit(0) - - rc = run_checker( - image=args.image, - urls=urls, - short_mode=bool(args.short), - ignore_network_blocks_from=list(args.ignore_network_blocks_from or []), - always_pull=bool(args.always_pull), - use_host_network=not bool(args.no_host_network), - ) + rc = 0 + for batch_domains, batch_proxy in ( + (clearnet_domains, ""), + (onion_domains, args.tor_proxy), + ): + if not batch_domains: + continue + urls = build_urls_from_nginx_confs(args.nginx_config_dir, batch_domains) + if not urls: + print(f"No URLs built to check for: {sorted(batch_domains)}") + continue + batch_rc = run_checker( + image=args.image, + urls=urls, + short_mode=bool(args.short), + ignore_network_blocks_from=list(args.ignore_network_blocks_from or []), + always_pull=bool(args.always_pull), + use_host_network=not bool(args.no_host_network), + proxy=batch_proxy, + ) + rc = rc or batch_rc sys.exit(rc) diff --git a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py index 847d8fb49c..08d344c073 100644 --- a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py +++ b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py @@ -61,8 +61,39 @@ class LookupModule(LookupBase): Skips canonical + alias domains of every selected application whose ``server.status_codes.default`` declares any HTTP code >= 400 (e.g. federation-only roles that legitimately serve 4xx at ``/``). + + Additionally skips canonical domains owned by a disabled service: a + service entry may declare ``domains: [, ...]``; when its + ``enabled`` resolves falsy those canonicals get no vhost (e.g. the + seaweedfs filer/master frontend on an onion node), so probing them can + only fail. """ + def _service_disabled_domains(self, applications: Mapping, app_id: str) -> set[str]: + services = get(applications, app_id, "services", strict=False, default={}) + canonical = get( + applications, app_id, "server.domains.canonical", strict=False, default={} + ) + if not isinstance(services, Mapping) or not isinstance(canonical, Mapping): + return set() + templar = getattr(self, "_templar", None) + skip: set[str] = set() + for svc in services.values(): + if not isinstance(svc, Mapping) or "domains" not in svc: + continue + enabled = svc.get("enabled", True) + if isinstance(enabled, str) and templar is not None: + enabled = templar.template(enabled) + if enabled: + continue + for key in _to_list(svc.get("domains")): + domain = canonical.get(key) + if isinstance(domain, str) and "{{" in domain and templar is not None: + domain = templar.template(domain) + if isinstance(domain, str) and domain: + skip.add(domain) + return skip + def run( self, terms: list[Any] | None, @@ -90,6 +121,8 @@ class LookupModule(LookupBase): if selection and app_id not in selection: continue + skip |= self._service_disabled_domains(applications, app_id) + default = get( applications, app_id, diff --git a/roles/sys-ctl-hlth-csp/tasks/00_core.yml b/roles/sys-ctl-hlth-csp/tasks/00_core.yml index 661b895cd4..9216b832ea 100644 --- a/roles/sys-ctl-hlth-csp/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-csp/tasks/00_core.yml @@ -58,6 +58,10 @@ (HEALTH_CSP_SKIP_DOMAINS | length > 0) | ternary( '--skip-domain ' ~ (HEALTH_CSP_SKIP_DOMAINS | join(' ')), '' + ), + (lookup('config', 'svc-net-tor', 'services.tor.node', '') | length > 0) | ternary( + '--tor-proxy=socks5://' ~ lookup('tor_socks'), + '' ) ] | reject('equalto','') diff --git a/roles/sys-ctl-hlth-disc-space/README.md b/roles/sys-ctl-hlth-disc-space/README.md index cb9d25f1a9..ed36fdcdda 100644 --- a/roles/sys-ctl-hlth-disc-space/README.md +++ b/roles/sys-ctl-hlth-disc-space/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-hlth-disc-space/files/script.py b/roles/sys-ctl-hlth-disc-space/files/python/script.py similarity index 88% rename from roles/sys-ctl-hlth-disc-space/files/script.py rename to roles/sys-ctl-hlth-disc-space/files/python/script.py index 520c94fdcc..94ba9719cc 100755 --- a/roles/sys-ctl-hlth-disc-space/files/script.py +++ b/roles/sys-ctl-hlth-disc-space/files/python/script.py @@ -13,7 +13,7 @@ def get_disk_usage_percentages(): ["df", "--output=pcent"], capture_output=True, text=True, check=True ) - lines = result.stdout.strip().split("\n")[1:] # Skip header + lines = result.stdout.strip().split("\n")[1:] percentages = [] for line in lines: @@ -39,9 +39,7 @@ def main(): threshold = args.minimum_percent_cleanup_disk_space print("Checking disk space usage...") - subprocess.run( - ["df"], check=False - ) # Show the same df output as the original script + subprocess.run(["df"], check=False) errors = 0 percentages = get_disk_usage_percentages() diff --git a/roles/sys-ctl-hlth-journalctl/README.md b/roles/sys-ctl-hlth-journalctl/README.md index a9eb2f45ed..c60c77d27d 100644 --- a/roles/sys-ctl-hlth-journalctl/README.md +++ b/roles/sys-ctl-hlth-journalctl/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-hlth-journalctl/files/script.sh b/roles/sys-ctl-hlth-journalctl/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-hlth-journalctl/files/script.sh rename to roles/sys-ctl-hlth-journalctl/files/shell/script.sh diff --git a/roles/sys-ctl-hlth-msmtp/README.md b/roles/sys-ctl-hlth-msmtp/README.md index ae79b28397..cc51a9c5d5 100644 --- a/roles/sys-ctl-hlth-msmtp/README.md +++ b/roles/sys-ctl-hlth-msmtp/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-hlth-msmtp/files/script.sh b/roles/sys-ctl-hlth-msmtp/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-hlth-msmtp/files/script.sh rename to roles/sys-ctl-hlth-msmtp/files/shell/script.sh diff --git a/roles/sys-ctl-hlth-volumes/README.md b/roles/sys-ctl-hlth-volumes/README.md index 85139eabd6..d134df1c13 100644 --- a/roles/sys-ctl-hlth-volumes/README.md +++ b/roles/sys-ctl-hlth-volumes/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-hlth-volumes/files/script.sh b/roles/sys-ctl-hlth-volumes/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-hlth-volumes/files/script.sh rename to roles/sys-ctl-hlth-volumes/files/shell/script.sh diff --git a/roles/sys-ctl-hlth-webserver/README.md b/roles/sys-ctl-hlth-webserver/README.md index 3e27d6dc15..96549564f7 100644 --- a/roles/sys-ctl-hlth-webserver/README.md +++ b/roles/sys-ctl-hlth-webserver/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-hlth-webserver/files/script.py b/roles/sys-ctl-hlth-webserver/files/python/script.py similarity index 79% rename from roles/sys-ctl-hlth-webserver/files/script.py rename to roles/sys-ctl-hlth-webserver/files/python/script.py index 571622351a..4b04d6a68b 100755 --- a/roles/sys-ctl-hlth-webserver/files/script.py +++ b/roles/sys-ctl-hlth-webserver/files/python/script.py @@ -30,6 +30,12 @@ def parse_args(argv=None): return p.parse_args(argv) +def _protocol_for(domain: str, default_protocol: str) -> str: + """Onion services are plaintext-only (no TLS): probe them over http + regardless of the clearnet default. Everything else uses the default.""" + return "http" if domain.endswith(".onion") else default_protocol + + def _parse_json_mapping(name: str, value: str) -> dict[str, list[int]]: try: obj = json.loads(value) @@ -37,7 +43,6 @@ def _parse_json_mapping(name: str, value: str) -> dict[str, list[int]]: raise SystemExit(f"--{name} must be a valid JSON string: {e}") from e if not isinstance(obj, dict): raise SystemExit(f"--{name} must be a JSON object (mapping)") - # sanitize list-of-ints shape clean = {} for k, v in obj.items(): if isinstance(v, list): @@ -66,13 +71,16 @@ def main(argv=None) -> int: errors = 0 for domain in sorted(expectations.keys()): expected = expectations[domain] or [] - url = f"{args.web_protocol}://{domain}" + is_onion = domain.endswith(".onion") + url = f"{_protocol_for(domain, args.web_protocol)}://{domain}" + timeout = 30 if is_onion else 10 try: - r = requests.head(url, allow_redirects=False, timeout=10, verify=verify) + r = requests.head( + url, allow_redirects=False, timeout=timeout, verify=verify + ) if expected and r.status_code in expected: print(f"{domain}: OK") elif not expected: - # If somehow empty list slipped through, treat as failure to be explicit print( f"{domain}: ERROR: No expectations provided. Got {r.status_code}." ) @@ -85,9 +93,7 @@ def main(argv=None) -> int: errors += 1 if errors: - print( - f"Warning: {errors} domains responded with an unexpected https status code." - ) + print(f"Warning: {errors} domains responded with an unexpected status code.") return errors diff --git a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py index 24cf0684b0..169d635acf 100644 --- a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py +++ b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py @@ -2,11 +2,8 @@ import sys from collections.abc import Mapping from pathlib import Path -from utils.roles.applications.config import get # reuse existing helper +from utils.roles.applications.config import get -# Allow imports from utils (same trick as your config filter). -# Role-bundled plugin: Ansible loads by file path with no package -# context, so `from . import PROJECT_ROOT` cannot resolve here. # nocheck: project-root-import _BASE_DIR = str(Path(__file__).resolve().parents[3]) _MODULE_UTILS_DIR = str(Path(_BASE_DIR) / "utils") @@ -119,8 +116,42 @@ def _normalize_codes(x): return [c] if c is not None else [] +def _apply_onion_deploy_view(per_app, applications, primary_domain, node_onion): + """Rewrite each app's expectation domains to what the current deploy serves: + for a ``services.tor.enabled`` app the onion domains replace (``exclusive``) + or accompany (dual) the clearnet ones, reusing ``_inject_onion_domains`` and + letting each onion domain inherit its clearnet source's status codes.""" + node = str(node_onion or "").strip() + primary = str(primary_domain or "").strip() + if not node or not primary: + return + + from utils.cache.domains import _inject_onion_domains, _onion_of + + clearnet_lists = {app: list(exp.keys()) for app, exp in per_app.items()} + served = _inject_onion_domains(clearnet_lists, applications, primary, node) + + for app_id, exp in per_app.items(): + onion_codes = {} + for d, codes in exp.items(): + o = _onion_of(str(d), primary, node) + if o: + onion_codes[o] = codes + served_list = served.get(app_id, list(exp.keys())) + per_app[app_id] = { + s: (exp[s] if s in exp else onion_codes[s]) + for s in served_list + if s in exp or s in onion_codes + } + + def web_health_expectations( - applications, www_enabled: bool = False, group_names=None, redirect_maps=None + applications, + www_enabled: bool = False, + group_names=None, + redirect_maps=None, + primary_domain=None, + node_onion=None, ): """Produce a **flat mapping**: domain -> [expected_status_codes]. @@ -135,13 +166,17 @@ def web_health_expectations( - No legacy fallbacks (ignore 'home'/'landingpage'). - `redirect_maps`: force -> [301] and override app-derived entries. - If `www_enabled`: add and/or force www.* -> [301] for all domains. + - Deploy-aware onion view: when `primary_domain` and `node_onion` are set + (svc-net-tor deployed), each `services.tor.enabled` app's clearnet + domains are swapped (exclusive) or extended (dual) with their onion + domains, so the probe checks exactly what the current deploy serves. """ if not isinstance(applications, Mapping): return {} selection = _normalize_selection(group_names) - expectations = {} + per_app = {} for app_id in applications: if app_id not in selection: @@ -165,33 +200,65 @@ def web_health_expectations( if codes: sc_map[str(k)] = codes + suppressed = set() + services_raw = get(applications, app_id, "services", strict=False, default={}) + if isinstance(services_raw, Mapping): + for svc in services_raw.values(): + if not isinstance(svc, Mapping) or "domains" not in svc: + continue + if svc.get("enabled"): + continue + for key in _to_list(svc.get("domains"), allow_mapping=False): + if key: + suppressed.add(str(key)) + + app_exp = {} if isinstance(canonical_raw, Mapping) and canonical_raw: for key, domains in canonical_raw.items(): + if str(key) in suppressed: + continue domains_list = _to_list(domains, allow_mapping=False) codes = sc_map.get(key) or sc_map.get("default") expected = list(codes) if codes else list(DEFAULT_OK) for d in domains_list: if d: - expectations[d] = expected + app_exp[d] = expected else: for d in _to_list(canonical_raw, allow_mapping=True): if not d: continue codes = sc_map.get("default") - expectations[d] = list(codes) if codes else list(DEFAULT_OK) + app_exp[d] = list(codes) if codes else list(DEFAULT_OK) for d in aliases: if d: - expectations[d] = [301] + app_exp[d] = [301] + + per_app[app_id] = app_exp + + primary = str(primary_domain or "").strip() + if primary and "web-opt-rdr-domains" not in selection: + for app_exp in per_app.values(): + app_exp.pop(primary, None) + + _apply_onion_deploy_view(per_app, applications, primary_domain, node_onion) + + expectations = {} + for app_exp in per_app.values(): + expectations.update(app_exp) for src in _extract_redirect_sources(redirect_maps): expectations[src] = [301] if www_enabled: + node = str(node_onion or "").strip() add = {} for d in expectations: - if not d.startswith("www."): - add[f"www.{d}"] = [301] + if d.startswith("www."): + continue + if node and d.endswith(node): + continue + add[f"www.{d}"] = [301] expectations.update(add) for d in list(expectations.keys()): if d.startswith("www."): diff --git a/roles/sys-ctl-hlth-webserver/tasks/00_core.yml b/roles/sys-ctl-hlth-webserver/tasks/00_core.yml index 4e009a188e..5da77cf140 100644 --- a/roles/sys-ctl-hlth-webserver/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-webserver/tasks/00_core.yml @@ -33,7 +33,8 @@ system_service_tpl_exec_start: > {{ system_service_script_exec }} --web-protocol {{ lookup('tls', DOMAIN_PRIMARY, 'protocols.web') }} - --expectations '{{ lookup('applications') | web_health_expectations(www_enabled=WWW_REDIRECT_ENABLED | bool, group_names=lookup('deployment').deployed) | to_json + --expectations '{{ lookup('applications') | web_health_expectations(www_enabled=WWW_REDIRECT_ENABLED | bool, group_names=lookup('deployment').deployed, primary_domain=DOMAIN_PRIMARY, + node_onion=lookup('config', 'svc-net-tor', 'services.tor.node', '')) | to_json }}' system_service_force_flush_final: true diff --git a/roles/sys-ctl-hlth-webserver/tasks/main.yml b/roles/sys-ctl-hlth-webserver/tasks/main.yml index 7d76238af7..bb15cc44e6 100644 --- a/roles/sys-ctl-hlth-webserver/tasks/main.yml +++ b/roles/sys-ctl-hlth-webserver/tasks/main.yml @@ -2,4 +2,4 @@ - include_tasks: 00_core.yml when: - run_once_sys_ctl_hlth_webserver is not defined - - DEPLOYMENT_MODE == 'compose' or inventory_hostname in (groups['svc-swarm-node'] | default([])) + - IS_STACK_HOST | bool diff --git a/roles/sys-ctl-mtn-cert-deploy/README.md b/roles/sys-ctl-mtn-cert-deploy/README.md index bc09d1274f..a4533bbe85 100644 --- a/roles/sys-ctl-mtn-cert-deploy/README.md +++ b/roles/sys-ctl-mtn-cert-deploy/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-ctl-mtn-cert-deploy/files/script.sh b/roles/sys-ctl-mtn-cert-deploy/files/shell/script.sh similarity index 100% rename from roles/sys-ctl-mtn-cert-deploy/files/script.sh rename to roles/sys-ctl-mtn-cert-deploy/files/shell/script.sh diff --git a/roles/sys-ctl-mtn-cert-deploy/files/test.sh b/roles/sys-ctl-mtn-cert-deploy/files/shell/test.sh similarity index 95% rename from roles/sys-ctl-mtn-cert-deploy/files/test.sh rename to roles/sys-ctl-mtn-cert-deploy/files/shell/test.sh index 29450372b9..28066ec062 100755 --- a/roles/sys-ctl-mtn-cert-deploy/files/test.sh +++ b/roles/sys-ctl-mtn-cert-deploy/files/shell/test.sh @@ -48,7 +48,8 @@ check_local() { return fi - # Public-key comparison works for RSA and EC alike (modulus does not). + # Exception: compare public keys, not moduli — an EC key has no modulus, so the + # conventional `openssl ... -modulus` pairing check silently passes for every EC cert. cert_pub="$(openssl x509 -in "$cert" -pubkey -noout 2>/dev/null)" key_pub="$(openssl pkey -in "$key" -pubout 2>/dev/null)" if [ -z "$key_pub" ] || [ "$cert_pub" != "$key_pub" ]; then diff --git a/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml b/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml index 2e3e4689f2..357bdcc967 100644 --- a/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml +++ b/roles/sys-ctl-mtn-cert-deploy/tasks/00_core.yml @@ -22,7 +22,7 @@ - name: "✅ Verify deployed certificate material" ansible.builtin.script: - cmd: "{{ [ role_path, 'files/test.sh' ] | path_join }} {{ lookup('container', application_id, 'directories.instance') }}" + cmd: "{{ [ role_path, 'files/shell/test.sh' ] | path_join }} {{ lookup('container', application_id, 'directories.instance') }}" environment: # Exception: caller-supplied endpoints win so the mail provider can point the remote # check at the production server it just configured; the env var stays the fallback diff --git a/roles/sys-ctl-mtn-cert-deploy/tasks/main.yml b/roles/sys-ctl-mtn-cert-deploy/tasks/main.yml index 3222848ca2..13be3f7aaf 100644 --- a/roles/sys-ctl-mtn-cert-deploy/tasks/main.yml +++ b/roles/sys-ctl-mtn-cert-deploy/tasks/main.yml @@ -1,3 +1,14 @@ --- +- name: "🚫 Cert deploy N/A for '{{ application_id }}' (TLS off) — mark role executed" + ansible.builtin.debug: + msg: >- + Skipping certificate deploy: TLS is disabled for '{{ application_id }}' + (onion transport is authenticated by the hidden service itself). + when: + - run_once_sys_ctl_mtn_cert_deploy is not defined + - not (lookup('tls', application_id, 'enabled') | bool) + - include_tasks: 00_core.yml - when: run_once_sys_ctl_mtn_cert_deploy is not defined + when: + - run_once_sys_ctl_mtn_cert_deploy is not defined + - lookup('tls', application_id, 'enabled') | bool diff --git a/roles/sys-ctl-mtn-cert-renew/README.md b/roles/sys-ctl-mtn-cert-renew/README.md index 12baa17588..8d6e2346d0 100644 --- a/roles/sys-ctl-mtn-cert-renew/README.md +++ b/roles/sys-ctl-mtn-cert-renew/README.md @@ -30,7 +30,7 @@ flowchart LR dep_sys_ctl_cln_certs -- "1:1" --> svc_cert_renew ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-rpr-btrfs-balancer/README.md b/roles/sys-ctl-rpr-btrfs-balancer/README.md index f165238f2e..c7bb44b6fc 100644 --- a/roles/sys-ctl-rpr-btrfs-balancer/README.md +++ b/roles/sys-ctl-rpr-btrfs-balancer/README.md @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-rpr-btrfs-balancer/tasks/00_core.yml b/roles/sys-ctl-rpr-btrfs-balancer/tasks/00_core.yml index e2b0d879b5..8fa9f361e2 100644 --- a/roles/sys-ctl-rpr-btrfs-balancer/tasks/00_core.yml +++ b/roles/sys-ctl-rpr-btrfs-balancer/tasks/00_core.yml @@ -4,11 +4,12 @@ name: sys-ctl-alm-compose when: run_once_sys_ctl_alm_compose is not defined -- name: "📦 pkgmgr install" +- name: 📦 Install btrfs-auto-balancer system-wide via pip include_role: - name: pkgmgr-install + name: sys-pip-install vars: package_name: btrfs-auto-balancer + global_install: true - include_role: name: sys-service diff --git a/roles/sys-ctl-rpr-container-hard/README.md b/roles/sys-ctl-rpr-container-hard/README.md index 00e74c32d8..a84ec240a7 100644 --- a/roles/sys-ctl-rpr-container-hard/README.md +++ b/roles/sys-ctl-rpr-container-hard/README.md @@ -23,7 +23,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-rpr-container-hard/files/script.py b/roles/sys-ctl-rpr-container-hard/files/python/script.py similarity index 100% rename from roles/sys-ctl-rpr-container-hard/files/script.py rename to roles/sys-ctl-rpr-container-hard/files/python/script.py diff --git a/roles/sys-ctl-rpr-container-soft/README.md b/roles/sys-ctl-rpr-container-soft/README.md index 0fce6f4927..b3a0bb0c00 100644 --- a/roles/sys-ctl-rpr-container-soft/README.md +++ b/roles/sys-ctl-rpr-container-soft/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-ctl-rpr-container-soft/files/script.py b/roles/sys-ctl-rpr-container-soft/files/python/script.py similarity index 100% rename from roles/sys-ctl-rpr-container-soft/files/script.py rename to roles/sys-ctl-rpr-container-soft/files/python/script.py diff --git a/roles/sys-daemon/README.md b/roles/sys-daemon/README.md index b35f407845..41a30f8fb9 100644 --- a/roles/sys-daemon/README.md +++ b/roles/sys-daemon/README.md @@ -23,7 +23,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-daemon/handlers/main.yml b/roles/sys-daemon/handlers/main.yml index a42c6c858c..9df24c758b 100644 --- a/roles/sys-daemon/handlers/main.yml +++ b/roles/sys-daemon/handlers/main.yml @@ -1,5 +1,5 @@ --- -- name: collect systemd unit files +- name: 🔍 collect systemd unit files shell: | shopt -s nullglob files=({{ DIR_SYSTEM_SERVICE }}*.service {{ DIR_SYSTEM_SERVICE }}*.timer) @@ -11,10 +11,10 @@ failed_when: false become: true listen: - - reload system daemon - - reexec systemd manager + - reload-system-daemon + - reexec-systemd-manager -- name: validate systemd units +- name: ✅ validate systemd units shell: | systemd-analyze verify {{ _unit_files.stdout_lines | join(' ') }} register: _verify_units @@ -23,28 +23,27 @@ become: true when: _unit_files.stdout | length > 0 listen: - - reload system daemon - - reexec systemd manager + - reload-system-daemon + - reexec-systemd-manager -- name: show merged manager config +- name: 🐛 show merged manager config command: systemd-analyze cat-config systemd/system.conf register: _catcfg changed_when: false become: true listen: - - reload system daemon - - reexec systemd manager + - reload-system-daemon + - reexec-systemd-manager -- name: "reload system daemon" +- name: "♻️ reload system daemon" ansible.builtin.systemd: daemon_reload: true become: true - listen: reload system daemon + listen: reload-system-daemon -- name: reexec systemd manager - # daemon-reexec terminates PID-1-systemd containers; effect applies on next boot. +- name: 🔄 reexec systemd manager ansible.builtin.systemd: daemon_reexec: true become: true - listen: reexec systemd manager + listen: reexec-systemd-manager when: not (DOCKER_IN_CONTAINER | bool) diff --git a/roles/sys-daemon/tasks/01_reset.yml b/roles/sys-daemon/tasks/01_reset.yml index 46cbf911c1..bddac03025 100644 --- a/roles/sys-daemon/tasks/01_reset.yml +++ b/roles/sys-daemon/tasks/01_reset.yml @@ -1,7 +1,7 @@ --- - name: 🔄 reload system daemon command: /bin/true - notify: "reload system daemon" + notify: "reload-system-daemon" - name: "✅ Sanity check SYSTEMD_MANAGER_CONF_DIR" assert: @@ -16,4 +16,4 @@ file: path: "{{ SYSTEMD_MANAGER_CONF_DIR }}" state: absent - notify: reexec systemd manager + notify: reexec-systemd-manager diff --git a/roles/sys-daemon/tasks/02_defaults.yml b/roles/sys-daemon/tasks/02_defaults.yml index f6522fee3f..3c53b701a9 100644 --- a/roles/sys-daemon/tasks/02_defaults.yml +++ b/roles/sys-daemon/tasks/02_defaults.yml @@ -10,4 +10,4 @@ src: timeouts.conf.j2 dest: "{{ SYSTEMD_MANAGER_CONF_DIR }}/timeouts.conf" mode: "0644" - notify: reexec systemd manager + notify: reexec-systemd-manager diff --git a/roles/sys-dns-cloudflare-records/README.md b/roles/sys-dns-cloudflare-records/README.md index ff649e4382..19a78a26b9 100644 --- a/roles/sys-dns-cloudflare-records/README.md +++ b/roles/sys-dns-cloudflare-records/README.md @@ -22,7 +22,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-dns-cloudflare-records/defaults/main.yml b/roles/sys-dns-cloudflare-records/defaults/main.yml index 55bc5321b9..4060fd9a59 100644 --- a/roles/sys-dns-cloudflare-records/defaults/main.yml +++ b/roles/sys-dns-cloudflare-records/defaults/main.yml @@ -4,6 +4,4 @@ cloudflare_async_time: "{{ ASYNC_TIME }}" cloudflare_async_poll: "{{ ASYNC_POLL }}" cloudflare_no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" -# Supported types: -# A/AAAA (content), CNAME/MX/TXT (value, MX hat priority), SRV (service/proto/…) cloudflare_records: [] diff --git a/roles/sys-dns-hetzner-rdns/README.md b/roles/sys-dns-hetzner-rdns/README.md index 0103da067c..31417a2a00 100644 --- a/roles/sys-dns-hetzner-rdns/README.md +++ b/roles/sys-dns-hetzner-rdns/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-dns-hetzner-rdns/defaults/main.yml b/roles/sys-dns-hetzner-rdns/defaults/main.yml index 4ecb6388ba..1c775a8122 100644 --- a/roles/sys-dns-hetzner-rdns/defaults/main.yml +++ b/roles/sys-dns-hetzner-rdns/defaults/main.yml @@ -3,8 +3,6 @@ # @see https://docs.hetzner.com/cloud/api/getting-started/generating-api-token/ HETZNER_API_TOKEN: "" -# Robot (dedicated) credentials -# You can create an user here: https://robot.hetzner.com/preferences/index HETZNER_ROBOT_USER: "" HETZNER_ROBOT_PASSWORD: "" @@ -15,7 +13,3 @@ hetzner_async_time: "{{ ASYNC_TIME }}" hetzner_async_poll: "{{ ASYNC_POLL }}" hetzner_no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" rdns_records: [] -# Example: -# rdns_records: -# - { resource: "server", ip_address: "1.2.3.4", dns_ptr: "mail.example.com" } -# - { resource: "primary_ip", identifier: "12345", ip_address: "2001:db8::1", dns_ptr: "mail.example.com" } diff --git a/roles/sys-dns-wildcards/README.md b/roles/sys-dns-wildcards/README.md index a7548dbcb2..9c3957aa0b 100644 --- a/roles/sys-dns-wildcards/README.md +++ b/roles/sys-dns-wildcards/README.md @@ -25,7 +25,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py b/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py index 02061ab3d1..1121594c50 100644 --- a/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py +++ b/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py @@ -110,7 +110,7 @@ def _build_wildcard_records( { "zone": apex, "type": rtype, - "name": name, # For apex wildcard, name "*" means "*.apex" in Cloudflare + "name": name, "content": content, "proxied": bool(proxied), "ttl": 1, @@ -118,12 +118,9 @@ def _build_wildcard_records( ) for p in sorted(set(parents)): - # Create wildcard at apex as well (name="*") if p == apex: wc = "*" else: - # relative part (drop ".apex"); empty rel is a safety guard - # — shouldn't happen because p==apex handled above. rel = p[: -len(apex) - 1] wc = "*" if not rel else f"*.{rel}" _add(wc, "A", str(ip4)) @@ -133,7 +130,7 @@ def _build_wildcard_records( def wildcard_records( - current_play_domains_all, # dict expected when explicit_domains is None + current_play_domains_all, apex: str, ip4: str, ip6: str | None = None, @@ -150,7 +147,6 @@ def wildcard_records( - If 'explicit_domains' is provided and non-empty, use it (expects list[str]). - Else flatten 'current_play_domains_all' (expects dict). """ - # Source domains if explicit_domains and len(explicit_domains) > 0: if not isinstance(explicit_domains, list) or not all( isinstance(x, str) for x in explicit_domains @@ -160,7 +156,6 @@ def wildcard_records( else: domains = _flatten_domains_any_structure(current_play_domains_all) - # Determine parents and ALWAYS include apex for apex wildcard parents = _parents_from(domains, apex, min_child_depth=min_child_depth) parents = list(set(parents) | {apex}) diff --git a/roles/sys-front-inj-all/README.md b/roles/sys-front-inj-all/README.md index d7f40e0671..2a592de6fc 100644 --- a/roles/sys-front-inj-all/README.md +++ b/roles/sys-front-inj-all/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-front-inj-all/filter_plugins/inj_enabled.py b/roles/sys-front-inj-all/filter_plugins/inj_enabled.py index d884b3f0f0..e1940e5771 100644 --- a/roles/sys-front-inj-all/filter_plugins/inj_enabled.py +++ b/roles/sys-front-inj-all/filter_plugins/inj_enabled.py @@ -3,9 +3,6 @@ from pathlib import Path from utils.roles.applications.config import get -# Allow imports from utils (same trick as your config filter). -# Role-bundled plugin: Ansible loads by file path with no package -# context, so `from . import PROJECT_ROOT` cannot resolve here. # nocheck: project-root-import _BASE_DIR = str(Path(__file__).resolve().parents[3]) _MODULE_UTILS_DIR = str(Path(_BASE_DIR) / "utils") diff --git a/roles/sys-front-inj-all/filter_plugins/inj_snippets.py b/roles/sys-front-inj-all/filter_plugins/inj_snippets.py index 5249766fa3..9550a136fd 100644 --- a/roles/sys-front-inj-all/filter_plugins/inj_snippets.py +++ b/roles/sys-front-inj-all/filter_plugins/inj_snippets.py @@ -15,8 +15,6 @@ Usage in a template: from pathlib import Path -# Role-bundled plugin: Ansible loads this file by file path with no -# package context, so `from . import PROJECT_ROOT` cannot resolve here. # nocheck: project-root-import _ROLES_DIR = str(Path(__file__).resolve().parents[2]) @@ -43,7 +41,6 @@ def _has_snippet(feature: str, kind: str) -> bool: def inj_features_filter(features, kind: str = "head"): if not isinstance(features, (list, tuple)): return [] - # Validation + filtering in one pass; will raise if a role dir is missing. valid = [] for f in features: name = str(f) diff --git a/roles/sys-front-inj-all/tasks/main.yml b/roles/sys-front-inj-all/tasks/main.yml index 82ee9eedbd..a23b9673ac 100644 --- a/roles/sys-front-inj-all/tasks/main.yml +++ b/roles/sys-front-inj-all/tasks/main.yml @@ -48,4 +48,4 @@ src: body_filter.lua.j2 dest: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ application_id }}.lua" mode: "0644" - notify: restart openresty + notify: reload-openresty diff --git a/roles/sys-front-inj-all/templates/body_filter.lua.j2 b/roles/sys-front-inj-all/templates/body_filter.lua.j2 index 582dcc98c7..21cd5d294a 100644 --- a/roles/sys-front-inj-all/templates/body_filter.lua.j2 +++ b/roles/sys-front-inj-all/templates/body_filter.lua.j2 @@ -31,6 +31,40 @@ end local whole = table.concat(ngx.ctx.buf) ngx.ctx.buf = nil +{% set _mirror_tor_enabled = lookup('config', application_id, 'services.tor.enabled', False) | bool %} +{% if _mirror_tor_enabled %} +{% set _mirror_origins = lookup('applications') | external_asset_origins(application_id, DOMAIN_PRIMARY) %} +{% set _mirror_tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} +{% set _mirror_onion = lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') | to_onion_url(_mirror_tor_node, DOMAIN_PRIMARY) %} +{% if _mirror_origins %} +-- Onion sessions: rewrite external asset origins to the local mirror (privacy proxy) +do + local host = ngx.var.http_host or "" + if host:sub(-6) == ".onion" then +{% for origin in _mirror_origins %} + do + local pat = ([=[https://{{ origin }}]=]):gsub("([^%w])", "%%%1") + whole = (whole:gsub(pat, [=[{{ _mirror_onion }}/{{ origin }}]=])) + end +{% endfor %} + end +end +{% endif %} +{% endif %} +{% set _cdn_base = lookup('tls', 'web-svc-cdn', 'url.base') | regex_replace('/+$', '') %} +{% set _tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} +{% set _cdn_onion = _cdn_base | to_onion_url(_tor_node, DOMAIN_PRIMARY) %} +local function onionize(s) +{% if _tor_node and _cdn_onion != _cdn_base %} + local host = ngx.var.http_host or "" + if host:sub(-6) == ".onion" then + local pat = ([=[{{ _cdn_base }}]=]):gsub("([^%w])", "%%%1") + s = (s:gsub(pat, [=[{{ _cdn_onion }}]=])) + end +{% endif %} + return s +end + -- Remove inline CSP (case-insensitive) local meta_re = [[]+http-equiv=["']Content-Security-Policy["'][^>]*>\s*]] whole = ngx.re.gsub(whole, meta_re, "", "ijo") @@ -38,7 +72,7 @@ whole = ngx.re.gsub(whole, meta_re, "", "ijo") -- Build head snippets (rendered by Jinja at template time) local head_snippets = {} {{ push_snippets('head_snippets', inj_head_features) }} -local head_payload = table.concat(head_snippets, "\n") .. "" +local head_payload = onionize(table.concat(head_snippets, "\n")) .. "" -- Inject before (first occurrence) local function repl_head(_) return head_payload end @@ -60,7 +94,7 @@ end -- Build body snippets (rendered by Jinja at template time) local body_snippets = {} {{ push_snippets('body_snippets', inj_body_features) }} -local body_payload = table.concat(body_snippets, "\n") .. "" +local body_payload = onionize(table.concat(body_snippets, "\n")) .. "" -- Inject before (first occurrence), or append if missing local function repl_body(_) return body_payload end diff --git a/roles/sys-front-inj-css/README.md b/roles/sys-front-inj-css/README.md index 9e75f0877a..99c467fa5b 100644 --- a/roles/sys-front-inj-css/README.md +++ b/roles/sys-front-inj-css/README.md @@ -21,7 +21,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Purpose diff --git a/roles/sys-front-inj-css/templates/css/bootstrap.css.j2 b/roles/sys-front-inj-css/templates/css/bootstrap.css.j2 index 2c3ceb44b8..a17c08c320 100644 --- a/roles/sys-front-inj-css/templates/css/bootstrap.css.j2 +++ b/roles/sys-front-inj-css/templates/css/bootstrap.css.j2 @@ -12,7 +12,6 @@ html[native-dark-active] .btn, .btn { /* Navigation (Background and Text Colors) */ .navbar, .navbar-light, .navbar-dark, .navbar.bg-light { background-color: var(--color-01-90); - /* New Gradient based on original background (90 -5, 90, 90 +1, 90 +5) */ background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-85), var(--color-01-90), var(--color-01-91), var(--color-01-95)); color: var(--color-01-50); border-color: var(--color-01-85); @@ -30,7 +29,6 @@ html[native-dark-active] .btn, .btn { Cards now use a slightly lighter background and a bold, clear shadow */ .card { background-color: var(--color-01-90); - /* New Gradient based on original background (90 -5, 90, 90 +1, 90 +5) */ background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-85), var(--color-01-90), var(--color-01-91), var(--color-01-95)); border-color: var(--color-01-85); color: var(--color-01-12); @@ -40,11 +38,9 @@ html[native-dark-active] .btn, .btn { color: var(--color-01-40); } -/* Dropdown Menu and Submenu (Background, Text, and Shadow) */ .navbar .dropdown-menu, .nav-item .dropdown-menu { background-color: var(--color-01-80); - /* New Gradient based on original background (80 -5, 80, 80 +1, 80 +5) */ background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-75), var(--color-01-80), var(--color-01-81), var(--color-01-85)); color: var(--color-01-40); } @@ -56,14 +52,12 @@ html[native-dark-active] .btn, .btn { .dropdown-item { color: var(--color-01-40); background-color: var(--color-01-80); - /* New Gradient based on original background (80 -5, 80, 80 +1, 80 +5) */ background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-75), var(--color-01-80), var(--color-01-81), var(--color-01-85)); } .dropdown-item:hover, .dropdown-item:focus { background-color: var(--color-01-65); - /* New Gradient based on original background (65 -5, 65, 65 +1, 65 +5) */ background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-60), var(--color-01-65), var(--color-01-66), var(--color-01-70)); color: var(--color-01-40); } diff --git a/roles/sys-front-inj-css/templates/css/default.css.j2 b/roles/sys-front-inj-css/templates/css/default.css.j2 index 9bf722c020..b47872f93f 100644 --- a/roles/sys-front-inj-css/templates/css/default.css.j2 +++ b/roles/sys-front-inj-css/templates/css/default.css.j2 @@ -21,70 +21,67 @@ HINT: } } :root, ::after, ::before, ::backdrop { - /* For Dark Mode Plugin - * @See https://chromewebstore.google.com/detail/dark-mode/dmghijelimhndkbmpgbldicpogfkceaj - */ - --native-dark-accent-color: var(--color-01-60); /* was #a9a9a9 */ - --native-dark-bg-color: var(--color-01-10); /* was #292929 */ - --native-dark-bg-image-color: rgba(var(--color-rgb-01-01), 0.10); /* remains the same, or adjust if needed */ - --native-dark-border-color: var(--color-01-40); /* was #555555 */ + --native-dark-accent-color: var(--color-01-60); + --native-dark-bg-color: var(--color-01-10); + --native-dark-bg-image-color: rgba(var(--color-rgb-01-01), 0.10); + --native-dark-border-color: var(--color-01-40); --native-dark-box-shadow: 0 0 0 1px rgb(var(--color-rgb-01-99), / 10%); - --native-dark-cite-color: var(--color-01-70); /* was #92de92 – you might adjust if a green tone is needed */ - --native-dark-fill-color: var(--color-01-50); /* was #7d7d7d */ - --native-dark-font-color: var(--color-01-95); /* was #dcdcdc */ - --native-dark-link-color: var(--color-01-80); /* was #8db2e5 */ - --native-dark-visited-link-color: var(--color-01-85); /* was #c76ed7 */ + --native-dark-cite-color: var(--color-01-70); + --native-dark-fill-color: var(--color-01-50); + --native-dark-font-color: var(--color-01-95); + --native-dark-link-color: var(--color-01-80); + --native-dark-visited-link-color: var(--color-01-85); } /* Bootstrap Overrides (Color/Shadow Variables Only) */ :root { - --bs-black: var(--color-01-01); /* Original tone: Black (#000) */ - --bs-white: var(--color-01-99); /* Original tone: White (#fff) */ - --bs-gray: var(--color-01-50); /* Original tone: Gray (#6c757d) */ - --bs-gray-dark: var(--color-01-20); /* Original tone: Dark Gray (#343a40) */ + --bs-black: var(--color-01-01); + --bs-white: var(--color-01-99); + --bs-gray: var(--color-01-50); + --bs-gray-dark: var(--color-01-20); {% for i in range(1, 10) %} {% set gray = i * 100 %} {% set color = 100 - i * 10 %} --bs-gray-{{ gray }}: var(--color-01-{{ "%02d" % color }}); {% endfor %} - --bs-primary: var(--color-01-65); /* Original tone: Blue (#0d6efd) */ - --bs-light: var(--color-01-95); /* Original tone: Light (#f8f9fa) */ - --bs-dark: var(--color-01-10); /* Original tone: Dark (#212529) */ - --bs-primary-rgb: var(--color-rgb-01-65); /* Original tone: Blue (13, 110, 253) */ - --bs-secondary-rgb: var(--color-rgb-01-50); /* Original tone: Grayish (#6c757d / 108, 117, 125) */ - --bs-light-rgb: var(--color-rgb-01-95); /* Original tone: Light (248, 249, 250) */ - --bs-dark-rgb: var(--color-rgb-01-10); /* Original tone: Dark (33, 37, 41) */ - --bs-white-rgb: var(--color-rgb-01-99); /* Original tone: White (255, 255, 255) */ - --bs-black-rgb: var(--color-rgb-01-01); /* Original tone: Black (0, 0, 0) */ - --bs-body-color-rgb: var(--color-rgb-01-10); /* Original tone: Dark (#212529 / 33, 37, 41) */ - --bs-body-bg-rgb: var(--color-rgb-01-99); /* Original tone: White (#fff / 255, 255, 255) */ - --bs-body-color: var(--color-01-10); /* Original tone: Dark (#212529) */ - --bs-body-bg: var(--color-01-99); /* Original tone: White (#fff) */ - --bs-border-color: var(--color-01-85); /* Original tone: Gray (#dee2e6) */ - --bs-link-color: var(--color-01-65); /* Original tone: Blue (#0d6efd) */ - --bs-link-hover-color: var(--color-01-60); /* Original tone: Darker Blue (#0a58ca) */ - --bs-code-color: var(--color-01-55); /* Original tone: Pink (#d63384) */ - --bs-highlight-bg: var(--color-01-93); /* Original tone: Light Yellow (#fff3cd) */ + --bs-primary: var(--color-01-65); + --bs-light: var(--color-01-95); + --bs-dark: var(--color-01-10); + --bs-primary-rgb: var(--color-rgb-01-65); + --bs-secondary-rgb: var(--color-rgb-01-50); + --bs-light-rgb: var(--color-rgb-01-95); + --bs-dark-rgb: var(--color-rgb-01-10); + --bs-white-rgb: var(--color-rgb-01-99); + --bs-black-rgb: var(--color-rgb-01-01); + --bs-body-color-rgb: var(--color-rgb-01-10); + --bs-body-bg-rgb: var(--color-rgb-01-99); + --bs-body-color: var(--color-01-10); + --bs-body-bg: var(--color-01-99); + --bs-border-color: var(--color-01-85); + --bs-link-color: var(--color-01-65); + --bs-link-hover-color: var(--color-01-60); + --bs-code-color: var(--color-01-55); + --bs-highlight-bg: var(--color-01-93); --bs-list-group-bg: var(--color-01-40); - --bs-emphasis-color: var(--color-01-01); /* Gemappt von #000 */ - --bs-emphasis-color-rgb: var(--color-rgb-01-01); /* Gemappt von 0, 0, 0 */ - --bs-secondary-color: rgba(var(--color-rgb-01-10), 0.75); /* Gemappt von rgba(33, 37, 41, 0.75) */ - --bs-secondary-color-rgb: var(--color-rgb-01-10); /* Gemappt von 33, 37, 41 */ - --bs-secondary-bg: var(--color-01-90); /* Gemappt von #e9ecef */ - --bs-secondary-bg-rgb: var(--color-rgb-01-90); /* Gemappt von 233, 236, 239 */ - --bs-tertiary-color: rgba(var(--color-rgb-01-10), 0.5); /* Gemappt von rgba(33, 37, 41, 0.5) */ - --bs-tertiary-color-rgb: var(--color-rgb-01-10); /* Gemappt von 33, 37, 41 */ - --bs-tertiary-bg: var(--color-01-95); /* Gemappt von #f8f9fa */ - --bs-tertiary-bg-rgb: var(--color-rgb-01-95); /* Gemappt von 248, 249, 250 */ - --bs-link-color-rgb: var(--color-rgb-01-65); /* Gemappt von 13, 110, 253 */ - --bs-link-hover-color-rgb: var(--color-rgb-01-60); /* Gemappt von 10, 88, 202 */ - --bs-highlight-color: var(--color-01-10); /* Gemappt von #212529 */ - --bs-border-color-translucent: rgba(var(--color-rgb-01-01), 0.175); /* Gemappt von rgba(0, 0, 0, 0.175) */ - --bs-focus-ring-color: rgba(var(--color-rgb-01-65), 0.25); /* Gemappt von rgba(13, 110, 253, 0.25) */ + --bs-emphasis-color: var(--color-01-01); + --bs-emphasis-color-rgb: var(--color-rgb-01-01); + --bs-secondary-color: rgba(var(--color-rgb-01-10), 0.75); + --bs-secondary-color-rgb: var(--color-rgb-01-10); + --bs-secondary-bg: var(--color-01-90); + --bs-secondary-bg-rgb: var(--color-rgb-01-90); + --bs-tertiary-color: rgba(var(--color-rgb-01-10), 0.5); + --bs-tertiary-color-rgb: var(--color-rgb-01-10); + --bs-tertiary-bg: var(--color-01-95); + --bs-tertiary-bg-rgb: var(--color-rgb-01-95); + --bs-link-color-rgb: var(--color-rgb-01-65); + --bs-link-hover-color-rgb: var(--color-rgb-01-60); + --bs-highlight-color: var(--color-01-10); + --bs-border-color-translucent: rgba(var(--color-rgb-01-01), 0.175); + --bs-focus-ring-color: rgba(var(--color-rgb-01-65), 0.25); --bs-table-color: var(--bs-emphasis-color); - --bs-table-bg: var(--color-01-99); /* White (#fff) */ - --bs-table-border-color: var(--color-01-99); /* White (#fff) */ - --bs-table-striped-bg: var(--color-01-85); /* Light Gray (entspricht ca. #dee2e6) */ - --bs-table-hover-color: var(--color-01-01); /* Black (#000) */ + --bs-table-bg: var(--color-01-99); + --bs-table-border-color: var(--color-01-99); + --bs-table-striped-bg: var(--color-01-85); + --bs-table-hover-color: var(--color-01-01); --bs-table-hover-bg: rgba(var(--bs-emphasis-color-rgb), 0.075); } /* Global Defaults (Colors Only) */ @@ -119,53 +116,42 @@ a:active { html[native-dark-active] button, button{ background-color: var(--color-01-87); } -/* Bootstrap stretched-link cards use a full-card overlay; filtering that - overlay on hover causes unstable pointer hit-testing on the card. */ button:hover, .btn:not(.stretched-link):hover { filter: brightness(0.9); } -/* {# Invalid state: when the input value fails validation criteria. Use danger color for error indication. #} */ input:invalid, textarea:invalid, select:invalid { background-color: var(--color-01-01); background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-01), var(--color-01-10)); - /* Use Bootstrap danger color for error messages */ color: var(--bs-danger); border-color: var(--color-01-20); } -/* {# Valid state: when the input value meets all validation criteria. Use success color for confirmation. #} */ input:valid, textarea:valid, select:valid { background-color: var(--color-01-80); background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-80), var(--color-01-90)); - /* Use Bootstrap success color for confirmation messages */ color: var(--bs-success); border-color: var(--color-01-70); } -/* {# Required field: applied to elements that must be filled out by the user. Use warning color for emphasis. #} */ input:required, textarea:required, select:required { background-color: var(--color-01-50); background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-50), var(--color-01-60)); - /* Use Bootstrap warning color to indicate a required field */ color: var(--bs-warning); border-color: var(--color-01-70); } -/* {# Optional field: applied to elements that are not mandatory. Use info color to denote additional information. #} */ input:optional, textarea:optional, select:optional { background-color: var(--color-01-60); background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-60), var(--color-01-70)); - /* Use Bootstrap info color to indicate optional information */ color: var(--bs-info); border-color: var(--color-01-70); } -/* {# Read-only state: when an element is not editable by the user. #} */ input:read-only, textarea:read-only, select:read-only { @@ -174,7 +160,6 @@ select:read-only { color: var(--color-01-20); border-color: var(--color-01-50); } -/* {# Read-write state: when an element is editable by the user. #} */ input:read-write, textarea:read-write, select:read-write { @@ -183,7 +168,6 @@ select:read-write { color: var(--color-01-40); border-color: var(--color-01-70); } -/* {# In-range: for inputs with a defined range, when the value is within the allowed limits. #} */ input:in-range, textarea:in-range, select:in-range { @@ -192,7 +176,6 @@ select:in-range { color: var(--color-01-40); border-color: var(--color-01-70); } -/* {# Out-of-range: for inputs with a defined range, when the value falls outside the allowed limits. #} */ input:out-of-range, textarea:out-of-range, select:out-of-range { @@ -201,7 +184,6 @@ select:out-of-range { color: var(--color-01-10); border-color: var(--color-01-50); } -/* {# Placeholder-shown: when the input field is displaying its placeholder text. #} */ input:placeholder-shown, textarea:placeholder-shown, select:placeholder-shown { @@ -210,7 +192,6 @@ select:placeholder-shown { color: var(--color-01-40); border-color: var(--color-01-70); } -/* {# Focus state: when the element is focused by the user. #} */ input:focus, textarea:focus, select:focus { @@ -219,7 +200,6 @@ select:focus { color: var(--color-01-40); border-color: var(--color-01-50); } -/* {# Hover state: when the mouse pointer is over the element. #} */ input:hover, textarea:hover, select:hover { @@ -228,7 +208,6 @@ select:hover { color: var(--color-01-40); border-color: var(--color-01-65); } -/* {# Active state: when the element is being activated (e.g., clicked). #} */ input:active, textarea:active, select:active { @@ -260,7 +239,6 @@ th, td { } thead { background-color: var(--color-01-80); - /* New Gradient based on original background (80 -5, 80, 80 +1, 80 +5) */ background: linear-gradient({{ CSS_GRADIENT_ANGLE }}deg, var(--color-01-75), var(--color-01-80), var(--color-01-81), var(--color-01-85)); color: var(--color-01-40); } diff --git a/roles/sys-front-inj-dashboard/README.md b/roles/sys-front-inj-dashboard/README.md index 4deb143b29..afe6098934 100644 --- a/roles/sys-front-inj-dashboard/README.md +++ b/roles/sys-front-inj-dashboard/README.md @@ -22,7 +22,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 b/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 index fdcfbd1941..6920636a3f 100644 --- a/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 +++ b/roles/sys-front-inj-dashboard/templates/iframe-handler.js.j2 @@ -17,12 +17,17 @@ } } + function isInternalHost(hostname) { + if (hostname.endsWith(primary_domain) || hostname.endsWith(current_domain)) return true; + var onion = current_domain.match(/[a-z2-7]{56}\.onion$/); + return !!(onion && hostname.endsWith(onion[0])); + } + function forceExternalLinks() { Array.prototype.forEach.call(document.querySelectorAll("a[href]"), function (a) { try { var url = new URL(a.href, location); - // open new tab if link goes outside our primary OR current domain - if (!(url.hostname.endsWith(primary_domain) || url.hostname.endsWith(current_domain))) { + if (!isInternalHost(url.hostname)) { a.target = "_blank"; a.rel = "noopener"; } diff --git a/roles/sys-front-inj-javascript/README.md b/roles/sys-front-inj-javascript/README.md index 9786e2551f..217671a0df 100644 --- a/roles/sys-front-inj-javascript/README.md +++ b/roles/sys-front-inj-javascript/README.md @@ -19,7 +19,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-front-inj-javascript/tasks/main.yml b/roles/sys-front-inj-javascript/tasks/main.yml index 4647279bc2..663538e6c3 100644 --- a/roles/sys-front-inj-javascript/tasks/main.yml +++ b/roles/sys-front-inj-javascript/tasks/main.yml @@ -6,7 +6,7 @@ javascript_file_custom: >- {{ (application_id | abs_role_path_by_application_id ~ '/templates/javascript.js.j2') if lookup('fileglob', application_id | abs_role_path_by_application_id ~ '/templates/javascript.js.j2') - else application_id | abs_role_path_by_application_id ~ '/files/javascript.js' }} + else application_id | abs_role_path_by_application_id ~ '/files/javascript/javascript.js' }} - name: "📄 Load JavaScript code for '{{ application_id }}'" set_fact: diff --git a/roles/sys-front-inj-logout/README.md b/roles/sys-front-inj-logout/README.md index b65335668c..366069d8b5 100644 --- a/roles/sys-front-inj-logout/README.md +++ b/roles/sys-front-inj-logout/README.md @@ -9,7 +9,7 @@ The `sys-front-inj-logout` Ansible role automatically embeds a lightweight JavaS ## Overview - **Detection**: Scans the DOM for anchors (``), buttons, inputs, forms, `use` elements and any attributes indicating logout functionality. -- **Override**: Rewrites logout URLs to point at your OIDC provider’s logout endpoint, including a redirect back to the application. +- **Override**: Rewrites logout URLs to point at your OIDC provider’s logout endpoint. - **Dynamic content support**: Uses a `MutationObserver` to handle AJAX‑loaded or dynamically injected logout elements. - **CSP integration**: Automatically appends the required script hash into your CSP policy via the role’s CSP helper. @@ -24,7 +24,7 @@ flowchart LR end ``` -Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments). Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (💻 host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and ⚙️ an Ansible role dependency declared in `meta/main.yml`. ## Features diff --git a/roles/sys-front-inj-logout/files/logout.js b/roles/sys-front-inj-logout/files/javascript/logout.js similarity index 91% rename from roles/sys-front-inj-logout/files/logout.js rename to roles/sys-front-inj-logout/files/javascript/logout.js index 997b40d62d..2076b9a90d 100644 --- a/roles/sys-front-inj-logout/files/logout.js +++ b/roles/sys-front-inj-logout/files/javascript/logout.js @@ -3,12 +3,10 @@ /** * Initialize the logout patch script. - * @param {string} logoutUrlBase - Base logout URL (e.g., from your OIDC client). - * @param {string} webProtocol - Protocol to use (e.g., "https"). - * @param {string} primaryDomain - Primary domain (e.g., "example.com"). + * @param {string} logoutUrl - Logout URL (e.g., from your OIDC client). * @param {boolean} debugMode - If true, debug logging is enabled. */ - function initLogoutPatch(logoutUrlBase, webProtocol, primaryDomain, debugMode) { + function initLogoutPatch(logoutUrl, debugMode) { const DEBUG = !!debugMode; function log(reason, el, extra) { @@ -16,9 +14,6 @@ console.debug('[logoutPatch]', reason, extra || {}, el || null); } - const redirectUri = encodeURIComponent(`${webProtocol}://${primaryDomain}`); - const logoutUrl = `${logoutUrlBase}?redirect_uri=${redirectUri}`; - function matchesLogout(str) { const matched = str && /(?:^|\W)log\s*out(?:\W|$)|logout/i.test(str); if (matched) log('matchesLogout', null, { value: str }); @@ -102,7 +97,7 @@ * – Marks the element as patched to avoid double‐binding * * @param {Element} el – The element to override (e.g. ,