-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbpf_prog_run_test.go
69 lines (55 loc) · 1.49 KB
/
bpf_prog_run_test.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
package main
import (
"testing"
"unsafe"
"github.com/asavie/xdp"
"github.com/cilium/ebpf"
"github.com/vishvananda/netlink"
)
func preparePacketData() []byte {
buf := make([]byte, 14+20+8) // eth + iph + icmph
be.PutUint16(buf[12:14], 0x0800) // ethertype = IPv4
iph := buf[14:]
iph[0] = 0x45 // version = 4, ihl = 5
iph[9] = 1 // protocol = ICMP
icmph := iph[20:]
icmph[0] = 8 // type = ECHO
return buf
}
func TestXDPProgRun(t *testing.T) {
ifi, err := netlink.LinkByName("lo")
if err != nil {
t.Fatalf("Failed to get device info: %v", err)
}
xsk, err := xdp.NewSocket(ifi.Attrs().Index, 0, nil)
if err != nil {
t.Fatalf("Failed to new XDP socket: %v", err)
}
defer xsk.Close()
var obj xdpfnObjects
if err := loadXdpfnObjects(&obj, nil); err != nil {
t.Fatalf("Failed to load XDP bpf obj: %v", err)
}
defer obj.Close()
// Map is required to be populated before running the program for `bpf_redirect_map`.
if err := obj.XdpSockets.Put(uint32(0), uint32(xsk.FD())); err != nil {
t.Fatalf("Failed to update XDP socket bpf map: %v", err)
return
}
data := preparePacketData()
dataOut := make([]byte, len(data)+4)
act, err := obj.XdpFn.Run(&ebpf.RunOptions{
Data: data,
DataOut: dataOut,
})
if err != nil {
t.Fatalf("Failed to run XDP bpf prog: %v", err)
}
if act != 4 { // XDP_REDIRECT
t.Fatalf("Expected action %d, got %d", 4, act)
}
lat := *(*uint32)(unsafe.Pointer(&dataOut[0]))
if lat != 200 {
t.Fatalf("Expected latency %d, got %d", 200, lat)
}
}