2020-05-04 20:46:48 +00:00
|
|
|
package internal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2020-08-10 17:43:49 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"strings"
|
2020-05-04 20:46:48 +00:00
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
var sysCPU struct {
|
|
|
|
once sync.Once
|
|
|
|
err error
|
|
|
|
num int
|
|
|
|
}
|
|
|
|
|
|
|
|
// PossibleCPUs returns the max number of CPUs a system may possibly have
|
|
|
|
// Logical CPU numbers must be of the form 0-n
|
|
|
|
func PossibleCPUs() (int, error) {
|
|
|
|
sysCPU.once.Do(func() {
|
2020-08-10 17:43:49 +00:00
|
|
|
sysCPU.num, sysCPU.err = parseCPUsFromFile("/sys/devices/system/cpu/possible")
|
2020-05-04 20:46:48 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return sysCPU.num, sysCPU.err
|
|
|
|
}
|
|
|
|
|
2020-08-10 17:43:49 +00:00
|
|
|
func parseCPUsFromFile(path string) (int, error) {
|
|
|
|
spec, err := ioutil.ReadFile(path)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2020-05-04 20:46:48 +00:00
|
|
|
|
2020-08-10 17:43:49 +00:00
|
|
|
n, err := parseCPUs(string(spec))
|
|
|
|
if err != nil {
|
|
|
|
return 0, fmt.Errorf("can't parse %s: %v", path, err)
|
|
|
|
}
|
2020-05-04 20:46:48 +00:00
|
|
|
|
2020-08-10 17:43:49 +00:00
|
|
|
return n, nil
|
2020-05-04 20:46:48 +00:00
|
|
|
}
|
|
|
|
|
2020-08-10 17:43:49 +00:00
|
|
|
// parseCPUs parses the number of cpus from a string produced
|
|
|
|
// by bitmap_list_string() in the Linux kernel.
|
|
|
|
// Multiple ranges are rejected, since they can't be unified
|
|
|
|
// into a single number.
|
|
|
|
// This is the format of /sys/devices/system/cpu/possible, it
|
|
|
|
// is not suitable for /sys/devices/system/cpu/online, etc.
|
|
|
|
func parseCPUs(spec string) (int, error) {
|
|
|
|
if strings.Trim(spec, "\n") == "0" {
|
|
|
|
return 1, nil
|
2020-05-04 20:46:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var low, high int
|
2020-08-10 17:43:49 +00:00
|
|
|
n, err := fmt.Sscanf(spec, "%d-%d\n", &low, &high)
|
|
|
|
if n != 2 || err != nil {
|
|
|
|
return 0, fmt.Errorf("invalid format: %s", spec)
|
2020-05-04 20:46:48 +00:00
|
|
|
}
|
2020-08-10 17:43:49 +00:00
|
|
|
if low != 0 {
|
|
|
|
return 0, fmt.Errorf("CPU spec doesn't start at zero: %s", spec)
|
2020-05-04 20:46:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// cpus is 0 indexed
|
|
|
|
return high + 1, nil
|
|
|
|
}
|