package agent
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"time"
"github.com/henrygd/beszel/agent/utils"
"github.com/henrygd/beszel/internal/entities/smart"
)
type SmartManager struct {
sync.Mutex
data map[string]*smart.SmartData
refreshMutex sync.Mutex
last map[string]smartResult
woken map[string]struct{}
scanned []smartDevice
scanErr error
lastScan time.Time
smartctlPath string
excludedDevices map[string]struct{}
run smartctlRunner
darwinNvmeOnce sync.Once
darwinNvmeCapacity map[string]uint64
darwinNvmeProvider func() ([]byte, error)
}
type smartctlRunner func(timeout time.Duration, args ...string) (output []byte, exitCode int, err error)
type smartDevice struct {
name string
dtype string
explicit bool
}
type smartAttempt struct {
path string
dtype string
}
type smartTarget struct {
key string
dtype string
name string
attempts []smartAttempt
}
type smartResult struct {
key string
data *smart.SmartData
attempt int
ata bool
}
var errNoValidSmartData = fmt.Errorf("no valid SMART data found")
const smartScanInterval = 30 * time.Minute
func (sm *SmartManager) Refresh(forceScan bool) (bool, error) {
sm.refreshMutex.Lock()
defer sm.refreshMutex.Unlock()
targets, scanErr := sm.buildTargets(forceScan)
if scanErr != nil {
slog.Debug("smartctl scan failed", "err", scanErr)
}
data := make(map[string]*smart.SmartData, len(targets))
last := make(map[string]smartResult, len(targets))
complete := scanErr == nil
var collectErr error
for _, target := range targets {
result, err := sm.collectTarget(target)
if err != nil {
if prev, ok := sm.last[target.key]; ok {
last[target.key] = prev
}
complete = false
if !errors.Is(err, errStandby) {
slog.Info("smartctl failed", "device", target.name, "err", err)
collectErr = err
}
continue
}
if existing, ok := data[result.key]; ok {
slog.Debug("skipping duplicate SMART device", "device", target.name, "serial", result.key, "first", existing.DiskName)
continue
}
data[result.key] = result.data
last[target.key] = result
}
sm.last = last
sm.Lock()
sm.data = data
sm.Unlock()
if len(data) > 0 {
return complete, nil
}
if len(targets) == 0 && scanErr != nil {
return false, scanErr
}
switch {
case collectErr != nil:
return false, collectErr
case scanErr != nil:
return false, scanErr
}
return false, errNoValidSmartData
}
func (sm *SmartManager) GetCurrentData() map[string]smart.SmartData {
sm.Lock()
defer sm.Unlock()
result := make(map[string]smart.SmartData, len(sm.data))
for key, value := range sm.data {
if value != nil {
result[key] = *value
}
}
return result
}
func (sm *SmartManager) buildTargets(forceScan bool) ([]smartTarget, error) {
var configured []smartDevice
if raw, ok := utils.GetEnv("SMART_DEVICES"); ok {
slog.Debug("SMART_DEVICES", "value", raw)
if strings.TrimSpace(raw) == "" {
return nil, errNoValidSmartData
}
var err error
if configured, err = parseConfiguredDevices(raw); err != nil {
return nil, err
}
}
scanned, scanErr := sm.scanSmartctl(forceScan)
scanned = append(slices.Clone(scanned), scanSysfsDevices()...)
devices := mergeDevices(scanned, configured)
targets := make([]smartTarget, 0, len(devices))
for _, device := range devices {
if sm.isExcludedDevice(device.name) {
continue
}
targets = append(targets, smartTarget{
key: device.name + "|" + device.dtype,
dtype: device.dtype,
name: device.name,
attempts: sm.attemptsFor(device),
})
}
return targets, scanErr
}
var scanSysfsDevices = func() []smartDevice {
var devices []smartDevice
for _, path := range scanEmmcDevices() {
devices = append(devices, smartDevice{name: path, dtype: "emmc"})
}
for _, path := range scanMdraidDevices() {
devices = append(devices, smartDevice{name: path, dtype: "mdraid"})
}
return devices
}
func mergeDevices(scanned, configured []smartDevice) []smartDevice {
devices := slices.Clone(scanned)
nameCounts := make(map[string]int, len(scanned))
for _, device := range scanned {
nameCounts[device.name]++
}
for _, device := range configured {
if i := slices.IndexFunc(devices, func(d smartDevice) bool { return d.name == device.name && d.dtype == device.dtype }); i >= 0 {
devices[i].explicit = devices[i].explicit || device.explicit
continue
}
if nameCounts[device.name] == 1 {
if device.dtype != "" {
i := slices.IndexFunc(devices, func(d smartDevice) bool { return d.name == device.name })
devices[i] = device
nameCounts[device.name] = 0
}
continue
}
devices = append(devices, device)
}
seen := make(map[smartDevice]struct{}, len(devices))
return slices.DeleteFunc(devices, func(d smartDevice) bool {
d.explicit = false
if _, ok := seen[d]; ok || d.name == "" {
return true
}
seen[d] = struct{}{}
return false
})
}
func (sm *SmartManager) attemptsFor(device smartDevice) []smartAttempt {
dtype := strings.ToLower(device.dtype)
var attempts []smartAttempt
switch {
case device.explicit:
attempts = []smartAttempt{{device.name, device.dtype}}
case dtype == "scsi":
attempts = []smartAttempt{{device.name, ""}, {device.name, "sat"}}
case dtype == "ata":
attempts = []smartAttempt{{device.name, ""}}
default:
attempts = []smartAttempt{{device.name, device.dtype}}
}
if isNvmeControllerPath(device.name) && (dtype == "" || dtype == "nvme") {
if namespace := device.name + "n1"; !sm.isExcludedDevice(namespace) {
attempts = append(attempts, smartAttempt{namespace, device.dtype})
}
}
return attempts
}
func (sm *SmartManager) scanSmartctl(force bool) ([]smartDevice, error) {
if sm.smartctlPath == "" && sm.run == nil {
return nil, nil
}
if !force && !sm.lastScan.IsZero() && time.Since(sm.lastScan) < smartScanInterval {
return sm.scanned, sm.scanErr
}
sm.lastScan = time.Now()
output, exitCode, err := sm.runSmartctl(10*time.Second, "--scan", "-j")
if err == nil && exitCode != 0 {
err = fmt.Errorf("smartctl scan failed (exit status %d)", exitCode)
}
if err == nil {
var devices []smartDevice
if devices, err = parseScan(output); err == nil {
if len(devices) == 0 && len(sm.scanned) > 0 {
err = errors.New("smartctl scan found no devices")
} else {
sm.scanned = devices
}
}
}
sm.scanErr = err
return sm.scanned, err
}
func parseScan(output []byte) ([]smartDevice, error) {
var scan struct {
Devices []struct {
Name string `json:"name"`
Type string `json:"type"`
Protocol string `json:"protocol"`
} `json:"devices"`
}
if err := json.Unmarshal(output, &scan); err != nil {
return nil, fmt.Errorf("invalid smartctl scan output: %w", err)
}
devices := make([]smartDevice, 0, len(scan.Devices))
for _, device := range scan.Devices {
slog.Debug("smartctl scan", "name", device.Name, "type", device.Type, "protocol", device.Protocol)
devices = append(devices, smartDevice{name: device.Name, dtype: device.Type})
}
return devices, nil
}
func parseConfiguredDevices(config string) ([]smartDevice, error) {
splitChar, _ := utils.GetEnv("SMART_DEVICES_SEPARATOR")
if splitChar == "" {
splitChar = ","
}
var devices []smartDevice
for entry := range strings.SplitSeq(config, splitChar) {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
name, dtype, _ := strings.Cut(entry, ":")
name = strings.TrimSpace(name)
if name == "" {
return nil, fmt.Errorf("invalid SMART_DEVICES entry %q", entry)
}
dtype = strings.ToLower(strings.TrimSpace(dtype))
devices = append(devices, smartDevice{name: name, dtype: dtype, explicit: dtype != ""})
}
if len(devices) == 0 {
return nil, errNoValidSmartData
}
return devices, nil
}
var errStandby = errors.New("device is in standby")
func (sm *SmartManager) collectTarget(target smartTarget) (smartResult, error) {
switch target.dtype {
case "emmc", "mmc":
if key, data, ok := readEmmcSmartData(target.name); ok {
return smartResult{key: key, data: data}, nil
}
return smartResult{}, errNoValidSmartData
case "mdraid":
if key, data, ok := readMdraidSmartData(target.name); ok {
return smartResult{key: key, data: data}, nil
}
return smartResult{}, errNoValidSmartData
}
if sm.smartctlPath == "" && sm.run == nil {
return smartResult{}, errNoValidSmartData
}
prev, hasPrev := sm.last[target.key]
order := make([]int, 0, len(target.attempts))
if hasPrev && prev.attempt < len(target.attempts) {
order = append(order, prev.attempt)
}
for i := range target.attempts {
if !hasPrev || i != prev.attempt {
order = append(order, i)
}
}
var err error
for _, i := range order {
attempt := target.attempts[i]
ata := prev.ata || !hasPrev && strings.EqualFold(target.dtype, "ata")
args := smartctlArgs(attempt, ata, true)
output, exitCode, runErr := sm.runSmartctl(15*time.Second, args...)
if runErr != nil {
err = runErr
slog.Debug("smartctl attempt failed", "device", attempt.path, "type", attempt.dtype, "err", runErr)
continue
}
data, protocol, parseErr := sm.parseSmartctl(output, attempt.dtype)
if parseErr == nil {
return smartResult{key: data.SerialNumber, data: data, attempt: i, ata: protocol == "ata"}, nil
}
if isStandby(output, exitCode) {
if hasPrev {
slog.Debug("smartctl device in standby", "device", attempt.path)
return prev, nil
}
if _, ok := sm.woken[target.key]; !ok {
if sm.woken == nil {
sm.woken = make(map[string]struct{})
}
sm.woken[target.key] = struct{}{}
slog.Info("smartctl waking device in standby for first collection", "device", attempt.path)
result, wakeErr := sm.wakeTarget(attempt, i, ata)
if wakeErr == nil {
return result, nil
}
err = wakeErr
continue
}
if bytes.Contains(bytes.ToUpper(output), []byte("SLEEP MODE")) {
slog.Info("smartctl reports device asleep (or lacks permission), skipping", "device", attempt.path)
} else {
slog.Info("smartctl reports device in standby, skipping", "device", attempt.path)
}
return smartResult{}, errStandby
}
err = fmt.Errorf("%w (exit status %d)", parseErr, exitCode)
slog.Debug("smartctl attempt failed", "device", attempt.path, "type", attempt.dtype, "args", args, "exit", exitCode, "err", parseErr)
}
return smartResult{}, err
}
func (sm *SmartManager) wakeTarget(attempt smartAttempt, i int, ata bool) (smartResult, error) {
args := smartctlArgs(attempt, ata, false)
output, exitCode, err := sm.runSmartctl(15*time.Second, args...)
if err != nil {
return smartResult{}, err
}
data, protocol, err := sm.parseSmartctl(output, attempt.dtype)
if err != nil {
slog.Debug("smartctl wake attempt failed", "device", attempt.path, "type", attempt.dtype, "args", args, "exit", exitCode, "err", err)
return smartResult{}, fmt.Errorf("%w (exit status %d)", err, exitCode)
}
return smartResult{key: data.SerialNumber, data: data, attempt: i, ata: protocol == "ata"}, nil
}
func smartctlArgs(attempt smartAttempt, ata, standby bool) []string {
args := make([]string, 0, 9)
if attempt.dtype != "" {
args = append(args, "-d", attempt.dtype)
}
args = append(args, "-a", "--json=c")
if dtype := strings.ToLower(attempt.dtype); ata || dtype == "sat" || dtype == "ata" {
args = append(args, "-l", "devstat")
}
if standby {
args = append(args, "-n", "standby")
}
return append(args, attempt.path)
}
func isStandby(output []byte, exitCode int) bool {
if exitCode&2 == 0 {
return false
}
upper := bytes.ToUpper(output)
return bytes.Contains(upper, []byte("DEVICE IS IN ")) && bytes.Contains(upper, []byte(" MODE"))
}
func (sm *SmartManager) runSmartctl(timeout time.Duration, args ...string) ([]byte, int, error) {
if sm.run != nil {
return sm.run(timeout, args...)
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
output, err := exec.CommandContext(ctx, sm.smartctlPath, args...).Output()
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok && ctx.Err() == nil {
return output, exitErr.ExitCode(), nil
}
return output, 0, err
}
func (sm *SmartManager) refreshExcludedDevices() {
rawValue, _ := utils.GetEnv("EXCLUDE_SMART")
sm.excludedDevices = make(map[string]struct{})
for entry := range strings.SplitSeq(rawValue, ",") {
device := strings.TrimSpace(entry)
if device == "" {
continue
}
sm.excludedDevices[device] = struct{}{}
}
}
func (sm *SmartManager) isExcludedDevice(deviceName string) bool {
_, exists := sm.excludedDevices[deviceName]
return exists
}
func (sm *SmartManager) detectSmartctl() (string, error) {
if runtime.GOOS == "windows" {
if runtime.GOARCH == "amd64" {
if path, err := ensureEmbeddedSmartctl(); err == nil {
return path, nil
}
}
const location = "C:\\Program Files\\smartmontools\\bin\\smartctl.exe"
if _, err := os.Stat(location); err == nil {
return location, nil
}
}
return utils.LookPathHomebrew("smartctl")
}
func isNvmeControllerPath(path string) bool {
base := filepath.Base(path)
if !strings.HasPrefix(base, "nvme") {
return false
}
suffix := strings.TrimPrefix(base, "nvme")
if suffix == "" {
return false
}
for _, c := range suffix {
if c < '0' || c > '9' {
return false
}
}
return true
}
func NewSmartManager() (*SmartManager, error) {
sm := &SmartManager{
data: make(map[string]*smart.SmartData),
}
sm.refreshExcludedDevices()
path, err := sm.detectSmartctl()
slog.Debug("smartctl", "path", path, "err", err)
if err != nil {
if runtime.GOOS == "linux" {
if len(scanEmmcDevices()) > 0 || len(scanMdraidDevices()) > 0 {
return sm, nil
}
}
return nil, err
}
sm.smartctlPath = path
return sm, nil
}