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.

Forward-port SMART collector hardening

rcourtman24fc9a019bdd
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 9940d2ab77..a87fad5066 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -124,6 +124,15 @@ management, and fleet control surfaces.
1. Add or change install-command generation, canonical /api/auto-register behavior, or installer download behavior through the owned `internal/api/` files above.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
+ That runtime-side ownership includes local disk telemetry collection in
+ `internal/hostagent/smartctl.go`. Linux SMART discovery must prefer
+ `smartctl --scan-open` typed targets before generic block-device fallback so
+ controller-backed disks keep their canonical SMART and wearout coverage.
+ FreeBSD SMART probing must retry through the canonical typed and untyped
+ device modes and the SCT temperature status path before settling on standby
+ or no-data results, and partial or plain-text smartctl output must still
+ preserve model, serial, health, and temperature data through the same
+ host-agent runtime boundary instead of leaving monitoring to guess.
4. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.
The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.
4. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
diff --git a/internal/hostagent/agent_metrics_test.go b/internal/hostagent/agent_metrics_test.go
index a7835e46cd..91bb363f2e 100644
--- a/internal/hostagent/agent_metrics_test.go
+++ b/internal/hostagent/agent_metrics_test.go
@@ -241,4 +241,47 @@ func TestBuildReport(t *testing.T) {
}
mc.smartLocalFn = nil
})
+
+ t.Run("SMART collection preserves typed controller-backed attributes", func(t *testing.T) {
+ used := 6
+ spare := 94
+ mc.smartLocalFn = func(_ context.Context, _ []string) ([]DiskSMART, error) {
+ return []DiskSMART{
+ {
+ Device: "/dev/sda [megaraid,7]",
+ Model: "RAID SSD",
+ Type: "nvme",
+ Health: "PASSED",
+ Attributes: &SMARTAttributes{
+ PercentageUsed: &used,
+ AvailableSpare: &spare,
+ },
+ },
+ }, nil
+ }
+ mc.goos = "linux"
+
+ report, err := agent.buildReport(context.Background())
+ if err != nil {
+ t.Fatalf("buildReport failed: %v", err)
+ }
+ if len(report.Sensors.SMART) != 1 {
+ t.Fatalf("Expected 1 SMART disk, got %d", len(report.Sensors.SMART))
+ }
+
+ disk := report.Sensors.SMART[0]
+ if disk.Device != "/dev/sda [megaraid,7]" {
+ t.Fatalf("Expected typed controller-backed device label, got %s", disk.Device)
+ }
+ if disk.Attributes == nil {
+ t.Fatal("expected SMART attributes to be preserved")
+ }
+ if disk.Attributes.PercentageUsed == nil || *disk.Attributes.PercentageUsed != used {
+ t.Fatalf("expected PercentageUsed=%d, got %#v", used, disk.Attributes.PercentageUsed)
+ }
+ if disk.Attributes.AvailableSpare == nil || *disk.Attributes.AvailableSpare != spare {
+ t.Fatalf("expected AvailableSpare=%d, got %#v", spare, disk.Attributes.AvailableSpare)
+ }
+ mc.smartLocalFn = nil
+ })
}
diff --git a/internal/hostagent/smartctl.go b/internal/hostagent/smartctl.go
index 656bc4d24d..940e035228 100644
--- a/internal/hostagent/smartctl.go
+++ b/internal/hostagent/smartctl.go
@@ -9,7 +9,9 @@ import (
"os"
"os/exec"
"path/filepath"
+ "regexp"
"runtime"
+ "sort"
"strconv"
"strings"
"time"
@@ -19,6 +21,7 @@ import (
const smartctlComponent = "smartctl_collector"
const maxCommandOutputBytes = 1 << 20 // 1 MiB
+const smartctlStandbyExitStatus = 3
var (
errCommandOutputTooLarge = errors.New("command output exceeds size limit")
@@ -27,8 +30,9 @@ var (
smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
return runCommandOutputLimited(ctx, maxCommandOutputBytes, name, args...)
}
- readDir = os.ReadDir
- osStat = os.Stat
+ readDir = os.ReadDir
+ smartctlReadFile = os.ReadFile
+ smartctlEvalSymlinks = filepath.EvalSymlinks
timeNow = time.Now
runtimeGOOS = runtime.GOOS
@@ -68,10 +72,6 @@ type SMARTAttributes struct {
UnsafeShutdowns *int64 `json:"unsafeShutdowns,omitempty"`
}
-type smartStatusJSON struct {
- Passed bool `json:"passed"`
-}
-
type nvmeSmartHealthInformationLogJSON struct {
Temperature int `json:"temperature"`
AvailableSpare int `json:"available_spare"`
@@ -82,8 +82,6 @@ type nvmeSmartHealthInformationLogJSON struct {
PowerCycles int64 `json:"power_cycles"`
}
-// smartctlJSON represents the JSON output from smartctl --json.
-// lsblkJSON is the JSON output from lsblk -J.
type lsblkJSON struct {
Blockdevices []lsblkDevice `json:"blockdevices"`
}
@@ -139,7 +137,11 @@ var linuxSMARTVirtualSubsystemTokens = []string{
"zfs",
}
+// smartctlJSON represents the JSON output from smartctl --json=o.
type smartctlJSON struct {
+ Smartctl struct {
+ Output []string `json:"output"`
+ } `json:"smartctl"`
Device struct {
Name string `json:"name"`
Type string `json:"type"`
@@ -159,7 +161,6 @@ type smartctlJSON struct {
Temperature struct {
Current int `json:"current"`
} `json:"temperature"`
- // ATA SMART attributes table
ATASmartAttributes struct {
Table []struct {
ID int `json:"id"`
@@ -173,40 +174,74 @@ type smartctlJSON struct {
} `json:"raw"`
} `json:"table"`
} `json:"ata_smart_attributes"`
- // NVMe-specific health information
+ ATASCTStatus struct {
+ Current struct {
+ Value int `json:"value"`
+ } `json:"current"`
+ } `json:"ata_sct_status"`
NVMeSmartHealthInformationLog *nvmeSmartHealthInformationLogJSON `json:"nvme_smart_health_information_log"`
PowerMode string `json:"power_mode"`
}
+type smartTextFallback struct {
+ Model string
+ Serial string
+ Type string
+ Health string
+ Temperature int
+ Standby bool
+}
+
+var (
+ smartTextTempAttributeRE = regexp.MustCompile(`^\s*(190|194)\s+\S+.*-\s+(\d{1,3})\b`)
+ smartTextCurrentTempRE = regexp.MustCompile(`(?i)^current temperature:\s*(\d{1,3})\b`)
+ smartTextTemperatureRE = regexp.MustCompile(`(?i)^temperature:\s*(\d{1,3})\b`)
+)
+
+type smartctlTarget struct {
+ Path string
+ DeviceType string
+}
+
+func (t smartctlTarget) displayName() string {
+ name := filepath.Base(strings.TrimSpace(t.Path))
+ if name == "" || name == "." || name == string(filepath.Separator) {
+ name = strings.TrimSpace(t.Path)
+ }
+ if t.DeviceType == "" {
+ return name
+ }
+ return name + " [" + t.DeviceType + "]"
+}
+
// CollectSMARTLocal collects S.M.A.R.T. data from all local block devices.
// The diskExclude parameter specifies patterns for devices to skip (e.g., "sda", "/dev/nvme*", "*cache*").
func CollectSMARTLocal(ctx context.Context, diskExclude []string) ([]DiskSMART, error) {
- // List block devices
- devices, err := listBlockDevices(ctx, diskExclude)
+ targets, err := listSMARTTargets(ctx, diskExclude)
if err != nil {
log.Debug().Err(err).Msg("failed to list block devices for SMART collection")
return nil, fmt.Errorf("list block devices for SMART collection: %w", err)
}
- if len(devices) == 0 {
+ if len(targets) == 0 {
return nil, nil
}
var results []DiskSMART
- for _, dev := range devices {
- smart, err := collectDeviceSMART(ctx, dev)
+ for _, target := range targets {
+ smart, err := collectSMARTTarget(ctx, target)
if err != nil {
if errors.Is(err, errSMARTDataUnavailable) {
log.Debug().
Str("component", smartctlComponent).
Str("action", "skip_no_smart_data").
- Str("device", dev).
+ Str("device", target.displayName()).
Msg("Device returned no usable SMART data, skipping")
} else {
log.Debug().
Str("component", smartctlComponent).
Str("action", "collect_device_smart_failed").
- Str("device", dev).
+ Str("device", target.Path).
Err(err).
Msg("Failed to collect SMART data for device")
}
@@ -220,42 +255,246 @@ func CollectSMARTLocal(ctx context.Context, diskExclude []string) ([]DiskSMART,
log.Debug().
Str("component", smartctlComponent).
Str("action", "collect_local_complete").
- Int("devices_discovered", len(devices)).
+ Int("devices_discovered", len(targets)).
Int("devices_collected", len(results)).
Msg("Completed SMART collection for local devices")
return results, nil
}
+func listSMARTTargets(ctx context.Context, diskExclude []string) ([]smartctlTarget, error) {
+ if runtimeGOOS == "linux" {
+ return listSMARTTargetsLinux(ctx, diskExclude)
+ }
+
+ devices, err := listBlockDevices(ctx, diskExclude)
+ if err != nil {
+ return nil, err
+ }
+ return smartctlTargetsFromDevices(devices), nil
+}
+
+func smartctlTargetsFromDevices(devices []string) []smartctlTarget {
+ if len(devices) == 0 {
+ return nil
+ }
+ targets := make([]smartctlTarget, 0, len(devices))
+ for _, device := range devices {
+ targets = append(targets, smartctlTarget{Path: device})
+ }
+ return targets
+}
+
+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 {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Err(err).
+ Msg("Failed to enumerate Linux SMART targets via smartctl --scan-open, falling back to block device discovery")
+ }
+
+ devices, fallbackErr := listBlockDevicesLinux(ctx, diskExclude)
+ if fallbackErr != nil {
+ return nil, fallbackErr
+ }
+ return smartctlTargetsFromDevices(devices), nil
+}
+
+func listSMARTTargetsLinuxFromScanOpen(ctx context.Context, diskExclude []string) ([]smartctlTarget, error) {
+ smartctlPath, err := execLookPath("smartctl")
+ if err != nil {
+ return nil, fmt.Errorf("look up smartctl binary: %w", err)
+ }
+
+ output, err := smartRunCommandOutput(ctx, smartctlPath, "--scan-open")
+ if err != nil {
+ return nil, err
+ }
+
+ return parseSmartctlScanOpenTargets(output, diskExclude), nil
+}
+
+func parseSmartctlScanOpenTargets(output []byte, diskExclude []string) []smartctlTarget {
+ lines := strings.Split(string(output), "\n")
+ targets := make([]smartctlTarget, 0, len(lines))
+ typedByPath := make(map[string]bool)
+ seen := make(map[string]struct{})
+
+ for _, rawLine := range lines {
+ line := strings.TrimSpace(rawLine)
+ if line == "" {
+ continue
+ }
+ if idx := strings.Index(line, "#"); idx >= 0 {
+ line = strings.TrimSpace(line[:idx])
+ }
+ if line == "" {
+ continue
+ }
+
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
+ continue
+ }
+
+ path := strings.TrimSpace(fields[0])
+ if path == "" || (!strings.HasPrefix(path, "/") && !strings.HasPrefix(path, "-")) {
+ continue
+ }
+
+ deviceType := ""
+ for i := 1; i < len(fields)-1; i++ {
+ if fields[i] == "-d" {
+ deviceType = strings.TrimSpace(fields[i+1])
+ break
+ }
+ }
+
+ name := filepath.Base(path)
+ if matchesDeviceExclude(name, path, diskExclude) {
+ continue
+ }
+
+ key := path + "\x00" + deviceType
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ if deviceType != "" {
+ typedByPath[path] = true
+ }
+
+ targets = append(targets, smartctlTarget{
+ Path: path,
+ DeviceType: deviceType,
+ })
+ }
+
+ if len(targets) == 0 {
+ return nil
+ }
+
+ filtered := make([]smartctlTarget, 0, len(targets))
+ for _, target := range targets {
+ if target.DeviceType == "" && typedByPath[target.Path] {
+ continue
+ }
+ filtered = append(filtered, target)
+ }
+ return filtered
+}
+
// listBlockDevices returns a list of block devices suitable for SMART queries.
// Devices matching any of the diskExclude patterns are skipped.
func listBlockDevices(ctx context.Context, diskExclude []string) ([]string, error) {
if runtimeGOOS == "freebsd" {
- devices, err := listBlockDevicesFreeBSD(ctx, diskExclude)
- if err != nil {
- return nil, fmt.Errorf("list FreeBSD block devices: %w", err)
- }
+ return listBlockDevicesFreeBSD(ctx, diskExclude)
+ }
+ return listBlockDevicesLinux(ctx, diskExclude)
+}
+
+func listBlockDevicesLinux(ctx context.Context, diskExclude []string) ([]string, error) {
+ devices, err := listBlockDevicesLinuxFromSysfs(diskExclude)
+ if err == nil {
return devices, nil
}
- devices, err := listBlockDevicesLinux(ctx, diskExclude)
+ log.Debug().
+ Str("component", smartctlComponent).
+ Err(err).
+ Msg("sysfs device discovery failed, falling back to lsblk")
+
+ return listBlockDevicesLinuxFromLSBLK(ctx, diskExclude)
+}
+
+func listBlockDevicesLinuxFromSysfs(diskExclude []string) ([]string, error) {
+ entries, err := readDir("/sys/block")
if err != nil {
- return nil, fmt.Errorf("list Linux block devices: %w", err)
+ return nil, err
+ }
+
+ var devices []string
+ for _, entry := range entries {
+ name := strings.TrimSpace(entry.Name())
+ if name == "" {
+ continue
+ }
+
+ devicePath := "/dev/" + name
+ if reason := linuxSMARTSkipReasonSysfs(name); reason != "" {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "skip_virtual_device").
+ Str("device", devicePath).
+ Str("reason", reason).
+ Msg("Skipping non-physical device for SMART collection")
+ continue
+ }
+ if matchesDeviceExclude(name, devicePath, diskExclude) {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "skip_excluded_device").
+ Str("device", devicePath).
+ Msg("Skipping excluded device for SMART collection")
+ continue
+ }
+ devices = append(devices, devicePath)
}
+
return devices, nil
}
-// listBlockDevicesLinux uses lsblk JSON output to find physical disks on Linux,
-// filtering out virtual/logical devices that cannot provide SMART data.
-func listBlockDevicesLinux(ctx context.Context, diskExclude []string) ([]string, error) {
+func linuxSMARTSkipReasonSysfs(name string) string {
+ lowerName := strings.ToLower(name)
+ for _, prefix := range linuxSMARTVirtualPrefixes {
+ if strings.HasPrefix(lowerName, prefix) {
+ return "virtual/logical device prefix"
+ }
+ }
+
+ blockPath := filepath.Join("/sys/block", name)
+ if resolved, err := smartctlEvalSymlinks(blockPath); err == nil && strings.Contains(strings.ToLower(resolved), "/virtual/") {
+ return "virtual block device"
+ }
+
+ subsystemPath := filepath.Join(blockPath, "device", "subsystem")
+ if resolved, err := smartctlEvalSymlinks(subsystemPath); err == nil {
+ lowerResolved := strings.ToLower(resolved)
+ for _, token := range linuxSMARTVirtualSubsystemTokens {
+ if strings.Contains(lowerResolved, token) {
+ return "virtual/logical subsystem"
+ }
+ }
+ }
+
+ metadata := strings.ToLower(strings.TrimSpace(
+ readTrimmedFile(filepath.Join(blockPath, "device", "vendor")) + " " +
+ readTrimmedFile(filepath.Join(blockPath, "device", "model")),
+ ))
+ for _, token := range linuxSMARTVirtualMetadataTokens {
+ if strings.Contains(metadata, token) {
+ return "virtual disk model/vendor signature"
+ }
+ }
+
+ return ""
+}
+
+func readTrimmedFile(path string) string {
+ data, err := smartctlReadFile(path)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(data))
+}
+
+func listBlockDevicesLinuxFromLSBLK(ctx context.Context, diskExclude []string) ([]string, error) {
output, err := smartRunCommandOutput(ctx, "lsblk", "-J", "-d", "-o", "NAME,TYPE,TRAN,MODEL,VENDOR,SUBSYSTEMS")
if err != nil {
- // Fall back to sysfs enumeration for minimal hosts/images where lsblk is unavailable.
- log.Debug().Err(err).Msg("lsblk device discovery failed, falling back to /sys/block")
- devices, fallbackErr := listBlockDevicesLinuxSysfs(diskExclude)
- if fallbackErr != nil {
- return nil, fmt.Errorf("linux block-device discovery failed: lsblk error: %w; /sys/block fallback error: %v", err, fallbackErr)
- }
- return devices, nil
+ return nil, err
}
var data lsblkJSON
@@ -329,27 +568,59 @@ func linuxSMARTSkipReason(device lsblkDevice) string {
return ""
}
-func listBlockDevicesLinuxSysfs(diskExclude []string) ([]string, error) {
- entries, err := readDir("/sys/block")
- if err != nil {
- return nil, err
+// listBlockDevicesFreeBSD uses sysctl kern.disks and /dev fallback to find disks on FreeBSD.
+func listBlockDevicesFreeBSD(ctx context.Context, diskExclude []string) ([]string, error) {
+ names, sysctlErr := freeBSDDiskNamesFromSysctl(ctx)
+ if sysctlErr != nil {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Err(sysctlErr).
+ Msg("Failed to enumerate FreeBSD disks from kern.disks")
}
- var devices []string
- for _, entry := range entries {
- name := strings.TrimSpace(entry.Name())
- if name == "" || isVirtualLinuxBlockDevice(name) {
- continue
+ fallbackNames, fallbackErr := freeBSDDiskNamesFromDev()
+ if fallbackErr != nil {
+ log.Debug().
+ Str("component", smartctlComponent).
+ 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)
+ }
+ }
- // Keep only concrete device-backed entries and skip synthetic block devices.
- if _, err := osStat(filepath.Join("/sys/block", name, "device")); err != nil {
- continue
+ 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")
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "skip_excluded_device").
+ Str("device", devicePath).
+ Msg("Skipping excluded device for SMART collection")
continue
}
devices = append(devices, devicePath)
@@ -358,43 +629,91 @@ func listBlockDevicesLinuxSysfs(diskExclude []string) ([]string, error) {
return devices, nil
}
-func isVirtualLinuxBlockDevice(name string) bool {
- for _, prefix := range linuxSMARTVirtualPrefixes {
- if strings.HasPrefix(name, prefix) {
- return true
- }
- }
- return strings.HasPrefix(name, "fd") ||
- strings.HasPrefix(name, "sr")
-}
-
-// listBlockDevicesFreeBSD uses sysctl kern.disks to find disks on FreeBSD.
-func listBlockDevicesFreeBSD(ctx context.Context, diskExclude []string) ([]string, error) {
+func freeBSDDiskNamesFromSysctl(ctx context.Context) ([]string, error) {
output, err := smartRunCommandOutput(ctx, "sysctl", "-n", "kern.disks")
if err != nil {
return nil, fmt.Errorf("run sysctl kern.disks: %w", 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("component", smartctlComponent).
- Str("action", "skip_excluded_device").
- 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:
@@ -412,7 +731,6 @@ func matchesDeviceExclude(name, devicePath string, excludePatterns []string) boo
continue
}
- // Contains pattern: *substring*
if strings.HasPrefix(pattern, "*") && strings.HasSuffix(pattern, "*") && len(pattern) > 2 {
substring := pattern[1 : len(pattern)-1]
if strings.Contains(name, substring) || strings.Contains(devicePath, substring) {
@@ -421,7 +739,6 @@ func matchesDeviceExclude(name, devicePath string, excludePatterns []string) boo
continue
}
- // Prefix pattern: prefix*
if strings.HasSuffix(pattern, "*") {
prefix := pattern[:len(pattern)-1]
if strings.HasPrefix(name, prefix) || strings.HasPrefix(devicePath, prefix) {
@@ -430,7 +747,6 @@ func matchesDeviceExclude(name, devicePath string, excludePatterns []string) boo
continue
}
- // Exact match against name or full path
if name == pattern || devicePath == pattern {
return true
}
@@ -441,90 +757,252 @@ func matchesDeviceExclude(name, devicePath string, excludePatterns []string) boo
// collectDeviceSMART runs smartctl on a single device and parses the result.
func collectDeviceSMART(ctx context.Context, device string) (*DiskSMART, error) {
- // Use timeout to avoid hanging on slow/unresponsive disks
+ return collectSMARTTarget(ctx, smartctlTarget{Path: device})
+}
+
+func collectSMARTTarget(ctx context.Context, target smartctlTarget) (*DiskSMART, error) {
cmdCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
- // Check if smartctl is available
smartctlPath, err := execLookPath("smartctl")
if err != nil {
return nil, fmt.Errorf("look up smartctl binary: %w", err)
}
- // Run smartctl with standby check to avoid waking sleeping drives
- // -n standby: don't check if drive is in standby (return exit code 2)
- // -i: device info
- // -A: attributes (for temperature)
- // --json=o: output original smartctl JSON format
- output, err := smartRunCommandOutput(cmdCtx, smartctlPath, "-n", "standby", "-i", "-A", "-H", "--json=o", device)
+ attempts := smartctlProbeAttempts(target)
+ var firstParsed *DiskSMART
+ var firstStandby *DiskSMART
+ var lastErr error
- // 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()
- // Check for standby (bit 1 set in exit status)
- if exitCode&2 != 0 {
+ for i, args := range attempts {
+ output, err := smartRunCommandOutput(cmdCtx, smartctlPath, args...)
+ if err != nil {
+ var exitErr *exec.ExitError
+ if errors.As(err, &exitErr) {
+ exitCode := exitErr.ExitCode()
+ if (exitCode == smartctlStandbyExitStatus || exitCode&2 != 0) && len(output) == 0 {
+ standbyResult := &DiskSMART{
+ Device: filepath.Base(target.Path),
+ Standby: true,
+ LastUpdated: timeNow(),
+ }
+ if runtimeGOOS == "freebsd" && i < len(attempts)-1 && target.DeviceType == "" {
+ if firstStandby == nil {
+ firstStandby = standbyResult
+ }
+ continue
+ }
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "device_in_standby").
+ Str("device", filepath.Base(target.Path)).
+ Msg("Skipping SMART collection for standby device")
+ return standbyResult, nil
+ }
+ if len(output) == 0 {
+ lastErr = fmt.Errorf("run smartctl for %s: %w", target.Path, err)
+ continue
+ }
log.Debug().
Str("component", smartctlComponent).
- Str("action", "device_in_standby").
- Str("device", filepath.Base(device)).
- Msg("Skipping SMART collection for standby device")
- return &DiskSMART{
- Device: filepath.Base(device),
- Standby: true,
- LastUpdated: timeNow(),
- }, nil
- }
- // Other exit codes might still have valid JSON output
- // Continue parsing if we got output
- if len(output) == 0 {
- return nil, fmt.Errorf("run smartctl for %s: %w", device, err)
+ Str("action", "collect_device_smart_nonzero_exit").
+ Str("device", filepath.Base(target.Path)).
+ Int("exit_code", exitCode).
+ Msg("smartctl returned non-zero exit status with JSON output")
+ } else {
+ lastErr = fmt.Errorf("run smartctl for %s: %w", target.Path, err)
+ continue
}
+ }
+
+ result, parseErr := parseSMARTOutput(output, target)
+ if parseErr != nil {
+ lastErr = parseErr
+ continue
+ }
+ result = enrichFreeBSDSCTTemperature(cmdCtx, smartctlPath, args, target, result)
+ if firstParsed == nil {
+ firstParsed = result
+ }
+ if !shouldRetryFreeBSDSMART(target.Path, result, i, len(attempts)) {
log.Debug().
Str("component", smartctlComponent).
- Str("action", "collect_device_smart_nonzero_exit").
- Str("device", filepath.Base(device)).
- Int("exit_code", exitCode).
- Msg("smartctl returned non-zero exit status with JSON output")
- } else {
- return nil, fmt.Errorf("run smartctl for %s: %w", device, err)
+ Str("action", "collect_device_smart_success").
+ Str("device", result.Device).
+ Str("type", result.Type).
+ Str("model", result.Model).
+ Int("temperature", result.Temperature).
+ Str("health", result.Health).
+ Msg("collected SMART data")
+ return result, nil
+ }
+ }
+
+ if firstParsed != nil {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "collect_device_smart_success").
+ Str("device", firstParsed.Device).
+ Str("type", firstParsed.Type).
+ Str("model", firstParsed.Model).
+ Int("temperature", firstParsed.Temperature).
+ Str("health", firstParsed.Health).
+ Msg("collected SMART data")
+ return firstParsed, nil
+ }
+ if firstStandby != nil {
+ log.Debug().
+ Str("component", smartctlComponent).
+ Str("action", "device_in_standby").
+ Str("device", filepath.Base(target.Path)).
+ Msg("Skipping SMART collection for standby device")
+ return firstStandby, nil
+ }
+ if lastErr != nil {
+ return nil, lastErr
+ }
+ return nil, errSMARTDataUnavailable
+}
+
+func smartctlProbeAttempts(target smartctlTarget) [][]string {
+ device := target.Path
+ if target.DeviceType != "" {
+ return [][]string{
+ smartctlArgs(device, target.DeviceType),
}
}
- // Parse JSON output
+ 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, ""))
+ }
+ }
+
+ return [][]string{
+ smartctlArgs(device, ""),
+ }
+}
+
+func smartctlArgs(device, deviceType string) []string {
+ args := []string{}
+ if deviceType != "" {
+ args = append(args, "-d", deviceType)
+ }
+ args = append(args, "-n", "standby,"+strconv.Itoa(smartctlStandbyExitStatus), "-i", "-A", "-H", "--json=o", device)
+ return args
+}
+
+func smartctlArgsWithLog(args []string, logPage string) []string {
+ if logPage == "" || len(args) == 0 {
+ return append([]string(nil), args...)
+ }
+ for i := 0; i < len(args)-1; i++ {
+ if args[i] == "-l" && args[i+1] == logPage {
+ return append([]string(nil), args...)
+ }
+ }
+
+ deviceIndex := len(args) - 1
+ withLog := make([]string, 0, len(args)+2)
+ withLog = append(withLog, args[:deviceIndex]...)
+ withLog = append(withLog, "-l", logPage)
+ withLog = append(withLog, args[deviceIndex:]...)
+ return withLog
+}
+
+func freeBSDSmartctlDeviceTypes(device string) []string {
+ if runtimeGOOS != "freebsd" {
+ return nil
+ }
+
+ switch {
+ case strings.HasPrefix(device, "ada"), strings.HasPrefix(device, "ad"):
+ return []string{"sat"}
+ case strings.HasPrefix(device, "da"):
+ return []string{"sat,auto", "scsi"}
+ case strings.HasPrefix(device, "nda"), strings.HasPrefix(device, "nvd"), strings.HasPrefix(device, "nvme"):
+ return []string{"nvme"}
+ default:
+ return nil
+ }
+}
+
+func shouldRetryFreeBSDSMART(device string, result *DiskSMART, attemptIndex, attemptCount int) bool {
+ if runtimeGOOS != "freebsd" || attemptIndex >= attemptCount-1 || result == nil {
+ return false
+ }
+ if result.Temperature > 0 {
+ return false
+ }
+ if result.Standby {
+ return true
+ }
+ return len(freeBSDSmartctlDeviceTypes(filepath.Base(device))) > 0
+}
+
+func enrichFreeBSDSCTTemperature(ctx context.Context, smartctlPath string, args []string, target smartctlTarget, current *DiskSMART) *DiskSMART {
+ if runtimeGOOS != "freebsd" || current == nil || current.Standby || current.Temperature > 0 {
+ return current
+ }
+ if len(freeBSDSmartctlDeviceTypes(filepath.Base(target.Path))) == 0 {
+ return current
+ }
+
+ sctArgs := smartctlArgsWithLog(args, "scttempsts")
+ if len(sctArgs) == len(args) {
+ return current
+ }
+
+ output, err := smartRunCommandOutput(ctx, smartctlPath, sctArgs...)
+ if err != nil {
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) || len(output) == 0 {
+ return current
+ }
+ }
+
+ sctResult, parseErr := parseSMARTOutput(output, target)
+ if parseErr != nil || sctResult == nil || sctResult.Temperature <= 0 {
+ return current
+ }
+ return sctResult
+}
+
+func parseSMARTOutput(output []byte, target smartctlTarget) (*DiskSMART, error) {
var smartData smartctlJSON
if err := json.Unmarshal(output, &smartData); err != nil {
- return nil, fmt.Errorf("parse smartctl JSON for %s: %w", device, err)
+ return parseSMARTTextOutput(string(output), target)
}
result := &DiskSMART{
- Device: filepath.Base(device),
+ Device: target.displayName(),
Model: smartData.ModelName,
Serial: smartData.SerialNumber,
Type: detectDiskType(smartData),
+ Standby: isStandbyPowerMode(smartData.PowerMode),
LastUpdated: timeNow(),
}
- // Build WWN string if available
if smartData.WWN.NAA != 0 {
result.WWN = formatWWN(smartData.WWN.NAA, smartData.WWN.OUI, smartData.WWN.ID)
}
- // Get temperature (different location for NVMe vs SATA).
- // Try top-level fields first, then fall back to ATA attributes 194/190.
if smartData.Temperature.Current > 0 {
result.Temperature = smartData.Temperature.Current
} else if smartData.NVMeSmartHealthInformationLog != nil && smartData.NVMeSmartHealthInformationLog.Temperature > 0 {
result.Temperature = smartData.NVMeSmartHealthInformationLog.Temperature
+ } else if smartData.ATASCTStatus.Current.Value > 0 {
+ result.Temperature = smartData.ATASCTStatus.Current.Value
} else {
- // Fallback: extract from ATA SMART attributes 194 (Temperature_Celsius)
- // or 190 (Airflow_Temperature_Cel). Some drives don't populate the
- // top-level temperature field.
for _, attr := range smartData.ATASmartAttributes.Table {
if attr.ID == 194 || attr.ID == 190 {
temp := int(parseRawValue(attr.Raw.String, attr.Raw.Value))
- if temp > 0 && temp < 150 { // sanity: valid operating range
+ if temp > 0 && temp < 150 {
result.Temperature = temp
break
}
@@ -532,46 +1010,171 @@ func collectDeviceSMART(ctx context.Context, device string) (*DiskSMART, error)
}
}
- // Get health status
- if smartData.SmartStatus == nil {
+ if smartData.SmartStatus != nil {
+ if smartData.SmartStatus.Passed {
+ result.Health = "PASSED"
+ } else {
+ result.Health = "FAILED"
+ }
+ }
+
+ applySMARTTextFallback(result, parseSMARTTextFallback(strings.Join(smartData.Smartctl.Output, "\n")))
+ if result.Health == "" {
result.Health = "UNKNOWN"
- } else if smartData.SmartStatus.Passed {
- result.Health = "PASSED"
- } else {
- result.Health = "FAILED"
}
- // Parse SMART attributes
result.Attributes = parseSMARTAttributes(&smartData, result.Type)
-
- // If the device returned no useful data at all, treat as unavailable
- // rather than reporting a misleading UNKNOWN/FAILED entry.
- if (result.Health == "" || result.Health == "UNKNOWN") && result.Temperature == 0 && result.Attributes == nil {
+ if result.Health == "UNKNOWN" && result.Temperature == 0 && result.Attributes == nil && !result.Standby {
return nil, errSMARTDataUnavailable
}
- log.Debug().
- Str("component", smartctlComponent).
- Str("action", "collect_device_smart_success").
- Str("device", result.Device).
- Str("type", result.Type).
- Str("model", result.Model).
- Int("temperature", result.Temperature).
- Str("health", result.Health).
- Msg("collected SMART data")
+ return result, nil
+}
+func parseSMARTTextOutput(text string, target smartctlTarget) (*DiskSMART, error) {
+ fallback := parseSMARTTextFallback(text)
+ result := &DiskSMART{
+ Device: target.displayName(),
+ Model: fallback.Model,
+ Serial: fallback.Serial,
+ Type: fallback.Type,
+ Temperature: fallback.Temperature,
+ Health: fallback.Health,
+ Standby: fallback.Standby,
+ LastUpdated: timeNow(),
+ }
+ if result.Type == "" {
+ switch {
+ case target.DeviceType == "nvme",
+ strings.HasPrefix(filepath.Base(target.Path), "nvme"),
+ strings.HasPrefix(filepath.Base(target.Path), "nvd"),
+ strings.HasPrefix(filepath.Base(target.Path), "nda"):
+ result.Type = "nvme"
+ default:
+ result.Type = "sata"
+ }
+ }
+ if result.Health == "" {
+ result.Health = "UNKNOWN"
+ }
+ if result.Health == "UNKNOWN" && result.Temperature == 0 && !result.Standby {
+ return nil, errSMARTDataUnavailable
+ }
return result, nil
}
+func applySMARTTextFallback(result *DiskSMART, fallback smartTextFallback) {
+ if result == nil {
+ return
+ }
+ if result.Model == "" && fallback.Model != "" {
+ result.Model = fallback.Model
+ }
+ if result.Serial == "" && fallback.Serial != "" {
+ result.Serial = fallback.Serial
+ }
+ if result.Type == "" && fallback.Type != "" {
+ result.Type = fallback.Type
+ }
+ if result.Health == "" && fallback.Health != "" {
+ result.Health = fallback.Health
+ }
+ if result.Temperature == 0 && fallback.Temperature > 0 {
+ result.Temperature = fallback.Temperature
+ }
+ if !result.Standby && fallback.Standby {
+ result.Standby = true
+ }
+}
+
+func parseSMARTTextFallback(text string) smartTextFallback {
+ var fallback smartTextFallback
+ for _, rawLine := range strings.Split(text, "\n") {
+ line := strings.TrimSpace(rawLine)
+ if line == "" {
+ continue
+ }
+ lower := strings.ToLower(line)
+ switch {
+ case strings.HasPrefix(lower, "device model:"):
+ fallback.Model = strings.TrimSpace(line[len("Device Model:"):])
+ case strings.HasPrefix(lower, "model number:"):
+ if fallback.Model == "" {
+ fallback.Model = strings.TrimSpace(line[len("Model Number:"):])
+ }
+ case strings.HasPrefix(lower, "product:"):
+ if fallback.Model == "" {
+ fallback.Model = strings.TrimSpace(line[len("Product:"):])
+ }
+ case strings.HasPrefix(lower, "serial number:"):
+ fallback.Serial = strings.TrimSpace(line[len("Serial Number:"):])
+ case strings.Contains(lower, "device is in standby mode"):
+ fallback.Standby = true
+ case strings.HasPrefix(lower, "smart overall-health self-assessment test result:"):
+ fallback.Health = parseSMARTHealthText(line)
+ case strings.HasPrefix(lower, "smart health status:"):
+ if fallback.Health == "" {
+ fallback.Health = parseSMARTHealthText(line)
+ }
+ case strings.Contains(lower, "transport protocol:") && strings.Contains(lower, "nvme"):
+ fallback.Type = "nvme"
+ case strings.Contains(lower, "transport protocol:") && strings.Contains(lower, "sas"):
+ fallback.Type = "sas"
+ case strings.Contains(lower, "sata version is:") || strings.Contains(lower, "ata version is:"):
+ if fallback.Type == "" {
+ fallback.Type = "sata"
+ }
+ }
+
+ if fallback.Temperature == 0 {
+ if matches := smartTextCurrentTempRE.FindStringSubmatch(line); len(matches) == 2 {
+ if temp, err := strconv.Atoi(matches[1]); err == nil && temp > 0 && temp < 150 {
+ fallback.Temperature = temp
+ continue
+ }
+ }
+ if matches := smartTextTemperatureRE.FindStringSubmatch(line); len(matches) == 2 && strings.Contains(lower, "celsius") {
+ if temp, err := strconv.Atoi(matches[1]); err == nil && temp > 0 && temp < 150 {
+ fallback.Temperature = temp
+ continue
+ }
+ }
+ if matches := smartTextTempAttributeRE.FindStringSubmatch(line); len(matches) == 3 {
+ if temp, err := strconv.Atoi(matches[2]); err == nil && temp > 0 && temp < 150 {
+ fallback.Temperature = temp
+ }
+ }
+ }
+ }
+ return fallback
+}
+
+func parseSMARTHealthText(line string) string {
+ lower := strings.ToLower(line)
+ switch {
+ case strings.Contains(lower, "passed"), strings.Contains(lower, "ok"):
+ return "PASSED"
+ case strings.Contains(lower, "failed"):
+ return "FAILED"
+ default:
+ return ""
+ }
+}
+
+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{}
hasData := false
if diskType == "nvme" {
- nvmeLog := data.NVMeSmartHealthInformationLog
- if nvmeLog != nil {
+ if data.NVMeSmartHealthInformationLog != nil {
hasData = true
+ nvmeLog := data.NVMeSmartHealthInformationLog
poh := nvmeLog.PowerOnHours
attrs.PowerOnHours = &poh
pc := nvmeLog.PowerCycles
@@ -586,27 +1189,26 @@ func parseSMARTAttributes(data *smartctlJSON, diskType string) *SMARTAttributes
attrs.UnsafeShutdowns = &us
}
} else {
- // SATA / SAS — iterate the ATA attributes table
for _, attr := range data.ATASmartAttributes.Table {
hasData = true
raw := parseRawValue(attr.Raw.String, attr.Raw.Value)
switch attr.ID {
- case 5: // Reallocated Sector Count
+ case 5:
v := raw
attrs.ReallocatedSectors = &v
- case 9: // Power-On Hours
+ case 9:
v := raw
attrs.PowerOnHours = &v
- case 12: // Power Cycle Count
+ case 12:
v := raw
attrs.PowerCycles = &v
- case 197: // Current Pending Sector Count
+ case 197:
v := raw
attrs.PendingSectors = &v
- case 198: // Offline Uncorrectable
+ case 198:
v := raw
attrs.OfflineUncorrectable = &v
- case 199: // UDMA CRC Error Count
+ case 199:
v := raw
attrs.UDMACRCErrors = &v
}
@@ -654,18 +1256,16 @@ func detectDiskType(data smartctlJSON) string {
case strings.Contains(protocol, "ata"), strings.Contains(protocol, "sata"):
return "sata"
default:
- // Try to infer from device type
devType := strings.ToLower(data.Device.Type)
if strings.Contains(devType, "nvme") {
return "nvme"
}
- return "sata" // default
+ return "sata"
}
}
// formatWWN formats WWN components into a standard string.
func formatWWN(naa, oui, id uint64) string {
- // Format as hex string: naa-oui-id
return strconv.FormatUint(naa, 16) + "-" +
strconv.FormatUint(oui, 16) + "-" +
strconv.FormatUint(id, 16)
diff --git a/internal/hostagent/smartctl_coverage_test.go b/internal/hostagent/smartctl_coverage_test.go
index 7c24ed13b1..8acd76c7d3 100644
--- a/internal/hostagent/smartctl_coverage_test.go
+++ b/internal/hostagent/smartctl_coverage_test.go
@@ -5,9 +5,9 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io/fs"
"os"
"os/exec"
- "path/filepath"
"strings"
"testing"
"time"
@@ -21,22 +21,90 @@ func mockLsblkJSON(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 forceLinuxLSBLKFallback(t *testing.T) {
+ t.Helper()
+
+ origGOOS := runtimeGOOS
+ origReadDir := readDir
+ origReadFile := smartctlReadFile
+ origEvalSymlinks := smartctlEvalSymlinks
+ t.Cleanup(func() {
+ runtimeGOOS = origGOOS
+ readDir = origReadDir
+ smartctlReadFile = origReadFile
+ smartctlEvalSymlinks = origEvalSymlinks
+ })
+
+ runtimeGOOS = "linux"
+ readDir = func(string) ([]os.DirEntry, error) {
+ return nil, errors.New("sysfs unavailable")
+ }
+ smartctlReadFile = func(string) ([]byte, error) { return nil, fs.ErrNotExist }
+ smartctlEvalSymlinks = func(string) (string, error) { return "", fs.ErrNotExist }
+}
+
func TestListBlockDevices(t *testing.T) {
origRun := smartRunCommandOutput
origGOOS := runtimeGOOS
+ origReadDir := readDir
+ origReadFile := smartctlReadFile
+ origEvalSymlinks := smartctlEvalSymlinks
t.Cleanup(func() { smartRunCommandOutput = origRun; runtimeGOOS = origGOOS })
+ t.Cleanup(func() {
+ readDir = origReadDir
+ smartctlReadFile = origReadFile
+ smartctlEvalSymlinks = origEvalSymlinks
+ })
runtimeGOOS = "linux"
- smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
- if name != "lsblk" {
- return nil, errors.New("unexpected command")
+ readDir = func(string) ([]os.DirEntry, error) {
+ return []os.DirEntry{
+ fakeDirEntry{name: "sda"},
+ fakeDirEntry{name: "nvme0n1"},
+ fakeDirEntry{name: "zd0"},
+ }, nil
+ }
+ smartctlReadFile = func(path string) ([]byte, error) {
+ switch path {
+ case "/sys/block/sda/device/vendor":
+ return []byte("ATA\n"), nil
+ case "/sys/block/sda/device/model":
+ return []byte("Samsung SSD 870 EVO\n"), nil
+ case "/sys/block/nvme0n1/device/model":
+ return []byte("Samsung SSD 980\n"), nil
+ default:
+ return nil, fs.ErrNotExist
+ }
+ }
+ smartctlEvalSymlinks = func(path string) (string, error) {
+ switch path {
+ case "/sys/block/sda":
+ return "/sys/devices/pci0000:00/0000:00:17.0/ata1/host0/target0:0:0/0:0:0:0/block/sda", nil
+ case "/sys/block/sda/device/subsystem":
+ return "/sys/bus/scsi", nil
+ case "/sys/block/nvme0n1":
+ return "/sys/devices/pci0000:00/0000:00:1d.0/nvme/nvme0/nvme0n1", nil
+ case "/sys/block/nvme0n1/device/subsystem":
+ return "/sys/bus/nvme", nil
+ case "/sys/block/zd0":
+ return "/sys/devices/virtual/block/zd0", nil
+ case "/sys/block/zd0/device/subsystem":
+ return "", fs.ErrNotExist
+ default:
+ return "", fs.ErrNotExist
}
- return mockLsblkJSON(
- lsblkDevice{Name: "sda", Type: "disk", Tran: "sata", Subsystems: "block:scsi:pci"},
- lsblkDevice{Name: "sda1", Type: "part", Tran: "sata"},
- lsblkDevice{Name: "sr0", Type: "rom"},
- lsblkDevice{Name: "nvme0n1", Type: "disk", Tran: "nvme", Subsystems: "block:nvme:pci"},
- ), nil
+ }
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return nil, errors.New("lsblk should not be called when sysfs enumeration succeeds")
}
devices, err := listBlockDevices(context.Background(), nil)
@@ -51,7 +119,8 @@ func TestListBlockDevices(t *testing.T) {
func TestListBlockDevicesFreeBSD(t *testing.T) {
origRun := smartRunCommandOutput
origGOOS := runtimeGOOS
- t.Cleanup(func() { smartRunCommandOutput = origRun; runtimeGOOS = origGOOS })
+ origReadDir := readDir
+ t.Cleanup(func() { smartRunCommandOutput = origRun; runtimeGOOS = origGOOS; readDir = origReadDir })
runtimeGOOS = "freebsd"
smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
@@ -60,6 +129,14 @@ func TestListBlockDevicesFreeBSD(t *testing.T) {
}
return []byte("ada0 da0 nvd0\n"), nil
}
+ readDir = func(string) ([]os.DirEntry, error) {
+ return []os.DirEntry{
+ fakeDirEntry{name: "ada0"},
+ fakeDirEntry{name: "da0"},
+ fakeDirEntry{name: "nvd0"},
+ fakeDirEntry{name: "ada0p1"},
+ }, nil
+ }
devices, err := listBlockDevices(context.Background(), nil)
if err != nil {
@@ -73,12 +150,16 @@ func TestListBlockDevicesFreeBSD(t *testing.T) {
func TestListBlockDevicesFreeBSDWithExcludes(t *testing.T) {
origRun := smartRunCommandOutput
origGOOS := runtimeGOOS
- t.Cleanup(func() { smartRunCommandOutput = origRun; runtimeGOOS = origGOOS })
+ origReadDir := readDir
+ t.Cleanup(func() { smartRunCommandOutput = origRun; runtimeGOOS = origGOOS; readDir = origReadDir })
runtimeGOOS = "freebsd"
smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
return []byte("ada0 da0 nvd0\n"), nil
}
+ readDir = func(string) ([]os.DirEntry, error) {
+ return nil, nil
+ }
devices, err := listBlockDevices(context.Background(), []string{"da0"})
if err != nil {
@@ -89,7 +170,7 @@ func TestListBlockDevicesFreeBSDWithExcludes(t *testing.T) {
}
}
-func TestListBlockDevicesError(t *testing.T) {
+func TestListBlockDevicesFreeBSDFallsBackToDevEntries(t *testing.T) {
origRun := smartRunCommandOutput
origReadDir := readDir
origGOOS := runtimeGOOS
@@ -99,94 +180,212 @@ func TestListBlockDevicesError(t *testing.T) {
runtimeGOOS = origGOOS
})
- runtimeGOOS = "linux"
+ runtimeGOOS = "freebsd"
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return []byte("\n"), nil
+ }
+ readDir = func(string) ([]os.DirEntry, error) {
+ return []os.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 TestListBlockDevicesError(t *testing.T) {
+ origRun := smartRunCommandOutput
+ forceLinuxLSBLKFallback(t)
+ t.Cleanup(func() { smartRunCommandOutput = origRun })
smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
return nil, errors.New("boom")
}
- readDir = func(path string) ([]os.DirEntry, error) {
- return nil, errors.New("sysfs unavailable")
- }
if _, err := listBlockDevices(context.Background(), nil); err == nil {
t.Fatalf("expected error")
}
}
-func TestListBlockDevicesLinuxFallbackSysfs(t *testing.T) {
+func TestParseSmartctlScanOpenTargets(t *testing.T) {
+ output := []byte(strings.Join([]string{
+ `/dev/sda -d sat # /dev/sda, ATA device`,
+ `/dev/sda # duplicate plain path should be ignored when typed target exists`,
+ `/dev/bsg/sssraid0 -d sssraid,0,1 # controller-backed disk`,
+ `/dev/sdb -d megaraid,0 # megaraid slot 0`,
+ `/dev/sdb -d megaraid,1 # megaraid slot 1`,
+ `/dev/sdc # plain disk`,
+ ``,
+ }, "\n"))
+
+ targets := parseSmartctlScanOpenTargets(output, []string{"sdc"})
+ if len(targets) != 4 {
+ t.Fatalf("expected 4 targets, got %#v", targets)
+ }
+ if targets[0].Path != "/dev/sda" || targets[0].DeviceType != "sat" {
+ t.Fatalf("unexpected first target: %#v", targets[0])
+ }
+ if targets[1].Path != "/dev/bsg/sssraid0" || targets[1].DeviceType != "sssraid,0,1" {
+ t.Fatalf("unexpected second target: %#v", targets[1])
+ }
+ if targets[2].DeviceType != "megaraid,0" || targets[3].DeviceType != "megaraid,1" {
+ t.Fatalf("expected megaraid targets to be preserved separately, got %#v", targets)
+ }
+}
+
+func TestCollectSMARTLocalUsesSmartctlScanOpenTargetsOnLinux(t *testing.T) {
origRun := smartRunCommandOutput
- origReadDir := readDir
- origStat := osStat
+ origLook := execLookPath
+ origGOOS := runtimeGOOS
t.Cleanup(func() {
smartRunCommandOutput = origRun
- readDir = origReadDir
- osStat = origStat
+ execLookPath = origLook
+ runtimeGOOS = origGOOS
})
- tempDir := t.TempDir()
- sysBlockDir := filepath.Join(tempDir, "sys", "block")
- mkdirAll := func(path string) {
- t.Helper()
- if err := os.MkdirAll(path, 0o755); err != nil {
- t.Fatalf("mkdir %s: %v", path, err)
+ runtimeGOOS = "linux"
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+
+ var seenArgs [][]string
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ seenArgs = append(seenArgs, append([]string(nil), args...))
+
+ if len(args) == 1 && args[0] == "--scan-open" {
+ return []byte("/dev/sda -d megaraid,7 # RAID-backed SSD\n"), nil
}
+
+ payload := smartctlJSON{
+ ModelName: "RAID SSD",
+ SerialNumber: "raid-ssd-1",
+ }
+ payload.Device.Protocol = "NVMe"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+ payload.NVMeSmartHealthInformationLog = &nvmeSmartHealthInformationLogJSON{
+ PercentageUsed: 6,
+ AvailableSpare: 94,
+ }
+ out, _ := json.Marshal(payload)
+ return out, nil
}
- mkdirAll(filepath.Join(sysBlockDir, "sda", "device"))
- mkdirAll(filepath.Join(sysBlockDir, "nvme0n1", "device"))
- mkdirAll(filepath.Join(sysBlockDir, "loop0")) // filtered as virtual
- mkdirAll(filepath.Join(sysBlockDir, "sr0")) // filtered as optical
+ result, err := CollectSMARTLocal(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("CollectSMARTLocal error: %v", err)
+ }
+ if len(result) != 1 {
+ t.Fatalf("expected 1 result, got %#v", result)
+ }
+ if result[0].Device != "sda [megaraid,7]" {
+ t.Fatalf("unexpected device label: %#v", result[0])
+ }
+ if result[0].Attributes == nil || result[0].Attributes.PercentageUsed == nil || *result[0].Attributes.PercentageUsed != 6 {
+ t.Fatalf("expected percentage_used SMART data, got %#v", result[0].Attributes)
+ }
+
+ if len(seenArgs) < 2 {
+ t.Fatalf("expected scan and probe calls, got %v", seenArgs)
+ }
+ probe := seenArgs[1]
+ if len(probe) < 3 || probe[0] != "-d" || probe[1] != "megaraid,7" || probe[len(probe)-1] != "/dev/sda" {
+ t.Fatalf("expected typed smartctl probe, got %v", probe)
+ }
+}
+
+func TestListBlockDevicesLinuxFallsBackToLSBLKWhenSysfsUnavailable(t *testing.T) {
+ origRun := smartRunCommandOutput
+ forceLinuxLSBLKFallback(t)
+ t.Cleanup(func() { smartRunCommandOutput = origRun })
smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
if name != "lsblk" {
return nil, errors.New("unexpected command")
}
- return nil, errors.New("lsblk not found")
- }
-
- readDir = func(path string) ([]os.DirEntry, error) {
- if path == "/sys/block" {
- return os.ReadDir(sysBlockDir)
- }
- return os.ReadDir(path)
- }
- osStat = func(name string) (os.FileInfo, error) {
- if strings.HasPrefix(name, "/sys/block/") {
- name = filepath.Join(sysBlockDir, strings.TrimPrefix(name, "/sys/block/"))
- }
- return os.Stat(name)
+ return mockLsblkJSON(
+ lsblkDevice{Name: "sda", Type: "disk", Model: "Samsung SSD 870 EVO", Vendor: "ATA"},
+ lsblkDevice{Name: "sr0", Type: "rom"},
+ ), nil
}
- devices, err := listBlockDevicesLinux(context.Background(), []string{"nvme*"})
+ devices, err := listBlockDevices(context.Background(), nil)
if err != nil {
- t.Fatalf("listBlockDevicesLinux fallback error: %v", err)
+ t.Fatalf("listBlockDevices error: %v", err)
}
if len(devices) != 1 || devices[0] != "/dev/sda" {
- t.Fatalf("unexpected fallback devices: %#v", devices)
+ t.Fatalf("unexpected devices: %#v", devices)
}
}
-func TestListBlockDevicesLinuxFallbackError(t *testing.T) {
+func TestListBlockDevicesLinuxSysfsSkipsVirtualMetadata(t *testing.T) {
origRun := smartRunCommandOutput
+ origGOOS := runtimeGOOS
origReadDir := readDir
- origStat := osStat
+ origReadFile := smartctlReadFile
+ origEvalSymlinks := smartctlEvalSymlinks
t.Cleanup(func() {
smartRunCommandOutput = origRun
+ runtimeGOOS = origGOOS
readDir = origReadDir
- osStat = origStat
+ smartctlReadFile = origReadFile
+ smartctlEvalSymlinks = origEvalSymlinks
})
- smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
- return nil, errors.New("lsblk failed")
+ runtimeGOOS = "linux"
+ readDir = func(string) ([]os.DirEntry, error) {
+ return []os.DirEntry{
+ fakeDirEntry{name: "sda"},
+ fakeDirEntry{name: "sdb"},
+ }, nil
+ }
+ smartctlReadFile = func(path string) ([]byte, error) {
+ switch path {
+ case "/sys/block/sda/device/vendor":
+ return []byte("ATA\n"), nil
+ case "/sys/block/sda/device/model":
+ return []byte("Samsung SSD 870 EVO\n"), nil
+ case "/sys/block/sdb/device/vendor":
+ return []byte("VMware\n"), nil
+ case "/sys/block/sdb/device/model":
+ return []byte("Virtual disk\n"), nil
+ default:
+ return nil, fs.ErrNotExist
+ }
}
- readDir = func(path string) ([]os.DirEntry, error) {
- return nil, errors.New("sysfs unavailable")
+ smartctlEvalSymlinks = func(path string) (string, error) {
+ switch path {
+ case "/sys/block/sda":
+ return "/sys/devices/pci0000:00/0000:00:17.0/ata1/host0/target0:0:0/0:0:0:0/block/sda", nil
+ case "/sys/block/sda/device/subsystem":
+ return "/sys/bus/scsi", nil
+ case "/sys/block/sdb":
+ return "/sys/devices/pci0000:00/0000:00:18.0/host1/target1:0:0/1:0:0:0/block/sdb", nil
+ case "/sys/block/sdb/device/subsystem":
+ return "/sys/bus/scsi", nil
+ default:
+ return "", fs.ErrNotExist
+ }
+ }
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return nil, errors.New("lsblk should not be called when sysfs enumeration succeeds")
}
- if _, err := listBlockDevicesLinux(context.Background(), nil); err == nil {
- t.Fatalf("expected fallback error")
- } else if !strings.Contains(err.Error(), "lsblk error") || !strings.Contains(err.Error(), "fallback error") {
- t.Fatalf("unexpected error: %v", err)
+ devices, err := listBlockDevices(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("listBlockDevices error: %v", err)
+ }
+ if len(devices) != 1 || devices[0] != "/dev/sda" {
+ t.Fatalf("unexpected devices: %#v", devices)
}
}
@@ -497,6 +696,203 @@ func TestCollectDeviceSMARTNVMeTempFallback(t *testing.T) {
}
}
+func TestCollectDeviceSMARTFreeBSDAdaFallback(t *testing.T) {
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ origNow := timeNow
+ origGOOS := runtimeGOOS
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ timeNow = origNow
+ runtimeGOOS = origGOOS
+ })
+
+ fixed := time.Date(2024, 4, 6, 7, 8, 9, 0, time.UTC)
+ timeNow = func() time.Time { return fixed }
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+ runtimeGOOS = "freebsd"
+
+ var attempts [][]string
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ attempts = append(attempts, append([]string(nil), args...))
+
+ payload := smartctlJSON{}
+ payload.Device.Protocol = "ATA"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+
+ if len(args) >= 2 && args[0] == "-d" && args[1] == "sat" {
+ payload.Temperature.Current = 37
+ }
+
+ out, _ := json.Marshal(payload)
+ return out, nil
+ }
+
+ result, err := collectDeviceSMART(context.Background(), "/dev/ada0")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil || result.Temperature != 37 || !result.LastUpdated.Equal(fixed) {
+ t.Fatalf("unexpected result: %#v", result)
+ }
+ 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 TestCollectDeviceSMARTFreeBSDFalseStandbyFallsBackToUntypedProbe(t *testing.T) {
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ origNow := timeNow
+ origGOOS := runtimeGOOS
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ timeNow = origNow
+ runtimeGOOS = origGOOS
+ })
+
+ fixed := time.Date(2024, 4, 7, 9, 10, 11, 0, time.UTC)
+ timeNow = func() time.Time { return fixed }
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+ runtimeGOOS = "freebsd"
+
+ var attempts [][]string
+ smartRunCommandOutput = 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" {
+ return exec.CommandContext(ctx, "sh", "-c", "exit 3").Output()
+ }
+
+ payload := smartctlJSON{}
+ payload.Device.Protocol = "ATA"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+ payload.Temperature.Current = 41
+ out, _ := json.Marshal(payload)
+ return out, nil
+ }
+
+ result, err := collectDeviceSMART(context.Background(), "/dev/ada0")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil || result.Standby || result.Temperature != 41 || !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[0]) < 2 || attempts[0][0] != "-d" || attempts[0][1] != "sat" {
+ t.Fatalf("expected first probe to use -d sat, got %v", attempts[0])
+ }
+ if len(attempts[1]) < 1 || attempts[1][0] == "-d" {
+ t.Fatalf("expected second probe to fall back to untyped smartctl, got %v", attempts[1])
+ }
+}
+
+func TestCollectDeviceSMARTFreeBSDUsesSCTTemperatureFallback(t *testing.T) {
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ origNow := timeNow
+ origGOOS := runtimeGOOS
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ timeNow = origNow
+ runtimeGOOS = origGOOS
+ })
+
+ fixed := time.Date(2024, 4, 7, 10, 30, 0, 0, time.UTC)
+ timeNow = func() time.Time { return fixed }
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+ runtimeGOOS = "freebsd"
+
+ var attempts [][]string
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ attempts = append(attempts, append([]string(nil), args...))
+
+ payload := smartctlJSON{}
+ payload.Device.Protocol = "ATA"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+
+ for i := 0; i < len(args)-1; i++ {
+ if args[i] == "-l" && args[i+1] == "scttempsts" {
+ payload.ATASCTStatus.Current.Value = 43
+ }
+ }
+
+ out, _ := json.Marshal(payload)
+ return out, nil
+ }
+
+ result, err := collectDeviceSMART(context.Background(), "/dev/ada0")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil || result.Standby || result.Temperature != 43 || !result.LastUpdated.Equal(fixed) {
+ t.Fatalf("unexpected result: %#v", result)
+ }
+ if len(attempts) != 2 {
+ t.Fatalf("expected typed probe plus SCT retry, got %d attempts: %v", len(attempts), attempts)
+ }
+ if len(attempts[0]) < 2 || attempts[0][0] != "-d" || attempts[0][1] != "sat" {
+ t.Fatalf("expected first probe to use -d sat, got %v", attempts[0])
+ }
+ if !strings.Contains(strings.Join(attempts[1], " "), "-l scttempsts") {
+ t.Fatalf("expected second probe to request SCT temperature status, got %v", attempts[1])
+ }
+}
+
+func TestCollectDeviceSMARTFreeBSDFallsBackToPlainTextSMARTOutput(t *testing.T) {
+ origRun := smartRunCommandOutput
+ origLook := execLookPath
+ origNow := timeNow
+ origGOOS := runtimeGOOS
+ t.Cleanup(func() {
+ smartRunCommandOutput = origRun
+ execLookPath = origLook
+ timeNow = origNow
+ runtimeGOOS = origGOOS
+ })
+
+ fixed := time.Date(2024, 4, 7, 10, 30, 0, 0, time.UTC)
+ timeNow = func() time.Time { return fixed }
+ execLookPath = func(string) (string, error) { return "smartctl", nil }
+ runtimeGOOS = "freebsd"
+
+ smartRunCommandOutput = func(ctx context.Context, name string, args ...string) ([]byte, error) {
+ return []byte(`
+=== START OF INFORMATION SECTION ===
+Device Model: WDC WD40EFRX
+Serial Number: WD-123
+SMART overall-health self-assessment test result: PASSED
+Current Temperature: 38 C
+`), nil
+ }
+
+ result, err := collectDeviceSMART(context.Background(), "/dev/ada0")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil || result.Standby || result.Temperature != 38 || result.Health != "PASSED" || !result.LastUpdated.Equal(fixed) {
+ t.Fatalf("unexpected result: %#v", result)
+ }
+ if result.Model != "WDC WD40EFRX" || result.Serial != "WD-123" {
+ t.Fatalf("expected text fallback model/serial, got %#v", result)
+ }
+}
+
func TestCollectDeviceSMARTWWN(t *testing.T) {
origRun := smartRunCommandOutput
origLook := execLookPath
diff --git a/internal/hostagent/smartctl_test.go b/internal/hostagent/smartctl_test.go
index 23bcc328e9..fd22c1f343 100644
--- a/internal/hostagent/smartctl_test.go
+++ b/internal/hostagent/smartctl_test.go
@@ -1,6 +1,7 @@
package hostagent
import (
+ "encoding/json"
"testing"
)
@@ -387,6 +388,123 @@ func TestParseSMARTAttributes_NVMeZeroValuesWhenLogPresent(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, smartctlTarget{Path: "/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 TestParseSMARTOutputUsesATASCTTemperature(t *testing.T) {
+ payload := smartctlJSON{
+ ModelName: "WDC WD40EFRX",
+ SerialNumber: "WD-456",
+ }
+ payload.Device.Protocol = "ATA"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+ payload.ATASCTStatus.Current.Value = 41
+
+ out, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal payload: %v", err)
+ }
+
+ result, err := parseSMARTOutput(out, smartctlTarget{Path: "/dev/ada0"})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil {
+ t.Fatal("expected result")
+ }
+ if result.Temperature != 41 {
+ t.Fatalf("expected SCT temperature 41, got %#v", result)
+ }
+}
+
+func TestParseSMARTOutputFallsBackToOriginalTextTemperature(t *testing.T) {
+ payload := smartctlJSON{
+ ModelName: "WDC WD40EFRX",
+ SerialNumber: "WD-789",
+ }
+ payload.Device.Protocol = "ATA"
+ payload.SmartStatus = &struct {
+ Passed bool `json:"passed"`
+ }{Passed: true}
+ payload.Smartctl.Output = []string{
+ "=== START OF READ SMART DATA SECTION ===",
+ "194 Temperature_Celsius 0x0022 120 099 000 Old_age Always - 37 (Min/Max 20/45)",
+ }
+
+ out, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal payload: %v", err)
+ }
+
+ result, err := parseSMARTOutput(out, smartctlTarget{Path: "/dev/ada0"})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil {
+ t.Fatal("expected result")
+ }
+ if result.Temperature != 37 {
+ t.Fatalf("expected text-fallback temperature 37, got %#v", result)
+ }
+ if result.Model != "WDC WD40EFRX" || result.Serial != "WD-789" || result.Health != "PASSED" {
+ t.Fatalf("expected model/serial/health to be preserved, got %#v", result)
+ }
+}
+
+func TestParseSMARTOutputFallsBackToPlainTextOutput(t *testing.T) {
+ output := []byte(`
+=== START OF INFORMATION SECTION ===
+Device Model: WDC WD40EFRX
+Serial Number: WD-123
+SMART overall-health self-assessment test result: PASSED
+Current Temperature: 39 C
+`)
+
+ result, err := parseSMARTOutput(output, smartctlTarget{Path: "/dev/ada0"})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if result == nil {
+ t.Fatal("expected result")
+ }
+ if result.Model != "WDC WD40EFRX" || result.Serial != "WD-123" {
+ t.Fatalf("expected text model/serial, got %#v", result)
+ }
+ if result.Health != "PASSED" || result.Temperature != 39 {
+ t.Fatalf("expected text-fallback health/temp, got %#v", result)
+ }
+ if result.Type != "sata" {
+ t.Fatalf("expected sata fallback type, got %#v", result)
+ }
+}
+
func TestMatchesDeviceExclude(t *testing.T) {
tests := []struct {
name string