Skip to content

Commit

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

Signed-off-by: Pranshu Srivastava <rexagod@gmail.com>
  • Loading branch information
rexagod authored and jritter committed Jul 15, 2024
1 parent b2df17d commit c63cde0
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 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
5 changes: 5 additions & 0 deletions testdata/fixtures.ttar
Original file line number Diff line number Diff line change
Expand Up @@ -13441,6 +13441,11 @@ Mode: 775
Path: fixtures/sys/devices/system/cpu/cpu0/cpufreq
SymlinkTo: ../cpufreq/policy0
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/sys/devices/system/cpu/cpu0/online
Lines: 1
1EOF
Mode: 644
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Directory: fixtures/sys/devices/system/cpu/cpu0/thermal_throttle
Mode: 755
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Expand Down

0 comments on commit c63cde0

Please sign in to comment.