Skip to content

Commit

Permalink
enhancement: Expose CPU online status
Browse files Browse the repository at this point in the history
Required for prometheus/node_exporter#873.

Signed-off-by: Pranshu Srivastava <[email protected]>
  • Loading branch information
rexagod committed May 30, 2024
1 parent d9448e6 commit 9687001
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 23 deletions.
10 changes: 10 additions & 0 deletions sysfs/system_cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,16 @@ func (c CPU) ThermalThrottle() (*CPUThermalThrottle, error) {
return t, nil
}

// Online returns the online status of a CPU from `/sys/devices/system/cpu/cpuN/online`.
func (c CPU) Online() (bool, error) {
cpuPath := filepath.Join(string(c), "online")
str, err := util.SysReadFile(cpuPath)
if err != nil {
return false, err
}
return str == "1", nil
}

func parseCPUThermalThrottle(cpuPath string) (*CPUThermalThrottle, error) {
t := CPUThermalThrottle{}
var err error
Expand Down
29 changes: 29 additions & 0 deletions sysfs/system_cpu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package sysfs

import (
"errors"
"os"
"reflect"
"testing"
)
Expand Down Expand Up @@ -63,6 +64,34 @@ func TestCPUTopology(t *testing.T) {
}
}

func TestCPUOnline(t *testing.T) {
fs, err := NewFS(sysTestFixtures)
if err != nil {
t.Fatal(err)
}
cpus, err := fs.CPUs()
if err != nil {
t.Fatal(err)
}
if want, have := 3, len(cpus); want != have {
t.Errorf("incorrect number of CPUs, have %v, want %v", want, have)
}
cpu0Online, err := cpus[0].Online()
if err != nil {
t.Fatal(err)
}
if want, have := true, cpu0Online; want != have {
t.Errorf("incorrect online status, have %v, want %v", want, have)
}
cpu1Online, err := cpus[1].Online()
if err != nil && !errors.Is(err, os.ErrNotExist) {
t.Fatal(err)
}
if want, have := false, cpu1Online; want != have {
t.Errorf("incorrect online status, have %v, want %v", want, have)
}
}

func TestCPUThermalThrottle(t *testing.T) {
fs, err := NewFS(sysTestFixtures)
if err != nil {
Expand Down
Loading

0 comments on commit 9687001

Please sign in to comment.