Skip to content

Commit

Permalink
BPFProg: create AttachCgroup to allow Cgroup link attachments
Browse files Browse the repository at this point in the history
Create AttachCgroup(string) to allow the following program types:

- BPF_PROG_TYPE_CGROUP_SKB
- BPF_PROG_TYPE_CGROUP_SOCK
- BPF_PROG_TYPE_CGROUP_DEVICE
- BPF_PROG_TYPE_CGROUP_SOCK_ADDR
- BPF_PROG_TYPE_CGROUP_SYSCTL
- BPF_PROG_TYPE_CGROUP_SOCKOPT

to be attached to a cgroupv2 directory file descriptor, such as:

- /sys/fs/cgroup/unified
- /sys/fs/cgroup/unified/user.slice/user-1000.slice

and on...

Those eBPF program types will be triggered for all processes within the
cgroupv2 they were attached to.
  • Loading branch information
rafaeldtinoco committed Jul 28, 2022
1 parent 53b8dbb commit 40a7f68
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions libbpfgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import (
"fmt"
"net"
"path/filepath"
"strings"
"sync"
"syscall"
"unsafe"
Expand Down Expand Up @@ -237,6 +238,7 @@ const (
Uretprobe
Tracing
XDP
Cgroup
)

type BPFLink struct {
Expand Down Expand Up @@ -1302,6 +1304,36 @@ func (p *BPFProg) SetAttachType(attachType BPFAttachType) {
C.bpf_program__set_expected_attach_type(p.prog, C.enum_bpf_attach_type(int(attachType)))
}

func (p *BPFProg) AttachCgroup(cgroupV2DirPath string) (*BPFLink, error) {
const (
O_DIRECTORY int = 0200000
O_RDONLY int = 00
)
fd, err := syscall.Open(cgroupV2DirPath, O_DIRECTORY|O_RDONLY, 0)
if fd < 0 {
return nil, fmt.Errorf("failed to open cgroupv2 directory path %s: %w", cgroupV2DirPath, err)
}
link := C.bpf_program__attach_cgroup(p.prog, C.int(fd))
if C.IS_ERR_OR_NULL(unsafe.Pointer(link)) {
return nil, errptrError(unsafe.Pointer(link), "failed to attach cgroup on cgroupv2 %s to program %s", cgroupV2DirPath, p.name)
}

// dirName will be used in bpfLink.eventName. eventName follows a format
// convention and is used to better identify link types and what they are
// linked with in case of errors or similar needs. Having eventName as:
// cgroup-progName-/sys/fs/cgroup/unified/ would look weird so replace it
// to be cgroup-progName-sys-fs-cgroup-unified instead.
dirName := strings.ReplaceAll(cgroupV2DirPath[1:], "/", "-")
bpfLink := &BPFLink{
link: link,
prog: p,
linkType: Cgroup,
eventName: fmt.Sprintf("cgroup-%s-%s", p.name, dirName),
}
p.module.links = append(p.module.links, bpfLink)
return bpfLink, nil
}

func (p *BPFProg) AttachXDP(deviceName string) (*BPFLink, error) {
iface, err := net.InterfaceByName(deviceName)
if err != nil {
Expand Down

0 comments on commit 40a7f68

Please sign in to comment.