-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.go
93 lines (75 loc) · 2.16 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"log"
"net"
"os"
"path/filepath"
"github.com/cilium/ebpf/link"
"github.com/iovisor/gobpf/pkg/bpffs"
"github.com/spf13/cobra"
)
const bpffsPath = "bpffs"
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang xdptailcall ./xdp_tailcall.c -- -D__TARGET_ARCH_x86 -I../headers -Wall
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang tcmd ./tc_metadata.c -- -D__TARGET_ARCH_x86 -I../headers -Wall
var flags struct {
device string
}
var rootCmd = cobra.Command{
Use: "xdpmetadata",
}
func init() {
rootCmd.Run = func(cmd *cobra.Command, args []string) {
runXDPtailcall()
}
flag := rootCmd.PersistentFlags()
flag.StringVar(&flags.device, "dev", "", "device to run XDP")
}
func runXDPtailcall() {
ifiDev, err := net.InterfaceByName(flags.device)
if err != nil {
log.Fatalf("Failed to fetch device info of %s: %v", flags.device, err)
}
var obj xdptailcallObjects
if err := loadXdptailcallObjects(&obj, nil); err != nil {
log.Fatalf("Failed to load xdp_tailcall bpf obj: %v", err)
}
defer obj.Close()
if err := obj.XdpProgs.Put(uint32(0), obj.XdpFn); err != nil {
log.Fatalf("Failed to save xdp_fn to xdp_progs: %v", err)
}
mapPinPath := filepath.Join(bpffsPath, "xdp_progs")
if err := obj.XdpProgs.Pin(mapPinPath); err != nil {
log.Fatalf("Failed to pin xdp_pros to %s: %v", "xdp_progs", err)
}
xdp, err := link.AttachXDP(link.XDPOptions{
Program: obj.XdpTailcall,
Interface: ifiDev.Index,
Flags: link.XDPGenericMode,
})
if err != nil {
log.Fatalf("Failed to attach xdp_tailcall to %s: %v", flags.device, err)
}
defer xdp.Close()
devPinPath := filepath.Join(bpffsPath, flags.device)
if err := xdp.Pin(devPinPath); err != nil {
log.Fatalf("Failed to pin xdp_tailcall to %s: %v", flags.device, err)
}
log.Printf("xdp_tailcall is running on %s\n", flags.device)
}
func checkBpffs() {
_ = os.Mkdir(bpffsPath, 0o700)
mounted, _ := bpffs.IsMountedAt(bpffsPath)
if mounted {
return
}
err := bpffs.MountAt(bpffsPath)
if err != nil {
log.Fatalf("Failed to mount -t bpf %s: %v", bpffsPath, err)
}
}
func main() {
checkBpffs()
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}