Debian Codegraph @

internal/linux/cpu.go

raw symbols SCIP
1 package linux
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7 )
8
9 func ParseCPUsFromFile(path string) (int, error) {
10 spec, err := os.ReadFile(path)
11 if err != nil {
12 return 0, err
13 }
14
15 n, err := parseCPUs(string(spec))
16 if err != nil {
17 return 0, fmt.Errorf("can't parse %s: %v", path, err)
18 }
19
20 return n, nil
21 }
22
23 // parseCPUs parses the number of cpus from a string produced
24 // by bitmap_list_string() in the Linux kernel.
25 // Multiple ranges are rejected, since they can't be unified
26 // into a single number.
27 // This is the format of /sys/devices/system/cpu/possible, it
28 // is not suitable for /sys/devices/system/cpu/online, etc.
29 func parseCPUs(spec string) (int, error) {
30 if strings.Trim(spec, "\n") == "0" {
31 return 1, nil
32 }
33
34 var low, high int
35 n, err := fmt.Sscanf(spec, "%d-%d\n", &low, &high)
36 if n != 2 || err != nil {
37 return 0, fmt.Errorf("invalid format: %s", spec)
38 }
39 if low != 0 {
40 return 0, fmt.Errorf("CPU spec doesn't start at zero: %s", spec)
41 }
42
43 // cpus is 0 indexed
44 return high + 1, nil
45 }