diff --git a/app/src/api/controller.js b/app/src/api/controller.js index 912d7902..4e32ee0b 100644 --- a/app/src/api/controller.js +++ b/app/src/api/controller.js @@ -180,10 +180,17 @@ export async function getMounts() { return controllerFetch('/disks/mounts'); } -export async function mountDisk(device, mountPoint, fstype = null, options = 'defaults', persist = false) { +export async function mountDisk(device, mountPoint, fstype = null, options = 'defaults', persist = false, forceShadowed = false) { return controllerFetch('/disks/mount', { method: 'POST', - body: JSON.stringify({device, mount_point: mountPoint, fstype, options, persist}), + body: JSON.stringify({ + device, + mount_point: mountPoint, + fstype, + options, + persist, + force_shadowed: forceShadowed, + }), }); } diff --git a/app/src/components/admin/ControllerPage.js b/app/src/components/admin/ControllerPage.js index 126132c6..b68711b0 100644 --- a/app/src/components/admin/ControllerPage.js +++ b/app/src/components/admin/ControllerPage.js @@ -651,10 +651,23 @@ const formatSize = (size) => { }; +function formatBytes(bytes) { + if (!bytes || bytes < 1) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let i = 0; + let n = bytes; + while (n >= 1024 && i < units.length - 1) { + n /= 1024; + i++; + } + return `${n.toFixed(n >= 10 ? 0 : 1)} ${units[i]}`; +} + function MountModal({disk, open, onClose, onMount}) { const [mountPoint, setMountPoint] = React.useState(''); const [persist, setPersist] = React.useState(false); const [loading, setLoading] = React.useState(false); + const [shadowed, setShadowed] = React.useState(null); // Set default mount point when disk changes React.useEffect(() => { @@ -662,23 +675,21 @@ function MountModal({disk, open, onClose, onMount}) { const defaultMount = disk.label ? `/media/${disk.label}` : `/media/${disk.name}`; setMountPoint(defaultMount); setPersist(false); + setShadowed(null); } }, [disk]); - const handleMount = async () => { - if (!mountPoint.trim()) { - toast({ - type: 'error', - title: 'Mount point required', - description: 'Please enter a mount point.', - time: 3000, - }); - return; - } - + const performMount = async (forceShadowed) => { setLoading(true); try { - await mountDisk(disk.path, mountPoint.trim(), disk.fstype, 'defaults', persist); + const result = await mountDisk(disk.path, mountPoint.trim(), disk.fstype, 'defaults', persist, forceShadowed); + + // Soft-block: target contains data that would be hidden by the mount. + if (result && result.success === false && result.needs_force === 'shadowed') { + setShadowed(result.shadowed_data || {entries: [], size_bytes: 0}); + return; + } + toast({ type: 'success', title: 'Disk Mounted', @@ -699,8 +710,63 @@ function MountModal({disk, open, onClose, onMount}) { } }; + const handleMount = async () => { + if (!mountPoint.trim()) { + toast({ + type: 'error', + title: 'Mount point required', + description: 'Please enter a mount point.', + time: 3000, + }); + return; + } + await performMount(false); + }; + + const handleForceMount = () => performMount(true); + + const handleCancel = () => { + setShadowed(null); + onClose(); + }; + if (!disk) return null; + if (shadowed) { + const entries = (shadowed.entries || []).join(', ') || '(unknown)'; + return ( + + + + Existing Files Detected + + +

+ Mounting {disk.name} at {mountPoint} would + hide existing files that are already there. +

+

+ Found {entries} ({formatBytes(shadowed.size_bytes)}) at the mount target. +

+

+ Those files will continue to consume space on the underlying filesystem + (typically the SD card on a Raspberry Pi) and can fill it up. +

+

+ Recommended: cancel, move or delete the existing files, then mount. +

+
+ + + + +
+ ); + } + return ( diff --git a/controller/api/disks.py b/controller/api/disks.py index cacd820e..d061fa89 100644 --- a/controller/api/disks.py +++ b/controller/api/disks.py @@ -14,6 +14,7 @@ from controller.lib.config import ( update_config, ) from controller.lib.disks import ( + check_shadowed_data, get_block_devices, get_mounts, mount_drive, @@ -39,6 +40,10 @@ class MountRequest(BaseModel): fstype: Optional[str] = Field(default=None, description="Filesystem type (auto-detected if not specified)") options: str = Field(default="defaults", description="Mount options") persist: bool = Field(default=False, description="Add to fstab for persistent mounting") + force_shadowed: bool = Field( + default=False, + description="Proceed even if existing data at the mount target would be hidden by the new mount", + ) class UnmountRequest(BaseModel): @@ -98,6 +103,24 @@ async def disk_mount(request: MountRequest): """Mount a partition.""" _check_native_mode() + # Soft-block if the mount target already contains user data that would + # be hidden by the new mount. The UI re-submits with force_shadowed=True + # to override. + if not request.force_shadowed: + shadowed = check_shadowed_data(request.mount_point) + if shadowed: + return { + "success": False, + "needs_force": "shadowed", + "shadowed_data": shadowed, + "error": ( + f"{request.mount_point} contains {len(shadowed['entries'])} " + f"existing data " + f"{'entry' if len(shadowed['entries']) == 1 else 'entries'}. " + f"Mounting now would hide them on the underlying filesystem." + ), + } + result = mount_drive( device=request.device, mount_point=request.mount_point, diff --git a/controller/api/onboarding.py b/controller/api/onboarding.py index 93caa11c..1e28bf0a 100644 --- a/controller/api/onboarding.py +++ b/controller/api/onboarding.py @@ -12,6 +12,7 @@ from controller.api.schemas import ( OnboardingCommitResponse, OnboardingProbeRequest, OnboardingProbeResponse, + ShadowedDataInfo, ) from controller.lib.config import is_docker_mode, is_primary_drive_mounted from controller.lib.onboarding import ( @@ -78,9 +79,23 @@ async def commit(request: OnboardingCommitRequest): result = commit_onboarding( device_path=request.device_path, fstype=request.fstype, - force=request.force, + force_shadowed=request.force_shadowed, ) + # Soft-block: existing data at the mount target would be hidden. Return + # a structured response (200 OK with success=False) so the UI can prompt + # the user to override. + if not result.get("success") and result.get("needs_force") == "shadowed": + shadowed = result.get("shadowed_data") or {} + return OnboardingCommitResponse( + success=False, + error=result.get("error"), + mounts=[], + repair_started=False, + needs_force="shadowed", + shadowed_data=ShadowedDataInfo(**shadowed) if shadowed else None, + ) + if not result.get("success"): raise HTTPException(status_code=500, detail=result.get("error", "Onboarding failed")) diff --git a/controller/api/schemas.py b/controller/api/schemas.py index 7d500258..eaf0b312 100644 --- a/controller/api/schemas.py +++ b/controller/api/schemas.py @@ -467,7 +467,17 @@ class OnboardingCommitRequest(BaseModel): device_path: str = Field(description="Device path to use as primary drive") fstype: str = Field(description="Filesystem type") - force: bool = Field(default=False, description="Proceed even if no config found on drive") + force_shadowed: bool = Field( + default=False, + description="Proceed even if existing data at the mount target would be hidden by the new mount", + ) + + +class ShadowedDataInfo(BaseModel): + """Information about data that would be hidden by a mount.""" + + size_bytes: int = Field(description="Total size of data that would be shadowed") + entries: list[str] = Field(description="Top-level entries that would be hidden") class OnboardingCommitResponse(BaseModel): @@ -477,3 +487,12 @@ class OnboardingCommitResponse(BaseModel): error: Optional[str] = Field(default=None, description="Error message if failed") mounts: list[str] = Field(default_factory=list, description="Mount points that were mounted") repair_started: bool = Field(default=False, description="Whether repair script was started") + needs_force: Optional[str] = Field( + default=None, + description="If set, the request was soft-blocked. Re-submit with the matching force flag. " + "Currently: 'shadowed'.", + ) + shadowed_data: Optional[ShadowedDataInfo] = Field( + default=None, + description="Populated when needs_force='shadowed'.", + ) diff --git a/controller/lib/disks.py b/controller/lib/disks.py index 9762d9f2..ef8448ca 100644 --- a/controller/lib/disks.py +++ b/controller/lib/disks.py @@ -254,6 +254,49 @@ def is_mount_busy(mount_point: str) -> bool: return False +def check_shadowed_data(target: str) -> Optional[dict]: + """Look for user data at `target` that would be hidden by a mount over it. + + Returns a dict with `size_bytes` and `entries` when non-config content is + present, or None when the target is empty (or contains only `config/`). + + `config/` is whitelisted because it is created transiently by + `generate_certificates.sh` before the primary drive is mounted; that is + expected, not user data. + + Returns None for non-existent targets. + """ + target_path = Path(target) + if not target_path.exists() or not target_path.is_dir(): + return None + + try: + entries = [e.name for e in target_path.iterdir() if e.name != "config"] + except OSError: + return None + if not entries: + return None + + size_bytes = 0 + for entry in entries: + entry_path = target_path / entry + try: + if entry_path.is_dir(): + for path in entry_path.rglob("*"): + try: + if path.is_file() and not path.is_symlink(): + size_bytes += path.stat().st_size + except OSError: + # File disappeared mid-walk or unreadable; skip. + continue + elif entry_path.is_file() and not entry_path.is_symlink(): + size_bytes += entry_path.stat().st_size + except OSError: + continue + + return {"size_bytes": size_bytes, "entries": sorted(entries)} + + def get_mounts() -> list[dict]: """ Get current mounts under /media. diff --git a/controller/lib/onboarding.py b/controller/lib/onboarding.py index c990ef3c..e102d517 100644 --- a/controller/lib/onboarding.py +++ b/controller/lib/onboarding.py @@ -21,7 +21,7 @@ from controller.lib.config import ( save_config, update_config, ) -from controller.lib.disks import get_block_devices, mount_drive, unmount_drive +from controller.lib.disks import check_shadowed_data, get_block_devices, mount_drive, unmount_drive from controller.lib.fstab import add_fstab_entry from controller.lib.scripts import start_script @@ -165,25 +165,32 @@ def cancel_probe() -> dict: return {"success": True} -def commit_onboarding(device_path: str, fstype: str, force: bool = False) -> dict: +def commit_onboarding( + device_path: str, + fstype: str, + force_shadowed: bool = False, +) -> dict: """ Execute the full onboarding setup. 1. Unmount temp mount - 2. Mount primary drive at /media/wrolpi - 3. Add fstab entry for primary - 4. Reload config - 5. Mount secondary drives per config - 6. Add fstab entries for secondary drives - 7. Start repair + 2. Check for shadowed data at the mount target + 3. Mount primary drive at /media/wrolpi + 4. Add fstab entry for primary + 5. Reload config + 6. Mount secondary drives per config + 7. Add fstab entries for secondary drives + 8. Start repair Args: device_path: Device path fstype: Filesystem type - force: If True, proceed even without config on drive + force_shadowed: If True, proceed even when existing data at the + mount target would be hidden by the new mount Returns: - dict with success, error, mounts, repair_started + dict with success, error, mounts, repair_started, and on a shadowed + block, `needs_force` and `shadowed_data` """ media_dir = str(get_media_directory()) mounted_mounts = [] @@ -201,6 +208,26 @@ def commit_onboarding(device_path: str, fstype: str, force: bool = False) -> dic shutil.rmtree(transient_config) logger.info("Removed transient config directory at %s", transient_config) + # Step 1c: Check for shadowed data. If the user has been downloading + # to /media/wrolpi without a drive mounted, mounting now would hide + # those files on the SD card / root filesystem. + if not force_shadowed: + shadowed = check_shadowed_data(media_dir) + if shadowed: + return { + "success": False, + "needs_force": "shadowed", + "shadowed_data": shadowed, + "error": ( + f"{media_dir} contains {len(shadowed['entries'])} " + f"existing data " + f"{'entry' if len(shadowed['entries']) == 1 else 'entries'}. " + f"Mounting now would hide them on the underlying filesystem." + ), + "mounts": [], + "repair_started": False, + } + # Step 2: Mount primary drive result = mount_drive(device_path, media_dir, fstype=fstype) if not result.get("success"): diff --git a/controller/templates/index.html b/controller/templates/index.html index 0308c52e..53073664 100644 --- a/controller/templates/index.html +++ b/controller/templates/index.html @@ -841,7 +841,7 @@ - + + + +