aboutsummaryrefslogtreecommitdiffstats
path: root/extras/hs-test/cpu.go
blob: 9a034ed2096db8db0c0c37aedb86f72bd896f089 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main

import (
	"bufio"
	"fmt"
	"os"
)

var CPU_PATH = "/sys/fs/cgroup/cpuset.cpus.effective"

type CpuContext struct {
	cpuAllocator *CpuAllocatorT
	cpus         []int
}

func (c *CpuContext) Release() {
	c.cpuAllocator.cpus = append(c.cpuAllocator.cpus, c.cpus...)
	c.cpus = c.cpus[:0] // empty the list
}

type CpuAllocatorT struct {
	cpus []int
}

var cpuAllocator *CpuAllocatorT = nil

func (c *CpuAllocatorT) Allocate(nCpus int) (*CpuContext, error) {
	var cpuCtx CpuContext

	if len(c.cpus) < nCpus {
		return nil, fmt.Errorf("could not allocate %d CPUs; available: %d", nCpus, len(c.cpus))
	}
	cpuCtx.cpus = c.cpus[0:nCpus]
	cpuCtx.cpuAllocator = c
	c.cpus = c.cpus[nCpus:]
	return &cpuCtx, nil
}

func (c *CpuAllocatorT) readCpus() error {
	var first, last int
	file, err := os.Open(CPU_PATH)
	if err != nil {
		return err
	}
	defer file.Close()

	sc := bufio.NewScanner(file)
	sc.Scan()
	line := sc.Text()
	_, err = fmt.Sscanf(line, "%d-%d", &first, &last)
	if err != nil {
		return err
	}
	for i := first; i <= last; i++ {
		c.cpus = append(c.cpus, i)
	}
	return nil
}

func CpuAllocator() (*CpuAllocatorT, error) {
	if cpuAllocator == nil {
		cpuAllocator = new(CpuAllocatorT)
		err := cpuAllocator.readCpus()
		if err != nil {
			return nil, err
		}
	}
	return cpuAllocator, nil
}