/
cgroup.go
66 lines (54 loc) · 1.18 KB
/
cgroup.go
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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package testutils
import (
"errors"
"os"
"strings"
"sync"
"testing"
)
type cache struct {
once sync.Once
path string
err error
}
var c cache
func cgroup2Path() (string, error) {
c.once.Do(func() {
mounts, err := os.ReadFile("/proc/mounts")
if err != nil {
c.path, c.err = "", err
return
}
for _, line := range strings.Split(string(mounts), "\n") {
mount := strings.SplitN(line, " ", 3)
if mount[0] == "cgroup2" {
c.path, c.err = mount[1], nil
return
}
continue
}
c.path, c.err = "", errors.New("cgroup2 not mounted")
})
return c.path, c.err
}
// TempCgroup finds the first cgroup2 mount point on the host and creates a
// temporary cgroup in it. Returns the absolute path to the cgroup.
//
// The cgroup is automatically cleaned up at the end of the test run.
func TempCgroup(tb testing.TB) string {
tb.Helper()
cg2, err := cgroup2Path()
if err != nil {
tb.Fatal("Can't locate cgroup2 mount:", err)
}
cgdir, err := os.MkdirTemp(cg2, "cilium-test")
if err != nil {
tb.Fatal("Can't create cgroupv2:", err)
}
tb.Cleanup(func() {
os.Remove(cgdir)
})
return cgdir
}