github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/internal/testutils/cgroup.go (about) 1 package testutils 2 3 import ( 4 "errors" 5 "os" 6 "strings" 7 "sync" 8 "testing" 9 10 "github.com/cilium/ebpf/internal/unix" 11 ) 12 13 var cgroup2Path = sync.OnceValues(func() (string, error) { 14 mounts, err := os.ReadFile("/proc/mounts") 15 if err != nil { 16 return "", err 17 } 18 19 for _, line := range strings.Split(string(mounts), "\n") { 20 mount := strings.SplitN(line, " ", 3) 21 if mount[0] == "cgroup2" { 22 return mount[1], nil 23 } 24 25 continue 26 } 27 28 return "", errors.New("cgroup2 not mounted") 29 }) 30 31 func CreateCgroup(tb testing.TB) *os.File { 32 tb.Helper() 33 34 cg2, err := cgroup2Path() 35 if err != nil { 36 tb.Fatal("Can't locate cgroup2 mount:", err) 37 } 38 39 cgdir, err := os.MkdirTemp(cg2, "ebpf-link") 40 if err != nil { 41 tb.Fatal("Can't create cgroupv2:", err) 42 } 43 44 cgroup, err := os.Open(cgdir) 45 if err != nil { 46 os.Remove(cgdir) 47 tb.Fatal(err) 48 } 49 tb.Cleanup(func() { 50 cgroup.Close() 51 os.Remove(cgdir) 52 }) 53 54 return cgroup 55 } 56 57 func GetCgroupIno(t *testing.T, cgroup *os.File) uint64 { 58 cgroupStat := unix.Stat_t{} 59 err := unix.Fstat(int(cgroup.Fd()), &cgroupStat) 60 if err != nil { 61 t.Fatal(err) 62 } 63 64 return cgroupStat.Ino 65 }