add memory stats

This commit is contained in:
alu
2026-08-06 11:58:34 -07:00
parent 0998633e5c
commit b99bb45877
14 changed files with 448 additions and 143 deletions
+32
View File
@@ -0,0 +1,32 @@
package drivers
type TemperatureSensor struct {
path string
Name string
TempC float64
}
type TemperatureDriver interface {
ReadTemperatureSensors() ([]TemperatureSensor, error)
}
type PowerSensor struct {
path string
Name string
Watts float64
}
type PowerDriver interface {
ReadPowerSensors() ([]PowerSensor, error)
}
type ClockSensor struct {
path string
number int
Name string
FrequencyGHz float64
}
type ClockDriver interface {
ReadClockSensors() ([]ClockSensor, error)
}
+76
View File
@@ -0,0 +1,76 @@
package drivers
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type HwmonDriver struct {
hwmonDir string
hwmonDriver string
}
func NewHwmonDriver(expectedDrivers []string) *HwmonDriver {
// Locate hwmon path
dirs, err := filepath.Glob("/sys/class/hwmon/hwmon*")
if err != nil {
return nil
}
for _, dir := range dirs {
nameRaw, err := os.ReadFile(filepath.Join(dir, "name"))
name := strings.TrimSpace(string(nameRaw))
if err == nil {
for _, driver := range expectedDrivers {
if driver == name {
return &HwmonDriver{
hwmonDir: dir,
hwmonDriver: driver,
}
}
}
}
}
return nil
}
func (r *HwmonDriver) ReadTemperatureSensors() ([]TemperatureSensor, error) {
inputs, err := filepath.Glob(filepath.Join(r.hwmonDir, "temp*_input"))
if err != nil || len(inputs) == 0 {
return nil, fmt.Errorf("no temperature inputs found in %s", r.hwmonDir)
}
temps := make([]TemperatureSensor, 0, len(inputs))
for _, inputPath := range inputs {
valBytes, err := os.ReadFile(inputPath)
if err != nil {
continue
}
milliC, err := strconv.ParseFloat(strings.TrimSpace(string(valBytes)), 64)
if err != nil {
continue
}
labelPath := strings.TrimSuffix(inputPath, "_input") + "_label"
label := ""
if lBytes, err := os.ReadFile(labelPath); err == nil {
label = strings.TrimSpace(string(lBytes))
} else {
label = filepath.Base(strings.TrimSuffix(inputPath, "_input"))
}
temps = append(temps, TemperatureSensor{
path: inputPath,
Name: label,
TempC: milliC / 1000.0,
})
}
return temps, nil
}
+123
View File
@@ -0,0 +1,123 @@
package drivers
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const milliJoulePerJoule = float64(1000000)
type EnergyState struct {
lastEnergy uint64
lastTime time.Time
}
type RaplDriver struct {
energyState map[string]EnergyState
}
func NewRaplDriver() *RaplDriver {
return &RaplDriver{
energyState: map[string]EnergyState{},
}
}
func (r *RaplDriver) ReadPowerSensors() ([]PowerSensor, error) {
powerSensors := []PowerSensor{}
patterns := []string{
"/sys/class/powercap/intel-rapl*/energy_uj",
"/sys/class/powercap/intel-rapl/intel-rapl*/energy_uj",
"/sys/class/powercap/intel-rapl/intel-rapl*/*/energy_uj",
"/sys/class/powercap/intel-rapl:*/energy_uj",
"/sys/class/powercap/intel-rapl:*/*/energy_uj",
}
energyInputs := []string{}
unique := make(map[string]bool)
for _, pattern := range patterns {
matches, _ := filepath.Glob(pattern)
for _, match := range matches {
realPath, err := filepath.EvalSymlinks(match)
if err != nil {
realPath = match
}
if !unique[realPath] {
unique[realPath] = true
energyInputs = append(energyInputs, realPath)
}
}
}
if len(energyInputs) == 0 {
return powerSensors, fmt.Errorf("found no compatible rapl drivers")
}
r.calculateEnergyDelta(energyInputs, &powerSensors)
return powerSensors, nil
}
func getRaplLabel(inputPath string) string {
dir := filepath.Dir(inputPath)
if nameBytes, err := os.ReadFile(filepath.Join(dir, "name")); err == nil {
return strings.TrimSpace(string(nameBytes))
}
return filepath.Base(dir)
}
func (r *RaplDriver) calculateEnergyDelta(inputs []string, out *[]PowerSensor) {
for _, path := range inputs {
now := time.Now()
valBytes, err := os.ReadFile(path)
if err != nil {
continue
}
microJoules, err := strconv.ParseUint(strings.TrimSpace(string(valBytes)), 10, 64)
if err != nil {
continue
}
sensorLabel := getRaplLabel(path)
prevState, exists := r.energyState[path]
if !exists {
r.energyState[path] = EnergyState{
lastEnergy: microJoules,
lastTime: now,
}
*out = append(*out, PowerSensor{
Name: sensorLabel,
Watts: 0.0,
})
continue
}
timeDiff := now.Sub(prevState.lastTime).Seconds()
// technically the energy counter could overflow, at ~18 TerraJoules
// the value will be off for that one measurement, then become correct again
energyDiff := float64(microJoules - prevState.lastEnergy)
watts := (energyDiff / milliJoulePerJoule) / timeDiff
r.energyState[path] = EnergyState{
lastEnergy: microJoules,
lastTime: now,
}
*out = append(*out, PowerSensor{
Name: sensorLabel,
Watts: watts,
})
}
}
+68
View File
@@ -0,0 +1,68 @@
package drivers
import (
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
)
type SysDriver struct{}
func NewSysDriver() *SysDriver {
return &SysDriver{}
}
func (r *SysDriver) ReadClockSensors() ([]ClockSensor, error) {
// Glob directly targets scaling_cur_freq for all numerical CPU core paths
freqFiles, err := filepath.Glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq/scaling_cur_freq")
if err != nil {
return nil, fmt.Errorf("failed to glob cpufreq files: %w", err)
}
clockSensors := []ClockSensor{}
for _, path := range freqFiles {
// Example path: /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
// Extract core ID from path segments
parts := strings.Split(path, "/")
if len(parts) < 6 {
continue
}
// Parse "cpu0" -> 0
cpuDir := parts[5]
coreIDStr := strings.TrimPrefix(cpuDir, "cpu")
coreID, err := strconv.Atoi(coreIDStr)
if err != nil {
continue
}
// Read frequency in kHz directly from the matched file path
data, err := os.ReadFile(path)
if err != nil {
continue
}
khz, err := strconv.ParseFloat(strings.TrimSpace(string(data)), 64)
if err != nil {
continue
}
clockSensors = append(clockSensors, ClockSensor{
path: path,
number: coreID,
Name: fmt.Sprintf("core %d", coreID),
FrequencyGHz: khz / 1000000.0, // Convert KHz to GHz
})
}
// Guarantee numerical order by core ID
sort.Slice(clockSensors, func(i, j int) bool {
return clockSensors[i].number < clockSensors[j].number
})
return clockSensors, nil
}