v0.11.0 — Phase C: Storage Init Wizard, Data Migration & Startup Fix

- Startup ping: fire heartbeat + health + hub report immediately on boot
  (5s delay after scheduler start, instead of waiting 5-15 min for first tick)

- Storage init wizard: new internal/storage/ package with disk scanning
  (lsblk -J), format+mount pipeline (sfdisk → mkfs.ext4 → blkid → fstab →
  mount → chown), safety guards (system disk detection, confirmation "FORMÁZÁS"),
  progress channel, auto-register in settings.json

- Data migration: MigrateAppData() with rsync --info=progress2 progress parsing,
  stop/rsync/update-config/start flow, rollback on failure, old data preserved

- New pages: /settings/storage/init (wizard), /stacks/{name}/migrate (migration)
- New API routes: /api/storage/{scan,init,init/status,migrate,migrate/status}
- Deploy page: storage info section for deployed apps (path, size, free, migrate link)
- Settings page: "Mozgatás" button per app in storage path details
- Container: privileged: true, /dev:/dev, /etc/fstab:/host-fstab, /run/udev:/run/udev:ro
- Dockerfile: add util-linux, e2fsprogs, rsync, parted for disk ops

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-17 10:27:18 +01:00
parent e7c27364bf
commit 2fb2c6e1ae
23 changed files with 2236 additions and 6 deletions
+50
View File
@@ -0,0 +1,50 @@
package storage
import (
"bufio"
"fmt"
"strings"
)
// FormatRequest holds parameters for formatting and mounting a disk.
type FormatRequest struct {
DevicePath string // "/dev/sdb" or "/dev/sdb1"
MountName string // "hdd_1" → mounts at /mnt/hdd_1
Label string // Display label for the UI
CreatePartition bool // If true, create a single partition first (wipes disk)
SetDefault bool // Register as default storage path
}
// FormatProgress tracks the formatting/mounting progress.
type FormatProgress struct {
Step string // "validating","partitioning","formatting","mounting","permissions","done","error"
Message string // Human-readable status
Error string // Non-empty if Step == "error"
Percent int // 0100
}
// parseRsyncProgress parses a single line of rsync --info=progress2 output.
// Returns (bytesCopied, percent, ok).
func parseRsyncProgress(line string) (int64, int, bool) {
// Format: " 45,678,901 49% 12.34MB/s 0:00:30"
scanner := bufio.NewScanner(strings.NewReader(line))
scanner.Split(bufio.ScanWords)
var tokens []string
for scanner.Scan() {
tokens = append(tokens, scanner.Text())
}
if len(tokens) < 2 {
return 0, 0, false
}
bytesStr := strings.ReplaceAll(tokens[0], ",", "")
var bytesCopied int64
if _, err := fmt.Sscanf(bytesStr, "%d", &bytesCopied); err != nil {
return 0, 0, false
}
pctStr := strings.TrimSuffix(tokens[1], "%")
var pct int
if _, err := fmt.Sscanf(pctStr, "%d", &pct); err != nil {
return 0, 0, false
}
return bytesCopied, pct, true
}
+181
View File
@@ -0,0 +1,181 @@
//go:build linux
package storage
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// FormatAndMount formats a disk/partition and mounts it.
// Progress updates are sent on the progress channel.
// Returns the final mount path on success.
func FormatAndMount(req FormatRequest, progress chan<- FormatProgress) (string, error) {
send := func(step, msg string, pct int) {
progress <- FormatProgress{Step: step, Message: msg, Percent: pct}
}
fail := func(step, msg string, err error) error {
errStr := ""
if err != nil {
errStr = err.Error()
}
progress <- FormatProgress{Step: "error", Message: msg, Error: errStr, Percent: 0}
return fmt.Errorf("%s: %w", msg, err)
}
mountPath := "/mnt/" + req.MountName
// --- Step 1: Validate ---
send("validating", "Eszköz ellenőrzése...", 5)
if err := ValidateMountName(req.MountName); err != nil {
return "", fail("validating", "Érvénytelen csatlakoztatási név", err)
}
if _, err := os.Stat(req.DevicePath); err != nil {
return "", fail("validating", "Az eszköz nem létezik: "+req.DevicePath, err)
}
isSystem, err := IsSystemDisk(req.DevicePath)
if err != nil {
return "", fail("validating", "Rendszermeghajtó ellenőrzése sikertelen", err)
}
if isSystem {
return "", fail("validating", "Ez a rendszermeghajtó — nem formázható!", fmt.Errorf("device is system disk"))
}
mounted, err := IsDeviceMounted(req.DevicePath)
if err != nil {
return "", fail("validating", "Csatlakoztatási állapot ellenőrzése sikertelen", err)
}
if mounted {
return "", fail("validating", "Az eszköz már csatlakoztatva van", fmt.Errorf("device already mounted"))
}
inUse, err := IsMountPathInUse(mountPath)
if err != nil {
return "", fail("validating", "Csatlakoztatási útvonal ellenőrzése sikertelen", err)
}
if inUse {
return "", fail("validating", "A csatlakoztatási útvonal már használatban van: "+mountPath, fmt.Errorf("mount path in use"))
}
send("validating", "Ellenőrzés kész", 10)
// --- Step 2: Partition (if requested) ---
partDev := req.DevicePath
if req.CreatePartition {
send("partitioning", "Partíció létrehozása...", 15)
sfdiskInput := "label: gpt\n,,,L\n"
cmd := exec.Command("sfdisk", req.DevicePath)
cmd.Stdin = strings.NewReader(sfdiskInput)
if out, err := cmd.CombinedOutput(); err != nil {
return "", fail("partitioning", "Partícionálás sikertelen: "+string(out), err)
}
_ = exec.Command("partprobe", req.DevicePath).Run()
time.Sleep(2 * time.Second)
partDev = req.DevicePath + "1"
if strings.Contains(req.DevicePath, "nvme") {
partDev = req.DevicePath + "p1"
}
if _, err := os.Stat(partDev); err != nil {
return "", fail("partitioning", "Partíció nem található a létrehozás után: "+partDev, err)
}
send("partitioning", "Partíció létrehozva: "+partDev, 25)
}
// --- Step 3: Format ---
send("formatting", "Fájlrendszer formázása (ext4)...", 30)
label := req.Label
if label == "" {
label = req.MountName
}
if len(label) > 16 {
label = label[:16]
}
mkfsCmd := exec.Command("mkfs.ext4", "-L", label, "-F", partDev)
var mkfsOut bytes.Buffer
mkfsCmd.Stdout = &mkfsOut
mkfsCmd.Stderr = &mkfsOut
if err := mkfsCmd.Run(); err != nil {
return "", fail("formatting", "Formázás sikertelen: "+mkfsOut.String(), err)
}
send("formatting", "Formázás kész", 60)
// --- Step 4: Mount ---
send("mounting", "Csatlakoztatás: "+mountPath+"...", 65)
if err := os.MkdirAll(mountPath, 0755); err != nil {
return "", fail("mounting", "Csatlakoztatási mappa nem hozható létre: "+mountPath, err)
}
uuidOut, err := exec.Command("blkid", "-s", "UUID", "-o", "value", partDev).Output()
if err != nil {
return "", fail("mounting", "UUID lekérése sikertelen", err)
}
uuid := strings.TrimSpace(string(uuidOut))
if uuid == "" {
return "", fail("mounting", "UUID üres a formázás után", fmt.Errorf("empty UUID"))
}
// Backup fstab (non-fatal)
_ = BackupFstab(FstabPath)
if err := AppendFstabEntry(FstabPath, uuid, mountPath, "ext4", "defaults,nofail,noatime"); err != nil {
return "", fail("mounting", "fstab bejegyzés hozzáadása sikertelen", err)
}
if out, err := exec.Command("mount", mountPath).CombinedOutput(); err != nil {
return "", fail("mounting", "Csatlakoztatás sikertelen: "+string(out), err)
}
send("mounting", "Csatlakoztatva: "+mountPath, 80)
// --- Step 5: Permissions + subdirs ---
send("permissions", "Mappák létrehozása és jogosultságok beállítása...", 85)
_ = exec.Command("chown", "1000:1000", mountPath).Run()
for _, subdir := range []string{"storage", "Dokumentumok"} {
dir := filepath.Join(mountPath, subdir)
if err := os.MkdirAll(dir, 0755); err == nil {
_ = exec.Command("chown", "1000:1000", dir).Run()
}
}
send("done", "Meghajtó sikeresen inicializálva: "+mountPath, 100)
return mountPath, nil
}
// GetDeviceUUID returns the UUID of a block device/partition.
func GetDeviceUUID(devicePath string) (string, error) {
out, err := exec.Command("blkid", "-s", "UUID", "-o", "value", devicePath).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// ReadFstab reads the current fstab content.
func ReadFstab() (string, error) {
data, err := os.ReadFile(FstabPath)
if err != nil {
data, err = os.ReadFile("/etc/fstab")
if err != nil {
return "", err
}
}
return string(data), nil
}
@@ -0,0 +1,20 @@
//go:build !linux
package storage
import "fmt"
// FormatAndMount is not supported on non-Linux platforms.
func FormatAndMount(req FormatRequest, progress chan<- FormatProgress) (string, error) {
return "", fmt.Errorf("storage init is only supported on Linux")
}
// GetDeviceUUID is not supported on non-Linux platforms.
func GetDeviceUUID(devicePath string) (string, error) {
return "", fmt.Errorf("storage init is only supported on Linux")
}
// ReadFstab is not supported on non-Linux platforms.
func ReadFstab() (string, error) {
return "", fmt.Errorf("storage init is only supported on Linux")
}
+298
View File
@@ -0,0 +1,298 @@
package storage
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
)
// MigrateRequest holds parameters for migrating app data.
type MigrateRequest struct {
StackName string // e.g., "immich"
DisplayName string // e.g., "Immich"
CurrentHDDPath string // e.g., "/mnt/hdd_placeholder"
TargetPath string // e.g., "/mnt/hdd_1"
HDDMounts []string // host-side paths to rsync (e.g., ["/mnt/hdd_placeholder/storage/immich"])
}
// MigrateProgress tracks migration state.
type MigrateProgress struct {
Step string // "stopping","copying","updating","starting","done","error","rolling_back"
Message string
BytesCopied int64
BytesTotal int64
Percent int
Error string
ElapsedSeconds int
}
// StopFunc stops an app's containers. Returns error if stop fails.
type StopFunc func(stackName string) error
// StartFunc starts an app's containers. Returns error if start fails.
type StartFunc func(stackName string) error
// UpdateHDDPathFunc updates the HDD_PATH in app.yaml. Returns error on failure.
type UpdateHDDPathFunc func(stackName, newPath string) error
// MigrateAppData moves app data from current to target storage path.
// stopFn and startFn are called to stop/start the app containers.
// updateFn is called to update the app's HDD_PATH configuration.
func MigrateAppData(
req MigrateRequest,
stopFn StopFunc,
startFn StartFunc,
updateFn UpdateHDDPathFunc,
progress chan<- MigrateProgress,
) error {
start := time.Now()
send := func(step, msg string, pct int, bytesCopied, bytesTotal int64) {
progress <- MigrateProgress{
Step: step,
Message: msg,
Percent: pct,
BytesCopied: bytesCopied,
BytesTotal: bytesTotal,
ElapsedSeconds: int(time.Since(start).Seconds()),
}
}
fail := func(step, msg string, err error) error {
errStr := ""
if err != nil {
errStr = err.Error()
}
progress <- MigrateProgress{
Step: "error",
Message: msg,
Error: errStr,
ElapsedSeconds: int(time.Since(start).Seconds()),
}
return fmt.Errorf("%s: %w", msg, err)
}
// --- Step 1: Validate ---
if req.CurrentHDDPath == "" {
return fail("validating", "A jelenlegi tárhely nem megadott", fmt.Errorf("empty current HDD path"))
}
if req.TargetPath == "" {
return fail("validating", "A cél tárhely nem megadott", fmt.Errorf("empty target path"))
}
if req.CurrentHDDPath == req.TargetPath {
return fail("validating", "A forrás és a cél tárhely azonos", fmt.Errorf("source equals target"))
}
if _, err := os.Stat(req.TargetPath); err != nil {
return fail("validating", "A cél tárhely nem létezik: "+req.TargetPath, err)
}
if len(req.HDDMounts) == 0 {
return fail("validating", "Nincsenek HDD csatlakozások az alkalmazáshoz", fmt.Errorf("no HDD mounts"))
}
// Estimate total size
var totalBytes int64
for _, m := range req.HDDMounts {
if info, err := os.Stat(m); err == nil && info.IsDir() {
totalBytes += dirSize(m)
}
}
// Check free space on target
freeBytes := getFreeBytes(req.TargetPath)
if freeBytes > 0 && totalBytes > 0 && int64(float64(totalBytes)*1.05) > freeBytes {
return fail("validating", fmt.Sprintf(
"Nincs elég szabad hely a céltárolón: szükséges ~%s, szabad %s",
bytesHuman(totalBytes), bytesHuman(freeBytes),
), fmt.Errorf("insufficient disk space"))
}
send("stopping", "Alkalmazás leállítása...", 5, 0, totalBytes)
// --- Step 2: Stop app ---
if err := stopFn(req.StackName); err != nil {
return fail("stopping", "Alkalmazás leállítása sikertelen", err)
}
send("stopping", "Alkalmazás leállítva", 10, 0, totalBytes)
// --- Step 3: rsync ---
var bytesCopied int64
for i, srcPath := range req.HDDMounts {
// Determine destination path: replace CurrentHDDPath prefix with TargetPath
if !strings.HasPrefix(srcPath, req.CurrentHDDPath) {
continue
}
relPath := strings.TrimPrefix(srcPath, req.CurrentHDDPath)
dstPath := filepath.Join(req.TargetPath, relPath)
// Ensure destination parent exists
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
// Rollback
send("rolling_back", "Hiba: mappa létrehozása sikertelen, visszagörgetés...", 0, bytesCopied, totalBytes)
_ = startFn(req.StackName)
return fail("copying", "Cél mappa létrehozása sikertelen: "+filepath.Dir(dstPath), err)
}
mountPct := 10 + (i * 60 / len(req.HDDMounts))
send("copying", fmt.Sprintf("Adatok másolása (%d/%d): %s...", i+1, len(req.HDDMounts), filepath.Base(srcPath)),
mountPct, bytesCopied, totalBytes)
var rsyncErr error
bytesCopied, rsyncErr = runRsync(srcPath, dstPath, totalBytes, bytesCopied, mountPct, progress, start)
if rsyncErr != nil {
// Rollback
send("rolling_back", "rsync sikertelen, alkalmazás visszaállítása az eredeti tárolóra...", 0, bytesCopied, totalBytes)
_ = startFn(req.StackName)
return fail("copying", "Adatmásolás sikertelen", rsyncErr)
}
}
send("updating", "Konfiguráció frissítése...", 75, bytesCopied, totalBytes)
// --- Step 4: Update app.yaml HDD_PATH ---
if err := updateFn(req.StackName, req.TargetPath); err != nil {
send("rolling_back", "Konfiguráció frissítése sikertelen, visszaállítás...", 0, bytesCopied, totalBytes)
_ = startFn(req.StackName)
return fail("updating", "HDD_PATH frissítése sikertelen", err)
}
send("starting", "Alkalmazás indítása az új tárolóról...", 85, bytesCopied, totalBytes)
// --- Step 5: Start app ---
if err := startFn(req.StackName); err != nil {
// Revert config and restart with old path
_ = updateFn(req.StackName, req.CurrentHDDPath)
_ = startFn(req.StackName)
return fail("starting", "Alkalmazás indítása sikertelen az új tárolóról", err)
}
elapsed := int(time.Since(start).Seconds())
send("done",
fmt.Sprintf("Áthelyezés kész! Az alkalmazás az új tárolóról fut. (Régi adat: %s)", req.CurrentHDDPath),
100, bytesCopied, totalBytes)
_ = elapsed
return nil
}
// runRsync runs rsync from srcPath to dstPath and reports progress.
func runRsync(srcPath, dstPath string, totalBytes, prevCopied int64, basePct int, progress chan<- MigrateProgress, start time.Time) (int64, error) {
// Ensure src ends with / for rsync to sync contents (not the directory itself)
if !strings.HasSuffix(srcPath, "/") {
srcPath += "/"
}
cmd := exec.Command(
"rsync", "-a", "--info=progress2", "--human-readable",
srcPath, dstPath,
)
stdout, err := cmd.StdoutPipe()
if err != nil {
return prevCopied, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return prevCopied, err
}
if err := cmd.Start(); err != nil {
return prevCopied, fmt.Errorf("rsync start failed: %w", err)
}
var bytesCopied int64 = prevCopied
var mu sync.Mutex
// Parse stdout progress
go func() {
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
line := scanner.Text()
if b, pct, ok := parseRsyncProgress(line); ok {
mu.Lock()
bytesCopied = prevCopied + b
// Scale pct into our range
scaledPct := basePct + pct*40/100
if scaledPct > 99 {
scaledPct = 99
}
mu.Unlock()
progress <- MigrateProgress{
Step: "copying",
Message: fmt.Sprintf("Adatok másolása... %s / %s", bytesHuman(b), bytesHuman(totalBytes)),
Percent: scaledPct,
BytesCopied: bytesCopied,
BytesTotal: totalBytes,
ElapsedSeconds: int(time.Since(start).Seconds()),
}
}
}
}()
var stderrBuf strings.Builder
io.Copy(&stderrBuf, stderr)
if err := cmd.Wait(); err != nil {
return bytesCopied, fmt.Errorf("rsync failed: %w — %s", err, stderrBuf.String())
}
mu.Lock()
finalCopied := bytesCopied
mu.Unlock()
return finalCopied, nil
}
// dirSize returns the total bytes in a directory (best-effort).
func dirSize(path string) int64 {
var total int64
filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
total += info.Size()
return nil
})
return total
}
// getFreeBytes returns available bytes on the filesystem at path.
func getFreeBytes(path string) int64 {
// Use df to get available bytes — works cross-platform within Linux container
out, err := exec.Command("df", "-B1", "--output=avail", path).Output()
if err != nil {
return 0
}
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
if len(lines) < 2 {
return 0
}
var avail int64
fmt.Sscanf(strings.TrimSpace(lines[1]), "%d", &avail)
return avail
}
// bytesHuman converts a byte count to human-readable string.
func bytesHuman(b int64) string {
const (
KB = 1024
MB = KB * 1024
GB = MB * 1024
)
switch {
case b >= GB:
return fmt.Sprintf("%.1f GB", float64(b)/float64(GB))
case b >= MB:
return fmt.Sprintf("%.0f MB", float64(b)/float64(MB))
case b >= KB:
return fmt.Sprintf("%.0f KB", float64(b)/float64(KB))
default:
return fmt.Sprintf("%d B", b)
}
}
+27
View File
@@ -0,0 +1,27 @@
package storage
import (
"fmt"
"regexp"
)
// mountNameRe validates mount names: only alphanumeric + underscore.
var mountNameRe = regexp.MustCompile(`^[a-zA-Z0-9_]+$`)
// FstabPath is the path to the host fstab inside the container.
// The compose file mounts /etc/fstab → /host-fstab.
const FstabPath = "/host-fstab"
// ValidateMountName returns an error if the mount name is invalid.
func ValidateMountName(name string) error {
if name == "" {
return fmt.Errorf("a csatlakoztatási névnek nem szabad üresnek lennie")
}
if !mountNameRe.MatchString(name) {
return fmt.Errorf("a csatlakoztatási néven csak betűk, számok és alávonás megengedett")
}
if len(name) > 32 {
return fmt.Errorf("a csatlakoztatási néven legfeljebb 32 karakter megengedett")
}
return nil
}
+102
View File
@@ -0,0 +1,102 @@
//go:build linux
package storage
import (
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
)
// IsSystemDisk checks if the given device path overlaps with the root filesystem device.
// Returns true if the device is (or is the parent of) the system disk.
func IsSystemDisk(devicePath string) (bool, error) {
// Get the block device major number of the root filesystem
var rootStat syscall.Stat_t
if err := syscall.Stat("/", &rootStat); err != nil {
return false, fmt.Errorf("cannot stat /: %w", err)
}
// Get block device info of the target device
var devStat syscall.Stat_t
if err := syscall.Stat(devicePath, &devStat); err != nil {
return false, fmt.Errorf("cannot stat %s: %w", devicePath, err)
}
// Compare major device numbers
rootMajor := rootStat.Dev >> 8 & 0xff
devMajor := devStat.Rdev >> 8 & 0xff
if rootMajor == devMajor {
return true, nil
}
return false, nil
}
// IsDeviceMounted checks if a device or any of its partitions is currently mounted.
func IsDeviceMounted(devicePath string) (bool, error) {
data, err := os.ReadFile("/proc/mounts")
if err != nil {
return false, fmt.Errorf("cannot read /proc/mounts: %w", err)
}
base := filepath.Base(devicePath)
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
dev := fields[0]
devBase := filepath.Base(dev)
if devBase == base || strings.HasPrefix(devBase, base) {
return true, nil
}
}
return false, nil
}
// IsMountPathInUse checks if a path is already used as a mount point.
func IsMountPathInUse(mountPath string) (bool, error) {
data, err := os.ReadFile("/proc/mounts")
if err != nil {
return false, fmt.Errorf("cannot read /proc/mounts: %w", err)
}
mountPath = filepath.Clean(mountPath)
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
if filepath.Clean(fields[1]) == mountPath {
return true, nil
}
}
return false, nil
}
// BackupFstab creates a dated backup of the fstab file.
func BackupFstab(fstabPath string) error {
data, err := os.ReadFile(fstabPath)
if err != nil {
return fmt.Errorf("cannot read %s: %w", fstabPath, err)
}
backupPath := fstabPath + ".bak." + time.Now().Format("20060102")
return os.WriteFile(backupPath, data, 0644)
}
// AppendFstabEntry appends a UUID-based fstab entry.
func AppendFstabEntry(fstabPath, uuid, mountPoint, fsType, options string) error {
entry := fmt.Sprintf("\nUUID=%s\t%s\t%s\t%s\t0 2\n", uuid, mountPoint, fsType, options)
f, err := os.OpenFile(fstabPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("cannot open fstab for writing: %w", err)
}
defer f.Close()
if _, err := f.WriteString(entry); err != nil {
return fmt.Errorf("cannot write fstab entry: %w", err)
}
return nil
}
@@ -0,0 +1,25 @@
//go:build !linux
package storage
import "fmt"
func IsSystemDisk(devicePath string) (bool, error) {
return false, fmt.Errorf("storage init is only supported on Linux")
}
func IsDeviceMounted(devicePath string) (bool, error) {
return false, fmt.Errorf("storage init is only supported on Linux")
}
func IsMountPathInUse(mountPath string) (bool, error) {
return false, fmt.Errorf("storage init is only supported on Linux")
}
func BackupFstab(fstabPath string) error {
return fmt.Errorf("storage init is only supported on Linux")
}
func AppendFstabEntry(fstabPath, uuid, mountPoint, fsType, options string) error {
return fmt.Errorf("storage init is only supported on Linux")
}
+32
View File
@@ -0,0 +1,32 @@
package storage
// BlockDevice represents a detected physical disk.
type BlockDevice struct {
Name string // "sdb"
Path string // "/dev/sdb"
Size string // "931.5G"
SizeBytes int64 // raw bytes from lsblk
Model string // "WD Elements 25A2"
Type string // "disk"
Removable bool // true for USB
Partitions []Partition // child partitions
Mounted bool // any partition is mounted
}
// Partition represents a partition on a block device.
type Partition struct {
Name string // "sdb1"
Path string // "/dev/sdb1"
Size string // "931.5G"
SizeBytes int64
FSType string // "ext4", "" for no filesystem
Label string // filesystem label
UUID string
MountPoint string // "" if not mounted
}
// ScanResult from disk detection.
type ScanResult struct {
AvailableDisks []BlockDevice // Unmounted, non-system disks
SystemDisks []BlockDevice // System/mounted disks (display only)
}
+168
View File
@@ -0,0 +1,168 @@
//go:build linux
package storage
import (
"encoding/json"
"fmt"
"os/exec"
"strings"
)
// lsblkOutput matches the top-level JSON from lsblk -J.
type lsblkOutput struct {
BlockDevices []lsblkDevice `json:"blockdevices"`
}
// lsblkDevice is the raw JSON structure from lsblk.
type lsblkDevice struct {
Name string `json:"name"`
Path string `json:"path"`
Size interface{} `json:"size"` // may be float64 or string
Type string `json:"type"`
FSType *string `json:"fstype"`
MountPoint *string `json:"mountpoint"`
Model *string `json:"model"`
RM interface{} `json:"rm"` // removable: bool or "0"/"1"
Children []lsblkDevice `json:"children"`
}
func (d *lsblkDevice) sizeBytes() int64 {
switch v := d.Size.(type) {
case float64:
return int64(v)
}
return 0
}
func (d *lsblkDevice) sizeHuman() string {
bytes := d.sizeBytes()
const (
GB = 1024 * 1024 * 1024
TB = GB * 1024
)
switch {
case bytes >= TB:
return fmt.Sprintf("%.1f TB", float64(bytes)/float64(TB))
case bytes >= GB:
return fmt.Sprintf("%.1f GB", float64(bytes)/float64(GB))
default:
return fmt.Sprintf("%d MB", bytes/(1024*1024))
}
}
func (d *lsblkDevice) isRemovable() bool {
switch v := d.RM.(type) {
case bool:
return v
case float64:
return v != 0
case string:
return v == "1" || strings.EqualFold(v, "true")
}
return false
}
func (d *lsblkDevice) fsType() string {
if d.FSType != nil {
return *d.FSType
}
return ""
}
func (d *lsblkDevice) mountPoint() string {
if d.MountPoint != nil {
return *d.MountPoint
}
return ""
}
func (d *lsblkDevice) model() string {
if d.Model != nil {
return strings.TrimSpace(*d.Model)
}
return ""
}
// ScanDisks detects all block devices and classifies them into
// available (not mounted, not system) and system/mounted disks.
func ScanDisks() (*ScanResult, error) {
out, err := exec.Command(
"lsblk", "-J", "-b",
"-o", "NAME,PATH,SIZE,TYPE,FSTYPE,MOUNTPOINT,MODEL,RM",
).Output()
if err != nil {
return nil, fmt.Errorf("lsblk failed: %w", err)
}
var parsed lsblkOutput
if err := json.Unmarshal(out, &parsed); err != nil {
return nil, fmt.Errorf("lsblk JSON parse failed: %w", err)
}
result := &ScanResult{}
for _, dev := range parsed.BlockDevices {
if dev.Type != "disk" {
continue
}
bd := BlockDevice{
Name: dev.Name,
Path: dev.Path,
Size: dev.sizeHuman(),
SizeBytes: dev.sizeBytes(),
Model: dev.model(),
Type: dev.Type,
Removable: dev.isRemovable(),
}
if bd.Path == "" {
bd.Path = "/dev/" + bd.Name
}
isSystem := false
anyMounted := false
for _, child := range dev.Children {
if child.Type != "part" && child.Type != "lvm" && child.Type != "crypt" {
continue
}
part := Partition{
Name: child.Name,
Path: child.Path,
Size: child.sizeHuman(),
SizeBytes: child.sizeBytes(),
FSType: child.fsType(),
MountPoint: child.mountPoint(),
}
if part.Path == "" {
part.Path = "/dev/" + part.Name
}
bd.Partitions = append(bd.Partitions, part)
if part.MountPoint != "" {
anyMounted = true
if part.MountPoint == "/" || part.MountPoint == "/boot" || part.MountPoint == "/boot/efi" {
isSystem = true
}
}
}
// Also check if the disk itself is directly mounted (no partition table)
if dev.mountPoint() != "" {
anyMounted = true
mp := dev.mountPoint()
if mp == "/" || mp == "/boot" {
isSystem = true
}
}
bd.Mounted = anyMounted
if isSystem {
result.SystemDisks = append(result.SystemDisks, bd)
} else {
result.AvailableDisks = append(result.AvailableDisks, bd)
}
}
return result, nil
}
+10
View File
@@ -0,0 +1,10 @@
//go:build !linux
package storage
import "fmt"
// ScanDisks is not supported on non-Linux platforms.
func ScanDisks() (*ScanResult, error) {
return nil, fmt.Errorf("storage init is only supported on Linux")
}