Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(disks): ground SMART disk discovery in /sys/block so no physical disk vanishes

rcourtmanc511c935b340
diff --git a/internal/hostagent/smartctl.go b/internal/hostagent/smartctl.go
index 1be2336cfa..020e383994 100644
--- a/internal/hostagent/smartctl.go
+++ b/internal/hostagent/smartctl.go
@@ -235,7 +235,14 @@ func CollectSMARTLocal(ctx context.Context, diskExclude []string) ([]DiskSMART,
}
var results []DiskSMART
+ var missed []smartctlTarget
+ collected := make(map[string]struct{}, len(targets))
+ multiplexed := make(map[string]struct{})
for _, target := range targets {
+ block := canonicalBlockDeviceForScanPath(target.Path)
+ if isMultiplexedDeviceType(target.DeviceType) && block != "" {
+ multiplexed[block] = struct{}{}
+ }
smart, err := collectSMARTTarget(ctx, target)
if err != nil {
if errors.Is(err, errSMARTDataUnavailable) {
@@ -252,14 +259,35 @@ func CollectSMARTLocal(ctx context.Context, diskExclude []string) ([]DiskSMART,
Err(err).
Msg("Failed to collect SMART data for device")
}
+ missed = append(missed, target)
+ continue
+ }
+ if smart == nil {
+ missed = append(missed, target)
continue
}
- if smart != nil {
- refineLinuxBlockDeviceIdentity(smart, target)
- results = append(results, *smart)
+ refineLinuxBlockDeviceIdentity(smart, target)
+ // The refine step can rename the device (nvme0 -> nvme0n1), so re-apply
+ // exclusions against the canonical name the user actually sees.
+ if matchesDeviceExclude(smart.Device, "/dev/"+smart.Device, diskExclude) {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "skip_excluded_device").
+ Str("device", smart.Device).
+ Msg("Skipping excluded device for SMART collection")
+ if block != "" {
+ collected[block] = struct{}{}
+ }
+ continue
+ }
+ results = append(results, *smart)
+ if block != "" {
+ collected[block] = struct{}{}
}
}
+ results = append(results, linuxIdentityOnlyDisks(missed, collected, multiplexed, diskExclude)...)
+
log.Debug().
Str("component", smartctlComponent).
Str("action", "collect_local_complete").
@@ -294,22 +322,65 @@ func smartctlTargetsFromDevices(devices []string) []smartctlTarget {
}
func listSMARTTargetsLinux(ctx context.Context, diskExclude []string) ([]smartctlTarget, error) {
- targets, err := listSMARTTargetsLinuxFromScanOpen(ctx, diskExclude)
- if err == nil && len(targets) > 0 {
- return targets, nil
- }
- if err != nil {
+ scanTargets, scanErr := listSMARTTargetsLinuxFromScanOpen(ctx, diskExclude)
+ if scanErr != nil {
log.Debug().
Str("component", smartctlComponent).
- Err(err).
- Msg("Failed to enumerate Linux SMART targets via smartctl --scan-open, falling back to block device discovery")
+ Err(scanErr).
+ Msg("Failed to enumerate Linux SMART targets via smartctl --scan-open, relying on block device discovery")
+ }
+
+ // smartctl --scan-open silently omits any device it fails to open at scan
+ // time (the failure is only a #-comment in its output), so the scan alone
+ // can hide a real disk while listing its neighbours (#1483: a SATA SSD
+ // missing while two NVMe controllers were reported). The kernel block
+ // device list is the ground truth for which disks exist; scan-open only
+ // contributes device-type hints. Union the two.
+ devices, devErr := listBlockDevicesLinux(ctx, diskExclude)
+ if devErr != nil {
+ if len(scanTargets) > 0 {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Err(devErr).
+ Msg("Block device discovery failed; using smartctl --scan-open targets only")
+ return scanTargets, nil
+ }
+ if scanErr != nil {
+ return nil, scanErr
+ }
+ return nil, devErr
}
- devices, fallbackErr := listBlockDevicesLinux(ctx, diskExclude)
- if fallbackErr != nil {
- return nil, fallbackErr
+ return unionSMARTTargets(scanTargets, devices), nil
+}
+
+// unionSMARTTargets returns scanTargets plus an untyped target for every block
+// device that no scan target covers. A scan target covers its own path's
+// basename and, for an NVMe controller, the namespace it canonicalizes to.
+func unionSMARTTargets(scanTargets []smartctlTarget, devices []string) []smartctlTarget {
+ covered := make(map[string]struct{}, len(scanTargets)*2)
+ for _, target := range scanTargets {
+ if name := filepath.Base(strings.TrimSpace(target.Path)); name != "" && name != "." {
+ covered[name] = struct{}{}
+ }
+ if block := canonicalBlockDeviceForScanPath(target.Path); block != "" {
+ covered[block] = struct{}{}
+ }
}
- return smartctlTargetsFromDevices(devices), nil
+
+ targets := append([]smartctlTarget(nil), scanTargets...)
+ for _, device := range devices {
+ name := filepath.Base(strings.TrimSpace(device))
+ if name == "" || name == "." {
+ continue
+ }
+ if _, ok := covered[name]; ok {
+ continue
+ }
+ covered[name] = struct{}{}
+ targets = append(targets, smartctlTarget{Path: device})
+ }
+ return targets
}
func listSMARTTargetsLinuxFromScanOpen(ctx context.Context, diskExclude []string) ([]smartctlTarget, error) {
@@ -745,6 +816,74 @@ func refineLinuxBlockDeviceIdentity(smart *DiskSMART, target smartctlTarget) {
}
}
+// linuxIdentityOnlyDisks builds identity-only entries for physical disks whose
+// SMART probes produced nothing usable. A real disk that refuses SMART must
+// still be listed — Proxmox's own disks/list shows it, and a monitoring view
+// that silently hides a present disk reads as data loss (#1483: a SATA SSD
+// vanished from the UI because its probe yielded no data). Each entry carries
+// only the identity /sys/block can prove (name, capacity, model, serial) plus
+// health UNKNOWN; no SMART data is fabricated. Multiplexed controller paths
+// are skipped: their per-member typed targets describe the real disks, and the
+// shared /dev path is the array, not a disk.
+func linuxIdentityOnlyDisks(missed []smartctlTarget, collected, multiplexed map[string]struct{}, diskExclude []string) []DiskSMART {
+ if runtimeGOOS != "linux" || len(missed) == 0 {
+ return nil
+ }
+
+ var results []DiskSMART
+ seen := make(map[string]struct{}, len(missed))
+ for _, target := range missed {
+ if isMultiplexedDeviceType(target.DeviceType) {
+ continue
+ }
+ block := canonicalBlockDeviceForScanPath(target.Path)
+ if block == "" {
+ continue
+ }
+ if _, ok := collected[block]; ok {
+ continue
+ }
+ if _, ok := multiplexed[block]; ok {
+ continue
+ }
+ if _, ok := seen[block]; ok {
+ continue
+ }
+ seen[block] = struct{}{}
+
+ size := blockDeviceSizeBytes(block)
+ if size <= 0 {
+ // Zero capacity means no medium (card readers, empty bridges) or
+ // no /sys/block entry at all; nothing real to report.
+ continue
+ }
+ if matchesDeviceExclude(block, "/dev/"+block, diskExclude) {
+ continue
+ }
+
+ diskType := "sata"
+ if strings.HasPrefix(block, "nvme") {
+ diskType = "nvme"
+ }
+ results = append(results, DiskSMART{
+ Device: block,
+ Model: readTrimmedFile(filepath.Join("/sys/block", block, "device", "model")),
+ Serial: readTrimmedFile(filepath.Join("/sys/block", block, "device", "serial")),
+ Type: diskType,
+ SizeBytes: size,
+ Health: "UNKNOWN",
+ LastUpdated: timeNow(),
+ })
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "identity_only_disk").
+ Str("device", block).
+ Int64("sizeBytes", size).
+ Msg("Reporting identity-only entry for physical disk without usable SMART data")
+ }
+ return results
+}
+
// isMultiplexedDeviceType reports whether a smartctl -d type addresses a member
// disk behind a controller (e.g. "megaraid,7"), as opposed to a directly
// attached device ("", "sat", "nvme", "scsi", "sat,auto").
@@ -925,6 +1064,16 @@ func collectSMARTTarget(ctx context.Context, target smartctlTarget) (*DiskSMART,
}
continue
}
+ // -n standby,3 makes a real standby exit 3; exit bit 2 with
+ // no output is an open/identify failure, not standby. When
+ // another attempt remains (Linux untyped retry), try it
+ // before reporting a phantom standby disk.
+ if runtimeGOOS == "linux" && i < len(attempts)-1 && exitCode != smartctlStandbyExitStatus {
+ if firstStandby == nil {
+ firstStandby = standbyResult
+ }
+ continue
+ }
log.Debug().
Str("component", smartctlComponent).
Str("action", "device_in_standby").
@@ -1000,9 +1149,19 @@ func collectSMARTTarget(ctx context.Context, target smartctlTarget) (*DiskSMART,
func smartctlProbeAttempts(target smartctlTarget) [][]string {
device := target.Path
if target.DeviceType != "" {
- return [][]string{
+ attempts := [][]string{
smartctlArgs(device, target.DeviceType),
}
+ // A scan-open device type is a hint, not ground truth: smartctl can
+ // suggest a type whose full query (-i -A -H) fails or returns no usable
+ // data even though untyped auto-detection works (#1483: a SATA SSD
+ // dropped after its typed probe yielded nothing). Retry untyped before
+ // giving up. Multiplexed controller members are exempt because dropping
+ // the -d would re-probe the shared array device, not the member.
+ if runtimeGOOS == "linux" && !isMultiplexedDeviceType(target.DeviceType) {
+ attempts = append(attempts, smartctlArgs(device, ""))
+ }
+ return attempts
}
if runtimeGOOS == "freebsd" {
diff --git a/internal/hostagent/smartctl_coverage_test.go b/internal/hostagent/smartctl_coverage_test.go
index f80c920814..1ebbd3f940 100644
--- a/internal/hostagent/smartctl_coverage_test.go
+++ b/internal/hostagent/smartctl_coverage_test.go
@@ -247,14 +247,19 @@ func TestCollectSMARTLocalUsesSmartctlScanOpenTargetsOnLinux(t *testing.T) {
origRun := smartRunCommandOutput
origLook := execLookPath
origGOOS := runtimeGOOS
+ origReadDir := readDir
t.Cleanup(func() {
smartRunCommandOutput = origRun
execLookPath = origLook
runtimeGOOS = origGOOS
+ readDir = origReadDir
})
runtimeGOOS = "linux"
execLookPath = func(string) (string, error) { return "smartctl", nil }
+ // Empty /sys/block: the scan-open target is the only discovery source, so
+ // the seenArgs order below stays scan -> probe.
+ readDir = func(string) ([]os.DirEntry, error) { return nil, nil }
var seenArgs [][]string
smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
diff --git a/internal/hostagent/smartctl_discovery_test.go b/internal/hostagent/smartctl_discovery_test.go
new file mode 100644
index 0000000000..21b63dd3e8
--- /dev/null
+++ b/internal/hostagent/smartctl_discovery_test.go
@@ -0,0 +1,428 @@
+package hostagent
+
+// Regression tests for #1483: on a Proxmox VE node the agent reported NVMe
+// disks keyed by controller with size 0 and dropped a SATA SSD entirely.
+// Fixture strings are captured from real PVE 9.1.9 hosts (smartctl 7.4) and
+// from the issue report itself.
+
+import (
+ "context"
+ "errors"
+ "io/fs"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+// scanOpenPVENVMeOnly reproduces the #1483 discovery failure: smartctl
+// --scan-open lists the two NVMe controllers but omits the SATA disk it could
+// not open at scan time (open failures are only emitted as # comments).
+// The NVMe lines are verbatim `smartctl --scan-open` output from a PVE 9.1.9
+// host (delly, 2026-06-10).
+const scanOpenPVENVMeOnly = `/dev/nvme0 -d nvme # /dev/nvme0, NVMe device
+/dev/nvme1 -d nvme # /dev/nvme1, NVMe device
+`
+
+// scanOpenPVESATA is verbatim `smartctl --scan-open` output from a PVE 9.1.9
+// host with a single SATA SSD (minipc, 2026-06-10).
+const scanOpenPVESATA = `/dev/sda -d sat # /dev/sda [SAT], ATA device
+`
+
+// smartctlSATAProbeJSON carries the key fields of a real
+// `smartctl -d sat -n standby,3 -i -A -H --json=o /dev/sda` run on a PVE
+// 9.1.9 host (minipc, 2026-06-10).
+const smartctlSATAProbeJSON = `{
+ "device": {"name": "/dev/sda", "info_name": "/dev/sda [SAT]", "type": "sat", "protocol": "ATA"},
+ "model_name": "N900-512",
+ "serial_number": "AA000000000000000588",
+ "user_capacity": {"blocks": 1000215216, "bytes": 512110190592},
+ "smart_status": {"passed": true},
+ "temperature": {"current": 40}
+}`
+
+// smartctlNVMeProbeJSON mirrors the reporter's KINGSTON SNV3S2000G output
+// (issue #1483); smartctl reports NVMe controllers by their char device.
+const smartctlNVMeProbeJSON = `{
+ "device": {"name": "/dev/nvme0", "type": "nvme", "protocol": "NVMe"},
+ "model_name": "KINGSTON SNV3S2000G",
+ "serial_number": "50026B7282A0FB69",
+ "nvme_total_capacity": 2000398934016,
+ "smart_status": {"passed": true},
+ "temperature": {"current": 37}
+}`
+
+// smartctlNoDataJSON is a syntactically valid smartctl JSON envelope with no
+// usable SMART payload, as produced when a probe addresses a device with the
+// wrong -d type.
+const smartctlNoDataJSON = `{
+ "device": {"name": "/dev/sda", "type": "sat", "protocol": "ATA"}
+}`
+
+func stubLinuxSysfs(t *testing.T, entries []string, files map[string]string) {
+ t.Helper()
+
+ origGOOS := runtimeGOOS
+ origReadDir := readDir
+ origReadFile := smartctlReadFile
+ origEvalSymlinks := smartctlEvalSymlinks
+ origNow := timeNow
+ t.Cleanup(func() {
+ runtimeGOOS = origGOOS
+ readDir = origReadDir
+ smartctlReadFile = origReadFile
+ smartctlEvalSymlinks = origEvalSymlinks
+ timeNow = origNow
+ })
+
+ runtimeGOOS = "linux"
+ timeNow = func() time.Time { return time.Date(2026, 6, 10, 12, 0, 0, 0, time.UTC) }
+ readDir = func(string) ([]os.DirEntry, error) {
+ dirEntries := make([]os.DirEntry, 0, len(entries))
+ for _, name := range entries {
+ dirEntries = append(dirEntries, fakeDirEntry{name: name})
+ }
+ return dirEntries, nil
+ }
+ smartctlReadFile = func(path string) ([]byte, error) {
+ if content, ok := files[path]; ok {
+ return []byte(content), nil
+ }
+ return nil, fs.ErrNotExist
+ }
+ smartctlEvalSymlinks = func(string) (string, error) { return "", fs.ErrNotExist }
+}
+
+func TestParseSmartctlScanOpenTargetsRealPVEOutput(t *testing.T) {
+ targets := parseSmartctlScanOpenTargets([]byte(scanOpenPVENVMeOnly+scanOpenPVESATA), nil)
+ if len(targets) != 3 {
+ t.Fatalf("expected 3 targets, got %#v", targets)
+ }
+ if targets[0].Path != "/dev/nvme0" || targets[0].DeviceType != "nvme" {
+ t.Errorf("unexpected first target: %#v", targets[0])
+ }
+ if targets[2].Path != "/dev/sda" || targets[2].DeviceType != "sat" {
+ t.Errorf("unexpected SATA target: %#v", targets[2])
+ }
+}
+
+func TestUnionSMARTTargetsAddsDevicesMissingFromScanOpen(t *testing.T) {
+ stubLinuxSysfs(t, []string{"nvme0n1", "nvme1n1", "sda"}, nil)
+
+ scanTargets := []smartctlTarget{
+ {Path: "/dev/nvme0", DeviceType: "nvme"},
+ {Path: "/dev/nvme1", DeviceType: "nvme"},
+ }
+ devices := []string{"/dev/nvme0n1", "/dev/nvme1n1", "/dev/sda"}
+
+ targets := unionSMARTTargets(scanTargets, devices)
+ if len(targets) != 3 {
+ t.Fatalf("expected 3 targets, got %#v", targets)
+ }
+ if targets[2].Path != "/dev/sda" || targets[2].DeviceType != "" {
+ t.Errorf("expected untyped /dev/sda appended, got %#v", targets[2])
+ }
+
+ // A device already covered by a scan target must not be duplicated.
+ scanTargets = append(scanTargets, smartctlTarget{Path: "/dev/sda", DeviceType: "sat"})
+ targets = unionSMARTTargets(scanTargets, devices)
+ if len(targets) != 3 {
+ t.Fatalf("expected no duplicate for covered devices, got %#v", targets)
+ }
+}
+
+// TestCollectSMARTLocalIncludesSATADiskOmittedByScanOpen reproduces the #1483
+// host: two NVMe controllers in the scan-open output, the SATA SSD missing
+// from it, and all three disks present in /sys/block. The SATA disk must
+// still be discovered, probed untyped, and reported.
+func TestCollectSMARTLocalIncludesSATADiskOmittedByScanOpen(t *testing.T) {
+ stubLinuxSysfs(t,
+ []string{"loop0", "nvme0n1", "nvme1n1", "sda", "zd0"},
+ map[string]string{
+ "/sys/block/nvme0n1/size": "3907029168\n", // 2000398934016 bytes
+ "/sys/block/nvme1n1/size": "3907029168\n",
+ "/sys/block/sda/size": "468862128\n", // 240057409536 bytes
+ },
+ )
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ var probed []string
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if len(args) == 1 && args[0] == "--scan-open" {
+ return []byte(scanOpenPVENVMeOnly), nil
+ }
+ device := args[len(args)-1]
+ probed = append(probed, strings.Join(args, " "))
+ switch device {
+ case "/dev/nvme0", "/dev/nvme1":
+ return []byte(smartctlNVMeProbeJSON), nil
+ case "/dev/sda":
+ if args[0] == "-d" {
+ t.Errorf("expected untyped probe for scan-omitted /dev/sda, got args %v", args)
+ }
+ return []byte(smartctlSATAProbeJSON), nil
+ default:
+ return nil, errors.New("unexpected device " + device)
+ }
+ }
+
+ results, err := CollectSMARTLocal(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("CollectSMARTLocal error: %v", err)
+ }
+ if len(results) != 3 {
+ t.Fatalf("expected 3 disks (2 NVMe + omitted SATA), got %#v", results)
+ }
+
+ byDevice := make(map[string]DiskSMART, len(results))
+ for _, disk := range results {
+ byDevice[disk.Device] = disk
+ }
+ for _, namespace := range []string{"nvme0n1", "nvme1n1"} {
+ disk, ok := byDevice[namespace]
+ if !ok {
+ t.Fatalf("missing namespace-keyed NVMe disk %q in %#v", namespace, results)
+ }
+ if disk.SizeBytes != 2000398934016 {
+ t.Errorf("%s SizeBytes = %d, want 2000398934016", namespace, disk.SizeBytes)
+ }
+ }
+ sata, ok := byDevice["sda"]
+ if !ok {
+ t.Fatalf("SATA disk missing from results: %#v", results)
+ }
+ if sata.Model != "N900-512" || sata.Serial != "AA000000000000000588" {
+ t.Errorf("unexpected SATA identity: %#v", sata)
+ }
+ if sata.SizeBytes != 240057409536 {
+ t.Errorf("SATA SizeBytes = %d, want 240057409536 (from /sys/block)", sata.SizeBytes)
+ }
+ if sata.Health != "PASSED" {
+ t.Errorf("SATA health = %q, want PASSED", sata.Health)
+ }
+}
+
+func TestCollectSMARTTargetRetriesUntypedAfterTypedProbeFailure(t *testing.T) {
+ cases := map[string]func(args []string) ([]byte, error){
+ "typed probe errors": func(args []string) ([]byte, error) {
+ return nil, errors.New("smartctl: unsupported field in scsi command")
+ },
+ "typed probe returns no usable data": func(args []string) ([]byte, error) {
+ return []byte(smartctlNoDataJSON), nil
+ },
+ }
+
+ for name, typedResponse := range cases {
+ t.Run(name, func(t *testing.T) {
+ stubLinuxSysfs(t, []string{"sda"}, nil)
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ var attempts [][]string
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ attempts = append(attempts, append([]string(nil), args...))
+ if args[0] == "-d" {
+ return typedResponse(args)
+ }
+ return []byte(smartctlSATAProbeJSON), nil
+ }
+
+ result, err := collectSMARTTarget(context.Background(), smartctlTarget{Path: "/dev/sda", DeviceType: "sat"})
+ if err != nil {
+ t.Fatalf("collectSMARTTarget error: %v", err)
+ }
+ if len(attempts) != 2 {
+ t.Fatalf("expected typed attempt then untyped retry, got %v", attempts)
+ }
+ if attempts[0][0] != "-d" || attempts[0][1] != "sat" {
+ t.Errorf("first attempt should be typed, got %v", attempts[0])
+ }
+ if attempts[1][0] == "-d" {
+ t.Errorf("retry should be untyped, got %v", attempts[1])
+ }
+ if result.Model != "N900-512" || result.SizeBytes != 512110190592 {
+ t.Errorf("unexpected retry result: %#v", result)
+ }
+ })
+ }
+}
+
+func TestCollectSMARTTargetKeepsSingleTypedAttemptForMultiplexed(t *testing.T) {
+ stubLinuxSysfs(t, []string{"sda"}, nil)
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ var attempts int
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ attempts++
+ return []byte(smartctlNoDataJSON), nil
+ }
+
+ if _, err := collectSMARTTarget(context.Background(), smartctlTarget{Path: "/dev/sda", DeviceType: "megaraid,7"}); !errors.Is(err, errSMARTDataUnavailable) {
+ t.Fatalf("expected errSMARTDataUnavailable, got %v", err)
+ }
+ if attempts != 1 {
+ t.Fatalf("multiplexed member must not retry untyped (would probe the array), got %d attempts", attempts)
+ }
+}
+
+// TestCollectSMARTLocalEmitsIdentityOnlyEntryWhenSMARTUnavailable covers the
+// last line of defence: every probe failed, but the disk demonstrably exists
+// in /sys/block, so it is reported with its provable identity instead of
+// silently disappearing from the UI.
+func TestCollectSMARTLocalEmitsIdentityOnlyEntryWhenSMARTUnavailable(t *testing.T) {
+ stubLinuxSysfs(t,
+ []string{"sda"},
+ map[string]string{
+ "/sys/block/sda/size": "1000215216\n", // 512110190592 bytes
+ "/sys/block/sda/device/model": "N900-512 \n",
+ },
+ )
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if len(args) == 1 && args[0] == "--scan-open" {
+ return []byte(scanOpenPVESATA), nil
+ }
+ return []byte(smartctlNoDataJSON), nil
+ }
+
+ results, err := CollectSMARTLocal(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("CollectSMARTLocal error: %v", err)
+ }
+ if len(results) != 1 {
+ t.Fatalf("expected identity-only entry, got %#v", results)
+ }
+ disk := results[0]
+ if disk.Device != "sda" || disk.Model != "N900-512" || disk.Type != "sata" {
+ t.Errorf("unexpected identity: %#v", disk)
+ }
+ if disk.SizeBytes != 512110190592 {
+ t.Errorf("SizeBytes = %d, want 512110190592", disk.SizeBytes)
+ }
+ if disk.Health != "UNKNOWN" {
+ t.Errorf("Health = %q, want UNKNOWN", disk.Health)
+ }
+ if disk.Temperature != 0 || disk.Attributes != nil {
+ t.Errorf("identity-only entry must not fabricate SMART data: %#v", disk)
+ }
+}
+
+func TestCollectSMARTLocalSkipsIdentityOnlyEntries(t *testing.T) {
+ t.Run("multiplexed controller path", func(t *testing.T) {
+ stubLinuxSysfs(t,
+ []string{"sda"},
+ map[string]string{"/sys/block/sda/size": "1000215216\n"},
+ )
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if len(args) == 1 && args[0] == "--scan-open" {
+ return []byte("/dev/sda -d megaraid,0 # slot 0\n/dev/sda -d megaraid,1 # slot 1\n"), nil
+ }
+ return []byte(smartctlNoDataJSON), nil
+ }
+
+ results, err := CollectSMARTLocal(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("CollectSMARTLocal error: %v", err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("array path behind a multiplexing controller must not gain an identity row, got %#v", results)
+ }
+ })
+
+ t.Run("device without capacity", func(t *testing.T) {
+ stubLinuxSysfs(t, []string{"sda"}, map[string]string{"/sys/block/sda/size": "0\n"})
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if len(args) == 1 && args[0] == "--scan-open" {
+ return []byte(scanOpenPVESATA), nil
+ }
+ return []byte(smartctlNoDataJSON), nil
+ }
+
+ results, err := CollectSMARTLocal(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("CollectSMARTLocal error: %v", err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("zero-capacity device must not gain an identity row, got %#v", results)
+ }
+ })
+}
+
+// TestCollectSMARTLocalAppliesExcludeToCanonicalNamespaceName guards the
+// post-refine exclusion check: the scan target is the controller (nvme0), but
+// the user excludes the canonical namespace name they see in the UI.
+func TestCollectSMARTLocalAppliesExcludeToCanonicalNamespaceName(t *testing.T) {
+ stubLinuxSysfs(t,
+ []string{"nvme0n1"},
+ map[string]string{"/sys/block/nvme0n1/size": "3907029168\n"},
+ )
+
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ })
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ if len(args) == 1 && args[0] == "--scan-open" {
+ return []byte("/dev/nvme0 -d nvme # /dev/nvme0, NVMe device\n"), nil
+ }
+ return []byte(smartctlNVMeProbeJSON), nil
+ }
+
+ results, err := CollectSMARTLocal(context.Background(), []string{"nvme0n1"})
+ if err != nil {
+ t.Fatalf("CollectSMARTLocal error: %v", err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("excluded canonical namespace must not be reported, got %#v", results)
+ }
+}