Files

88 lines
2.6 KiB
Go

package server
import (
"context"
"encoding/json"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func sampleGPU(ctx context.Context) protocol.ServerGPUStats {
if runtime.GOOS == "linux" {
return sampleNVIDIA(ctx)
}
if runtime.GOOS == "darwin" {
return sampleMacGPU(ctx)
}
return protocol.ServerGPUStats{Reason: "GPU detection is unsupported on this platform"}
}
func sampleNVIDIA(parent context.Context) protocol.ServerGPUStats {
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()
out, e := exec.CommandContext(ctx, "nvidia-smi", "--query-gpu=name,utilization.gpu,memory.total,memory.used,temperature.gpu", "--format=csv,noheader,nounits").Output()
if e != nil {
return protocol.ServerGPUStats{Reason: "nvidia-smi unavailable"}
}
devices := parseNVIDIA(string(out))
if len(devices) == 0 {
return protocol.ServerGPUStats{Reason: "nvidia-smi returned no usable GPUs"}
}
return protocol.ServerGPUStats{Available: true, Devices: devices}
}
func parseNVIDIA(text string) []protocol.ServerGPUDevice {
var out []protocol.ServerGPUDevice
for _, line := range strings.Split(text, "\n") {
p := strings.Split(line, ",")
if len(p) != 5 {
continue
}
d := protocol.ServerGPUDevice{Name: strings.TrimSpace(p[0]), Vendor: "NVIDIA"}
if d.Name == "" {
continue
}
if v, e := strconv.ParseFloat(strings.TrimSpace(p[1]), 64); e == nil {
d.UtilizationPercent = &v
}
if v, e := strconv.ParseUint(strings.TrimSpace(p[2]), 10, 64); e == nil {
v *= 1024 * 1024
d.MemoryTotalBytes = &v
}
if v, e := strconv.ParseUint(strings.TrimSpace(p[3]), 10, 64); e == nil {
v *= 1024 * 1024
d.MemoryUsedBytes = &v
}
if v, e := strconv.ParseFloat(strings.TrimSpace(p[4]), 64); e == nil {
d.TemperatureC = &v
}
out = append(out, d)
}
return out
}
func sampleMacGPU(parent context.Context) protocol.ServerGPUStats {
ctx, cancel := context.WithTimeout(parent, 3*time.Second)
defer cancel()
out, e := exec.CommandContext(ctx, "system_profiler", "SPDisplaysDataType", "-json").Output()
if e != nil {
return protocol.ServerGPUStats{Reason: "system_profiler unavailable"}
}
var v struct {
Items []struct {
Chipset string `json:"sppci_model"`
Vendor string `json:"spdisplays_vendor"`
} `json:"SPDisplaysDataType"`
}
if json.Unmarshal(out, &v) != nil || len(v.Items) == 0 {
return protocol.ServerGPUStats{Reason: "no display GPU found"}
}
r := protocol.ServerGPUStats{Available: true}
for _, i := range v.Items {
r.Devices = append(r.Devices, protocol.ServerGPUDevice{Name: i.Chipset, Vendor: i.Vendor})
}
return r
}