mirror of
https://github.com/fscotto/infra.git
synced 2026-11-25 21:29:51 +00:00
Add encrypted media volume controls and tolerate unavailable HEIC builds
This commit is contained in:
@@ -9,6 +9,7 @@ gemini_cli_uninstall_enabled: true
|
||||
chatgpt_desktop_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
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ 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"
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
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 + '/')
|
||||
@@ -319,10 +322,12 @@
|
||||
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:
|
||||
|
||||
@@ -2,8 +2,96 @@
|
||||
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"
|
||||
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"
|
||||
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)
|
||||
@@ -13,6 +101,9 @@ case "$app" in
|
||||
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)
|
||||
@@ -27,7 +118,7 @@ case "$app" in
|
||||
"localhost/ai-media-$tool:managed" verify
|
||||
done
|
||||
exit 0 ;;
|
||||
*) echo "Usage: ai-media {facefusion|rvc|ffmpeg|preset|verify} [args ...]" >&2; exit 2 ;;
|
||||
*) 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
|
||||
@@ -35,6 +126,9 @@ for path in "$root" "$root/input" "$root/output" "$root/models" "$root/state/$ap
|
||||
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.
|
||||
|
||||
176
ansible/roles/desktop_ai_media/tests/test_storage_commands.py
Normal file
176
ansible/roles/desktop_ai_media/tests/test_storage_commands.py
Normal file
@@ -0,0 +1,176 @@
|
||||
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 == "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"):
|
||||
(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 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")]
|
||||
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"],
|
||||
["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, [["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"], ["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"], ["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, [])
|
||||
@@ -66,12 +66,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
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
# 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
|
||||
|
||||
Reference in New Issue
Block a user