ebpf.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package ebpf
  2. import (
  3. "github.com/cilium/ebpf"
  4. "github.com/cilium/ebpf/asm"
  5. "github.com/pkg/errors"
  6. "golang.org/x/sys/unix"
  7. )
  8. // LoadAttachCgroupDeviceFilter installs eBPF device filter program to /sys/fs/cgroup/<foo> directory.
  9. //
  10. // Requires the system to be running in cgroup2 unified-mode with kernel >= 4.15 .
  11. //
  12. // https://github.com/torvalds/linux/commit/ebc614f687369f9df99828572b1d85a7c2de3d92
  13. func LoadAttachCgroupDeviceFilter(insts asm.Instructions, license string, dirFD int) (func() error, error) {
  14. nilCloser := func() error {
  15. return nil
  16. }
  17. // Increase `ulimit -l` limit to avoid BPF_PROG_LOAD error (#2167).
  18. // This limit is not inherited into the container.
  19. memlockLimit := &unix.Rlimit{
  20. Cur: unix.RLIM_INFINITY,
  21. Max: unix.RLIM_INFINITY,
  22. }
  23. _ = unix.Setrlimit(unix.RLIMIT_MEMLOCK, memlockLimit)
  24. spec := &ebpf.ProgramSpec{
  25. Type: ebpf.CGroupDevice,
  26. Instructions: insts,
  27. License: license,
  28. }
  29. prog, err := ebpf.NewProgram(spec)
  30. if err != nil {
  31. return nilCloser, err
  32. }
  33. if err := prog.Attach(dirFD, ebpf.AttachCGroupDevice, unix.BPF_F_ALLOW_MULTI); err != nil {
  34. return nilCloser, errors.Wrap(err, "failed to call BPF_PROG_ATTACH (BPF_CGROUP_DEVICE, BPF_F_ALLOW_MULTI)")
  35. }
  36. closer := func() error {
  37. if err := prog.Detach(dirFD, ebpf.AttachCGroupDevice, unix.BPF_F_ALLOW_MULTI); err != nil {
  38. return errors.Wrap(err, "failed to call BPF_PROG_DETACH (BPF_CGROUP_DEVICE, BPF_F_ALLOW_MULTI)")
  39. }
  40. return nil
  41. }
  42. return closer, nil
  43. }