package agent
import (
"bufio"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/henrygd/beszel/agent/utils"
"github.com/henrygd/beszel/internal/entities/system"
)
var amdSysfsSleep = time.Sleep
var amdgpuNameCache = struct {
sync.RWMutex
hits map[string]string
misses map[string]struct{}
}{
hits: make(map[string]string),
misses: make(map[string]struct{}),
}
func (gm *GPUManager) hasAmdSysfs() bool {
cards, err := filepath.Glob(filepath.Join(drmSysfsRoot, "card*/device/vendor"))
if err != nil {
return false
}
for _, vendorPath := range cards {
vendor, err := utils.ReadStringFileLimited(vendorPath, 64)
if err == nil && vendor == "0x1002" {
return true
}
}
return false
}
func (gm *GPUManager) collectAmdStats() error {
sysfsPollInterval := 3000 * time.Millisecond
cards, err := filepath.Glob(filepath.Join(drmSysfsRoot, "card*"))
if err != nil {
return err
}
var amdGpuPaths []string
for _, card := range cards {
if strings.Contains(filepath.Base(card), "-") || !isAmdGpu(card) {
continue
}
amdGpuPaths = append(amdGpuPaths, card)
}
if len(amdGpuPaths) == 0 {
return errNoValidData
}
slog.Debug("Using sysfs for AMD GPU data collection")
failures := 0
for {
hasData := false
for _, cardPath := range amdGpuPaths {
if gm.updateAmdGpuData(cardPath) {
hasData = true
}
}
if !hasData {
failures++
log := slog.Debug
if failures <= maxFailureRetries {
log = slog.Warn
}
log("No AMD GPU data from sysfs", "failures", failures)
amdSysfsSleep(retryWaitTime)
continue
}
failures = 0
amdSysfsSleep(sysfsPollInterval)
}
}
func isAmdGpu(cardPath string) bool {
vendor, err := utils.ReadStringFileLimited(filepath.Join(cardPath, "device/vendor"), 64)
if err != nil {
return false
}
return vendor == "0x1002"
}
const unifiedMemoryMaxVram = 2 << 30
type amdMemoryKind uint8
const (
amdMemoryUnknown amdMemoryKind = iota
amdMemoryDiscrete
amdMemoryUnified
amdMemoryBySize
)
var amdMemoryKindCache = struct {
sync.Mutex
kinds map[string]amdMemoryKind
}{kinds: make(map[string]amdMemoryKind)}
func amdGpuIsUnifiedMemory(devicePath string, vramTotal float64) bool {
amdMemoryKindCache.Lock()
kind := amdMemoryKindCache.kinds[devicePath]
amdMemoryKindCache.Unlock()
if kind == amdMemoryUnknown {
kind = detectAmdMemoryKind(devicePath)
if kind != amdMemoryUnknown {
amdMemoryKindCache.Lock()
amdMemoryKindCache.kinds[devicePath] = kind
amdMemoryKindCache.Unlock()
}
}
switch kind {
case amdMemoryDiscrete:
return false
case amdMemoryUnified:
return true
default:
return vramTotal > 0 && vramTotal < unifiedMemoryMaxVram
}
}
func detectAmdMemoryKind(devicePath string) amdMemoryKind {
header := make([]byte, 4)
n, err := readSysfsHead(filepath.Join(devicePath, "gpu_metrics"), header)
switch {
case err == nil && n == len(header):
switch header[2] {
case 1:
return amdMemoryDiscrete
case 2, 3:
return amdMemoryUnified
}
return amdMemoryBySize
case err == nil, errors.Is(err, fs.ErrNotExist), errors.Is(err, syscall.EOPNOTSUPP):
return amdMemoryBySize
}
return amdMemoryUnknown
}
func (gm *GPUManager) updateAmdGpuData(cardPath string) bool {
devicePath := filepath.Join(cardPath, "device")
id := filepath.Base(cardPath)
usage, usageErr := readSysfsFloat(filepath.Join(devicePath, "gpu_busy_percent"))
memUsed, memUsedErr := readSysfsFloat(filepath.Join(devicePath, "mem_info_vram_used"))
memTotal, _ := readSysfsFloat(filepath.Join(devicePath, "mem_info_vram_total"))
if amdGpuIsUnifiedMemory(devicePath, memTotal) {
if gttUsed, err := readSysfsFloat(filepath.Join(devicePath, "mem_info_gtt_used")); err == nil && gttUsed > 0 {
if gttTotal, err := readSysfsFloat(filepath.Join(devicePath, "mem_info_gtt_total")); err == nil {
memUsed += gttUsed
memTotal += gttTotal
}
}
}
var temp, power float64
hwmons, _ := filepath.Glob(filepath.Join(devicePath, "hwmon/hwmon*"))
for _, hwmonDir := range hwmons {
if t, err := readSysfsFloat(filepath.Join(hwmonDir, "temp1_input")); err == nil {
temp = t / 1000.0
}
if p, err := readSysfsFloat(filepath.Join(hwmonDir, "power1_average")); err == nil {
power += p / 1000000.0
} else if p, err := readSysfsFloat(filepath.Join(hwmonDir, "power1_input")); err == nil {
power += p / 1000000.0
}
}
if usageErr != nil && memUsedErr != nil && temp == 0 {
return false
}
gm.Lock()
defer gm.Unlock()
gpu, ok := gm.GpuDataMap[id]
if !ok {
gpu = &system.GPUData{Name: getAmdGpuName(devicePath)}
gm.GpuDataMap[id] = gpu
}
if usageErr == nil {
gpu.Usage += usage
}
gpu.MemoryUsed = utils.BytesToMegabytes(memUsed)
gpu.MemoryTotal = utils.BytesToMegabytes(memTotal)
gpu.Temperature = temp
gpu.Power += power
gpu.Count++
return true
}
func readSysfsFloat(path string) (float64, error) {
now := time.Now()
if !amdSysfsBackoff.allow(path, now) {
return 0, errSysfsBackoff
}
val, err := utils.ReadStringFileLimited(path, 64)
amdSysfsBackoff.record(path, err, time.Since(now), now)
if err != nil {
slog.Debug("Failed to read sysfs value", "path", path, "error", err)
return 0, err
}
return strconv.ParseFloat(val, 64)
}
func readSysfsHead(path string, buf []byte) (int, error) {
now := time.Now()
if !amdSysfsBackoff.allow(path, now) {
return 0, errSysfsBackoff
}
n, err := readFileHead(path, buf)
amdSysfsBackoff.record(path, err, time.Since(now), now)
if err != nil {
slog.Debug("Failed to read sysfs file", "path", path, "error", err)
}
return n, err
}
func readFileHead(path string, buf []byte) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
n, err := io.ReadFull(f, buf)
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
err = nil
}
return n, err
}
const (
sysfsSlowReadThreshold = 500 * time.Millisecond
sysfsBackoffMin = 30 * time.Second
sysfsBackoffMax = 10 * time.Minute
)
var errSysfsBackoff = errors.New("sysfs read skipped during backoff")
var amdSysfsBackoff = newSysfsBackoff()
type sysfsBackoff struct {
sync.Mutex
entries map[string]*sysfsBackoffEntry
}
type sysfsBackoffEntry struct {
until time.Time
delay time.Duration
}
func newSysfsBackoff() *sysfsBackoff {
return &sysfsBackoff{entries: make(map[string]*sysfsBackoffEntry)}
}
func (b *sysfsBackoff) allow(path string, now time.Time) bool {
b.Lock()
defer b.Unlock()
entry, ok := b.entries[path]
return !ok || !now.Before(entry.until)
}
func (b *sysfsBackoff) record(path string, err error, elapsed time.Duration, now time.Time) {
b.Lock()
defer b.Unlock()
if err == nil {
delete(b.entries, path)
return
}
if elapsed < sysfsSlowReadThreshold && !errors.Is(err, syscall.EOPNOTSUPP) {
return
}
entry, ok := b.entries[path]
if !ok {
entry = &sysfsBackoffEntry{delay: sysfsBackoffMin}
b.entries[path] = entry
} else {
entry.delay = min(entry.delay*2, sysfsBackoffMax)
}
entry.until = now.Add(entry.delay)
slog.Warn("Backing off slow or unsupported sysfs file", "path", path, "elapsed", elapsed, "error", err, "retry", entry.delay)
}
func normalizeHexID(id string) string {
return strings.TrimPrefix(strings.ToLower(strings.TrimSpace(id)), "0x")
}
func cacheKeyForAmdgpu(deviceID, revisionID string) string {
if revisionID != "" {
return deviceID + ":" + revisionID
}
return deviceID
}
func lookupAmdgpuNameInFile(deviceID, revisionID, filePath string) (name string, exact bool, found bool) {
file, err := os.Open(filePath)
if err != nil {
return "", false, false
}
defer file.Close()
var byDevice string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, ",", 3)
if len(parts) != 3 {
continue
}
dev := normalizeHexID(parts[0])
rev := normalizeHexID(parts[1])
productName := strings.TrimSpace(parts[2])
if dev == "" || productName == "" || dev != deviceID {
continue
}
if byDevice == "" {
byDevice = productName
}
if revisionID != "" && rev == revisionID {
return productName, true, true
}
}
if byDevice != "" {
return byDevice, false, true
}
return "", false, false
}
func getCachedAmdgpuName(deviceID, revisionID string) (name string, found bool, done bool) {
keys := []string{cacheKeyForAmdgpu(deviceID, revisionID)}
if revisionID != "" {
keys = append(keys, deviceID)
}
knownMisses := 0
amdgpuNameCache.RLock()
defer amdgpuNameCache.RUnlock()
for _, key := range keys {
if name, ok := amdgpuNameCache.hits[key]; ok {
return name, true, true
}
if _, ok := amdgpuNameCache.misses[key]; ok {
knownMisses++
}
}
return "", false, knownMisses == len(keys)
}
func normalizeAmdgpuName(name string) string {
for _, suffix := range []string{" Graphics", " Series"} {
name = strings.TrimSuffix(name, suffix)
}
return name
}
func cacheAmdgpuName(deviceID, revisionID, name string, exact bool) {
name = normalizeAmdgpuName(name)
amdgpuNameCache.Lock()
defer amdgpuNameCache.Unlock()
if exact && revisionID != "" {
amdgpuNameCache.hits[cacheKeyForAmdgpu(deviceID, revisionID)] = name
}
amdgpuNameCache.hits[deviceID] = name
}
func cacheMissingAmdgpuName(deviceID, revisionID string) {
amdgpuNameCache.Lock()
defer amdgpuNameCache.Unlock()
amdgpuNameCache.misses[deviceID] = struct{}{}
if revisionID != "" {
amdgpuNameCache.misses[cacheKeyForAmdgpu(deviceID, revisionID)] = struct{}{}
}
}
func getAmdGpuName(devicePath string) string {
if prod, err := utils.ReadStringFileLimited(filepath.Join(devicePath, "product_name"), 128); err == nil {
return prod
}
if deviceID, err := utils.ReadStringFileLimited(filepath.Join(devicePath, "device"), 64); err == nil {
id := normalizeHexID(deviceID)
revision := ""
if rev, revErr := utils.ReadStringFileLimited(filepath.Join(devicePath, "revision"), 64); revErr == nil {
revision = normalizeHexID(rev)
}
if name, found, done := getCachedAmdgpuName(id, revision); found {
return name
} else if !done {
if name, exact, ok := lookupAmdgpuNameInFile(id, revision, "/usr/share/libdrm/amdgpu.ids"); ok {
cacheAmdgpuName(id, revision, name, exact)
return normalizeAmdgpuName(name)
}
cacheMissingAmdgpuName(id, revision)
}
return fmt.Sprintf("AMD GPU (%s)", id)
}
return "AMD GPU"
}