12 var CgroupPath = "/sys/fs/cgroup/"
14 type CpuContext struct {
15 cpuAllocator *CpuAllocatorT
19 func (c *CpuContext) Release() {
20 c.cpuAllocator.cpus = append(c.cpuAllocator.cpus, c.cpus...)
21 c.cpus = c.cpus[:0] // empty the list
24 type CpuAllocatorT struct {
28 var cpuAllocator *CpuAllocatorT = nil
30 func (c *CpuAllocatorT) Allocate(nCpus int) (*CpuContext, error) {
33 if len(c.cpus) < nCpus {
34 return nil, fmt.Errorf("could not allocate %d CPUs; available: %d", nCpus, len(c.cpus))
36 cpuCtx.cpus = c.cpus[0:nCpus]
37 cpuCtx.cpuAllocator = c
38 c.cpus = c.cpus[nCpus:]
42 func (c *CpuAllocatorT) readCpus() error {
45 // Path depends on cgroup version. We need to check which version is in use.
46 // For that following command can be used: 'stat -fc %T /sys/fs/cgroup/'
47 // In case the output states 'cgroup2fs' then cgroups v2 is used, 'tmpfs' in case cgroups v1.
48 cmd := exec.Command("stat", "-fc", "%T", "/sys/fs/cgroup/")
49 byteOutput, err := cmd.CombinedOutput()
54 if strings.Contains(string(byteOutput), "tmpfs") {
55 CpuPath += "cpuset/cpuset.effective_cpus"
56 } else if strings.Contains(string(byteOutput), "cgroup2fs") {
57 CpuPath += "cpuset.cpus.effective"
59 return errors.New("cgroup unknown fs: " + string(byteOutput))
62 file, err := os.Open(CpuPath)
68 sc := bufio.NewScanner(file)
71 _, err = fmt.Sscanf(line, "%d-%d", &first, &last)
75 for i := first; i <= last; i++ {
76 c.cpus = append(c.cpus, i)
81 func CpuAllocator() (*CpuAllocatorT, error) {
82 if cpuAllocator == nil {
83 cpuAllocator = new(CpuAllocatorT)
84 err := cpuAllocator.readCpus()
89 return cpuAllocator, nil