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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Fix physical disks vanishing on wide nodes and standby-misreporting SSDs
rcourtmanf2b732721e66
diff --git a/internal/api/setup_script_render.go b/internal/api/setup_script_render.goindex 762a0799b4..7dd08771c4 100644--- a/internal/api/setup_script_render.go+++ b/internal/api/setup_script_render.go@@ -935,6 +935,19 @@ def canonical_block_for_device(device):return name+def is_non_rotational_block_device(device):+ # Positively confirmed SSD via sysfs; anything uncertain returns False so+ # the caller keeps the conservative standby guard.+ block = canonical_block_for_device(device)+ if not block:+ return False+ try:+ with open("/sys/block/%%s/queue/rotational" %% block) as handle:+ return handle.read().strip() == "0"+ except Exception:+ return False++def inferred_smart_device_types(device):name = os.path.basename(str(device or "").strip()).lower()if re.fullmatch(r"(sd|hd)[a-z]+", name or ""):@@ -1184,7 +1197,15 @@ def collect_smart():args = [path]if attempt_type:args.extend(["-d", attempt_type])- args.extend(["-n", "standby,3", "-i", "-A", "-H", "--json=o", attempt_device])+ # The standby guard avoids spinning up sleeping rotational disks.+ # SSDs have nothing to spin up, and some SATA SSDs answer CHECK+ # POWER MODE with a bogus standby state that permanently hides+ # their SMART data (#1516), so confirmed SSDs are probed without+ # it. Multiplexed members keep the guard: the shared /dev path's+ # rotational flag describes the array, not the member.+ if is_multiplexed_device_type(attempt_type) or not is_non_rotational_block_device(attempt_device):+ args.extend(["-n", "standby,3"])+ args.extend(["-i", "-A", "-H", "--json=o", attempt_device])result = run_command(args)if not result or not result.stdout.strip():diff --git a/internal/hostagent/smartctl.go b/internal/hostagent/smartctl.goindex dcb627688a..09d3b9fd32 100644--- a/internal/hostagent/smartctl.go+++ b/internal/hostagent/smartctl.go@@ -1213,10 +1213,34 @@ func smartctlArgs(device, deviceType string) []string {if deviceType != "" {args = append(args, "-d", deviceType)}- args = append(args, "-n", "standby,"+strconv.Itoa(smartctlStandbyExitStatus), "-i", "-A", "-H", "--json=o", device)+ // The standby guard exists to avoid spinning up sleeping rotational disks.+ // An SSD has nothing to spin up, and some SATA SSDs answer the guard's+ // CHECK POWER MODE with a bogus standby state that permanently hides their+ // SMART data (#1516), so confirmed non-rotational devices are probed+ // without it. Multiplexed controller members keep the guard: the shared+ // /dev path's rotational flag describes the array device, not the member.+ if isMultiplexedDeviceType(deviceType) || !linuxNonRotationalBlockDevice(device) {+ args = append(args, "-n", "standby,"+strconv.Itoa(smartctlStandbyExitStatus))+ }+ args = append(args, "-i", "-A", "-H", "--json=o", device)return args}+// linuxNonRotationalBlockDevice reports whether the canonical block device+// behind path is positively confirmed non-rotational (SSD) via sysfs. Any+// uncertainty — non-Linux, unresolvable device, unreadable sysfs — returns+// false so the caller keeps the conservative standby guard.+func linuxNonRotationalBlockDevice(device string) bool {+ if runtimeGOOS != "linux" {+ return false+ }+ block := canonicalBlockDeviceForScanPath(device)+ if block == "" {+ return false+ }+ return readTrimmedFile(filepath.Join("/sys/block", block, "queue", "rotational")) == "0"+}+func smartctlArgsWithLog(args []string, logPage string) []string {if logPage == "" || len(args) == 0 {return append([]string(nil), args...)diff --git a/internal/hostagent/smartctl_standby_guard_test.go b/internal/hostagent/smartctl_standby_guard_test.gonew file mode 100644index 0000000000..09bfd4e6e1--- /dev/null+++ b/internal/hostagent/smartctl_standby_guard_test.go@@ -0,0 +1,110 @@+package hostagent++import (+ "fmt"+ "io/fs"+ "strings"+ "testing"+)++// The -n standby guard exists to avoid spinning up sleeping rotational disks.+// SSDs have nothing to spin up, and some SATA SSDs answer CHECK POWER MODE+// with a bogus standby state that permanently hides their SMART data (#1516),+// so confirmed non-rotational devices must be probed without the guard.+func TestSmartctlArgsStandbyGuard(t *testing.T) {+ origGOOS := runtimeGOOS+ origReadFile := smartctlReadFile+ t.Cleanup(func() {+ runtimeGOOS = origGOOS+ smartctlReadFile = origReadFile+ })++ rotationalByDevice := map[string]string{}+ smartctlReadFile = func(path string) ([]byte, error) {+ for device, value := range rotationalByDevice {+ if path == fmt.Sprintf("/sys/block/%s/queue/rotational", device) {+ return []byte(value + "\n"), nil+ }+ }+ return nil, fs.ErrNotExist+ }++ hasStandbyGuard := func(args []string) bool {+ for i, arg := range args {+ if arg == "-n" && i+1 < len(args) && strings.HasPrefix(args[i+1], "standby,") {+ return true+ }+ }+ return false+ }++ tests := []struct {+ name string+ goos string+ device string+ deviceType string+ rotational map[string]string+ wantGuard bool+ }{+ {+ name: "linux ssd drops guard",+ goos: "linux",+ device: "/dev/sda",+ deviceType: "sat",+ rotational: map[string]string{"sda": "0"},+ wantGuard: false,+ },+ {+ name: "linux hdd keeps guard",+ goos: "linux",+ device: "/dev/sdb",+ deviceType: "sat",+ rotational: map[string]string{"sdb": "1"},+ wantGuard: true,+ },+ {+ name: "unreadable sysfs keeps guard",+ goos: "linux",+ device: "/dev/sdc",+ deviceType: "",+ rotational: map[string]string{},+ wantGuard: true,+ },+ {+ name: "multiplexed member keeps guard even when array is non-rotational",+ goos: "linux",+ device: "/dev/sda",+ deviceType: "megaraid,7",+ rotational: map[string]string{"sda": "0"},+ wantGuard: true,+ },+ {+ name: "non-linux keeps guard",+ goos: "freebsd",+ device: "/dev/ada0",+ deviceType: "sat",+ rotational: map[string]string{"ada0": "0"},+ wantGuard: true,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ runtimeGOOS = tc.goos+ rotationalByDevice = tc.rotational++ args := smartctlArgs(tc.device, tc.deviceType)+ if got := hasStandbyGuard(args); got != tc.wantGuard {+ t.Fatalf("smartctlArgs(%q, %q) standby guard = %v, want %v (args %v)",+ tc.device, tc.deviceType, got, tc.wantGuard, args)+ }+ // The probe flags and device must survive in both shapes.+ joined := strings.Join(args, " ")+ for _, required := range []string{"-i", "-A", "-H", "--json=o", tc.device} {+ if !strings.Contains(joined, required) {+ t.Fatalf("smartctlArgs(%q, %q) missing %q in %v", tc.device, tc.deviceType, required, args)+ }+ }+ })+ }+}diff --git a/internal/monitoring/monitor_pve.go b/internal/monitoring/monitor_pve.goindex 310ea26387..b72c722596 100644--- a/internal/monitoring/monitor_pve.go+++ b/internal/monitoring/monitor_pve.go@@ -870,8 +870,14 @@ func (m *Monitor) maybePollPhysicalDisksAsync(go func(inst string, pveClient PVEClientInterface, nodeList []proxmox.Node, nodeStatus map[string]string, modelNodesCopy []models.Node) {defer recoverFromPanic(fmt.Sprintf("pollPhysicalDisks-%s", inst))- // Use a generous timeout for disk polling+ // Use a generous timeout for disk polling. Each node gets its own+ // attempt window below, so the overall budget scales to the polling+ // interval: one slow node must not consume the whole instance budget,+ // and staying inside the interval means polls can never overlap.diskTimeout := 60 * time.Second+ if pollingInterval > diskTimeout {+ diskTimeout = pollingInterval+ }// Use monitor lifecycle context so shutdown can interrupt detached async polling.parentCtx := m.getRuntimeContext()if parentCtx == nil {@@ -907,12 +913,21 @@ func (m *Monitor) maybePollPhysicalDisksAsync(for _, h := range hosts {hostByID[h.ID] = h}+ // Also map node name → linked host agent SMART inventory so a node whose+ // Proxmox disk query fails can still populate its physical disks from+ // the agent's smartctl view (#1516).+ smartByNode := make(map[string][]models.HostDiskSMART)for _, n := range nodesFromState {if n.LinkedAgentID == "" || n.Instance != inst {continue}- if linkedHost, ok := hostByID[n.LinkedAgentID]; ok && len(linkedHost.DiskExclude) > 0 {- diskExcludeByNode[n.Name] = linkedHost.DiskExclude+ if linkedHost, ok := hostByID[n.LinkedAgentID]; ok {+ if len(linkedHost.DiskExclude) > 0 {+ diskExcludeByNode[n.Name] = linkedHost.DiskExclude+ }+ if len(linkedHost.Sensors.SMART) > 0 {+ smartByNode[n.Name] = linkedHost.Sensors.SMART+ }}}@@ -920,14 +935,16 @@ func (m *Monitor) maybePollPhysicalDisksAsync(polledNodes := make(map[string]bool) // Track which nodes we successfully polledzfsPoolingEnabled := zfsMonitoringEnabledFromEnv()+ nodeLoop:for _, node := range nodeList {- // Check if context timed out+ // Check if context timed out. Break instead of returning so the+ // nodes already polled still land in state.select {case <-diskCtx.Done():log.Debug().Str("instance", inst).- Msg("Physical disk polling timed out - preserving existing data")- return+ Msg("Physical disk polling timed out - saving partial results")+ break nodeLoopdefault:}@@ -937,9 +954,13 @@ func (m *Monitor) maybePollPhysicalDisksAsync(continue}+ // Each node gets its own attempt window so one slow node cannot+ // starve the rest of the cluster's disk poll.+ nodeCtx, nodeCancel := context.WithTimeout(diskCtx, 60*time.Second)+// Get disk list for this nodelog.Debug().Str("node", node.Node).Msg("getting disk list for node")- disks, err := pveClient.GetDisks(diskCtx, node.Node)+ disks, err := pveClient.GetDisks(nodeCtx, node.Node)if err != nil {// Check if it's a permission error or if the endpoint doesn't existerrStr := err.Error()@@ -958,6 +979,20 @@ func (m *Monitor) maybePollPhysicalDisksAsync(Err(err).Msg("Failed to get disk list")}+ // The Proxmox query failed, but a linked host agent sees the+ // same disks via smartctl. Wide nodes (dozens of disks) can+ // exceed the API window PVE itself allows for disks/list, so+ // without this fallback their Physical Disks view empties+ // permanently (#1516).+ if fallback := physicalDisksFromHostAgentSMART(inst, node.Node, smartByNode[node.Node]); len(fallback) > 0 {+ polledNodes[node.Node] = true+ allDisks = append(allDisks, fallback...)+ log.Info().+ Str("node", node.Node).+ Int("diskCount", len(fallback)).+ Msg("Proxmox disk query failed - using linked host agent SMART inventory for physical disks")+ }+ nodeCancel()continue}@@ -969,7 +1004,7 @@ func (m *Monitor) maybePollPhysicalDisksAsync(// non-fatal; we simply leave StorageGroup empty.var poolAssignment *diskPoolAssignmentif zfsPoolingEnabled {- if pools, pErr := pveClient.GetZFSPoolsWithDetails(diskCtx, node.Node); pErr == nil {+ if pools, pErr := pveClient.GetZFSPoolsWithDetails(nodeCtx, node.Node); pErr == nil {poolAssignment = buildDiskPoolAssignment(pools)} else {log.Debug().@@ -978,6 +1013,7 @@ func (m *Monitor) maybePollPhysicalDisksAsync(Msg("Could not fetch ZFS pool details for disk→pool mapping; StorageGroup will be empty")}}+ nodeCancel()// Record each disk; alert evaluation happens after host-agent SMART merges// so the canonical disk view includes post-merge health/wearout data.@@ -1064,6 +1100,52 @@ func (m *Monitor) maybePollPhysicalDisksAsync(}(instanceName, client, nodes, nodeEffectiveStatus, modelNodes)}+// physicalDisksFromHostAgentSMART builds PhysicalDisk entries for a node from+// its linked host agent's SMART inventory. This is the fallback when the+// Proxmox disks/list query fails: PVE probes SMART per disk inside that call,+// so a node with dozens of disks can exceed the API window and the view would+// otherwise empty even though the agent on the node sees every disk (#1516).+// Only what the agent actually reports is carried over; nothing is fabricated.+func physicalDisksFromHostAgentSMART(inst, nodeName string, smartEntries []models.HostDiskSMART) []models.PhysicalDisk {+ if len(smartEntries) == 0 {+ return nil+ }+ now := time.Now()+ disks := make([]models.PhysicalDisk, 0, len(smartEntries))+ for _, smart := range smartEntries {+ device := strings.TrimSpace(smart.Device)+ if device == "" {+ continue+ }+ devPath := device+ if !strings.HasPrefix(devPath, "/dev/") {+ devPath = "/dev/" + devPath+ }+ health := strings.TrimSpace(smart.Health)+ if health == "" {+ health = "UNKNOWN"+ }+ disks = append(disks, models.PhysicalDisk{+ ID: fmt.Sprintf("%s-%s-%s", inst, nodeName, strings.ReplaceAll(devPath, "/", "-")),+ Node: nodeName,+ Instance: inst,+ DevPath: devPath,+ Model: strings.TrimSpace(smart.Model),+ Serial: strings.TrimSpace(smart.Serial),+ WWN: strings.TrimSpace(smart.WWN),+ Type: strings.TrimSpace(smart.Type),+ Size: smart.SizeBytes,+ Health: health,+ Wearout: deriveWearoutFromSMARTAttributes(smart.Attributes),+ Temperature: smart.Temperature,+ StorageGroup: strings.TrimSpace(smart.Pool),+ SmartAttributes: smartAttributesCopy(smart.Attributes),+ LastChecked: now,+ })+ }+ return disks+}+func proxmoxDiskFromPhysicalDisk(disk models.PhysicalDisk) proxmox.Disk {return proxmox.Disk{DevPath: disk.DevPath,diff --git a/internal/monitoring/monitor_pve_disk_fallback_test.go b/internal/monitoring/monitor_pve_disk_fallback_test.gonew file mode 100644index 0000000000..ddf47ea013--- /dev/null+++ b/internal/monitoring/monitor_pve_disk_fallback_test.go@@ -0,0 +1,148 @@+package monitoring++import (+ "context"+ "fmt"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++func int64PtrDiskFallback(v int64) *int64 { return &v }++func TestPhysicalDisksFromHostAgentSMART_BuildsDisks(t *testing.T) {+ entries := []models.HostDiskSMART{+ {+ Device: "sda",+ Model: "ST18000NM019J",+ Serial: "ZR5DLAYJ",+ WWN: "5-c500-da60ca43",+ Type: "sas",+ SizeBytes: 18000207937536,+ Temperature: 30,+ Health: "PASSED",+ Pool: "tank",+ Attributes: &models.SMARTAttributes{PowerOnHours: int64PtrDiskFallback(327)},+ },+ {+ // Standby entry keeps its identity but carries no health reading.+ Device: "sdb",+ Model: "ST18000NM019J",+ Serial: "ZR5DLXYZ",+ Type: "sas",+ Standby: true,+ },+ {+ // Entries without a device name cannot form a stable ID.+ Device: " ",+ },+ }++ disks := physicalDisksFromHostAgentSMART("pve1", "node1", entries)+ if len(disks) != 2 {+ t.Fatalf("expected 2 disks, got %d: %+v", len(disks), disks)+ }++ first := disks[0]+ if first.ID != "pve1-node1--dev-sda" {+ t.Errorf("unexpected ID %q", first.ID)+ }+ if first.DevPath != "/dev/sda" || first.Node != "node1" || first.Instance != "pve1" {+ t.Errorf("unexpected identity fields: %+v", first)+ }+ if first.Health != "PASSED" || first.Temperature != 30 || first.Size != 18000207937536 {+ t.Errorf("unexpected data fields: %+v", first)+ }+ if first.StorageGroup != "tank" {+ t.Errorf("expected pool carried into StorageGroup, got %q", first.StorageGroup)+ }+ if first.SmartAttributes == nil || first.SmartAttributes.PowerOnHours == nil || *first.SmartAttributes.PowerOnHours != 327 {+ t.Errorf("expected SMART attributes carried over, got %+v", first.SmartAttributes)+ }+ if first.Wearout != -1 {+ t.Errorf("expected wearout unknown (-1) without wear attributes, got %d", first.Wearout)+ }++ second := disks[1]+ if second.DevPath != "/dev/sdb" || second.Health != "UNKNOWN" {+ t.Errorf("expected standby disk listed with UNKNOWN health, got %+v", second)+ }++ if got := physicalDisksFromHostAgentSMART("pve1", "node1", nil); got != nil {+ t.Errorf("expected nil for empty SMART inventory, got %+v", got)+ }+}++type disksErrorPVEClient struct {+ fakeStorageClient+}++func (*disksErrorPVEClient) GetDisks(ctx context.Context, node string) ([]proxmox.Disk, error) {+ return nil, fmt.Errorf("596 connection timed out")+}++// A node whose Proxmox disks/list query fails (wide nodes can exceed the API+// window) must still populate its Physical Disks view from the linked host+// agent's SMART inventory instead of silently emptying (#1516).+func TestMaybePollPhysicalDisksAsync_AgentFallbackWhenDiskQueryFails(t *testing.T) {+ m := &Monitor{+ state: models.NewState(),+ lastPhysicalDiskPoll: make(map[string]time.Time),+ alertManager: alerts.NewManager(),+ }++ m.state.UpdateNodesForInstance("pve1", []models.Node{{+ ID: "pve1-node1",+ Name: "node1",+ Instance: "pve1",+ LinkedAgentID: "host-1",+ }})+ m.state.UpsertHost(models.Host{+ ID: "host-1",+ Hostname: "node1",+ Sensors: models.HostSensorSummary{+ SMART: []models.HostDiskSMART{{+ Device: "sda",+ Model: "ST18000NM019J",+ Serial: "ZR5DLAYJ",+ Type: "sas",+ SizeBytes: 18000207937536,+ Temperature: 30,+ Health: "PASSED",+ }},+ },+ })++ m.maybePollPhysicalDisksAsync(+ context.Background(),+ "pve1",+ &config.PVEInstance{},+ &disksErrorPVEClient{},+ []proxmox.Node{{Node: "node1", Status: "online"}},+ map[string]string{"node1": "online"},+ []models.Node{{Name: "node1"}},+ )++ deadline := time.Now().Add(3 * time.Second)+ for {+ disks := m.state.GetSnapshot().PhysicalDisks+ if len(disks) == 1 {+ disk := disks[0]+ if disk.DevPath != "/dev/sda" || disk.Node != "node1" || disk.Instance != "pve1" {+ t.Fatalf("unexpected fallback disk identity: %+v", disk)+ }+ if disk.Health != "PASSED" || disk.Temperature != 30 {+ t.Fatalf("unexpected fallback disk data: %+v", disk)+ }+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("expected fallback physical disk from host agent SMART, got %+v", disks)+ }+ time.Sleep(10 * time.Millisecond)+ }+}