Skip to content

Commit 1754b78

Browse files
authored
enhancement: Expose CPU online status (#644)
Required for prometheus/node_exporter#873. Signed-off-by: Pranshu Srivastava <[email protected]>
1 parent 51919fd commit 1754b78

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

sysfs/system_cpu.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,16 @@ func (c CPU) ThermalThrottle() (*CPUThermalThrottle, error) {
132132
return t, nil
133133
}
134134

135+
// Online returns the online status of a CPU from `/sys/devices/system/cpu/cpuN/online`.
136+
func (c CPU) Online() (bool, error) {
137+
cpuPath := filepath.Join(string(c), "online")
138+
str, err := util.SysReadFile(cpuPath)
139+
if err != nil {
140+
return false, err
141+
}
142+
return str == "1", nil
143+
}
144+
135145
func parseCPUThermalThrottle(cpuPath string) (*CPUThermalThrottle, error) {
136146
t := CPUThermalThrottle{}
137147
var err error

sysfs/system_cpu_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package sysfs
1818

1919
import (
2020
"errors"
21+
"os"
2122
"reflect"
2223
"testing"
2324
)
@@ -63,6 +64,34 @@ func TestCPUTopology(t *testing.T) {
6364
}
6465
}
6566

67+
func TestCPUOnline(t *testing.T) {
68+
fs, err := NewFS(sysTestFixtures)
69+
if err != nil {
70+
t.Fatal(err)
71+
}
72+
cpus, err := fs.CPUs()
73+
if err != nil {
74+
t.Fatal(err)
75+
}
76+
if want, have := 3, len(cpus); want != have {
77+
t.Errorf("incorrect number of CPUs, have %v, want %v", want, have)
78+
}
79+
cpu0Online, err := cpus[0].Online()
80+
if err != nil {
81+
t.Fatal(err)
82+
}
83+
if want, have := true, cpu0Online; want != have {
84+
t.Errorf("incorrect online status, have %v, want %v", want, have)
85+
}
86+
cpu1Online, err := cpus[1].Online()
87+
if err != nil && !errors.Is(err, os.ErrNotExist) {
88+
t.Fatal(err)
89+
}
90+
if want, have := false, cpu1Online; want != have {
91+
t.Errorf("incorrect online status, have %v, want %v", want, have)
92+
}
93+
}
94+
6695
func TestCPUThermalThrottle(t *testing.T) {
6796
fs, err := NewFS(sysTestFixtures)
6897
if err != nil {

testdata/fixtures.ttar

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13441,6 +13441,11 @@ Mode: 775
1344113441
Path: fixtures/sys/devices/system/cpu/cpu0/cpufreq
1344213442
SymlinkTo: ../cpufreq/policy0
1344313443
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
13444+
Path: fixtures/sys/devices/system/cpu/cpu0/online
13445+
Lines: 1
13446+
1EOF
13447+
Mode: 644
13448+
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1344413449
Directory: fixtures/sys/devices/system/cpu/cpu0/thermal_throttle
1344513450
Mode: 755
1344613451
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

0 commit comments

Comments
 (0)