...

Source file src/github.com/cilium/ebpf/internal/testutils/cgroup.go

Documentation: github.com/cilium/ebpf/internal/testutils

     1  package testutils
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"strings"
     7  	"sync"
     8  	"testing"
     9  
    10  	"golang.org/x/sys/unix"
    11  )
    12  
    13  var cgroup2 = struct {
    14  	once sync.Once
    15  	path string
    16  	err  error
    17  }{}
    18  
    19  func cgroup2Path() (string, error) {
    20  	cgroup2.once.Do(func() {
    21  		mounts, err := os.ReadFile("/proc/mounts")
    22  		if err != nil {
    23  			cgroup2.err = err
    24  			return
    25  		}
    26  
    27  		for _, line := range strings.Split(string(mounts), "\n") {
    28  			mount := strings.SplitN(line, " ", 3)
    29  			if mount[0] == "cgroup2" {
    30  				cgroup2.path = mount[1]
    31  				return
    32  			}
    33  
    34  			continue
    35  		}
    36  
    37  		cgroup2.err = errors.New("cgroup2 not mounted")
    38  	})
    39  
    40  	if cgroup2.err != nil {
    41  		return "", cgroup2.err
    42  	}
    43  
    44  	return cgroup2.path, nil
    45  }
    46  
    47  func CreateCgroup(tb testing.TB) *os.File {
    48  	tb.Helper()
    49  
    50  	cg2, err := cgroup2Path()
    51  	if err != nil {
    52  		tb.Fatal("Can't locate cgroup2 mount:", err)
    53  	}
    54  
    55  	cgdir, err := os.MkdirTemp(cg2, "ebpf-link")
    56  	if err != nil {
    57  		tb.Fatal("Can't create cgroupv2:", err)
    58  	}
    59  
    60  	cgroup, err := os.Open(cgdir)
    61  	if err != nil {
    62  		os.Remove(cgdir)
    63  		tb.Fatal(err)
    64  	}
    65  	tb.Cleanup(func() {
    66  		cgroup.Close()
    67  		os.Remove(cgdir)
    68  	})
    69  
    70  	return cgroup
    71  }
    72  
    73  func GetCgroupIno(t *testing.T, cgroup *os.File) uint64 {
    74  	cgroupStat := unix.Stat_t{}
    75  	err := unix.Fstat(int(cgroup.Fd()), &cgroupStat)
    76  	if err != nil {
    77  		t.Fatal(err)
    78  	}
    79  
    80  	return cgroupStat.Ino
    81  }
    82  

View as plain text