Debian Codegraph @

examples/cgroup_skb/main.go

raw symbols SCIP
1 //go:build linux
2
3 // This program demonstrates attaching an eBPF program to a control group.
4 // The eBPF program will be attached as an egress filter,
5 // receiving an `__sk_buff` pointer for each outgoing packet.
6 // It prints the count of total packets every second.
7 package main
8
9 import (
10 "bufio"
11 "errors"
12 "log"
13 "os"
14 "strings"
15 "time"
16
17 "github.com/cilium/ebpf"
18 "github.com/cilium/ebpf/link"
19 "github.com/cilium/ebpf/rlimit"
20 )
21
22 //go:generate go tool bpf2go -tags linux bpf cgroup_skb.c -- -I../headers
23
24 func main() {
25 // Allow the current process to lock memory for eBPF resources.
26 if err := rlimit.RemoveMemlock(); err != nil {
27 log.Fatal(err)
28 }
29
30 // Load pre-compiled programs and maps into the kernel.
31 objs := bpfObjects{}
32 if err := loadBpfObjects(&objs, nil); err != nil {
33 log.Fatalf("loading objects: %v", err)
34 }
35 defer objs.Close()
36
37 // Get the first-mounted cgroupv2 path.
38 cgroupPath, err := detectCgroupPath()
39 if err != nil {
40 log.Fatal(err)
41 }
42
43 // Link the count_egress_packets program to the cgroup.
44 l, err := link.AttachCgroup(link.CgroupOptions{
45 Path: cgroupPath,
46 Attach: ebpf.AttachCGroupInetEgress,
47 Program: objs.CountEgressPackets,
48 })
49 if err != nil {
50 log.Fatal(err)
51 }
52 defer l.Close()
53
54 log.Println("Counting packets...")
55
56 // Read loop reporting the total amount of times the kernel
57 // function was entered, once per second.
58 ticker := time.NewTicker(1 * time.Second)
59 defer ticker.Stop()
60
61 for range ticker.C {
62 var value uint64
63 if err := objs.PktCount.Lookup(uint32(0), &value); err != nil {
64 log.Fatalf("reading map: %v", err)
65 }
66 log.Printf("number of packets: %d\n", value)
67 }
68 }
69
70 // detectCgroupPath returns the first-found mount point of type cgroup2
71 // and stores it in the cgroupPath global variable.
72 func detectCgroupPath() (string, error) {
73 f, err := os.Open("/proc/mounts")
74 if err != nil {
75 return "", err
76 }
77 defer f.Close()
78
79 scanner := bufio.NewScanner(f)
80 for scanner.Scan() {
81 // example fields: cgroup2 /sys/fs/cgroup/unified cgroup2 rw,nosuid,nodev,noexec,relatime 0 0
82 fields := strings.Split(scanner.Text(), " ")
83 if len(fields) >= 3 && fields[2] == "cgroup2" {
84 return fields[1], nil
85 }
86 }
87
88 return "", errors.New("cgroup2 not mounted")
89 }