-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscover.go
More file actions
413 lines (378 loc) · 10.8 KB
/
Copy pathdiscover.go
File metadata and controls
413 lines (378 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package main
import (
"bufio"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
// hwPaths holds all sysfs paths discovered once at startup.
type hwPaths struct {
cpuTemp string
cpuModel string
cpuPowerPath string // RAPL energy_uj (requires udev rule — see README)
cpuPowerMax uint64 // max_energy_range_uj for rollover handling
gpuBusy string
gpuName string
gpuTempEdge string
gpuTempJunc string
gpuTempMem string
gpuVRAMUsed string
gpuVRAMTotal string
gpuFan string
gpuPower string
netIface string
}
var hw hwPaths
// cpuHwmonDrivers lists known CPU thermal hwmon drivers in preference order.
var cpuHwmonDrivers = []string{"coretemp", "k10temp", "zenpower"}
// cpuPreferredLabels maps driver → preferred sensor label (package-level temp).
var cpuPreferredLabels = map[string][]string{
"coretemp": {"Package id 0"},
"k10temp": {"Tdie", "Tctl"},
"zenpower": {"Tdie", "Tctl"},
}
// gpuHwmonDrivers lists known GPU hwmon driver names.
var gpuHwmonDrivers = map[string]bool{
"amdgpu": true,
"radeon": true,
"nouveau": true,
}
func discoverHardware() hwPaths {
var h hwPaths
hwmons, _ := filepath.Glob("/sys/class/hwmon/hwmon*")
// CPU: try drivers in preference order, stop at first match.
outer:
for _, driver := range cpuHwmonDrivers {
for _, dir := range hwmons {
name, err := readSysFile(dir + "/name")
if err != nil || name != driver {
continue
}
if path := bestCPUTempPath(dir, driver); path != "" {
h.cpuTemp = path
log.Printf("CPU temp: %s (%s)", path, driver)
break outer
}
}
}
if h.cpuTemp == "" {
log.Printf("WARNING: no CPU thermal sensor found (tried: %s)", strings.Join(cpuHwmonDrivers, ", "))
}
h.cpuModel = detectCPUModel()
// GPU: scan DRM cards, skip connector entries (card0-DP-1 etc.).
cardDirs, _ := filepath.Glob("/sys/class/drm/card*")
for _, cardDir := range cardDirs {
if strings.Contains(filepath.Base(cardDir), "-") {
continue
}
gpuHwmons, _ := filepath.Glob(cardDir + "/device/hwmon/hwmon*")
for _, hwmon := range gpuHwmons {
driverName, err := readSysFile(hwmon + "/name")
if err != nil || !gpuHwmonDrivers[driverName] {
continue
}
if p := cardDir + "/device/gpu_busy_percent"; fileExists(p) {
h.gpuBusy = p
}
assignGPUPaths(&h, hwmon)
if p := cardDir + "/device/mem_info_vram_used"; fileExists(p) {
h.gpuVRAMUsed = p
}
if p := cardDir + "/device/mem_info_vram_total"; fileExists(p) {
h.gpuVRAMTotal = p
}
h.gpuName = detectGPUName(cardDir, driverName)
log.Printf("GPU (%s / %q): card=%s hwmon=%s", driverName, h.gpuName, cardDir, hwmon)
log.Printf(" temps: edge=%s junction=%s mem=%s", h.gpuTempEdge, h.gpuTempJunc, h.gpuTempMem)
log.Printf(" fan=%s power=%s", h.gpuFan, h.gpuPower)
goto doneGPU
}
}
doneGPU:
if h.gpuBusy == "" && h.gpuTempEdge == "" {
log.Printf("WARNING: no GPU sensor found")
}
// CPU RAPL power (Intel). Readable only after the udev rule grants group access.
// To enable: create /etc/udev/rules.d/99-rapl.rules with:
// SUBSYSTEM=="powercap", KERNEL=="intel-rapl:?*", RUN+="/usr/bin/chgrp power %S%p/energy_uj", RUN+="/usr/bin/chmod g+r %S%p/energy_uj"
// Then: sudo udevadm trigger && sudo usermod -aG power $USER (re-login)
raplPkg := "/sys/class/powercap/intel-rapl:0/energy_uj"
if b, err := os.ReadFile(raplPkg); err == nil && len(b) > 0 {
h.cpuPowerPath = raplPkg
if maxStr, err := readSysFile("/sys/class/powercap/intel-rapl:0/max_energy_range_uj"); err == nil {
h.cpuPowerMax, _ = strconv.ParseUint(maxStr, 10, 64)
}
log.Printf("CPU RAPL: %s (max_range=%d µJ)", raplPkg, h.cpuPowerMax)
} else {
log.Printf("CPU RAPL not readable — apply udev rule to enable CPU power monitoring")
}
h.netIface = detectNetIface()
if h.netIface != "" {
log.Printf("Network interface: %s", h.netIface)
} else {
log.Printf("WARNING: no active network interface found")
}
return h
}
// bestCPUTempPath finds the best temp sensor path for a CPU hwmon dir.
// Prefers labeled package-level sensors, falls back to first available.
func bestCPUTempPath(hwmonDir, driver string) string {
inputs, _ := filepath.Glob(hwmonDir + "/temp*_input")
if len(inputs) == 0 {
return ""
}
type sensor struct{ label, path string }
sensors := make([]sensor, 0, len(inputs))
for _, inp := range inputs {
label, _ := readSysFile(strings.TrimSuffix(inp, "_input") + "_label")
sensors = append(sensors, sensor{label, inp})
}
for _, want := range cpuPreferredLabels[driver] {
for _, s := range sensors {
if s.label == want {
return s.path
}
}
}
return sensors[0].path
}
// assignGPUPaths maps temp labels → paths and discovers fan/power for a GPU hwmon.
func assignGPUPaths(h *hwPaths, hwmonDir string) {
inputs, _ := filepath.Glob(hwmonDir + "/temp*_input")
for _, inp := range inputs {
label, _ := readSysFile(strings.TrimSuffix(inp, "_input") + "_label")
switch strings.ToLower(strings.TrimSpace(label)) {
case "edge":
h.gpuTempEdge = inp
case "junction":
h.gpuTempJunc = inp
case "mem":
h.gpuTempMem = inp
}
}
// Fallback by index for drivers without labels.
if h.gpuTempEdge == "" && len(inputs) > 0 {
h.gpuTempEdge = inputs[0]
}
if h.gpuTempJunc == "" && len(inputs) > 1 {
h.gpuTempJunc = inputs[1]
}
if h.gpuTempMem == "" && len(inputs) > 2 {
h.gpuTempMem = inputs[2]
}
if p := hwmonDir + "/fan1_input"; fileExists(p) {
h.gpuFan = p
}
if p := hwmonDir + "/power1_average"; fileExists(p) {
h.gpuPower = p
}
}
// detectNetIface picks the most active non-loopback interface from /proc/net/dev.
func detectNetIface() string {
f, err := os.Open("/proc/net/dev")
if err != nil {
return ""
}
defer f.Close()
var bestIface string
var bestBytes uint64
sc := bufio.NewScanner(f)
sc.Scan() // header line 1
sc.Scan() // header line 2
for sc.Scan() {
line := sc.Text()
colon := strings.IndexByte(line, ':')
if colon < 0 {
continue
}
iface := strings.TrimSpace(line[:colon])
if iface == "lo" {
continue
}
fields := strings.Fields(line[colon+1:])
if len(fields) < 1 {
continue
}
rx, err := strconv.ParseUint(fields[0], 10, 64)
if err != nil {
continue
}
if rx > bestBytes {
bestBytes = rx
bestIface = iface
}
}
return bestIface
}
var pciIDsPaths = []string{
"/usr/share/hwdata/pci.ids",
"/usr/share/misc/pci.ids",
"/usr/share/pci.ids",
}
// detectGPUName resolves the GPU marketing name, trying in order:
// 1. Vulkan device name (Mesa/RADV/NVIDIA have exact names)
// 2. sysfs product_name / marketing_name
// 3. PCI IDs database (3-level subsystem lookup)
// 4. Brand from driver
func detectGPUName(cardDir, driver string) string {
deviceRaw, _ := readSysFile(cardDir + "/device/device")
deviceID := strings.TrimPrefix(strings.ToLower(deviceRaw), "0x")
if name := gpuNameFromVulkan(deviceID); name != "" {
return name
}
for _, field := range []string{"product_name", "marketing_name"} {
if name, err := readSysFile(cardDir + "/device/" + field); err == nil && name != "" {
return name
}
}
if name := lookupPCIName(cardDir); name != "" {
return name
}
switch driver {
case "amdgpu", "radeon":
return "AMD"
case "nouveau":
return "NVIDIA"
}
return ""
}
// gpuNameFromVulkan runs vulkaninfo --summary (once, at startup) and returns
// the device name for the given PCI device ID, stripping the driver suffix.
// Example: "AMD Radeon RX 9070 XT (RADV GFX1201)" → "AMD Radeon RX 9070 XT"
func gpuNameFromVulkan(wantDeviceID string) string {
out, err := exec.Command("vulkaninfo", "--summary").Output()
if err != nil {
return ""
}
type gpuEntry struct {
deviceID string
name string
discrete bool
}
var entries []gpuEntry
var cur gpuEntry
for _, raw := range strings.Split(string(out), "\n") {
line := strings.TrimSpace(raw)
key, val, ok := strings.Cut(line, "=")
if !ok {
continue
}
key = strings.TrimSpace(key)
val = strings.TrimSpace(val)
switch key {
case "deviceID":
cur.deviceID = strings.TrimPrefix(strings.ToLower(val), "0x")
case "deviceType":
cur.discrete = val == "PHYSICAL_DEVICE_TYPE_DISCRETE_GPU"
case "deviceName":
// Strip driver suffix: "AMD Radeon RX 9070 XT (RADV GFX1201)" → "AMD Radeon RX 9070 XT"
if i := strings.LastIndex(val, " ("); i >= 0 {
val = strings.TrimSpace(val[:i])
}
cur.name = val
entries = append(entries, cur)
cur = gpuEntry{}
}
}
// Prefer exact device ID match, then first discrete GPU.
var firstDiscrete string
for _, e := range entries {
if e.deviceID == wantDeviceID {
return e.name
}
if e.discrete && firstDiscrete == "" {
firstDiscrete = e.name
}
}
return firstDiscrete
}
func lookupPCIName(cardDir string) string {
vendorRaw, err1 := readSysFile(cardDir + "/device/vendor")
deviceRaw, err2 := readSysFile(cardDir + "/device/device")
if err1 != nil || err2 != nil {
return ""
}
vendorID := strings.TrimPrefix(strings.ToLower(vendorRaw), "0x")
deviceID := strings.TrimPrefix(strings.ToLower(deviceRaw), "0x")
for _, path := range pciIDsPaths {
if name := searchPCIIDs(path, vendorID, deviceID); name != "" {
return name
}
}
return ""
}
func searchPCIIDs(path, vendorID, deviceID string) string {
f, err := os.Open(path)
if err != nil {
return ""
}
defer f.Close()
inVendor := false
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
if len(line) == 0 || line[0] == '#' {
continue
}
if line[0] == '\t' {
if !inVendor || len(line) < 2 || line[1] == '\t' {
continue
}
rest := line[1:]
if strings.HasPrefix(rest, deviceID) && len(rest) > len(deviceID) {
return cleanPCIDeviceName(strings.TrimSpace(rest[len(deviceID):]))
}
} else {
if inVendor {
break // past our vendor's section
}
inVendor = strings.HasPrefix(line, vendorID+" ") || strings.HasPrefix(line, vendorID+"\t")
}
}
return ""
}
// cleanPCIDeviceName extracts the marketing name from brackets when present.
// "Navi 48 [Radeon RX 9070 XT]" → "Radeon RX 9070 XT"
func cleanPCIDeviceName(name string) string {
if i := strings.Index(name, "["); i >= 0 {
if j := strings.LastIndex(name, "]"); j > i {
return name[i+1 : j]
}
}
return name
}
// detectCPUModel reads /proc/cpuinfo and returns a cleaned model name.
func detectCPUModel() string {
f, err := os.Open("/proc/cpuinfo")
if err != nil {
return ""
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
line := sc.Text()
if !strings.HasPrefix(line, "model name") {
continue
}
parts := strings.SplitN(line, ":", 2)
if len(parts) < 2 {
break
}
name := strings.TrimSpace(parts[1])
name = strings.ReplaceAll(name, "(R)", "")
name = strings.ReplaceAll(name, "(TM)", "")
name = strings.ReplaceAll(name, " ", " ")
if i := strings.Index(name, " @ "); i >= 0 {
name = name[:i]
}
return strings.TrimSpace(name)
}
return ""
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}