Debian Codegraph @

examples/tcx/main.go

raw symbols SCIP
1 //go:build linux
2
3 // This program demonstrates attaching an eBPF program to a network interface
4 // with Linux TCX (Traffic Control with eBPF). The program counts ingress and egress
5 // packets using two variables. The userspace program (Go code in this file)
6 // prints the contents of the two variables to stdout every second.
7 // This example depends on tcx bpf_link, available in Linux kernel version 6.6 or newer.
8 package main
9
10 import (
11 "fmt"
12 "log"
13 "net"
14 "os"
15 "time"
16
17 "github.com/cilium/ebpf"
18 "github.com/cilium/ebpf/link"
19 )
20
21 //go:generate go tool bpf2go -tags linux bpf tcx.c -- -I../headers
22 func main() {
23 if len(os.Args) < 2 {
24 log.Fatalf("Please specify a network interface")
25 }
26
27 // Look up the network interface by name.
28 ifaceName := os.Args[1]
29 iface, err := net.InterfaceByName(ifaceName)
30 if err != nil {
31 log.Fatalf("lookup network iface %q: %s", ifaceName, err)
32 }
33
34 // Load pre-compiled programs into the kernel.
35 objs := bpfObjects{}
36 if err := loadBpfObjects(&objs, nil); err != nil {
37 log.Fatalf("loading objects: %s", err)
38 }
39 defer objs.Close()
40
41 // Attach the program to Ingress TC.
42 l, err := link.AttachTCX(link.TCXOptions{
43 Interface: iface.Index,
44 Program: objs.IngressProgFunc,
45 Attach: ebpf.AttachTCXIngress,
46 })
47 if err != nil {
48 log.Fatalf("could not attach TCx program: %s", err)
49 }
50 defer l.Close()
51
52 log.Printf("Attached TCx program to INGRESS iface %q (index %d)", iface.Name, iface.Index)
53
54 // Attach the program to Egress TC.
55 l2, err := link.AttachTCX(link.TCXOptions{
56 Interface: iface.Index,
57 Program: objs.EgressProgFunc,
58 Attach: ebpf.AttachTCXEgress,
59 })
60 if err != nil {
61 log.Fatalf("could not attach TCx program: %s", err)
62 }
63 defer l2.Close()
64
65 log.Printf("Attached TCx program to EGRESS iface %q (index %d)", iface.Name, iface.Index)
66 log.Printf("Press Ctrl-C to exit and remove the program")
67
68 // Print the contents of the counters maps.
69 ticker := time.NewTicker(1 * time.Second)
70 defer ticker.Stop()
71 for range ticker.C {
72 s, err := formatCounters(objs.IngressPktCount, objs.EgressPktCount)
73 if err != nil {
74 log.Printf("Error reading map: %s", err)
75 continue
76 }
77
78 log.Printf("Packet Count: %s\n", s)
79 }
80 }
81
82 func formatCounters(ingressVar, egressVar *ebpf.Variable) (string, error) {
83 var (
84 ingressPacketCount uint64
85 egressPacketCount uint64
86 )
87
88 // retrieve value from the ingress map
89 if err := ingressVar.Get(&ingressPacketCount); err != nil {
90 return "", err
91 }
92
93 // retrieve value from the egress map
94 if err := egressVar.Get(&egressPacketCount); err != nil {
95 return "", err
96 }
97
98 return fmt.Sprintf("%10v Ingress, %10v Egress", ingressPacketCount, egressPacketCount), nil
99 }