mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
Moving WROLPi-managed mounts off /etc/fstab onto a drive-resident fstab.yaml.
A WROLPi drive can move between hosts and across deployment styles (Portable, RPi, Debian). /etc/fstab is host-specific and on the Portable image it's part of a read-only squashfs, so persisting secondary mounts there was both wrong-host and lost-on-reboot. This change makes /media/wrolpi/config/fstab.yaml the single source of truth for WROLPi- managed mounts and introduces a new wrolpi-mounts.service that reconciles live state to match. Architecture: - The Controller writes intent (fstab.yaml) but never calls mount(8) or umount(8) itself. Every mutation triggers `systemctl restart wrolpi-mounts.service`; the Controller then verifies the outcome via the same MountExecutor abstraction the service uses. - wrolpi-mounts.service runs a thin entry point that constructs a real Reconciler with a SubprocessMountExecutor and calls apply(). The reconciler mounts what's in fstab.yaml but missing from the live state, and unmounts paths it previously claimed that are no longer in fstab.yaml. A managed-set file in /run/wrolpi-mounts/managed prevents the reconciler from ever touching user-mounted paths it didn't own. - One-time migration (marker-gated) lifts both /etc/fstab WROLPi entries and any controller.yaml drives.mounts entries into fstab.yaml. /etc/fstab is backed up to /etc/fstab.wrolpi-migration.backup; migrated lines are commented in place with a "migrated to fstab.yaml:" prefix so a host admin can hand-recover. Test approach: dependency injection in place of patching. The MountExecutor protocol has SubprocessMountExecutor (production) and FakeMountExecutor (in-memory, records calls). The Reconciler accepts an executor in its constructor, so the 20 reconciler tests + 13 migration tests + 18 fstab_yaml tests use real files in tmp_path with zero mock.patch calls. test_disks_api.py drops to mocks only for the host-touching read helpers; the mount/unmount paths now run the real Reconciler against the fake executor. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
94d56f313a
commit
719905cb77
15 changed files with 2257 additions and 320 deletions
229
controller/lib/fstab_migration.py
Normal file
229
controller/lib/fstab_migration.py
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
"""
|
||||
One-time migration of WROLPi-managed mount entries into fstab.yaml.
|
||||
|
||||
Two legacy sources exist:
|
||||
|
||||
1. ``/etc/fstab`` — older WROLPi versions wrote WROLPi-managed mounts as
|
||||
ordinary fstab lines so systemd-fstab-generator would mount them at
|
||||
boot. On Portable this is read-only squashfs (writes go to RAM and
|
||||
evaporate), and on any host an /etc/fstab entry is tied to *that* host,
|
||||
not the drive.
|
||||
|
||||
2. ``controller.yaml drives.mounts`` — a brief intermediate iteration
|
||||
stored the mount table alongside Controller settings in
|
||||
``/media/wrolpi/config/controller.yaml``. Lives on the drive but
|
||||
conflates "definitions" with "applier"; we split them out into a
|
||||
dedicated file.
|
||||
|
||||
Both sources feed into ``/media/wrolpi/config/fstab.yaml``. Each source
|
||||
is migrated at most once (gated by a marker file). /etc/fstab is backed
|
||||
up; migrated lines are commented in place rather than deleted so the host
|
||||
admin can hand-recover if something goes wrong.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from controller.lib.fstab_yaml import (
|
||||
DEFAULT_PATH as DEFAULT_FSTAB_YAML_PATH,
|
||||
FstabEntry,
|
||||
load as load_fstab_yaml,
|
||||
save as save_fstab_yaml,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FSTAB_PATH = Path("/etc/fstab")
|
||||
CONTROLLER_YAML_PATH = Path("/media/wrolpi/config/controller.yaml")
|
||||
MARKER_PATH = Path("/media/wrolpi/config/.fstab-migrated")
|
||||
BACKUP_PATH = Path("/etc/fstab.wrolpi-migration.backup")
|
||||
|
||||
# Mount points that legitimately appear in /etc/fstab or drives.mounts but
|
||||
# must not be lifted into fstab.yaml: the primary's mount is host-specific
|
||||
# (live-boot, /etc/fstab installer entry, or repair.sh sets it up directly)
|
||||
# and the temp onboarding mount belongs to the Controller's onboarding flow.
|
||||
EXCLUDED_MIGRATION_MOUNT_POINTS = frozenset({
|
||||
"/media/wrolpi",
|
||||
"/media/wrolpi_temp_onboarding",
|
||||
})
|
||||
|
||||
MIGRATED_PREFIX = "# migrated to fstab.yaml:"
|
||||
|
||||
|
||||
# --- /etc/fstab parser ----------------------------------------------------
|
||||
|
||||
def _parse_fstab_text(text: str) -> list[dict]:
|
||||
"""Parse the contents of an fstab file into structured entries."""
|
||||
entries: list[dict] = []
|
||||
for raw in text.splitlines(keepends=False):
|
||||
stripped = raw.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
entries.append({"type": "comment", "line": raw})
|
||||
continue
|
||||
parts = stripped.split()
|
||||
if len(parts) >= 4:
|
||||
entries.append({
|
||||
"type": "mount",
|
||||
"device": parts[0],
|
||||
"mount_point": parts[1],
|
||||
"fstype": parts[2],
|
||||
"options": parts[3],
|
||||
"line": raw,
|
||||
})
|
||||
else:
|
||||
entries.append({"type": "comment", "line": raw})
|
||||
return entries
|
||||
|
||||
|
||||
def _is_migration_candidate(entry: dict) -> bool:
|
||||
if entry.get("type") != "mount":
|
||||
return False
|
||||
mp = entry.get("mount_point", "")
|
||||
if not mp.startswith("/media"):
|
||||
return False
|
||||
if mp in EXCLUDED_MIGRATION_MOUNT_POINTS:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# --- controller.yaml helpers ----------------------------------------------
|
||||
|
||||
def _read_controller_yaml(path: Path) -> dict:
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
return yaml.safe_load(path.read_text()) or {}
|
||||
except (OSError, yaml.YAMLError) as e:
|
||||
logger.warning("Could not parse %s, treating as empty: %s", path, e)
|
||||
return {}
|
||||
|
||||
|
||||
def _save_controller_yaml(path: Path, data: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(yaml.safe_dump(data, default_flow_style=False, sort_keys=True))
|
||||
|
||||
|
||||
# --- Main entry point -----------------------------------------------------
|
||||
|
||||
def migrate_etc_fstab(
|
||||
*,
|
||||
fstab_path: Path = FSTAB_PATH,
|
||||
controller_yaml_path: Path = CONTROLLER_YAML_PATH,
|
||||
fstab_yaml_path: Path = None,
|
||||
marker_path: Path = MARKER_PATH,
|
||||
backup_path: Path = BACKUP_PATH,
|
||||
) -> dict:
|
||||
"""Lift WROLPi-managed mounts from /etc/fstab and
|
||||
controller.yaml drives.mounts into fstab.yaml.
|
||||
|
||||
Returns ``{migrated, reason?, count}`` where ``count`` is the number of
|
||||
new entries added to fstab.yaml.
|
||||
"""
|
||||
if marker_path.exists():
|
||||
return {"migrated": False, "reason": "already-migrated", "count": 0}
|
||||
|
||||
fstab_yaml_path = fstab_yaml_path or DEFAULT_FSTAB_YAML_PATH
|
||||
|
||||
# --- Gather candidates from both sources ----------------------------
|
||||
etc_fstab_candidates: list[dict] = []
|
||||
if fstab_path.exists():
|
||||
try:
|
||||
etc_fstab_text = fstab_path.read_text()
|
||||
except OSError as e:
|
||||
logger.warning("Could not read %s: %s", fstab_path, e)
|
||||
etc_fstab_text = ""
|
||||
etc_fstab_entries = _parse_fstab_text(etc_fstab_text)
|
||||
etc_fstab_candidates = [
|
||||
e for e in etc_fstab_entries if _is_migration_candidate(e)
|
||||
]
|
||||
else:
|
||||
etc_fstab_text = ""
|
||||
etc_fstab_entries = []
|
||||
|
||||
controller_data = _read_controller_yaml(controller_yaml_path)
|
||||
drives_mounts_candidates = []
|
||||
for m in (controller_data.get("drives") or {}).get("mounts") or []:
|
||||
mp = m.get("mount_point", "")
|
||||
if not mp.startswith("/media") or mp in EXCLUDED_MIGRATION_MOUNT_POINTS:
|
||||
continue
|
||||
drives_mounts_candidates.append(m)
|
||||
|
||||
# --- Backup /etc/fstab before any modification ----------------------
|
||||
if etc_fstab_candidates:
|
||||
try:
|
||||
shutil.copy2(fstab_path, backup_path)
|
||||
except OSError as e:
|
||||
logger.warning("Could not back up %s: %s", fstab_path, e)
|
||||
|
||||
# --- Merge into fstab.yaml (dedup by mount_point) -------------------
|
||||
fstab_data = load_fstab_yaml(fstab_yaml_path)
|
||||
existing = fstab_data.mount_points()
|
||||
added = 0
|
||||
|
||||
for cand in etc_fstab_candidates:
|
||||
if cand["mount_point"] in existing:
|
||||
continue
|
||||
fstab_data.add_or_replace(FstabEntry(
|
||||
device=cand["device"],
|
||||
mount_point=cand["mount_point"],
|
||||
fstype=cand["fstype"],
|
||||
options=cand.get("options") or "defaults",
|
||||
))
|
||||
existing.add(cand["mount_point"])
|
||||
added += 1
|
||||
|
||||
for cand in drives_mounts_candidates:
|
||||
mp = cand["mount_point"]
|
||||
if mp in existing:
|
||||
continue
|
||||
fstab_data.add_or_replace(FstabEntry(
|
||||
device=cand.get("device", ""),
|
||||
mount_point=mp,
|
||||
fstype=cand.get("fstype") or "auto",
|
||||
options=cand.get("options") or "defaults",
|
||||
))
|
||||
existing.add(mp)
|
||||
added += 1
|
||||
|
||||
if etc_fstab_candidates or drives_mounts_candidates:
|
||||
save_fstab_yaml(fstab_data, fstab_yaml_path)
|
||||
|
||||
# --- Comment out migrated entries in /etc/fstab ---------------------
|
||||
if etc_fstab_candidates:
|
||||
candidate_mps = {e["mount_point"] for e in etc_fstab_candidates}
|
||||
new_lines = []
|
||||
for entry in etc_fstab_entries:
|
||||
if (entry["type"] == "mount"
|
||||
and entry["mount_point"] in candidate_mps):
|
||||
new_lines.append(f"{MIGRATED_PREFIX} {entry['line']}")
|
||||
else:
|
||||
new_lines.append(entry["line"])
|
||||
suffix = "\n" if etc_fstab_text.endswith("\n") else ""
|
||||
try:
|
||||
fstab_path.write_text("\n".join(new_lines) + suffix)
|
||||
except OSError as e:
|
||||
logger.warning("Could not rewrite %s: %s", fstab_path, e)
|
||||
|
||||
# --- Strip drives.mounts from controller.yaml -----------------------
|
||||
if drives_mounts_candidates and (controller_data.get("drives") or {}).get("mounts"):
|
||||
drives = controller_data.get("drives") or {}
|
||||
drives.pop("mounts", None)
|
||||
if not drives:
|
||||
controller_data.pop("drives", None)
|
||||
else:
|
||||
controller_data["drives"] = drives
|
||||
_save_controller_yaml(controller_yaml_path, controller_data)
|
||||
|
||||
# --- Mark done ------------------------------------------------------
|
||||
marker_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
marker_path.touch()
|
||||
|
||||
logger.info(
|
||||
"Migration complete: %d /etc/fstab candidate(s), %d drives.mounts "
|
||||
"candidate(s), %d new entry/entries written to fstab.yaml",
|
||||
len(etc_fstab_candidates), len(drives_mounts_candidates), added,
|
||||
)
|
||||
return {"migrated": True, "count": added}
|
||||
146
controller/lib/fstab_yaml.py
Normal file
146
controller/lib/fstab_yaml.py
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
"""
|
||||
Reader/writer for /media/wrolpi/config/fstab.yaml.
|
||||
|
||||
This file is the WROLPi-managed mount table. It lives on the drive itself
|
||||
(so it travels between hosts) and is the sole input to the Reconciler.
|
||||
|
||||
Schema::
|
||||
|
||||
version: 1
|
||||
mounts:
|
||||
- device: UUID=... # filesystem UUID; the entry is portable
|
||||
mount_point: /media/... # must be under /media
|
||||
fstype: ext4
|
||||
options: defaults # mount(8) -o options
|
||||
|
||||
The Controller defines what should be mounted by editing this file; the
|
||||
Reconciler (invoked by wrolpi-mounts.service) applies the diff between this
|
||||
file and the live mount state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_PATH = Path("/media/wrolpi/config/fstab.yaml")
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class FstabEntry:
|
||||
"""A single row in fstab.yaml."""
|
||||
|
||||
device: str
|
||||
mount_point: str
|
||||
fstype: str
|
||||
options: str = "defaults"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"device": self.device,
|
||||
"mount_point": self.mount_point,
|
||||
"fstype": self.fstype,
|
||||
"options": self.options,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "FstabEntry":
|
||||
return cls(
|
||||
device=data.get("device", ""),
|
||||
mount_point=data.get("mount_point", ""),
|
||||
fstype=data.get("fstype", "auto"),
|
||||
options=data.get("options") or "defaults",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FstabFile:
|
||||
"""In-memory representation of fstab.yaml."""
|
||||
|
||||
version: int = SCHEMA_VERSION
|
||||
mounts: list[FstabEntry] = field(default_factory=list)
|
||||
|
||||
# --- Lookup helpers ------------------------------------------------
|
||||
|
||||
def find_by_mount_point(self, mount_point: str) -> Optional[FstabEntry]:
|
||||
for m in self.mounts:
|
||||
if m.mount_point == mount_point:
|
||||
return m
|
||||
return None
|
||||
|
||||
def mount_points(self) -> set[str]:
|
||||
return {m.mount_point for m in self.mounts}
|
||||
|
||||
# --- Mutation -------------------------------------------------------
|
||||
|
||||
def add_or_replace(self, entry: FstabEntry) -> None:
|
||||
"""Insert ``entry``, replacing any prior row that shares its
|
||||
mount_point OR its device. The device clause handles the "remount
|
||||
the same drive to a different path" case so we don't accumulate
|
||||
stale rows."""
|
||||
self.mounts = [
|
||||
m for m in self.mounts
|
||||
if m.mount_point != entry.mount_point and m.device != entry.device
|
||||
]
|
||||
self.mounts.append(entry)
|
||||
|
||||
def remove_by_mount_point(self, mount_point: str) -> bool:
|
||||
"""Remove the entry at ``mount_point``. Returns True if a row was
|
||||
removed, False if none matched."""
|
||||
before = len(self.mounts)
|
||||
self.mounts = [m for m in self.mounts if m.mount_point != mount_point]
|
||||
return len(self.mounts) < before
|
||||
|
||||
|
||||
# --- File I/O -------------------------------------------------------------
|
||||
|
||||
def load(path: Optional[Path] = None) -> FstabFile:
|
||||
"""Read fstab.yaml. Returns an empty FstabFile if the file is absent
|
||||
or malformed; both are normal startup conditions on a fresh drive.
|
||||
|
||||
``path`` defaults to the module-level ``DEFAULT_PATH`` at call time
|
||||
(resolved on each invocation, so tests can redirect via monkeypatch).
|
||||
"""
|
||||
if path is None:
|
||||
path = DEFAULT_PATH
|
||||
if not path.exists():
|
||||
return FstabFile()
|
||||
try:
|
||||
raw = yaml.safe_load(path.read_text()) or {}
|
||||
except yaml.YAMLError as e:
|
||||
logger.warning("fstab.yaml at %s is malformed (%s); treating as empty", path, e)
|
||||
return FstabFile()
|
||||
version = raw.get("version", SCHEMA_VERSION)
|
||||
mounts = [FstabEntry.from_dict(m) for m in (raw.get("mounts") or [])]
|
||||
return FstabFile(version=version, mounts=mounts)
|
||||
|
||||
|
||||
def save(data: FstabFile, path: Optional[Path] = None) -> None:
|
||||
"""Write fstab.yaml atomically (write-then-rename). Creates the parent
|
||||
directory if needed. Sorted by mount_point so diffs stay tidy.
|
||||
|
||||
``path`` defaults to the module-level ``DEFAULT_PATH`` at call time so
|
||||
tests can redirect via monkeypatch.
|
||||
"""
|
||||
if path is None:
|
||||
path = DEFAULT_PATH
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
sorted_mounts = sorted(data.mounts, key=lambda m: m.mount_point)
|
||||
serialised = yaml.safe_dump(
|
||||
{
|
||||
"version": data.version,
|
||||
"mounts": [m.to_dict() for m in sorted_mounts],
|
||||
},
|
||||
default_flow_style=False,
|
||||
sort_keys=True,
|
||||
)
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_text(serialised)
|
||||
tmp.replace(path)
|
||||
182
controller/lib/mount_executor.py
Normal file
182
controller/lib/mount_executor.py
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
"""
|
||||
The narrow interface between WROLPi's mount reconciler and the operating
|
||||
system. Pulling these three operations behind a single abstraction lets the
|
||||
reconciler stay pure-orchestration: tests construct a FakeMountExecutor that
|
||||
records calls + holds an in-memory mount-table, with no patches against
|
||||
subprocess, /proc/mounts, or pwd/grp.
|
||||
|
||||
Two implementations live here:
|
||||
|
||||
- SubprocessMountExecutor — production. Calls mount(8) / umount(8) via
|
||||
subprocess and reads /proc/mounts.
|
||||
|
||||
- FakeMountExecutor — tests. Tracks a mount-point set in memory, records
|
||||
every mount/unmount call, and accepts predetermined per-call failures via
|
||||
`fail_for`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, Protocol
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MountResult:
|
||||
"""Outcome of a single mount or unmount call."""
|
||||
|
||||
ok: bool
|
||||
error: Optional[str] = None
|
||||
|
||||
|
||||
class MountExecutor(Protocol):
|
||||
"""The contract every executor must satisfy.
|
||||
|
||||
Implementations should never raise for I/O failures; instead, return a
|
||||
MountResult(ok=False, error="…"). Raising is reserved for programmer
|
||||
errors (bad arguments, etc.).
|
||||
"""
|
||||
|
||||
def mount(
|
||||
self,
|
||||
device: str,
|
||||
mount_point: str,
|
||||
fstype: str,
|
||||
options: str,
|
||||
) -> MountResult: ...
|
||||
|
||||
def unmount(self, mount_point: str) -> MountResult: ...
|
||||
|
||||
def current_mount_points(self, prefix: str = "/media") -> set[str]: ...
|
||||
|
||||
|
||||
# --- Production implementation -------------------------------------------
|
||||
|
||||
MOUNT_TIMEOUT_SECONDS = 30
|
||||
|
||||
|
||||
class SubprocessMountExecutor:
|
||||
"""Executes mount/umount via subprocess and parses /proc/mounts."""
|
||||
|
||||
def __init__(self, timeout_seconds: int = MOUNT_TIMEOUT_SECONDS):
|
||||
self._timeout = timeout_seconds
|
||||
|
||||
def mount(
|
||||
self,
|
||||
device: str,
|
||||
mount_point: str,
|
||||
fstype: str,
|
||||
options: str,
|
||||
) -> MountResult:
|
||||
cmd = ["mount", "-t", fstype, "-o", options, device, mount_point]
|
||||
return self._run(cmd, label=f"mount {device} {mount_point}")
|
||||
|
||||
def unmount(self, mount_point: str) -> MountResult:
|
||||
# Plain umount. If the mount is busy, the reconciler will see it
|
||||
# still present on the next pass and retry; we deliberately do not
|
||||
# add `-l` (lazy) here because lazy unmounts can hide bugs.
|
||||
return self._run(["umount", mount_point], label=f"umount {mount_point}")
|
||||
|
||||
def current_mount_points(self, prefix: str = "/media") -> set[str]:
|
||||
out: set[str] = set()
|
||||
try:
|
||||
with open("/proc/mounts") as f:
|
||||
for line in f:
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1].startswith(prefix):
|
||||
out.add(parts[1])
|
||||
except OSError as e:
|
||||
logger.error("Could not read /proc/mounts: %s", e)
|
||||
return out
|
||||
|
||||
def _run(self, cmd: list[str], *, label: str) -> MountResult:
|
||||
logger.info("Running: %s", " ".join(cmd))
|
||||
try:
|
||||
result = subprocess.run(
|
||||
cmd, capture_output=True, text=True, timeout=self._timeout,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return MountResult(
|
||||
ok=False,
|
||||
error=f"{label}: timed out after {self._timeout}s",
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return MountResult(
|
||||
ok=False,
|
||||
error=f"{label}: {result.stderr.strip() or 'non-zero exit'}",
|
||||
)
|
||||
return MountResult(ok=True)
|
||||
|
||||
|
||||
# --- Test fake ------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class MountCall:
|
||||
"""Recorded mount invocation, for test assertions."""
|
||||
|
||||
device: str
|
||||
mount_point: str
|
||||
fstype: str
|
||||
options: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class UnmountCall:
|
||||
"""Recorded unmount invocation, for test assertions."""
|
||||
|
||||
mount_point: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeMountExecutor:
|
||||
"""In-memory MountExecutor for tests.
|
||||
|
||||
Behaviour:
|
||||
- mount(...) adds mount_point to the live set and records the call,
|
||||
unless the call matches an entry in ``fail_for_mount`` (matched by
|
||||
mount_point), in which case it returns a failure and the set is
|
||||
unchanged.
|
||||
- unmount(...) removes mount_point from the live set and records the
|
||||
call, unless the call matches ``fail_for_unmount``.
|
||||
- current_mount_points(prefix) returns a copy of the live set filtered
|
||||
by prefix.
|
||||
|
||||
Tests can seed the live set via the ``initially_mounted`` argument.
|
||||
"""
|
||||
|
||||
initially_mounted: frozenset[str] = frozenset()
|
||||
fail_for_mount: frozenset[str] = frozenset()
|
||||
fail_for_unmount: frozenset[str] = frozenset()
|
||||
mount_calls: list[MountCall] = field(default_factory=list)
|
||||
unmount_calls: list[UnmountCall] = field(default_factory=list)
|
||||
_live: set[str] = field(init=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._live = set(self.initially_mounted)
|
||||
|
||||
def mount(
|
||||
self,
|
||||
device: str,
|
||||
mount_point: str,
|
||||
fstype: str,
|
||||
options: str,
|
||||
) -> MountResult:
|
||||
self.mount_calls.append(MountCall(device, mount_point, fstype, options))
|
||||
if mount_point in self.fail_for_mount:
|
||||
return MountResult(ok=False, error=f"fake: configured to fail mount {mount_point}")
|
||||
self._live.add(mount_point)
|
||||
return MountResult(ok=True)
|
||||
|
||||
def unmount(self, mount_point: str) -> MountResult:
|
||||
self.unmount_calls.append(UnmountCall(mount_point))
|
||||
if mount_point in self.fail_for_unmount:
|
||||
return MountResult(ok=False, error=f"fake: configured to fail umount {mount_point}")
|
||||
self._live.discard(mount_point)
|
||||
return MountResult(ok=True)
|
||||
|
||||
def current_mount_points(self, prefix: str = "/media") -> set[str]:
|
||||
return {mp for mp in self._live if mp.startswith(prefix)}
|
||||
67
controller/lib/mount_runner.py
Normal file
67
controller/lib/mount_runner.py
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
"""
|
||||
Entry point for wrolpi-mounts.service.
|
||||
|
||||
This module is intentionally tiny: it wires up production dependencies
|
||||
(real subprocess executor, real wrolpi uid/gid lookup, real fstab.yaml on
|
||||
the drive) and asks the Reconciler to apply. All real work lives in
|
||||
controller.lib.reconciler; tests for the orchestration live in
|
||||
test_reconciler.py using FakeMountExecutor.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from controller.lib.disks import get_wrolpi_uid_gid
|
||||
from controller.lib.fstab_migration import migrate_etc_fstab
|
||||
from controller.lib.mount_executor import SubprocessMountExecutor
|
||||
from controller.lib.reconciler import Reconciler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s wrolpi-mounts: %(message)s",
|
||||
)
|
||||
|
||||
# Migration is idempotent (marker-gated). Doing it here means a freshly
|
||||
# upgraded WROLPi picks up legacy /etc/fstab entries on the first boot
|
||||
# of the new mount system, before we try to apply them.
|
||||
try:
|
||||
migrate_etc_fstab()
|
||||
except Exception as e: # noqa: BLE001 - never fail boot on migration error
|
||||
logger.error("fstab migration raised, continuing without it: %s", e)
|
||||
|
||||
try:
|
||||
wrolpi_uid, wrolpi_gid = get_wrolpi_uid_gid()
|
||||
except Exception as e: # noqa: BLE001 - best-effort enrichment
|
||||
logger.warning("Could not resolve wrolpi uid/gid (%s)", e)
|
||||
wrolpi_uid, wrolpi_gid = None, None
|
||||
|
||||
reconciler = Reconciler(
|
||||
executor=SubprocessMountExecutor(),
|
||||
wrolpi_uid=wrolpi_uid,
|
||||
wrolpi_gid=wrolpi_gid,
|
||||
)
|
||||
result = reconciler.apply()
|
||||
|
||||
logger.info(
|
||||
"Reconcile complete: %d mounted, %d unmounted, %d mount failures, %d unmount failures",
|
||||
len(result.mounted), len(result.unmounted),
|
||||
len(result.mount_failures), len(result.unmount_failures),
|
||||
)
|
||||
for mp, err in result.mount_failures:
|
||||
logger.error("Failed to mount %s: %s", mp, err)
|
||||
for mp, err in result.unmount_failures:
|
||||
logger.error("Failed to unmount %s: %s", mp, err)
|
||||
|
||||
# Always return 0: the service must not block boot if a single mount
|
||||
# is broken. Failures are logged and surfaced via the journal.
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -297,8 +297,9 @@ def commit_onboarding(
|
|||
mount_result = mount_drive(mount_device, mount_point, fstype=mount_fstype, options=mount_options)
|
||||
if mount_result.get("success"):
|
||||
mounted_mounts.append(mount_point)
|
||||
# Add fstab entry
|
||||
add_fstab_entry(mount_device, mount_point, mount_fstype, options=mount_options)
|
||||
# No /etc/fstab write — entry already lives in drives.mounts
|
||||
# (it's the source we just read), so wrolpi-mounts.service
|
||||
# will re-apply it on every subsequent boot.
|
||||
else:
|
||||
logger.warning(
|
||||
"Failed to mount secondary drive %s at %s: %s",
|
||||
|
|
|
|||
183
controller/lib/reconciler.py
Normal file
183
controller/lib/reconciler.py
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
"""
|
||||
Reconcile the live mount state under /media/ with fstab.yaml.
|
||||
|
||||
The Reconciler reads the desired mount table from fstab.yaml and asks an
|
||||
injected MountExecutor what is currently mounted. Then::
|
||||
|
||||
mount each entry in fstab.yaml that is missing from the live set
|
||||
unmount each previously-managed path that has been removed from fstab.yaml
|
||||
|
||||
"Previously-managed" is the load-bearing concept: we never unmount paths
|
||||
that WROLPi has never claimed. The set of managed mount points is
|
||||
persisted to ``managed_path`` (a small newline-separated file) so the
|
||||
reconciler can tell apart its own mounts from the user's manual ones
|
||||
across reboots. On Portable this file is on tmpfs (overlay upper layer)
|
||||
which is acceptable — each boot the reconciler starts from a clean managed
|
||||
set and re-discovers everything from fstab.yaml.
|
||||
|
||||
The reconciler never raises for I/O failures. Per-entry failures are
|
||||
collected into the ReconcileResult and reported, but the run continues so
|
||||
a single broken drive does not block the rest of the boot.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from controller.lib.fstab_yaml import DEFAULT_PATH as DEFAULT_FSTAB_PATH
|
||||
from controller.lib.fstab_yaml import FstabEntry, FstabFile, load as load_fstab
|
||||
from controller.lib.mount_executor import MountExecutor
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_MANAGED_PATH = Path("/run/wrolpi-mounts/managed")
|
||||
|
||||
# Mount points the reconciler will never touch, even if they appear in
|
||||
# fstab.yaml: the primary mount belongs to live-boot persistence (Portable)
|
||||
# or the host's installer (/etc/fstab on RPi/Debian), and the temp mount
|
||||
# belongs to the Controller's onboarding flow.
|
||||
RESERVED_MOUNT_POINTS = frozenset({
|
||||
"/media/wrolpi",
|
||||
"/media/wrolpi_temp_onboarding",
|
||||
})
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReconcileResult:
|
||||
"""Per-run summary suitable for logging or surfacing back to an API."""
|
||||
|
||||
mounted: list[str] = field(default_factory=list)
|
||||
unmounted: list[str] = field(default_factory=list)
|
||||
mount_failures: list[tuple[str, str]] = field(default_factory=list)
|
||||
unmount_failures: list[tuple[str, str]] = field(default_factory=list)
|
||||
skipped: list[tuple[str, str]] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def all_succeeded(self) -> bool:
|
||||
return not self.mount_failures and not self.unmount_failures
|
||||
|
||||
|
||||
class Reconciler:
|
||||
"""Apply fstab.yaml to the live mount state via an injected executor."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
executor: MountExecutor,
|
||||
fstab_path: Path = DEFAULT_FSTAB_PATH,
|
||||
managed_path: Path = DEFAULT_MANAGED_PATH,
|
||||
wrolpi_uid: Optional[int] = None,
|
||||
wrolpi_gid: Optional[int] = None,
|
||||
):
|
||||
self._executor = executor
|
||||
self._fstab_path = fstab_path
|
||||
self._managed_path = managed_path
|
||||
self._wrolpi_uid = wrolpi_uid
|
||||
self._wrolpi_gid = wrolpi_gid
|
||||
|
||||
# --- Public entry point ------------------------------------------
|
||||
|
||||
def apply(self) -> ReconcileResult:
|
||||
"""Reconcile once. Idempotent."""
|
||||
result = ReconcileResult()
|
||||
|
||||
desired = load_fstab(self._fstab_path)
|
||||
live = self._executor.current_mount_points()
|
||||
managed = self._read_managed()
|
||||
|
||||
# 1. Mount each entry in fstab.yaml that isn't already live.
|
||||
for entry in desired.mounts:
|
||||
skip = self._skip_reason(entry)
|
||||
if skip:
|
||||
result.skipped.append((entry.mount_point, skip))
|
||||
continue
|
||||
if entry.mount_point in live:
|
||||
# Already mounted — claim ownership so a later removal can
|
||||
# safely unmount it.
|
||||
managed.add(entry.mount_point)
|
||||
continue
|
||||
options = self._inject_uid_gid(entry)
|
||||
self._ensure_dir(entry.mount_point)
|
||||
r = self._executor.mount(
|
||||
entry.device, entry.mount_point, entry.fstype, options,
|
||||
)
|
||||
if r.ok:
|
||||
result.mounted.append(entry.mount_point)
|
||||
managed.add(entry.mount_point)
|
||||
else:
|
||||
result.mount_failures.append((entry.mount_point, r.error or "unknown"))
|
||||
|
||||
# 2. Unmount each previously-managed mount that is no longer in
|
||||
# fstab.yaml. We only consider paths in the managed set, which
|
||||
# protects user-mounted /media/* paths the reconciler never owned.
|
||||
desired_set = desired.mount_points()
|
||||
for mp in sorted(managed - desired_set):
|
||||
if mp in RESERVED_MOUNT_POINTS:
|
||||
continue
|
||||
if mp not in live:
|
||||
managed.discard(mp)
|
||||
continue
|
||||
r = self._executor.unmount(mp)
|
||||
if r.ok:
|
||||
result.unmounted.append(mp)
|
||||
managed.discard(mp)
|
||||
else:
|
||||
result.unmount_failures.append((mp, r.error or "unknown"))
|
||||
|
||||
self._write_managed(managed)
|
||||
return result
|
||||
|
||||
# --- Internals -----------------------------------------------------
|
||||
|
||||
def _skip_reason(self, entry: FstabEntry) -> Optional[str]:
|
||||
if not entry.device or not entry.mount_point:
|
||||
return "missing required field"
|
||||
if entry.mount_point in RESERVED_MOUNT_POINTS:
|
||||
return "reserved mount point"
|
||||
if not entry.mount_point.startswith("/media/"):
|
||||
return "mount point outside /media/"
|
||||
return None
|
||||
|
||||
def _inject_uid_gid(self, entry: FstabEntry) -> str:
|
||||
"""exfat/vfat have no POSIX permissions; without uid/gid the
|
||||
mounted directory belongs to root and the wrolpi user cannot write
|
||||
to it."""
|
||||
options = entry.options or "defaults"
|
||||
if entry.fstype not in ("exfat", "vfat"):
|
||||
return options
|
||||
if "uid=" in options or "gid=" in options:
|
||||
return options
|
||||
if self._wrolpi_uid is None or self._wrolpi_gid is None:
|
||||
return options
|
||||
return f"{options},uid={self._wrolpi_uid},gid={self._wrolpi_gid}"
|
||||
|
||||
def _ensure_dir(self, mount_point: str) -> None:
|
||||
try:
|
||||
Path(mount_point).mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e:
|
||||
logger.warning("Could not create %s: %s", mount_point, e)
|
||||
|
||||
def _read_managed(self) -> set[str]:
|
||||
if not self._managed_path.exists():
|
||||
return set()
|
||||
try:
|
||||
return {
|
||||
line.strip()
|
||||
for line in self._managed_path.read_text().splitlines()
|
||||
if line.strip()
|
||||
}
|
||||
except OSError as e:
|
||||
logger.warning("Could not read %s: %s", self._managed_path, e)
|
||||
return set()
|
||||
|
||||
def _write_managed(self, managed: set[str]) -> None:
|
||||
try:
|
||||
self._managed_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._managed_path.write_text(
|
||||
"\n".join(sorted(managed)) + ("\n" if managed else "")
|
||||
)
|
||||
except OSError as e:
|
||||
logger.warning("Could not write %s: %s", self._managed_path, e)
|
||||
Loading…
Add table
Add a link
Reference in a new issue