mirror of
https://github.com/fscotto/infra.git
synced 2026-11-26 21:59:50 +00:00
Compare commits
68 Commits
7db322039e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a9ecffecf | ||
| 012cb3534b | |||
| 47acda71b6 | |||
|
|
e74088e85b | ||
|
|
e2370ec91d | ||
|
|
59160abf0d | ||
| cdc102a970 | |||
| 66925b1d0d | |||
| 3facf61866 | |||
| 0b30890464 | |||
| ffa9960c64 | |||
| 7b85314cca | |||
| 95630f74d3 | |||
|
|
a2dca0e0d1 | ||
|
|
269f08a332 | ||
| 3f3781437b | |||
| 52c3615d26 | |||
| 4df3067c38 | |||
|
|
94eb555ff3 | ||
|
|
25a3b97b14 | ||
|
|
e8db4e5f38 | ||
|
|
2cadbf25eb | ||
|
|
d26dddd822 | ||
| 0bd0a4589b | |||
| bc01cd3863 | |||
| 9bc8e9bf72 | |||
| 4041af0799 | |||
|
|
4bd3c21295 | ||
| f09a708fe9 | |||
| ccb4a0daa6 | |||
| 695fdf4711 | |||
| 08728f45a1 | |||
| da13299a8a | |||
| da5742e1e1 | |||
| 5e62a02feb | |||
| ada83e97d3 | |||
| 667f55b87b | |||
| 69196460c9 | |||
| e4e99d2a2f | |||
| 775840d3ef | |||
| bde34e19f4 | |||
| 849e522287 | |||
| 1e40a867e7 | |||
| 4e8665a7d4 | |||
| 146c93c6c6 | |||
| 57c34a6de0 | |||
| 7928ff3825 | |||
| 90fe7a1671 | |||
| f6ef70a43f | |||
| 5d5339637d | |||
| 92a05e1f36 | |||
| 740a3571a6 | |||
| 6f6dabd532 | |||
| e48b0dce3d | |||
|
|
8b13e63a35 | ||
|
|
272667a20d | ||
| 393b633103 | |||
|
|
e29b3ed8b4 | ||
|
|
7b6d5396ab | ||
|
|
479b60f270 | ||
|
|
45d6e7e3ee | ||
|
|
d658fb6595 | ||
|
|
ed2cd1acd5 | ||
|
|
d9cee2effe | ||
|
|
5ebf1c1eb6 | ||
|
|
5f3792d603 | ||
|
|
c8df4dde87 | ||
|
|
7d80c57570 |
68
AGENTS.md
68
AGENTS.md
@@ -6,9 +6,10 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
|
||||
- Main orchestration: `ansible/site.yml`
|
||||
- Inventory and layering inputs: `ansible/inventory/hosts.yml`, `ansible/inventory/group_vars/*.yml`, `ansible/inventory/host_vars/*.yml`
|
||||
- Dotfiles live under `dotfiles/`
|
||||
- AI agent instructions (bootstrap, rules, knowledge) are centralized in `dotfiles/common/.config/ai/` and shared between OpenCode, Codex, and Gemini CLI.
|
||||
- OpenCode loads its entrypoint configuration from `dotfiles/common/.config/opencode/opencode.json`.
|
||||
- AI agent instructions (bootstrap, dispatcher, knowledge, rules, patterns) are centralized in `dotfiles/common/.config/ai/` and shared between OpenCode, Codex, Gemini CLI, and Cline.
|
||||
- OpenCode loads its entrypoint configuration from `dotfiles/common/.config/opencode/opencode.json`; Codex global instructions deploy from `dotfiles/common/.codex/AGENTS.md`; Cline deploys both the cross-tool `dotfiles/common/.agents/AGENTS.md` pointer (to `~/.agents/AGENTS.md`) and the always-on global rule `dotfiles/common/.cline/rules/ai-context.md` (to `~/.cline/rules/`), which auto-binds the deployed `bootstrap.md`, dispatcher, safety directives, and distilled ChatGPT knowledge.
|
||||
- Codex config is rendered from `dotfiles/common/.codex/config.toml.j2` so `model_instructions_file` points to the deployed `~/.config/ai/bootstrap.md`.
|
||||
- ChatGPT conversation memory is stored in `dotfiles/common/.config/ai/memory/chatgpt/` and regenerated incrementally by `scripts/chatgpt_export_to_memory.py` from an official ChatGPT data export.
|
||||
|
||||
## Topology
|
||||
- Current personal desktop: `ikaros = platform_fedora + role_personal_workstation + graphical_desktop + desktop_gnome`
|
||||
@@ -28,9 +29,10 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
|
||||
- Keep completed one-time cleanup operations out of the playbook. Execute them directly
|
||||
with explicit authorization; retain only the ongoing desired-state configuration and
|
||||
historical documentation, not permanent cleanup flags or tasks.
|
||||
- Use Git Flow branch prefixes: `feature/` for new functionality, `bugfix/` for non-urgent fixes,
|
||||
`hotfix/` for urgent production fixes, `release/` for release preparation, and `support/` for
|
||||
maintained release lines. Do not use abbreviated prefixes such as `feat/`.
|
||||
- Use trunk-based development: `main` is the single long-lived branch. Land small,
|
||||
validated changes quickly, either as direct commits or via short-lived branches merged
|
||||
as soon as validation passes. Do not maintain `release/`, `support/`, or other
|
||||
long-lived branch lines: tag releases from the trunk and fix production issues on it.
|
||||
- Desktop and WSL hosts use `ansible_connection: local`; remote infrastructure hosts use SSH.
|
||||
- Treat `secrets/` as sensitive. Never print secret values.
|
||||
- Tmux plugins are bootstrapped by TPM on the host; the repo only keeps tmux config and custom helper scripts.
|
||||
@@ -56,7 +58,9 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
|
||||
- Focused checks:
|
||||
- Emacs is disabled by default; temporary Emacs check: `ansible-playbook ansible/site.yml --limit <host> --tags emacs --check --diff -e emacs_enabled=true`
|
||||
- AI coding agents: `ansible-playbook ansible/site.yml --limit <host> --tags ai_agents --check --diff`
|
||||
- AI desktop apps lifecycle: `ansible-playbook ansible/site.yml --limit ikaros --tags chatgpt,opencode_desktop,cline_desktop --check --diff`
|
||||
- Mail bootstrap: `sh -n scripts/bootstrap_mail.sh` and `shellcheck scripts/bootstrap_mail.sh`
|
||||
- Thunderbird iCloud profile: `ansible-playbook ansible/site.yml --limit ikaros --tags thunderbird --check --diff`
|
||||
- Server NPM Quadlet: `systemctl status prometheus-npm.service`; the Compose fallback is retired.
|
||||
- Explicit Prometheus legacy cleanup (destructive only without check mode):
|
||||
`ansible-playbook ansible/site.yml --limit prometheus --tags server_legacy_cleanup --check --diff -e server_legacy_cleanup=true`
|
||||
@@ -101,6 +105,8 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
|
||||
- Prefer declarative modules over `command`/`shell`; when `shell` is required, make idempotency and failure behavior explicit.
|
||||
- Start YAML files with `---`, use 2-space indentation, and keep file modes quoted like `"0644"`.
|
||||
- Keep booleans as booleans and structured vars as YAML lists/maps.
|
||||
- Group similar tasks into list variables (typically in `group_vars`) and apply them
|
||||
with a single task looping over the list, rather than one near-identical task per item.
|
||||
- Put host-specific overrides in `host_vars`, not shared `group_vars`.
|
||||
- Use `no_log: true` for secret-bearing task inputs or outputs.
|
||||
|
||||
@@ -116,6 +122,7 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
|
||||
- `dotfiles/desktop/.config/niri/config.kdl` and `session-env` deployed via `desktop_niri_dotfiles` (Niri / Wayland)
|
||||
- Void Niri lives in `profile_desktop_niri`, gated on `'niri' in desktop_sessions_enabled`; it installs the `emptty` `niri.desktop` session, the `/usr/local/bin/start-niri` launcher, and the xdg-desktop-portal config, mirroring `profile_desktop_sway`.
|
||||
- Fedora GNOME (`desktop_gnome`) assumes GNOME comes from the Fedora Workstation base install; Ansible deploys shared desktop dotfiles and git/GPG config for `ikaros` and `nymph`, not GNOME settings.
|
||||
- `profile_desktop_gnome` first discovers configured Thunderbird accounts in both `~/.thunderbird` and `~/.config/thunderbird` and selects an existing profile without changing its account settings. Only if no account exists does it seed a new iCloud IMAP/SMTP profile with CalDAV and CardDAV through a non-overwriting `user.js`. Registry changes preserve other profiles and create backups; Thunderbird must be closed. The bootstrap address comes from `vault_icloud_email` and the app-specific password is never stored by Ansible.
|
||||
- Do not switch or restart the display manager during a playbook run from an active graphical session.
|
||||
- `nymph` is the Fedora/GNOME laptop target; keep GNOME settings unmanaged for now and add host-specific tuning only after real use.
|
||||
|
||||
@@ -134,7 +141,6 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
|
||||
## Workstation Notes
|
||||
- `deadalus` is modeled as Windows + Fedora WSL and is the sole workstation target.
|
||||
- Fedora WSL belongs to `platform_fedora`, `workstation_dev_fedora`, and the shared WSL layer. It must not receive Flatpak or Snap runtimes.
|
||||
- Fedora WSL installs Mise from the official `jdxcode/mise` COPR and uses its pinned Temurin Java 11 JDK; update the declared Mise version deliberately.
|
||||
- Windows applications are installed manually and are not managed from the WSL profile.
|
||||
|
||||
## Rocky Server Notes
|
||||
@@ -204,6 +210,39 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
|
||||
when it is assigned. After a firewalld reload, restore Prometheus' rootful Podman networking with
|
||||
`podman network reload --all` so the existing proxy stack retains container DNS.
|
||||
|
||||
- Atlas qBittorrent is selected by `atlas_manage_qbittorrent` and managed with the
|
||||
`qbittorrent` tag as the admin-owned rootless `atlas-qbittorrent.service` Quadlet.
|
||||
Its Web UI is `http://192.168.178.55:8090` on the LAN and prepared for the manual
|
||||
NPM HTTPS domain `torrent.fscotto.co`, trusting only Aegis for forwarded client
|
||||
addresses. DNS and NPM configuration stay manual. Configuration lives in
|
||||
`services/data/qbittorrent`, and only `Archive/Downloads` is writable as payload
|
||||
storage. It uses the home Internet connection, not WireGuard or a VPN; no router
|
||||
forwarding or published torrent peer port is configured. See `docs/atlas-qbittorrent.md`.
|
||||
|
||||
- Atlas HTTP downloads use the admin-owned rootless `atlas-aria2.service` and
|
||||
`atlas-ariang.service` Quadlets, gated by `atlas_manage_aria2` and the `aria2` tag.
|
||||
AriaNg binds the LAN at `http://192.168.178.55:8091`; direct RPC is LAN-only on TCP/6800
|
||||
and requires a private target-generated token. State lives in `services/data/aria2`,
|
||||
with payloads in `Archive/Downloads`; do not expose RPC through the existing
|
||||
qBittorrent `torrent.fscotto.co` endpoint. Public `downloads.fscotto.co` uses
|
||||
a manual NPM Access List for both UI and `/jsonrpc`. The `aria2_gateway` tag
|
||||
manages an admin user service on TCP/8092, accessible only through Aegis,
|
||||
injecting the private token for JSON-RPC POST clients; keep this route
|
||||
authenticated and never expose the gateway directly. See `docs/atlas-aria2.md`.
|
||||
|
||||
- Atlas Nextcloud backup preparation (`atlas-nextcloud-backup.service`) is an ordered
|
||||
requirement of the nightly `atlas-borg-backup.service` and the operator-started
|
||||
`atlas-usb-backup.service`. A structurally complete bundle younger than
|
||||
`atlas_nextcloud_backup_reuse_max_seconds` (20 h, asserted below 24 h so the nightly
|
||||
Borg cycle always refreshes it) is reused without pausing the applications: a manual
|
||||
USB run therefore reaches its LUKS prompt within seconds, while preparation failure
|
||||
still blocks the dependent job. Force one fresh preparation with
|
||||
`systemctl set-environment ATLAS_NEXTCLOUD_BACKUP_FORCE=1` before the start and unset
|
||||
the variable afterwards. Deployed and validated on 2026-11-15: a dependency start reused
|
||||
a verified bundle 14 h old and skipped preparation in 14 ms, and an operator-started
|
||||
USB run reached its LUKS prompt in under a second; the FORCE path has not been exercised
|
||||
in production yet. See `docs/atlas-nextcloud.md`.
|
||||
|
||||
## Atlas NAS TODO
|
||||
Completed validation: the existing RAIDZ2 pool and datasets, SELinux, LAN firewall, SSH, Cockpit with
|
||||
the selected 45Drives plugins, encrypted SMB3 `Archive`, the Aegis-only NFSv4 `photobook` export, and the
|
||||
@@ -525,9 +564,13 @@ validated exports of older historical data will use a dedicated Atlas NFS datase
|
||||
- Shared agent dotfiles live in `ai_agents_dotfiles`; rendered configs live in `ai_agents_templates`.
|
||||
- Every `ai_agents.<agent>` entry has independent `install_enabled`, `deploy_enabled`, and `uninstall_enabled` flags. Installation and removal must not both be true for the same agent; the common pre-task fails before changes when they conflict.
|
||||
- Fedora, Void desktop, and WSL workstation profiles consume the shared agent definitions; do not duplicate package entries in profile-specific vars. IBM Bob on the workstation follows its own flags.
|
||||
- WSL (`deadalus`) installs Claude Code, Codex and the Cline CLI; every other managed agent (including IBM Bob) is disabled and selected for removal through host overrides. `cline_deploy_enabled: true` also keeps Cline's cross-tool AGENTS pointer, global rules, and shared `~/.config/ai` context deployed on the host for the ecaas/cdp devcontainer bind mounts. Existing user state remains untouched.
|
||||
- `dotfiles_common` deploys `ai_agents_dotfiles` and renders `ai_agents_templates` only when deployment is enabled.
|
||||
- Removal is limited to the managed npm packages and `/usr/local/bin/bob`; never remove agent dotfiles, instructions, credentials, or user data.
|
||||
- Keep `.config/ai/` as the common instruction source; update agent-specific entrypoints to reference it rather than duplicating instruction text.
|
||||
- Fedora desktop AI apps (`chatgpt_desktop`, `opencode_desktop`, `cline_desktop`) follow the same lifecycle pattern through `ai_desktop_apps` in `ansible/inventory/group_vars/fedora.yml`; `install_enabled` and `uninstall_enabled` are independent per app and mutually exclusive (enforced by the common pre-task).
|
||||
- ChatGPT opts in per host (`ikaros`, `nymph`); Cline opts in through `desktop_gnome` group vars; OpenCode Desktop keeps removal selected by default because Cline replaced it.
|
||||
- Desktop-app removal deletes only managed artifacts: the RPM package (`chatgpt`, `opencode`, `cline`), ChatGPT's managed repository and signing key, and every cached download; it never removes user data, GNOME favorites, or the npm-managed CLI counterparts.
|
||||
|
||||
## Tooling Notes
|
||||
- Install local tooling with:
|
||||
@@ -561,3 +604,16 @@ validated exports of older historical data will use a dedicated Atlas NFS datase
|
||||
not depend on the AdGuard container during startup.
|
||||
- Aegis iCloudPD has been retired and is no longer managed by this role. Its service, Quadlet,
|
||||
data, and MFA state were removed with the operator's explicit authorization.
|
||||
|
||||
## Project Devcontainer Generator
|
||||
- `cmd/devcontainer/` generates standalone per-project language configurations;
|
||||
it does not replace existing deadalus ecaas/cdp provisioning or remove host tools.
|
||||
- Keep shared Git/agent behavior documented in `docs/project-devcontainers.md`.
|
||||
- Focused validation: `go -C cmd/devcontainer test ./...`.
|
||||
- Real engine builds, host credential forwarding and Fedora SELinux/Podman checks
|
||||
require target-host validation; do not report generator tests as runtime evidence.
|
||||
|
||||
- `devcontainer_generator` builds the CLI natively on Fedora graphical desktops
|
||||
and development workstations and installs it in `~/.local/bin/devcontainer`.
|
||||
Validate with `ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator --check --diff`;
|
||||
check mode skips compilation and binary installation explicitly.
|
||||
|
||||
@@ -164,7 +164,6 @@ Lo stato attuale del profilo workstation include:
|
||||
|
||||
- installazione pacchetti base Fedora via dnf
|
||||
- installazione e configurazione di Docker dal repository ufficiale
|
||||
- installazione di Mise dal COPR ufficiale con JDK Eclipse Temurin Java 11 fissato
|
||||
- gestione dei dotfiles workstation e rendering dei template dev condivisi
|
||||
- preparazione di Fedora WSL con `systemd` per il toolchain di sviluppo
|
||||
- attivazione del firewall `firewalld` sui target Fedora che dichiarano regole host-specifiche
|
||||
@@ -754,7 +753,7 @@ Allo stato attuale `ansible/site.yml` espone questi tag:
|
||||
| Tag | Scopo | Ambito principale |
|
||||
| --- | --- | --- |
|
||||
| `always` | pre-task sempre eseguiti, inclusi caricamento vault e validazioni preliminari | common |
|
||||
| `ai_agents` | installazione agenti AI condivisi | Fedora, WSL |
|
||||
| `ai_agents` | installazione agenti AI condivisi e distribuzione del contesto condiviso (bootstrap, regole, memoria ChatGPT) | Fedora, WSL |
|
||||
| `atlas` | account, storage, condivisioni e container Atlas | NAS Atlas |
|
||||
| `backend_phase1` | Quadlet rootless Navidrome e Syncthing | NAS Atlas |
|
||||
| `containers` | Quadlet rootful Atlas | NAS Atlas |
|
||||
|
||||
146
README.md
146
README.md
@@ -63,9 +63,11 @@ nymph is allowed to break
|
||||
|
||||
`ikaros` is the stable personal Fedora/GNOME desktop. `nymph` is the laptop and gets the same shared desktop dotfiles while GNOME itself stays close to the Fedora defaults. The legacy `void` and `desktop` groups are compatibility parents; the main axes are `platform_*`, `role_*`, and `desktop_*`.
|
||||
|
||||
The official ChatGPT desktop RPM is enabled only on `ikaros` and `nymph`. The
|
||||
playbook configures OpenAI's signed RPM repository and imports its pinned RPM
|
||||
signing key before installation; subsequent updates are handled by DNF.
|
||||
The official ChatGPT desktop RPM is installed only on `ikaros` and `nymph`
|
||||
through their `chatgpt_desktop_install_enabled` host overrides. The playbook
|
||||
configures OpenAI's signed RPM repository and imports its pinned RPM signing
|
||||
key before installation; subsequent updates are handled by DNF. Enabling
|
||||
`chatgpt_desktop_uninstall_enabled` removes the package, repository, and key.
|
||||
|
||||
## Deferred planned node: Cerberus
|
||||
|
||||
@@ -114,7 +116,7 @@ The workstation receives two layers:
|
||||
- Fedora development setup through `workstation_dev_fedora`.
|
||||
- WSL setup with `systemd` through `workstation_dev_wsl`.
|
||||
|
||||
That gives it Fedora packages through DNF, Docker from the official repository, Mise from its official COPR repository with a pinned Eclipse Temurin Java 11 JDK, shared workstation dotfiles and templates, tmux helpers, and WSL systemd configuration. Windows applications are installed manually; the WSL profile does not manage Python remoting components for them.
|
||||
That gives it Fedora packages through DNF, Docker from the official repository, shared workstation dotfiles and templates, tmux helpers, and WSL systemd configuration. Windows applications are installed manually; the WSL profile does not manage Python remoting components for them.
|
||||
|
||||
### WSL workflow
|
||||
|
||||
@@ -575,8 +577,8 @@ ansible-playbook ansible/site.yml --limit <host> --tags emacs -e emacs_enabled=t
|
||||
## AI coding agents
|
||||
|
||||
The shared npm-managed agents are OpenCode, Claude Code, Codex, Gemini CLI, and
|
||||
GitHub Copilot; IBM Bob is also managed on `deadalus`. Codex Relay is installed
|
||||
only on `ikaros`. Each agent has its own lifecycle flags in
|
||||
GitHub Copilot; IBM Bob is also managed on Fedora workstations. Codex Relay is installed
|
||||
only on `ikaros`. On WSL (`deadalus`), Claude Code is the only installed coding agent. Each agent has its own lifecycle flags in
|
||||
`ansible/inventory/group_vars/all.yml`, so one agent can be installed,
|
||||
configured, or removed without affecting the others:
|
||||
|
||||
@@ -596,6 +598,48 @@ instructions, credentials, and user data. Installation and removal are mutually
|
||||
exclusive per agent: the playbook fails before making changes when both flags are
|
||||
true for the same agent. Servers set `ai_agents: {}` and therefore manage none.
|
||||
|
||||
On WSL (`deadalus`), Claude Code, Codex and the Cline CLI are installed through
|
||||
`profile_workstation_dev_common`. Every other managed coding agent is disabled through
|
||||
host overrides and its managed npm package or `bob` binary is selected for removal.
|
||||
`cline_deploy_enabled: true` also keeps Cline's cross-tool AGENTS pointer, global rules,
|
||||
and shared `~/.config/ai` context deployed on the WSL host for the ecaas/cdp devcontainers.
|
||||
Existing configuration, credentials, and user data are left untouched.
|
||||
|
||||
The shared agent context is centralized in `dotfiles/common/.config/ai/` and
|
||||
deployed to `~/.config/ai/` for every enabled agent: `bootstrap.md` (operating
|
||||
context), `AGENTS.md` (task-specific file dispatcher), plus `knowledge/`,
|
||||
`rules/`, and `patterns/`. Each agent is wired to it: OpenCode through the
|
||||
`instructions` array in `opencode.json`, Codex through `model_instructions_file`
|
||||
plus the global `~/.codex/AGENTS.md`, Gemini CLI through its settings context
|
||||
files, Claude Code through the `@` imports in `~/.claude/CLAUDE.md`, and Cline
|
||||
through both the cross-tool `~/.agents/AGENTS.md` pointer and the always-on
|
||||
global rule `~/.cline/rules/ai-context.md`, which binds `bootstrap.md`, the
|
||||
dispatcher, the safety directives, and the distilled ChatGPT knowledge under
|
||||
`memory/chatgpt/` (both deployed with `cline_deploy_enabled: true`). Cline
|
||||
shows the rule in its Rules panel as `global:ai-context`, where it can be
|
||||
toggled per project.
|
||||
|
||||
ChatGPT conversation memory lives in
|
||||
`dotfiles/common/.config/ai/memory/chatgpt/`: one Markdown transcript per
|
||||
conversation, a generated `INDEX.md`, and topic-distilled knowledge files under
|
||||
`memory/chatgpt/knowledge/` that agents load through the dispatcher. Regenerate
|
||||
it incrementally from an official ChatGPT data export with:
|
||||
|
||||
```bash
|
||||
python3 scripts/chatgpt_export_to_memory.py --export-dir ~/Downloads/<export>
|
||||
```
|
||||
|
||||
Binary and personal assets (PDFs, images) are deliberately not imported;
|
||||
textual ones are copied under `memory/chatgpt/assets/`. Non-technical personal
|
||||
conversations are excluded from import by a privacy blocklist in the script,
|
||||
which also prunes any previously imported copy.
|
||||
|
||||
The `opencode-mobile` npm package is no longer installed on managed hosts: its
|
||||
agent entry sets `install_enabled: false` and `uninstall_enabled: true`, so the
|
||||
playbook removes the managed package. The plugin declaration and `/mobile`
|
||||
command are still deployed with the OpenCode dotfiles, and pairing and
|
||||
connectivity remain manual; see the [upstream instructions](https://github.com/doza62/opencode-mobile#readme).
|
||||
|
||||
Run a focused dry run with:
|
||||
|
||||
```bash
|
||||
@@ -610,6 +654,86 @@ only in the entry for the agent being removed, then run:
|
||||
ansible-playbook ansible/site.yml --limit deadalus --tags ai_agents --check --diff
|
||||
```
|
||||
|
||||
### AI desktop applications
|
||||
|
||||
The same lifecycle-flag pattern manages the Fedora desktop applications
|
||||
through `ai_desktop_apps` in `ansible/inventory/group_vars/fedora.yml`.
|
||||
`chatgpt_desktop`, `opencode_desktop` and `cline_desktop` each expose
|
||||
`install_enabled` and `uninstall_enabled`, and the common pre-task rejects
|
||||
both being true for the same app. ChatGPT opts in per host (`ikaros`, `nymph`),
|
||||
Cline opts in through `desktop_gnome` group vars, and OpenCode Desktop keeps
|
||||
removal selected because Cline replaced it.
|
||||
|
||||
Removal deletes only what the playbook manages — the installed RPM package,
|
||||
ChatGPT's managed repository and signing key, and every cached download — and
|
||||
leaves GNOME favorites, user data, and the npm-managed CLI counterparts
|
||||
untouched. To switch an app between installed and removed, flip exactly one
|
||||
of its lifecycle flags, then preview with:
|
||||
|
||||
```bash
|
||||
ansible-playbook ansible/site.yml --limit ikaros --tags chatgpt,opencode_desktop,cline_desktop --check --diff
|
||||
```
|
||||
|
||||
### Cline Desktop on Fedora
|
||||
|
||||
The [official Cline Desktop RPM](https://cline.bot/desktop) is managed on the
|
||||
Fedora/GNOME workstations `ikaros` and `nymph`. WSL, Fedora IoT, Void and servers
|
||||
are excluded. The GNOME profile pins `Cline.desktop` in the position of an old
|
||||
OpenCode favorite, or appends it if there was no OpenCode favorite. Other
|
||||
favorites keep their order. Run the playbook from an active GNOME session.
|
||||
|
||||
The version and per-architecture SHA-256 digests are pinned in
|
||||
`ansible/inventory/group_vars/fedora.yml`; update both together from the official
|
||||
[Desktop release](https://github.com/cline/cline/releases/tag/desktop-v0.0.49).
|
||||
Only the checksum-verified local RPM installation disables DNF signature
|
||||
checking; no repository policy is changed. The Cline VS Code extension and
|
||||
npm-managed CLIs are independent of this app.
|
||||
|
||||
```bash
|
||||
ansible-playbook ansible/site.yml --limit ikaros --tags cline_desktop --check --diff
|
||||
ansible-playbook ansible/site.yml --limit ikaros --tags cline_desktop -K
|
||||
```
|
||||
|
||||
Run locally on each workstation (`ansible_connection: local`); use `--limit nymph`
|
||||
on the laptop. With a cold RPM cache, check mode reports that dependency resolution
|
||||
is not validated; the real run downloads, verifies, and installs the package.
|
||||
Cline replaced OpenCode Desktop: its `ai_desktop_apps` entry keeps
|
||||
`opencode_desktop_uninstall_enabled: true` by default, so a previously
|
||||
installed `opencode` RPM converges away on graphical hosts. Flip the entry's
|
||||
flags to reinstall the pinned release instead. Neither removal touches the
|
||||
npm CLI or user data.
|
||||
|
||||
### Thunderbird iCloud profile on Fedora
|
||||
|
||||
`profile_desktop_gnome` seeds a Thunderbird profile for `ikaros` and `nymph` so the
|
||||
iCloud account is already declared: IMAP `imap.mail.me.com:993` over SSL/TLS, SMTP
|
||||
`smtp.mail.me.com:587` over STARTTLS, the identity and folder mapping, one CalDAV
|
||||
calendar (`caldav.icloud.com`) and one CardDAV address book (`contacts.icloud.com`).
|
||||
|
||||
Before provisioning, the role checks both `~/.thunderbird` and
|
||||
`~/.config/thunderbird`, including registered absolute profile paths. If a profile
|
||||
already has a configured mail account, it selects that profile without modifying
|
||||
its account preferences, passwords, calendars or address books. Registered default
|
||||
profiles take priority over other discovered profiles. The active registry keeps
|
||||
its other profiles and is backed up before changes, including installation defaults.
|
||||
|
||||
Only when no configured account exists does the role create the iCloud profile
|
||||
and seed `user.js` without overwriting an existing file. Thunderbird must be closed
|
||||
before applying this tag; the playbook never stops it automatically. No profile or
|
||||
mail data is deleted or copied. A fresh installation uses `~/.config/thunderbird`;
|
||||
an existing legacy `~/.thunderbird` directory is retained.
|
||||
|
||||
The address comes from `vault_icloud_email` and the display name from
|
||||
`vault_personal_full_name`. The password is deliberately not stored: iCloud mail
|
||||
requires an app-specific password, which Thunderbird requests on first use and
|
||||
keeps in its own credential store. Set `thunderbird_icloud_enabled: false` to stop
|
||||
managing the profile without deleting it.
|
||||
|
||||
```bash
|
||||
ansible-playbook ansible/site.yml --limit ikaros --tags thunderbird --check --diff
|
||||
ansible-playbook ansible/site.yml --limit ikaros --tags thunderbird -K
|
||||
```
|
||||
|
||||
## Main roles
|
||||
|
||||
| Role | What it does |
|
||||
@@ -769,3 +893,13 @@ For a future Void desktop host:
|
||||
4. Put hardware-specific details in `host_vars/<host>.yml`.
|
||||
|
||||
The legacy `void` and `desktop` groups remain compatibility parents, so hosts in `platform_void` and `graphical_desktop` still receive the existing Void and desktop variables.
|
||||
|
||||
## Project devcontainer generator
|
||||
|
||||
Generate a reusable language environment for an existing project with
|
||||
`devcontainer ~/src/project --language python --agents codex,cline`.
|
||||
Git and selected coding-agent configuration are shared from the development host.
|
||||
See [profiles, host requirements and validation](docs/project-devcontainers.md).
|
||||
|
||||
Deploy `~/.local/bin/devcontainer` on a Fedora desktop/workstation with
|
||||
`ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator -K`.
|
||||
|
||||
@@ -93,43 +93,75 @@ common_dotfiles:
|
||||
# AI coding-agent lifecycle controls are independent for every agent.
|
||||
# Installation and removal are mutually exclusive per agent; the common
|
||||
# pre-task enforces this before any changes are made.
|
||||
opencode_install_enabled: true
|
||||
opencode_deploy_enabled: true
|
||||
opencode_uninstall_enabled: false
|
||||
codex_install_enabled: true
|
||||
codex_deploy_enabled: true
|
||||
codex_uninstall_enabled: false
|
||||
codex_relay_install_enabled: false
|
||||
codex_relay_uninstall_enabled: false
|
||||
gemini_cli_install_enabled: true
|
||||
gemini_cli_deploy_enabled: true
|
||||
gemini_cli_uninstall_enabled: false
|
||||
claude_code_install_enabled: false
|
||||
claude_code_uninstall_enabled: true
|
||||
cline_install_enabled: true
|
||||
cline_deploy_enabled: true
|
||||
cline_uninstall_enabled: false
|
||||
ibm_bob_install_enabled: true
|
||||
ibm_bob_uninstall_enabled: false
|
||||
|
||||
# npm registry requests can be interrupted transiently. Keep retries bounded
|
||||
# so persistent proxy, DNS, or registry failures still fail the play clearly.
|
||||
ai_agents_npm_install_retries: 3
|
||||
ai_agents_npm_install_retry_delay: 10
|
||||
|
||||
ai_agents:
|
||||
opencode:
|
||||
npm_package: opencode-ai
|
||||
install_enabled: true
|
||||
deploy_enabled: true
|
||||
uninstall_enabled: false
|
||||
claude_code:
|
||||
npm_package: "@anthropic-ai/claude-code"
|
||||
install_enabled: "{{ opencode_install_enabled }}"
|
||||
deploy_enabled: "{{ opencode_deploy_enabled }}"
|
||||
uninstall_enabled: "{{ opencode_uninstall_enabled }}"
|
||||
opencode_mobile:
|
||||
npm_package: opencode-mobile
|
||||
install_enabled: false
|
||||
deploy_enabled: false
|
||||
uninstall_enabled: true
|
||||
claude_code:
|
||||
npm_package: "@anthropic-ai/claude-code"
|
||||
install_enabled: "{{ claude_code_install_enabled }}"
|
||||
deploy_enabled: false
|
||||
uninstall_enabled: "{{ claude_code_uninstall_enabled }}"
|
||||
codex:
|
||||
npm_package: "@openai/codex"
|
||||
install_enabled: true
|
||||
deploy_enabled: true
|
||||
uninstall_enabled: false
|
||||
install_enabled: "{{ codex_install_enabled }}"
|
||||
deploy_enabled: "{{ codex_deploy_enabled }}"
|
||||
uninstall_enabled: "{{ codex_uninstall_enabled }}"
|
||||
codex_relay:
|
||||
npm_package: codex-relay
|
||||
install_enabled: "{{ codex_relay_install_enabled }}"
|
||||
deploy_enabled: false
|
||||
uninstall_enabled: false
|
||||
uninstall_enabled: "{{ codex_relay_uninstall_enabled }}"
|
||||
gemini_cli:
|
||||
npm_package: "@google/gemini-cli"
|
||||
install_enabled: true
|
||||
deploy_enabled: true
|
||||
uninstall_enabled: false
|
||||
install_enabled: "{{ gemini_cli_install_enabled }}"
|
||||
deploy_enabled: "{{ gemini_cli_deploy_enabled }}"
|
||||
uninstall_enabled: "{{ gemini_cli_uninstall_enabled }}"
|
||||
cline:
|
||||
npm_package: cline
|
||||
install_enabled: "{{ cline_install_enabled }}"
|
||||
deploy_enabled: "{{ cline_deploy_enabled }}"
|
||||
uninstall_enabled: "{{ cline_uninstall_enabled }}"
|
||||
github_copilot:
|
||||
npm_package: "@github/copilot"
|
||||
install_enabled: false
|
||||
deploy_enabled: false
|
||||
uninstall_enabled: true
|
||||
ibm_bob:
|
||||
install_enabled: true
|
||||
install_enabled: "{{ ibm_bob_install_enabled }}"
|
||||
deploy_enabled: false
|
||||
uninstall_enabled: false
|
||||
uninstall_enabled: "{{ ibm_bob_uninstall_enabled }}"
|
||||
|
||||
ai_agents_deploy_enabled_names: >-
|
||||
{{ ai_agents | dict2items | selectattr('value.deploy_enabled') | map(attribute='key') | list }}
|
||||
@@ -143,6 +175,7 @@ ai_agents_dotfiles:
|
||||
- opencode
|
||||
- codex
|
||||
- gemini_cli
|
||||
- cline
|
||||
- name: Gemini CLI config
|
||||
src: .gemini/
|
||||
dest: .gemini/
|
||||
@@ -161,6 +194,24 @@ ai_agents_dotfiles:
|
||||
mode: preserve
|
||||
agents:
|
||||
- claude_code
|
||||
- name: Codex global AGENTS instructions
|
||||
src: .codex/AGENTS.md
|
||||
dest: .codex/AGENTS.md
|
||||
mode: "0644"
|
||||
agents:
|
||||
- codex
|
||||
- name: Cline cross-tool AGENTS instructions
|
||||
src: .agents/AGENTS.md
|
||||
dest: .agents/AGENTS.md
|
||||
mode: "0644"
|
||||
agents:
|
||||
- cline
|
||||
- name: Cline global rules
|
||||
src: .cline/rules/
|
||||
dest: .cline/rules/
|
||||
mode: preserve
|
||||
agents:
|
||||
- cline
|
||||
|
||||
ai_agents_templates:
|
||||
- name: Codex config
|
||||
|
||||
@@ -42,10 +42,6 @@ desktop_uv_tools:
|
||||
- python-lsp-server
|
||||
|
||||
desktop_common_dotfiles:
|
||||
- name: XDG autostart entries
|
||||
src: .config/autostart/
|
||||
dest: .config/autostart/
|
||||
mode: preserve
|
||||
- name: fastfetch config
|
||||
src: .config/fastfetch/
|
||||
dest: .config/fastfetch/
|
||||
@@ -218,7 +214,6 @@ desktop_niri_dotfiles:
|
||||
|
||||
desktop_flatpak_packages:
|
||||
- be.alexandervanhee.gradia
|
||||
- ch.protonmail.protonmail-bridge
|
||||
- com.discordapp.Discord
|
||||
- com.calibre_ebook.calibre
|
||||
- com.github.tchx84.Flatseal
|
||||
|
||||
@@ -4,6 +4,9 @@ desktop_environment: gnome
|
||||
desktop_sessions_enabled: []
|
||||
desktop_default_session: gnome
|
||||
emacs_enabled: true
|
||||
# Cline Desktop is installed (and pinned in the GNOME favorites) on every
|
||||
# GNOME host; set cline_desktop_uninstall_enabled here to remove it instead.
|
||||
cline_desktop_install_enabled: true
|
||||
|
||||
# Fedora Workstation/GNOME desktop applications. Keep this profile separate from
|
||||
# workstation_* so nymph can remain a desktop laptop rather than a dev workstation.
|
||||
@@ -22,7 +25,7 @@ fedora_desktop_packages:
|
||||
- croc
|
||||
- delve
|
||||
- dnsmasq
|
||||
- evolution
|
||||
- thunderbird
|
||||
- fastfetch
|
||||
- poppler-glib
|
||||
- poppler-utils
|
||||
@@ -42,6 +45,7 @@ fedora_desktop_packages:
|
||||
- libXft-devel
|
||||
- meld
|
||||
- mpv
|
||||
- nextcloud-client
|
||||
- pdfarranger
|
||||
- pinentry-gnome3
|
||||
- plocate
|
||||
@@ -72,6 +76,10 @@ fedora_desktop_packages:
|
||||
- yt-dlp
|
||||
- zstd
|
||||
|
||||
fedora_removed_packages:
|
||||
- evolution
|
||||
- evolution-langpacks
|
||||
|
||||
fedora_nerd_fonts_version: v3.3.0
|
||||
fedora_nerd_fonts:
|
||||
- Hack
|
||||
@@ -82,7 +90,82 @@ fedora_nerd_fonts:
|
||||
|
||||
fedora_flatpak_packages:
|
||||
- be.alexandervanhee.gradia
|
||||
- ch.protonmail.protonmail-bridge
|
||||
- com.spotify.Client
|
||||
- org.desktop_plus.desktop-plus
|
||||
- org.onlyoffice.desktopeditors
|
||||
- org.telegram.desktop
|
||||
|
||||
# GNOME-only dotfiles. Kept out of desktop_common_dotfiles so the Void desktops
|
||||
# do not receive XDG autostart entries for applications they do not install.
|
||||
# Nextcloud desktop is the `nextcloud-client` package in fedora_desktop_packages;
|
||||
# this entry matches what the client itself writes when "Launch on startup" is on.
|
||||
desktop_gnome_dotfiles:
|
||||
- name: Nextcloud autostart entry
|
||||
src: .config/autostart/Nextcloud.desktop
|
||||
dest: .config/autostart/Nextcloud.desktop
|
||||
mode: "0644"
|
||||
|
||||
# Thunderbird is provisioned from a seeded profile plus a managed user.js:
|
||||
# Existing Thunderbird accounts are reused without changing their preferences.
|
||||
# Only a new profile receives account, calendar and address book defaults in user.js.
|
||||
# The address comes from Vault; the app-specific password is never stored here
|
||||
# and is requested by Thunderbird on first use.
|
||||
thunderbird_icloud_enabled: true
|
||||
thunderbird_profile_name: "{{ username }}"
|
||||
thunderbird_profile_dir: "{{ username }}.default-release"
|
||||
thunderbird_full_name: "{{ vault_personal_full_name | default(username) }}"
|
||||
thunderbird_icloud_email: "{{ vault_icloud_email }}"
|
||||
thunderbird_icloud_account_name: iCloud
|
||||
thunderbird_icloud_imap_host: imap.mail.me.com
|
||||
thunderbird_icloud_imap_port: 993
|
||||
thunderbird_icloud_smtp_host: smtp.mail.me.com
|
||||
thunderbird_icloud_smtp_port: 587
|
||||
thunderbird_icloud_caldav_url: https://caldav.icloud.com/
|
||||
thunderbird_icloud_carddav_url: https://contacts.icloud.com/
|
||||
thunderbird_icloud_calendar_id: 4f2c1d6e-9b3a-4f7c-8e21-6d5a0c9b7e13
|
||||
thunderbird_icloud_addressbook_uid: 9e0b7c4a-2d51-4a8f-b6c3-1f7d5e2a8b46
|
||||
|
||||
# Native VS Code; opt in to managing settings only after defining them.
|
||||
vscode_extensions:
|
||||
- esbenp.prettier-vscode
|
||||
- github.remotehub
|
||||
- ms-azuretools.vscode-containers
|
||||
# ms-azuretools.vscode-docker is deprecated: since June 2025 it is just an
|
||||
# extension pack wrapping Container Tools. Only the real extension is kept.
|
||||
- ms-vscode-remote.remote-containers
|
||||
- ms-vscode-remote.remote-ssh
|
||||
- ms-vscode-remote.remote-ssh-edit
|
||||
- ms-vscode-remote.remote-wsl
|
||||
- ms-vscode-remote.vscode-remote-extensionpack
|
||||
- ms-vscode.azure-repos
|
||||
- ms-vscode.remote-explorer
|
||||
- ms-vscode.remote-repositories
|
||||
- ms-vscode.remote-server
|
||||
- pkief.material-icon-theme
|
||||
- redhat.vscode-xml
|
||||
- redhat.vscode-yaml
|
||||
- saoudrizwan.claude-dev
|
||||
- vscodevim.vim
|
||||
# Managed user settings deploy as a full-file overlay with a timestamped backup;
|
||||
# any manual settings.json edit is converged away on the next run. These keys cover
|
||||
# the podman Dev Containers engine selection and the Container Tools clients.
|
||||
# editor.fontFamily uses the canonical 'JetBrainsMono Nerd Font' family name: the
|
||||
# live 'JetBriansMono NF' was a typo whose fallback chain rendered Liberation Mono.
|
||||
vscode_settings:
|
||||
containers.containerClient: com.microsoft.visualstudio.containers.podman
|
||||
containers.orchestratorClient: com.microsoft.visualstudio.orchestrators.podmancompose
|
||||
dev.containers.dockerPath: podman
|
||||
editor.cursorStyle: block
|
||||
editor.fontFamily: "'JetBrainsMono Nerd Font', 'Droid Sans Mono', monospace"
|
||||
editor.formatOnPaste: true
|
||||
workbench.iconTheme: material-icon-theme
|
||||
workbench.startupEditor: none
|
||||
# User-level keybindings apply to every window, including Dev Containers, SSH and WSL remotes.
|
||||
# Keys avoid Ctrl+<letter>, which the Vim extension uses for its motions; Alt is not bound by Vim.
|
||||
vscode_keybindings:
|
||||
- key: alt+j
|
||||
command: workbench.action.terminal.toggleTerminal
|
||||
when: "!terminalFocus"
|
||||
- key: alt+j
|
||||
command: workbench.action.togglePanel
|
||||
when: terminalFocus
|
||||
|
||||
@@ -8,7 +8,10 @@ fedora_packages_base:
|
||||
- htop
|
||||
- jq
|
||||
- make
|
||||
- nodejs
|
||||
# Keep the LTS stream explicit. Fedora 45's rolling `nodejs` package
|
||||
# conflicts with the nodejs22-bin alternative installed by the F44→F45
|
||||
# upgrade.
|
||||
- nodejs22
|
||||
- openssl
|
||||
- ripgrep
|
||||
|
||||
@@ -60,10 +63,54 @@ fedora_dev_packages:
|
||||
fedora_flatpak_remote_name: flathub
|
||||
fedora_flatpak_remote_url: https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
chatgpt_desktop_enabled: false
|
||||
cline_desktop_version: "0.0.49"
|
||||
# Launcher file shipped by the pinned RPM; the GNOME profile pins it in the
|
||||
# favorites while installation stays enabled.
|
||||
cline_desktop_launcher: Cline.desktop
|
||||
# Digests published with the official GitHub release; update with the version.
|
||||
cline_desktop_rpm_checksums:
|
||||
x86_64: sha256:e10036a036ee531451695559e2c96feceb3d621408a6615bdd708ffcf9e778ab
|
||||
aarch64: sha256:aec36edb594bdc400b0c2275230f29de6814a78ad60add4938347d20cfb93b74
|
||||
cline_desktop_rpm_url: >-
|
||||
https://github.com/cline/cline/releases/download/desktop-v{{ cline_desktop_version }}/Cline_{{ cline_desktop_version }}_{{ ansible_facts['architecture'] }}.rpm
|
||||
cline_desktop_rpm_path: "/var/cache/cline-desktop-{{ cline_desktop_version }}-{{ ansible_facts['architecture'] }}.rpm"
|
||||
|
||||
# OpenCode Desktop was replaced by Cline Desktop. The pinned release stays
|
||||
# available for reinstall, while removal is selected in the lifecycle flags
|
||||
# below so leftovers from the switch converge away on graphical hosts.
|
||||
opencode_desktop_version: "2.2.5"
|
||||
# Digests published with the official GitHub release; update with the version.
|
||||
opencode_desktop_rpm_checksums:
|
||||
x86_64: sha256:4feb27fe98df9b7579abd31a790d331e9aff87c95f67081beefa2aaaa76ebada
|
||||
aarch64: sha256:e84b1e03e2b4fb337ddfe015b6457a7aa0dfe171338be08e643ad66b1657033a
|
||||
opencode_desktop_rpm_url: >-
|
||||
https://github.com/anomalyco/opencode/releases/download/v{{ opencode_desktop_version }}/opencode-desktop-linux-{{ ansible_facts['architecture'] }}.rpm
|
||||
opencode_desktop_rpm_path: "/var/cache/opencode-desktop-{{ opencode_desktop_version }}-{{ ansible_facts['architecture'] }}.rpm"
|
||||
|
||||
# AI desktop-app lifecycle controls are independent for every app and mirror
|
||||
# the CLI coding-agent flags. Installation and removal are mutually exclusive
|
||||
# per app; the common pre-task enforces this before any changes are made.
|
||||
# ChatGPT opts in per host, Cline opts in through desktop_gnome group vars.
|
||||
chatgpt_desktop_install_enabled: false
|
||||
chatgpt_desktop_uninstall_enabled: false
|
||||
opencode_desktop_install_enabled: false
|
||||
opencode_desktop_uninstall_enabled: true
|
||||
|
||||
ai_desktop_apps:
|
||||
chatgpt_desktop:
|
||||
install_enabled: "{{ chatgpt_desktop_install_enabled }}"
|
||||
uninstall_enabled: "{{ chatgpt_desktop_uninstall_enabled }}"
|
||||
opencode_desktop:
|
||||
install_enabled: "{{ opencode_desktop_install_enabled }}"
|
||||
uninstall_enabled: "{{ opencode_desktop_uninstall_enabled }}"
|
||||
cline_desktop:
|
||||
install_enabled: "{{ cline_desktop_install_enabled | default(false) }}"
|
||||
uninstall_enabled: "{{ cline_desktop_uninstall_enabled | default(false) }}"
|
||||
|
||||
chatgpt_desktop_supported_fedora_versions:
|
||||
- "43"
|
||||
- "44"
|
||||
- "45"
|
||||
chatgpt_desktop_supported_architectures:
|
||||
- x86_64
|
||||
- aarch64
|
||||
|
||||
@@ -183,7 +183,7 @@ profile_packages:
|
||||
- deluge-gtk
|
||||
- delve
|
||||
- dnsmasq
|
||||
- evolution
|
||||
- thunderbird
|
||||
- poppler-glib
|
||||
- poppler-utils
|
||||
- fontconfig-devel
|
||||
@@ -224,5 +224,8 @@ profile_packages:
|
||||
- yaru-plus
|
||||
- zstd
|
||||
|
||||
void_removed_packages:
|
||||
- evolution
|
||||
|
||||
profile_emacs_packages:
|
||||
- emacs-pgtk
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
---
|
||||
emacs_enabled: true
|
||||
|
||||
workstation_git_https_cas:
|
||||
- url: https://gitlab.ecaas.datacenter.comune.roma
|
||||
certificate: ecaas.datacenter.comune.roma.crt
|
||||
- url: https://gitlab.datacenter.comune.roma
|
||||
certificate: datacenter.comune.roma.crt
|
||||
|
||||
workstation_user_directories:
|
||||
- path: "{{ user_home }}/.config"
|
||||
mode: "0755"
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
---
|
||||
# Claude Code is managed only on the Fedora WSL development profile.
|
||||
claude_code_install_enabled: true
|
||||
claude_code_uninstall_enabled: false
|
||||
|
||||
enabled_services:
|
||||
- docker
|
||||
|
||||
@@ -7,26 +11,17 @@ workstation_dev_wsl_packages:
|
||||
- helm
|
||||
# Fedora ships the kubectl client binary in the kubernetes-client package.
|
||||
- kubernetes-client
|
||||
- mise
|
||||
- pinentry-curses
|
||||
- python3-pip
|
||||
- tmux
|
||||
|
||||
# Java 11, Java 25 and Maven are managed by Mise on this Fedora WSL profile.
|
||||
# Keep their versions pinned; update them deliberately.
|
||||
workstation_mise_java_version: temurin-11.0.31+11
|
||||
workstation_mise_java_25_version: 25.0.2
|
||||
workstation_mise_maven_version: 3.9.16
|
||||
# Maven version pinned in the devcontainer images; update it deliberately.
|
||||
workstation_maven_version: 3.9.16
|
||||
workstation_cdp_node_version: 20.18.3
|
||||
|
||||
workstation_is_wsl: true
|
||||
workstation_wsl_systemd_enabled: true
|
||||
workstation_dev_wsl_dotfiles:
|
||||
- src: .bashrc.d/30-mise.sh
|
||||
dest: .bashrc.d/30-mise.sh
|
||||
mode: "0644"
|
||||
- src: .config/mise/
|
||||
dest: .config/mise/
|
||||
mode: preserve
|
||||
- src: .gnupg/gpg-agent.conf
|
||||
dest: .gnupg/gpg-agent.conf
|
||||
mode: "0600"
|
||||
|
||||
@@ -72,7 +72,9 @@ atlas_nextcloud_external_mounts:
|
||||
source: /zpool/archive/Documents
|
||||
target: /mnt/archive-documents
|
||||
readonly: false
|
||||
- name: Foto iCloud
|
||||
# Expose the iCloudPD originals directly in Fabio's canonical Photos folder.
|
||||
# This remains a read-only external mount; iCloudPD is the sole writer.
|
||||
- name: Photos
|
||||
user: fabio
|
||||
source: /zpool/archive/Pictures/iCloudPD
|
||||
target: /mnt/archive-icloud
|
||||
@@ -95,6 +97,17 @@ atlas_nextcloud_apps:
|
||||
url: https://github.com/nextcloud-releases/calendar/releases/download/v6.6.2/calendar-v6.6.2.tar.gz
|
||||
checksum: sha256:7e83632d4436d3037a34d1c73cbc06d5ccb6e8fc10f096a86a43a0515588529c
|
||||
# Rootless Gitea was restored from the stopped-source export before production activation.
|
||||
# Paperless runs rootless on dedicated ZFS datasets; NPM remains on Prometheus.
|
||||
atlas_manage_paperless: true
|
||||
atlas_paperless_domain: documents.fscotto.co
|
||||
# Resolved official amd64 images on 2026-10-12; upgrades remain deliberate.
|
||||
atlas_paperless_image: ghcr.io/paperless-ngx/paperless-ngx:3.2.1@sha256:5fa76604a81df6945086e0837b14b56543d137e8ce4f311cc5d9ebe907e74e79
|
||||
atlas_paperless_postgres_image: docker.io/library/postgres:17-bookworm@sha256:3645570cccdfa447589da9f57dd740faa29b30938e861289a5574b6ca6b03826
|
||||
atlas_paperless_valkey_image: docker.io/valkey/valkey:8-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571
|
||||
atlas_paperless_tika_image: docker.io/apache/tika:3.3.1.0@sha256:90b7fa1dc018434075fce9e1d9b88b1e3d0ea6979d0cf86e116c79a8073ae973
|
||||
atlas_paperless_gotenberg_image: docker.io/gotenberg/gotenberg:8.37@sha256:f29984bd1e226bf1b93ba90af06000afa8b315853e99d27b9aaa41b93f15c769
|
||||
atlas_paperless_ollama_image: docker.io/ollama/ollama:0.40.3@sha256:adca95a12c2b386a8f9a995e7fa0600e187e3323b5e5522f5a6c3b1ec73eff99
|
||||
|
||||
atlas_manage_gitea: true
|
||||
atlas_gitea_production_enabled: true
|
||||
atlas_gitea_public_domain: git.fscotto.co
|
||||
@@ -257,3 +270,16 @@ host_enabled_services:
|
||||
- cockpit.socket
|
||||
- pmlogger.service
|
||||
- zfs.target
|
||||
|
||||
# Torrent Web UI: LAN and the existing Aegis gateway for the manual NPM proxy.
|
||||
atlas_manage_qbittorrent: true
|
||||
atlas_qbittorrent_image: docker.io/qbittorrentofficial/qbittorrent-nox@sha256:92bfd78d731e254ba64f62b77b0696add6447a33642ee5feda106a26b285aa7f
|
||||
atlas_qbittorrent_reverse_proxy_enabled: true
|
||||
atlas_qbittorrent_public_domain: torrent.fscotto.co
|
||||
|
||||
# LAN-only HTTP downloader; RPC secret is generated and retained privately on Atlas.
|
||||
atlas_manage_aria2: true
|
||||
atlas_aria2_gateway_enabled: true
|
||||
atlas_aria2_public_domain: downloads.fscotto.co
|
||||
atlas_aria2_image: docker.io/p3terx/aria2-pro@sha256:086d1a37c586edb07ec0fb956bf9edd89d1d38d138ad5309ff96d510c8c9a011
|
||||
atlas_ariang_image: docker.io/p3terx/ariang@sha256:73849cf75fe9f959229222622e887310df505cbf868eb9c735e2af376523c010
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
---
|
||||
hostname: deadalus
|
||||
workstation_wsl_windows_user_home: /mnt/c/Users/FABIOSCOTTODISANTOLO
|
||||
workstation_ecaas_workspace: "{{ user_home }}/Work/sipo/ecaas"
|
||||
workstation_cdp_workspace: "{{ user_home }}/Work/sipo/cdp"
|
||||
workstation_ecaas_git_required_ca: ecaas.datacenter.comune.roma.crt
|
||||
|
||||
# Claude Code, Codex and the Cline CLI are the coding agents installed on WSL; every
|
||||
# other managed agent is disabled. Cline's cross-tool instructions (.agents/AGENTS.md,
|
||||
# .cline/rules/) and the shared ~/.config/ai context are deployed for the ecaas/cdp
|
||||
# devcontainers, and the cline npm package is installed by profile_workstation_dev_common.
|
||||
claude_code_install_enabled: true
|
||||
claude_code_uninstall_enabled: false
|
||||
opencode_install_enabled: false
|
||||
opencode_deploy_enabled: false
|
||||
opencode_uninstall_enabled: true
|
||||
codex_install_enabled: true
|
||||
codex_deploy_enabled: false
|
||||
codex_uninstall_enabled: false
|
||||
gemini_cli_install_enabled: false
|
||||
gemini_cli_deploy_enabled: false
|
||||
gemini_cli_uninstall_enabled: true
|
||||
cline_install_enabled: true
|
||||
cline_deploy_enabled: true
|
||||
cline_uninstall_enabled: false
|
||||
ibm_bob_install_enabled: false
|
||||
ibm_bob_uninstall_enabled: true
|
||||
|
||||
host_packages: []
|
||||
host_enabled_services: []
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
---
|
||||
hostname: ikaros
|
||||
|
||||
codex_relay_install_enabled: true
|
||||
chatgpt_desktop_enabled: true
|
||||
codex_relay_install_enabled: false
|
||||
codex_relay_uninstall_enabled: true
|
||||
gemini_cli_install_enabled: false
|
||||
gemini_cli_deploy_enabled: false
|
||||
gemini_cli_uninstall_enabled: true
|
||||
chatgpt_desktop_install_enabled: true
|
||||
desktop_ai_media_enabled: true
|
||||
desktop_ai_media_external_storage_enabled: true
|
||||
desktop_ai_media_external_luks_uuid: 6948c504-2d60-4cc8-9e7f-3ccdf28e80d7
|
||||
desktop_ai_media_external_mountpoint: /run/media/fscotto/Backup
|
||||
desktop_ai_media_external_source: /run/media/fscotto/Backup/ai-media
|
||||
|
||||
host_packages:
|
||||
- podman
|
||||
- openssh-clients
|
||||
- openssh-server
|
||||
- mesa-vulkan-drivers
|
||||
@@ -141,7 +151,7 @@ gnome_gsettings_settings:
|
||||
value: "'file:///usr/share/backgrounds/gnome/morphogenesis-l.svg'"
|
||||
- schema: org.gnome.desktop.search-providers
|
||||
key: sort-order
|
||||
value: "['org.gnome.Settings.desktop', 'org.gnome.Contacts.desktop', 'org.gnome.Nautilus.desktop']"
|
||||
value: "['org.gnome.Settings.desktop', 'org.gnome.Contacts.desktop', 'org.gnome.Nautilus.desktop', 'org.mozilla.firefox.desktop', 'org.gnome.seahorse.Application.desktop', 'org.gnome.Calculator.desktop', 'org.gnome.Calendar.desktop', 'org.gnome.Software.desktop', 'org.gnome.Characters.desktop', 'org.gnome.Boxes.desktop', 'org.gnome.clocks.desktop', 'com.mattjakeman.ExtensionManager.desktop']"
|
||||
- schema: org.gnome.desktop.wm.keybindings
|
||||
key: switch-to-workspace-1
|
||||
value: "['<Super>1']"
|
||||
@@ -204,7 +214,7 @@ gnome_gsettings_settings:
|
||||
value: "false"
|
||||
- schema: org.gnome.nautilus.preferences
|
||||
key: default-folder-viewer
|
||||
value: "'list-view'"
|
||||
value: "'icon-view'"
|
||||
- schema: org.gnome.nautilus.preferences
|
||||
key: show-create-link
|
||||
value: "true"
|
||||
@@ -232,19 +242,19 @@ gnome_gsettings_settings:
|
||||
- schema: org.gnome.shell
|
||||
key: app-picker-layout
|
||||
value: >-
|
||||
[{'System': <{'position': <0>}>, 'Utilities': <{'position': <1>}>, 'org.fedoraproject.MediaWriter.desktop': <{'position': <2>}>, 'org.gnome.Contacts.desktop': <{'position': <3>}>, 'org.gnome.Calendar.desktop': <{'position': <4>}>, 'org.gnome.Calculator.desktop': <{'position': <5>}>, 'org.gnome.Weather.desktop': <{'position': <6>}>, 'org.gnome.clocks.desktop': <{'position': <7>}>, 'org.gnome.Maps.desktop': <{'position': <8>}>, 'org.gnome.SimpleScan.desktop': <{'position': <9>}>, 'org.gnome.TextEditor.desktop': <{'position': <10>}>, 'org.gnome.Settings.desktop': <{'position': <11>}>, 'org.gnome.Boxes.desktop': <{'position': <12>}>, 'org.gnome.Showtime.desktop': <{'position': <13>}>, 'org.gnome.Snapshot.desktop': <{'position': <14>}>, 'org.gnome.Characters.desktop': <{'position': <15>}>, 'org.gnome.Tour.desktop': <{'position': <16>}>, 'org.gnome.Yelp.desktop': <{'position': <17>}>, 'org.gnome.Software.desktop': <{'position': <18>}>, 'be.alexandervanhee.gradia.desktop': <{'position': <19>}>, 'com.github.jeromerobert.pdfarranger.desktop': <{'position': <20>}>, 'org.onlyoffice.desktopeditors.desktop': <{'position': <21>}>, 'org.gnome.Meld.desktop': <{'position': <22>}>, 'com.mattjakeman.ExtensionManager.desktop': <{'position': <23>}>}, {'org.remmina.Remmina.desktop': <{'position': <0>}>, 'ch.protonmail.protonmail-bridge.desktop': <{'position': <1>}>, 'syncthing-start.desktop': <{'position': <2>}>, 'syncthing-ui.desktop': <{'position': <3>}>, 'emacs.desktop': <{'position': <4>}>, 'emacs-client.desktop': <{'position': <5>}>, 'org.gnome.gitlab.somas.Apostrophe.desktop': <{'position': <6>}>, 'mpv.desktop': <{'position': <7>}>, 'htop.desktop': <{'position': <8>}>, 'com.raspberrypi.rpi-imager.desktop': <{'position': <9>}>}]
|
||||
[{'System': <{'position': <0>}>, 'Utilities': <{'position': <1>}>, 'org.fedoraproject.MediaWriter.desktop': <{'position': <2>}>, 'org.gnome.Contacts.desktop': <{'position': <3>}>, 'org.gnome.Calendar.desktop': <{'position': <4>}>, 'org.gnome.Calculator.desktop': <{'position': <5>}>, 'org.gnome.Weather.desktop': <{'position': <6>}>, 'org.gnome.clocks.desktop': <{'position': <7>}>, 'org.gnome.Maps.desktop': <{'position': <8>}>, 'org.gnome.SimpleScan.desktop': <{'position': <9>}>, 'org.gnome.TextEditor.desktop': <{'position': <10>}>, 'org.gnome.Settings.desktop': <{'position': <11>}>, 'org.gnome.Boxes.desktop': <{'position': <12>}>, 'org.gnome.Showtime.desktop': <{'position': <13>}>, 'org.gnome.Snapshot.desktop': <{'position': <14>}>, 'org.gnome.Characters.desktop': <{'position': <15>}>, 'org.gnome.Tour.desktop': <{'position': <16>}>, 'org.gnome.Yelp.desktop': <{'position': <17>}>, 'org.gnome.Software.desktop': <{'position': <18>}>, 'be.alexandervanhee.gradia.desktop': <{'position': <19>}>, 'com.github.jeromerobert.pdfarranger.desktop': <{'position': <20>}>, 'org.onlyoffice.desktopeditors.desktop': <{'position': <21>}>, 'org.gnome.Meld.desktop': <{'position': <22>}>, 'com.mattjakeman.ExtensionManager.desktop': <{'position': <23>}>}, {'com.raspberrypi.rpi-imager.desktop': <{'position': <0>}>, 'org.remmina.Remmina.desktop': <{'position': <1>}>, 'com.nextcloud.desktopclient.nextcloud.desktop': <{'position': <2>}>, 'syncthing-start.desktop': <{'position': <3>}>, 'syncthing-ui.desktop': <{'position': <4>}>, 'emacs.desktop': <{'position': <5>}>, 'emacs-client.desktop': <{'position': <6>}>, 'chatgpt.desktop': <{'position': <7>}>, 'org.gnome.gitlab.somas.Apostrophe.desktop': <{'position': <8>}>, 'mpv.desktop': <{'position': <9>}>, 'htop.desktop': <{'position': <10>}>, 'ai-media-facefusion.desktop': <{'position': <11>}>, 'ai-media-rvc.desktop': <{'position': <12>}>}]
|
||||
- schema: org.gnome.shell
|
||||
key: disabled-extensions
|
||||
value: >-
|
||||
['window-list@gnome-shell-extensions.gcampax.github.com', 'background-logo@fedorahosted.org', 'apps-menu@gnome-shell-extensions.gcampax.github.com', 'places-menu@gnome-shell-extensions.gcampax.github.com']
|
||||
['window-list@gnome-shell-extensions.gcampax.github.com', 'background-logo@fedorahosted.org', 'apps-menu@gnome-shell-extensions.gcampax.github.com', 'places-menu@gnome-shell-extensions.gcampax.github.com', 'maximize-new-windows@VitalyOstanin']
|
||||
- schema: org.gnome.shell
|
||||
key: enabled-extensions
|
||||
value: >-
|
||||
['status-icons@gnome-shell-extensions.gcampax.github.com', 'gnome-ui-tune@itstime.tech', 'appindicatorsupport@rgcjonas.gmail.com', 'bluetooth-battery-monitor@v8v88v8v88.com', 'clipboard-indicator@tudmotu.com', 'status-area-horizontal-spacing@mathematical.coffee.gmail.com', 'MaximizeWindowIntoNewWorkspace@kyleross.com', 'maximize-new-windows@VitalyOstanin']
|
||||
['status-icons@gnome-shell-extensions.gcampax.github.com', 'gnome-ui-tune@itstime.tech', 'appindicatorsupport@rgcjonas.gmail.com', 'bluetooth-battery-monitor@v8v88v8v88.com', 'clipboard-indicator@tudmotu.com', 'status-area-horizontal-spacing@mathematical.coffee.gmail.com', 'MaximizeWindowIntoNewWorkspace@kyleross.com', 'gnome-shell-extension-maximized-by-default@stiggimy.github.com']
|
||||
- schema: org.gnome.shell
|
||||
key: favorite-apps
|
||||
value: >-
|
||||
['org.gnome.Nautilus.desktop', 'org.mozilla.firefox.desktop', 'com.spotify.Client.desktop', 'org.gnome.Evolution.desktop', 'org.telegram.desktop.desktop', 'chatgpt.desktop', 'org.gnome.Ptyxis.desktop', 'virt-manager.desktop']
|
||||
['org.gnome.Nautilus.desktop', 'org.mozilla.firefox.desktop', 'com.spotify.Client.desktop', 'net.thunderbird.Thunderbird.desktop', 'org.telegram.desktop.desktop', 'Cline.desktop', 'org.desktop_plus.desktop-plus.desktop', 'com.microsoft.VSCode.desktop', 'org.gnome.Ptyxis.desktop', 'virt-manager.desktop']
|
||||
- schema: org.gnome.shell
|
||||
key: remember-mount-password
|
||||
value: "true"
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
---
|
||||
hostname: nymph
|
||||
|
||||
chatgpt_desktop_enabled: true
|
||||
codex_relay_install_enabled: false
|
||||
codex_relay_uninstall_enabled: true
|
||||
gemini_cli_install_enabled: false
|
||||
gemini_cli_deploy_enabled: false
|
||||
gemini_cli_uninstall_enabled: true
|
||||
|
||||
chatgpt_desktop_install_enabled: true
|
||||
|
||||
# Fedora Workstation/GNOME laptop target. GNOME is provided by the base Fedora
|
||||
# Workstation install; Ansible deploys shared desktop dotfiles but leaves GNOME
|
||||
|
||||
14
ansible/roles/desktop_ai_media/defaults/main.yml
Normal file
14
ansible/roles/desktop_ai_media/defaults/main.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
desktop_ai_media_enabled: false
|
||||
desktop_ai_media_root: "{{ user_home }}/.local/share/ai-media"
|
||||
desktop_ai_media_build_root: "{{ user_home }}/.local/share/ai-media-build"
|
||||
desktop_ai_media_external_storage_enabled: false
|
||||
desktop_ai_media_external_luks_uuid: ""
|
||||
desktop_ai_media_external_mountpoint: ""
|
||||
desktop_ai_media_external_source: ""
|
||||
desktop_ai_media_debian_snapshot: "20261013T000000Z"
|
||||
desktop_ai_media_base_image: >-
|
||||
docker.io/library/python@sha256:34386ef0cb081344d7ec1c103ba398e6e9f64e9ab3a1509accc92a4e24a07258
|
||||
desktop_ai_media_facefusion_revision: 72470819a0373be3388b3929c8f8f311f418fc3c
|
||||
desktop_ai_media_rvc_revision: 81eed5e8f68b6bed1789f682fe78cdd324495afc
|
||||
desktop_ai_media_apps: [facefusion, rvc]
|
||||
56
ansible/roles/desktop_ai_media/files/check_storage.py
Normal file
56
ansible/roles/desktop_ai_media/files/check_storage.py
Normal file
@@ -0,0 +1,56 @@
|
||||
import configparser
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
root = pathlib.Path(sys.argv[1]).resolve()
|
||||
home = pathlib.Path.home()
|
||||
local_filesystems = {
|
||||
"btrfs", "ext2", "ext3", "ext4", "xfs", "zfs", "tmpfs", "overlay",
|
||||
"ramfs", "ntfs3", "vfat", "exfat",
|
||||
}
|
||||
mounts = []
|
||||
for line in pathlib.Path("/proc/self/mountinfo").read_text().splitlines():
|
||||
fields, description = line.split(" - ", 1)
|
||||
mount = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields.split()[4])
|
||||
mounts.append((pathlib.Path(mount), description.split()[0]))
|
||||
automount_at_root = any(p == root and kind == "autofs" for p, kind in mounts)
|
||||
backing_mount_at_root = any(
|
||||
p == root and kind != "autofs" for p, kind in mounts
|
||||
)
|
||||
if automount_at_root and not backing_mount_at_root:
|
||||
raise SystemExit("Media storage is not mounted; refusing to start")
|
||||
covering = [
|
||||
(p, kind) for p, kind in mounts
|
||||
if kind != "autofs" and (root == p or root.is_relative_to(p))
|
||||
]
|
||||
if covering:
|
||||
selected = max(covering, key=lambda entry: len(entry[0].parts))
|
||||
if selected[1] not in local_filesystems:
|
||||
raise SystemExit("Media storage is not on a local filesystem; refusing to start")
|
||||
for mount, kind in mounts:
|
||||
if mount == root and kind == "autofs":
|
||||
continue
|
||||
if mount.is_relative_to(root) and kind not in local_filesystems:
|
||||
raise SystemExit("Non-local mount beneath media storage; refusing to start")
|
||||
sync_roots = []
|
||||
nextcloud = home / ".config/Nextcloud/nextcloud.cfg"
|
||||
if nextcloud.exists():
|
||||
configuration = configparser.ConfigParser(interpolation=None, strict=False)
|
||||
configuration.read(nextcloud)
|
||||
for section in configuration.sections():
|
||||
for key, value in configuration.items(section):
|
||||
if key.lower().endswith("localpath"):
|
||||
sync_roots.append(pathlib.Path(value).expanduser().resolve())
|
||||
for configuration in (
|
||||
home / ".config/syncthing/config.xml",
|
||||
home / ".local/state/syncthing/config.xml",
|
||||
):
|
||||
if configuration.exists():
|
||||
for folder in ET.parse(configuration).getroot().findall("folder"):
|
||||
if folder.get("path"):
|
||||
sync_roots.append(pathlib.Path(folder.get("path")).expanduser().resolve())
|
||||
for path in sync_roots:
|
||||
if root == path or root.is_relative_to(path) or path.is_relative_to(root):
|
||||
raise SystemExit("Media storage overlaps a Nextcloud/Syncthing folder; refusing to start")
|
||||
88
ansible/roles/desktop_ai_media/files/prepare.py
Normal file
88
ansible/roles/desktop_ai_media/files/prepare.py
Normal file
@@ -0,0 +1,88 @@
|
||||
import hashlib
|
||||
import pathlib
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
app = sys.argv[1]
|
||||
root = pathlib.Path("/opt/app")
|
||||
if app == "facefusion":
|
||||
sys.path.insert(0, str(root))
|
||||
from facefusion import state_manager
|
||||
from facefusion.args import apply_args
|
||||
from facefusion.program import create_program
|
||||
from facefusion.core import common_pre_check, processors_pre_check
|
||||
|
||||
args = vars(create_program().parse_args([
|
||||
"run", "--execution-providers", "cpu",
|
||||
"--processors", "face_swapper",
|
||||
]))
|
||||
apply_args(args, state_manager.init_item)
|
||||
if not common_pre_check() or not processors_pre_check():
|
||||
raise RuntimeError("FaceFusion model preparation failed")
|
||||
else:
|
||||
for relative in (
|
||||
"hubert_base/config.json",
|
||||
"hubert_base/preprocessor_config.json",
|
||||
"hubert_base/pytorch_model.bin",
|
||||
"rmvpe.pt",
|
||||
):
|
||||
destination = root / "assets" / relative
|
||||
if relative == "rmvpe.pt":
|
||||
destination = root / "assets/rmvpe/rmvpe.pt"
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not destination.is_file():
|
||||
raise FileNotFoundError("Missing checksum-pinned public model: " + str(destination))
|
||||
for directory in ("weights", "indices", "pretrained", "pretrained_v2", "pymss_weights"):
|
||||
(root / "assets" / directory).mkdir(parents=True, exist_ok=True)
|
||||
# Mutable working data stays outside the immutable application tree.
|
||||
for name, destination in (
|
||||
("TEMP", "/tmp/rvc-temp"),
|
||||
("assets/weights", "/work/state/weights"),
|
||||
("logs", "/work/state"),
|
||||
):
|
||||
path = root / name
|
||||
if path.exists():
|
||||
import shutil
|
||||
shutil.rmtree(path)
|
||||
path.symlink_to(destination)
|
||||
|
||||
# Expose only separation models that are actually baked into this image.
|
||||
separation = root / "tools/pymss_webui.py"
|
||||
original = "PYMSS_MODEL_CHOICES = [spec.label for spec in MODEL_SPECS]"
|
||||
replacement = """PYMSS_MODEL_CHOICES = [
|
||||
spec.label for spec in MODEL_SPECS
|
||||
if (weight_pymss_root / spec.model_file).is_file()
|
||||
and (weight_pymss_root / spec.config_file).is_file()
|
||||
]"""
|
||||
code = separation.read_text()
|
||||
if code.count(original) != 1:
|
||||
raise RuntimeError("Pinned RVC separation model selector has changed")
|
||||
separation.write_text(code.replace(original, replacement))
|
||||
webui = root / "webui.py"
|
||||
code = webui.read_text()
|
||||
for label, destination in (
|
||||
("主结果文件夹", "/work/output/vocals"),
|
||||
("分离残余文件夹", "/work/output/instrumental"),
|
||||
):
|
||||
original = 'label=i18n("' + label + '"), value="opt"'
|
||||
if code.count(original) != 1:
|
||||
raise RuntimeError("Pinned RVC separation output selector has changed")
|
||||
code = code.replace(original, 'label=i18n("' + label + '"), value="' + destination + '"')
|
||||
webui.write_text(code)
|
||||
|
||||
# Bake only the public silence fixture; personal datasets never enter the build.
|
||||
with zipfile.ZipFile(root / "assets/mute.zip") as archive:
|
||||
destination = pathlib.Path("/opt/training-fixture")
|
||||
for entry in archive.infolist():
|
||||
target = (destination / entry.filename).resolve()
|
||||
if not target.is_relative_to(destination):
|
||||
raise ValueError("Invalid public silence archive member")
|
||||
archive.extractall(destination)
|
||||
|
||||
with open("/opt/model-checksums.sha256", "w") as manifest:
|
||||
for directory in (root / ".assets", root / "assets"):
|
||||
if directory.exists():
|
||||
for path in sorted(directory.rglob("*")):
|
||||
if path.is_file():
|
||||
digest = hashlib.file_digest(path.open("rb"), "sha256").hexdigest()
|
||||
manifest.write(digest + " " + str(path) + "\n")
|
||||
384
ansible/roles/desktop_ai_media/files/preset.py
Normal file
384
ansible/roles/desktop_ai_media/files/preset.py
Normal file
@@ -0,0 +1,384 @@
|
||||
"""Small host-side orchestrator for offline ai-media presets."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
|
||||
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
|
||||
SOURCE_NAMES = tuple(f"source{number}.jpg" for number in range(11, 19))
|
||||
|
||||
|
||||
def video_url(value):
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password:
|
||||
raise ValueError("Use an HTTP(S) video URL without embedded credentials")
|
||||
host = parsed.hostname.lower().rstrip(".")
|
||||
if host == "localhost" or host.endswith(".localhost"):
|
||||
raise ValueError("Local URLs are not accepted")
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
if not address.is_global:
|
||||
raise ValueError("Private or local IP URLs are not accepted")
|
||||
return value
|
||||
|
||||
|
||||
def media_file(root, name, *, video=False):
|
||||
if not NAME.fullmatch(name) or name in (".", ".."):
|
||||
raise ValueError("Use a simple filename in the ai-media input directory")
|
||||
path = root / "input" / name
|
||||
if not path.is_file() or path.is_symlink():
|
||||
raise FileNotFoundError(path)
|
||||
if video and path.suffix.lower() != ".mp4":
|
||||
raise ValueError("The video must be an MP4 file")
|
||||
return path
|
||||
|
||||
|
||||
def audio_file(root, name):
|
||||
if not name or any(not NAME.fullmatch(part) or part in (".", "..")
|
||||
for part in name.split("/")):
|
||||
raise ValueError("Use an audio path relative to input/ or output/ without traversal")
|
||||
matches = [root / directory / name for directory in ("input", "output")]
|
||||
matches = [path for path in matches if path.is_file() and path.resolve() == path]
|
||||
if len(matches) != 1:
|
||||
raise ValueError("Audio must exist in exactly one of input/ or output/")
|
||||
return matches[0]
|
||||
|
||||
|
||||
def container_path(root, path):
|
||||
directory = path.relative_to(root).parts[0]
|
||||
if directory not in ("input", "output"):
|
||||
raise ValueError("Media path outside input/output")
|
||||
return "/work/" + str(path.relative_to(root))
|
||||
|
||||
|
||||
def run(*command):
|
||||
print("+", " ".join(map(str, command)), flush=True)
|
||||
subprocess.run([str(part) for part in command], check=True)
|
||||
|
||||
|
||||
def has_stream(path, kind):
|
||||
result = subprocess.run([
|
||||
"ffprobe", "-v", "error", "-show_entries", "stream=codec_type",
|
||||
"-of", "json", str(path),
|
||||
], check=True, capture_output=True, text=True)
|
||||
return kind in [stream["codec_type"] for stream in json.loads(result.stdout)["streams"]]
|
||||
|
||||
|
||||
def probe(path, kind):
|
||||
if not has_stream(path, kind):
|
||||
raise RuntimeError(f"Missing {kind} stream: {path}")
|
||||
|
||||
|
||||
def duration(path):
|
||||
result = subprocess.run([
|
||||
"ffprobe", "-v", "error", "-show_entries", "format=duration",
|
||||
"-of", "default=noprint_wrappers=1:nokey=1", str(path),
|
||||
], check=True, capture_output=True, text=True)
|
||||
return float(result.stdout.strip())
|
||||
|
||||
|
||||
def output_path(root, video, suffix, extension="mp4"):
|
||||
return root / "output" / f"{video.stem}-{suffix}.{extension}"
|
||||
|
||||
|
||||
def mix_target(root, args):
|
||||
name = args.output or f"{Path(args.vocals).stem}-mix.wav"
|
||||
return wav_target(root, name)
|
||||
|
||||
|
||||
def wav_target(root, name):
|
||||
if not NAME.fullmatch(name) or Path(name).suffix.lower() != ".wav":
|
||||
raise ValueError("Use a simple WAV output filename")
|
||||
target = root / "output" / name
|
||||
if target.exists() or target.is_symlink():
|
||||
raise FileExistsError(target)
|
||||
return target
|
||||
|
||||
|
||||
def process_voice(args, root, launcher):
|
||||
source = audio_file(root, args.audio)
|
||||
probe(source, "audio")
|
||||
target = wav_target(root, args.output or f"{source.stem}-mia_voce.wav")
|
||||
job = root / "output" / f".{source.stem}-voice-convert-{args.job_id}"
|
||||
job.mkdir(mode=0o700)
|
||||
print("Working directory:", job, flush=True)
|
||||
prepared = job / "audio.wav"
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, source), "-map", "0:a:0", "-vn",
|
||||
"-c:a", "pcm_s16le", container_path(root, prepared))
|
||||
run(launcher, "rvc", "cli", container_path(root, prepared),
|
||||
container_path(root, job), "--convert-only")
|
||||
converted = job / "vocals-mia_voce.wav"
|
||||
probe(converted, "audio")
|
||||
os.link(converted, target)
|
||||
return target
|
||||
|
||||
|
||||
def process_mix(args, root, launcher):
|
||||
vocals = audio_file(root, args.vocals)
|
||||
instrumental = audio_file(root, args.instrumental)
|
||||
target = mix_target(root, args)
|
||||
for source in (vocals, instrumental):
|
||||
probe(source, "audio")
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, vocals), "-i", container_path(root, instrumental),
|
||||
"-filter_complex", "[0:a][1:a]amix=inputs=2:duration=longest:normalize=0[a]",
|
||||
"-map", "[a]", "-c:a", "pcm_s16le", container_path(root, target))
|
||||
probe(target, "audio")
|
||||
return target
|
||||
|
||||
|
||||
def mux(launcher, root, video, audio, target):
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, video), "-i", container_path(root, audio),
|
||||
"-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac",
|
||||
"-b:a", "192k", "-shortest", "-movflags", "+faststart",
|
||||
container_path(root, target))
|
||||
probe(target, "video")
|
||||
probe(target, "audio")
|
||||
|
||||
|
||||
def download_video(root, url, job_id):
|
||||
video_url(url)
|
||||
if not job_id or not NAME.fullmatch(job_id):
|
||||
raise ValueError("Invalid job ID")
|
||||
if shutil.which("yt-dlp") is None:
|
||||
raise RuntimeError("yt-dlp is required for URL downloads")
|
||||
prefix = f"download-{job_id}"
|
||||
destination = root / "input" / f"{prefix}.mp4"
|
||||
if list((root / "input").glob(prefix + ".*")):
|
||||
raise FileExistsError(destination)
|
||||
print("Downloading one video into input/ with yt-dlp", flush=True)
|
||||
subprocess.run([
|
||||
"yt-dlp", "--ignore-config", "--no-playlist", "--no-overwrites",
|
||||
"--no-progress", "-t", "mp4", "--recode-video", "mp4",
|
||||
"--output", str(root / "input" / f"{prefix}.%(ext)s"), url,
|
||||
], check=True)
|
||||
if not destination.is_file() or destination.is_symlink():
|
||||
raise RuntimeError("yt-dlp did not produce the expected MP4 in input/")
|
||||
probe(destination, "video")
|
||||
return destination
|
||||
|
||||
|
||||
def process_split(args, root, launcher, video):
|
||||
probe(video, "audio")
|
||||
target = root / "output" / f"{video.stem}-{args.preset}"
|
||||
if target.exists():
|
||||
raise FileExistsError(target)
|
||||
job = root / "output" / f".{video.stem}-{args.preset}-{args.job_id}"
|
||||
job.mkdir(mode=0o700)
|
||||
print("Working directory:", job, flush=True)
|
||||
silent = job / "video.mp4"
|
||||
audio = job / "audio.wav"
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, video), "-map", "0:v:0", "-c:v", "copy",
|
||||
"-an", "-movflags", "+faststart", container_path(root, silent))
|
||||
probe(silent, "video")
|
||||
if has_stream(silent, "audio"):
|
||||
raise RuntimeError("Unexpected audio stream in split video")
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, video), "-map", "0:a:0", "-vn",
|
||||
"-c:a", "pcm_s16le", container_path(root, audio))
|
||||
probe(audio, "audio")
|
||||
files = {"video.mp4": silent, "audio.wav": audio}
|
||||
if args.preset == "split-stems":
|
||||
run(launcher, "rvc", "cli", container_path(root, audio),
|
||||
container_path(root, job), "--separate-only")
|
||||
for stem in ("vocals", "instrumental"):
|
||||
matches = list((job / stem).glob("*.wav"))
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError(f"Expected exactly one {stem} stem")
|
||||
probe(matches[0], "audio")
|
||||
files[f"{stem}.wav"] = matches[0]
|
||||
# Publish only after every processing step and stream check succeeded.
|
||||
target.mkdir(mode=0o700)
|
||||
for name, source in files.items():
|
||||
os.link(source, target / name)
|
||||
return target
|
||||
|
||||
|
||||
def process(args, root, launcher):
|
||||
video = media_file(root, args.video, video=True)
|
||||
probe(video, "video")
|
||||
if args.preset in ("split", "split-stems"):
|
||||
return process_split(args, root, launcher, video)
|
||||
if args.preset == "merge":
|
||||
audio = audio_file(root, args.audio)
|
||||
probe(audio, "audio")
|
||||
target = output_path(root, video, "unito")
|
||||
if target.exists():
|
||||
raise FileExistsError(target)
|
||||
mux(launcher, root, video, audio, target)
|
||||
return target
|
||||
|
||||
suffix = "mia_voce" if args.preset == "audio-convert" else "facefusion"
|
||||
target = output_path(root, video, suffix, "wav" if args.preset == "audio-convert" else "mp4")
|
||||
if target.exists():
|
||||
raise FileExistsError(target)
|
||||
job = root / "output" / f".{video.stem}-{suffix}-{args.job_id}"
|
||||
job.mkdir(mode=0o700)
|
||||
print("Working directory:", job, flush=True)
|
||||
if args.preset == "audio-convert":
|
||||
probe(video, "audio")
|
||||
extracted = job / "audio.wav"
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, video), "-vn", "-c:a", "pcm_s16le",
|
||||
container_path(root, extracted))
|
||||
run(launcher, "rvc", "cli", container_path(root, extracted), container_path(root, job))
|
||||
instrumental = list((job / "instrumental").glob("*.wav"))
|
||||
if len(instrumental) != 1:
|
||||
raise RuntimeError("Expected exactly one instrumental stem")
|
||||
converted = job / "vocals-mia_voce.wav"
|
||||
probe(converted, "audio")
|
||||
mixed = job / "mix.wav"
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, instrumental[0]),
|
||||
"-i", container_path(root, converted),
|
||||
"-filter_complex", "[0:a][1:a]amix=inputs=2:duration=longest:normalize=0[a]",
|
||||
"-map", "[a]", "-c:a", "pcm_s16le", container_path(root, mixed))
|
||||
probe(mixed, "audio")
|
||||
os.link(mixed, target)
|
||||
else:
|
||||
original_has_audio = has_stream(video, "audio")
|
||||
sources = [media_file(root, name) for name in SOURCE_NAMES]
|
||||
processed = job / "swapped.mp4"
|
||||
run(launcher, "facefusion", "cli", "headless-run",
|
||||
"--source-paths", *[container_path(root, path) for path in sources],
|
||||
"--target-path", container_path(root, video),
|
||||
"--output-path", container_path(root, processed),
|
||||
"--processors", "face_swapper", "--face-swapper-model", "hyperswap_1a_256",
|
||||
"--face-swapper-pixel-boost", "256x256", "--face-swapper-weight", "0.5",
|
||||
"--face-detector-model", "yolo_face", "--face-detector-size", "640x640",
|
||||
"--face-detector-angles", "0", "90", "180", "270",
|
||||
"--face-detector-score", "0.5", "--face-selector-mode", "one",
|
||||
"--face-selector-order", "large-small", "--face-selector-gender", "female",
|
||||
"--face-selector-race", "white",
|
||||
"--face-mask-types", "occlusion", "region", "area", "box",
|
||||
"--face-occluder-model", "xseg_1",
|
||||
"--face-parser-model", "bisenet_resnet_34", "--face-mask-blur", "0.3",
|
||||
"--output-video-encoder", "libx264", "--output-video-preset", "veryfast",
|
||||
"--output-video-quality", "80", "--output-video-fps", "30",
|
||||
"--execution-providers", "cpu", "--output-audio-encoder", "aac",
|
||||
"--jobs-path", "/work/state", "--temp-path", "/work/state/tmp")
|
||||
probe(processed, "video")
|
||||
if abs(duration(processed) - duration(video)) > 0.5:
|
||||
raise RuntimeError("FaceFusion output duration differs from the input; refusing a partial result")
|
||||
if original_has_audio:
|
||||
# Restore the original soundtrack explicitly. Some completed
|
||||
# FaceFusion jobs have produced video-only MP4 files.
|
||||
mux(launcher, root, processed, video, target)
|
||||
else:
|
||||
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||
"-i", container_path(root, processed), "-map", "0:v:0",
|
||||
"-c:v", "copy", "-an", "-movflags", "+faststart",
|
||||
container_path(root, target))
|
||||
probe(target, "video")
|
||||
if has_stream(target, "audio"):
|
||||
raise RuntimeError("Unexpected audio stream in silent FaceFusion output")
|
||||
return target
|
||||
|
||||
|
||||
def process_complete(args, root, launcher):
|
||||
video = media_file(root, args.video, video=True)
|
||||
if not has_stream(video, "audio"):
|
||||
raise RuntimeError("The video has no audio to convert")
|
||||
common = {"video": video.name, "job_id": args.job_id}
|
||||
audio = process(argparse.Namespace(preset="audio-convert", **common), root, launcher)
|
||||
swapped = process(argparse.Namespace(preset="video-convert", **common), root, launcher)
|
||||
target = output_path(root, video, "completo")
|
||||
if target.exists():
|
||||
raise FileExistsError(target)
|
||||
mux(launcher, root, swapped, audio, target)
|
||||
return target
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(prog="ai-media preset")
|
||||
parser.add_argument("root", type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument("launcher", type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--run", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument("--job-id", help=argparse.SUPPRESS)
|
||||
sub = parser.add_subparsers(dest="preset", required=True)
|
||||
for name in ("audio-convert", "video-convert", "merge", "split", "split-stems", "convert"):
|
||||
command = sub.add_parser(name)
|
||||
command.add_argument("video", help="MP4 filename inside input/ or HTTP(S) video URL")
|
||||
if name == "merge":
|
||||
command.add_argument("audio", help="unique audio filename in input/ or output/")
|
||||
mix = sub.add_parser("mix", help="mix vocal and instrumental audio into one WAV")
|
||||
mix.add_argument("vocals", help="vocal audio path relative to input/ or output/")
|
||||
mix.add_argument("instrumental", help="instrumental audio path relative to input/ or output/")
|
||||
mix.add_argument("--output", help="WAV filename in output/ (default: <vocals>-mix.wav)")
|
||||
voice = sub.add_parser("voice-convert", help="apply mia_voce directly to an audio file")
|
||||
voice.add_argument("audio", help="audio path relative to input/ or output/")
|
||||
voice.add_argument("--output", help="WAV filename in output/ (default: <audio>-mia_voce.wav)")
|
||||
args = parser.parse_args()
|
||||
root = args.root.resolve(strict=True)
|
||||
launcher = args.launcher.resolve(strict=True)
|
||||
audio_only = args.preset in ("mix", "voice-convert")
|
||||
remote_video = not audio_only and not NAME.fullmatch(args.video)
|
||||
if args.preset == "voice-convert":
|
||||
source = audio_file(root, args.audio)
|
||||
wav_target(root, args.output or f"{source.stem}-mia_voce.wav")
|
||||
preset_inputs = [args.audio]
|
||||
if args.output:
|
||||
preset_inputs += ["--output", args.output]
|
||||
elif args.preset == "mix":
|
||||
audio_file(root, args.vocals)
|
||||
audio_file(root, args.instrumental)
|
||||
mix_target(root, args)
|
||||
preset_inputs = [args.vocals, args.instrumental]
|
||||
if args.output:
|
||||
preset_inputs += ["--output", args.output]
|
||||
elif remote_video:
|
||||
video_url(args.video)
|
||||
if shutil.which("yt-dlp") is None:
|
||||
raise RuntimeError("yt-dlp is required for URL downloads")
|
||||
else:
|
||||
media_file(root, args.video, video=True)
|
||||
if not audio_only:
|
||||
preset_inputs = [args.video] + ([args.audio] if args.preset == "merge" else [])
|
||||
if args.preset == "merge":
|
||||
audio_file(root, args.audio)
|
||||
if args.preset in ("video-convert", "convert"):
|
||||
for name in SOURCE_NAMES:
|
||||
media_file(root, name)
|
||||
if args.run:
|
||||
if remote_video:
|
||||
args.video = download_video(root, args.video, args.job_id).name
|
||||
if args.preset == "voice-convert":
|
||||
result = process_voice(args, root, launcher)
|
||||
elif args.preset == "mix":
|
||||
result = process_mix(args, root, launcher)
|
||||
else:
|
||||
result = (process_complete(args, root, launcher)
|
||||
if args.preset == "convert" else process(args, root, launcher))
|
||||
print("Completed:", result, flush=True)
|
||||
return
|
||||
unit = "ai-media-preset-" + datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
|
||||
subprocess.run(["systemd-run", "--user", "--collect", f"--unit={unit}",
|
||||
"--property=Type=exec", "--property=Restart=no",
|
||||
"/usr/bin/python3", str(Path(__file__).resolve()), str(root), str(launcher),
|
||||
"--run", "--job-id", unit, args.preset,
|
||||
*preset_inputs], check=True)
|
||||
print("Job:", unit)
|
||||
print("Logs: journalctl --user -fu", unit)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (ValueError, FileNotFoundError, FileExistsError, subprocess.CalledProcessError) as error:
|
||||
raise SystemExit(str(error)) from error
|
||||
94
ansible/roles/desktop_ai_media/files/preset_rvc.py
Normal file
94
ansible/roles/desktop_ai_media/files/preset_rvc.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""Offline RVC worker for the voice preset (runs inside the RVC container)."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("input_wav", type=Path)
|
||||
parser.add_argument("job_dir", type=Path)
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument("--separate-only", action="store_true")
|
||||
mode.add_argument("--convert-only", action="store_true")
|
||||
args = parser.parse_args()
|
||||
source = args.input_wav.resolve(strict=True)
|
||||
job = args.job_dir.resolve(strict=True)
|
||||
output = Path("/work/output").resolve(strict=True)
|
||||
if not source.is_relative_to(output) or not job.is_relative_to(output):
|
||||
raise ValueError("RVC preset paths must be inside /work/output")
|
||||
if source.parent != job or not source.is_file():
|
||||
raise ValueError("Expected the extracted WAV inside the job directory")
|
||||
|
||||
weights = Path("/work/state/weights/mia_voce.pth")
|
||||
index = Path("/work/state/mia_voce/added_IVF256_Flat_nprobe_1_mia_voce_v2.index")
|
||||
if not args.separate_only and not weights.is_file():
|
||||
raise FileNotFoundError(weights)
|
||||
if not args.separate_only and not index.is_file():
|
||||
raise FileNotFoundError(index)
|
||||
os.environ.update(
|
||||
weight_root="/work/state/weights",
|
||||
outside_index_root="/work/models/indices",
|
||||
index_root="/work/state",
|
||||
weight_pymss_root="/opt/app/assets/pymss_weights",
|
||||
rmvpe_root="/opt/app/assets/rmvpe",
|
||||
OMP_NUM_THREADS="4",
|
||||
MKL_NUM_THREADS="4",
|
||||
)
|
||||
|
||||
# The pinned WebUI imports its own argparse configuration at module load.
|
||||
sys.argv = sys.argv[:1]
|
||||
vocal_source = source
|
||||
if not args.convert_only:
|
||||
from tools.pymss_webui import pymss_separate
|
||||
|
||||
vocals_dir = job / "vocals"
|
||||
instrumental_dir = job / "instrumental"
|
||||
vocals_dir.mkdir()
|
||||
instrumental_dir.mkdir()
|
||||
failures = []
|
||||
|
||||
def on_event(event):
|
||||
if event.get("event") in ("fatal", "cancelled", "busy"):
|
||||
failures.append(event.get("message", str(event)))
|
||||
|
||||
for progress in pymss_separate(
|
||||
"vocals-bs-roformer-368", str(source), str(vocals_dir), None,
|
||||
str(instrumental_dir), "wav", event_callback=on_event,
|
||||
):
|
||||
print(progress, flush=True)
|
||||
if failures:
|
||||
raise RuntimeError("RVC separation failed: " + "; ".join(failures))
|
||||
vocals = list(vocals_dir.glob("*.wav"))
|
||||
instrumental = list(instrumental_dir.glob("*.wav"))
|
||||
if len(vocals) != 1 or len(instrumental) != 1:
|
||||
raise RuntimeError("RVC did not produce exactly one vocal and instrumental stem")
|
||||
|
||||
if args.separate_only:
|
||||
print("Vocal and instrumental stems ready (no voice conversion)", flush=True)
|
||||
return
|
||||
|
||||
vocal_source = vocals[0]
|
||||
|
||||
from configs.config import Config
|
||||
from infer.vc.modules import VC
|
||||
import soundfile as sf
|
||||
|
||||
voice = VC(Config())
|
||||
voice.get_vc(weights.name)
|
||||
status, result = voice.vc_single(
|
||||
0, str(vocal_source), 0, "rmvpe", str(index), 0.75, 0, 1, 0.33,
|
||||
)
|
||||
if result is None or result[0] is None or result[1] is None:
|
||||
raise RuntimeError("RVC voice conversion failed: " + str(status))
|
||||
converted = job / "vocals-mia_voce.wav"
|
||||
sf.write(converted, result[1], result[0])
|
||||
if converted.stat().st_size == 0:
|
||||
raise RuntimeError("RVC produced an empty converted voice")
|
||||
print("RVC converted voice ready", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,63 @@
|
||||
--index-url https://pypi.org/simple
|
||||
aiofiles==24.1.0
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.15.1
|
||||
brotli==1.2.0
|
||||
certifi==2026.7.22
|
||||
click==8.5.0
|
||||
fastapi==0.143.0
|
||||
ffmpy==1.0.0
|
||||
filelock==4.1.1
|
||||
flatbuffers==25.12.19
|
||||
fsspec==2026.9.0
|
||||
gradio==5.50.0
|
||||
gradio_client==1.14.0
|
||||
gradio_rangeslider==0.0.8
|
||||
groovy==0.1.2
|
||||
h11==0.16.0
|
||||
hf-xet==1.7.0
|
||||
httpcore==1.0.9
|
||||
httpx==0.28.1
|
||||
huggingface_hub==1.33.0
|
||||
idna==3.20
|
||||
Jinja2==3.1.6
|
||||
markdown-it-py==4.2.0
|
||||
MarkupSafe==3.0.4
|
||||
mdurl==0.1.2
|
||||
ml_dtypes==0.6.0
|
||||
numpy==2.4.6
|
||||
onnx==1.23.1
|
||||
onnxruntime==1.30.0
|
||||
opencv-python-headless==5.0.0.93
|
||||
opentelemetry-api==1.45.1
|
||||
orjson==3.13.0
|
||||
packaging==26.3
|
||||
pandas==2.3.3
|
||||
pillow==11.3.0
|
||||
pip==25.0.1
|
||||
protobuf==7.36.2
|
||||
pydantic==2.12.3
|
||||
pydantic_core==2.41.4
|
||||
pydub==0.25.1
|
||||
Pygments==2.21.0
|
||||
python-dateutil==2.9.0.post0
|
||||
python-multipart==0.0.32
|
||||
pytz==2026.5
|
||||
PyYAML==6.0.3
|
||||
rich==15.0.0
|
||||
ruff==0.17.0
|
||||
safehttpx==0.1.7
|
||||
scipy==1.18.1
|
||||
semantic-version==2.10.0
|
||||
shellingham==1.5.4
|
||||
six==1.17.0
|
||||
starlette==0.52.1
|
||||
tomlkit==0.13.3
|
||||
tqdm==4.70.1
|
||||
typer==0.27.3
|
||||
typing-inspection==0.4.4
|
||||
typing_extensions==4.16.0
|
||||
tzdata==2026.5
|
||||
uvicorn==0.54.0
|
||||
websockets==15.0.1
|
||||
120
ansible/roles/desktop_ai_media/files/requirements-rvc.lock
Normal file
120
ansible/roles/desktop_ai_media/files/requirements-rvc.lock
Normal file
@@ -0,0 +1,120 @@
|
||||
--index-url https://pypi.org/simple
|
||||
--extra-index-url https://download.pytorch.org/whl/cpu
|
||||
absl-py==2.5.1
|
||||
aiohappyeyeballs==2.7.1
|
||||
aiohttp==3.14.5
|
||||
aiosignal==1.4.0
|
||||
altair==4.2.2
|
||||
anyio==3.7.1
|
||||
attrs==26.1.0
|
||||
audioread==3.1.0
|
||||
av==15.1.0
|
||||
certifi==2026.7.22
|
||||
cffi==2.1.1
|
||||
charset-normalizer==3.5.2
|
||||
click==8.5.0
|
||||
cloudpickle==3.1.2
|
||||
coloredlogs==15.0.1
|
||||
contourpy==1.3.3
|
||||
cycler==0.12.1
|
||||
decorator==5.3.1
|
||||
einops==0.8.2
|
||||
entrypoints==0.4
|
||||
faiss-cpu==1.15.1
|
||||
fastapi==0.99.1
|
||||
ffmpeg-python==0.2.0
|
||||
ffmpy==1.0.0
|
||||
filelock==4.1.1
|
||||
flatbuffers==25.12.19
|
||||
fonttools==4.66.1
|
||||
FreeSimpleGUI==5.1.1
|
||||
frozenlist==1.8.0
|
||||
fsspec==2026.9.0
|
||||
future==1.0.0
|
||||
gradio==3.14.0
|
||||
grpcio==1.84.0
|
||||
h11==0.14.0
|
||||
hf-xet==1.7.0
|
||||
httpcore==0.16.3
|
||||
httpx==0.23.3
|
||||
huggingface_hub==0.36.2
|
||||
humanfriendly==10.0
|
||||
hyper-connections==0.4.2
|
||||
idna==3.20
|
||||
Jinja2==3.1.6
|
||||
joblib==1.6.0
|
||||
jsonschema==4.26.0
|
||||
jsonschema-specifications==2025.9.1
|
||||
kiwisolver==1.5.1
|
||||
lazy-loader==0.6
|
||||
librosa==0.10.2.post1
|
||||
linkify-it-py==2.2.0
|
||||
llvmlite==0.50.0
|
||||
local-attention==1.11.2
|
||||
Markdown==3.11
|
||||
markdown-it-py==2.2.0
|
||||
MarkupSafe==3.0.4
|
||||
matplotlib==3.11.2
|
||||
mdit-py-plugins==0.3.5
|
||||
mdurl==0.1.2
|
||||
mpmath==1.3.0
|
||||
msgpack==1.2.3
|
||||
multidict==7.1.0
|
||||
narwhals==2.27.1
|
||||
networkx==3.7
|
||||
numba==0.68.0
|
||||
numpy==1.26.4
|
||||
onnxruntime==1.31.0
|
||||
opencv-python-headless==4.11.0.86
|
||||
orjson==3.13.0
|
||||
packaging==26.3
|
||||
pandas==3.0.6
|
||||
pillow==12.3.0
|
||||
pip==25.0.1
|
||||
platformdirs==4.13.0
|
||||
pooch==1.9.0
|
||||
praat-parselmouth==0.4.7
|
||||
propcache==0.5.4
|
||||
protobuf==7.36.2
|
||||
pycparser==3.11
|
||||
pycryptodome==3.24.1
|
||||
pydantic==1.10.26
|
||||
pydub==0.25.1
|
||||
pyparsing==3.0.9
|
||||
python-dateutil==2.9.0.post0
|
||||
python-multipart==0.0.32
|
||||
PyYAML==6.0.3
|
||||
referencing==0.37.0
|
||||
regex==2026.9.29
|
||||
requests==2.34.2
|
||||
rfc3986==1.5.0
|
||||
rpds-py==2026.9.1
|
||||
safetensors==0.8.0
|
||||
scikit-learn==1.9.1
|
||||
scipy==1.17.1
|
||||
setuptools==80.10.2
|
||||
six==1.17.0
|
||||
sniffio==1.3.1
|
||||
sounddevice==0.5.6
|
||||
soundfile==0.14.0
|
||||
soxr==1.1.0
|
||||
starlette==0.27.0
|
||||
sympy==1.14.0
|
||||
tensorboard==2.21.0
|
||||
tensorboard-data-server==0.7.2
|
||||
threadpoolctl==3.7.0
|
||||
tokenizers==0.21.4
|
||||
toolz==1.2.0
|
||||
torch==2.4.1+cpu
|
||||
torchaudio==2.4.1+cpu
|
||||
torchfcpe==0.0.4
|
||||
torchvision==0.19.1+cpu
|
||||
tqdm==4.70.1
|
||||
transformers==4.49.0
|
||||
typing_extensions==4.16.0
|
||||
urllib3==2.8.0
|
||||
uvicorn==0.22.0
|
||||
websockets==10.4
|
||||
Werkzeug==3.1.9
|
||||
wheel==0.48.0
|
||||
yarl==1.25.1
|
||||
111
ansible/roles/desktop_ai_media/files/session.py
Normal file
111
ansible/roles/desktop_ai_media/files/session.py
Normal file
@@ -0,0 +1,111 @@
|
||||
import os
|
||||
import pathlib
|
||||
import signal
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
app = os.environ["APP"]
|
||||
os.chdir("/opt/app")
|
||||
if sys.argv[1:] == ["verify"]:
|
||||
os.execv(sys.executable, [sys.executable, "/opt/verify.py"])
|
||||
if sys.argv[1:2] == ["ffmpeg"]:
|
||||
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *sys.argv[2:]])
|
||||
if sys.argv[1:2] == ["cli"]:
|
||||
if app != "facefusion":
|
||||
raise SystemExit("CLI is available for FaceFusion only")
|
||||
os.execv(sys.executable, [sys.executable, "facefusion.py", *sys.argv[2:]])
|
||||
if app == "facefusion":
|
||||
command = [
|
||||
sys.executable, "facefusion.py", "run",
|
||||
"--execution-providers", "cpu", "--processors", "face_swapper",
|
||||
"--temp-path", "/work/state/tmp", "--jobs-path", "/work/state",
|
||||
"--output-path", "/work/output",
|
||||
]
|
||||
port = 7860
|
||||
else:
|
||||
pathlib.Path("/tmp/rvc-temp").mkdir(exist_ok=True)
|
||||
weights = pathlib.Path("/work/state/weights")
|
||||
weights.mkdir(exist_ok=True)
|
||||
for source in pathlib.Path("/work/models/weights").glob("*.pth"):
|
||||
target = weights / source.name
|
||||
if not target.exists() and not target.is_symlink():
|
||||
target.symlink_to(source)
|
||||
fixture = pathlib.Path("/opt/training-fixture/mute")
|
||||
for source in fixture.rglob("*"):
|
||||
target = pathlib.Path("/work/state/mute") / source.relative_to(fixture)
|
||||
if source.is_dir():
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
elif not target.exists():
|
||||
shutil.copyfile(source, target)
|
||||
os.environ.update(
|
||||
weight_root="/work/state/weights",
|
||||
outside_index_root="/work/models/indices",
|
||||
index_root="/work/state",
|
||||
weight_pymss_root="/opt/app/assets/pymss_weights",
|
||||
)
|
||||
command = [sys.executable, "webui.py", "--noautoopen", "--port", "7865"]
|
||||
port = 7865
|
||||
server = subprocess.Popen(command)
|
||||
browser = None
|
||||
profile = pathlib.Path("/tmp/browser")
|
||||
profile.mkdir(exist_ok=True)
|
||||
(profile / "user.js").write_text('''
|
||||
user_pref("browser.download.folderList", 2);
|
||||
user_pref("browser.download.dir", "/work/output");
|
||||
user_pref("browser.download.useDownloadDir", true);
|
||||
user_pref("widget.use-xdg-desktop-portal.file-picker", 0);
|
||||
user_pref("browser.shell.checkDefaultBrowser", false);
|
||||
user_pref("browser.aboutwelcome.enabled", false);
|
||||
user_pref("datareporting.policy.dataSubmissionEnabled", false);
|
||||
user_pref("toolkit.telemetry.enabled", false);
|
||||
''')
|
||||
bookmarks = pathlib.Path.home() / ".config/gtk-3.0/bookmarks"
|
||||
bookmarks.parent.mkdir(parents=True, exist_ok=True)
|
||||
bookmarks.write_text("file:///work/input Input\nfile:///work/output Output\nfile:///work/models Models\n")
|
||||
|
||||
|
||||
def stop(*_):
|
||||
if browser is not None and browser.poll() is None:
|
||||
browser.terminate()
|
||||
if server.poll() is None:
|
||||
server.terminate()
|
||||
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
for _ in range(180):
|
||||
if server.poll() is not None:
|
||||
raise RuntimeError(f"{app} exited: {server.returncode}")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=1) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("Offline WebUI did not become ready")
|
||||
print(f"{app}: offline WebUI ready", flush=True)
|
||||
if sys.argv[1:] == ["smoke"]:
|
||||
subprocess.run([
|
||||
"firefox-esr", "--headless", "--no-remote", "--profile", "/tmp/browser",
|
||||
"--screenshot", "/tmp/offline-ui.png", url,
|
||||
], check=True, timeout=90)
|
||||
assert pathlib.Path("/tmp/offline-ui.png").stat().st_size > 1000
|
||||
raise SystemExit(0)
|
||||
browser = subprocess.Popen([
|
||||
"firefox-esr", "--no-remote", "--profile", "/tmp/browser", url,
|
||||
])
|
||||
while browser.poll() is None:
|
||||
if server.poll() is not None:
|
||||
raise RuntimeError("WebUI terminated unexpectedly")
|
||||
time.sleep(1)
|
||||
finally:
|
||||
stop()
|
||||
if browser is not None:
|
||||
browser.wait(timeout=15)
|
||||
server.wait(timeout=15)
|
||||
139
ansible/roles/desktop_ai_media/files/verify.py
Normal file
139
ansible/roles/desktop_ai_media/files/verify.py
Normal file
@@ -0,0 +1,139 @@
|
||||
import os
|
||||
import gc
|
||||
import pathlib
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
interfaces = {p.name for p in pathlib.Path("/sys/class/net").iterdir()}
|
||||
assert interfaces == {"lo"}, interfaces
|
||||
for family, address in (
|
||||
(socket.AF_INET, ("1.1.1.1", 443)),
|
||||
(socket.AF_INET6, ("2606:4700:4700::1111", 443, 0, 0)),
|
||||
):
|
||||
with socket.socket(family, socket.SOCK_STREAM) as connection:
|
||||
connection.settimeout(2)
|
||||
try:
|
||||
connection.connect(address)
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
raise RuntimeError("External networking is available")
|
||||
subprocess.run(["sha256sum", "--quiet", "--check", "/opt/model-checksums.sha256"], check=True)
|
||||
if os.environ["APP"] == "facefusion":
|
||||
sys.path.insert(0, "/opt/app")
|
||||
from facefusion import state_manager
|
||||
from facefusion.args import apply_args
|
||||
from facefusion.program import create_program
|
||||
from facefusion.core import common_pre_check, processors_pre_check
|
||||
args = vars(create_program().parse_args([
|
||||
"run", "--execution-providers", "cpu", "--processors", "face_swapper",
|
||||
]))
|
||||
apply_args(args, state_manager.init_item)
|
||||
assert common_pre_check() and processors_pre_check()
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
options = ort.SessionOptions()
|
||||
options.intra_op_num_threads = 4
|
||||
options.inter_op_num_threads = 1
|
||||
model = ort.InferenceSession(
|
||||
"/opt/app/.assets/models/hyperswap_1a_256.onnx",
|
||||
sess_options=options, providers=["CPUExecutionProvider"],
|
||||
)
|
||||
feeds = {}
|
||||
for argument in model.get_inputs():
|
||||
assert argument.type == "tensor(float)"
|
||||
shape = [size if isinstance(size, int) and size > 0 else 1 for size in argument.shape]
|
||||
feeds[argument.name] = np.full(shape, 0.01, dtype=np.float32)
|
||||
assert all(np.isfinite(result).all() for result in model.run(None, feeds))
|
||||
else:
|
||||
sys.path.insert(0, "/opt/app")
|
||||
import numpy as np
|
||||
import torch
|
||||
import transformers
|
||||
import onnxruntime
|
||||
assert not torch.cuda.is_available()
|
||||
torch.set_num_threads(4)
|
||||
from infer.hubert import load_hubert_model, extract_hubert_features
|
||||
from infer.rmvpe import RMVPE
|
||||
with torch.inference_mode():
|
||||
hubert = load_hubert_model("cpu", False)
|
||||
features = extract_hubert_features(hubert, torch.zeros(1, 16000), "v2")
|
||||
assert torch.isfinite(features).all()
|
||||
del hubert, features
|
||||
pitch = RMVPE("/opt/app/assets/rmvpe/rmvpe.pt", False, "cpu")
|
||||
result = pitch.infer_from_audio(np.zeros(16000, dtype=np.float32))
|
||||
assert len(result) > 0 and np.isfinite(result).all()
|
||||
del pitch
|
||||
gc.collect()
|
||||
# Exercise the exact WebUI subprocess entrypoint, not only in-process imports.
|
||||
from scipy.io import wavfile
|
||||
with tempfile.TemporaryDirectory(prefix="rvc-slicing-") as temporary:
|
||||
directory = pathlib.Path(temporary)
|
||||
dataset = directory / "input"
|
||||
experiment = directory / "experiment"
|
||||
dataset.mkdir()
|
||||
experiment.mkdir()
|
||||
samples = np.arange(4 * 40000, dtype=np.float32) / 40000
|
||||
waveform = (0.2 * np.sin(2 * np.pi * 220 * samples)).astype(np.float32)
|
||||
wavfile.write(dataset / "synthetic.wav", 40000, waveform)
|
||||
subprocess.run([
|
||||
sys.executable, "train/preprocess.py", str(dataset), "40000", "1",
|
||||
str(experiment), "False", "3.7",
|
||||
], check=True, timeout=120)
|
||||
assert list((experiment / "0_gt_wavs").glob("*.wav"))
|
||||
assert list((experiment / "1_16k_wavs").glob("*.wav"))
|
||||
print("rvc: synthetic data slicing subprocess verified", flush=True)
|
||||
# Check the v2/40k training baseline and writable inference-model export.
|
||||
from train.utils import get_hparams_from_file
|
||||
from train.process_ckpt import savee
|
||||
hps = get_hparams_from_file("configs/v1/40k.json")
|
||||
checkpoint = torch.load("assets/pretrained_v2/f0G40k.pth", map_location="cpu")
|
||||
assert checkpoint["model"]
|
||||
pathlib.Path("/work/state/weights").mkdir(exist_ok=True)
|
||||
savee(checkpoint["model"], "40k", 1, "offline-readiness", 0, "v2", hps)
|
||||
exported = pathlib.Path("assets/weights/offline-readiness.pth")
|
||||
assert exported.is_file()
|
||||
exported.unlink()
|
||||
del checkpoint
|
||||
checkpoint = torch.load("assets/pretrained_v2/f0D40k.pth", map_location="cpu")
|
||||
assert checkpoint["model"]
|
||||
del checkpoint
|
||||
assert pathlib.Path("/opt/training-fixture/mute/0_gt_wavs/mute40k.wav").is_file()
|
||||
print("rvc: v2/40k training assets and model export verified", flush=True)
|
||||
# Exercise the WebUI's real worker and encoder on a synthetic stereo mix.
|
||||
with tempfile.TemporaryDirectory(prefix="rvc-separation-") as temporary:
|
||||
directory = pathlib.Path(temporary)
|
||||
sample_rate = 44100
|
||||
time_axis = np.arange(2 * sample_rate, dtype=np.float32) / sample_rate
|
||||
left = 0.1 * np.sin(2 * np.pi * 220 * time_axis)
|
||||
right = 0.1 * np.sin(2 * np.pi * 330 * time_axis)
|
||||
mix = np.stack((left, right), axis=1).astype(np.float32)
|
||||
wavfile.write(directory / "synthetic.wav", sample_rate, mix)
|
||||
subprocess.run([
|
||||
sys.executable, "-c",
|
||||
"import sys; from pathlib import Path; p=Path(sys.argv[1]); sys.argv=sys.argv[:1]; "
|
||||
"from tools.pymss_webui import pymss_separate, resolve_model, PYMSS_MODEL_CHOICES; "
|
||||
"assert PYMSS_MODEL_CHOICES == [resolve_model('vocals-bs-roformer-368').label]; "
|
||||
"list(pymss_separate('vocals-bs-roformer-368', str(p/'synthetic.wav'), "
|
||||
"str(p/'vocals'), None, str(p/'instrumental'), 'wav'))",
|
||||
str(directory),
|
||||
], check=True, timeout=600, env={
|
||||
**os.environ, "OMP_NUM_THREADS": "4", "MKL_NUM_THREADS": "4",
|
||||
})
|
||||
import soundfile as sf
|
||||
stems = []
|
||||
for name in ("vocals", "instrumental"):
|
||||
files = list((directory / name).glob("*.wav"))
|
||||
assert len(files) == 1, (name, files)
|
||||
data, rate = sf.read(files[0], dtype="float32", always_2d=True)
|
||||
assert rate == sample_rate and data.shape == mix.shape
|
||||
assert np.isfinite(data).all()
|
||||
stems.append(data)
|
||||
assert np.allclose(stems[0] + stems[1], mix, atol=1e-4)
|
||||
print("rvc: offline stereo vocal/instrumental separation verified", flush=True)
|
||||
|
||||
gc.collect()
|
||||
subprocess.run([sys.executable, "/opt/session.py", "smoke"], check=True)
|
||||
print(os.environ["APP"] + ": models verified, offline UI ready, IPv4/IPv6 egress blocked")
|
||||
4
ansible/roles/desktop_ai_media/handlers/main.yml
Normal file
4
ansible/roles/desktop_ai_media/handlers/main.yml
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
- name: Reload systemd units
|
||||
ansible.builtin.systemd_service:
|
||||
daemon_reload: true
|
||||
343
ansible/roles/desktop_ai_media/tasks/main.yml
Normal file
343
ansible/roles/desktop_ai_media/tasks/main.yml
Normal file
@@ -0,0 +1,343 @@
|
||||
---
|
||||
- name: Configure on-demand external ai-media storage
|
||||
become: true
|
||||
when: desktop_ai_media_external_storage_enabled | bool
|
||||
tags: [ai_media, ai_media_storage]
|
||||
block:
|
||||
- name: Validate external ai-media storage paths
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- desktop_ai_media_external_mountpoint is match('^/run/media/[^/]+/[^/]+$')
|
||||
- >-
|
||||
not desktop_ai_media_external_luks_uuid or
|
||||
desktop_ai_media_external_luks_uuid is match('^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')
|
||||
- desktop_ai_media_external_source.startswith(desktop_ai_media_external_mountpoint + '/')
|
||||
- desktop_ai_media_external_source != desktop_ai_media_external_mountpoint
|
||||
- desktop_ai_media_root.startswith(user_home + '/')
|
||||
- desktop_ai_media_root != user_home
|
||||
|
||||
- name: Derive external source mount unit name
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- systemd-escape
|
||||
- -p
|
||||
- --suffix=mount
|
||||
- "{{ desktop_ai_media_external_mountpoint }}"
|
||||
register: desktop_ai_media_external_source_mount_unit
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Derive ai-media bind mount unit name
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- systemd-escape
|
||||
- -p
|
||||
- --suffix=mount
|
||||
- "{{ desktop_ai_media_root }}"
|
||||
register: desktop_ai_media_bind_mount_unit
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Derive ai-media bind automount unit name
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- systemd-escape
|
||||
- -p
|
||||
- --suffix=automount
|
||||
- "{{ desktop_ai_media_root }}"
|
||||
register: desktop_ai_media_bind_automount_unit
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Create ai-media mount destination in the user home
|
||||
ansible.builtin.file:
|
||||
path: "{{ desktop_ai_media_root }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ username }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Install ai-media bind mount unit
|
||||
ansible.builtin.template:
|
||||
src: ai-media-bind.mount.j2
|
||||
dest: "/etc/systemd/system/{{ desktop_ai_media_bind_mount_unit.stdout }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
notify: Reload systemd units
|
||||
|
||||
- name: Install ai-media bind automount unit
|
||||
ansible.builtin.template:
|
||||
src: ai-media-bind.automount.j2
|
||||
dest: "/etc/systemd/system/{{ desktop_ai_media_bind_automount_unit.stdout }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
notify: Reload systemd units
|
||||
|
||||
- name: Install ai-media bind automount failure restarter
|
||||
ansible.builtin.template:
|
||||
src: ai-media-bind-restarter.service.j2
|
||||
dest: /etc/systemd/system/ai-media-bind-restarter.service
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
notify: Reload systemd units
|
||||
|
||||
- name: Flush systemd unit changes
|
||||
ansible.builtin.meta: flush_handlers
|
||||
|
||||
- name: Stop a stale ai-media bind mount when the Backup source is absent
|
||||
ansible.builtin.systemd_service:
|
||||
name: "{{ desktop_ai_media_bind_mount_unit.stdout }}"
|
||||
state: stopped
|
||||
when:
|
||||
- desktop_ai_media_root in (ansible_facts['mounts'] | default([]) | selectattr('fstype', 'ne', 'autofs') | map(attribute='mount') | list)
|
||||
- desktop_ai_media_external_mountpoint not in (ansible_facts['mounts'] | default([]) | map(attribute='mount') | list)
|
||||
|
||||
- name: Enable and start ai-media bind automount
|
||||
ansible.builtin.systemd_service:
|
||||
name: "{{ desktop_ai_media_bind_automount_unit.stdout }}"
|
||||
enabled: true
|
||||
state: started
|
||||
|
||||
- name: Configure isolated desktop media tools as the desktop user
|
||||
become: false
|
||||
block:
|
||||
- name: Determine whether the ai-media storage source is currently available
|
||||
ansible.builtin.set_fact:
|
||||
desktop_ai_media_external_available: >-
|
||||
{{ (not (desktop_ai_media_external_storage_enabled | bool)) or
|
||||
(desktop_ai_media_external_mountpoint in
|
||||
(ansible_facts['mounts'] | default([]) | map(attribute='mount') | list)) }}
|
||||
|
||||
- name: Load pinned public model manifest
|
||||
ansible.builtin.include_vars: models.yml
|
||||
|
||||
- name: Identify unprivileged desktop user
|
||||
ansible.builtin.command:
|
||||
argv: [id, -un]
|
||||
register: desktop_ai_media_user
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Verify local Fedora desktop scope
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- "'platform_fedora' in group_names"
|
||||
- "'desktop_gnome' in group_names"
|
||||
- ansible_connection == 'local'
|
||||
- desktop_ai_media_user.stdout == username
|
||||
- ansible_facts.architecture == 'x86_64'
|
||||
- desktop_ai_media_root.startswith(user_home + '/')
|
||||
- desktop_ai_media_root != user_home
|
||||
- desktop_ai_media_build_root != desktop_ai_media_root
|
||||
- desktop_ai_media_facefusion_revision is match('^[0-9a-f]{40}$')
|
||||
- desktop_ai_media_rvc_revision is match('^[0-9a-f]{40}$')
|
||||
- "'@sha256:' in desktop_ai_media_base_image"
|
||||
- desktop_ai_media_debian_snapshot is match('^[0-9]{8}T[0-9]{6}Z$')
|
||||
- desktop_ai_media_public_models | length > 0
|
||||
- >-
|
||||
desktop_ai_media_apps | difference(
|
||||
desktop_ai_media_public_models | map(attribute='app') | list) | length == 0
|
||||
|
||||
- name: Verify existing rootless Podman runtime
|
||||
ansible.builtin.command:
|
||||
argv: [podman, --remote=false, info, --format, "{{ '{{.Host.Security.Rootless}}' }}"]
|
||||
register: desktop_ai_media_podman
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Require rootless containers
|
||||
ansible.builtin.assert:
|
||||
that: desktop_ai_media_podman.stdout == 'true'
|
||||
|
||||
- name: Reject remote or synchronized media storage before provisioning
|
||||
ansible.builtin.command:
|
||||
argv: [python3, "-", "{{ desktop_ai_media_root }}"]
|
||||
stdin: "{{ lookup('ansible.builtin.file', role_path + '/files/check_storage.py') }}"
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
when: desktop_ai_media_external_available | bool
|
||||
|
||||
- name: Create the data-free local build context
|
||||
ansible.builtin.file:
|
||||
path: "{{ desktop_ai_media_build_root }}"
|
||||
state: directory
|
||||
mode: "0700"
|
||||
|
||||
- name: Create private application and media directories on mounted media storage
|
||||
ansible.builtin.file:
|
||||
path: "{{ item }}"
|
||||
state: directory
|
||||
mode: "0700"
|
||||
loop:
|
||||
- "{{ desktop_ai_media_root }}"
|
||||
- "{{ desktop_ai_media_root }}/input"
|
||||
- "{{ desktop_ai_media_root }}/input/voice"
|
||||
- "{{ desktop_ai_media_root }}/output"
|
||||
- "{{ desktop_ai_media_root }}/models"
|
||||
- "{{ desktop_ai_media_root }}/models/weights"
|
||||
- "{{ desktop_ai_media_root }}/models/indices"
|
||||
- "{{ desktop_ai_media_root }}/state"
|
||||
- "{{ desktop_ai_media_root }}/state/facefusion"
|
||||
- "{{ desktop_ai_media_root }}/state/rvc"
|
||||
when: desktop_ai_media_external_available | bool
|
||||
|
||||
- name: Ensure user launcher directories exist without changing existing permissions
|
||||
ansible.builtin.file:
|
||||
path: "{{ item }}"
|
||||
state: directory
|
||||
loop:
|
||||
- "{{ user_home }}/.local/bin"
|
||||
- "{{ user_home }}/.local/share/applications"
|
||||
|
||||
- name: Install runtime and model preparation code into the data-free build context
|
||||
ansible.builtin.copy:
|
||||
src: "{{ item }}"
|
||||
dest: "{{ desktop_ai_media_build_root }}/{{ item }}"
|
||||
mode: "0644"
|
||||
loop: [session.py, prepare.py, verify.py, check_storage.py]
|
||||
register: desktop_ai_media_support
|
||||
|
||||
- name: Install host-side offline preset workers without rebuilding images
|
||||
tags: [ai_media_presets]
|
||||
ansible.builtin.copy:
|
||||
src: "{{ item }}"
|
||||
dest: "{{ desktop_ai_media_build_root }}/{{ item }}"
|
||||
mode: "0644"
|
||||
loop: [preset.py, preset_rvc.py]
|
||||
|
||||
- name: Create public model cache directories
|
||||
ansible.builtin.file:
|
||||
path: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path | dirname }}"
|
||||
state: directory
|
||||
mode: "0700"
|
||||
loop: "{{ desktop_ai_media_public_models }}"
|
||||
loop_control:
|
||||
label: "{{ item.app }}/{{ item.path }}"
|
||||
|
||||
- name: Cache public models using pinned SHA256 checksums without personal data
|
||||
ansible.builtin.get_url:
|
||||
url: "{{ item.url }}"
|
||||
dest: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path }}"
|
||||
checksum: "sha256:{{ item.sha256 }}"
|
||||
mode: "0644"
|
||||
timeout: 60
|
||||
use_netrc: false
|
||||
use_proxy: false
|
||||
loop: "{{ desktop_ai_media_public_models }}"
|
||||
loop_control:
|
||||
label: "{{ item.app }}/{{ item.path }}"
|
||||
register: desktop_ai_media_model_cache
|
||||
|
||||
- name: Install complete Python dependency locks
|
||||
ansible.builtin.copy:
|
||||
src: "requirements-{{ item }}.lock"
|
||||
dest: "{{ desktop_ai_media_build_root }}/requirements-{{ item }}.lock"
|
||||
mode: "0644"
|
||||
loop: "{{ desktop_ai_media_apps }}"
|
||||
register: desktop_ai_media_locks
|
||||
|
||||
- name: Restrict the build context to code and checksum-pinned public models
|
||||
ansible.builtin.template:
|
||||
src: containerignore.j2
|
||||
dest: "{{ desktop_ai_media_build_root }}/.containerignore"
|
||||
mode: "0644"
|
||||
register: desktop_ai_media_ignore
|
||||
|
||||
- name: Render separate pinned application builds
|
||||
ansible.builtin.template:
|
||||
src: Containerfile.j2
|
||||
dest: "{{ desktop_ai_media_build_root }}/Containerfile.{{ item }}"
|
||||
mode: "0644"
|
||||
loop: "{{ desktop_ai_media_apps }}"
|
||||
register: desktop_ai_media_containerfiles
|
||||
|
||||
- name: Fingerprint the complete application build specification
|
||||
ansible.builtin.set_fact:
|
||||
desktop_ai_media_build_keys: >-
|
||||
{{ desktop_ai_media_build_keys | default({}) | combine({
|
||||
item: (
|
||||
lookup('ansible.builtin.template', role_path + '/templates/Containerfile.j2')
|
||||
+ lookup('ansible.builtin.file', role_path + '/files/prepare.py')
|
||||
+ lookup('ansible.builtin.file', role_path + '/files/session.py')
|
||||
+ lookup('ansible.builtin.file', role_path + '/files/verify.py')
|
||||
+ lookup('ansible.builtin.file', role_path + '/files/requirements-' + item + '.lock')
|
||||
+ lookup('ansible.builtin.file', role_path + '/templates/containerignore.j2')
|
||||
) | hash('sha256')
|
||||
}) }}
|
||||
loop: "{{ desktop_ai_media_apps }}"
|
||||
|
||||
- name: Inspect installed media images
|
||||
ansible.builtin.command:
|
||||
argv: [podman, --remote=false, image, exists, "localhost/ai-media-{{ item }}:managed"]
|
||||
loop: "{{ desktop_ai_media_apps }}"
|
||||
register: desktop_ai_media_images
|
||||
failed_when: desktop_ai_media_images.rc not in [0, 1]
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Inspect committed image build fingerprints
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- podman
|
||||
- --remote=false
|
||||
- image
|
||||
- inspect
|
||||
- --format
|
||||
- "{{ '{{ index .Labels \"io.fscotto.ai-media.build-key\" }}' }}"
|
||||
- "localhost/ai-media-{{ item.item }}:managed"
|
||||
loop: "{{ desktop_ai_media_images.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item }}"
|
||||
when: item.rc == 0
|
||||
register: desktop_ai_media_image_keys
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Build media images without mounting personal data
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- podman
|
||||
- --remote=false
|
||||
- build
|
||||
- --http-proxy=false
|
||||
- --pull=missing
|
||||
- --label
|
||||
- "io.fscotto.ai-media.build-key={{ desktop_ai_media_build_keys[item.item] }}"
|
||||
- --tag
|
||||
- "localhost/ai-media-{{ item.item }}:managed"
|
||||
- --file
|
||||
- "{{ desktop_ai_media_build_root }}/Containerfile.{{ item.item }}"
|
||||
- "{{ desktop_ai_media_build_root }}"
|
||||
loop: "{{ desktop_ai_media_images.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item }}"
|
||||
when: >-
|
||||
item.rc != 0 or
|
||||
desktop_ai_media_image_keys.results[desktop_ai_media_apps.index(item.item)].stdout | default('') !=
|
||||
desktop_ai_media_build_keys[item.item]
|
||||
changed_when: true
|
||||
timeout: 3600
|
||||
|
||||
- name: Install offline launcher
|
||||
tags: [ai_media_launcher]
|
||||
ansible.builtin.template:
|
||||
src: ai-media.j2
|
||||
dest: "{{ user_home }}/.local/bin/ai-media"
|
||||
mode: "0755"
|
||||
validate: /usr/bin/bash -n %s
|
||||
|
||||
- name: Install manual offline desktop entries
|
||||
ansible.builtin.template:
|
||||
src: application.desktop.j2
|
||||
dest: "{{ user_home }}/.local/share/applications/ai-media-{{ item }}.desktop"
|
||||
mode: "0644"
|
||||
loop: "{{ desktop_ai_media_apps }}"
|
||||
|
||||
- name: Verify offline networking and application readiness without personal files
|
||||
ansible.builtin.command:
|
||||
argv: ["{{ user_home }}/.local/bin/ai-media", verify]
|
||||
changed_when: false
|
||||
when: not ansible_check_mode
|
||||
40
ansible/roles/desktop_ai_media/templates/Containerfile.j2
Normal file
40
ansible/roles/desktop_ai_media/templates/Containerfile.j2
Normal file
@@ -0,0 +1,40 @@
|
||||
FROM {{ desktop_ai_media_base_image }}
|
||||
LABEL io.fscotto.ai-media.models="{{ desktop_ai_media_public_models | selectattr('app', 'equalto', item) | list | to_json | hash('sha256') }}"
|
||||
ENV DEBIAN_FRONTEND=noninteractive PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
RUN sed -i \
|
||||
-e 's|http://deb.debian.org/debian$|https://snapshot.debian.org/archive/debian/{{ desktop_ai_media_debian_snapshot }}/|' \
|
||||
-e 's|http://deb.debian.org/debian-security$|https://snapshot.debian.org/archive/debian-security/{{ desktop_ai_media_debian_snapshot }}/|' \
|
||||
/etc/apt/sources.list.d/debian.sources \
|
||||
&& apt-get -o Acquire::Check-Valid-Until=false update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl git ffmpeg firefox-esr fonts-dejavu-core libgl1 libglib2.0-0 libportaudio2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY requirements-{{ item }}.lock /opt/requirements.lock
|
||||
WORKDIR /opt/app
|
||||
{% if item == 'facefusion' %}
|
||||
RUN git init . && git remote add origin https://github.com/facefusion/facefusion.git \
|
||||
&& git fetch --depth 1 origin {{ desktop_ai_media_facefusion_revision }} \
|
||||
&& git checkout --detach FETCH_HEAD && rm -rf .git \
|
||||
&& pip install --no-cache-dir -r /opt/requirements.lock
|
||||
{% else %}
|
||||
RUN git init . && git remote add origin https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git \
|
||||
&& git fetch --depth 1 origin {{ desktop_ai_media_rvc_revision }} \
|
||||
&& git checkout --detach FETCH_HEAD && rm -rf .git \
|
||||
&& pip install --no-cache-dir -r /opt/requirements.lock
|
||||
{% endif %}
|
||||
{% for model in desktop_ai_media_public_models if model.app == item %}
|
||||
COPY models/{{ model.app }}/{{ model.path }} /opt/app/{{ model.path }}
|
||||
{% endfor %}
|
||||
COPY prepare.py /opt/
|
||||
RUN python /opt/prepare.py {{ item }} \
|
||||
&& pip freeze --all > /opt/python-requirements.lock \
|
||||
&& test -s /opt/model-checksums.sha256
|
||||
COPY session.py verify.py /opt/
|
||||
RUN mkdir -p /work/input /work/output /work/state /work/models /home/media
|
||||
ENV GRADIO_ANALYTICS_ENABLED=False HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
|
||||
HF_HUB_DISABLE_TELEMETRY=1 DO_NOT_TRACK=1 HOME=/home/media \
|
||||
XDG_RUNTIME_DIR=/run/media MOZ_ENABLE_WAYLAND=1 GTK_USE_PORTAL=0 \
|
||||
LIBGL_ALWAYS_SOFTWARE=1 GRADIO_SERVER_NAME=127.0.0.1 GRADIO_SERVER_PORT=7860 \
|
||||
PYTHONPATH=/opt/app PYTHONSAFEPATH=1 PYTHONDONTWRITEBYTECODE=1 NUMBA_CACHE_DIR=/tmp/numba MPLCONFIGDIR=/tmp/matplotlib \
|
||||
GRADIO_TEMP_DIR=/tmp/gradio APP={{ item }}
|
||||
ENTRYPOINT ["python", "/opt/session.py"]
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Recover the ai-media bind automount after an unavailable Backup volume
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStartPre=/usr/bin/sleep 3
|
||||
ExecStart=/usr/bin/bash -c '/usr/bin/systemctl restart "$(/usr/bin/systemd-escape -p --suffix=automount {{ desktop_ai_media_root }})"'
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=On-demand ai-media bind mount from the Backup LUKS volume
|
||||
ConditionPathIsDirectory={{ desktop_ai_media_root }}
|
||||
OnFailure=ai-media-bind-restarter.service
|
||||
|
||||
[Automount]
|
||||
Where={{ desktop_ai_media_root }}
|
||||
TimeoutIdleSec=5min
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Bind mount ai-media from the Backup LUKS volume
|
||||
RequiresMountsFor={{ desktop_ai_media_external_mountpoint }}
|
||||
After={{ desktop_ai_media_external_source_mount_unit.stdout }}
|
||||
BindsTo={{ desktop_ai_media_external_source_mount_unit.stdout }}
|
||||
ConditionPathIsMountPoint={{ desktop_ai_media_external_mountpoint }}
|
||||
ConditionPathIsDirectory={{ desktop_ai_media_external_source }}
|
||||
|
||||
[Mount]
|
||||
What={{ desktop_ai_media_external_source }}
|
||||
Where={{ desktop_ai_media_root }}
|
||||
Options=bind
|
||||
193
ansible/roles/desktop_ai_media/templates/ai-media.j2
Normal file
193
ansible/roles/desktop_ai_media/templates/ai-media.j2
Normal file
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
root={{ desktop_ai_media_root | quote }}
|
||||
build_root={{ desktop_ai_media_build_root | quote }}
|
||||
{% set manage_luks = desktop_ai_media_external_storage_enabled | default(false) and desktop_ai_media_external_luks_uuid | default('') %}
|
||||
{% if manage_luks %}
|
||||
encrypted={{ ('/dev/disk/by-uuid/' + desktop_ai_media_external_luks_uuid) | quote }}
|
||||
external_mount={{ desktop_ai_media_external_mountpoint | quote }}
|
||||
bind_fsroot={{ (desktop_ai_media_external_source | replace(desktop_ai_media_external_mountpoint, '', 1)) | quote }}
|
||||
|
||||
fail() { echo "$*" >&2; exit 1; }
|
||||
|
||||
read_mapper() {
|
||||
local devices mapping
|
||||
devices=$(lsblk -nrpo NAME,TYPE,MAJ:MIN -- "$encrypted") ||
|
||||
fail "The configured LUKS volume is not available: $encrypted"
|
||||
mapping=$(awk '$2 == "crypt" {print $1, $3}' <<< "$devices")
|
||||
[[ "$mapping" != *$'\n'* ]] || fail "Multiple mappings for $encrypted; refusing to continue"
|
||||
read -r mapper mapper_id <<< "$mapping"
|
||||
}
|
||||
|
||||
mount_info() {
|
||||
# Inspect the kernel mount table without following the automount path.
|
||||
findmnt -krnC --mountpoint "$1" --types noautofs --output MAJ:MIN,FSROOT || [[ $? == 1 ]]
|
||||
}
|
||||
|
||||
volume_mounts() {
|
||||
[[ -n "$mapper_id" ]] || return 0
|
||||
findmnt -krnC --source "$mapper_id" --output TARGET || [[ $? == 1 ]]
|
||||
}
|
||||
|
||||
require_external_bind() {
|
||||
read_mapper
|
||||
[[ -n "$mapper_id" && "$(mount_info "$root")" == "$mapper_id $bind_fsroot" ]] ||
|
||||
fail "Encrypted media storage is not mounted; run ai-media mount first"
|
||||
}
|
||||
|
||||
manage_volume() {
|
||||
local action=$1 mapper mapper_id bind_unit automount_unit mounted bind jobs containers
|
||||
[[ $# == 1 ]] || fail "Usage: ai-media $action"
|
||||
bind_unit=$(systemd-escape -p --suffix=mount -- "$root")
|
||||
automount_unit=$(systemd-escape -p --suffix=automount -- "$root")
|
||||
read_mapper
|
||||
mounted=$(mount_info "$external_mount")
|
||||
bind=$(mount_info "$root")
|
||||
[[ -z "$mounted" || "$mounted" == "$mapper_id /" ]] ||
|
||||
fail "Unexpected filesystem at $external_mount; refusing to continue"
|
||||
[[ -z "$bind" || "$bind" == "$mapper_id $bind_fsroot" ]] ||
|
||||
fail "Unexpected filesystem at $root; refusing to continue"
|
||||
|
||||
if [[ "$action" == mount ]]; then
|
||||
if [[ -z "$mapper" ]]; then
|
||||
udisksctl unlock --block-device "$encrypted"
|
||||
read_mapper
|
||||
[[ -n "$mapper" ]] || fail "No decrypted block device found after unlock"
|
||||
fi
|
||||
if [[ -z "$mounted" ]]; then
|
||||
[[ -z "$(volume_mounts)" ]] || fail "The LUKS volume is already mounted elsewhere"
|
||||
udisksctl mount --block-device "$mapper"
|
||||
fi
|
||||
[[ "$(mount_info "$external_mount")" == "$mapper_id /" ]] ||
|
||||
fail "The LUKS volume is not mounted at the expected path: $external_mount"
|
||||
sudo systemctl start "$automount_unit" "$bind_unit"
|
||||
require_external_bind
|
||||
echo "Encrypted media storage mounted at $root"
|
||||
else
|
||||
jobs=$(systemctl --user list-units --type=service --state=active,activating,deactivating \
|
||||
--no-legend --no-pager 'ai-media-*.service')
|
||||
containers=$(podman --remote=false ps -q \
|
||||
--filter ancestor=localhost/ai-media-facefusion:managed \
|
||||
--filter ancestor=localhost/ai-media-rvc:managed)
|
||||
[[ -z "$jobs" && -z "$containers" ]] ||
|
||||
fail "Stop the running ai-media jobs and applications before unmounting"
|
||||
sudo systemctl stop ai-media-bind-restarter.service "$automount_unit" "$bind_unit"
|
||||
[[ -z "$(mount_info "$root")" ]] || fail "The media bind mount is still in use"
|
||||
mounted=$(volume_mounts)
|
||||
if [[ -n "$mounted" ]]; then
|
||||
[[ "$mounted" == "$external_mount" && "$(mount_info "$external_mount")" == "$mapper_id /" ]] ||
|
||||
fail "The LUKS volume has other mounts; refusing to unmount or lock it"
|
||||
udisksctl unmount --block-device "$mapper"
|
||||
fi
|
||||
if [[ -n "$mapper" ]]; then
|
||||
[[ -z "$(volume_mounts)" ]] || fail "The LUKS volume is still mounted"
|
||||
udisksctl lock --block-device "$encrypted"
|
||||
fi
|
||||
echo "Encrypted media storage unmounted and locked"
|
||||
fi
|
||||
}
|
||||
{% endif %}
|
||||
app="${1:-}"
|
||||
case "$app" in
|
||||
{% if manage_luks %}
|
||||
mount|umount) manage_volume "$@"; exit ;;
|
||||
{% endif %}
|
||||
facefusion|rvc) shift ;;
|
||||
ffmpeg) app=facefusion; shift; set -- ffmpeg "$@" ;;
|
||||
preset)
|
||||
shift
|
||||
for path in "$root" "$root/input" "$root/output"; do
|
||||
[[ -d "$path" && "$(realpath -- "$path")" == "$path" ]] || {
|
||||
echo "Unsafe or missing media directory: $path" >&2; exit 1;
|
||||
}
|
||||
done
|
||||
{% if manage_luks %}
|
||||
require_external_bind
|
||||
{% endif %}
|
||||
python3 "$build_root/check_storage.py" "$root"
|
||||
exec python3 "$build_root/preset.py" "$root" "$(realpath -- "$0")" "$@" ;;
|
||||
verify)
|
||||
for tool in facefusion rvc; do
|
||||
podman --remote=false run --rm --pull=never --network=none --read-only \
|
||||
--cap-drop=ALL --cap-add=SYS_CHROOT \
|
||||
--security-opt=no-new-privileges --userns=keep-id --http-proxy=false \
|
||||
--tmpfs "/tmp:rw,nosuid,nodev,size=4g,mode=1777" \
|
||||
--tmpfs "/home/media:rw,nosuid,nodev,size=128m,mode=1777" \
|
||||
--tmpfs "/work/state:rw,nosuid,nodev,size=128m,mode=1777" \
|
||||
--tmpfs "/work/models:rw,nosuid,nodev,size=128m,mode=1777" \
|
||||
"localhost/ai-media-$tool:managed" verify
|
||||
done
|
||||
exit 0 ;;
|
||||
*) echo "Usage: ai-media {facefusion|rvc|ffmpeg|preset|verify{% if manage_luks %}|mount|umount{% endif %}} [args ...]" >&2; exit 2 ;;
|
||||
esac
|
||||
# Fail closed if an existing data path was replaced by a symlink.
|
||||
for path in "$root" "$root/input" "$root/output" "$root/models" "$root/state/$app"; do
|
||||
[[ -d "$path" && "$(realpath -- "$path")" == "$path" ]] || {
|
||||
echo "Unsafe or missing media directory: $path" >&2; exit 1;
|
||||
}
|
||||
done
|
||||
{% if manage_luks %}
|
||||
require_external_bind
|
||||
{% endif %}
|
||||
python3 {{ (desktop_ai_media_build_root + "/check_storage.py") | quote }} "$root"
|
||||
# Run interactive sessions under the user manager, not the launching terminal.
|
||||
# No autostart or automatic restart: recovering a training run remains explicit.
|
||||
if [[ "$app" == rvc || "$app" == facefusion ]] && [[ $# -eq 0 ]]; then
|
||||
: "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}"
|
||||
: "${WAYLAND_DISPLAY:?A Wayland session is required}"
|
||||
[[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1
|
||||
active=$(podman --remote=false ps --filter "ancestor=localhost/ai-media-$app:managed" --format '{{ '{{.ID}}' }}')
|
||||
if [[ -n "$active" ]]; then
|
||||
echo "$app is already running; leave its training session open." >&2
|
||||
exit 1
|
||||
fi
|
||||
exec systemd-run --user --collect --unit="ai-media-$app" \
|
||||
--property=Type=exec --property=Restart=no --property=Delegate=yes \
|
||||
--setenv="XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR" --setenv="WAYLAND_DISPLAY=$WAYLAND_DISPLAY" \
|
||||
-- /usr/bin/bash "$(realpath -- "$0")" "$app" --foreground
|
||||
fi
|
||||
if [[ "${1:-}" == --foreground ]]; then
|
||||
shift
|
||||
fi
|
||||
if [[ "$app" == rvc && "${1:-}" == cli ]]; then
|
||||
shift
|
||||
rvc_cli=1
|
||||
set -- /opt/preset_rvc.py "$@"
|
||||
else
|
||||
rvc_cli=0
|
||||
fi
|
||||
args=(
|
||||
run --rm --pull=never --network=none --read-only --userns=keep-id --http-proxy=false
|
||||
--cap-drop=ALL --security-opt=no-new-privileges
|
||||
--tmpfs "/tmp:rw,nosuid,nodev,size=8g,mode=1777"
|
||||
--tmpfs "/home/media:rw,nosuid,nodev,size=128m,mode=1777"
|
||||
--shm-size=512m
|
||||
--volume "$root/input:/work/input:ro,Z"
|
||||
--volume "$root/output:/work/output:rw,Z"
|
||||
--volume "$root/models:/work/models:ro,Z"
|
||||
--volume "$root/state/$app:/work/state:rw,Z"
|
||||
)
|
||||
if [[ "$rvc_cli" == 1 ]]; then
|
||||
args+=(--volume "$build_root/preset_rvc.py:/opt/preset_rvc.py:ro,Z" --entrypoint python)
|
||||
fi
|
||||
if [[ "$rvc_cli" != 1 && "${1:-}" != cli && "${1:-}" != ffmpeg ]]; then
|
||||
: "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}"
|
||||
: "${WAYLAND_DISPLAY:?A Wayland session is required}"
|
||||
[[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1
|
||||
# Share only the display socket, never the runtime directory, D-Bus, home
|
||||
# directory or host browser. Do not relabel the compositor's socket.
|
||||
args+=(
|
||||
--cap-add=SYS_CHROOT
|
||||
--security-opt label=disable
|
||||
--tmpfs "/run/media:rw,nosuid,nodev,size=1m,mode=1777"
|
||||
--volume "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY:/run/media/wayland-0:ro"
|
||||
--env WAYLAND_DISPLAY=wayland-0
|
||||
)
|
||||
if [[ -S "$XDG_RUNTIME_DIR/pulse/native" ]]; then
|
||||
args+=(
|
||||
--volume "$XDG_RUNTIME_DIR/pulse/native:/run/media/pulse-native:ro"
|
||||
--env PULSE_SERVER=unix:/run/media/pulse-native
|
||||
)
|
||||
fi
|
||||
fi
|
||||
exec podman --remote=false "${args[@]}" "localhost/ai-media-$app:managed" "$@"
|
||||
@@ -0,0 +1,7 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name={{ 'FaceFusion' if item == 'facefusion' else 'RVC Voice Conversion' }} (offline)
|
||||
Exec={{ user_home }}/.local/bin/ai-media {{ item }}
|
||||
Terminal=false
|
||||
Categories=AudioVideo;
|
||||
StartupNotify=false
|
||||
15
ansible/roles/desktop_ai_media/templates/containerignore.j2
Normal file
15
ansible/roles/desktop_ai_media/templates/containerignore.j2
Normal file
@@ -0,0 +1,15 @@
|
||||
*
|
||||
!Containerfile.*
|
||||
!prepare.py
|
||||
!session.py
|
||||
!verify.py
|
||||
!requirements-facefusion.lock
|
||||
!requirements-rvc.lock
|
||||
!models/
|
||||
{% for model in desktop_ai_media_public_models %}
|
||||
!models/{{ model.app }}/
|
||||
{% for depth in range(1, model.path.split('/') | length) %}
|
||||
!models/{{ model.app }}/{{ model.path.split('/')[:depth] | join('/') }}/
|
||||
{% endfor %}
|
||||
!models/{{ model.app }}/{{ model.path }}
|
||||
{% endfor %}
|
||||
Binary file not shown.
584
ansible/roles/desktop_ai_media/tests/test_launcher.py
Normal file
584
ansible/roles/desktop_ai_media/tests/test_launcher.py
Normal file
@@ -0,0 +1,584 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import wave
|
||||
import struct
|
||||
|
||||
from jinja2 import Environment
|
||||
import shlex
|
||||
|
||||
ROLE = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class LauncherTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.media = self.root / '.local/share/ai-media'
|
||||
for directory in ('input', 'output', 'models', 'state/facefusion', 'state/rvc'):
|
||||
(self.media / directory).mkdir(parents=True)
|
||||
environment = Environment()
|
||||
environment.filters['quote'] = shlex.quote
|
||||
self.launcher = self.root / 'ai-media'
|
||||
self.launcher.write_text(environment.from_string(
|
||||
(ROLE / 'templates/ai-media.j2').read_text()
|
||||
).render(desktop_ai_media_root=str(self.media), desktop_ai_media_build_root=str(self.root)))
|
||||
(self.root / 'check_storage.py').write_text((ROLE / 'files/check_storage.py').read_text())
|
||||
for name in ('preset.py', 'preset_rvc.py'):
|
||||
(self.root / name).write_text((ROLE / 'files' / name).read_text())
|
||||
self.log = self.root / 'podman.json'
|
||||
podman = self.root / 'podman'
|
||||
podman.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||
podman.chmod(0o755)
|
||||
self.env = dict(os.environ, PATH=str(self.root) + ':' + os.environ['PATH'],
|
||||
TEST_LOG=str(self.log), HOME=str(self.root))
|
||||
|
||||
def launch(self, *args):
|
||||
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
|
||||
capture_output=True, text=True)
|
||||
|
||||
def fake_media_launcher(self):
|
||||
fake = self.root / 'fake-ai-media'
|
||||
fake.write_text('''#!/usr/bin/python3
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
root = Path(os.environ["TEST_MEDIA"])
|
||||
def host(path):
|
||||
return str(path).replace("/work/input/", str(root / "input") + "/").replace(
|
||||
"/work/output/", str(root / "output") + "/")
|
||||
|
||||
tool = sys.argv[1]
|
||||
args = sys.argv[2:]
|
||||
if tool == "ffmpeg":
|
||||
os.execvp("ffmpeg", ["ffmpeg", *[host(arg) for arg in args]])
|
||||
if tool == "facefusion":
|
||||
(root / "facefusion-args.json").write_text(__import__("json").dumps(args))
|
||||
shutil.copyfile(host(args[args.index("--target-path") + 1]),
|
||||
host(args[args.index("--output-path") + 1]))
|
||||
raise SystemExit(0)
|
||||
if tool == "rvc":
|
||||
(root / "rvc-args.json").write_text(__import__("json").dumps(args))
|
||||
source = Path(host(args[1]))
|
||||
job = Path(host(args[2]))
|
||||
if "--convert-only" not in args:
|
||||
(job / "instrumental").mkdir()
|
||||
shutil.copyfile(source, job / "instrumental/stem.wav")
|
||||
if "--separate-only" in args:
|
||||
(job / "vocals").mkdir()
|
||||
shutil.copyfile(source, job / "vocals/stem.wav")
|
||||
else:
|
||||
shutil.copyfile(source, job / "vocals-mia_voce.wav")
|
||||
raise SystemExit(0)
|
||||
raise SystemExit("Unexpected tool: " + tool)
|
||||
''')
|
||||
fake.chmod(0o755)
|
||||
return fake
|
||||
|
||||
def fake_downloader(self, fixture):
|
||||
downloader = self.root / 'yt-dlp'
|
||||
downloader.write_text('''#!/usr/bin/python3
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
Path(os.environ["TEST_LOG"]).write_text(json.dumps(args))
|
||||
destination = args[args.index("--output") + 1].replace("%(ext)s", "mp4")
|
||||
shutil.copyfile(os.environ["TEST_DOWNLOAD_FIXTURE"], destination)
|
||||
''')
|
||||
downloader.chmod(0o755)
|
||||
self.env['TEST_DOWNLOAD_FIXTURE'] = str(fixture)
|
||||
return downloader
|
||||
|
||||
def run_preset(self, fake, *args, job_id='test'):
|
||||
return subprocess.run(['python3', str(self.root / 'preset.py'),
|
||||
str(self.media), str(fake), '--run', '--job-id', job_id, *args],
|
||||
env={**self.env, 'TEST_MEDIA': str(self.media)},
|
||||
capture_output=True, text=True)
|
||||
|
||||
def create_video(self, *, audio=False):
|
||||
video = self.media / 'input/video1.mp4'
|
||||
command = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi',
|
||||
'-i', 'color=c=black:s=64x64:d=1']
|
||||
if audio:
|
||||
command += ['-f', 'lavfi', '-i', 'sine=frequency=440:duration=1']
|
||||
command += ['-c:v', 'mpeg4']
|
||||
if audio:
|
||||
command += ['-c:a', 'aac', '-shortest']
|
||||
subprocess.run([*command, str(video)], check=True)
|
||||
return video
|
||||
|
||||
def stream_types(self, path):
|
||||
probe = subprocess.check_output(['ffprobe', '-v', 'error', '-show_entries',
|
||||
'stream=codec_type', '-of', 'json', str(path)])
|
||||
return {stream['codec_type'] for stream in json.loads(probe)['streams']}
|
||||
|
||||
def create_audio(self, relative, sample=1000, seconds=1):
|
||||
path = self.media / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with wave.open(str(path), 'wb') as audio:
|
||||
audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed'))
|
||||
audio.writeframes(struct.pack('<h', sample) * (8000 * seconds))
|
||||
return path
|
||||
|
||||
def test_mix_sums_stems_and_preserves_longest_duration(self):
|
||||
vocals = self.create_audio('output/video1-split-stems/vocals.wav')
|
||||
instrumental = self.create_audio('output/video1-split-stems/instrumental.wav',
|
||||
sample=2000, seconds=2)
|
||||
before = [path.read_bytes() for path in (vocals, instrumental)]
|
||||
result = self.run_preset(self.fake_media_launcher(), 'mix',
|
||||
'video1-split-stems/vocals.wav',
|
||||
'video1-split-stems/instrumental.wav', '--output', 'song.wav')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
output = self.media / 'output/song.wav'
|
||||
self.assertEqual(self.stream_types(output), {'audio'})
|
||||
with wave.open(str(output), 'rb') as audio:
|
||||
self.assertEqual(audio.getnframes(), 16000)
|
||||
samples = struct.unpack('<16000h', audio.readframes(16000))
|
||||
self.assertAlmostEqual(samples[4000], 3000, delta=1)
|
||||
self.assertAlmostEqual(samples[12000], 2000, delta=1)
|
||||
self.assertEqual([path.read_bytes() for path in (vocals, instrumental)], before)
|
||||
|
||||
def test_voice_convert_audio_skips_separation_and_preserves_input(self):
|
||||
source = self.create_audio('output/video1-split-stems/vocals.wav')
|
||||
before = source.read_bytes()
|
||||
result = self.run_preset(self.fake_media_launcher(), 'voice-convert',
|
||||
'video1-split-stems/vocals.wav')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
output = self.media / 'output/vocals-mia_voce.wav'
|
||||
self.assertEqual(self.stream_types(output), {'audio'})
|
||||
args = json.loads((self.media / 'rvc-args.json').read_text())
|
||||
self.assertIn('--convert-only', args)
|
||||
self.assertFalse(list((self.media / 'output').rglob('instrumental')))
|
||||
self.assertFalse((self.media / 'facefusion-args.json').exists())
|
||||
self.assertEqual(source.read_bytes(), before)
|
||||
repeated = self.run_preset(self.fake_media_launcher(), 'voice-convert',
|
||||
'video1-split-stems/vocals.wav')
|
||||
self.assertNotEqual(repeated.returncode, 0)
|
||||
|
||||
def test_voice_convert_dispatches_with_custom_output(self):
|
||||
self.create_audio('input/voice.wav')
|
||||
runner = self.root / 'systemd-run'
|
||||
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||
runner.chmod(0o755)
|
||||
result = self.launch('preset', 'voice-convert', 'voice.wav', '--output', 'mine.wav')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--user', args)
|
||||
self.assertEqual(args[-4:], ['voice-convert', 'voice.wav', '--output', 'mine.wav'])
|
||||
|
||||
def test_voice_convert_rejects_invalid_audio_and_output(self):
|
||||
self.create_audio('input/voice.wav')
|
||||
for name in ('missing.wav', '../voice.wav', 'https://example.org/audio.wav'):
|
||||
self.assertNotEqual(self.launch('preset', 'voice-convert', name).returncode, 0)
|
||||
for name in ('../mine.wav', 'mine.mp3'):
|
||||
self.assertNotEqual(self.launch('preset', 'voice-convert', 'voice.wav',
|
||||
'--output', name).returncode, 0)
|
||||
self.create_audio('output/voice.wav')
|
||||
self.assertNotEqual(self.launch('preset', 'voice-convert', 'voice.wav').returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_mix_default_output_and_no_overwrite(self):
|
||||
self.create_audio('input/voice.wav')
|
||||
self.create_audio('output/instrumental.wav')
|
||||
args = ('mix', 'voice.wav', 'instrumental.wav')
|
||||
result = self.run_preset(self.fake_media_launcher(), *args)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
target = self.media / 'output/voice-mix.wav'
|
||||
original = target.read_bytes()
|
||||
result = self.run_preset(self.fake_media_launcher(), *args)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(target.read_bytes(), original)
|
||||
|
||||
def test_mix_dispatches_audio_only_background_job(self):
|
||||
self.create_audio('input/voice.wav')
|
||||
self.create_audio('output/instrumental.wav')
|
||||
runner = self.root / 'systemd-run'
|
||||
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||
runner.chmod(0o755)
|
||||
result = self.launch('preset', 'mix', 'voice.wav', 'instrumental.wav',
|
||||
'--output', 'song.wav')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--user', args)
|
||||
self.assertEqual(args[-5:], ['mix', 'voice.wav', 'instrumental.wav',
|
||||
'--output', 'song.wav'])
|
||||
self.assertFalse((self.media / 'output/song.wav').exists())
|
||||
|
||||
def test_mix_rejects_unsafe_paths_and_ambiguous_audio(self):
|
||||
self.create_audio('input/voice.wav')
|
||||
self.create_audio('output/instrumental.wav')
|
||||
for unsafe in ('../voice.wav', '/tmp/voice.wav', 'https://example.org/voice.wav'):
|
||||
result = self.launch('preset', 'mix', unsafe, 'instrumental.wav')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
for unsafe in ('../song.wav', '/tmp/song.wav', 'song.mp3'):
|
||||
result = self.launch('preset', 'mix', 'voice.wav', 'instrumental.wav',
|
||||
'--output', unsafe)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
(self.media / 'output/linked').symlink_to(self.media / 'input', target_is_directory=True)
|
||||
self.assertNotEqual(self.launch('preset', 'mix', 'linked/voice.wav',
|
||||
'instrumental.wav').returncode, 0)
|
||||
self.create_audio('output/voice.wav')
|
||||
self.assertNotEqual(self.launch('preset', 'mix', 'voice.wav',
|
||||
'instrumental.wav').returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_mix_rejects_missing_audio_stream(self):
|
||||
video = self.create_video()
|
||||
self.create_audio('output/instrumental.wav')
|
||||
result = self.run_preset(self.fake_media_launcher(), 'mix', video.name,
|
||||
'instrumental.wav')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse((self.media / 'output/video1-mix.wav').exists())
|
||||
|
||||
def test_cli_has_no_network_or_host_home(self):
|
||||
result = self.launch('facefusion', 'cli', '--help')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
for flag in ('--network=none', '--pull=never', '--read-only',
|
||||
'--security-opt=no-new-privileges', '--cap-drop=ALL'):
|
||||
self.assertIn(flag, args)
|
||||
self.assertIn(str(self.media / 'input') + ':/work/input:ro,Z', args)
|
||||
self.assertNotIn('--privileged', args)
|
||||
self.assertNotIn('--security-opt', args)
|
||||
self.assertNotIn('label=disable', args)
|
||||
|
||||
def test_gui_exposes_only_wayland_socket(self):
|
||||
self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0')
|
||||
with socket.socket(socket.AF_UNIX) as sock:
|
||||
sock.bind(str(self.root / 'wayland-0'))
|
||||
result = self.launch('rvc', '--foreground')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--network=none', args)
|
||||
self.assertIn(str(self.root / 'wayland-0') + ':/run/media/wayland-0:ro', args)
|
||||
self.assertIn('/run/media:rw,nosuid,nodev,size=1m,mode=1777', args)
|
||||
self.assertFalse(any('uid=' in arg or 'gid=' in arg for arg in args))
|
||||
self.assertNotIn('--publish', args)
|
||||
self.assertFalse(any('dbus' in arg for arg in args))
|
||||
|
||||
def test_rvc_cli_is_offline_and_mounts_only_preset_code(self):
|
||||
result = self.launch('rvc', 'cli', '/work/output/job/audio.wav', '/work/output/job')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--network=none', args)
|
||||
self.assertIn('--entrypoint', args)
|
||||
self.assertIn('python', args)
|
||||
self.assertIn(str(self.root / 'preset_rvc.py') + ':/opt/preset_rvc.py:ro,Z', args)
|
||||
self.assertIn('/opt/preset_rvc.py', args)
|
||||
self.assertNotIn('label=disable', args)
|
||||
|
||||
def test_voice_preset_dispatches_to_user_service(self):
|
||||
(self.media / 'input/video1.mp4').write_bytes(b'not processed in dispatch')
|
||||
runner = self.root / 'systemd-run'
|
||||
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||
runner.chmod(0o755)
|
||||
result = self.launch('preset', 'audio-convert', 'video1.mp4')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--user', args)
|
||||
self.assertIn('--property=Restart=no', args)
|
||||
self.assertIn('audio-convert', args)
|
||||
self.assertIn('video1.mp4', args)
|
||||
|
||||
def test_face_preset_requires_all_sources(self):
|
||||
(self.media / 'input/video1.mp4').write_bytes(b'video')
|
||||
self.assertNotEqual(self.launch('preset', 'video-convert', 'video1.mp4').returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_complete_preset_rejects_local_url(self):
|
||||
result = self.launch('preset', 'convert', 'file:///tmp/video.mp4')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_old_preset_names_are_rejected(self):
|
||||
for name in ('voce', 'volti', 'unisci', 'completo'):
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(self.launch('preset', name, 'video1.mp4').returncode, 2)
|
||||
|
||||
def test_all_url_presets_dispatch_one_background_job(self):
|
||||
for number in range(11, 19):
|
||||
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||
runner = self.root / 'systemd-run'
|
||||
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||
runner.chmod(0o755)
|
||||
(self.media / 'input/audio.wav').write_bytes(b'audio')
|
||||
for preset in ('audio-convert', 'video-convert', 'merge', 'split',
|
||||
'split-stems', 'convert'):
|
||||
with self.subTest(preset=preset):
|
||||
extra = ['audio.wav'] if preset == 'merge' else []
|
||||
result = self.launch('preset', preset, 'https://example.org/video', *extra)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--user', args)
|
||||
self.assertIn(preset, args)
|
||||
self.assertIn('https://example.org/video', args)
|
||||
if extra:
|
||||
self.assertEqual(args[-1], 'audio.wav')
|
||||
self.assertFalse(list((self.media / 'input').glob('download-*')))
|
||||
|
||||
def test_mux_preset_rejects_ambiguous_audio(self):
|
||||
(self.media / 'input/video1.mp4').write_bytes(b'video')
|
||||
(self.media / 'input/audio.wav').write_bytes(b'audio')
|
||||
(self.media / 'output/audio.wav').write_bytes(b'audio')
|
||||
self.assertNotEqual(self.launch('preset', 'merge', 'video1.mp4', 'audio.wav').returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_mux_preset_creates_audio_video_with_streams(self):
|
||||
if subprocess.run(['bash', '-c', 'command -v ffmpeg && command -v ffprobe'],
|
||||
capture_output=True).returncode != 0:
|
||||
self.skipTest('ffmpeg and ffprobe required')
|
||||
self.create_video()
|
||||
audio = self.media / 'input/audio.wav'
|
||||
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi',
|
||||
'-i', 'sine=frequency=440:duration=1', str(audio)], check=True)
|
||||
result = self.run_preset(self.fake_media_launcher(), 'merge', 'video1.mp4', 'audio.wav')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
output = self.media / 'output/video1-unito.mp4'
|
||||
self.assertTrue(output.is_file())
|
||||
self.assertEqual(self.stream_types(output), {'video', 'audio'})
|
||||
|
||||
def test_voice_preset_outputs_audio_only(self):
|
||||
self.create_video(audio=True)
|
||||
result = self.run_preset(self.fake_media_launcher(), 'audio-convert', 'video1.mp4')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
output = self.media / 'output/video1-mia_voce.wav'
|
||||
self.assertEqual(self.stream_types(output), {'audio'})
|
||||
self.assertFalse((self.media / 'output/video1-mia_voce.mp4').exists())
|
||||
|
||||
def test_split_presets_output_separate_streams_without_conversion(self):
|
||||
original = self.create_video(audio=True).read_bytes()
|
||||
for preset in ('split', 'split-stems'):
|
||||
with self.subTest(preset=preset):
|
||||
result = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
output = self.media / 'output' / f'video1-{preset}'
|
||||
expected = {'video.mp4', 'audio.wav'}
|
||||
if preset == 'split-stems':
|
||||
expected |= {'vocals.wav', 'instrumental.wav'}
|
||||
args = json.loads((self.media / 'rvc-args.json').read_text())
|
||||
self.assertIn('--separate-only', args)
|
||||
else:
|
||||
self.assertFalse((self.media / 'rvc-args.json').exists())
|
||||
self.assertEqual({p.name for p in output.iterdir()}, expected)
|
||||
for name in expected:
|
||||
self.assertEqual(self.stream_types(output / name),
|
||||
{'video'} if name == 'video.mp4' else {'audio'})
|
||||
self.assertEqual((self.media / 'input/video1.mp4').read_bytes(), original)
|
||||
self.assertFalse(list((self.media / 'output').rglob('*mia_voce*')))
|
||||
before = {p.name: p.read_bytes() for p in output.iterdir()}
|
||||
repeated = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4',
|
||||
job_id='repeat')
|
||||
self.assertNotEqual(repeated.returncode, 0)
|
||||
self.assertEqual({p.name: p.read_bytes() for p in output.iterdir()}, before)
|
||||
|
||||
def test_split_presets_reject_video_without_audio(self):
|
||||
self.create_video()
|
||||
for preset in ('split', 'split-stems'):
|
||||
result = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(list((self.media / 'output').iterdir()))
|
||||
|
||||
def test_face_preset_preserves_audio_only_when_present(self):
|
||||
for audio in (False, True):
|
||||
with self.subTest(audio=audio):
|
||||
video = self.media / 'input/video1.mp4'
|
||||
if video.exists():
|
||||
video.unlink()
|
||||
self.create_video(audio=audio)
|
||||
for number in range(11, 19):
|
||||
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||
output = self.media / 'output/video1-facefusion.mp4'
|
||||
if output.exists():
|
||||
output.unlink()
|
||||
result = self.run_preset(self.fake_media_launcher(), 'video-convert', 'video1.mp4',
|
||||
job_id=f'test-{audio}')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.stream_types(output),
|
||||
{'video', 'audio'} if audio else {'video'})
|
||||
|
||||
def test_face_preset_uses_requested_options(self):
|
||||
self.create_video(audio=True)
|
||||
for number in range(11, 19):
|
||||
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||
result = self.run_preset(self.fake_media_launcher(), 'video-convert', 'video1.mp4')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads((self.media / 'facefusion-args.json').read_text())
|
||||
source_start = args.index('--source-paths') + 1
|
||||
self.assertEqual(args[source_start:source_start + 8],
|
||||
[f'/work/input/source{number}.jpg' for number in range(11, 19)])
|
||||
expected = {
|
||||
'--processors': ['face_swapper'],
|
||||
'--face-swapper-model': ['hyperswap_1a_256'],
|
||||
'--face-swapper-pixel-boost': ['256x256'],
|
||||
'--face-swapper-weight': ['0.5'],
|
||||
'--face-detector-model': ['yolo_face'],
|
||||
'--face-detector-size': ['640x640'],
|
||||
'--face-detector-angles': ['0', '90', '180', '270'],
|
||||
'--face-detector-score': ['0.5'],
|
||||
'--face-selector-mode': ['one'],
|
||||
'--face-selector-order': ['large-small'],
|
||||
'--face-selector-gender': ['female'],
|
||||
'--face-selector-race': ['white'],
|
||||
'--face-mask-types': ['occlusion', 'region', 'area', 'box'],
|
||||
'--face-occluder-model': ['xseg_1'],
|
||||
'--face-parser-model': ['bisenet_resnet_34'],
|
||||
'--face-mask-blur': ['0.3'],
|
||||
'--output-video-encoder': ['libx264'],
|
||||
'--output-video-preset': ['veryfast'],
|
||||
'--output-video-quality': ['80'],
|
||||
'--output-video-fps': ['30'],
|
||||
'--execution-providers': ['cpu'],
|
||||
'--output-audio-encoder': ['aac'],
|
||||
'--jobs-path': ['/work/state'],
|
||||
'--temp-path': ['/work/state/tmp'],
|
||||
}
|
||||
for flag, values in expected.items():
|
||||
with self.subTest(flag=flag):
|
||||
start = args.index(flag) + 1
|
||||
self.assertEqual(args[start:start + len(values)], values)
|
||||
|
||||
def test_complete_preset_downloads_and_combines_both_results(self):
|
||||
fixture = self.create_video(audio=True)
|
||||
for number in range(11, 19):
|
||||
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||
self.fake_downloader(fixture)
|
||||
result = self.run_preset(self.fake_media_launcher(), 'convert',
|
||||
'https://example.org/video', job_id='test')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue((self.media / 'input/download-test.mp4').is_file())
|
||||
self.assertEqual(self.stream_types(self.media / 'output/download-test-mia_voce.wav'),
|
||||
{'audio'})
|
||||
self.assertEqual(self.stream_types(self.media / 'output/download-test-facefusion.mp4'),
|
||||
{'video', 'audio'})
|
||||
self.assertEqual(self.stream_types(self.media / 'output/download-test-completo.mp4'),
|
||||
{'video', 'audio'})
|
||||
face_args = json.loads((self.media / 'facefusion-args.json').read_text())
|
||||
self.assertEqual(face_args[face_args.index('--face-selector-gender') + 1], 'female')
|
||||
self.assertEqual(face_args[face_args.index('--output-video-fps') + 1], '30')
|
||||
downloader_args = json.loads(self.log.read_text())
|
||||
self.assertIn('--ignore-config', downloader_args)
|
||||
self.assertIn('--no-playlist', downloader_args)
|
||||
|
||||
def test_default_gui_uses_independent_user_service(self):
|
||||
self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0')
|
||||
runner = self.root / 'systemd-run'
|
||||
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||
runner.chmod(0o755)
|
||||
with socket.socket(socket.AF_UNIX) as sock:
|
||||
sock.bind(str(self.root / 'wayland-0'))
|
||||
result = self.launch('rvc')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = json.loads(self.log.read_text())
|
||||
self.assertIn('--user', args)
|
||||
self.assertIn('--unit=ai-media-rvc', args)
|
||||
self.assertIn('--property=Restart=no', args)
|
||||
self.assertIn('--foreground', args)
|
||||
self.assertNotIn('--scope', args)
|
||||
self.assertNotIn('--pty', args)
|
||||
self.assertNotIn('--wait', args)
|
||||
|
||||
def test_all_presets_download_url_before_processing(self):
|
||||
fixture = self.create_video(audio=True)
|
||||
self.fake_downloader(fixture)
|
||||
for number in range(11, 19):
|
||||
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||
audio = self.media / 'input/audio.wav'
|
||||
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-i',
|
||||
str(fixture), '-vn', str(audio)], check=True)
|
||||
outputs = {
|
||||
'audio-convert': 'mia_voce.wav', 'video-convert': 'facefusion.mp4',
|
||||
'merge': 'unito.mp4', 'split': 'split', 'split-stems': 'split-stems',
|
||||
'convert': 'completo.mp4',
|
||||
}
|
||||
for preset, suffix in outputs.items():
|
||||
with self.subTest(preset=preset):
|
||||
extra = ['audio.wav'] if preset == 'merge' else []
|
||||
result = self.run_preset(self.fake_media_launcher(), preset,
|
||||
'https://example.org/video?a=1&b=2', *extra,
|
||||
job_id=preset)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.count('Downloading one video'), 1)
|
||||
self.assertTrue((self.media / f'input/download-{preset}.mp4').is_file())
|
||||
output = self.media / f'output/download-{preset}-{suffix}'
|
||||
self.assertTrue(output.exists())
|
||||
if preset in ('split', 'split-stems'):
|
||||
self.assertEqual(self.stream_types(output / 'video.mp4'), {'video'})
|
||||
self.assertEqual(self.stream_types(output / 'audio.wav'), {'audio'})
|
||||
else:
|
||||
self.assertEqual(self.stream_types(output), {'audio'} if
|
||||
preset == 'audio-convert' else {'video', 'audio'})
|
||||
download_args = json.loads(self.log.read_text())
|
||||
self.assertEqual(download_args[-1], 'https://example.org/video?a=1&b=2')
|
||||
for flag in ('--ignore-config', '--no-playlist', '--no-overwrites'):
|
||||
self.assertIn(flag, download_args)
|
||||
|
||||
def test_convert_also_accepts_local_video_without_download(self):
|
||||
fixture = self.create_video(audio=True)
|
||||
self.fake_downloader(fixture)
|
||||
for number in range(11, 19):
|
||||
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||
result = self.run_preset(self.fake_media_launcher(), 'convert', fixture.name)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertFalse(self.log.exists())
|
||||
self.assertEqual(self.stream_types(self.media / 'output/video1-completo.mp4'),
|
||||
{'video', 'audio'})
|
||||
|
||||
def test_all_presets_reject_invalid_urls_before_dispatch(self):
|
||||
for preset in ('split', 'split-stems', 'audio-convert', 'video-convert',
|
||||
'merge', 'convert'):
|
||||
for url in ('file:///tmp/video.mp4', 'https://localhost/video',
|
||||
'http://192.168.1.1/video', 'https://user:password@example.org/video'):
|
||||
with self.subTest(preset=preset, url=url):
|
||||
extra = ['audio.wav'] if preset == 'merge' else []
|
||||
result = self.launch('preset', preset, url, *extra)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_failed_url_download_does_not_start_processing(self):
|
||||
downloader = self.root / 'yt-dlp'
|
||||
downloader.write_text('#!/bin/sh\nexit 1\n')
|
||||
downloader.chmod(0o755)
|
||||
result = self.run_preset(self.fake_media_launcher(), 'split',
|
||||
'https://example.org/video')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(list((self.media / 'output').iterdir()))
|
||||
|
||||
def test_symlinked_input_is_rejected(self):
|
||||
(self.media / 'input').rmdir()
|
||||
(self.media / 'input').symlink_to(self.root)
|
||||
self.assertNotEqual(self.launch('facefusion', 'cli', '--help').returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_synced_storage_is_rejected(self):
|
||||
directory = self.root / '.config/Nextcloud'
|
||||
directory.mkdir(parents=True)
|
||||
(directory / 'nextcloud.cfg').write_text(
|
||||
'[Accounts]\n0\\Folders\\1\\localPath=' + str(self.media) + '\n'
|
||||
)
|
||||
self.assertNotEqual(self.launch('facefusion', 'cli', '--help').returncode, 0)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
def test_invalid_tool_is_rejected(self):
|
||||
self.assertEqual(self.launch('--network=host').returncode, 2)
|
||||
self.assertFalse(self.log.exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
93
ansible/roles/desktop_ai_media/tests/test_preset_rvc.py
Normal file
93
ansible/roles/desktop_ai_media/tests/test_preset_rvc.py
Normal file
@@ -0,0 +1,93 @@
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
from types import ModuleType
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
|
||||
class SeparationWorkerTest(unittest.TestCase):
|
||||
def test_convert_only_applies_mia_voce_without_importing_separator(self):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'preset_rvc', Path(__file__).resolve().parents[1] / 'files/preset_rvc.py')
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(worker)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
output = root / 'output'
|
||||
job = output / 'job'
|
||||
job.mkdir(parents=True)
|
||||
source = job / 'audio.wav'
|
||||
source.write_bytes(b'audio')
|
||||
weights = root / 'state/weights/mia_voce.pth'
|
||||
index = root / 'state/mia_voce/added_IVF256_Flat_nprobe_1_mia_voce_v2.index'
|
||||
for path in (weights, index):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b'model')
|
||||
|
||||
def mapped_path(value):
|
||||
return root / str(value).removeprefix('/work/') if str(value).startswith(
|
||||
'/work/') else Path(value)
|
||||
|
||||
config = ModuleType('configs.config')
|
||||
config.Config = Mock()
|
||||
vc = ModuleType('infer.vc.modules')
|
||||
voice = Mock()
|
||||
voice.vc_single.return_value = ('Success', (40000, [0.1, 0.2]))
|
||||
vc.VC = Mock(return_value=voice)
|
||||
sf = ModuleType('soundfile')
|
||||
sf.write = Mock(side_effect=lambda path, data, rate: path.write_bytes(b'converted'))
|
||||
modules = {'configs.config': config, 'infer.vc.modules': vc,
|
||||
'soundfile': sf, 'tools.pymss_webui': None}
|
||||
with patch.object(worker, 'Path', mapped_path), \
|
||||
patch.object(sys, 'argv', ['preset_rvc.py', str(source), str(job),
|
||||
'--convert-only']), \
|
||||
patch.dict(sys.modules, modules), patch.dict(os.environ):
|
||||
worker.main()
|
||||
voice.get_vc.assert_called_once_with('mia_voce.pth')
|
||||
self.assertEqual(voice.vc_single.call_args.args[1], str(source))
|
||||
self.assertEqual(voice.vc_single.call_args.args[4], str(index))
|
||||
self.assertEqual((job / 'vocals-mia_voce.wav').read_bytes(), b'converted')
|
||||
self.assertFalse((job / 'vocals').exists())
|
||||
self.assertFalse((job / 'instrumental').exists())
|
||||
|
||||
def test_separate_only_does_not_require_personal_voice_weights(self):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'preset_rvc', Path(__file__).resolve().parents[1] / 'files/preset_rvc.py')
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(worker)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)
|
||||
job = output / 'job'
|
||||
job.mkdir()
|
||||
source = job / 'audio.wav'
|
||||
source.write_bytes(b'fixture')
|
||||
separator = ModuleType('tools.pymss_webui')
|
||||
|
||||
def separate(model, audio, vocals, unused, instrumental, fmt, **kwargs):
|
||||
self.assertEqual(model, 'vocals-bs-roformer-368')
|
||||
self.assertEqual(audio, str(source))
|
||||
(Path(vocals) / 'stem.wav').write_bytes(b'vocals')
|
||||
(Path(instrumental) / 'stem.wav').write_bytes(b'instrumental')
|
||||
yield 'Separated'
|
||||
|
||||
separator.pymss_separate = separate
|
||||
|
||||
def mapped_path(value):
|
||||
return output if str(value) == '/work/output' else Path(value)
|
||||
|
||||
with patch.object(worker, 'Path', mapped_path), \
|
||||
patch.object(sys, 'argv', ['preset_rvc.py', str(source), str(job),
|
||||
'--separate-only']), \
|
||||
patch.dict(sys.modules, {'tools.pymss_webui': separator}), \
|
||||
patch.dict(os.environ):
|
||||
worker.main()
|
||||
self.assertTrue((job / 'vocals/stem.wav').is_file())
|
||||
self.assertTrue((job / 'instrumental/stem.wav').is_file())
|
||||
self.assertFalse((job / 'vocals-mia_voce.wav').exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
183
ansible/roles/desktop_ai_media/tests/test_storage_commands.py
Normal file
183
ansible/roles/desktop_ai_media/tests/test_storage_commands.py
Normal file
@@ -0,0 +1,183 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from jinja2 import Environment
|
||||
|
||||
|
||||
TEMPLATE = Path(__file__).resolve().parents[1] / "templates/ai-media.j2"
|
||||
UUID = "6948c504-2d60-4cc8-9e7f-3ccdf28e80d7"
|
||||
|
||||
|
||||
class StorageCommandsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.media = self.root / "media"
|
||||
for directory in ("input", "output"):
|
||||
(self.media / directory).mkdir(parents=True)
|
||||
env = Environment()
|
||||
env.filters["quote"] = shlex.quote
|
||||
self.launcher = self.root / "ai-media"
|
||||
self.launcher.write_text(env.from_string(TEMPLATE.read_text()).render(
|
||||
desktop_ai_media_root=str(self.media),
|
||||
desktop_ai_media_build_root=str(self.root),
|
||||
desktop_ai_media_external_storage_enabled=True,
|
||||
desktop_ai_media_external_luks_uuid=UUID,
|
||||
desktop_ai_media_external_mountpoint="/run/media/test/Backup",
|
||||
desktop_ai_media_external_source="/run/media/test/Backup/ai-media",
|
||||
))
|
||||
self.state = self.root / "state.json"
|
||||
self.log = self.root / "commands.jsonl"
|
||||
mock = self.root / "mock"
|
||||
mock.write_text('''#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
cmd = Path(sys.argv[0]).name
|
||||
args = sys.argv[1:]
|
||||
state_file = Path(os.environ["STORAGE_TEST_STATE"])
|
||||
state = json.loads(state_file.read_text())
|
||||
root = os.environ["STORAGE_TEST_ROOT"]
|
||||
external = "/run/media/test/Backup"
|
||||
with open(os.environ["STORAGE_TEST_LOG"], "a") as log:
|
||||
log.write(json.dumps([cmd, *args]) + "\\n")
|
||||
if cmd == "sudo":
|
||||
os.execvp(args[0], args)
|
||||
elif cmd == "lsblk":
|
||||
if state.get("missing"):
|
||||
sys.exit(1)
|
||||
print("/dev/sda1 part 8:1")
|
||||
if state.get("unlocked"):
|
||||
print("/dev/dm-0 crypt 252:0")
|
||||
elif cmd == "findmnt":
|
||||
if "--mountpoint" in args:
|
||||
target = args[args.index("--mountpoint") + 1]
|
||||
match = state.get("bind" if target == root else "mounted")
|
||||
if not match:
|
||||
sys.exit(1)
|
||||
print(match)
|
||||
elif "--source" in args:
|
||||
assert args[args.index("--source") + 1] == "252:0"
|
||||
mounts = ([external] if state.get("mounted") else []) + (
|
||||
[root] if state.get("bind") else []) + state.get("other_mounts", [])
|
||||
if not mounts:
|
||||
sys.exit(1)
|
||||
print(*mounts, sep="\\n")
|
||||
else:
|
||||
sys.exit(2)
|
||||
elif cmd == "systemctl":
|
||||
if args[0] == "--user":
|
||||
if state.get("running"):
|
||||
print("ai-media-preset-test.service loaded active running")
|
||||
elif args[0] == "start":
|
||||
state["bind"] = "252:0 /ai-media"
|
||||
elif args[0] == "stop":
|
||||
state.pop("bind", None)
|
||||
elif cmd == "podman":
|
||||
assert args[:3] == ["--remote=false", "ps", "-q"]
|
||||
if state.get("container"):
|
||||
print("abcdef")
|
||||
elif cmd == "udisksctl":
|
||||
if args[0] == "unlock":
|
||||
state["unlocked"] = True
|
||||
elif args[0] == "mount":
|
||||
state["mounted"] = "252:0 /"
|
||||
elif args[0] == "unmount":
|
||||
if state.get("busy"):
|
||||
sys.exit("Device is busy")
|
||||
state.pop("mounted", None)
|
||||
elif args[0] == "lock":
|
||||
assert not state.get("mounted")
|
||||
state.pop("unlocked")
|
||||
state_file.write_text(json.dumps(state))
|
||||
''')
|
||||
mock.chmod(0o755)
|
||||
for command in ("lsblk", "findmnt", "systemctl", "podman", "udisksctl", "sudo"):
|
||||
(self.root / command).symlink_to(mock)
|
||||
self.env = dict(os.environ, PATH=f"{self.root}:{os.environ['PATH']}",
|
||||
STORAGE_TEST_STATE=str(self.state), STORAGE_TEST_LOG=str(self.log),
|
||||
STORAGE_TEST_ROOT=str(self.media))
|
||||
|
||||
def units(self):
|
||||
return [subprocess.check_output(["systemd-escape", "-p", "--suffix=" + suffix, "--", str(self.media)], text=True).strip()
|
||||
for suffix in ("automount", "mount")]
|
||||
|
||||
def launch(self, *args, **state):
|
||||
self.state.write_text(json.dumps(state))
|
||||
self.log.write_text("")
|
||||
result = subprocess.run(["bash", str(self.launcher), *args], env=self.env,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
operations = [row[:2] if row[0] == "systemctl" else row
|
||||
for line in self.log.read_text().splitlines()
|
||||
if (row := json.loads(line))[0] in ("udisksctl", "systemctl", "sudo")]
|
||||
return result, operations
|
||||
|
||||
def test_mount_unlocks_only_the_configured_volume_then_starts_bind(self):
|
||||
result, operations = self.launch("mount")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(operations, [
|
||||
["udisksctl", "unlock", "--block-device", f"/dev/disk/by-uuid/{UUID}"],
|
||||
["udisksctl", "mount", "--block-device", "/dev/dm-0"],
|
||||
["sudo", "systemctl", "start", *self.units()],
|
||||
["systemctl", "start"],
|
||||
])
|
||||
|
||||
def test_mount_does_not_reopen_already_mounted_volume(self):
|
||||
result, operations = self.launch("mount", unlocked=True, mounted="252:0 /")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(operations, [["sudo", "systemctl", "start", *self.units()], ["systemctl", "start"]])
|
||||
|
||||
def test_umount_stops_bind_before_unmount_and_lock(self):
|
||||
result, operations = self.launch("umount", unlocked=True, mounted="252:0 /",
|
||||
bind="252:0 /ai-media")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(operations, [
|
||||
["systemctl", "--user"], ["sudo", "systemctl", "stop", "ai-media-bind-restarter.service", *self.units()], ["systemctl", "stop"],
|
||||
["udisksctl", "unmount", "--block-device", "/dev/dm-0"],
|
||||
["udisksctl", "lock", "--block-device", f"/dev/disk/by-uuid/{UUID}"],
|
||||
])
|
||||
|
||||
def test_umount_refuses_running_jobs_and_containers(self):
|
||||
for condition in ("running", "container"):
|
||||
with self.subTest(condition=condition):
|
||||
result, operations = self.launch("umount", **{condition: True})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("running ai-media jobs", result.stderr)
|
||||
self.assertEqual(operations, [["systemctl", "--user"]])
|
||||
|
||||
def test_umount_does_not_lock_if_busy(self):
|
||||
result, operations = self.launch("umount", unlocked=True, mounted="252:0 /", busy=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(operations[-1][:2], ["udisksctl", "unmount"])
|
||||
|
||||
def test_umount_does_not_touch_other_mounts(self):
|
||||
result, operations = self.launch("umount", unlocked=True, mounted="252:0 /",
|
||||
other_mounts=["/mnt/other"])
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(operations, [["systemctl", "--user"], ["sudo", "systemctl", "stop", "ai-media-bind-restarter.service", *self.units()], ["systemctl", "stop"]])
|
||||
|
||||
def test_rejects_foreign_mount_missing_device_and_extra_arguments(self):
|
||||
for args, state in [
|
||||
(("mount",), {"mounted": "8:2 /"}),
|
||||
(("umount",), {"bind": "8:2 /ai-media"}),
|
||||
(("mount",), {"missing": True}),
|
||||
(("umount", "/dev/sdb"), {}),
|
||||
]:
|
||||
with self.subTest(args=args, state=state):
|
||||
result, operations = self.launch(*args, **state)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(operations, [])
|
||||
|
||||
def test_preset_refuses_local_fallback_when_bind_is_stopped(self):
|
||||
result, operations = self.launch("preset", "split", "test.mp4")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("run ai-media mount first", result.stderr)
|
||||
self.assertEqual(operations, [])
|
||||
134
ansible/roles/desktop_ai_media/vars/models.yml
Normal file
134
ansible/roles/desktop_ai_media/vars/models.yml
Normal file
@@ -0,0 +1,134 @@
|
||||
---
|
||||
desktop_ai_media_public_models:
|
||||
- app: facefusion
|
||||
path: .assets/models/2dfan4.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/2dfan4.hash
|
||||
sha256: e6a6ef99b10b9fdb790c790879ca201f7afbe52560e4379248922324a9d503e8
|
||||
- app: facefusion
|
||||
path: .assets/models/2dfan4.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/2dfan4.onnx
|
||||
sha256: 678c6fa539d52335a31c980feefdf4a6e02d781d83dce00af8a894f114557285
|
||||
- app: facefusion
|
||||
path: .assets/models/arcface_w600k_r50.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/arcface_w600k_r50.hash
|
||||
sha256: e3a6d709939a81fe09e71c7d36f96d54a0deede904e31a38c191a1904e808371
|
||||
- app: facefusion
|
||||
path: .assets/models/arcface_w600k_r50.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/arcface_w600k_r50.onnx
|
||||
sha256: f1f79dc3b0b79a69f94799af1fffebff09fbd78fd96a275fd8f0cbbea23270d1
|
||||
- app: facefusion
|
||||
path: .assets/models/bisenet_resnet_34.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/bisenet_resnet_34.hash
|
||||
sha256: bfca5e43ca55110701ab691d864cacfddccad324dc42043aea8c001a949ce1f8
|
||||
- app: facefusion
|
||||
path: .assets/models/bisenet_resnet_34.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/bisenet_resnet_34.onnx
|
||||
sha256: 4a0b8c958a3c938913bd06a8365dbb3c8761afba6ecbf0d14b3b1f77eb230c96
|
||||
- app: facefusion
|
||||
path: .assets/models/fairface.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fairface.hash
|
||||
sha256: e232c933114a6c9ce446195e4a96bf1c3327dd31c13165849cd00f9f19a2ea62
|
||||
- app: facefusion
|
||||
path: .assets/models/fairface.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fairface.onnx
|
||||
sha256: b176b1e4b0739496e7943af7ba4ff306271fecf837bca5ec5d9a48201959db37
|
||||
- app: facefusion
|
||||
path: .assets/models/fan_68_5.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fan_68_5.hash
|
||||
sha256: 092d902410959b3ce01294d7c1ad157f1c602e3918238117e7ef87157be9534e
|
||||
- app: facefusion
|
||||
path: .assets/models/fan_68_5.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fan_68_5.onnx
|
||||
sha256: ea05f7d9d014ae1d9cdc6e9c72643d8f00d198b5db3fdd384148ddff499a613e
|
||||
- app: facefusion
|
||||
path: .assets/models/hyperswap_1a_256.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/hyperswap_1a_256.hash
|
||||
sha256: 70b33d0a9d6044847d9b29f9d08ce7afc140a2cada5b4b5f532bbd6440ba48c1
|
||||
- app: facefusion
|
||||
path: .assets/models/hyperswap_1a_256.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/hyperswap_1a_256.onnx
|
||||
sha256: c0e98a8a03a238f461ed3d2570e426b49f46745ee400854a60dceeb70c246add
|
||||
- app: facefusion
|
||||
path: .assets/models/kim_vocal_2.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/kim_vocal_2.hash
|
||||
sha256: fcd81ca30adf430b697fe58d60183031173c8ab0ca82efef308d652b1afb4197
|
||||
- app: facefusion
|
||||
path: .assets/models/kim_vocal_2.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/kim_vocal_2.onnx
|
||||
sha256: fbde1fd7d35a6b1785add2225ce03255a01ccef6c8a5fb7b2ccd4e0c1e9097f7
|
||||
- app: facefusion
|
||||
path: .assets/models/nsfw_1.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_1.hash
|
||||
sha256: 48c61a15ffcda1ae9e6d4c790224072c8e5648d4ba2f767cf4cfe0be7e282853
|
||||
- app: facefusion
|
||||
path: .assets/models/nsfw_1.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_1.onnx
|
||||
sha256: 3debfd72763bc931dd308f57d1e9299ae13bb309d14ddbdc17ce8f1fd42f96af
|
||||
- app: facefusion
|
||||
path: .assets/models/nsfw_2.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_2.hash
|
||||
sha256: 64cbc0c1a4d72e181fae364281b6d2130be3b87d5784909c5a29adf436f09a01
|
||||
- app: facefusion
|
||||
path: .assets/models/nsfw_2.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_2.onnx
|
||||
sha256: 5aae1806ce44e3c27fab0a7d44eed581dd25ca71a4387ff809a191c98239c1be
|
||||
- app: facefusion
|
||||
path: .assets/models/nsfw_3.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_3.hash
|
||||
sha256: b15c591d8177511959174a0c6761827e3bf9c0aa1d63aaa79645d9fc9a4e774b
|
||||
- app: facefusion
|
||||
path: .assets/models/nsfw_3.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_3.onnx
|
||||
sha256: 778139fb930240ac39812a1480295bfc5dc2cec8a8e46ee6b453481d600c0fa2
|
||||
- app: facefusion
|
||||
path: .assets/models/xseg_1.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.1.0/xseg_1.hash
|
||||
sha256: da3648ccecaa79f3be5ca0e1c3713f775504dd5c5dff716c095925132c02b08e
|
||||
- app: facefusion
|
||||
path: .assets/models/xseg_1.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.1.0/xseg_1.onnx
|
||||
sha256: c4d1498b8a03b5fe2a3a5d2ef2a0402ab03bd51edaf5b2d8d5fb764702a97dd3
|
||||
- app: facefusion
|
||||
path: .assets/models/yoloface_8n.hash
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/yoloface_8n.hash
|
||||
sha256: 7a4bd7e1a8cd938db2234dba41d4a8b7719bedbf7496d35510927cbd4b71683f
|
||||
- app: facefusion
|
||||
path: .assets/models/yoloface_8n.onnx
|
||||
url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/yoloface_8n.onnx
|
||||
sha256: 821cdbb1e65fbbabdde7dd0933f754797a343e56fd962729c61ffcefcd135929
|
||||
- app: rvc
|
||||
path: assets/hubert_base/config.json
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/config.json
|
||||
sha256: 0346950779dfb7f9316fa74ed846e2b8a22a08eedfdc5387b73f327cb1a4a7cf
|
||||
- app: rvc
|
||||
path: assets/hubert_base/preprocessor_config.json
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/preprocessor_config.json
|
||||
sha256: 7c1976a680fb7acc757cd36fb08eef878fa36c70b4c9d2d595df9c608bbbbf0e
|
||||
- app: rvc
|
||||
path: assets/hubert_base/pytorch_model.bin
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/pytorch_model.bin
|
||||
sha256: cc8c20f4b90a520757260197a3ff2505705a7adbd20ad9eeaa4e1a9b38442ef5
|
||||
- app: rvc
|
||||
path: assets/rmvpe/rmvpe.pt
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/rmvpe.pt
|
||||
sha256: 6d62215f4306e3ca278246188607209f09af3dc77ed4232efdd069798c4ec193
|
||||
- app: rvc
|
||||
path: assets/mute.zip
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/mute.zip
|
||||
sha256: ee948e85213e4ed2f2ba2f8dfcee810bfd0b63131d91450e920bbe1cbd0321d0
|
||||
- app: rvc
|
||||
path: assets/pretrained_v2/f0D40k.pth
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pretrained_v2/f0D40k.pth
|
||||
sha256: 6b6ab091e70801b28e3f41f335f2fc5f3f35c75b39ae2628d419644ec2b0fa09
|
||||
- app: rvc
|
||||
path: assets/pretrained_v2/f0G40k.pth
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pretrained_v2/f0G40k.pth
|
||||
sha256: 3b2c44035e782c4b14ddc0bede9e2f4a724d025cd073f736d4f43708453adfcb
|
||||
- app: rvc
|
||||
path: assets/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.ckpt
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.ckpt
|
||||
sha256: 97c9e1011924ff647d147b474638c161b80586fd5b9e83fab59cbbb70014bf62
|
||||
- app: rvc
|
||||
path: assets/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.yaml
|
||||
url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.yaml
|
||||
sha256: 105fd8e6a1ef1b038db2aa657a9f9696283d506dbc815bd7134a57aa80ec9f10
|
||||
4
ansible/roles/devcontainer_generator/defaults/main.yml
Normal file
4
ansible/roles/devcontainer_generator/defaults/main.yml
Normal file
@@ -0,0 +1,4 @@
|
||||
---
|
||||
devcontainer_generator_go_binary: /usr/bin/go
|
||||
devcontainer_generator_install_go: true
|
||||
devcontainer_generator_build_dir: "{{ user_home }}/.cache/infra/devcontainer-generator"
|
||||
64
ansible/roles/devcontainer_generator/tasks/main.yml
Normal file
64
ansible/roles/devcontainer_generator/tasks/main.yml
Normal file
@@ -0,0 +1,64 @@
|
||||
---
|
||||
- name: Install Go compiler for the devcontainer generator
|
||||
ansible.builtin.dnf:
|
||||
name: golang
|
||||
state: present
|
||||
when: devcontainer_generator_install_go | bool
|
||||
|
||||
- name: Ensure devcontainer generator directories exist
|
||||
ansible.builtin.file:
|
||||
path: "{{ item }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
loop:
|
||||
- "{{ user_home }}/.local/bin"
|
||||
- "{{ devcontainer_generator_build_dir }}"
|
||||
|
||||
- name: Copy devcontainer generator sources
|
||||
ansible.builtin.copy:
|
||||
src: "{{ playbook_dir }}/../cmd/devcontainer/"
|
||||
dest: "{{ devcontainer_generator_build_dir }}/src/"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: preserve
|
||||
|
||||
- name: Build devcontainer generator for the target host
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- "{{ devcontainer_generator_go_binary }}"
|
||||
- build
|
||||
- -trimpath
|
||||
- -buildvcs=false
|
||||
- -o
|
||||
- "{{ devcontainer_generator_build_dir }}/devcontainer"
|
||||
- .
|
||||
chdir: "{{ devcontainer_generator_build_dir }}/src"
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
GOCACHE: "{{ devcontainer_generator_build_dir }}/go-cache"
|
||||
GOTOOLCHAIN: local
|
||||
GOPROXY: "off"
|
||||
GOSUMDB: "off"
|
||||
CGO_ENABLED: "0"
|
||||
# Compilation refreshes a cached artifact; copy below reports installation changes.
|
||||
changed_when: false
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Install devcontainer generator in the user PATH
|
||||
ansible.builtin.copy:
|
||||
src: "{{ devcontainer_generator_build_dir }}/devcontainer"
|
||||
remote_src: true
|
||||
dest: "{{ user_home }}/.local/bin/devcontainer"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Explain devcontainer generator check-mode behavior
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
Check mode validates package and source deployment only. Compilation and
|
||||
installation of {{ user_home }}/.local/bin/devcontainer require a normal run.
|
||||
when: ansible_check_mode
|
||||
@@ -91,6 +91,20 @@
|
||||
loop_control:
|
||||
label: "{{ item.dest }}"
|
||||
|
||||
- name: Ensure AI coding-agent dotfile parent directories exist
|
||||
tags: [dotfiles, dotfiles:common, ai_agents]
|
||||
ansible.builtin.file:
|
||||
path: "{{ (effective_user_home ~ '/' ~ item.dest) | dirname }}"
|
||||
state: directory
|
||||
owner: "{{ effective_username }}"
|
||||
group: "{{ effective_user_group }}"
|
||||
mode: "0755"
|
||||
loop: "{{ ai_agents_dotfiles | default([]) }}"
|
||||
loop_control:
|
||||
label: "{{ item.dest }}"
|
||||
when:
|
||||
- (item.agents | intersect(ai_agents_deploy_enabled_names)) | length > 0
|
||||
|
||||
- name: Deploy AI coding-agent dotfiles
|
||||
tags: [dotfiles, dotfiles:common, ai_agents]
|
||||
ansible.builtin.copy:
|
||||
|
||||
92
ansible/roles/packages_fedora/tasks/chatgpt_desktop.yml
Normal file
92
ansible/roles/packages_fedora/tasks/chatgpt_desktop.yml
Normal file
@@ -0,0 +1,92 @@
|
||||
---
|
||||
# ChatGPT desktop is installed from OpenAI's signed RPM repository; removal
|
||||
# must clean up the package, the managed repository and its signing key.
|
||||
- name: Validate ChatGPT desktop architecture on Fedora
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- ansible_facts['architecture'] in chatgpt_desktop_supported_architectures
|
||||
- ansible_facts['distribution_major_version'] in chatgpt_desktop_supported_fedora_versions
|
||||
fail_msg: >-
|
||||
ChatGPT desktop supports Fedora {{ chatgpt_desktop_supported_fedora_versions | join(' and ') }}
|
||||
on x86_64 or aarch64; detected Fedora {{ ansible_facts['distribution_major_version'] }}
|
||||
on {{ ansible_facts['architecture'] }}.
|
||||
when: chatgpt_desktop_install_enabled | default(false) | bool
|
||||
|
||||
- name: Install ChatGPT desktop RPM signing key
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.copy:
|
||||
src: "{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
dest: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
when: chatgpt_desktop_install_enabled | default(false) | bool
|
||||
|
||||
- name: Import ChatGPT desktop RPM signing key
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.rpm_key:
|
||||
state: present
|
||||
key: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
when: chatgpt_desktop_install_enabled | default(false) | bool
|
||||
|
||||
- name: Configure ChatGPT desktop RPM repository
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.yum_repository:
|
||||
name: openai-chatgpt
|
||||
description: ChatGPT
|
||||
baseurl: "{{ chatgpt_desktop_rpm_repository }}"
|
||||
enabled: true
|
||||
gpgcheck: true
|
||||
repo_gpgcheck: true
|
||||
gpgkey: "file:///etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
state: present
|
||||
when: chatgpt_desktop_install_enabled | default(false) | bool
|
||||
|
||||
- name: Install ChatGPT desktop on selected Fedora hosts
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.dnf:
|
||||
name: chatgpt
|
||||
state: latest
|
||||
update_cache: true
|
||||
when: chatgpt_desktop_install_enabled | default(false) | bool
|
||||
|
||||
- name: Check for the installed ChatGPT desktop signing key
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.stat:
|
||||
path: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
get_checksum: false
|
||||
register: chatgpt_desktop_signing_key
|
||||
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Remove ChatGPT desktop from selected Fedora hosts
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.dnf:
|
||||
name: chatgpt
|
||||
state: absent
|
||||
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Remove ChatGPT desktop RPM repository
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.yum_repository:
|
||||
name: openai-chatgpt
|
||||
state: absent
|
||||
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
# rpm_key reads the identifier from the key file, so only remove the key from
|
||||
# the RPM database while the deployed file is still present.
|
||||
- name: Remove ChatGPT desktop RPM signing key from the RPM database
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.rpm_key:
|
||||
state: absent
|
||||
key: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
when:
|
||||
- chatgpt_desktop_uninstall_enabled | default(false) | bool
|
||||
- chatgpt_desktop_signing_key.stat.exists | default(false)
|
||||
|
||||
- name: Remove ChatGPT desktop RPM signing key file
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.file:
|
||||
path: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
state: absent
|
||||
when: chatgpt_desktop_uninstall_enabled | default(false) | bool
|
||||
78
ansible/roles/packages_fedora/tasks/cline_desktop.yml
Normal file
78
ansible/roles/packages_fedora/tasks/cline_desktop.yml
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
# Cline Desktop ships unsigned RPMs from its GitHub releases; only the
|
||||
# checksum-verified download makes the local installation trustworthy.
|
||||
- name: Validate Cline Desktop architecture on Fedora
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- ansible_facts['architecture'] in cline_desktop_rpm_checksums
|
||||
fail_msg: "No verified Cline Desktop RPM for {{ ansible_facts['architecture'] }}."
|
||||
when: cline_desktop_install_enabled | default(false) | bool
|
||||
|
||||
# Runs for both flows so the register below is always valid.
|
||||
- name: Check for cached Cline Desktop RPM
|
||||
ansible.builtin.stat:
|
||||
path: "{{ cline_desktop_rpm_path }}"
|
||||
get_checksum: false
|
||||
register: cline_desktop_rpm_cache
|
||||
|
||||
- name: Download verified Cline Desktop RPM
|
||||
ansible.builtin.get_url:
|
||||
url: "{{ cline_desktop_rpm_url }}"
|
||||
dest: "{{ cline_desktop_rpm_path }}"
|
||||
checksum: "{{ cline_desktop_rpm_checksums[ansible_facts['architecture']] }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
# get_url only sends HEAD in check mode and cannot populate a cold cache.
|
||||
when:
|
||||
- cline_desktop_install_enabled | default(false) | bool
|
||||
- not ansible_check_mode
|
||||
|
||||
- name: Install Cline Desktop on Fedora
|
||||
ansible.builtin.dnf:
|
||||
name: "{{ cline_desktop_rpm_path }}"
|
||||
state: present
|
||||
# Upstream ships an unsigned RPM. The download above verifies its pinned
|
||||
# SHA-256; do not disable signature checks in system repository settings.
|
||||
disable_gpg_check: true
|
||||
when:
|
||||
- cline_desktop_install_enabled | default(false) | bool
|
||||
- not ansible_check_mode
|
||||
or cline_desktop_rpm_cache.stat.exists
|
||||
|
||||
- name: Explain Cline Desktop cold-cache check-mode limitation
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
A real run will download and SHA-256 verify Cline Desktop
|
||||
{{ cline_desktop_version }} before ensuring it is installed.
|
||||
The RPM is not cached, so this dry run cannot validate DNF dependencies.
|
||||
when:
|
||||
- cline_desktop_install_enabled | default(false) | bool
|
||||
- ansible_check_mode
|
||||
- not cline_desktop_rpm_cache.stat.exists
|
||||
|
||||
# The `cline` RPM package name is verified from the pinned release header;
|
||||
# removal never touches the npm-managed cline CLI or user data.
|
||||
- name: Remove Cline Desktop from Fedora
|
||||
ansible.builtin.dnf:
|
||||
name: cline
|
||||
state: absent
|
||||
when: cline_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
# Clean every cached download so retirement also removes outdated pins.
|
||||
- name: Find cached Cline Desktop RPM downloads
|
||||
ansible.builtin.find:
|
||||
paths: /var/cache
|
||||
patterns: "cline-desktop-*.rpm"
|
||||
file_type: file
|
||||
register: cline_desktop_cached_rpms
|
||||
when: cline_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Remove cached Cline Desktop RPM downloads
|
||||
ansible.builtin.file:
|
||||
path: "{{ item.path }}"
|
||||
state: absent
|
||||
loop: "{{ cline_desktop_cached_rpms.files | default([]) }}"
|
||||
loop_control:
|
||||
label: "{{ item.path }}"
|
||||
when: cline_desktop_uninstall_enabled | default(false) | bool
|
||||
@@ -25,20 +25,6 @@
|
||||
- "'workstation_dev_fedora' in group_names"
|
||||
- fedora_manage_docker_repo | default(false)
|
||||
|
||||
- name: Install COPR support on Fedora WSL
|
||||
tags: [packages, mise]
|
||||
ansible.builtin.dnf:
|
||||
name: dnf-plugins-core
|
||||
state: present
|
||||
when: "'workstation_dev_wsl' in group_names"
|
||||
|
||||
- name: Configure Mise COPR repository on Fedora WSL
|
||||
tags: [packages, mise]
|
||||
community.general.copr:
|
||||
name: jdxcode/mise
|
||||
state: enabled
|
||||
when: "'workstation_dev_wsl' in group_names"
|
||||
|
||||
- name: Install distribution signing keys for Fedora desktop codecs
|
||||
tags: [packages, heic]
|
||||
ansible.builtin.dnf:
|
||||
@@ -66,12 +52,16 @@
|
||||
ansible.builtin.dnf:
|
||||
update_cache: true
|
||||
|
||||
- name: Install HEIC decoder on Fedora desktops
|
||||
- name: Install HEIC decoder when RPM Fusion has a compatible build
|
||||
tags: [packages, heic]
|
||||
ansible.builtin.dnf:
|
||||
name: libheif-freeworld
|
||||
state: present
|
||||
update_cache: true
|
||||
# libheif-freeworld requires the exact libheif build. RPM Fusion can lag
|
||||
# Fedora Updates, so retry on later runs instead of blocking all desktop
|
||||
# package convergence while the matching build is unavailable.
|
||||
skip_broken: true
|
||||
when: "'graphical_desktop' in group_names"
|
||||
|
||||
- name: Install packages on Fedora
|
||||
@@ -140,6 +130,10 @@
|
||||
name: "{{ item.value.npm_package }}"
|
||||
global: true
|
||||
state: latest
|
||||
register: ai_agent_npm_install
|
||||
retries: "{{ ai_agents_npm_install_retries }}"
|
||||
delay: "{{ ai_agents_npm_install_retry_delay }}"
|
||||
until: ai_agent_npm_install is succeeded
|
||||
loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}"
|
||||
when:
|
||||
- item.value.install_enabled | bool
|
||||
@@ -160,55 +154,29 @@
|
||||
loop_control:
|
||||
label: "{{ item.key }}"
|
||||
|
||||
- name: Validate ChatGPT desktop architecture on Fedora
|
||||
- name: Manage ChatGPT desktop lifecycle on Fedora graphical hosts
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- ansible_facts['architecture'] in chatgpt_desktop_supported_architectures
|
||||
- ansible_facts['distribution_major_version'] in chatgpt_desktop_supported_fedora_versions
|
||||
fail_msg: >-
|
||||
ChatGPT desktop supports Fedora {{ chatgpt_desktop_supported_fedora_versions | join(' and ') }}
|
||||
on x86_64 or aarch64; detected Fedora {{ ansible_facts['distribution_major_version'] }}
|
||||
on {{ ansible_facts['architecture'] }}.
|
||||
when: chatgpt_desktop_enabled | bool
|
||||
ansible.builtin.import_tasks: chatgpt_desktop.yml
|
||||
when:
|
||||
- "'graphical_desktop' in group_names"
|
||||
- chatgpt_desktop_install_enabled | default(false) | bool
|
||||
or chatgpt_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Install ChatGPT desktop RPM signing key
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.copy:
|
||||
src: "{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
dest: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
when: chatgpt_desktop_enabled | bool
|
||||
- name: Manage OpenCode Desktop lifecycle on Fedora graphical hosts
|
||||
tags: [packages, opencode_desktop]
|
||||
ansible.builtin.import_tasks: opencode_desktop.yml
|
||||
when:
|
||||
- "'graphical_desktop' in group_names"
|
||||
- opencode_desktop_install_enabled | default(false) | bool
|
||||
or opencode_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Import ChatGPT desktop RPM signing key
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.rpm_key:
|
||||
state: present
|
||||
key: "/etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
when: chatgpt_desktop_enabled | bool
|
||||
|
||||
- name: Configure ChatGPT desktop RPM repository
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.yum_repository:
|
||||
name: openai-chatgpt
|
||||
description: ChatGPT
|
||||
baseurl: "{{ chatgpt_desktop_rpm_repository }}"
|
||||
enabled: true
|
||||
gpgcheck: true
|
||||
repo_gpgcheck: true
|
||||
gpgkey: "file:///etc/pki/rpm-gpg/{{ chatgpt_desktop_rpm_gpg_key }}"
|
||||
state: present
|
||||
when: chatgpt_desktop_enabled | bool
|
||||
|
||||
- name: Install ChatGPT desktop on selected Fedora hosts
|
||||
tags: [packages, chatgpt]
|
||||
ansible.builtin.dnf:
|
||||
name: chatgpt
|
||||
state: latest
|
||||
update_cache: true
|
||||
when: chatgpt_desktop_enabled | bool
|
||||
- name: Manage Cline Desktop lifecycle on Fedora graphical hosts
|
||||
tags: [packages, cline_desktop]
|
||||
ansible.builtin.import_tasks: cline_desktop.yml
|
||||
when:
|
||||
- "'graphical_desktop' in group_names"
|
||||
- cline_desktop_install_enabled | default(false) | bool
|
||||
or cline_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Define Fedora Flatpak applications
|
||||
tags: [packages]
|
||||
|
||||
78
ansible/roles/packages_fedora/tasks/opencode_desktop.yml
Normal file
78
ansible/roles/packages_fedora/tasks/opencode_desktop.yml
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
# OpenCode Desktop ships unsigned RPMs from its GitHub releases; only the
|
||||
# checksum-verified download makes the local installation trustworthy.
|
||||
- name: Validate OpenCode Desktop architecture on Fedora
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- ansible_facts['architecture'] in opencode_desktop_rpm_checksums
|
||||
fail_msg: "No verified OpenCode Desktop RPM for {{ ansible_facts['architecture'] }}."
|
||||
when: opencode_desktop_install_enabled | default(false) | bool
|
||||
|
||||
# Runs for both flows so the register below is always valid.
|
||||
- name: Check for cached OpenCode Desktop RPM
|
||||
ansible.builtin.stat:
|
||||
path: "{{ opencode_desktop_rpm_path }}"
|
||||
get_checksum: false
|
||||
register: opencode_desktop_rpm_cache
|
||||
|
||||
- name: Download verified OpenCode Desktop RPM
|
||||
ansible.builtin.get_url:
|
||||
url: "{{ opencode_desktop_rpm_url }}"
|
||||
dest: "{{ opencode_desktop_rpm_path }}"
|
||||
checksum: "{{ opencode_desktop_rpm_checksums[ansible_facts['architecture']] }}"
|
||||
owner: root
|
||||
group: root
|
||||
mode: "0644"
|
||||
# get_url only sends HEAD in check mode and cannot populate a cold cache.
|
||||
when:
|
||||
- opencode_desktop_install_enabled | default(false) | bool
|
||||
- not ansible_check_mode
|
||||
|
||||
- name: Install OpenCode Desktop on Fedora
|
||||
ansible.builtin.dnf:
|
||||
name: "{{ opencode_desktop_rpm_path }}"
|
||||
state: present
|
||||
# Upstream ships an unsigned RPM. The download above verifies its pinned
|
||||
# SHA-256; do not disable signature checks in system repository settings.
|
||||
disable_gpg_check: true
|
||||
when:
|
||||
- opencode_desktop_install_enabled | default(false) | bool
|
||||
- not ansible_check_mode
|
||||
or opencode_desktop_rpm_cache.stat.exists
|
||||
|
||||
- name: Explain OpenCode Desktop cold-cache check-mode limitation
|
||||
ansible.builtin.debug:
|
||||
msg: >-
|
||||
A real run will download and SHA-256 verify OpenCode Desktop
|
||||
{{ opencode_desktop_version }} before ensuring it is installed.
|
||||
The RPM is not cached, so this dry run cannot validate DNF dependencies.
|
||||
when:
|
||||
- opencode_desktop_install_enabled | default(false) | bool
|
||||
- ansible_check_mode
|
||||
- not opencode_desktop_rpm_cache.stat.exists
|
||||
|
||||
# The `opencode` RPM package name is verified from the pinned release header;
|
||||
# removal never touches the npm-managed opencode-ai CLI or user data.
|
||||
- name: Remove OpenCode Desktop from Fedora
|
||||
ansible.builtin.dnf:
|
||||
name: opencode
|
||||
state: absent
|
||||
when: opencode_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
# Clean every cached download so retirement also removes outdated pins.
|
||||
- name: Find cached OpenCode Desktop RPM downloads
|
||||
ansible.builtin.find:
|
||||
paths: /var/cache
|
||||
patterns: "opencode-desktop-*.rpm"
|
||||
file_type: file
|
||||
register: opencode_desktop_cached_rpms
|
||||
when: opencode_desktop_uninstall_enabled | default(false) | bool
|
||||
|
||||
- name: Remove cached OpenCode Desktop RPM downloads
|
||||
ansible.builtin.file:
|
||||
path: "{{ item.path }}"
|
||||
state: absent
|
||||
loop: "{{ opencode_desktop_cached_rpms.files | default([]) }}"
|
||||
loop_control:
|
||||
label: "{{ item.path }}"
|
||||
when: opencode_desktop_uninstall_enabled | default(false) | bool
|
||||
@@ -106,6 +106,14 @@
|
||||
state: present
|
||||
update_cache: false
|
||||
|
||||
- name: Remove excluded packages on Void Linux
|
||||
tags: [packages]
|
||||
community.general.xbps:
|
||||
name: "{{ void_removed_packages | default([]) }}"
|
||||
state: absent
|
||||
update_cache: false
|
||||
when: (void_removed_packages | default([])) | length > 0
|
||||
|
||||
- name: Check whether the selected display manager is active
|
||||
tags: [packages, display-manager]
|
||||
ansible.builtin.stat:
|
||||
|
||||
@@ -18,6 +18,11 @@ atlas_nextcloud_redis_image: ""
|
||||
atlas_onlyoffice_image: ""
|
||||
atlas_nextcloud_backup_root: "{{ atlas_mount_root }}/backup/nextcloud"
|
||||
atlas_nextcloud_backup_keep: 2
|
||||
# A structurally complete bundle from an earlier verified run younger than
|
||||
# this many seconds is reused instead of re-preparing. Keep it below 24h so
|
||||
# the nightly Borg run, spaced 24h plus its randomized delay, always refreshes
|
||||
# the bundle; 0 disables reuse.
|
||||
atlas_nextcloud_backup_reuse_max_seconds: 72000
|
||||
atlas_nextcloud_admin: admin
|
||||
atlas_nextcloud_users: []
|
||||
atlas_nextcloud_apps: []
|
||||
@@ -297,3 +302,58 @@ atlas_media_quadlet_services:
|
||||
- atlas-immich-machine-learning.service
|
||||
- atlas-immich-server.service
|
||||
- atlas-npm.service
|
||||
|
||||
atlas_manage_qbittorrent: false
|
||||
atlas_qbittorrent_image: CHANGEME_PINNED_QBITTORRENT_IMAGE
|
||||
atlas_qbittorrent_state_dir: "{{ atlas_app_data_mountpoint }}/qbittorrent"
|
||||
atlas_qbittorrent_downloads_dir: "{{ atlas_archive_mountpoint }}/Downloads"
|
||||
atlas_qbittorrent_web_port: 8090
|
||||
|
||||
atlas_qbittorrent_reverse_proxy_enabled: false
|
||||
atlas_qbittorrent_public_domain: CHANGEME_QBITTORRENT_DOMAIN
|
||||
atlas_qbittorrent_web_settings:
|
||||
- {key: 'WebUI\ServerDomains', value: "{{ atlas_qbittorrent_public_domain }}"}
|
||||
- {key: 'WebUI\ReverseProxySupportEnabled', value: "true"}
|
||||
- {key: 'WebUI\TrustedReverseProxiesList', value: "{{ atlas_aegis_ip }}"}
|
||||
- {key: 'WebUI\HostHeaderValidation', value: "true"}
|
||||
- {key: 'WebUI\CSRFProtection', value: "true"}
|
||||
- {key: 'WebUI\LocalHostAuth', value: "true"}
|
||||
- {key: 'WebUI\AuthSubnetWhitelistEnabled', value: "false"}
|
||||
|
||||
atlas_manage_aria2: false
|
||||
atlas_aria2_gateway_enabled: false
|
||||
atlas_aria2_gateway_port: 8092
|
||||
atlas_aria2_public_domain: CHANGEME_ARIA2_DOMAIN
|
||||
atlas_aria2_state_dir: "{{ atlas_app_data_mountpoint }}/aria2"
|
||||
atlas_aria2_downloads_dir: "{{ atlas_archive_mountpoint }}/Downloads"
|
||||
atlas_aria2_rpc_port: 6800
|
||||
atlas_ariang_web_port: 8091
|
||||
atlas_aria2_image: CHANGEME_PINNED_ARIA2_IMAGE
|
||||
atlas_ariang_image: CHANGEME_PINNED_ARIANG_IMAGE
|
||||
|
||||
# Rootless Paperless-ngx document management. Secrets live only in the encrypted Vault.
|
||||
atlas_manage_paperless: false
|
||||
atlas_paperless_dataset: "{{ atlas_zfs_pool }}/services/data/paperless"
|
||||
atlas_paperless_root: "{{ atlas_app_data_mountpoint }}/paperless"
|
||||
atlas_paperless_private_dir: "{{ atlas_admin_home }}/.config/atlas-paperless"
|
||||
atlas_paperless_quadlet_dir: "{{ atlas_admin_home }}/.config/containers/systemd"
|
||||
atlas_paperless_domain: ""
|
||||
atlas_paperless_http_port: 8002
|
||||
atlas_paperless_network_subnet: 10.90.11.0/24
|
||||
atlas_paperless_network_gateway: 10.90.11.1
|
||||
atlas_paperless_ocr_language: ita+eng
|
||||
atlas_paperless_image: ""
|
||||
atlas_paperless_postgres_image: ""
|
||||
atlas_paperless_valkey_image: ""
|
||||
atlas_paperless_tika_image: ""
|
||||
atlas_paperless_gotenberg_image: ""
|
||||
atlas_paperless_ollama_image: ""
|
||||
atlas_paperless_llm_model: qwen2.5:1.5b-instruct-q4_K_M
|
||||
atlas_paperless_embedding_model: nomic-embed-text:v1.5
|
||||
atlas_paperless_services:
|
||||
- atlas-paperless-db.service
|
||||
- atlas-paperless-valkey.service
|
||||
- atlas-paperless-tika.service
|
||||
- atlas-paperless-gotenberg.service
|
||||
- atlas-paperless-ollama.service
|
||||
- atlas-paperless.service
|
||||
|
||||
131
ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py
Normal file
131
ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py
Normal file
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/python3
|
||||
"""Private NPM-only JSON-RPC adapter. Never serves the secret to browsers."""
|
||||
import argparse
|
||||
import copy
|
||||
import http.client
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
MAX_BODY = 2 * 1024 * 1024
|
||||
|
||||
|
||||
def inject(request, token, depth=0):
|
||||
if depth > 4 or not isinstance(request, dict):
|
||||
raise ValueError('Invalid RPC request')
|
||||
result = copy.deepcopy(request)
|
||||
method = result.get('method', result.get('methodName'))
|
||||
params = result.setdefault('params', [])
|
||||
if not isinstance(method, str) or not isinstance(params, list):
|
||||
raise ValueError('Invalid RPC method or params')
|
||||
if method == 'system.multicall':
|
||||
if len(params) != 1 or not isinstance(params[0], list) or len(params[0]) > 128:
|
||||
raise ValueError('Invalid multicall')
|
||||
result['params'] = [[inject(item, token, depth + 1) for item in params[0]]]
|
||||
elif method.startswith('aria2.'):
|
||||
if params and isinstance(params[0], str) and params[0].startswith('token:'):
|
||||
params.pop(0)
|
||||
# Keep RPC security configuration owned by Ansible, not remote callers.
|
||||
if method in ('aria2.changeGlobalOption', 'aria2.changeOption'):
|
||||
for value in params:
|
||||
if isinstance(value, dict) and any(key.startswith('rpc-') for key in value):
|
||||
raise ValueError('RPC security options are not editable')
|
||||
params.insert(0, 'token:' + token)
|
||||
elif method not in ('system.listMethods', 'system.listNotifications'):
|
||||
raise ValueError('Unsupported RPC method')
|
||||
return result
|
||||
|
||||
|
||||
def sanitize(value, token):
|
||||
if isinstance(value, dict):
|
||||
return {key: sanitize(item, token) for key, item in value.items()
|
||||
if key not in ('rpc-secret', 'rpc-passwd', 'rpc-user')}
|
||||
if isinstance(value, list):
|
||||
return [sanitize(item, token) for item in value]
|
||||
if isinstance(value, str):
|
||||
return value.replace(token, '[redacted]')
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--listen', required=True)
|
||||
parser.add_argument('--port', type=int, required=True)
|
||||
parser.add_argument('--upstream-port', type=int, required=True)
|
||||
parser.add_argument('--peer', required=True)
|
||||
parser.add_argument('--domain', required=True)
|
||||
parser.add_argument('--secret-file', required=True)
|
||||
args = parser.parse_args()
|
||||
token = Path(args.secret_file).read_text().strip()
|
||||
if len(token) != 64 or any(char not in '0123456789abcdef' for char in token):
|
||||
raise ValueError('Invalid private RPC secret')
|
||||
slots = threading.BoundedSemaphore(16)
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(15)
|
||||
|
||||
def log_message(self, *_):
|
||||
pass # No credentials, download URLs or request payloads in logs.
|
||||
|
||||
def reply(self, status, value):
|
||||
body = json.dumps(value).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self):
|
||||
if self.client_address[0] not in (args.peer, args.listen):
|
||||
return self.reply(403, {'error': 'Forbidden'})
|
||||
if self.path != '/jsonrpc' or self.headers.get('Host') not in (args.domain, args.domain + ':443'):
|
||||
return self.reply(403, {'error': 'Forbidden'})
|
||||
origin = self.headers.get('Origin')
|
||||
if origin and origin != 'https://' + args.domain:
|
||||
return self.reply(403, {'error': 'Forbidden origin'})
|
||||
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Type', '').split(';')[0].strip() not in ('application/json', 'application/json-rpc'):
|
||||
return self.reply(415, {'error': 'JSON POST required'})
|
||||
if not slots.acquire(blocking=False):
|
||||
return self.reply(503, {'error': 'Busy'})
|
||||
connection = None
|
||||
try:
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
if not 0 < length <= MAX_BODY:
|
||||
return self.reply(413, {'error': 'Invalid request size'})
|
||||
request = json.loads(self.rfile.read(length))
|
||||
if isinstance(request, list):
|
||||
if not 0 < len(request) <= 128:
|
||||
raise ValueError('Invalid batch')
|
||||
request = [inject(item, token) for item in request]
|
||||
else:
|
||||
request = inject(request, token)
|
||||
body = json.dumps(request).encode()
|
||||
if len(body) > MAX_BODY:
|
||||
return self.reply(413, {'error': 'Request too large'})
|
||||
connection = http.client.HTTPConnection(args.listen, args.upstream_port, timeout=30)
|
||||
connection.request('POST', '/jsonrpc', body, {'Content-Type': 'application/json'})
|
||||
response = connection.getresponse()
|
||||
payload = response.read(MAX_BODY + 1)
|
||||
if len(payload) > MAX_BODY:
|
||||
return self.reply(502, {'error': 'Upstream response too large'})
|
||||
self.reply(response.status, sanitize(json.loads(payload), token))
|
||||
except (ValueError, TypeError, KeyError):
|
||||
self.reply(400, {'error': 'Invalid RPC request'})
|
||||
except (OSError, http.client.HTTPException):
|
||||
self.reply(502, {'error': 'RPC upstream unavailable'})
|
||||
finally:
|
||||
if connection:
|
||||
connection.close()
|
||||
slots.release()
|
||||
|
||||
server = ThreadingHTTPServer((args.listen, args.port), Handler)
|
||||
server.daemon_threads = True
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
205
ansible/roles/profile_atlas/tasks/aria2.yml
Normal file
205
ansible/roles/profile_atlas/tasks/aria2.yml
Normal file
@@ -0,0 +1,205 @@
|
||||
---
|
||||
- name: Manage Atlas LAN HTTP downloader
|
||||
tags: [atlas, aria2]
|
||||
when: atlas_manage_aria2 | bool
|
||||
block:
|
||||
- name: Require isolated state, shared Downloads and pinned images
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_manage_storage | bool
|
||||
- atlas_aria2_state_dir == atlas_app_data_mountpoint ~ '/aria2'
|
||||
- atlas_aria2_downloads_dir == atlas_archive_mountpoint ~ '/Downloads'
|
||||
- atlas_aria2_image is search('@sha256:[0-9a-f]{64}$')
|
||||
- atlas_ariang_image is search('@sha256:[0-9a-f]{64}$')
|
||||
- atlas_aria2_rpc_port != atlas_ariang_web_port
|
||||
|
||||
- name: Inspect the existing downloader parent datasets
|
||||
community.general.zfs_facts:
|
||||
name: "{{ item.dataset }}"
|
||||
properties: name,mounted,mountpoint
|
||||
loop:
|
||||
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
|
||||
mountpoint: "{{ atlas_archive_mountpoint }}"
|
||||
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
|
||||
mountpoint: "{{ atlas_app_data_mountpoint }}"
|
||||
register: atlas_aria2_parents
|
||||
|
||||
- name: Require mounted downloader parent datasets
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- item.ansible_facts.ansible_zfs_datasets | length == 1
|
||||
- item.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
|
||||
- item.ansible_facts.ansible_zfs_datasets[0].mountpoint == item.item.mountpoint
|
||||
loop: "{{ atlas_aria2_parents.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item.dataset }}"
|
||||
|
||||
- name: Inspect shared Downloads without following links
|
||||
ansible.builtin.stat:
|
||||
path: "{{ atlas_aria2_downloads_dir }}"
|
||||
follow: false
|
||||
register: atlas_aria2_downloads
|
||||
|
||||
- name: Refuse unrelated or symlinked Downloads
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- >-
|
||||
not atlas_aria2_downloads.stat.exists or
|
||||
(atlas_aria2_downloads.stat.isdir | default(false) and
|
||||
atlas_aria2_downloads.stat.uid | int == atlas_admin_uid | int)
|
||||
|
||||
- name: Create the private aria2 dataset
|
||||
community.general.zfs:
|
||||
name: "{{ atlas_zfs_pool }}/services/data/aria2"
|
||||
state: present
|
||||
extra_zfs_properties:
|
||||
compression: zstd
|
||||
mountpoint: "{{ atlas_aria2_state_dir }}"
|
||||
|
||||
- name: Prepare state, downloads and Quadlet directories
|
||||
ansible.builtin.file:
|
||||
path: "{{ item.path }}"
|
||||
state: directory
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "{{ item.mode }}"
|
||||
loop:
|
||||
- {path: "{{ atlas_aria2_state_dir }}", mode: "0700"}
|
||||
- {path: "{{ atlas_aria2_downloads_dir }}", mode: "0770"}
|
||||
- {path: "{{ atlas_admin_home }}/.config/containers/systemd", mode: "0700"}
|
||||
|
||||
- name: Generate a private persistent RPC secret on Atlas only
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- python3
|
||||
- -c
|
||||
- >-
|
||||
import os, secrets;
|
||||
fd = os.open('{{ atlas_aria2_state_dir }}/rpc-secret',
|
||||
os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600);
|
||||
os.write(fd, (secrets.token_hex(32) + '\n').encode()); os.close(fd)
|
||||
creates: "{{ atlas_aria2_state_dir }}/rpc-secret"
|
||||
no_log: true
|
||||
|
||||
- name: Read the existing private RPC secret without displaying it
|
||||
ansible.builtin.slurp:
|
||||
src: "{{ atlas_aria2_state_dir }}/rpc-secret"
|
||||
register: atlas_aria2_rpc_secret
|
||||
no_log: true
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Require a strong RPC secret
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_aria2_rpc_secret.content | b64decode | trim is match('^[a-f0-9]{64}$')
|
||||
no_log: true
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Initialize the session file without replacing saved downloads
|
||||
ansible.builtin.copy:
|
||||
content: ""
|
||||
dest: "{{ atlas_aria2_state_dir }}/session"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0600"
|
||||
force: false
|
||||
diff: false
|
||||
no_log: true
|
||||
|
||||
- name: Render private aria2 configuration
|
||||
ansible.builtin.template:
|
||||
src: atlas-aria2.conf.j2
|
||||
dest: "{{ atlas_aria2_state_dir }}/aria2.conf"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0600"
|
||||
register: atlas_aria2_config
|
||||
no_log: true
|
||||
diff: false
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Allow only the LAN to reach AriaNg and the token-protected API
|
||||
ansible.posix.firewalld:
|
||||
zone: "{{ atlas_firewalld_zone }}"
|
||||
rich_rule: >-
|
||||
rule family="ipv4" source address="{{ atlas_lan_subnet }}"
|
||||
port port="{{ item }}" protocol="tcp" accept
|
||||
permanent: true
|
||||
immediate: true
|
||||
state: enabled
|
||||
loop:
|
||||
- "{{ atlas_aria2_rpc_port }}"
|
||||
- "{{ atlas_ariang_web_port }}"
|
||||
|
||||
- name: Keep the downloader user manager available at boot
|
||||
ansible.builtin.command: "loginctl enable-linger {{ atlas_admin_username }}"
|
||||
args:
|
||||
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
|
||||
|
||||
- name: Render the downloader and static Web UI Quadlets
|
||||
ansible.builtin.template:
|
||||
src: "atlas-{{ item }}.container.j2"
|
||||
dest: "{{ atlas_admin_home }}/.config/containers/systemd/atlas-{{ item }}.container"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0644"
|
||||
loop: [aria2, ariang]
|
||||
register: atlas_aria2_quadlets
|
||||
|
||||
- name: Reload the user manager after downloader Quadlet changes
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd:
|
||||
scope: user
|
||||
daemon_reload: true
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when:
|
||||
- atlas_aria2_quadlets.changed
|
||||
- not ansible_check_mode
|
||||
|
||||
- name: Start or update only the changed downloader service
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd:
|
||||
scope: user
|
||||
name: "atlas-{{ item.item }}.service"
|
||||
state: >-
|
||||
{{ 'restarted' if item.changed or
|
||||
(item.item == 'aria2' and atlas_aria2_config.changed | default(false))
|
||||
else 'started' }}
|
||||
loop: "{{ atlas_aria2_quadlets.results }}"
|
||||
loop_control:
|
||||
label: "atlas-{{ item.item }}.service"
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Verify the LAN Web UI responds
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_host }}:{{ atlas_ariang_web_port }}/"
|
||||
status_code: 200
|
||||
register: atlas_ariang_http
|
||||
retries: 15
|
||||
delay: 2
|
||||
until: atlas_ariang_http is succeeded
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Verify the authenticated RPC API
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_host }}:{{ atlas_aria2_rpc_port }}/jsonrpc"
|
||||
method: POST
|
||||
body_format: json
|
||||
body:
|
||||
jsonrpc: "2.0"
|
||||
id: ansible
|
||||
method: aria2.getVersion
|
||||
params: ["token:{{ atlas_aria2_rpc_secret.content | b64decode | trim }}"]
|
||||
return_content: true
|
||||
register: atlas_aria2_rpc_probe
|
||||
retries: 15
|
||||
delay: 2
|
||||
until: (atlas_aria2_rpc_probe.content | default('{}') | from_json).result.version is defined
|
||||
no_log: true
|
||||
when: not ansible_check_mode
|
||||
81
ansible/roles/profile_atlas/tasks/aria2_gateway.yml
Normal file
81
ansible/roles/profile_atlas/tasks/aria2_gateway.yml
Normal file
@@ -0,0 +1,81 @@
|
||||
---
|
||||
- name: Manage the private NPM aria2 adapter
|
||||
tags: [atlas, aria2_gateway]
|
||||
when:
|
||||
- atlas_manage_aria2 | bool
|
||||
- atlas_aria2_gateway_enabled | bool
|
||||
block:
|
||||
- name: Require a dedicated gateway and explicit public domain
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_aria2_gateway_port not in [atlas_aria2_rpc_port, atlas_ariang_web_port]
|
||||
- atlas_aria2_public_domain is match('^[a-z0-9][a-z0-9.-]+[.][a-z]{2,}$')
|
||||
- not atlas_aria2_public_domain.startswith('CHANGEME')
|
||||
|
||||
- name: Install the private JSON-RPC adapter
|
||||
ansible.builtin.copy:
|
||||
src: atlas-aria2-rpc-gateway.py
|
||||
dest: "{{ atlas_aria2_state_dir }}/rpc-gateway.py"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0600"
|
||||
register: atlas_aria2_gateway_script
|
||||
|
||||
- name: Prepare the user unit directory
|
||||
ansible.builtin.file:
|
||||
path: "{{ atlas_admin_home }}/.config/systemd/user"
|
||||
state: directory
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Install the user gateway unit
|
||||
ansible.builtin.template:
|
||||
src: atlas-aria2-gateway.service.j2
|
||||
dest: "{{ atlas_admin_home }}/.config/systemd/user/atlas-aria2-gateway.service"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0644"
|
||||
register: atlas_aria2_gateway_unit
|
||||
|
||||
- name: Allow only Aegis to reach the credential-injecting adapter
|
||||
ansible.posix.firewalld:
|
||||
zone: "{{ atlas_firewalld_zone }}"
|
||||
rich_rule: >-
|
||||
rule family="ipv4" source address="{{ atlas_aegis_ip }}"
|
||||
port port="{{ atlas_aria2_gateway_port }}" protocol="tcp" accept
|
||||
permanent: true
|
||||
immediate: true
|
||||
state: enabled
|
||||
|
||||
- name: Enable and start the private gateway
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd_service:
|
||||
scope: user
|
||||
name: atlas-aria2-gateway.service
|
||||
daemon_reload: "{{ atlas_aria2_gateway_unit.changed }}"
|
||||
enabled: true
|
||||
state: "{{ 'restarted' if atlas_aria2_gateway_script.changed or atlas_aria2_gateway_unit.changed else 'started' }}"
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Verify token-free requests through the private adapter
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_host }}:{{ atlas_aria2_gateway_port }}/jsonrpc"
|
||||
headers:
|
||||
Host: "{{ atlas_aria2_public_domain }}"
|
||||
method: POST
|
||||
body_format: json
|
||||
body:
|
||||
jsonrpc: "2.0"
|
||||
id: ansible-gateway
|
||||
method: aria2.getVersion
|
||||
params: []
|
||||
return_content: true
|
||||
register: atlas_aria2_gateway_probe
|
||||
retries: 10
|
||||
delay: 2
|
||||
until: atlas_aria2_gateway_probe.json.result.version is defined
|
||||
when: not ansible_check_mode
|
||||
@@ -26,6 +26,18 @@
|
||||
- name: Import Atlas iCloudPD storage and boot-started Quadlet tasks
|
||||
ansible.builtin.import_tasks: icloudpd.yml
|
||||
|
||||
- name: Import Atlas Paperless-ngx document-management service
|
||||
ansible.builtin.import_tasks: paperless.yml
|
||||
|
||||
- name: Import Atlas torrent service
|
||||
ansible.builtin.import_tasks: qbittorrent.yml
|
||||
|
||||
- name: Import Atlas LAN HTTP downloader
|
||||
ansible.builtin.import_tasks: aria2.yml
|
||||
|
||||
- name: Import Atlas private aria2 RPC gateway
|
||||
ansible.builtin.import_tasks: aria2_gateway.yml
|
||||
|
||||
- name: Import Atlas ZFS maintenance tasks
|
||||
ansible.builtin.import_tasks: zfs_maintenance.yml
|
||||
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
tags: [atlas, nextcloud_backup]
|
||||
when: atlas_manage_nextcloud | bool
|
||||
block:
|
||||
- name: Validate private backup scope and local bundle retention
|
||||
- name: Validate private backup scope, retention, and bundle reuse window
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_nextcloud_backup_root == atlas_mount_root ~ '/backup/nextcloud'
|
||||
- atlas_nextcloud_backup_keep | int >= 2
|
||||
- atlas_nextcloud_backup_reuse_max_seconds | int >= 0
|
||||
# Below 24h the nightly Borg run cannot reuse the previous bundle.
|
||||
- atlas_nextcloud_backup_reuse_max_seconds | int < 86400
|
||||
- atlas_manage_borg_backup | bool
|
||||
- atlas_manage_usb_backup | bool
|
||||
|
||||
|
||||
@@ -74,6 +74,18 @@
|
||||
state: present
|
||||
loop: "{{ atlas_nextcloud_external_mounts }}"
|
||||
|
||||
- name: Restore effective web write access inside writable external storage
|
||||
ansible.posix.acl:
|
||||
path: "{{ item.source }}"
|
||||
etype: mask
|
||||
permissions: rwX
|
||||
recursive: true
|
||||
follow: false
|
||||
recalculate_mask: no_mask
|
||||
state: present
|
||||
loop: "{{ atlas_nextcloud_external_mounts }}"
|
||||
when: not item.readonly
|
||||
|
||||
- name: Inherit web access on new files and directories
|
||||
ansible.posix.acl:
|
||||
path: "{{ item.source }}"
|
||||
|
||||
255
ansible/roles/profile_atlas/tasks/paperless.yml
Normal file
255
ansible/roles/profile_atlas/tasks/paperless.yml
Normal file
@@ -0,0 +1,255 @@
|
||||
---
|
||||
- name: Manage Atlas rootless Paperless-ngx
|
||||
tags: [atlas, paperless]
|
||||
when: atlas_manage_paperless | bool
|
||||
block:
|
||||
- name: Require isolated Paperless state, public domain and pinned images
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_manage_storage | bool
|
||||
- atlas_manage_firewall | bool
|
||||
- atlas_paperless_root == atlas_app_data_mountpoint ~ '/paperless'
|
||||
- atlas_paperless_dataset == atlas_zfs_pool ~ '/services/data/paperless'
|
||||
- atlas_paperless_domain is match('^[a-z0-9]+([.-][a-z0-9]+)+$')
|
||||
- atlas_paperless_http_port | int > 1024
|
||||
- atlas_paperless_http_port | int < 65536
|
||||
- atlas_paperless_network_subnet != atlas_nextcloud_network_subnet
|
||||
- item is search('@sha256:[0-9a-f]{64}$')
|
||||
loop:
|
||||
- "{{ atlas_paperless_image }}"
|
||||
- "{{ atlas_paperless_postgres_image }}"
|
||||
- "{{ atlas_paperless_valkey_image }}"
|
||||
- "{{ atlas_paperless_tika_image }}"
|
||||
- "{{ atlas_paperless_gotenberg_image }}"
|
||||
- "{{ atlas_paperless_ollama_image }}"
|
||||
|
||||
- name: Require dedicated Paperless Vault secrets without exposing them
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- vault_paperless_database_password | default('') is match('^[a-zA-Z0-9]{32,}$')
|
||||
- vault_paperless_secret_key | default('') | length >= 64
|
||||
no_log: true
|
||||
|
||||
- name: Verify the existing application-data parent is mounted
|
||||
community.general.zfs_facts:
|
||||
name: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
|
||||
properties: name,mounted,mountpoint
|
||||
register: atlas_paperless_parent
|
||||
|
||||
- name: Require the verified application-data parent
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_paperless_parent.ansible_facts.ansible_zfs_datasets | length == 1
|
||||
- atlas_paperless_parent.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
|
||||
- atlas_paperless_parent.ansible_facts.ansible_zfs_datasets[0].mountpoint == atlas_app_data_mountpoint
|
||||
|
||||
- name: Create dedicated Paperless component datasets
|
||||
community.general.zfs:
|
||||
name: "{{ atlas_paperless_dataset }}{{ item }}"
|
||||
state: present
|
||||
extra_zfs_properties:
|
||||
compression: zstd
|
||||
mountpoint: "{{ atlas_paperless_root }}{{ item }}"
|
||||
loop: ['', /data, /media, /consume, /database, /cache, /ollama]
|
||||
|
||||
- name: Prepare private Paperless paths and Quadlet directory
|
||||
ansible.builtin.file:
|
||||
path: "{{ item }}"
|
||||
state: directory
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0700"
|
||||
loop:
|
||||
- "{{ atlas_paperless_root }}"
|
||||
- "{{ atlas_paperless_root }}/data"
|
||||
- "{{ atlas_paperless_root }}/media"
|
||||
- "{{ atlas_paperless_root }}/consume"
|
||||
- "{{ atlas_paperless_root }}/ollama"
|
||||
- "{{ atlas_paperless_private_dir }}"
|
||||
- "{{ atlas_paperless_quadlet_dir }}"
|
||||
|
||||
- name: Derive the rootless PostgreSQL host UID
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- podman
|
||||
- unshare
|
||||
- python3
|
||||
- -c
|
||||
- >-
|
||||
print(next(int(host) + 999 - int(container) for container, host, size in
|
||||
(line.split() for line in open('/proc/self/uid_map'))
|
||||
if int(container) <= 999 < int(container) + int(size)))
|
||||
register: atlas_paperless_postgres_host_uid
|
||||
check_mode: false
|
||||
changed_when: false
|
||||
|
||||
- name: Allow the rootless PostgreSQL UID to traverse its dataset root
|
||||
ansible.builtin.file:
|
||||
path: "{{ atlas_paperless_root }}/database"
|
||||
state: directory
|
||||
owner: "{{ atlas_paperless_postgres_host_uid.stdout | trim }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Allow the rootless Valkey UID to write its persistent cache
|
||||
ansible.builtin.file:
|
||||
path: "{{ atlas_paperless_root }}/cache"
|
||||
state: directory
|
||||
owner: "{{ atlas_paperless_postgres_host_uid.stdout | trim }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0700"
|
||||
register: atlas_paperless_cache_root
|
||||
|
||||
- name: Store Paperless secrets in private mounted files
|
||||
ansible.builtin.copy:
|
||||
content: "{{ item.value }}\n"
|
||||
dest: "{{ atlas_paperless_private_dir }}/{{ item.name }}"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0644"
|
||||
loop:
|
||||
- {name: postgres-password, value: "{{ vault_paperless_database_password }}"}
|
||||
- {name: secret-key, value: "{{ vault_paperless_secret_key }}"}
|
||||
no_log: true
|
||||
diff: false
|
||||
register: atlas_paperless_secret_files
|
||||
|
||||
- name: Admit only the Aegis gateway to the Paperless listener
|
||||
ansible.posix.firewalld:
|
||||
rich_rule: >-
|
||||
rule family="ipv4" source address="{{ atlas_aegis_ip }}"
|
||||
port port="{{ atlas_paperless_http_port }}" protocol="tcp" accept
|
||||
zone: "{{ atlas_firewalld_zone }}"
|
||||
state: enabled
|
||||
permanent: true
|
||||
immediate: true
|
||||
|
||||
- name: Keep the Paperless rootless user manager available at boot
|
||||
ansible.builtin.command:
|
||||
argv: [loginctl, enable-linger, "{{ atlas_admin_username }}"]
|
||||
args:
|
||||
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
|
||||
|
||||
- name: Render the private Paperless Quadlets
|
||||
ansible.builtin.template:
|
||||
src: "{{ item }}.j2"
|
||||
dest: "{{ atlas_paperless_quadlet_dir }}/{{ item }}"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0644"
|
||||
loop:
|
||||
- atlas-paperless.network
|
||||
- atlas-paperless-db.container
|
||||
- atlas-paperless-valkey.container
|
||||
- atlas-paperless-tika.container
|
||||
- atlas-paperless-gotenberg.container
|
||||
- atlas-paperless-ollama.container
|
||||
- atlas-paperless.container
|
||||
register: atlas_paperless_quadlets
|
||||
|
||||
- name: Pull, start and verify Paperless
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when: not ansible_check_mode
|
||||
block:
|
||||
- name: Pull the pinned Paperless images before starting services
|
||||
containers.podman.podman_image:
|
||||
name: "{{ item }}"
|
||||
state: present
|
||||
loop:
|
||||
- "{{ atlas_paperless_image }}"
|
||||
- "{{ atlas_paperless_postgres_image }}"
|
||||
- "{{ atlas_paperless_valkey_image }}"
|
||||
- "{{ atlas_paperless_tika_image }}"
|
||||
- "{{ atlas_paperless_gotenberg_image }}"
|
||||
- "{{ atlas_paperless_ollama_image }}"
|
||||
|
||||
- name: Reload the rootless user manager for Paperless
|
||||
ansible.builtin.systemd:
|
||||
scope: user
|
||||
daemon_reload: true
|
||||
|
||||
- name: Start Paperless component services
|
||||
ansible.builtin.systemd:
|
||||
scope: user
|
||||
name: "{{ item }}"
|
||||
state: >-
|
||||
{{ 'restarted' if
|
||||
(atlas_paperless_quadlets.results |
|
||||
selectattr('item', 'equalto', item | replace('.service', '.container')) |
|
||||
selectattr('changed') | list | length > 0) or
|
||||
(atlas_paperless_quadlets.results |
|
||||
selectattr('item', 'equalto', 'atlas-paperless.network') |
|
||||
selectattr('changed') | list | length > 0) or
|
||||
(atlas_paperless_secret_files is changed and
|
||||
item in ['atlas-paperless-db.service', 'atlas-paperless.service']) or
|
||||
(atlas_paperless_cache_root is changed and
|
||||
item == 'atlas-paperless-valkey.service') else 'started' }}
|
||||
enabled: true
|
||||
loop: "{{ atlas_paperless_services }}"
|
||||
|
||||
- name: Verify the Paperless HTTP service through its LAN listener
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_host }}:{{ atlas_paperless_http_port }}/"
|
||||
status_code: [200, 302]
|
||||
register: atlas_paperless_http
|
||||
retries: 60
|
||||
delay: 5
|
||||
until: atlas_paperless_http is succeeded
|
||||
|
||||
- name: Verify the private Ollama API from Paperless
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- podman
|
||||
- exec
|
||||
- atlas-paperless
|
||||
- python3
|
||||
- -c
|
||||
- >-
|
||||
import urllib.request;
|
||||
urllib.request.urlopen('http://atlas-paperless-ollama:11434/api/tags', timeout=10).close()
|
||||
register: atlas_paperless_ollama_health
|
||||
changed_when: false
|
||||
retries: 30
|
||||
delay: 5
|
||||
until: atlas_paperless_ollama_health.rc == 0
|
||||
|
||||
- name: Check whether the local AI models are present
|
||||
ansible.builtin.command:
|
||||
argv: [podman, exec, atlas-paperless-ollama, ollama, show, "{{ item }}"]
|
||||
loop:
|
||||
- "{{ atlas_paperless_llm_model }}"
|
||||
- "{{ atlas_paperless_embedding_model }}"
|
||||
register: atlas_paperless_model_checks
|
||||
changed_when: false
|
||||
failed_when: false
|
||||
|
||||
- name: Download missing local AI models
|
||||
ansible.builtin.command:
|
||||
argv: [podman, exec, atlas-paperless-ollama, ollama, pull, "{{ item.item }}"]
|
||||
loop: "{{ atlas_paperless_model_checks.results }}"
|
||||
when: item.rc != 0
|
||||
loop_control:
|
||||
label: "{{ item.item }}"
|
||||
|
||||
- name: Verify private Office conversion endpoints from Paperless
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- podman
|
||||
- exec
|
||||
- atlas-paperless
|
||||
- python3
|
||||
- -c
|
||||
- >-
|
||||
import urllib.request;
|
||||
urls = ['http://atlas-paperless-tika:9998/version',
|
||||
'http://atlas-paperless-gotenberg:3000/health'];
|
||||
[urllib.request.urlopen(url, timeout=10).close() for url in urls]
|
||||
register: atlas_paperless_office_health
|
||||
changed_when: false
|
||||
retries: 30
|
||||
delay: 5
|
||||
until: atlas_paperless_office_health.rc == 0
|
||||
186
ansible/roles/profile_atlas/tasks/qbittorrent.yml
Normal file
186
ansible/roles/profile_atlas/tasks/qbittorrent.yml
Normal file
@@ -0,0 +1,186 @@
|
||||
---
|
||||
- name: Manage Atlas rootless qBittorrent
|
||||
tags: [atlas, qbittorrent]
|
||||
when: atlas_manage_qbittorrent | bool
|
||||
block:
|
||||
- name: Require isolated paths and a pinned image
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_manage_storage | bool
|
||||
- atlas_qbittorrent_state_dir == atlas_app_data_mountpoint ~ '/qbittorrent'
|
||||
- atlas_qbittorrent_downloads_dir == atlas_archive_mountpoint ~ '/Downloads'
|
||||
- atlas_qbittorrent_image is search('@sha256:[0-9a-f]{64}$')
|
||||
|
||||
- name: Inspect the existing parent datasets
|
||||
community.general.zfs_facts:
|
||||
name: "{{ item.dataset }}"
|
||||
properties: name,mounted,mountpoint
|
||||
loop:
|
||||
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
|
||||
mountpoint: "{{ atlas_archive_mountpoint }}"
|
||||
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
|
||||
mountpoint: "{{ atlas_app_data_mountpoint }}"
|
||||
register: atlas_qbittorrent_parents
|
||||
|
||||
- name: Refuse missing or unmounted parent datasets
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- item.ansible_facts.ansible_zfs_datasets | length == 1
|
||||
- item.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
|
||||
- item.ansible_facts.ansible_zfs_datasets[0].mountpoint == item.item.mountpoint
|
||||
loop: "{{ atlas_qbittorrent_parents.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item.dataset }}"
|
||||
|
||||
- name: Inspect the proposed download directory without following links
|
||||
ansible.builtin.stat:
|
||||
path: "{{ atlas_qbittorrent_downloads_dir }}"
|
||||
follow: false
|
||||
register: atlas_qbittorrent_downloads
|
||||
|
||||
- name: Refuse unrelated or symlinked download paths
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- >-
|
||||
not atlas_qbittorrent_downloads.stat.exists or
|
||||
(atlas_qbittorrent_downloads.stat.isdir | default(false) and
|
||||
atlas_qbittorrent_downloads.stat.uid | int == atlas_admin_uid | int)
|
||||
|
||||
- name: Create the dedicated configuration dataset
|
||||
community.general.zfs:
|
||||
name: "{{ atlas_zfs_pool }}/services/data/qbittorrent"
|
||||
state: present
|
||||
extra_zfs_properties:
|
||||
compression: zstd
|
||||
mountpoint: "{{ atlas_qbittorrent_state_dir }}"
|
||||
|
||||
- name: Prepare private state and the SMB download directory
|
||||
ansible.builtin.file:
|
||||
path: "{{ item.path }}"
|
||||
state: directory
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "{{ item.mode }}"
|
||||
loop:
|
||||
- {path: "{{ atlas_qbittorrent_state_dir }}", mode: "0700"}
|
||||
- {path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config", mode: "0700"}
|
||||
- {path: "{{ atlas_qbittorrent_downloads_dir }}", mode: "0770"}
|
||||
- {path: "{{ atlas_admin_home }}/.config/containers/systemd", mode: "0700"}
|
||||
|
||||
- name: Seed qBittorrent settings without overwriting application-managed state
|
||||
ansible.builtin.template:
|
||||
src: atlas-qbittorrent.conf.j2
|
||||
dest: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0600"
|
||||
force: false
|
||||
diff: false
|
||||
|
||||
- name: Allow only the declared LAN to reach the Web UI
|
||||
ansible.posix.firewalld:
|
||||
zone: "{{ atlas_firewalld_zone }}"
|
||||
rich_rule: >-
|
||||
rule family="ipv4" source address="{{ atlas_lan_subnet }}"
|
||||
port port="{{ atlas_qbittorrent_web_port }}" protocol="tcp" accept
|
||||
permanent: true
|
||||
immediate: true
|
||||
state: enabled
|
||||
|
||||
- name: Keep the rootless user manager available at boot
|
||||
ansible.builtin.command: "loginctl enable-linger {{ atlas_admin_username }}"
|
||||
args:
|
||||
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
|
||||
|
||||
- name: Render the rootless torrent Quadlet
|
||||
ansible.builtin.template:
|
||||
src: atlas-qbittorrent.container.j2
|
||||
dest: "{{ atlas_admin_home }}/.config/containers/systemd/atlas-qbittorrent.container"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0644"
|
||||
register: atlas_qbittorrent_quadlet
|
||||
|
||||
- name: Reload the user manager after a new or changed Quadlet
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd:
|
||||
scope: user
|
||||
daemon_reload: true
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when:
|
||||
- atlas_qbittorrent_quadlet.changed
|
||||
- not ansible_check_mode
|
||||
|
||||
- name: Manage the declared qBittorrent reverse-proxy settings
|
||||
when: atlas_qbittorrent_reverse_proxy_enabled | bool
|
||||
block:
|
||||
- name: Require a specific public domain and existing Aegis gateway
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_qbittorrent_public_domain is match('^[a-z0-9]+([.-][a-z0-9]+)+$')
|
||||
- "'CHANGEME' not in atlas_aegis_ip"
|
||||
|
||||
- name: Check whether managed Web settings need an update
|
||||
community.general.ini_file:
|
||||
path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
|
||||
section: Preferences
|
||||
option: "{{ item.key }}"
|
||||
value: "{{ item.value }}"
|
||||
no_extra_spaces: true
|
||||
mode: "0600"
|
||||
loop: "{{ atlas_qbittorrent_web_settings }}"
|
||||
check_mode: true
|
||||
register: atlas_qbittorrent_web_probe
|
||||
no_log: true
|
||||
diff: false
|
||||
|
||||
- name: Stop only qBittorrent before editing its application-managed settings
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd:
|
||||
name: atlas-qbittorrent.service
|
||||
scope: user
|
||||
state: stopped
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when:
|
||||
- atlas_qbittorrent_web_probe.changed
|
||||
- not ansible_check_mode
|
||||
|
||||
- name: Preserve credentials and change only the declared Web settings
|
||||
community.general.ini_file:
|
||||
path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
|
||||
section: Preferences
|
||||
option: "{{ item.key }}"
|
||||
value: "{{ item.value }}"
|
||||
no_extra_spaces: true
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0600"
|
||||
loop: "{{ atlas_qbittorrent_web_settings }}"
|
||||
when: atlas_qbittorrent_web_probe.changed
|
||||
no_log: true
|
||||
diff: false
|
||||
|
||||
- name: Start qBittorrent and restart only after a Quadlet change
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd:
|
||||
name: atlas-qbittorrent.service
|
||||
scope: user
|
||||
state: "{{ 'restarted' if atlas_qbittorrent_quadlet.changed else 'started' }}"
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Verify the Web UI responds on the LAN address
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_host }}:{{ atlas_qbittorrent_web_port }}/"
|
||||
status_code: 200
|
||||
register: atlas_qbittorrent_http
|
||||
retries: 15
|
||||
delay: 2
|
||||
until: atlas_qbittorrent_http is succeeded
|
||||
when: not ansible_check_mode
|
||||
@@ -0,0 +1,17 @@
|
||||
# Managed by Ansible. NPM authenticates callers; this private adapter adds RPC credentials.
|
||||
[Unit]
|
||||
Description=Atlas private aria2 RPC gateway
|
||||
After=atlas-aria2.service
|
||||
Requires=atlas-aria2.service
|
||||
PartOf=atlas-aria2.service
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/python3 {{ atlas_aria2_state_dir }}/rpc-gateway.py --listen {{ ansible_host }} --port {{ atlas_aria2_gateway_port }} --upstream-port {{ atlas_aria2_rpc_port }} --peer {{ atlas_aegis_ip }} --domain {{ atlas_aria2_public_domain }} --secret-file {{ atlas_aria2_state_dir }}/rpc-secret
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
RestrictAddressFamilies=AF_INET AF_UNIX
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
30
ansible/roles/profile_atlas/templates/atlas-aria2.conf.j2
Normal file
30
ansible/roles/profile_atlas/templates/atlas-aria2.conf.j2
Normal file
@@ -0,0 +1,30 @@
|
||||
# Managed by Ansible. Never expose this file: it contains the RPC secret.
|
||||
dir=/downloads
|
||||
input-file=/config/session
|
||||
save-session=/config/session
|
||||
save-session-interval=30
|
||||
auto-save-interval=30
|
||||
continue=true
|
||||
allow-overwrite=false
|
||||
auto-file-renaming=false
|
||||
max-concurrent-downloads=1
|
||||
max-connection-per-server=1
|
||||
split=1
|
||||
max-tries=20
|
||||
retry-wait=10
|
||||
connect-timeout=30
|
||||
timeout=60
|
||||
check-certificate=true
|
||||
file-allocation=none
|
||||
umask=007
|
||||
enable-rpc=true
|
||||
rpc-listen-all=true
|
||||
rpc-listen-port=6800
|
||||
rpc-allow-origin-all=true
|
||||
rpc-secret={{ atlas_aria2_rpc_secret.content | b64decode | trim }}
|
||||
rpc-max-request-size=2M
|
||||
enable-dht=false
|
||||
enable-dht6=false
|
||||
enable-peer-exchange=false
|
||||
bt-enable-lpd=false
|
||||
console-log-level=warn
|
||||
@@ -0,0 +1,30 @@
|
||||
# Managed by Ansible. Bypass upstream init, tracker updates and deletion hooks.
|
||||
[Unit]
|
||||
Description=Atlas rootless HTTP downloader
|
||||
RequiresMountsFor={{ atlas_aria2_state_dir }} {{ atlas_aria2_downloads_dir }}
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-aria2
|
||||
Image={{ atlas_aria2_image }}
|
||||
UserNS=keep-id
|
||||
User={{ atlas_admin_uid }}
|
||||
Group={{ atlas_admin_gid }}
|
||||
Entrypoint=/usr/local/bin/aria2c
|
||||
Exec=--conf-path=/config/aria2.conf
|
||||
PublishPort={{ ansible_host }}:{{ atlas_aria2_rpc_port }}:6800
|
||||
Volume={{ atlas_aria2_state_dir }}:/config:Z
|
||||
Volume={{ atlas_aria2_downloads_dir }}:/downloads:z
|
||||
ReadOnly=true
|
||||
Tmpfs=/tmp:rw,nosuid,nodev
|
||||
NoNewPrivileges=true
|
||||
DropCapability=all
|
||||
StopTimeout=60
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
TimeoutStopSec=90
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,22 @@
|
||||
# Managed by Ansible. Static frontend only; no host data or RPC secret mounted.
|
||||
[Unit]
|
||||
Description=Atlas AriaNg LAN Web UI
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-ariang
|
||||
Image={{ atlas_ariang_image }}
|
||||
UserNS=keep-id
|
||||
User={{ atlas_admin_uid }}
|
||||
Group={{ atlas_admin_gid }}
|
||||
PublishPort={{ ansible_host }}:{{ atlas_ariang_web_port }}:6880
|
||||
ReadOnly=true
|
||||
NoNewPrivileges=true
|
||||
DropCapability=all
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -14,6 +14,9 @@ StateDirectory=atlas-nextcloud-backup
|
||||
StateDirectoryMode=0700
|
||||
ExecStart=/usr/local/sbin/atlas-nextcloud-backup
|
||||
ExecStopPost=/usr/local/sbin/atlas-nextcloud-backup --recover
|
||||
# systemctl set-environment ATLAS_NEXTCLOUD_BACKUP_FORCE=1 makes the next run
|
||||
# ignore the bundle reuse window; unset the variable afterwards.
|
||||
PassEnvironment=ATLAS_NEXTCLOUD_BACKUP_FORCE
|
||||
TimeoutStartSec=3h
|
||||
TimeoutStopSec=5min
|
||||
Nice=10
|
||||
|
||||
@@ -7,6 +7,7 @@ readonly source_root={{ atlas_nextcloud_root | quote }}
|
||||
readonly backup_root={{ atlas_nextcloud_backup_root | quote }}
|
||||
readonly state=/var/lib/atlas-nextcloud-backup
|
||||
readonly keep={{ atlas_nextcloud_backup_keep | int }}
|
||||
readonly reuse_max={{ atlas_nextcloud_backup_reuse_max_seconds | int }}
|
||||
readonly owner={{ atlas_admin_username | quote }}
|
||||
readonly uid={{ atlas_admin_uid | int }}
|
||||
|
||||
@@ -64,6 +65,36 @@ recover() {
|
||||
}
|
||||
if [[ "${1:-}" == --recover ]]; then recover; exit; fi
|
||||
recover
|
||||
# Fast path: a structurally complete bundle from an earlier verified run is
|
||||
# reused while younger than the reuse window, without pausing the applications.
|
||||
# ATLAS_NEXTCLOUD_BACKUP_FORCE=1 ignores the window and prepares one anyway.
|
||||
if [[ "${ATLAS_NEXTCLOUD_BACKUP_FORCE:-0}" != 1 ]] && [[ "$reuse_max" -gt 0 ]]; then
|
||||
target="$(readlink -f "$backup_root/latest" 2>/dev/null || true)"
|
||||
if [[ -n "$target" && "$target" == "$backup_root/versions/"* ]]; then
|
||||
name="${target##*/}"
|
||||
if [[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z-[0-9]+$ ]]; then
|
||||
bundle_utc="${name:0:4}-${name:4:2}-${name:6:2} ${name:9:2}:${name:11:2}:${name:13:2} UTC"
|
||||
created="$(date -u -d "$bundle_utc" +%s 2>/dev/null || true)"
|
||||
if [[ -n "$created" ]]; then
|
||||
now="$(date -u +%s)"
|
||||
if [[ "$((now - created))" -le "$reuse_max" ]]; then
|
||||
reusable=true
|
||||
for component in manifest.txt SHA256SUMS database.dump \
|
||||
postgres-globals.sql database-toc.txt images.txt; do
|
||||
[[ -s "$target/$component" ]] || { reusable=false; break; }
|
||||
done
|
||||
for component in app files; do
|
||||
[[ -d "$target/$component" ]] || { reusable=false; break; }
|
||||
done
|
||||
if [[ "$reusable" == true ]]; then
|
||||
echo "Reusing verified Nextcloud bundle $name (age $((now - created))s <= ${reuse_max}s); preparation skipped"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
[[ "$(zfs get -H -o value mounted "$dataset")" == yes ]]
|
||||
[[ "$(zfs get -H -o value mountpoint "$dataset")" == "$source_root" ]]
|
||||
[[ "$(zfs get -H -o value mounted {{ (atlas_zfs_pool ~ '/backup') | quote }})" == yes ]]
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
[Unit]
|
||||
Description=Atlas Paperless PostgreSQL
|
||||
RequiresMountsFor={{ atlas_paperless_root }}/database
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-paperless-db
|
||||
Image={{ atlas_paperless_postgres_image }}
|
||||
Network=atlas-paperless.network
|
||||
NetworkAlias=atlas-paperless-db
|
||||
Environment=POSTGRES_DB=paperless
|
||||
Environment=POSTGRES_USER=paperless
|
||||
Environment=POSTGRES_PASSWORD_FILE=/run/secrets/postgres-password
|
||||
Volume={{ atlas_paperless_private_dir }}/postgres-password:/run/secrets/postgres-password:ro,z
|
||||
Volume={{ atlas_paperless_root }}/database:/var/lib/postgresql/data:Z
|
||||
PodmanArgs=--memory=1g
|
||||
HealthCmd=pg_isready -U paperless -d paperless
|
||||
HealthInterval=30s
|
||||
HealthStartPeriod=60s
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=Atlas Paperless private Gotenberg
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-paperless-gotenberg
|
||||
Image={{ atlas_paperless_gotenberg_image }}
|
||||
Network=atlas-paperless.network
|
||||
NetworkAlias=atlas-paperless-gotenberg
|
||||
# Keep external content and JavaScript disabled for email/Office conversion.
|
||||
Exec=gotenberg --chromium-disable-javascript=true --chromium-allow-list=^file:///tmp/.*
|
||||
PodmanArgs=--memory=2g
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,27 @@
|
||||
[Unit]
|
||||
Description=Atlas private Paperless Ollama
|
||||
RequiresMountsFor={{ atlas_paperless_root }}/ollama
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-paperless-ollama
|
||||
Image={{ atlas_paperless_ollama_image }}
|
||||
UserNS=keep-id:uid={{ atlas_admin_uid }},gid={{ atlas_admin_gid }}
|
||||
User={{ atlas_admin_uid }}:{{ atlas_admin_gid }}
|
||||
Network=atlas-paperless.network
|
||||
Environment=OLLAMA_HOST=0.0.0.0:11434
|
||||
Environment=OLLAMA_MODELS=/models
|
||||
Environment=OLLAMA_NUM_PARALLEL=1
|
||||
Environment=OLLAMA_MAX_LOADED_MODELS=1
|
||||
Environment=OLLAMA_KEEP_ALIVE=2m
|
||||
Environment=OLLAMA_NO_CLOUD=true
|
||||
Volume={{ atlas_paperless_root }}/ollama:/models:Z
|
||||
PodmanArgs=--memory=3g
|
||||
NoNewPrivileges=true
|
||||
DropCapability=all
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Atlas Paperless private Apache Tika
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-paperless-tika
|
||||
Image={{ atlas_paperless_tika_image }}
|
||||
Network=atlas-paperless.network
|
||||
NetworkAlias=atlas-paperless-tika
|
||||
PodmanArgs=--memory=1g
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,21 @@
|
||||
[Unit]
|
||||
Description=Atlas Paperless private Valkey broker
|
||||
RequiresMountsFor={{ atlas_paperless_root }}/cache
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-paperless-valkey
|
||||
Image={{ atlas_paperless_valkey_image }}
|
||||
Network=atlas-paperless.network
|
||||
NetworkAlias=atlas-paperless-valkey
|
||||
Volume={{ atlas_paperless_root }}/cache:/data:Z
|
||||
Exec=valkey-server --appendonly yes
|
||||
PodmanArgs=--memory=256m
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,54 @@
|
||||
[Unit]
|
||||
Description=Atlas Paperless-ngx
|
||||
Requires=atlas-paperless-db.service atlas-paperless-valkey.service atlas-paperless-tika.service atlas-paperless-gotenberg.service atlas-paperless-ollama.service
|
||||
After=atlas-paperless-db.service atlas-paperless-valkey.service atlas-paperless-tika.service atlas-paperless-gotenberg.service atlas-paperless-ollama.service
|
||||
RequiresMountsFor={{ atlas_paperless_root }}/data {{ atlas_paperless_root }}/media {{ atlas_paperless_root }}/consume
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-paperless
|
||||
Image={{ atlas_paperless_image }}
|
||||
UserNS=keep-id:uid={{ atlas_admin_uid }},gid={{ atlas_admin_gid }}
|
||||
Network=atlas-paperless.network
|
||||
PublishPort={{ ansible_host }}:{{ atlas_paperless_http_port }}:8000
|
||||
Environment=USERMAP_UID={{ atlas_admin_uid }}
|
||||
Environment=USERMAP_GID={{ atlas_admin_gid }}
|
||||
Environment=PAPERLESS_REDIS=redis://atlas-paperless-valkey:6379
|
||||
Environment=PAPERLESS_DBENGINE=postgresql
|
||||
Environment=PAPERLESS_DBHOST=atlas-paperless-db
|
||||
Environment=PAPERLESS_DBNAME=paperless
|
||||
Environment=PAPERLESS_DBUSER=paperless
|
||||
Environment=PAPERLESS_DBPASS_FILE=/run/secrets/postgres-password
|
||||
Environment=PAPERLESS_SECRET_KEY_FILE=/run/secrets/secret-key
|
||||
Environment=PAPERLESS_URL=https://{{ atlas_paperless_domain }}
|
||||
Environment=PAPERLESS_TIME_ZONE={{ atlas_timezone }}
|
||||
Environment=PAPERLESS_OCR_LANGUAGE={{ atlas_paperless_ocr_language }}
|
||||
Environment=PAPERLESS_CONSUMPTION_DIR=/usr/src/paperless/consume
|
||||
Environment=PAPERLESS_DATA_DIR=/usr/src/paperless/data
|
||||
Environment=PAPERLESS_MEDIA_ROOT=/usr/src/paperless/media
|
||||
Environment=PAPERLESS_TIKA_ENABLED=1
|
||||
Environment=PAPERLESS_TIKA_ENDPOINT=http://atlas-paperless-tika:9998
|
||||
Environment=PAPERLESS_TIKA_GOTENBERG_ENDPOINT=http://atlas-paperless-gotenberg:3000
|
||||
Environment=PAPERLESS_AI_ENABLED=true
|
||||
Environment=PAPERLESS_AI_LLM_BACKEND=ollama
|
||||
Environment=PAPERLESS_AI_LLM_ENDPOINT=http://atlas-paperless-ollama:11434
|
||||
Environment=PAPERLESS_AI_LLM_MODEL={{ atlas_paperless_llm_model }}
|
||||
Environment=PAPERLESS_AI_LLM_EMBEDDING_BACKEND=ollama
|
||||
Environment=PAPERLESS_AI_LLM_EMBEDDING_MODEL={{ atlas_paperless_embedding_model }}
|
||||
Environment=PAPERLESS_AI_LLM_CONTEXT_SIZE=2048
|
||||
Environment=PAPERLESS_AI_LLM_REQUEST_TIMEOUT=300
|
||||
Volume={{ atlas_paperless_root }}/data:/usr/src/paperless/data:Z
|
||||
Volume={{ atlas_paperless_root }}/media:/usr/src/paperless/media:Z
|
||||
Volume={{ atlas_paperless_root }}/consume:/usr/src/paperless/consume:Z
|
||||
Volume={{ atlas_paperless_private_dir }}/postgres-password:/run/secrets/postgres-password:ro,z
|
||||
Volume={{ atlas_paperless_private_dir }}/secret-key:/run/secrets/secret-key:ro,z
|
||||
PodmanArgs=--memory=2g
|
||||
NoNewPrivileges=true
|
||||
DropCapability=all
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -0,0 +1,5 @@
|
||||
# Managed by Ansible: private rootless Paperless network.
|
||||
[Network]
|
||||
NetworkName=atlas-paperless
|
||||
Subnet={{ atlas_paperless_network_subnet }}
|
||||
Gateway={{ atlas_paperless_network_gateway }}
|
||||
@@ -0,0 +1,17 @@
|
||||
; Seeded once by Ansible. Subsequent settings are managed through the Web UI.
|
||||
[BitTorrent]
|
||||
Session\DefaultSavePath=/downloads
|
||||
Session\TempPath=/downloads/.incomplete
|
||||
Session\TempPathEnabled=true
|
||||
Session\Port=6881
|
||||
[Meta]
|
||||
MigrationVersion=9999
|
||||
[Network]
|
||||
PortForwardingEnabled=false
|
||||
[Preferences]
|
||||
WebUI\Port={{ atlas_qbittorrent_web_port }}
|
||||
WebUI\LocalHostAuth=true
|
||||
WebUI\AuthSubnetWhitelistEnabled=false
|
||||
WebUI\CSRFProtection=true
|
||||
WebUI\ClickjackingProtection=true
|
||||
WebUI\HostHeaderValidation=true
|
||||
@@ -0,0 +1,33 @@
|
||||
# Managed by Ansible. No VPN, host networking or router port forwarding.
|
||||
[Unit]
|
||||
Description=Atlas rootless qBittorrent
|
||||
RequiresMountsFor={{ atlas_qbittorrent_state_dir }} {{ atlas_qbittorrent_downloads_dir }}
|
||||
|
||||
[Container]
|
||||
ContainerName=atlas-qbittorrent
|
||||
Image={{ atlas_qbittorrent_image }}
|
||||
UserNS=keep-id
|
||||
User={{ atlas_admin_uid }}
|
||||
Group={{ atlas_admin_gid }}
|
||||
PublishPort={{ ansible_host }}:{{ atlas_qbittorrent_web_port }}:{{ atlas_qbittorrent_web_port }}
|
||||
Environment=QBT_LEGAL_NOTICE=confirm
|
||||
Environment=QBT_WEBUI_PORT={{ atlas_qbittorrent_web_port }}
|
||||
Environment=XDG_CACHE_HOME=/tmp/cache
|
||||
Environment=TZ={{ atlas_timezone }}
|
||||
Environment=UMASK=007
|
||||
Volume={{ atlas_qbittorrent_state_dir }}:/config:Z
|
||||
Volume={{ atlas_qbittorrent_downloads_dir }}:/downloads:z
|
||||
ReadOnly=true
|
||||
Tmpfs=/tmp:rw,nosuid,nodev
|
||||
NoNewPrivileges=true
|
||||
DropCapability=all
|
||||
StopTimeout=1800
|
||||
|
||||
[Service]
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
TimeoutStartSec=900
|
||||
TimeoutStopSec=1900
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -562,6 +562,10 @@
|
||||
name: "{{ item.value.npm_package }}"
|
||||
global: true
|
||||
state: latest
|
||||
register: ai_agent_npm_install
|
||||
retries: "{{ ai_agents_npm_install_retries }}"
|
||||
delay: "{{ ai_agents_npm_install_retry_delay }}"
|
||||
until: ai_agent_npm_install is succeeded
|
||||
loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}"
|
||||
when:
|
||||
- item.value.install_enabled | bool
|
||||
|
||||
144
ansible/roles/profile_desktop_gnome/files/thunderbird_profile.py
Normal file
144
ansible/roles/profile_desktop_gnome/files/thunderbird_profile.py
Normal file
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only discovery and registry plan; never read stored login credentials."""
|
||||
|
||||
import configparser
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
def read_ini(path):
|
||||
result = configparser.RawConfigParser()
|
||||
result.optionxform = str
|
||||
if path.exists():
|
||||
with path.open() as source:
|
||||
result.read_file(source)
|
||||
return result
|
||||
|
||||
|
||||
def preferences(path):
|
||||
if not path.exists():
|
||||
return {}
|
||||
result = {}
|
||||
for key, value in re.findall(
|
||||
r'^\s*user_pref\("([^"\n]+)",\s*(.*?)\);',
|
||||
path.read_text(), re.MULTILINE,
|
||||
):
|
||||
try:
|
||||
result[key] = json.loads(value)
|
||||
except ValueError:
|
||||
continue
|
||||
return result
|
||||
|
||||
|
||||
def has_account(path):
|
||||
# user.js alone is only a bootstrap, not an account used by Thunderbird.
|
||||
prefs = preferences(path / 'prefs.js')
|
||||
for account in str(prefs.get('mail.accountmanager.accounts', '')).split(','):
|
||||
server = prefs.get('mail.account.' + account.strip() + '.server')
|
||||
prefix = 'mail.server.' + str(server) + '.'
|
||||
if (prefs.get(prefix + 'type') in ('imap', 'pop3', 'nntp')
|
||||
and prefs.get(prefix + 'hostname')):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def profile_path(root, registry, section):
|
||||
value = registry.get(section, 'Path')
|
||||
return (root / value if registry.get(section, 'IsRelative', fallback='1') == '1'
|
||||
else Path(value)).resolve()
|
||||
|
||||
|
||||
def render(registry):
|
||||
output = io.StringIO()
|
||||
registry.write(output, space_around_delimiters=False)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def plan(home, profile_dir, profile_name):
|
||||
home = Path(home)
|
||||
# A legacy directory takes precedence over the XDG registry on this build.
|
||||
roots = [home / '.thunderbird', home / '.config/thunderbird']
|
||||
root = next((p for p in roots if p.exists()), roots[1])
|
||||
registries = {p: read_ini(p / 'profiles.ini') for p in roots}
|
||||
candidates = []
|
||||
install_ids = set()
|
||||
for base, registry in registries.items():
|
||||
installs = read_ini(base / 'installs.ini')
|
||||
defaults = {registry.get(s, 'Default', fallback='')
|
||||
for s in registry.sections() if s.startswith('Install')}
|
||||
defaults.update(installs.get(s, 'Default', fallback='')
|
||||
for s in installs.sections())
|
||||
for section in registry.sections():
|
||||
if not re.fullmatch(r'Profile\d+', section):
|
||||
continue
|
||||
path = profile_path(base, registry, section)
|
||||
if has_account(path):
|
||||
candidates.append((registry.get(section, 'Path') not in defaults,
|
||||
base != root, str(path), path))
|
||||
# Reuse installation associations, including those in the other root.
|
||||
install_ids.update(s[7:] for s in registry.sections() if s.startswith('Install'))
|
||||
install_ids.update(installs.sections())
|
||||
# Also find unregistered profiles, without following arbitrary subtrees.
|
||||
if base.exists():
|
||||
for child in sorted(base.iterdir()):
|
||||
if child.is_dir() and has_account(child):
|
||||
candidates.append((True, base != root, str(child.resolve()), child.resolve()))
|
||||
existing = bool(candidates)
|
||||
selected = min(candidates)[3] if existing else root / profile_dir
|
||||
if not existing:
|
||||
number = 0
|
||||
while selected.exists():
|
||||
bootstrap = selected / 'user.js'
|
||||
if (not (selected / 'prefs.js').exists() and bootstrap.exists()
|
||||
and bootstrap.read_text().startswith('// Managed by Ansible from profile_desktop_gnome')):
|
||||
break
|
||||
number += 1
|
||||
selected = root / (profile_dir + '-' + str(number))
|
||||
registry = registries[root]
|
||||
section = next((s for s in registry.sections()
|
||||
if re.fullmatch(r'Profile\d+', s)
|
||||
and profile_path(root, registry, s) == selected), None)
|
||||
if section is None:
|
||||
number = 0
|
||||
while registry.has_section('Profile' + str(number)):
|
||||
number += 1
|
||||
section = 'Profile' + str(number)
|
||||
registry.add_section(section)
|
||||
registry.set(section, 'Name', profile_name if not existing else selected.name)
|
||||
registry.set(section, 'IsRelative', '0')
|
||||
registry.set(section, 'Path', str(selected))
|
||||
for other in registry.sections():
|
||||
if re.fullmatch(r'Profile\d+', other):
|
||||
registry.remove_option(other, 'Default')
|
||||
registry.set(section, 'Default', '1')
|
||||
if not registry.has_section('General'):
|
||||
registry.add_section('General')
|
||||
registry.set('General', 'StartWithLastProfile', '1')
|
||||
registry.set('General', 'Version', '2')
|
||||
value = registry.get(section, 'Path')
|
||||
installs = read_ini(root / 'installs.ini')
|
||||
for install in sorted(install_ids):
|
||||
# Do not redirect a separate installation with another configured account.
|
||||
defaults = []
|
||||
for base, source in registries.items():
|
||||
default = source.get('Install' + install, 'Default', fallback='')
|
||||
if not default:
|
||||
default = read_ini(base / 'installs.ini').get(install, 'Default', fallback='')
|
||||
if default:
|
||||
defaults.append((base / default).resolve())
|
||||
if any(p != selected and has_account(p) for p in defaults):
|
||||
continue
|
||||
for target, name in ((registry, 'Install' + install), (installs, install)):
|
||||
if not target.has_section(name):
|
||||
target.add_section(name)
|
||||
target.set(name, 'Default', value)
|
||||
target.set(name, 'Locked', '1')
|
||||
return dict(root=str(root), profile=str(selected), existing_account=existing,
|
||||
profiles_ini=render(registry), installs_ini=render(installs))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(json.dumps(plan(*sys.argv[1:])))
|
||||
56
ansible/roles/profile_desktop_gnome/tasks/cline_desktop.yml
Normal file
56
ansible/roles/profile_desktop_gnome/tasks/cline_desktop.yml
Normal file
@@ -0,0 +1,56 @@
|
||||
---
|
||||
- name: Find the installed Cline Desktop launcher
|
||||
ansible.builtin.stat:
|
||||
path: "/usr/share/applications/{{ cline_desktop_launcher }}"
|
||||
get_checksum: false
|
||||
register: cline_desktop_launcher_stat
|
||||
|
||||
- name: Verify Cline Desktop installed its expected launcher
|
||||
ansible.builtin.assert:
|
||||
that: cline_desktop_launcher_stat.stat.isreg | default(false)
|
||||
fail_msg: "Cline Desktop did not install {{ cline_desktop_launcher }}."
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Find the GNOME account for the Cline favorite
|
||||
ansible.builtin.getent:
|
||||
database: passwd
|
||||
key: "{{ username }}"
|
||||
when: cline_desktop_launcher_stat.stat.isreg | default(false)
|
||||
|
||||
- name: Update only the Cline and OpenCode entries in GNOME favorites
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ ansible_facts.getent_passwd[username][1] }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ ansible_facts.getent_passwd[username][1] }}/bus"
|
||||
when: cline_desktop_launcher_stat.stat.isreg | default(false)
|
||||
block:
|
||||
- name: Read the current GNOME favorites for Cline Desktop
|
||||
ansible.builtin.command:
|
||||
argv: [gsettings, get, org.gnome.shell, favorite-apps]
|
||||
register: cline_gnome_favorites_current
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Pin the Cline Desktop launcher without reordering other favorites
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- gsettings
|
||||
- set
|
||||
- org.gnome.shell
|
||||
- favorite-apps
|
||||
- "{{ cline_gnome_favorites_desired | to_json }}"
|
||||
vars:
|
||||
cline_gnome_favorites_existing: "{{ cline_gnome_favorites_current.stdout | regex_replace('^@as ', '') | from_yaml }}"
|
||||
cline_gnome_favorites_desired: >-
|
||||
{%- set ns = namespace(apps=[]) -%}
|
||||
{%- for app in cline_gnome_favorites_existing -%}
|
||||
{%- set launcher = cline_desktop_launcher
|
||||
if app in ['ai.opencode.desktop.desktop', 'opencode-desktop.desktop'] else app -%}
|
||||
{%- if launcher != cline_desktop_launcher or launcher not in ns.apps -%}
|
||||
{%- set ns.apps = ns.apps + [launcher] -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{{ ns.apps if cline_desktop_launcher in ns.apps else ns.apps + [cline_desktop_launcher] }}
|
||||
when: cline_gnome_favorites_desired != cline_gnome_favorites_existing
|
||||
changed_when: true
|
||||
@@ -41,7 +41,7 @@
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "{{ item.mode }}"
|
||||
loop: "{{ desktop_common_dotfiles | default([]) }}"
|
||||
loop: "{{ (desktop_common_dotfiles | default([])) + (desktop_gnome_dotfiles | default([])) }}"
|
||||
loop_control:
|
||||
label: "{{ item.dest }}"
|
||||
|
||||
@@ -279,3 +279,17 @@
|
||||
loop_control:
|
||||
label: "{{ item }}"
|
||||
when: workstation_firewall_backend | default('firewalld') == 'firewalld'
|
||||
|
||||
- name: Configure Thunderbird for iCloud
|
||||
tags: [dotfiles, dotfiles:desktop, gnome, thunderbird]
|
||||
ansible.builtin.import_tasks: thunderbird.yml
|
||||
when: thunderbird_icloud_enabled | default(false) | bool
|
||||
|
||||
- name: Configure native VS Code
|
||||
tags: [vscode]
|
||||
ansible.builtin.import_tasks: vscode.yml
|
||||
|
||||
- name: Pin Cline Desktop in GNOME
|
||||
tags: [cline_desktop]
|
||||
ansible.builtin.import_tasks: cline_desktop.yml
|
||||
when: cline_desktop_install_enabled | default(false) | bool
|
||||
|
||||
126
ansible/roles/profile_desktop_gnome/tasks/thunderbird.yml
Normal file
126
ansible/roles/profile_desktop_gnome/tasks/thunderbird.yml
Normal file
@@ -0,0 +1,126 @@
|
||||
---
|
||||
- name: Inspect existing Thunderbird profiles without changing them
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.command:
|
||||
argv:
|
||||
- "{{ ansible_facts.python.executable }}"
|
||||
- -c
|
||||
- "{{ lookup('ansible.builtin.file', role_path + '/files/thunderbird_profile.py') }}"
|
||||
- "{{ user_home }}"
|
||||
- "{{ thunderbird_profile_dir }}"
|
||||
- "{{ thunderbird_profile_name }}"
|
||||
become: true
|
||||
become_user: "{{ username }}"
|
||||
register: thunderbird_profile_probe
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
|
||||
- name: Select an existing account or plan an iCloud bootstrap
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.set_fact:
|
||||
thunderbird_selected: "{{ thunderbird_profile_probe.stdout | from_json }}"
|
||||
|
||||
- name: Require the iCloud address only when no configured account exists
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- vault_icloud_email is defined
|
||||
- vault_icloud_email | length > 0
|
||||
- vault_icloud_email != 'REPLACE_ME'
|
||||
- vault_icloud_email is match('^[^@\\s]+@[^@\\s]+$')
|
||||
fail_msg: >-
|
||||
vault_icloud_email must hold the iCloud mail address before a new
|
||||
Thunderbird profile can be provisioned.
|
||||
quiet: true
|
||||
when: not thunderbird_selected.existing_account
|
||||
|
||||
- name: Check whether Thunderbird is running
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.command:
|
||||
argv: [pgrep, -u, "{{ username }}", -x, thunderbird]
|
||||
register: thunderbird_running
|
||||
changed_when: false
|
||||
failed_when: thunderbird_running.rc not in [0, 1]
|
||||
check_mode: false
|
||||
|
||||
- name: Require Thunderbird to be closed before selecting its profile
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.assert:
|
||||
that: thunderbird_running.rc == 1
|
||||
fail_msg: Close Thunderbird before running the thunderbird tag; it is never stopped automatically.
|
||||
|
||||
- name: Create the selected Thunderbird registry directory
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.file:
|
||||
path: "{{ thunderbird_selected.root }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Create a new profile only when no configured account exists
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.file:
|
||||
path: "{{ thunderbird_selected.profile }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
when: not thunderbird_selected.existing_account
|
||||
|
||||
- name: Seed iCloud defaults only in a profile without a configured account
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.template:
|
||||
src: thunderbird/user.js.j2
|
||||
dest: "{{ thunderbird_selected.profile }}/user.js"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0600"
|
||||
force: false
|
||||
no_log: true
|
||||
when: not thunderbird_selected.existing_account
|
||||
|
||||
- name: Discover the Thunderbird installation directory for first-start profile adoption
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.stat:
|
||||
path: "{{ item }}/application.ini"
|
||||
loop: [/usr/lib64/thunderbird, /usr/lib/thunderbird]
|
||||
register: thunderbird_installation
|
||||
when: not thunderbird_selected.existing_account
|
||||
|
||||
- name: Seed compatibility information so Thunderbird adopts the new default profile
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.copy:
|
||||
content: |
|
||||
[Compatibility]
|
||||
LastPlatformDir={{ item.item }}
|
||||
LastAppDir={{ item.item }}
|
||||
dest: "{{ thunderbird_selected.profile }}/compatibility.ini"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0600"
|
||||
force: false
|
||||
loop: "{{ thunderbird_installation.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item }}"
|
||||
when:
|
||||
- not thunderbird_selected.existing_account
|
||||
- item.stat.exists | default(false)
|
||||
|
||||
- name: Select the profile while preserving other registered profiles
|
||||
tags: [thunderbird]
|
||||
ansible.builtin.copy:
|
||||
content: "{{ item.content }}"
|
||||
dest: "{{ thunderbird_selected.root }}/{{ item.name }}"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0600"
|
||||
backup: true
|
||||
loop:
|
||||
- name: profiles.ini
|
||||
content: "{{ thunderbird_selected.profiles_ini }}"
|
||||
- name: installs.ini
|
||||
content: "{{ thunderbird_selected.installs_ini }}"
|
||||
loop_control:
|
||||
label: "{{ item.name }}"
|
||||
when: item.content | length > 0
|
||||
70
ansible/roles/profile_desktop_gnome/tasks/vscode.yml
Normal file
70
ansible/roles/profile_desktop_gnome/tasks/vscode.yml
Normal file
@@ -0,0 +1,70 @@
|
||||
---
|
||||
- name: Configure Microsoft VS Code repository
|
||||
ansible.builtin.yum_repository:
|
||||
name: code
|
||||
description: Visual Studio Code
|
||||
baseurl: https://packages.microsoft.com/yumrepos/vscode
|
||||
enabled: true
|
||||
gpgcheck: true
|
||||
gpgkey: https://packages.microsoft.com/keys/microsoft.asc
|
||||
|
||||
- name: Install native VS Code
|
||||
ansible.builtin.dnf:
|
||||
name: code
|
||||
state: present
|
||||
|
||||
- name: List installed VS Code extensions
|
||||
ansible.builtin.command:
|
||||
argv: [code, --list-extensions]
|
||||
become: true
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
register: vscode_installed_extensions
|
||||
changed_when: false
|
||||
check_mode: false
|
||||
when:
|
||||
- vscode_extensions | length > 0
|
||||
- not ansible_check_mode
|
||||
|
||||
- name: Install missing VS Code extensions
|
||||
ansible.builtin.command:
|
||||
argv: [code, --install-extension, "{{ item }}"]
|
||||
become: true
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
loop: "{{ vscode_extensions }}"
|
||||
when:
|
||||
- not ansible_check_mode
|
||||
- item | lower not in (vscode_installed_extensions.stdout_lines | default([]) | map('lower') | list)
|
||||
changed_when: true
|
||||
|
||||
- name: Ensure VS Code user configuration directory exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/.config/Code/User"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
when: vscode_settings is not none or vscode_keybindings | length > 0
|
||||
|
||||
- name: Deploy explicitly managed VS Code settings
|
||||
ansible.builtin.copy:
|
||||
dest: "{{ user_home }}/.config/Code/User/settings.json"
|
||||
content: "{{ vscode_settings | to_nice_json }}\n"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
when: vscode_settings is not none
|
||||
|
||||
- name: Deploy managed VS Code keybindings
|
||||
ansible.builtin.copy:
|
||||
dest: "{{ user_home }}/.config/Code/User/keybindings.json"
|
||||
content: "{{ vscode_keybindings | to_nice_json }}\n"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
when: vscode_keybindings | length > 0
|
||||
@@ -0,0 +1,66 @@
|
||||
// Managed by Ansible from profile_desktop_gnome (tag: thunderbird).
|
||||
// Thunderbird rewrites prefs.js on exit, so the declared defaults live here
|
||||
// and are re-applied at every start. Seeded only when no account exists;
|
||||
// Ansible does not overwrite this file or configure an existing account.
|
||||
//
|
||||
// The account password is intentionally absent: iCloud mail requires an
|
||||
// app-specific password, which Thunderbird prompts for and stores in its own
|
||||
// credential store on first use.
|
||||
|
||||
// Mail account
|
||||
user_pref("mail.accountmanager.accounts", "account1");
|
||||
user_pref("mail.accountmanager.defaultaccount", "account1");
|
||||
user_pref("mail.account.account1.server", "server1");
|
||||
user_pref("mail.account.account1.identities", "id1");
|
||||
|
||||
user_pref("mail.server.server1.type", "imap");
|
||||
user_pref("mail.server.server1.hostname", "{{ thunderbird_icloud_imap_host }}");
|
||||
user_pref("mail.server.server1.port", {{ thunderbird_icloud_imap_port }});
|
||||
user_pref("mail.server.server1.socketType", 3);
|
||||
user_pref("mail.server.server1.authMethod", 3);
|
||||
user_pref("mail.server.server1.userName", "{{ thunderbird_icloud_email }}");
|
||||
user_pref("mail.server.server1.name", "{{ thunderbird_icloud_account_name }}");
|
||||
user_pref("mail.server.server1.directory-rel", "[ProfD]ImapMail/{{ thunderbird_icloud_imap_host }}");
|
||||
user_pref("mail.server.server1.directory", "{{ thunderbird_selected.profile }}/ImapMail/{{ thunderbird_icloud_imap_host }}");
|
||||
user_pref("mail.server.server1.max_cached_connections", 5);
|
||||
user_pref("mail.server.server1.check_new_mail", true);
|
||||
user_pref("mail.server.server1.check_time", 10);
|
||||
user_pref("mail.server.server1.login_at_startup", true);
|
||||
user_pref("mail.server.server1.empty_trash", false);
|
||||
|
||||
user_pref("mail.identity.id1.fullName", "{{ thunderbird_full_name }}");
|
||||
user_pref("mail.identity.id1.useremail", "{{ thunderbird_icloud_email }}");
|
||||
user_pref("mail.identity.id1.valid", true);
|
||||
user_pref("mail.identity.id1.smtpServer", "smtp1");
|
||||
user_pref("mail.identity.id1.compose_html", true);
|
||||
user_pref("mail.identity.id1.fcc_folder", "mailbox://{{ thunderbird_icloud_email }}@{{ thunderbird_icloud_imap_host }}/Sent%20Messages");
|
||||
user_pref("mail.identity.id1.draft_folder", "mailbox://{{ thunderbird_icloud_email }}@{{ thunderbird_icloud_imap_host }}/Drafts");
|
||||
|
||||
user_pref("mail.smtpservers", "smtp1");
|
||||
user_pref("mail.smtpserver.smtp1.hostname", "{{ thunderbird_icloud_smtp_host }}");
|
||||
user_pref("mail.smtpserver.smtp1.port", {{ thunderbird_icloud_smtp_port }});
|
||||
user_pref("mail.smtpserver.smtp1.try_ssl", 2);
|
||||
user_pref("mail.smtpserver.smtp1.authMethod", 3);
|
||||
user_pref("mail.smtpserver.smtp1.username", "{{ thunderbird_icloud_email }}");
|
||||
user_pref("mail.smtpserver.smtp1.description", "{{ thunderbird_icloud_account_name }} SMTP");
|
||||
|
||||
// Calendar (CalDAV). Calendars are discovered from the registry branch.
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.type", "caldav");
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.name", "{{ thunderbird_icloud_account_name }}");
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.uri", "{{ thunderbird_icloud_caldav_url }}");
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.username", "{{ thunderbird_icloud_email }}");
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.refreshInterval", 30);
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.readOnly", false);
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.disabled", false);
|
||||
user_pref("calendar.registry.{{ thunderbird_icloud_calendar_id }}.color", "#3a87ad");
|
||||
user_pref("calendar.list.sortOrder", "{{ thunderbird_icloud_calendar_id }}");
|
||||
|
||||
// Address book (CardDAV). dirType 102 is nsIAbManager.CARDDAV_DIRECTORY_TYPE.
|
||||
user_pref("ldap_2.servers.icloud.dirType", 102);
|
||||
user_pref("ldap_2.servers.icloud.uid", "{{ thunderbird_icloud_addressbook_uid }}");
|
||||
user_pref("ldap_2.servers.icloud.description", "{{ thunderbird_icloud_account_name }}");
|
||||
user_pref("ldap_2.servers.icloud.filename", "abook-icloud.sqlite");
|
||||
user_pref("ldap_2.servers.icloud.isOffline", false);
|
||||
user_pref("ldap_2.servers.icloud.position", 3);
|
||||
user_pref("ldap_2.servers.icloud.carddav.url", "{{ thunderbird_icloud_carddav_url }}");
|
||||
user_pref("ldap_2.servers.icloud.carddav.username", "{{ thunderbird_icloud_email }}");
|
||||
@@ -42,6 +42,10 @@
|
||||
global: true
|
||||
state: latest
|
||||
become: true
|
||||
register: ai_agent_npm_install
|
||||
retries: "{{ ai_agents_npm_install_retries }}"
|
||||
delay: "{{ ai_agents_npm_install_retry_delay }}"
|
||||
until: ai_agent_npm_install is succeeded
|
||||
loop: "{{ ai_agents | dict2items | selectattr('value.npm_package', 'defined') | list }}"
|
||||
when:
|
||||
- item.value.install_enabled | bool
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
ARG MAVEN_VERSION=3.9.16
|
||||
ARG NODE_VERSION=20.18.3
|
||||
FROM docker.io/library/maven:${MAVEN_VERSION}-eclipse-temurin-25 AS maven
|
||||
FROM docker.io/library/node:${NODE_VERSION}-bookworm-slim AS node
|
||||
# Java 25 runs both the application and the language servers.
|
||||
FROM mcr.microsoft.com/devcontainers/java:25-bookworm
|
||||
USER root
|
||||
COPY --from=maven /usr/share/maven/ /usr/share/maven/
|
||||
COPY --from=node /usr/local/bin/node /usr/local/bin/node
|
||||
COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/
|
||||
RUN ln -s /usr/share/maven/bin/mvn /usr/local/bin/mvn \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
|
||||
&& java -version \
|
||||
&& mvn -v \
|
||||
&& node --version \
|
||||
&& npm install --global --no-audit --no-fund @anthropic-ai/claude-code@2.1.312 cline@3.0.74 \
|
||||
&& npm cache clean --force
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client zoxide \
|
||||
&& arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in \
|
||||
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
|
||||
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
|
||||
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
|
||||
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
|
||||
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb
|
||||
ARG KUBECTL_VERSION=1.37.1
|
||||
ARG HELM_VERSION=4.2.2
|
||||
RUN arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in \
|
||||
amd64) kubectl_sha=65691ff77eb6fa44c908b77a1082c9f092c3b9733b5cefabec0d1104890e21a8; helm_sha=9adafecab4d406853bba163a70e9f104f47dbbf65ce24b7653bae7e36150bcb6 ;; \
|
||||
arm64) kubectl_sha=ff749f4b78d9c4f1ec87307df9b50119ed819e2094aa9810cb9acffc3286c8c7; helm_sha=78803142087a0069fa4b50d3f32a84d3ef25c14d1ee8a40fbccf86a6216d2f36 ;; \
|
||||
*) echo "Unsupported architecture for kubectl/helm: $arch" >&2; exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL --retry 3 "https://dl.k8s.io/release/v${KUBECTL_VERSION}/bin/linux/${arch}/kubectl" -o /tmp/kubectl \
|
||||
&& echo "$kubectl_sha /tmp/kubectl" | sha256sum -c - \
|
||||
&& install -m 0755 /tmp/kubectl /usr/local/bin/kubectl \
|
||||
&& curl -fsSL --retry 3 "https://get.helm.sh/helm-v${HELM_VERSION}-linux-${arch}.tar.gz" -o /tmp/helm.tgz \
|
||||
&& echo "$helm_sha /tmp/helm.tgz" | sha256sum -c - \
|
||||
&& tar -xzf /tmp/helm.tgz -C /tmp "linux-${arch}/helm" \
|
||||
&& install -m 0755 "/tmp/linux-${arch}/helm" /usr/local/bin/helm \
|
||||
&& rm -rf /tmp/kubectl /tmp/helm.tgz "/tmp/linux-${arch}" \
|
||||
&& kubectl version --client \
|
||||
&& helm version --short
|
||||
ARG GLAB_VERSION=1.114.0
|
||||
RUN arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in \
|
||||
amd64) sha256=6df680f88a2a45700d1dd6a08a44a74838473ef3dcc5cb1ad243f4d1fd704ad0 ;; \
|
||||
arm64) sha256=c2bcb44cc10d849cccb879e687f3b9e102a3415c3d02f0cecfd9ce1442519350 ;; \
|
||||
*) echo "Unsupported architecture for glab: $arch" >&2; exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL --retry 3 "https://gitlab.com/gitlab-org/cli/-/releases/v${GLAB_VERSION}/downloads/glab_${GLAB_VERSION}_linux_${arch}.deb" -o /tmp/glab.deb \
|
||||
&& echo "$sha256 /tmp/glab.deb" | sha256sum -c - \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends /tmp/glab.deb \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/glab.deb \
|
||||
&& glab --version
|
||||
COPY --chown=vscode:vscode bashrc /home/vscode/.bashrc
|
||||
COPY --chown=vscode:vscode bashrc.aliases /home/vscode/.bashrc.aliases
|
||||
USER vscode
|
||||
# Keep this file writable so VS Code can register its Git credential helper.
|
||||
RUN git config --file /home/vscode/.gitconfig include.path /run/ecaas-git/gitconfig
|
||||
@@ -0,0 +1,49 @@
|
||||
ARG MAVEN_VERSION=3.9.16
|
||||
FROM docker.io/library/maven:${MAVEN_VERSION}-eclipse-temurin-11 AS maven
|
||||
FROM docker.io/library/node:22.23.4-bookworm-slim AS node
|
||||
# Java 21 runs the language servers only. The final image keeps Java 11 on PATH.
|
||||
FROM mcr.microsoft.com/devcontainers/java:21-bookworm AS ide
|
||||
FROM mcr.microsoft.com/devcontainers/java:11-bookworm
|
||||
USER root
|
||||
COPY --from=ide /usr/lib/jvm/msopenjdk-current/ /opt/jdk-21/
|
||||
COPY --from=maven /usr/share/maven/ /usr/share/maven/
|
||||
COPY --from=node /usr/local/bin/node /usr/local/bin/node
|
||||
COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/
|
||||
RUN ln -s /usr/share/maven/bin/mvn /usr/local/bin/mvn \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
|
||||
&& java -version \
|
||||
&& /opt/jdk-21/bin/java -version \
|
||||
&& mvn -v \
|
||||
&& npm install --global --no-audit --no-fund @anthropic-ai/claude-code@2.1.312 cline@3.0.74 \
|
||||
&& npm cache clean --force
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client zoxide \
|
||||
&& arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in \
|
||||
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
|
||||
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
|
||||
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
|
||||
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
|
||||
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb
|
||||
ARG GLAB_VERSION=1.114.0
|
||||
RUN arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in \
|
||||
amd64) sha256=6df680f88a2a45700d1dd6a08a44a74838473ef3dcc5cb1ad243f4d1fd704ad0 ;; \
|
||||
arm64) sha256=c2bcb44cc10d849cccb879e687f3b9e102a3415c3d02f0cecfd9ce1442519350 ;; \
|
||||
*) echo "Unsupported architecture for glab: $arch" >&2; exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL --retry 3 "https://gitlab.com/gitlab-org/cli/-/releases/v${GLAB_VERSION}/downloads/glab_${GLAB_VERSION}_linux_${arch}.deb" -o /tmp/glab.deb \
|
||||
&& echo "$sha256 /tmp/glab.deb" | sha256sum -c - \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends /tmp/glab.deb \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/glab.deb \
|
||||
&& glab --version
|
||||
COPY --chown=vscode:vscode bashrc /home/vscode/.bashrc
|
||||
COPY --chown=vscode:vscode bashrc.aliases /home/vscode/.bashrc.aliases
|
||||
USER vscode
|
||||
# Keep this file writable so VS Code can register its Git credential helper.
|
||||
RUN git config --file /home/vscode/.gitconfig include.path /run/ecaas-git/gitconfig
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
- name: Refuse to deploy the cdp workspace outside WSL
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- "'wsl2' in (ansible_facts.kernel | default('') | lower)"
|
||||
- ansible_facts.distribution | default('') == 'Fedora'
|
||||
fail_msg: Run this deployment from the Fedora WSL 2 distribution on deadalus.
|
||||
|
||||
- name: Prepare the cdp workspace and private configuration
|
||||
vars:
|
||||
ecaas_agent_state: "{{ user_home }}/.local/state/ecaas-devcontainer"
|
||||
ecaas_git_available_cas: >-
|
||||
{{ ecaas_git_ca_probe.results | selectattr('stat.isreg', 'defined') |
|
||||
selectattr('stat.isreg') | map(attribute='item') | list }}
|
||||
block:
|
||||
- name: Prepare the shared Git configuration
|
||||
ansible.builtin.import_tasks: ecaas_git.yml
|
||||
|
||||
- name: Ensure the cdp dev container directory exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ workstation_cdp_workspace }}/.devcontainer"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
|
||||
- name: Ensure the local Maven directory mounted into the container exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/.m2"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
|
||||
- name: Ensure the local Kubernetes directory mounted into the container exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/.kube"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Ensure the persistent Bash history directory mounted into the container exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/.local/state/devcontainer-bash-history/cdp"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Ensure the private ecaas Git state directory exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ ecaas_agent_state }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Ensure the local agent configuration directories mounted into the container exist
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/{{ item.path }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "{{ item.mode }}"
|
||||
loop:
|
||||
- { path: .claude, mode: "0700" }
|
||||
- { path: .cline, mode: "0700" }
|
||||
- { path: .agents, mode: "0755" }
|
||||
- { path: .config/ai, mode: "0755" }
|
||||
- { path: .config/glab-cli, mode: "0700" }
|
||||
|
||||
- name: Deploy the cdp dev container configuration
|
||||
ansible.builtin.template:
|
||||
src: cdp-devcontainer.json.j2
|
||||
dest: "{{ workstation_cdp_workspace }}/.devcontainer/devcontainer.json"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
|
||||
- name: Deploy the cdp dev container build files
|
||||
ansible.builtin.copy:
|
||||
src: "{{ item.src }}"
|
||||
dest: "{{ workstation_cdp_workspace }}/.devcontainer/{{ item.dest }}"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
loop:
|
||||
- src: cdp-devcontainer.Dockerfile
|
||||
dest: Dockerfile
|
||||
- src: "{{ playbook_dir }}/../dotfiles/common/.bashrc"
|
||||
dest: bashrc
|
||||
loop_control:
|
||||
label: "{{ item.dest }}"
|
||||
|
||||
- name: Deploy the shared Bash aliases without the production tunnel
|
||||
ansible.builtin.copy:
|
||||
content: >-
|
||||
{{ lookup('ansible.builtin.file', playbook_dir ~ '/../dotfiles/common/.bashrc.aliases')
|
||||
| regex_replace('(?m)^(#[^\n]*Nginx Proxy Manager[^\n]*\n)?alias npm-tunnel=[^\n]*\n?', '') }}
|
||||
dest: "{{ workstation_cdp_workspace }}/.devcontainer/bashrc.aliases"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
@@ -0,0 +1,130 @@
|
||||
---
|
||||
- name: Refuse to deploy the ecaas workspace outside WSL
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- "'wsl2' in (ansible_facts.kernel | default('') | lower)"
|
||||
- ansible_facts.distribution | default('') == 'Fedora'
|
||||
fail_msg: Run this deployment from the Fedora WSL 2 distribution on deadalus.
|
||||
|
||||
- name: Prepare the ecaas workspace and private configuration
|
||||
vars:
|
||||
ecaas_agent_state: "{{ user_home }}/.local/state/ecaas-devcontainer"
|
||||
ecaas_git_available_cas: >-
|
||||
{{ ecaas_git_ca_probe.results | selectattr('stat.isreg', 'defined') |
|
||||
selectattr('stat.isreg') | map(attribute='item') | list }}
|
||||
block:
|
||||
- name: Prepare the ecaas Git configuration
|
||||
ansible.builtin.import_tasks: ecaas_git.yml
|
||||
|
||||
- name: Ensure the ecaas dev container directory exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ workstation_ecaas_workspace }}/.devcontainer"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
|
||||
- name: Ensure the local Maven directory mounted into the container exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/.m2"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0755"
|
||||
|
||||
- name: Ensure the persistent Bash history directory mounted into the container exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/.local/state/devcontainer-bash-history/ecaas"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Ensure the private ecaas Git state directory exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ ecaas_agent_state }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Ensure the local agent configuration directories mounted into the container exist
|
||||
ansible.builtin.file:
|
||||
path: "{{ user_home }}/{{ item.path }}"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "{{ item.mode }}"
|
||||
loop:
|
||||
- { path: .claude, mode: "0700" }
|
||||
- { path: .cline, mode: "0700" }
|
||||
- { path: .agents, mode: "0755" }
|
||||
- { path: .config/ai, mode: "0755" }
|
||||
- { path: .config/glab-cli, mode: "0700" }
|
||||
|
||||
- name: Read the WSL Claude account state
|
||||
ansible.builtin.slurp:
|
||||
src: "{{ user_home }}/.claude.json"
|
||||
register: ecaas_claude_account_state
|
||||
failed_when: false
|
||||
no_log: true
|
||||
|
||||
- name: Read the Claude state used when CLAUDE_CONFIG_DIR is set
|
||||
ansible.builtin.slurp:
|
||||
src: "{{ user_home }}/.claude/.claude.json"
|
||||
register: ecaas_claude_dir_state
|
||||
failed_when: false
|
||||
no_log: true
|
||||
|
||||
- name: Seed missing Claude account and onboarding state for the container
|
||||
ansible.builtin.copy:
|
||||
content: >-
|
||||
{{ (ecaas_claude_account_state.content | b64decode | from_json
|
||||
| dict2items
|
||||
| selectattr('key', 'in', ['oauthAccount', 'hasCompletedOnboarding', 'userID'])
|
||||
| items2dict)
|
||||
| combine(ecaas_claude_dir_state.content | default('e30=' | b64encode) | b64decode | from_json)
|
||||
| to_nice_json }}
|
||||
dest: "{{ user_home }}/.claude/.claude.json"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0600"
|
||||
when: ecaas_claude_account_state.content is defined
|
||||
no_log: true
|
||||
diff: false
|
||||
|
||||
- name: Deploy the ecaas dev container configuration
|
||||
ansible.builtin.template:
|
||||
src: ecaas-devcontainer.json.j2
|
||||
dest: "{{ workstation_ecaas_workspace }}/.devcontainer/devcontainer.json"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
|
||||
- name: Deploy the ecaas dev container build files
|
||||
ansible.builtin.copy:
|
||||
src: "{{ item.src }}"
|
||||
dest: "{{ workstation_ecaas_workspace }}/.devcontainer/{{ item.dest }}"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
loop:
|
||||
- src: ecaas-devcontainer.Dockerfile
|
||||
dest: Dockerfile
|
||||
- src: "{{ playbook_dir }}/../dotfiles/common/.bashrc"
|
||||
dest: bashrc
|
||||
loop_control:
|
||||
label: "{{ item.dest }}"
|
||||
|
||||
- name: Deploy the shared Bash aliases without the production tunnel
|
||||
ansible.builtin.copy:
|
||||
content: >-
|
||||
{{ lookup('ansible.builtin.file', playbook_dir ~ '/../dotfiles/common/.bashrc.aliases')
|
||||
| regex_replace('(?m)^(#[^\n]*Nginx Proxy Manager[^\n]*\n)?alias npm-tunnel=[^\n]*\n?', '') }}
|
||||
dest: "{{ workstation_ecaas_workspace }}/.devcontainer/bashrc.aliases"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
backup: true
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
- name: Locate the Git CA files configured for the workstation
|
||||
ansible.builtin.stat:
|
||||
path: "{{ user_home }}/.local/share/certs/{{ item.certificate }}"
|
||||
follow: true
|
||||
get_checksum: false
|
||||
get_mime: false
|
||||
loop: "{{ workstation_git_https_cas }}"
|
||||
loop_control:
|
||||
label: "{{ item.certificate }}"
|
||||
register: ecaas_git_ca_probe
|
||||
|
||||
- name: Require the ecaas Git CA before deploying the dev container
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- workstation_ecaas_git_required_ca in (ecaas_git_available_cas | map(attribute='certificate') | list)
|
||||
fail_msg: "Install the existing workstation CA at {{ user_home }}/.local/share/certs/{{ workstation_ecaas_git_required_ca }} first."
|
||||
|
||||
- name: Verify the available Git CA files are public PEM certificates
|
||||
ansible.builtin.shell: |
|
||||
if grep -q -- 'PRIVATE KEY-----' "$ECAAS_GIT_CA"; then
|
||||
exit 1
|
||||
fi
|
||||
openssl x509 -in "$ECAAS_GIT_CA" -noout
|
||||
environment:
|
||||
ECAAS_GIT_CA: "{{ user_home }}/.local/share/certs/{{ item.item.certificate }}"
|
||||
become_user: "{{ username }}"
|
||||
check_mode: false
|
||||
changed_when: false
|
||||
when: item.stat.isreg | default(false)
|
||||
loop: "{{ ecaas_git_ca_probe.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item.certificate }}"
|
||||
|
||||
- name: Ensure the private ecaas Git configuration directory exists
|
||||
ansible.builtin.file:
|
||||
path: "{{ ecaas_agent_state }}/git"
|
||||
state: directory
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Render the workstation Git configuration for the ecaas container
|
||||
ansible.builtin.template:
|
||||
src: "{{ playbook_dir }}/templates/workstation/.gitconfig.j2"
|
||||
dest: "{{ ecaas_agent_state }}/git/gitconfig"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0600"
|
||||
vars:
|
||||
workstation_git_in_devcontainer: true
|
||||
workstation_git_container_cas: "{{ ecaas_git_available_cas }}"
|
||||
no_log: true
|
||||
diff: false
|
||||
|
||||
- name: Deploy the workstation Git ignore and delta theme files
|
||||
ansible.builtin.copy:
|
||||
src: "{{ playbook_dir }}/../dotfiles/workstation/{{ item }}"
|
||||
dest: "{{ ecaas_agent_state }}/git/{{ item }}"
|
||||
owner: "{{ username }}"
|
||||
group: "{{ user_group }}"
|
||||
mode: "0644"
|
||||
loop:
|
||||
- .gitignore_global
|
||||
- .themes.gitignore
|
||||
@@ -1,4 +1,14 @@
|
||||
---
|
||||
- name: Deploy the ecaas Java 11 dev container
|
||||
ansible.builtin.import_tasks: ecaas_devcontainer.yml
|
||||
when: workstation_ecaas_workspace is defined
|
||||
tags: [ecaas_devcontainer]
|
||||
|
||||
- name: Deploy the cdp Java 25 dev container
|
||||
ansible.builtin.import_tasks: cdp_devcontainer.yml
|
||||
when: workstation_cdp_workspace is defined
|
||||
tags: [cdp_devcontainer]
|
||||
|
||||
- name: Ensure Windows Emacs authoring directories exist
|
||||
tags: [dotfiles, dotfiles:workstation, emacs, wsl]
|
||||
ansible.builtin.file:
|
||||
@@ -55,51 +65,6 @@
|
||||
loop_control:
|
||||
label: "{{ item.dest }}"
|
||||
|
||||
- name: Check whether the pinned Java version is installed with Mise
|
||||
tags: [packages, mise, java, wsl]
|
||||
ansible.builtin.command:
|
||||
cmd: "mise where java@{{ workstation_mise_java_version }}"
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
register: workstation_mise_java_where
|
||||
changed_when: false
|
||||
failed_when: false
|
||||
|
||||
- name: Check whether the pinned Java 25 version is installed with Mise
|
||||
tags: [packages, mise, java, wsl]
|
||||
ansible.builtin.command:
|
||||
cmd: "mise where java@{{ workstation_mise_java_25_version }}"
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
register: workstation_mise_java_25_where
|
||||
changed_when: false
|
||||
failed_when: false
|
||||
|
||||
- name: Check whether the pinned Maven version is installed with Mise
|
||||
tags: [packages, mise, maven, wsl]
|
||||
ansible.builtin.command:
|
||||
cmd: "mise where maven@{{ workstation_mise_maven_version }}"
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
register: workstation_mise_maven_where
|
||||
changed_when: false
|
||||
failed_when: false
|
||||
|
||||
- name: Install the pinned Mise tools
|
||||
tags: [packages, mise, java, maven, wsl]
|
||||
ansible.builtin.command:
|
||||
cmd: mise install
|
||||
become_user: "{{ username }}"
|
||||
environment:
|
||||
HOME: "{{ user_home }}"
|
||||
when: >-
|
||||
workstation_mise_java_where.rc != 0 or
|
||||
workstation_mise_java_25_where.rc != 0 or
|
||||
workstation_mise_maven_where.rc != 0
|
||||
|
||||
- name: Ensure WSL boot configuration file exists
|
||||
tags: [packages, services]
|
||||
ansible.builtin.file:
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"name": "cdp — Java 25 / Node 20",
|
||||
"build": {
|
||||
"dockerfile": "Dockerfile",
|
||||
"args": {
|
||||
"MAVEN_VERSION": {{ workstation_maven_version | to_json }},
|
||||
"NODE_VERSION": {{ workstation_cdp_node_version | to_json }}
|
||||
}
|
||||
},
|
||||
"remoteUser": "vscode",
|
||||
"updateRemoteUserUID": true,
|
||||
"containerEnv": {
|
||||
"CLAUDE_CONFIG_DIR": "/home/vscode/.claude",
|
||||
"HISTFILE": "/home/vscode/.bash_history.d/history"
|
||||
},
|
||||
"remoteEnv": {
|
||||
"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"
|
||||
},
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/docker-outside-of-docker:1": {
|
||||
"moby": false
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
{{ ('type=bind,source=' ~ ecaas_agent_state ~ '/git,target=/run/ecaas-git,readonly') | to_json }},
|
||||
{% for ca in ecaas_git_available_cas %}
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.local/share/certs/' ~ ca.certificate ~ ',target=/run/ecaas-git-ca/' ~ ca.certificate ~ ',readonly') | to_json }},
|
||||
{% endfor %}
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.config/ai,target=/home/vscode/.config/ai,readonly') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.local/state/devcontainer-bash-history/cdp,target=/home/vscode/.bash_history.d') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.claude,target=/home/vscode/.claude') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.cline,target=/home/vscode/.cline') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.agents,target=/home/vscode/.agents,readonly') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.m2,target=/home/vscode/.m2') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.config/glab-cli,target=/home/vscode/.config/glab-cli') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.kube,target=/home/vscode/.kube') | to_json }}
|
||||
],
|
||||
"forwardPorts": [4200, 4201, 4202, 4210, 8083, 8084],
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"vscjava.vscode-java-pack",
|
||||
"vmware.vscode-boot-dev-pack",
|
||||
"redhat.vscode-xml",
|
||||
"redhat.vscode-yaml",
|
||||
"ms-kubernetes-tools.vscode-kubernetes-tools",
|
||||
"angular.ng-template",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"saoudrizwan.claude-dev",
|
||||
"emmanuelbeziat.vscode-great-icons"
|
||||
],
|
||||
"settings": {
|
||||
"workbench.iconTheme": "vscode-great-icons",
|
||||
"java.configuration.runtimes": [
|
||||
{
|
||||
"name": "JavaSE-25",
|
||||
"path": "/usr/lib/jvm/msopenjdk-current",
|
||||
"default": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "ecaas — Java 11",
|
||||
"build": {
|
||||
"dockerfile": "Dockerfile",
|
||||
"args": {
|
||||
"MAVEN_VERSION": {{ workstation_maven_version | to_json }}
|
||||
}
|
||||
},
|
||||
"remoteUser": "vscode",
|
||||
"updateRemoteUserUID": true,
|
||||
"containerEnv": {
|
||||
"CLAUDE_CONFIG_DIR": "/home/vscode/.claude",
|
||||
"HISTFILE": "/home/vscode/.bash_history.d/history"
|
||||
},
|
||||
"remoteEnv": {
|
||||
"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"
|
||||
},
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/docker-outside-of-docker:1": {
|
||||
"moby": false
|
||||
}
|
||||
},
|
||||
"mounts": [
|
||||
{{ ('type=bind,source=' ~ ecaas_agent_state ~ '/git,target=/run/ecaas-git,readonly') | to_json }},
|
||||
{% for ca in ecaas_git_available_cas %}
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.local/share/certs/' ~ ca.certificate ~ ',target=/run/ecaas-git-ca/' ~ ca.certificate ~ ',readonly') | to_json }},
|
||||
{% endfor %}
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.config/ai,target=/home/vscode/.config/ai,readonly') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.local/state/devcontainer-bash-history/ecaas,target=/home/vscode/.bash_history.d') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.claude,target=/home/vscode/.claude') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.cline,target=/home/vscode/.cline') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.agents,target=/home/vscode/.agents,readonly') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.m2,target=/home/vscode/.m2') | to_json }},
|
||||
{{ ('type=bind,source=' ~ user_home ~ '/.config/glab-cli,target=/home/vscode/.config/glab-cli') | to_json }}
|
||||
],
|
||||
"forwardPorts": [8080],
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"vscjava.vscode-java-pack",
|
||||
"vmware.vscode-boot-dev-pack",
|
||||
"redhat.vscode-xml",
|
||||
"redhat.vscode-yaml",
|
||||
"saoudrizwan.claude-dev",
|
||||
"emmanuelbeziat.vscode-great-icons"
|
||||
],
|
||||
"settings": {
|
||||
"workbench.iconTheme": "vscode-great-icons",
|
||||
"java.jdt.ls.java.home": "/opt/jdk-21",
|
||||
"spring-boot.ls.java.home": "/opt/jdk-21",
|
||||
"java.configuration.runtimes": [
|
||||
{
|
||||
"name": "JavaSE-11",
|
||||
"path": "/usr/lib/jvm/msopenjdk-current",
|
||||
"default": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,19 @@
|
||||
loop_control:
|
||||
label: "{{ item.key }}"
|
||||
|
||||
- name: Reject conflicting AI desktop-app lifecycle flags
|
||||
tags: [always, ai_desktop_apps]
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- not (item.value.install_enabled | default(false)
|
||||
and item.value.uninstall_enabled | default(false) | bool)
|
||||
fail_msg: >-
|
||||
{{ item.key }} has both install_enabled and uninstall_enabled set to true.
|
||||
Choose either installation or removal before running the playbook.
|
||||
loop: "{{ ai_desktop_apps | default({}) | dict2items }}"
|
||||
loop_control:
|
||||
label: "{{ item.key }}"
|
||||
|
||||
roles:
|
||||
- role: dotfiles_common
|
||||
when:
|
||||
@@ -122,6 +135,9 @@
|
||||
|
||||
roles:
|
||||
- profile_desktop_gnome
|
||||
- role: desktop_ai_media
|
||||
when: desktop_ai_media_enabled | default(false) | bool
|
||||
tags: [ai_media]
|
||||
|
||||
- name: Configure Fedora workstation development layer
|
||||
hosts: workstation_dev_fedora
|
||||
@@ -136,3 +152,12 @@
|
||||
|
||||
roles:
|
||||
- profile_workstation_dev_wsl
|
||||
|
||||
- name: Deploy project devcontainer generator
|
||||
hosts: platform_fedora
|
||||
become: true
|
||||
tags: [devcontainer_generator]
|
||||
|
||||
roles:
|
||||
- role: devcontainer_generator
|
||||
when: "'graphical_desktop' in group_names or 'workstation_dev_fedora' in group_names"
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
{% set in_container = workstation_git_in_devcontainer | default(false) %}
|
||||
{% set git_support_dir = '/run/ecaas-git' if in_container else '~' %}
|
||||
[init]
|
||||
defaultBranch = main
|
||||
|
||||
[core]
|
||||
excludesfile = ~/.gitignore_global
|
||||
excludesfile = {{ git_support_dir }}/.gitignore_global
|
||||
pager = delta
|
||||
|
||||
[user]
|
||||
@@ -24,11 +26,21 @@
|
||||
|
||||
[merge]
|
||||
conflictstyle = diff3
|
||||
tool = bobide
|
||||
tool = {{ 'vscode' if in_container else 'bobide' }}
|
||||
|
||||
[mergetool]
|
||||
prompt = false
|
||||
|
||||
{% if in_container %}
|
||||
[mergetool "vscode"]
|
||||
cmd = code --wait --merge \"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\"
|
||||
|
||||
[diff]
|
||||
tool = vscode
|
||||
|
||||
[difftool "vscode"]
|
||||
cmd = code --wait --diff \"$LOCAL\" \"$REMOTE\"
|
||||
{% else %}
|
||||
[mergetool "bobide"]
|
||||
cmd = bobide --reuse-window --wait $MERGED
|
||||
|
||||
@@ -37,6 +49,7 @@
|
||||
|
||||
[difftool "bobide"]
|
||||
cmd = bobide --reuse-window --wait --diff $LOCAL $REMOTE
|
||||
{% endif %}
|
||||
|
||||
[color]
|
||||
ui = always
|
||||
@@ -79,7 +92,7 @@
|
||||
gcunreachablenow = gc --prune=now
|
||||
|
||||
[include]
|
||||
path = ~/.themes.gitignore
|
||||
path = {{ git_support_dir }}/.themes.gitignore
|
||||
|
||||
[delta]
|
||||
features = catppuccin-mocha navigate
|
||||
@@ -88,14 +101,16 @@
|
||||
tabs = 4
|
||||
side-by-side = true
|
||||
|
||||
[http "https://gitlab.ecaas.datacenter.comune.roma"]
|
||||
{% for ca in workstation_git_container_cas | default(workstation_git_https_cas) %}
|
||||
[http "{{ ca.url }}"]
|
||||
{% if not in_container %}
|
||||
sslBackend = openssl
|
||||
sslCAInfo = ~/.local/share/certs/ecaas.datacenter.comune.roma.crt
|
||||
|
||||
[http "https://gitlab.datacenter.comune.roma"]
|
||||
sslBackend = openssl
|
||||
sslCAInfo = ~/.local/share/certs/datacenter.comune.roma.crt
|
||||
{% endif %}
|
||||
sslCAInfo = {{ '/run/ecaas-git-ca' if in_container else '~/.local/share/certs' }}/{{ ca.certificate }}
|
||||
|
||||
{% endfor %}
|
||||
{% if not in_container %}
|
||||
[credential]
|
||||
helper = store
|
||||
{% endif %}
|
||||
|
||||
|
||||
11
cmd/devcontainer/delta.Dockerfile
Normal file
11
cmd/devcontainer/delta.Dockerfile
Normal file
@@ -0,0 +1,11 @@
|
||||
RUN apt-get update \
|
||||
&& arch="$(dpkg --print-architecture)" \
|
||||
&& case "$arch" in \
|
||||
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
|
||||
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
|
||||
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
|
||||
esac \
|
||||
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
|
||||
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
|
||||
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb
|
||||
3
cmd/devcontainer/go.mod
Normal file
3
cmd/devcontainer/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module github.com/fscotto/infra/cmd/devcontainer
|
||||
|
||||
go 1.22
|
||||
351
cmd/devcontainer/main.go
Normal file
351
cmd/devcontainer/main.go
Normal file
@@ -0,0 +1,351 @@
|
||||
// Command devcontainer generates project configurations sharing host Git and agent state.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed delta.Dockerfile
|
||||
var deltaDockerfile string
|
||||
|
||||
type profile struct {
|
||||
Image, Packages string
|
||||
Extensions []string
|
||||
}
|
||||
type agent struct {
|
||||
Package string
|
||||
Extension string
|
||||
Paths []string
|
||||
}
|
||||
type mount struct {
|
||||
Type string `json:"type"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
ReadOnly bool `json:"readOnly"`
|
||||
}
|
||||
|
||||
func exists(path string) bool { _, err := os.Stat(path); return err == nil }
|
||||
func isDir(path string) bool { info, err := os.Stat(path); return err == nil && info.IsDir() }
|
||||
func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" }
|
||||
func symlink(path string) bool {
|
||||
info, err := os.Lstat(path)
|
||||
return err == nil && info.Mode()&os.ModeSymlink != 0
|
||||
}
|
||||
|
||||
func selectAgents(selection, home string) ([]string, error) {
|
||||
result := []string{}
|
||||
candidates := strings.Split(selection, ",")
|
||||
if selection == "none" {
|
||||
return result, nil
|
||||
}
|
||||
if selection == "auto" {
|
||||
candidates = nil
|
||||
for name := range agents {
|
||||
candidates = append(candidates, name)
|
||||
}
|
||||
sort.Strings(candidates)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, name := range candidates {
|
||||
name = strings.TrimSpace(name)
|
||||
a, ok := agents[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown agent %q", name)
|
||||
}
|
||||
available := true
|
||||
for _, path := range a.Paths {
|
||||
if !isDir(filepath.Join(home, path)) {
|
||||
available = false
|
||||
}
|
||||
}
|
||||
if selection == "auto" && !available {
|
||||
continue
|
||||
}
|
||||
if !seen[name] {
|
||||
result = append(result, name)
|
||||
seen[name] = true
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func generate(project, language, home string, selected []string, local []string, force bool) (string, error) {
|
||||
p, ok := profiles[language]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unknown language %q", language)
|
||||
}
|
||||
project, err := filepath.Abs(project)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
project, err = filepath.EvalSymlinks(project)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
home, err = filepath.Abs(home)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
home, err = filepath.EvalSymlinks(home)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !isDir(project) {
|
||||
return "", fmt.Errorf("project directory does not exist: %s", project)
|
||||
}
|
||||
if home == "/" || strings.ContainsAny(home, "\n\r$,\\\"") {
|
||||
return "", errors.New("unsupported host home path")
|
||||
}
|
||||
target := filepath.Join(project, ".devcontainer")
|
||||
if symlink(target) {
|
||||
return "", errors.New("refusing a symlinked .devcontainer directory")
|
||||
}
|
||||
if exists(target) && !force {
|
||||
return "", errors.New(".devcontainer already exists; use --force to replace generated files")
|
||||
}
|
||||
paths := []struct {
|
||||
path string
|
||||
readonly bool
|
||||
}{{".gitconfig", true}, {".config/git", true}, {".gitignore_global", true}, {".config/ai", true}}
|
||||
claude := false
|
||||
for _, name := range selected {
|
||||
a, ok := agents[name]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unknown agent %q", name)
|
||||
}
|
||||
for _, path := range a.Paths {
|
||||
if !isDir(filepath.Join(home, path)) {
|
||||
return "", fmt.Errorf("missing host directory for %s: %s", name, filepath.Join(home, path))
|
||||
}
|
||||
paths = append(paths, struct {
|
||||
path string
|
||||
readonly bool
|
||||
}{path, false})
|
||||
}
|
||||
if name == "claude" {
|
||||
claude = true
|
||||
}
|
||||
}
|
||||
if claude {
|
||||
paths = append(paths, struct {
|
||||
path string
|
||||
readonly bool
|
||||
}{".claude.json", false})
|
||||
}
|
||||
mounts := []mount{}
|
||||
for _, item := range paths {
|
||||
if exists(filepath.Join(home, item.path)) {
|
||||
destination := filepath.Join(home, item.path)
|
||||
if item.path == ".gitconfig" {
|
||||
destination = "/run/host-gitconfig"
|
||||
}
|
||||
mounts = append(mounts, mount{"bind", "${localEnv:HOME}/" + item.path, destination, item.readonly})
|
||||
}
|
||||
}
|
||||
// The devcontainers node feature ships an nvm-based Node outside sudo's
|
||||
// secure_path, which broke the postCreateCommand npm install. Copy the
|
||||
// official Node image binaries into /usr/local instead, exactly like the
|
||||
// ecaas and cdp devcontainers, so sudo npm works in every profile.
|
||||
needsNode := len(selected) > 0
|
||||
dockerfile := ""
|
||||
if needsNode {
|
||||
dockerfile += "FROM docker.io/library/node:22-bookworm-slim AS node\n"
|
||||
}
|
||||
dockerfile += fmt.Sprintf("FROM %s\nUSER root\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide %s \\\n && rm -rf /var/lib/apt/lists/*\n", p.Image, p.Packages)
|
||||
if needsNode {
|
||||
dockerfile += "COPY --from=node /usr/local/bin/node /usr/local/bin/node\n"
|
||||
dockerfile += "COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/\n"
|
||||
dockerfile += "RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \\\n && ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \\\n && node --version && npm --version\n"
|
||||
}
|
||||
dockerfile += deltaDockerfile
|
||||
if home != "/home/vscode" {
|
||||
dockerfile += "RUN usermod --home " + quote(home) + " --move-home vscode\n"
|
||||
}
|
||||
// Docker ENV uses its own quoting syntax, rather than shell quoting.
|
||||
envHome, _ := json.Marshal(home)
|
||||
dockerfile += "ENV HOME=" + string(envHome) + "\n"
|
||||
if language == "python" {
|
||||
dockerfile += "RUN python -m pip install --no-cache-dir uv ruff ty\n"
|
||||
}
|
||||
if language == "infra" {
|
||||
dockerfile += "RUN python -m pip install --no-cache-dir ansible-core ansible-lint yamllint\n"
|
||||
}
|
||||
// The container installs the profile extensions, the VS Code extension of
|
||||
// every selected agent and the extensions currently installed in the local
|
||||
// VS Code, captured at generation time. Regenerate to refresh the local set.
|
||||
extensions := append([]string{}, p.Extensions...)
|
||||
addExtension := func(id string) {
|
||||
if !slices.ContainsFunc(extensions, func(e string) bool { return strings.EqualFold(e, id) }) {
|
||||
extensions = append(extensions, id)
|
||||
}
|
||||
}
|
||||
for _, name := range selected {
|
||||
if id := agents[name].Extension; id != "" {
|
||||
addExtension(id)
|
||||
}
|
||||
}
|
||||
for _, id := range local {
|
||||
addExtension(strings.TrimSpace(id))
|
||||
}
|
||||
slices.Sort(extensions)
|
||||
config := map[string]any{
|
||||
"name": filepath.Base(project) + " — " + language,
|
||||
"build": map[string]string{"dockerfile": "Dockerfile"},
|
||||
"remoteUser": "vscode", "updateRemoteUserUID": true,
|
||||
"containerEnv": map[string]string{"HOME": home}, "mounts": mounts,
|
||||
"customizations": map[string]any{"vscode": map[string]any{"extensions": extensions}},
|
||||
}
|
||||
if len(selected) > 0 {
|
||||
packages := []string{}
|
||||
for _, name := range selected {
|
||||
packages = append(packages, quote(agents[name].Package))
|
||||
}
|
||||
config["postCreateCommand"] = "sudo npm install --global --no-audit --no-fund " + strings.Join(packages, " ")
|
||||
}
|
||||
if claude {
|
||||
config["remoteEnv"] = map[string]string{"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"}
|
||||
}
|
||||
dockerfile += "USER vscode\n"
|
||||
if exists(filepath.Join(home, ".gitconfig")) {
|
||||
dockerfile += "RUN git config --global include.path /run/host-gitconfig\n"
|
||||
}
|
||||
var data bytes.Buffer
|
||||
encoder := json.NewEncoder(&data)
|
||||
encoder.SetEscapeHTML(false)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(config); err != nil {
|
||||
return "", err
|
||||
}
|
||||
files := []struct{ name, content string }{{"Dockerfile", dockerfile}, {"devcontainer.json", data.String()}}
|
||||
// Validate every output before replacing any file.
|
||||
for _, file := range files {
|
||||
path := filepath.Join(target, file.name)
|
||||
if info, err := os.Lstat(path); err == nil {
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("refusing non-regular output: %s", path)
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(target, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, file := range files {
|
||||
if err := writeAtomic(filepath.Join(target, file.name), file.content); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func writeAtomic(path, content string) error {
|
||||
file, err := os.CreateTemp(filepath.Dir(path), ".devcontainer-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
if _, err = io.WriteString(file, content); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
if err = file.Chmod(0644); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
if err = file.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(file.Name(), path)
|
||||
}
|
||||
|
||||
// discoverLocalExtensions lists the extensions installed in the local VS Code.
|
||||
// A missing or failing code binary is not fatal: the generated container then
|
||||
// only carries the profile and agent extensions.
|
||||
func discoverLocalExtensions(stderr io.Writer) []string {
|
||||
path, err := exec.LookPath("code")
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "note: no local VS Code found; skipping locally installed extensions")
|
||||
return nil
|
||||
}
|
||||
out, err := exec.Command(path, "--list-extensions").Output()
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "warning: could not list local VS Code extensions: %v\n", err)
|
||||
return nil
|
||||
}
|
||||
extensions := []string{}
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
if id := strings.TrimSpace(line); id != "" {
|
||||
extensions = append(extensions, id)
|
||||
}
|
||||
}
|
||||
return extensions
|
||||
}
|
||||
|
||||
func run(args []string, home string, out, stderr io.Writer) error {
|
||||
flags := flag.NewFlagSet("devcontainer", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
language := flags.String("language", "", "c-cpp, go, rust, python, node, java, infra (required)")
|
||||
selection := flags.String("agents", "auto", "auto, none, or comma-separated codex,cline,opencode,claude,gemini")
|
||||
force := flags.Bool("force", false, "Replace the two generated files")
|
||||
flags.Usage = func() {
|
||||
fmt.Fprintln(stderr, "Usage: devcontainer PROJECT --language LANGUAGE [--agents AGENTS] [--force]")
|
||||
flags.PrintDefaults()
|
||||
}
|
||||
// Accept the project's original position before the flags as well as flags first.
|
||||
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
|
||||
args = append(append([]string{}, args[1:]...), args[0])
|
||||
}
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if flags.NArg() != 1 || *language == "" {
|
||||
flags.Usage()
|
||||
return errors.New("one project and --language are required")
|
||||
}
|
||||
selected, err := selectAgents(*selection, home)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
local := discoverLocalExtensions(stderr)
|
||||
target, err := generate(flags.Arg(0), *language, home, selected, local, *force)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
names := strings.Join(selected, ", ")
|
||||
if names == "" {
|
||||
names = "none"
|
||||
}
|
||||
fmt.Fprintf(out, "Created %s; agents: %s\n", target, names)
|
||||
if len(local) > 0 {
|
||||
fmt.Fprintf(out, "Included %d local VS Code extensions.\n", len(local))
|
||||
}
|
||||
fmt.Fprintln(out, "Open the project in VS Code and choose Dev Containers: Reopen in Container.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
home, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
err = run(os.Args[1:], home, os.Stdout, os.Stderr)
|
||||
}
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
281
cmd/devcontainer/main_test.go
Normal file
281
cmd/devcontainer/main_test.go
Normal file
@@ -0,0 +1,281 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func setup(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
home, project := filepath.Join(root, "host home"), filepath.Join(root, "project with spaces")
|
||||
for _, path := range []string{home, project} {
|
||||
if err := os.MkdirAll(path, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return home, project
|
||||
}
|
||||
func read(t *testing.T, path string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
func put(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type vscodeCustomizations struct {
|
||||
Customizations struct {
|
||||
Vscode struct {
|
||||
Extensions []string `json:"extensions"`
|
||||
} `json:"vscode"`
|
||||
} `json:"customizations"`
|
||||
}
|
||||
|
||||
func extensionsOf(t *testing.T, target string) []string {
|
||||
t.Helper()
|
||||
var config vscodeCustomizations
|
||||
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return config.Customizations.Vscode.Extensions
|
||||
}
|
||||
|
||||
func TestProfiles(t *testing.T) {
|
||||
for name := range profiles {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
target, err := generate(project, name, home, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if config["containerEnv"].(map[string]any)["HOME"] != home {
|
||||
t.Fatal("wrong home")
|
||||
}
|
||||
if _, ok := config["postCreateCommand"]; ok {
|
||||
t.Fatal("unexpected agent install")
|
||||
}
|
||||
want := append([]string{}, profiles[name].Extensions...)
|
||||
slices.Sort(want)
|
||||
if got := extensionsOf(t, target); !slices.Equal(got, want) {
|
||||
t.Fatalf("wrong extensions: %v", got)
|
||||
}
|
||||
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
|
||||
if !strings.HasPrefix(dockerfile, "FROM "+profiles[name].Image+"\n") || !strings.HasSuffix(dockerfile, "USER vscode\n") {
|
||||
t.Fatal("wrong Dockerfile")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestSharedConfig(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
put(t, filepath.Join(home, ".codex/auth.json"), "secret-value")
|
||||
put(t, filepath.Join(home, ".gitconfig"), "[user]\nname = Test\n")
|
||||
target, err := generate(project, "python", home, []string{"codex"}, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
configText := read(t, filepath.Join(target, "devcontainer.json"))
|
||||
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
|
||||
if strings.Contains(configText+dockerfile, "secret-value") {
|
||||
t.Fatal("credential leaked")
|
||||
}
|
||||
var config struct {
|
||||
Mounts []mount
|
||||
PostCreateCommand string
|
||||
}
|
||||
if err := json.Unmarshal([]byte(configText), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foundGit, foundAgent := false, false
|
||||
for _, m := range config.Mounts {
|
||||
if m.Target == "/run/host-gitconfig" {
|
||||
foundGit = m.ReadOnly
|
||||
}
|
||||
if m.Target == filepath.Join(home, ".codex") {
|
||||
foundAgent = !m.ReadOnly
|
||||
}
|
||||
}
|
||||
if !foundGit || !foundAgent || !strings.Contains(dockerfile, "include.path /run/host-gitconfig") {
|
||||
t.Fatal("incorrect sharing")
|
||||
}
|
||||
if !strings.Contains(config.PostCreateCommand, "@openai/codex") || !strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node") {
|
||||
t.Fatal("missing CLI install or embedded Node")
|
||||
}
|
||||
if !slices.Contains(extensionsOf(t, target), "openai.chatgpt") {
|
||||
t.Fatal("agent VS Code extension missing")
|
||||
}
|
||||
}
|
||||
func TestAgentAndLocalExtensions(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
put(t, filepath.Join(home, ".cline/state/config"), "")
|
||||
put(t, filepath.Join(home, ".agents/AGENTS.md"), "")
|
||||
local := []string{"github.remotehub", "SAOUDRIZWAN.claude-dev", "ms-vscode.cpptools"}
|
||||
target, err := generate(project, "python", home, []string{"cline"}, local, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"ms-python.python", "charliermarsh.ruff", "saoudrizwan.claude-dev", "github.remotehub", "ms-vscode.cpptools"}
|
||||
slices.Sort(want)
|
||||
if got := extensionsOf(t, target); !slices.Equal(got, want) {
|
||||
t.Fatalf("extensions mismatch: %v", got)
|
||||
}
|
||||
}
|
||||
func TestAgentsShipNpmInsideSudoPath(t *testing.T) {
|
||||
for name := range profiles {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
put(t, filepath.Join(home, ".cline/state/config"), "")
|
||||
put(t, filepath.Join(home, ".agents/AGENTS.md"), "")
|
||||
target, err := generate(project, name, home, []string{"cline"}, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, hasFeature := config["features"]; hasFeature {
|
||||
t.Fatal("the nvm-based node feature breaks the sudo npm postCreateCommand")
|
||||
}
|
||||
post, _ := config["postCreateCommand"].(string)
|
||||
if !strings.Contains(post, "sudo npm install") {
|
||||
t.Fatalf("missing npm agent install: %q", post)
|
||||
}
|
||||
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
|
||||
if !strings.HasPrefix(dockerfile, "FROM docker.io/library/node:22-bookworm-slim AS node\n") ||
|
||||
!strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node /usr/local/bin/node") ||
|
||||
!strings.Contains(dockerfile, "ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm") {
|
||||
t.Fatal("npm must be reachable inside sudo's secure_path")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestOverwriteAndSymlinks(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
target, err := generate(project, "go", home, nil, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := read(t, filepath.Join(target, "Dockerfile"))
|
||||
if _, err := generate(project, "rust", home, nil, nil, false); err == nil {
|
||||
t.Fatal("overwrote existing configuration")
|
||||
}
|
||||
path := filepath.Join(target, "devcontainer.json")
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
victim := filepath.Join(home, "victim")
|
||||
put(t, victim, "keep")
|
||||
if err := os.Symlink(victim, path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := generate(project, "rust", home, nil, nil, true); err == nil {
|
||||
t.Fatal("accepted symlink")
|
||||
}
|
||||
if read(t, victim) != "keep" || read(t, filepath.Join(target, "Dockerfile")) != before {
|
||||
t.Fatal("changed files before rejecting symlink")
|
||||
}
|
||||
}
|
||||
func TestInvalidInputs(t *testing.T) {
|
||||
for _, kind := range []string{"agent", "language", "missing-directory", "home", "target-symlink"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
language := "go"
|
||||
var selected []string
|
||||
switch kind {
|
||||
case "agent":
|
||||
selected = []string{"codex"}
|
||||
case "language":
|
||||
language = "unknown"
|
||||
case "missing-directory":
|
||||
project = filepath.Join(project, "missing")
|
||||
case "home":
|
||||
home = "/"
|
||||
case "target-symlink":
|
||||
if err := os.Symlink(home, filepath.Join(project, ".devcontainer")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := generate(project, language, home, selected, nil, true); err == nil {
|
||||
t.Fatal("invalid input accepted")
|
||||
}
|
||||
if exists(filepath.Join(project, ".devcontainer/Dockerfile")) {
|
||||
t.Fatal("wrote invalid configuration")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestAgentSelection(t *testing.T) {
|
||||
home, _ := setup(t)
|
||||
put(t, filepath.Join(home, ".codex/config.toml"), "")
|
||||
got, err := selectAgents("auto", home)
|
||||
if err != nil || strings.Join(got, ",") != "codex" {
|
||||
t.Fatalf("auto: %v %v", got, err)
|
||||
}
|
||||
got, err = selectAgents("codex,codex", home)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatal("duplicate agents")
|
||||
}
|
||||
if _, err := selectAgents("invalid", home); err == nil {
|
||||
t.Fatal("unknown agent accepted")
|
||||
}
|
||||
}
|
||||
func TestCLI(t *testing.T) {
|
||||
for _, first := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "project-first", false: "flags-first"}[first], func(t *testing.T) {
|
||||
home, project := setup(t)
|
||||
args := []string{"--language", "go", "--agents", "none", project}
|
||||
if first {
|
||||
args = []string{project, "--language", "go", "--agents", "none"}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := run(args, home, &out, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "agents: none") {
|
||||
t.Fatal("missing output")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestLocalExtensionDiscovery(t *testing.T) {
|
||||
bin := t.TempDir()
|
||||
script := filepath.Join(bin, "code")
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\necho a.b\necho c.d\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
home, project := setup(t)
|
||||
var out bytes.Buffer
|
||||
if err := run([]string{project, "--language", "go", "--agents", "none"}, home, &out, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"a.b", "c.d", "golang.go"}
|
||||
slices.Sort(want)
|
||||
if got := extensionsOf(t, filepath.Join(project, ".devcontainer")); !slices.Equal(got, want) {
|
||||
t.Fatalf("extensions mismatch: %v", got)
|
||||
}
|
||||
if !strings.Contains(out.String(), "Included 2 local VS Code extensions.") {
|
||||
t.Fatal("missing local extensions summary")
|
||||
}
|
||||
}
|
||||
18
cmd/devcontainer/profiles.go
Normal file
18
cmd/devcontainer/profiles.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
var profiles = map[string]profile{
|
||||
"c-cpp": {Image: "mcr.microsoft.com/devcontainers/base:bookworm", Packages: "build-essential clang clangd cmake gdb valgrind universal-ctags cscope", Extensions: []string{"ms-vscode.cpptools", "ms-vscode.cmake-tools"}},
|
||||
"go": {Image: "mcr.microsoft.com/devcontainers/go:1.25-bookworm", Packages: "", Extensions: []string{"golang.go"}},
|
||||
"rust": {Image: "mcr.microsoft.com/devcontainers/rust:1-bookworm", Packages: "", Extensions: []string{"rust-lang.rust-analyzer"}},
|
||||
"python": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "", Extensions: []string{"ms-python.python", "charliermarsh.ruff"}},
|
||||
"node": {Image: "mcr.microsoft.com/devcontainers/javascript-node:22-bookworm", Packages: "", Extensions: []string{"esbenp.prettier-vscode"}},
|
||||
"java": {Image: "mcr.microsoft.com/devcontainers/java:21-bookworm", Packages: "maven", Extensions: []string{"vscjava.vscode-java-pack"}},
|
||||
"infra": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "shellcheck shfmt", Extensions: []string{"redhat.ansible", "redhat.vscode-yaml"}},
|
||||
}
|
||||
var agents = map[string]agent{
|
||||
"codex": {Package: "@openai/codex", Extension: "openai.chatgpt", Paths: []string{".codex"}},
|
||||
"cline": {Package: "cline", Extension: "saoudrizwan.claude-dev", Paths: []string{".cline", ".agents"}},
|
||||
"opencode": {Package: "opencode-ai", Extension: "sst-dev.opencode", Paths: []string{".config/opencode", ".local/share/opencode", ".local/state/opencode"}},
|
||||
"claude": {Package: "@anthropic-ai/claude-code@2.1.312", Extension: "anthropic.claude-code", Paths: []string{".claude"}},
|
||||
"gemini": {Package: "@google/gemini-cli", Extension: "Google.geminicodeassist", Paths: []string{".gemini"}},
|
||||
}
|
||||
159
docs/ai-media-presets.md
Normal file
159
docs/ai-media-presets.md
Normal file
@@ -0,0 +1,159 @@
|
||||
# Preset offline `ai-media`
|
||||
|
||||
## Volume cifrato Backup (Ikaros)
|
||||
|
||||
```bash
|
||||
ai-media mount # sblocca Backup e rende disponibili i file di ai-media
|
||||
ai-media umount # smonta prima il bind, poi Backup, e richiude LUKS
|
||||
```
|
||||
|
||||
Eseguire i comandi come utente desktop, da un terminale: UDisks chiede la
|
||||
passphrase LUKS se il volume è chiuso e systemd può chiedere l'autenticazione
|
||||
amministrativa. La passphrase non viene salvata dal launcher. Prima di
|
||||
`umount`, chiudere FaceFusion/RVC, attendere i job dei preset e chiudere file
|
||||
e terminali aperti sul disco. Il comando riguarda **tutto il volume Backup**,
|
||||
non solo la directory di ai-media, e non forza lo smontaggio. Non scollegare
|
||||
il disco se il comando segnala un errore.
|
||||
|
||||
## Preset disponibili
|
||||
|
||||
Tutti i preset video accettano un nome MP4 locale oppure un URL HTTP(S).
|
||||
I file locali vanno in `~/.local/share/ai-media/input/`. I preset avviano un servizio
|
||||
`systemd --user` e tornano subito; FaceFusion e RVC restano nei container
|
||||
offline. Il terminale stampa il nome del job e il comando per seguirne i log.
|
||||
|
||||
```bash
|
||||
# 1. Estrae l'audio, separa voce/strumentale, converte tutta la traccia
|
||||
# vocale con mia_voce e restituisce solo l'audio finale mixato.
|
||||
ai-media preset audio-convert video1.mp4
|
||||
|
||||
# 2. Applica source11.jpg ... source18.jpg al video: conserva l'audio
|
||||
# originale se presente, altrimenti produce un video senza audio.
|
||||
ai-media preset video-convert video1.mp4
|
||||
|
||||
# 3. Unisce un video in input/ con un audio presente in input/ oppure output/.
|
||||
ai-media preset merge video1.mp4 audio.wav
|
||||
|
||||
# 4. Esegue voce e volti, poi unisce il video modificato con l'audio convertito.
|
||||
# Se l'input è un URL, scarica prima un singolo video con yt-dlp.
|
||||
ai-media preset convert 'https://esempio.org/video'
|
||||
|
||||
# 5. Separa il video (senza ricodificarlo) dalla prima traccia audio.
|
||||
ai-media preset split video1.mp4
|
||||
|
||||
# 6. Come split, poi separa l'audio in voce e strumentale, senza convertirne la voce.
|
||||
ai-media preset split-stems video1.mp4
|
||||
|
||||
# 7. Sovrappone voce e strumentale in un unico audio (non concatena le tracce).
|
||||
ai-media preset mix vocals.wav instrumental.wav
|
||||
|
||||
# 8. Applica mia_voce direttamente a un audio, senza separazione né remix.
|
||||
ai-media preset voice-convert voce.wav
|
||||
```
|
||||
|
||||
## Applicare mia_voce a un audio
|
||||
|
||||
```bash
|
||||
ai-media preset voice-convert voce.wav
|
||||
ai-media preset voice-convert video1-split-stems/vocals.wav --output video1-mia_voce.wav
|
||||
```
|
||||
|
||||
`voice-convert` legge un audio locale in `input/` oppure `output/`, anche in
|
||||
una sottocartella, e produce `output/<nome-audio>-mia_voce.wav`. `--output`
|
||||
permette di scegliere un altro nome WAV. Converte prima la traccia in WAV e
|
||||
applica direttamente il modello RVC `mia_voce` con il relativo indice e RMVPE,
|
||||
senza BS Roformer e senza aggiungere lo strumentale. Usare preferibilmente
|
||||
una voce isolata: il preset non rimuove musica né separa parlanti.
|
||||
Accetta i formati audio decodificabili dal FFmpeg installato. Richiede il
|
||||
modello e l'indice personali già presenti nello stato RVC, funziona offline
|
||||
in background, conserva l'originale e rifiuta risultati già esistenti.
|
||||
Gli intermedi restano nella sottocartella nascosta del job in `output/`.
|
||||
|
||||
Per rimettere lo strumentale dopo la conversione:
|
||||
|
||||
```bash
|
||||
ai-media preset mix video1-mia_voce.wav video1-split-stems/instrumental.wav --output video1-mix.wav
|
||||
```
|
||||
|
||||
## Unire voce e strumentale
|
||||
|
||||
`mix` usa due audio locali in `input/` o `output/`, anche nelle sottocartelle
|
||||
create da `split-stems`:
|
||||
|
||||
```bash
|
||||
ai-media preset mix video1-split-stems/vocals.wav video1-split-stems/instrumental.wav --output video1-mix.wav
|
||||
```
|
||||
|
||||
Il risultato è `output/video1-mix.wav`, PCM WAV a 16 bit. Senza `--output`,
|
||||
il nome è `<nome-vocale>-mix.wav` (per esempio `vocals-mix.wav`). Le tracce
|
||||
partono insieme da zero e vengono sommate a volume originale, senza
|
||||
normalizzazione; la durata è quella della traccia più lunga. Livelli troppo
|
||||
alti possono causare clipping. Il preset non esegue separazione o conversione
|
||||
vocale, non modifica gli originali e non sovrascrive file esistenti. Parte in
|
||||
background come gli altri preset e usa solo FFmpeg nel container offline.
|
||||
Gli audio devono essere univoci tra `input/` e `output/`; percorsi assoluti,
|
||||
`..`, link simbolici e URL audio non sono accettati.
|
||||
|
||||
## Video da URL
|
||||
|
||||
Per ogni preset video si può sostituire il nome del video con un URL tra virgolette:
|
||||
|
||||
```bash
|
||||
ai-media preset split 'https://esempio.org/video'
|
||||
ai-media preset split-stems 'https://esempio.org/video'
|
||||
ai-media preset audio-convert 'https://esempio.org/video'
|
||||
ai-media preset video-convert 'https://esempio.org/video'
|
||||
ai-media preset merge 'https://esempio.org/video' audio.wav
|
||||
ai-media preset convert 'https://esempio.org/video'
|
||||
# Anche convert accetta un file locale, senza download:
|
||||
ai-media preset convert video1.mp4
|
||||
```
|
||||
|
||||
Il download con `yt-dlp` avviene una sola volta nello stesso job in background,
|
||||
prima dell'elaborazione. Il video scaricato resta in `input/download-<ID>.mp4`;
|
||||
i risultati usano lo stesso prefisso `download-<ID>` al posto di `video1`.
|
||||
Serve `yt-dlp` sull'host solo per gli URL. L'audio di `merge` rimane un file
|
||||
locale in `input/` oppure `output/`. URL locali/privati o contenenti credenziali
|
||||
non vengono accettati. Se il download fallisce, l'elaborazione non parte.
|
||||
|
||||
`split` produce `output/video1-split/video.mp4` (muto) e `audio.wav`.
|
||||
`split-stems` produce `output/video1-split-stems/` con `video.mp4`, `audio.wav`,
|
||||
`vocals.wav` e `instrumental.wav`. L'audio estratto è PCM WAV a 16 bit;
|
||||
la separazione usa BS Roformer offline nel container RVC e non richiede
|
||||
il modello personale `mia_voce`. Entrambi richiedono un video con audio,
|
||||
non modificano l'originale e rifiutano una cartella risultato già esistente.
|
||||
Mantengono gli intermedi nella sottocartella nascosta del job in `output/`;
|
||||
i risultati pubblicati sono hard link e non duplicano lo spazio dei file.
|
||||
|
||||
`video-convert` e il passaggio video di `convert` usano lo stesso profilo
|
||||
FaceFusion: HyperSwap 1a 256 (pixel boost 256x256, peso 0.5), rilevatore
|
||||
`yolo_face` 640x640 agli angoli 0/90/180/270, selezione `one` per volto
|
||||
grande, filtri `female` e `white`, maschere `occlusion region area box` con
|
||||
`xseg_1` e `bisenet_resnet_34` (blur 0.3), H.264 `libx264` veryfast, qualità
|
||||
80 e 30 fps. L'audio originale viene ripristinato separatamente quando esiste.
|
||||
|
||||
Risultati: `output/video1-mia_voce.wav`, `output/video1-facefusion.mp4` e
|
||||
`output/video1-unito.mp4`. Il preset `convert` crea
|
||||
`output/video1-completo.mp4` (o `output/download-<ID>-completo.mp4` da URL),
|
||||
mantenendo anche l'audio e il video intermedi. Richiede `source11.jpg`–`source18.jpg`
|
||||
in `input/` e un video che contenga audio. **Solo il download** tramite
|
||||
`yt-dlp` usa la rete; non usa la configurazione o i cookie personali di
|
||||
`yt-dlp` e non scarica playlist. I file esistenti non vengono sovrascritti. Il
|
||||
primo e il secondo preset conservano i passaggi intermedi in una sottocartella
|
||||
`.video1-...` di `output/`, utile per diagnosi e recupero; non viene rimossa
|
||||
automaticamente.
|
||||
|
||||
Per controllare un job, usare il nome stampato dal comando:
|
||||
|
||||
```bash
|
||||
journalctl --user -fu ai-media-preset-YYYYMMDD-HHMMSS-ID
|
||||
systemctl --user status ai-media-preset-YYYYMMDD-HHMMSS-ID
|
||||
```
|
||||
|
||||
Il preset `audio-convert` converte l'intero stem vocale: non distingue automaticamente
|
||||
voci maschili e femminili e non separa parlanti sovrapposti. L'elaborazione è
|
||||
in background, **non** più rapida della capacità della CPU. I nomi dei video locali
|
||||
devono essere semplici, senza percorsi; gli audio possono indicare sottocartelle
|
||||
relative a `input/` o `output/`. Se lo stesso audio
|
||||
è in `input/` e `output/`, il comando rifiuta l'ambiguità. Tutti i video di
|
||||
input dei preset devono essere MP4 con un nome diverso dal risultato atteso.
|
||||
160
docs/atlas-aria2.md
Normal file
160
docs/atlas-aria2.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# Atlas HTTP downloader: aria2 + AriaNg
|
||||
|
||||
Ansible manages two admin-owned rootless Quadlets, `atlas-aria2.service` and
|
||||
`atlas-ariang.service`, with pinned images. The third-party aria2 image is used
|
||||
only for its binary: its init scripts, tracker updates and automatic deletion
|
||||
hooks are bypassed. The static frontend has no host-data or credential mounts.
|
||||
|
||||
- Web UI (LAN only): `http://192.168.178.55:8091`.
|
||||
- RPC (LAN only, mandatory secret): `http://192.168.178.55:6800/jsonrpc`.
|
||||
- Payloads: `/zpool/archive/Downloads`, shared with qBittorrent and SMB Archive.
|
||||
- Private state: `zpool/services/data/aria2`, mounted at `/zpool/services/data/aria2`.
|
||||
- The persistent 256-bit RPC secret is generated only on Atlas; it is not committed
|
||||
or printed by Ansible. It is not a username/password: AriaNg passes it as an
|
||||
RPC token. Whoever has it can control the downloader.
|
||||
- No DNS/NPM/public exposure or WireGuard changes are performed. Never publish
|
||||
the bare RPC port on the Internet. LAN HTTP does not encrypt the token; use
|
||||
only a trusted LAN or an SSH tunnel.
|
||||
|
||||
## Deploy
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
ansible-playbook ansible/site.yml --limit atlas --tags aria2 --check
|
||||
ansible-playbook ansible/site.yml --limit atlas --tags aria2
|
||||
```
|
||||
|
||||
Check mode validates storage and Quadlet/firewall changes but skips generation,
|
||||
reading and rendering of secret-dependent configuration and runtime probes.
|
||||
Boot startup uses admin lingering plus `WantedBy=default.target`; a host reboot
|
||||
must be tested separately.
|
||||
|
||||
## First use
|
||||
|
||||
Open the LAN Web UI. In **AriaNg Settings -> RPC**, use:
|
||||
|
||||
- Protocol: HTTP (JSON-RPC)
|
||||
- Host/address: `192.168.178.55`
|
||||
- Port: `6800`
|
||||
- Interface/path: `jsonrpc`
|
||||
- Secret: privately read it in your terminal with:
|
||||
|
||||
```sh
|
||||
ssh admin@192.168.178.55 'cat /zpool/services/data/aria2/rpc-secret'
|
||||
```
|
||||
|
||||
Do not paste it into chat or share exported AriaNg settings, which may include
|
||||
it. After saving settings the status should be Connected. Select **New**, add
|
||||
one or more actual file URLs and start the download. One download/connection at
|
||||
a time is the default, to reduce load and avoid excessive requests to Apple.
|
||||
|
||||
The UI may store the secret in browser-local settings. There is no additional
|
||||
login for the static page; the RPC token protects the actual service. Do not
|
||||
publish this interface on the qBittorrent endpoint (`torrent.fscotto.co`).
|
||||
|
||||
## Public access: downloads.fscotto.co
|
||||
|
||||
NPM on Prometheus manages the public endpoint separately from the Atlas
|
||||
playbook. Atlas' existing LAN rules already admit the Aegis gateway; do not
|
||||
publish port 6800 on the router or Prometheus firewall.
|
||||
|
||||
Create an NPM Access List before enabling the Proxy Host:
|
||||
|
||||
- Add a unique username and strong password in the Authorization tab.
|
||||
- Leave Satisfy Any and Pass Auth to Host disabled. Do not add an IP-based
|
||||
authentication bypass.
|
||||
- Keep these credentials private; they are separate from the aria2 RPC secret.
|
||||
|
||||
Create the Proxy Host with that Access List selected:
|
||||
|
||||
- Domain: `downloads.fscotto.co`; DNS A record points to `179.237.102.172`.
|
||||
- Scheme: HTTP; Forward Host: `192.168.178.55`; Forward Port: `8091`.
|
||||
- Custom Location `/jsonrpc`: HTTP, `192.168.178.55`, port `8092` (private gateway).
|
||||
Leave its forwarding path unchanged so `/jsonrpc` reaches aria2.
|
||||
- Request a Let's Encrypt certificate and enable Force SSL.
|
||||
- Use HTTPS JSON-RPC (POST) in AriaNg: host `downloads.fscotto.co`, port `443`,
|
||||
path `jsonrpc`, with the RPC secret field empty. Never embed either secret in
|
||||
URLs or static frontend files.
|
||||
|
||||
Use NPM's Custom Locations UI rather than a hand-written unprotected location:
|
||||
the deployed NPM templates include Access List authentication in both the
|
||||
default location and custom locations. Verify this in the rendered host config.
|
||||
Both `/` and `/jsonrpc` must return 401 without proxy credentials; direct aria2
|
||||
RPC on port 6800 still requires its separate token. Validate before considering public
|
||||
access complete.
|
||||
|
||||
On 2026-10-10 NPM-to-AriaNg connectivity returned HTTP 200. After operator
|
||||
creation of the Access List and saving the Proxy Host, public DNS resolved to
|
||||
Prometheus and valid HTTPS returned 401 with a Basic authentication challenge
|
||||
for both `/` and `/jsonrpc`. The rendered NPM configuration confirmed both
|
||||
locations use the same Access List, with Satisfy All and no upstream forwarding
|
||||
of Basic credentials. Authenticated browser/RPC operation remains to be
|
||||
confirmed by the operator; no passwords were read or reset.
|
||||
|
||||
### Server-side token gateway
|
||||
|
||||
`atlas_aria2_gateway_enabled` enables the Ansible-managed admin user service
|
||||
`atlas-aria2-gateway.service` (tag `aria2_gateway`). Python's installed standard
|
||||
library implements HTTP JSON-RPC POST, batch and `system.multicall`; WebSocket,
|
||||
JSONP and XML-RPC are not supported. It reads the existing private `rpc-secret`
|
||||
only on Atlas and inserts it into RPC parameters. It filters credential-bearing
|
||||
response fields and rejects RPC security-option edits. Requests have size,
|
||||
timeout and concurrency limits; bodies and URLs are not logged.
|
||||
|
||||
The adapter binds Atlas' LAN IP on port 8092 and admits only Aegis through
|
||||
firewalld. Application checks admit Aegis and Atlas itself (local validation),
|
||||
require the declared public Host and reject foreign browser Origins. Its
|
||||
security boundary relies on Aegis and the authenticated NPM Custom Location:
|
||||
never open this adapter to the whole LAN or create an unauthenticated proxy
|
||||
route to it. It does not independently authenticate NPM users.
|
||||
|
||||
On each browser, use HTTPS `downloads.fscotto.co:443/jsonrpc`, POST and an empty
|
||||
RPC secret. The normal NPM username/password login remains required. Direct LAN
|
||||
clients using port 6800 still need the token. No token is embedded in static
|
||||
AriaNg assets, URLs or NPM configuration.
|
||||
|
||||
Validation: `python3 -B tests/test_aria2_rpc_gateway.py`; then
|
||||
`ansible-playbook ansible/site.yml --limit atlas --tags aria2_gateway`.
|
||||
|
||||
Gateway deployment on 2026-10-10 passed syntax/check validation and a second
|
||||
steady-state run reported `changed=0`, `failed=0`. Six offline regression tests
|
||||
passed. From the NPM container, token-free multicall returned version and global
|
||||
stats; an Atlas-local batch verified credential response filtering. Foreign
|
||||
Origins returned 403, direct Ikaros-to-gateway access was blocked, and both
|
||||
public UI and RPC remained 401 without Basic credentials. NPM host 16 now
|
||||
forwards `/jsonrpc` to 8092 with the same Access List. `nginx -t` passed;
|
||||
aria2, AriaNg, gateway and qBittorrent remained active. Public authenticated
|
||||
browser operation and an actual host reboot remain operator verification.
|
||||
|
||||
## Interrupted downloads and iCloud
|
||||
|
||||
The queue is saved every 30 seconds and on graceful shutdown. Keep both partial
|
||||
payloads and `.aria2` control files for resume. Restarting restores pending tasks.
|
||||
Resume requires server support and a valid link. Expired Apple links must be
|
||||
refreshed; some downloads also require authenticated cookies or headers. Never
|
||||
share full signed URLs or cookie files. Apple exports have not been tested until
|
||||
new links are available. TLS certificate verification remains enabled.
|
||||
|
||||
No completion/error deletion hooks are enabled. Cancelling a task does not
|
||||
implicitly clean payloads. Downloads remain inside the existing Archive backup
|
||||
scope, including incomplete files. Session files contain URLs and are kept
|
||||
private; their dataset inherits existing recursive backup/snapshot coverage.
|
||||
|
||||
References:
|
||||
- <https://github.com/aria2/aria2>
|
||||
- <https://github.com/mayswind/AriaNg>
|
||||
- <https://github.com/P3TERX/Aria2-Pro-Docker>
|
||||
|
||||
## Verified on 2026-10-10
|
||||
|
||||
The pinned aria2 binary reports 1.36.0. The Web UI and authenticated RPC are
|
||||
operational; RPC requests without a token are rejected. A second targeted
|
||||
Ansible application reported `changed=0`, `failed=0`.
|
||||
|
||||
A real HTTPS smoke test downloaded the official curl 8.10.1 source archive
|
||||
(2,726,748 bytes). After pausing at 1,048,576 bytes and restarting only
|
||||
`atlas-aria2.service`, the saved task and partial progress were restored. The
|
||||
completed file matched an independently downloaded reference by SHA-256.
|
||||
Only the exact smoke-test task and its temporary payload/control files were
|
||||
removed. A host reboot and authenticated Apple export downloads are not claimed.
|
||||
42
docs/atlas-gitea-registry.md
Normal file
42
docs/atlas-gitea-registry.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# Atlas Gitea container registry
|
||||
|
||||
The existing Gitea instance provides an OCI container registry at
|
||||
`git.fscotto.co`. Gitea 1.25.2 enables packages by default; no separate
|
||||
container, port, DNS record, or registry service is required. The existing
|
||||
Gitea HTTPS proxy route is used. The setting applies to Gitea's package
|
||||
registry generally, not only container images.
|
||||
|
||||
On 2026-10-25, both the Atlas HTTP endpoint and the public HTTPS `/v2/`
|
||||
endpoint returned the expected `401` bearer authentication challenge. NPM's
|
||||
effective `client_max_body_size` was `2000m`; larger individual requests may
|
||||
be rejected. Authentication and an actual image push and pull have not yet
|
||||
been tested. Do not interpret the unauthenticated challenge as a complete test.
|
||||
|
||||
## Use with Podman
|
||||
|
||||
Replace `OWNER`, `IMAGE`, and `TAG` with your Gitea user or organization and
|
||||
image details. Log in interactively; use a personal access token when using
|
||||
two-factor authentication. Do not put credentials in commands or shell history.
|
||||
|
||||
```sh
|
||||
podman login git.fscotto.co
|
||||
podman tag LOCAL_IMAGE:TAG git.fscotto.co/OWNER/IMAGE:TAG
|
||||
podman push git.fscotto.co/OWNER/IMAGE:TAG
|
||||
podman pull git.fscotto.co/OWNER/IMAGE:TAG
|
||||
```
|
||||
|
||||
Choose the package's visibility and access deliberately in Gitea. Check the
|
||||
package page and verify the pulled image digest when testing. No automatic
|
||||
cleanup policy is configured by this document.
|
||||
|
||||
## Data and recovery
|
||||
|
||||
The observed package storage directory is
|
||||
`/zpool/services/data/gitea/data/gitea/packages`, inside the existing Gitea
|
||||
dataset. Package metadata also depends on the Gitea database and configuration.
|
||||
Existing recursive ZFS and backup coverage must include both, but a successful
|
||||
registry-specific backup and restore has not been tested. Review backup capacity
|
||||
and consistency as image storage grows; a snapshot alone is not proof of an
|
||||
application-consistent restore.
|
||||
|
||||
Reference: https://docs.gitea.com/1.25/usage/packages/container/
|
||||
@@ -141,11 +141,22 @@ See `atlas-nextcloud-recovery-test.md` for scope, retained artifact and limitati
|
||||
|
||||
## Recurring consistent bundles
|
||||
|
||||
`atlas-nextcloud-backup.service` is now an ordered requirement of both
|
||||
`atlas-nextcloud-backup.service` is an ordered requirement of both
|
||||
`atlas-borg-backup.service` and the operator-started `atlas-usb-backup.service`.
|
||||
No additional backup timer is needed: the existing Borg schedule prepares a fresh
|
||||
bundle before its pool snapshot, and a manual USB run does the same. Preparation
|
||||
failure blocks the dependent job rather than silently using an old dump.
|
||||
bundle before its pool snapshot. A structurally complete bundle from an earlier
|
||||
verified run is reused instead while younger than
|
||||
`atlas_nextcloud_backup_reuse_max_seconds` (20 h): a manual USB run then skips
|
||||
the application pause, reaches its LUKS prompt within seconds and captures the
|
||||
latest Borg-prepared bundle, while the remaining pool snapshot reflects the
|
||||
moment of the run. Reuse does not re-hash the bundle; it was checksum-verified
|
||||
at publication. The window is asserted below 24 h so the nightly Borg run,
|
||||
spaced 24 h plus its randomized delay, never reuses the previous night's bundle.
|
||||
Preparation failure still blocks the dependent job rather than silently using an
|
||||
old dump; only a verified, bounded-age bundle may be reused. Set
|
||||
`ATLAS_NEXTCLOUD_BACKUP_FORCE=1` with `systemctl set-environment` (the unit
|
||||
passes it through) to ignore the window once and prepare a fresh bundle; unset
|
||||
the variable afterwards.
|
||||
|
||||
The helper checks the mounted datasets and healthy active application state,
|
||||
serializes preparations and briefly pauses cron, Nextcloud and ONLYOFFICE. It
|
||||
@@ -171,10 +182,12 @@ sudo systemctl start atlas-nextcloud-backup.service
|
||||
sudo systemctl show atlas-nextcloud-backup.service -p Result -p ExecMainExitTimestamp
|
||||
```
|
||||
|
||||
The second command briefly interrupts the applications and is an explicit manual
|
||||
run of the recurring job, not a normal deployment side effect. The preparation
|
||||
unit is not enabled as a boot backup; only interrupted-job recovery is enabled.
|
||||
Do not stop a Borg/USB job, break its lock or unmount its source snapshot to run a test.
|
||||
A manual start briefly interrupts the applications only when it prepares a fresh
|
||||
bundle; inside the reuse window it logs `Reusing verified ...` and finishes in
|
||||
seconds without touching them. It remains an explicit manual run of the
|
||||
recurring job, not a normal deployment side effect. The preparation unit is not
|
||||
enabled as a boot backup; only interrupted-job recovery is enabled. Do not stop a
|
||||
Borg/USB job, break its lock or unmount its source snapshot to run a test.
|
||||
|
||||
On 2026-10-04, both a new encrypted Borg archive and USB version
|
||||
`20261004T101101Z-3420114` were independently extracted and their consistent
|
||||
@@ -193,7 +206,7 @@ Nextcloud container, using shared SELinux `:z` labels:
|
||||
| Nextcloud folder | Host directory | Access |
|
||||
| --- | --- | --- |
|
||||
| `Documenti` | `/zpool/archive/Documents` | Read/write |
|
||||
| `Foto iCloud` | `/zpool/archive/Pictures/iCloudPD` | Read-only |
|
||||
| `Photos` | `/zpool/archive/Pictures/iCloudPD` | Read-only |
|
||||
|
||||
Both system mounts are restricted to the Nextcloud user `fabio` only; `chiara`
|
||||
and the `famiglia` group have no access through these mounts.
|
||||
@@ -262,8 +275,11 @@ search, not lack of recursive indexing.
|
||||
|
||||
The user preference `photosSourceFolders` was changed directly from
|
||||
`["/Photos","/Foto iCloud"]` to `["/Foto iCloud"]`, after verifying no indexed
|
||||
media under the personal Photos directory. No original files were moved or
|
||||
modified, and no permanent one-time repair task was added to Ansible.
|
||||
media under the personal Photos directory. On 2026-10-10, the managed external
|
||||
mount was renamed to `Photos`; after the old mount configuration is removed on
|
||||
the live instance, the source preference must be `['/Photos']`. No original
|
||||
files are moved or modified: `Photos` remains a read-only direct view of
|
||||
`/zpool/archive/Pictures/iCloudPD`, with iCloudPD as the sole writer.
|
||||
The diagnostic app password was revoked. Browser display confirmation remains
|
||||
with the operator; this check does not establish mobile-gallery behavior.
|
||||
|
||||
|
||||
80
docs/atlas-paperless.md
Normal file
80
docs/atlas-paperless.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# Paperless-ngx on Atlas
|
||||
|
||||
Atlas runs Paperless-ngx as six `admin`-owned rootless Quadlets:
|
||||
Paperless 3.2.1, PostgreSQL 17, Valkey 8, Apache Tika 3.3.1.0 and
|
||||
Gotenberg 8.37, and Ollama 0.40.3. State is isolated beneath
|
||||
`zpool/services/data/paperless` in `data`, `media`, `consume`, `database` and
|
||||
`cache`, and `ollama` datasets, so recursive ZFS snapshots, Borg and the UUID-bound USB
|
||||
backup cover it without an application-specific backup job.
|
||||
|
||||
The only published listener is `192.168.178.55:8002`; Atlas firewalld admits it
|
||||
only from Aegis. The database, broker and Office converters have no host
|
||||
listener. Paperless is
|
||||
configured with the canonical public URL `https://documents.fscotto.co`.
|
||||
|
||||
Ollama has no published host port and is reachable only on the private Paperless
|
||||
container network. Paperless uses `qwen2.5:1.5b-instruct-q4_K_M` for suggestions
|
||||
and chat and `nomic-embed-text:v1.5` for local document embeddings. Its context
|
||||
is capped at 2048 tokens; Ollama is limited to 3 GiB, one loaded
|
||||
model and one parallel request because Atlas has little spare RAM. Model files
|
||||
are downloaded once from the Ollama registry; documents are not sent there.
|
||||
The small language model trades answer quality and speed for resource safety.
|
||||
Review AI-generated suggestions and answers before relying on them.
|
||||
|
||||
After the first deployment, build the LLM index when convenient (it may take
|
||||
time and CPU proportional to the document count):
|
||||
|
||||
```sh
|
||||
sudo -iu admin XDG_RUNTIME_DIR=/run/user/1000 \
|
||||
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
|
||||
podman exec atlas-paperless document_llmindex rebuild
|
||||
```
|
||||
|
||||
The scheduled incremental index update runs daily. After changing the
|
||||
embedding model, rebuild the index again. App Configuration values in the
|
||||
Paperless database take precedence over environment variables, so avoid setting
|
||||
AI endpoint/backend overrides in the UI if Ansible should remain authoritative.
|
||||
|
||||
Tika and Gotenberg enable DOCX and other Office imports. Paperless retains the
|
||||
original and produces a PDF rendition; this does not add in-browser editing.
|
||||
Gotenberg disables Chromium JavaScript and restricts file access for email
|
||||
conversion. A targeted role run probes both converters from inside Paperless.
|
||||
|
||||
## Initial deployment
|
||||
|
||||
The required encrypted-Vault fields are `vault_paperless_database_password`
|
||||
and `vault_paperless_secret_key`; do not place them in host variables or paste
|
||||
them into chat. Generate unique values through the local Vault workflow before
|
||||
the first run. The service assertion deliberately rejects absent or weak
|
||||
values.
|
||||
|
||||
Deploy with:
|
||||
|
||||
```sh
|
||||
ANSIBLE_LOCAL_TEMP=/tmp/ansible-local \
|
||||
ansible-playbook ansible/site.yml --limit atlas --tags paperless --check --diff
|
||||
ANSIBLE_LOCAL_TEMP=/tmp/ansible-local \
|
||||
ansible-playbook ansible/site.yml --limit atlas --tags paperless
|
||||
```
|
||||
|
||||
After it is healthy, add an NPM Proxy Host manually on Prometheus for
|
||||
`documents.fscotto.co` to `http://192.168.178.55:8002`, request its TLS
|
||||
certificate, and keep Websocket Support enabled. DNS and NPM remain explicit
|
||||
operations and are not changed by the Paperless role.
|
||||
|
||||
Create the initial Paperless administrator interactively from an Atlas SSH
|
||||
session; do not put an initial user password in the playbook or Vault:
|
||||
|
||||
```sh
|
||||
sudo -iu admin XDG_RUNTIME_DIR=/run/user/1000 \
|
||||
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
|
||||
podman exec -it atlas-paperless document_index reindex
|
||||
sudo -iu admin XDG_RUNTIME_DIR=/run/user/1000 \
|
||||
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
|
||||
podman exec -it atlas-paperless createsuperuser
|
||||
```
|
||||
|
||||
The first command is optional for a new empty instance; it is included as a
|
||||
safe way to ensure the index is current before using Paperless. Put scanned
|
||||
files in the private `consume` dataset only via an intentionally configured
|
||||
source; Paperless consumes and moves them into its managed media store.
|
||||
120
docs/atlas-qbittorrent.md
Normal file
120
docs/atlas-qbittorrent.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# Atlas qBittorrent
|
||||
|
||||
Atlas runs the official qBittorrent-nox image, pinned by digest, in the
|
||||
admin-owned rootless `atlas-qbittorrent.service` Quadlet. No VPN is involved:
|
||||
outbound traffic uses Atlas' normal home-network default route. Existing
|
||||
WireGuard configuration is unchanged.
|
||||
|
||||
- LAN Web UI: `http://192.168.178.55:8090` (LAN-only firewalld rule,
|
||||
already including Aegis at `192.168.178.54`).
|
||||
- Prepared public domain: `torrent.fscotto.co`, through NPM on Prometheus.
|
||||
DNS and the NPM Proxy Host remain manual operations.
|
||||
- Downloads: `/zpool/archive/Downloads`, available through SMB `Archive`.
|
||||
- Private configuration dataset: `zpool/services/data/qbittorrent`.
|
||||
- Only configuration and Downloads are mounted in the container.
|
||||
- UPnP/NAT-PMP is disabled in the initial settings. No torrent peer port is
|
||||
published and no router port forwarding is configured. Outbound connections
|
||||
work; inbound peer connectivity and seeding are consequently limited.
|
||||
- The Web UI keeps authentication and CSRF/Host-header protection enabled.
|
||||
Initial settings are seeded only once. Ansible owns only the declared Web
|
||||
domain, reverse-proxy support, trusted Aegis source, and authentication/CSRF/Host
|
||||
protections; it stops only qBittorrent before changing these settings and
|
||||
preserves credentials and unrelated application settings.
|
||||
|
||||
## Deployment
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
ansible-playbook ansible/site.yml --limit atlas --tags qbittorrent --check --diff
|
||||
ansible-playbook ansible/site.yml --limit atlas --tags qbittorrent
|
||||
```
|
||||
|
||||
The service starts at boot through `WantedBy=default.target` and admin lingering.
|
||||
A real reboot must be verified separately. Only a changed Quadlet restarts the
|
||||
service on subsequent playbook runs.
|
||||
|
||||
## First login
|
||||
|
||||
Username: `admin`. The application generates a temporary password at startup.
|
||||
Read it privately on Atlas, without pasting it into chat:
|
||||
|
||||
```sh
|
||||
ssh admin@192.168.178.55 'podman logs atlas-qbittorrent 2>&1 | grep "temporary password" | tail -1'
|
||||
```
|
||||
|
||||
Set a permanent password immediately under Web UI settings. Temporary passwords
|
||||
change after restarting until a permanent password is saved. LAN access uses
|
||||
HTTP; do not expose this port to the Internet. An SSH tunnel may be used instead
|
||||
for encrypted access.
|
||||
|
||||
Downloads are inside Archive and inherit its existing snapshot, Borg and offline
|
||||
USB backup scope. Large downloads and incomplete files therefore affect backup
|
||||
capacity. No backup exclusions or automatic deletion are introduced.
|
||||
|
||||
Official image documentation:
|
||||
<https://github.com/qbittorrent/docker-qbittorrent-nox>
|
||||
|
||||
## Verified on 2026-10-10
|
||||
|
||||
The pinned image reports qBittorrent v5.2.4. Targeted deployment succeeded and a
|
||||
second application reported `changed=0`, `failed=0`. LAN HTTP returned 200 from
|
||||
Ikaros; unauthenticated API access returned 403. Authenticated API checks verified
|
||||
the download paths, required authentication, Host-header/CSRF protection, and
|
||||
port forwarding disabled, including after a qBittorrent service restart. Existing
|
||||
Gitea, Navidrome, Syncthing and iCloudPD services remained active.
|
||||
|
||||
A real torrent download and a host reboot have not been tested. The initial
|
||||
WebUI port mapping was corrected to use 8090 internally and externally, preserving
|
||||
Host-header validation. qBittorrent 5.2 uses `[Network] PortForwardingEnabled=false`
|
||||
for its persistent UPnP/NAT-PMP option.
|
||||
|
||||
|
||||
## Manual public endpoint setup
|
||||
|
||||
Atlas is prepared for `torrent.fscotto.co`, with reverse-proxy support enabled
|
||||
and only `192.168.178.54` (the Aegis source-NAT gateway) trusted for forwarded
|
||||
client addresses. Existing LAN access remains available. No new firewall opening
|
||||
is required because the existing `192.168.178.0/24` rule includes Aegis.
|
||||
|
||||
Before publishing, set a strong permanent Web UI password. A temporary startup
|
||||
password is not suitable for a public endpoint. Do not bypass authentication for
|
||||
the reverse proxy or disable CSRF/Host validation.
|
||||
|
||||
Namecheap:
|
||||
|
||||
- Type: A Record; Host: `torrent`; Value: `179.237.102.172` (Prometheus).
|
||||
- Do not point this record to Atlas' private LAN address.
|
||||
|
||||
NPM on Prometheus:
|
||||
|
||||
- Domain Names: `torrent.fscotto.co`
|
||||
- Scheme: `http`
|
||||
- Forward Hostname/IP: `192.168.178.55`
|
||||
- Forward Port: `8090`
|
||||
- SSL: request/select a certificate for the domain and enable Force SSL.
|
||||
- No custom Advanced configuration is needed for the currently deployed NPM:
|
||||
its standard include sets `Host $host`, `X-Forwarded-Proto`, and
|
||||
`X-Forwarded-For`. Host has no explicit external port, avoiding the Web UI's
|
||||
internal-port validation. Do not replace it with `Host $http_host` when the
|
||||
latter includes `:443`.
|
||||
|
||||
Reference: <https://github.com/qbittorrent/qBittorrent/wiki/NGINX-Reverse-Proxy-for-Web-UI>.
|
||||
Public DNS, TLS and end-to-end login remain unverified until the manual setup is
|
||||
complete. Preparing the Web proxy does not change torrent peer connectivity.
|
||||
|
||||
### Reverse-proxy preparation verified on 2026-10-10
|
||||
|
||||
The previous live domain `downloads.fscotto.co` was verified with HTTPS forwarded headers from the NPM
|
||||
container on Prometheus through Aegis (HTTP 200). Unauthenticated API access is
|
||||
still denied (403), and an unrelated Host is rejected (401). No DNS record,
|
||||
NPM Proxy Host, certificate, router forwarding or WireGuard configuration was
|
||||
changed. The existing LAN firewall rule already permits Aegis. A permanent
|
||||
Web UI password still needs to be configured before public exposure.
|
||||
|
||||
The domain change to `torrent.fscotto.co` was subsequently applied to Atlas with
|
||||
the targeted `qbittorrent` playbook tag. The old live Host allowlist caused HTTP
|
||||
401 (Unauthorized) on the new public domain. After deployment, public HTTPS
|
||||
returned 200 and unauthenticated API access remained denied (403). Credentials,
|
||||
Host validation and CSRF protection were preserved; all existing Atlas services
|
||||
remained active. DNS and NPM were not modified by this deployment.
|
||||
43
docs/deadalus-cdp-devcontainer.md
Normal file
43
docs/deadalus-cdp-devcontainer.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# cdp Java 25 / Node 20 dev container on deadalus
|
||||
|
||||
Same toolset and mounts as the [ecaas container](deadalus-ecaas-devcontainer.md)
|
||||
(Git configuration and GitLab CAs, Bash configuration, `~/.m2`, `~/.claude`,
|
||||
`~/.cline`, `~/.agents`, `~/.config/ai`, Docker outside of Docker, Claude Code,
|
||||
Cline, delta, Great Icons), with these differences:
|
||||
|
||||
- Java 25 (`mcr.microsoft.com/devcontainers/java:25-bookworm`) is the default JDK
|
||||
and also runs the Java and Spring language servers; there is no second JDK.
|
||||
- Maven is `workstation_maven_version`; Node is
|
||||
`workstation_cdp_node_version` (20.18.3) from the official Node image, used by
|
||||
the Angular Module Federation front ends and the Claude/Cline CLIs.
|
||||
- Angular Language Service and ESLint are added; forwarded ports are 4200, 4201,
|
||||
4202, 4210 (front ends) and 8083, 8084 (`mediation-ansc`, `ansc-allegati`).
|
||||
- `kubectl` 1.37.1 and Helm 4.2.2 are installed from the official releases with
|
||||
pinned SHA-256 checksums (amd64 and arm64), and the Kubernetes VS Code
|
||||
extension is added. The WSL `~/.kube` is bind-mounted read-write at
|
||||
`/home/vscode/.kube`, so contexts, tokens and cached data are shared with the
|
||||
host; the current `config` embeds the Rancher CA and credentials, which are
|
||||
therefore readable by anything in the container. The Rancher endpoint must be
|
||||
reachable from the container (VPN). `KUBECONFIG` on the host is not forwarded.
|
||||
- `glab` 1.114.0 (pinned checksum) is installed and `~/.config/glab-cli` is
|
||||
mounted read-write, as described in the ecaas document (tokens included).
|
||||
|
||||
Legacy `serv_roma-capitale-*` modules target Java 21 / Spring Boot 3.3.4 and
|
||||
are not covered by this image's JDK.
|
||||
|
||||
The workspace is multi-repo and not a Git repository itself; open
|
||||
`~/Work/sipo/cdp` from Fedora WSL. Maven needs the internal Nexus (VPN) and
|
||||
`-s settings.xml`, as described in the workspace `AGENTS.md`.
|
||||
|
||||
```sh
|
||||
ansible-playbook ansible/site.yml --limit deadalus --tags cdp_devcontainer -K
|
||||
```
|
||||
|
||||
The deploy writes `~/Work/sipo/cdp/.devcontainer/` (`devcontainer.json`,
|
||||
`Dockerfile`, `bashrc`, `bashrc.aliases`), backing up changed files. It shares
|
||||
the rendered Git configuration in `~/.local/state/ecaas-devcontainer/git` with
|
||||
the ecaas container and therefore also requires the ecaas GitLab CA. Then run
|
||||
**Dev Containers: Reopen in Container**. The `ANTHROPIC_AUTH_TOKEN` forwarding
|
||||
and credential caveats are the same as for ecaas.
|
||||
|
||||
Verify inside: `java -version`, `mvn -v`, `node -v` (v20.18.3), `docker info`.
|
||||
125
docs/deadalus-ecaas-devcontainer.md
Normal file
125
docs/deadalus-ecaas-devcontainer.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# ecaas Java 11 dev container on deadalus
|
||||
|
||||
From the AnsiblePlaybook checkout **in Fedora WSL 2 on deadalus**:
|
||||
|
||||
```sh
|
||||
ansible-playbook ansible/site.yml --limit deadalus --tags ecaas_devcontainer -K
|
||||
```
|
||||
|
||||
This creates `~/Work/sipo/ecaas/.devcontainer/` and deploys `devcontainer.json`,
|
||||
`Dockerfile` and `bashrc`, backing up previous versions if they change. It does
|
||||
not clone or modify application sources, change VS Code's Windows settings, or
|
||||
start Docker containers. The Docker context selection remains in the local
|
||||
WSL/VS Code setup.
|
||||
|
||||
Confirm that `docker context show` is `default` and `docker info` shows the local
|
||||
Fedora engine. Open `~/Work/ecaas` using `code .` from Fedora and select
|
||||
**Dev Containers: Reopen in Container** (or **Rebuild Container** if already open).
|
||||
Do not use the production context to build or open the workspace.
|
||||
|
||||
The container uses Java 11 for the application and Maven, and Java 21 only for
|
||||
the Java and Spring language servers. VS Code installs the Java and Spring Boot
|
||||
extension packs, XML, YAML, the Cline extension and the VSCode Great Icons theme
|
||||
(selected as the file icon theme) inside the container. The Java
|
||||
pack includes Maven, the Java debugger and test integration. Prefer the project's
|
||||
Maven wrapper where present. Node is provided for the Claude and Cline CLIs.
|
||||
|
||||
Git is installed in the container. The image uses the repository's portable Bash
|
||||
configuration: prompt with Git status, aliases, history search, completion,
|
||||
`fzf` and `zoxide`. The shared `.bashrc.aliases` is copied minus the
|
||||
production `npm-tunnel` alias. The image
|
||||
does not load the WSL host's production aliases or Bash history.
|
||||
Run the deploy and rebuild the container to pick up changes to the shared Bash
|
||||
configuration.
|
||||
|
||||
## Git, HTTPS, and SSH
|
||||
|
||||
The image provides Git, Git LFS, delta, OpenSSH and GnuPG. It includes the
|
||||
managed workstation Git configuration from a read-only mount at runtime,
|
||||
with VS Code rather than Bob as the diff and merge tool. Git identity and
|
||||
signing configuration stay outside the workspace and image layers.
|
||||
|
||||
Before deploying, ensure the existing WSL certificate
|
||||
`~/.local/share/certs/ecaas.datacenter.comune.roma.crt` is available. The
|
||||
playbook checks and mounts that file read-only. It also mounts
|
||||
`datacenter.comune.roma.crt` from the same directory if present. These files
|
||||
are scoped to their GitLab URLs in Git; the image does not disable TLS
|
||||
verification or add the internal certificates to its global trust store.
|
||||
Recreate the container after replacing a certificate on the host.
|
||||
|
||||
Open the project from Fedora WSL so VS Code Dev Containers can reuse WSL's
|
||||
HTTPS credential helper (including an existing `.git-credentials` used by
|
||||
`credential.helper=store`) and forward the SSH agent if configured. GPG
|
||||
signing remains enabled and needs the work key available through the GPG
|
||||
agent. The WSL `~/.m2` (repository cache and `settings*.xml`, which may hold Maven
|
||||
server credentials) is bind-mounted read-write at `/home/vscode/.m2`. No other
|
||||
credential file, SSH private key, or GPG private key is copied or mounted by
|
||||
the playbook. Do not forward a production SSH identity to this
|
||||
development workspace.
|
||||
|
||||
To verify GitLab access from the container without changing the repo, run
|
||||
`git ls-remote origin HEAD` after checking that `origin` is the expected
|
||||
GitLab repository.
|
||||
|
||||
## Docker
|
||||
|
||||
The `docker-outside-of-docker` Dev Container feature installs the Docker CLI
|
||||
and Compose plugin and shares the local Fedora WSL engine's socket
|
||||
(`/var/run/docker.sock`) with the container. Containers started from inside are
|
||||
siblings on the WSL engine, and bind-mount sources resolve on the WSL host.
|
||||
The socket grants root-equivalent control of that engine, and the container
|
||||
never sees the host's Docker contexts, so the production context is
|
||||
unreachable. Verify with `docker info` and `docker compose version`.
|
||||
|
||||
## GitLab CLI
|
||||
|
||||
`glab` 1.114.0 is installed from the official `.deb` with a pinned SHA-256
|
||||
checksum (amd64 and arm64). The WSL `~/.config/glab-cli` is bind-mounted
|
||||
read-write at `/home/vscode/.config/glab-cli`, so hosts, API tokens and
|
||||
`skip_tls_verify` settings are shared with the host and readable by anything in
|
||||
the container; changes made by `glab` inside affect the WSL configuration.
|
||||
`GITLAB_TOKEN` and similar variables from the host are not forwarded.
|
||||
|
||||
## Agent configuration and smoke test
|
||||
|
||||
Claude and Cline use the WSL configuration directly: `~/.claude` and `~/.cline`
|
||||
are bind-mounted read-write at `/home/vscode/.claude` and `/home/vscode/.cline`,
|
||||
the cross-tool `~/.agents` read-only at `/home/vscode/.agents`, and
|
||||
`~/.config/ai` read-only at `/home/vscode/.config/ai`, so rules, the AGENTS
|
||||
pointer and the shared AI context follow the WSL host. The playbook keeps
|
||||
Cline's managed configuration deployed on the host (`cline_deploy_enabled:
|
||||
true`) even though the cline CLI npm package is not installed there; the CLI
|
||||
ships inside the image and the VS Code Cline extension is installed through
|
||||
the devcontainer customizations. Settings, rules,
|
||||
skills, MCP configuration, sessions and **credential stores** are therefore
|
||||
shared with, and visible to, the container, and changes made inside it affect
|
||||
the WSL home. Host paths and tools referenced by rules or skills may need
|
||||
adaptation. The WSL login is the `ANTHROPIC_AUTH_TOKEN` exported by
|
||||
`~/.bashrc.d/60-claude-code.sh`, not the OAuth file. `remoteEnv` forwards it with
|
||||
`${localEnv:ANTHROPIC_AUTH_TOKEN}`: the value is never written to the repository
|
||||
or the image, but it is visible to processes in the container. VS Code must
|
||||
therefore be started from a WSL shell that exports it (`code .` after opening a
|
||||
new terminal; fully close any running VS Code server first). The endpoint and
|
||||
model come from the mounted `settings.json`. With `CLAUDE_CONFIG_DIR` set, Claude reads its account state from
|
||||
`~/.claude/.claude.json` instead of `~/.claude.json`, so the playbook seeds the
|
||||
missing `oauthAccount`, `hasCompletedOnboarding` and `userID` keys there from
|
||||
the WSL file without overwriting existing keys (`~/.claude.json` itself is not
|
||||
mounted); VS Code global storage is not shared
|
||||
either, so legacy Cline settings kept only there are not migrated. The full
|
||||
host home is not mounted. `~/.local/state/ecaas-devcontainer/` now holds only
|
||||
the rendered Git configuration.
|
||||
|
||||
|
||||
From the integrated terminal inside the Dev Container, verify:
|
||||
|
||||
```sh
|
||||
java -version
|
||||
mvn -v
|
||||
git --version
|
||||
delta --version
|
||||
claude --version
|
||||
cline --version
|
||||
```
|
||||
|
||||
Both Java and Maven should report Java 11. Run the project's Maven tests and
|
||||
check that the Spring Boot Dashboard, Java debugger and both AI panels open.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user