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 FreeBSD SMART disk detection for ada/da/nvd devices (#1254)

rcourtman98c9de7c91e2
diff --git a/internal/smartctl/collector.go b/internal/smartctl/collector.go
index f23d250992..faa5d7eb9f 100644
--- a/internal/smartctl/collector.go
+++ b/internal/smartctl/collector.go
@@ -5,9 +5,11 @@ import (
"context"
"encoding/json"
"errors"
+ "os"
"os/exec"
"path/filepath"
"runtime"
+ "sort"
"strconv"
"strings"
"time"
@@ -17,6 +19,7 @@ import (
var (
execLookPath = exec.LookPath
+ readDir = os.ReadDir
runCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
return exec.CommandContext(ctx, name, args...).Output()
}
@@ -26,6 +29,8 @@ var (
errSMARTDataUnavailable = errors.New("smart data unavailable for device")
)
+const smartctlStandbyExitStatus = 3
+
// DiskSMART represents S.M.A.R.T. data for a single disk.
type DiskSMART struct {
Device string `json:"device"` // Device path (e.g., /dev/sda)
@@ -267,27 +272,140 @@ func linuxSMARTSkipReason(device lsblkDevice) string {
// listBlockDevicesFreeBSD uses sysctl kern.disks to find disks on FreeBSD.
func listBlockDevicesFreeBSD(ctx context.Context, diskExclude []string) ([]string, error) {
+ names, sysctlErr := freeBSDDiskNamesFromSysctl(ctx)
+ if sysctlErr != nil {
+ log.Debug().Err(sysctlErr).Msg("Failed to enumerate FreeBSD disks from kern.disks")
+ }
+
+ fallbackNames, fallbackErr := freeBSDDiskNamesFromDev()
+ if fallbackErr != nil {
+ log.Debug().Err(fallbackErr).Msg("Failed to enumerate FreeBSD disks from /dev")
+ }
+
+ if len(names) == 0 {
+ names = fallbackNames
+ } else if len(fallbackNames) > 0 {
+ seen := make(map[string]struct{}, len(names))
+ for _, name := range names {
+ seen[name] = struct{}{}
+ }
+ for _, name := range fallbackNames {
+ if _, ok := seen[name]; ok {
+ continue
+ }
+ names = append(names, name)
+ }
+ }
+
+ if len(names) == 0 {
+ switch {
+ case sysctlErr != nil:
+ return nil, sysctlErr
+ case fallbackErr != nil:
+ return nil, fallbackErr
+ default:
+ return nil, nil
+ }
+ }
+
+ var devices []string
+ for _, name := range names {
+ devicePath := "/dev/" + name
+ if matchesDeviceExclude(name, devicePath, diskExclude) {
+ log.Debug().Str("device", devicePath).Msg("Skipping excluded device for SMART collection")
+ continue
+ }
+ devices = append(devices, devicePath)
+ }
+
+ return devices, nil
+}
+
+func freeBSDDiskNamesFromSysctl(ctx context.Context) ([]string, error) {
output, err := runCommandOutput(ctx, "sysctl", "-n", "kern.disks")
if err != nil {
return nil, err
}
var devices []string
+ seen := make(map[string]struct{})
for _, name := range strings.Fields(strings.TrimSpace(string(output))) {
if name == "" {
continue
}
- devicePath := "/dev/" + name
- if matchesDeviceExclude(name, devicePath, diskExclude) {
- log.Debug().Str("device", devicePath).Msg("Skipping excluded device for SMART collection")
+ if _, ok := seen[name]; ok {
continue
}
- devices = append(devices, devicePath)
+ seen[name] = struct{}{}
+ devices = append(devices, name)
}
return devices, nil
}
+func freeBSDDiskNamesFromDev() ([]string, error) {
+ entries, err := readDir("/dev")
+ if err != nil {
+ return nil, err
+ }
+
+ var names []string
+ for _, entry := range entries {
+ name := strings.TrimSpace(entry.Name())
+ if !isFreeBSDDiskDeviceName(name) {
+ continue
+ }
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ return names, nil
+}
+
+func isFreeBSDDiskDeviceName(name string) bool {
+ for _, prefix := range []string{
+ "ad",
+ "ada",
+ "aacd",
+ "amrd",
+ "da",
+ "idad",
+ "ipsd",
+ "mfid",
+ "mfisyspd",
+ "mlxd",
+ "mmcsd",
+ "nda",
+ "nvd",
+ "nvme",
+ "twa",
+ "twed",
+ "tws",
+ "vtbd",
+ "xbd",
+ } {
+ if hasNumericSuffix(name, prefix) {
+ return true
+ }
+ }
+
+ return false
+}
+
+func hasNumericSuffix(name, prefix string) bool {
+ if !strings.HasPrefix(name, prefix) || len(name) == len(prefix) {
+ return false
+ }
+
+ for _, r := range name[len(prefix):] {
+ if r < '0' || r > '9' {
+ return false
+ }
+ }
+
+ return true
+}
+
// matchesDeviceExclude checks if a block device matches any exclusion pattern.
// Patterns can match against the device name (e.g., "sda", "nvme0n1") or the full
// path (e.g., "/dev/sda"). Supports:
@@ -352,11 +470,9 @@ func collectDeviceSMART(ctx context.Context, device string) (*DiskSMART, error)
output, err := runCommandOutput(cmdCtx, smartctlPath, args...)
// smartctl returns non-zero exit codes for various conditions.
- // Exit code 2 means drive is in standby - that's okay.
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
- exitCode := exitErr.ExitCode()
- if exitCode&2 != 0 {
+ if exitErr.ExitCode() == smartctlStandbyExitStatus && len(output) == 0 {
return &DiskSMART{
Device: filepath.Base(device),
Standby: true,
@@ -411,15 +527,20 @@ func collectDeviceSMART(ctx context.Context, device string) (*DiskSMART, error)
}
func smartctlProbeAttempts(device string) [][]string {
- attempts := [][]string{
- smartctlArgs(device, ""),
+ if runtimeGOOS == "freebsd" {
+ deviceTypes := freeBSDSmartctlDeviceTypes(filepath.Base(device))
+ if len(deviceTypes) > 0 {
+ attempts := make([][]string, 0, len(deviceTypes)+1)
+ for _, deviceType := range deviceTypes {
+ attempts = append(attempts, smartctlArgs(device, deviceType))
+ }
+ return append(attempts, smartctlArgs(device, ""))
+ }
}
- for _, deviceType := range freeBSDSmartctlDeviceTypes(filepath.Base(device)) {
- attempts = append(attempts, smartctlArgs(device, deviceType))
+ return [][]string{
+ smartctlArgs(device, ""),
}
-
- return attempts
}
func smartctlArgs(device, deviceType string) []string {
@@ -427,7 +548,7 @@ func smartctlArgs(device, deviceType string) []string {
if deviceType != "" {
args = append(args, "-d", deviceType)
}
- args = append(args, "-n", "standby", "-i", "-A", "-H", "--json=o", device)
+ args = append(args, "-n", "standby,"+strconv.Itoa(smartctlStandbyExitStatus), "-i", "-A", "-H", "--json=o", device)
return args
}
@@ -441,7 +562,7 @@ func freeBSDSmartctlDeviceTypes(device string) []string {
return []string{"sat"}
case strings.HasPrefix(device, "da"):
return []string{"sat,auto", "scsi"}
- case strings.HasPrefix(device, "nvd"), strings.HasPrefix(device, "nvme"):
+ case strings.HasPrefix(device, "nda"), strings.HasPrefix(device, "nvd"), strings.HasPrefix(device, "nvme"):
return []string{"nvme"}
default:
return nil
@@ -452,6 +573,9 @@ func shouldRetryFreeBSDSMART(device string, result *DiskSMART, attemptIndex, att
if runtimeGOOS != "freebsd" || attemptIndex >= attemptCount-1 || result == nil {
return false
}
+ if result.Standby {
+ return false
+ }
if result.Temperature > 0 {
return false
}
@@ -471,6 +595,7 @@ func parseSMARTOutput(output []byte, device string) (*DiskSMART, error) {
Type: detectDiskType(smartData),
LastUpdated: timeNow(),
}
+ result.Standby = isStandbyPowerMode(smartData.PowerMode)
if smartData.WWN.NAA != 0 {
result.WWN = formatWWN(smartData.WWN.NAA, smartData.WWN.OUI, smartData.WWN.ID)
@@ -501,13 +626,18 @@ func parseSMARTOutput(output []byte, device string) (*DiskSMART, error) {
}
result.Attributes = parseSMARTAttributes(&smartData, result.Type)
- if result.Health == "" && result.Temperature == 0 && result.Attributes == nil {
+ if result.Health == "" && result.Temperature == 0 && result.Attributes == nil && !result.Standby {
return nil, errSMARTDataUnavailable
}
return result, nil
}
+func isStandbyPowerMode(powerMode string) bool {
+ mode := strings.ToLower(strings.TrimSpace(powerMode))
+ return strings.Contains(mode, "standby") || strings.Contains(mode, "sleep")
+}
+
// parseSMARTAttributes extracts normalized SMART attributes from smartctl JSON output.
func parseSMARTAttributes(data *smartctlJSON, diskType string) *SMARTAttributes {
attrs := &SMARTAttributes{}
diff --git a/internal/smartctl/collector_coverage_test.go b/internal/smartctl/collector_coverage_test.go
index 8c11f092d4..6eafa3b1c7 100644
--- a/internal/smartctl/collector_coverage_test.go
+++ b/internal/smartctl/collector_coverage_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "io/fs"
"os/exec"
"strings"
"testing"
@@ -20,6 +21,15 @@ func mustMarshalLSBLK(t *testing.T, devices []lsblkDevice) []byte {
return out
}
+type fakeDirEntry struct {
+ name string
+}
+
+func (e fakeDirEntry) Name() string { return e.name }
+func (e fakeDirEntry) IsDir() bool { return false }
+func (e fakeDirEntry) Type() fs.FileMode { return 0 }
+func (e fakeDirEntry) Info() (fs.FileInfo, error) { return nil, nil }
+
func TestListBlockDevices(t *testing.T) {
origRun := runCommandOutput
origGOOS := runtimeGOOS
@@ -49,8 +59,13 @@ func TestListBlockDevices(t *testing.T) {
func TestListBlockDevicesFreeBSD(t *testing.T) {
origRun := runCommandOutput
+ origReadDir := readDir
origGOOS := runtimeGOOS
- t.Cleanup(func() { runCommandOutput = origRun; runtimeGOOS = origGOOS })
+ t.Cleanup(func() {
+ runCommandOutput = origRun
+ readDir = origReadDir
+ runtimeGOOS = origGOOS
+ })
runtimeGOOS = "freebsd"
runCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
@@ -59,6 +74,14 @@ func TestListBlockDevicesFreeBSD(t *testing.T) {
}
return []byte("ada0 da0 nvd0\n"), nil
}
+ readDir = func(string) ([]fs.DirEntry, error) {
+ return []fs.DirEntry{
+ fakeDirEntry{name: "ada0"},
+ fakeDirEntry{name: "da0"},
+ fakeDirEntry{name: "nvd0"},
+ fakeDirEntry{name: "ada0p1"},
+ }, nil
+ }
devices, err := listBlockDevices(context.Background(), nil)
if err != nil {
@@ -71,13 +94,21 @@ func TestListBlockDevicesFreeBSD(t *testing.T) {
func TestListBlockDevicesFreeBSDWithExcludes(t *testing.T) {
origRun := runCommandOutput
+ origReadDir := readDir
origGOOS := runtimeGOOS
- t.Cleanup(func() { runCommandOutput = origRun; runtimeGOOS = origGOOS })
+ t.Cleanup(func() {
+ runCommandOutput = origRun
+ readDir = origReadDir
+ runtimeGOOS = origGOOS
+ })
runtimeGOOS = "freebsd"
runCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
return []byte("ada0 da0 nvd0\n"), nil
}
+ readDir = func(string) ([]fs.DirEntry, error) {
+ return nil, nil
+ }
devices, err := listBlockDevices(context.Background(), []string{"da0"})
if err != nil {
@@ -225,7 +256,7 @@ func TestCollectDeviceSMARTStandby(t *testing.T) {
timeNow = func() time.Time { return fixed }
execLookPath = func(string) (string, error) { return "smartctl", nil }
runCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
- return exec.CommandContext(ctx, "sh", "-c", "exit 2").Output()
+ return exec.CommandContext(ctx, "sh", "-c", "exit 3").Output()
}
result, err := collectDeviceSMART(context.Background(), "/dev/sda")
@@ -379,14 +410,92 @@ func TestCollectDeviceSMARTFreeBSDAdaFallback(t *testing.T) {
if result == nil || result.Temperature != 37 || !result.LastUpdated.Equal(fixed) {
t.Fatalf("unexpected result: %#v", result)
}
- if len(attempts) != 2 {
- t.Fatalf("expected 2 attempts, got %d", len(attempts))
+ if len(attempts) != 1 {
+ t.Fatalf("expected 1 attempt, got %d", len(attempts))
+ }
+ if len(attempts[0]) < 2 || attempts[0][0] != "-d" || attempts[0][1] != "sat" {
+ t.Fatalf("expected sat probe on first attempt, got %v", attempts[0])
+ }
+}
+
+func TestListBlockDevicesFreeBSDFallsBackToDevEntries(t *testing.T) {
+ origRun := runCommandOutput
+ origReadDir := readDir
+ origGOOS := runtimeGOOS
+ t.Cleanup(func() {
+ runCommandOutput = origRun
+ readDir = origReadDir
+ runtimeGOOS = origGOOS
+ })
+
+ runtimeGOOS = "freebsd"
+ runCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return []byte("\n"), nil
+ }
+ readDir = func(string) ([]fs.DirEntry, error) {
+ return []fs.DirEntry{
+ fakeDirEntry{name: "ada0"},
+ fakeDirEntry{name: "da0"},
+ fakeDirEntry{name: "nvd0"},
+ fakeDirEntry{name: "nda0"},
+ fakeDirEntry{name: "ada0p2"},
+ fakeDirEntry{name: "pass0"},
+ }, nil
+ }
+
+ devices, err := listBlockDevices(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("listBlockDevices error: %v", err)
+ }
+ if len(devices) != 4 || devices[0] != "/dev/ada0" || devices[1] != "/dev/da0" || devices[2] != "/dev/nda0" || devices[3] != "/dev/nvd0" {
+ t.Fatalf("unexpected devices from /dev fallback: %#v", devices)
+ }
+}
+
+func TestCollectDeviceSMARTFreeBSDPrefersTypedProbe(t *testing.T) {
+ origRun := runCommandOutput
+ origLook := execLookPath
+ origNow := timeNow
+ origGOOS := runtimeGOOS
+ t.Cleanup(func() {
+ runCommandOutput = origRun
+ execLookPath = origLook
+ timeNow = origNow
+ runtimeGOOS = origGOOS
+ })
+
+ fixed := time.Date(2024, 4, 7, 8, 9, 10, 0, time.UTC)
+ timeNow = func() time.Time { return fixed }
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+ runtimeGOOS = "freebsd"
+
+ var attempts [][]string
+ runCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ attempts = append(attempts, append([]string(nil), args...))
+
+ if len(args) >= 2 && args[0] == "-d" && args[1] == "sat" {
+ payload := smartctlJSON{}
+ payload.Device.Protocol = "ATA"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+ payload.Temperature.Current = 39
+ out, _ := json.Marshal(payload)
+ return out, nil
+ }
+
+ return exec.CommandContext(ctx, "sh", "-c", "exit 2").Output()
}
- if len(attempts[0]) >= 2 && attempts[0][0] == "-d" {
- t.Fatalf("expected first attempt without explicit device type, got %v", attempts[0])
+
+ result, err := collectDeviceSMART(context.Background(), "/dev/ada0")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil || result.Standby || result.Temperature != 39 || !result.LastUpdated.Equal(fixed) {
+ t.Fatalf("unexpected result: %#v", result)
}
- if len(attempts[1]) < 2 || attempts[1][0] != "-d" || attempts[1][1] != "sat" {
- t.Fatalf("expected sat fallback on second attempt, got %v", attempts[1])
+ if len(attempts) != 1 || len(attempts[0]) < 2 || attempts[0][0] != "-d" || attempts[0][1] != "sat" {
+ t.Fatalf("expected first probe to use -d sat, got %v", attempts)
}
}
diff --git a/internal/smartctl/collector_test.go b/internal/smartctl/collector_test.go
index a46076ce4a..4e44159cd6 100644
--- a/internal/smartctl/collector_test.go
+++ b/internal/smartctl/collector_test.go
@@ -1,6 +1,7 @@
package smartctl
import (
+ "encoding/json"
"testing"
)
@@ -431,6 +432,34 @@ func TestParseSMARTAttributes_Standby(t *testing.T) {
}
}
+func TestParseSMARTOutputStandbyPowerMode(t *testing.T) {
+ payload := smartctlJSON{
+ ModelName: "WDC WD40EFRX",
+ SerialNumber: "WD-123",
+ PowerMode: "STANDBY",
+ }
+ payload.Device.Protocol = "ATA"
+
+ out, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal payload: %v", err)
+ }
+
+ result, err := parseSMARTOutput(out, "/dev/ada0")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil {
+ t.Fatal("expected result")
+ }
+ if !result.Standby {
+ t.Fatalf("expected standby result, got %#v", result)
+ }
+ if result.Model != "WDC WD40EFRX" || result.Serial != "WD-123" {
+ t.Fatalf("expected model/serial to be preserved, got %#v", result)
+ }
+}
+
func TestParseRawValue(t *testing.T) {
tests := []struct {
name string