forked from cilium/ebpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
info_test.go
367 lines (312 loc) · 8.71 KB
/
info_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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package ebpf
import (
"errors"
"fmt"
"os"
"strings"
"testing"
"github.com/cilium/ebpf/asm"
"github.com/cilium/ebpf/internal"
"github.com/cilium/ebpf/internal/sys"
"github.com/cilium/ebpf/internal/testutils"
"github.com/cilium/ebpf/internal/unix"
qt "github.com/frankban/quicktest"
)
func TestMapInfoFromProc(t *testing.T) {
hash, err := NewMap(&MapSpec{
Name: "testing",
Type: Hash,
KeySize: 4,
ValueSize: 5,
MaxEntries: 2,
Flags: unix.BPF_F_NO_PREALLOC,
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer hash.Close()
info, err := newMapInfoFromProc(hash.fd)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't get map info:", err)
}
if info.Type != Hash {
t.Error("Expected Hash, got", info.Type)
}
if info.KeySize != 4 {
t.Error("Expected KeySize of 4, got", info.KeySize)
}
if info.ValueSize != 5 {
t.Error("Expected ValueSize of 5, got", info.ValueSize)
}
if info.MaxEntries != 2 {
t.Error("Expected MaxEntries of 2, got", info.MaxEntries)
}
if info.Flags != unix.BPF_F_NO_PREALLOC {
t.Errorf("Expected Flags to be %d, got %d", unix.BPF_F_NO_PREALLOC, info.Flags)
}
if info.Name != "" && info.Name != "testing" {
t.Error("Expected name to be testing, got", info.Name)
}
if _, ok := info.ID(); ok {
t.Error("Expected ID to not be available")
}
nested, err := NewMap(&MapSpec{
Type: ArrayOfMaps,
KeySize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer nested.Close()
_, err = newMapInfoFromProc(nested.fd)
if err != nil {
t.Fatal("Can't get nested map info from /proc:", err)
}
}
func TestProgramInfo(t *testing.T) {
prog := mustSocketFilter(t)
for name, fn := range map[string]func(*sys.FD) (*ProgramInfo, error){
"generic": newProgramInfoFromFd,
"proc": newProgramInfoFromProc,
} {
t.Run(name, func(t *testing.T) {
info, err := fn(prog.fd)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't get program info:", err)
}
if info.Type != SocketFilter {
t.Error("Expected Type to be SocketFilter, got", info.Type)
}
if info.Name != "" && info.Name != "test" {
t.Error("Expected Name to be test, got", info.Name)
}
if want := "d7edec644f05498d"; info.Tag != want {
t.Errorf("Expected Tag to be %s, got %s", want, info.Tag)
}
if id, ok := info.ID(); ok && id == 0 {
t.Error("Expected a valid ID:", id)
} else if name == "proc" && ok {
t.Error("Expected ID to not be available")
}
if name == "proc" {
_, ok := info.CreatedByUID()
qt.Assert(t, ok, qt.IsFalse)
} else {
uid, ok := info.CreatedByUID()
if testutils.IsKernelLessThan(t, "4.15") {
qt.Assert(t, ok, qt.IsFalse)
} else {
qt.Assert(t, ok, qt.IsTrue)
qt.Assert(t, uid, qt.Equals, uint32(os.Getuid()))
}
}
})
}
}
func TestProgramInfoMapIDs(t *testing.T) {
arr, err := NewMap(&MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
})
qt.Assert(t, err, qt.IsNil)
defer arr.Close()
prog, err := NewProgram(&ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.LoadMapPtr(asm.R0, arr.FD()),
asm.LoadImm(asm.R0, 2, asm.DWord),
asm.Return(),
},
License: "MIT",
})
qt.Assert(t, err, qt.IsNil)
defer prog.Close()
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, err, qt.IsNil)
ids, ok := info.MapIDs()
switch {
case testutils.IsKernelLessThan(t, "4.15"):
qt.Assert(t, ok, qt.IsFalse)
qt.Assert(t, ids, qt.HasLen, 0)
default:
qt.Assert(t, ok, qt.IsTrue)
mapInfo, err := arr.Info()
qt.Assert(t, err, qt.IsNil)
mapID, ok := mapInfo.ID()
qt.Assert(t, ok, qt.IsTrue)
qt.Assert(t, ids, qt.ContentEquals, []MapID{mapID})
}
}
func TestProgramInfoMapIDsNoMaps(t *testing.T) {
prog, err := NewProgram(&ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
},
License: "MIT",
})
qt.Assert(t, err, qt.IsNil)
defer prog.Close()
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, err, qt.IsNil)
ids, ok := info.MapIDs()
switch {
case testutils.IsKernelLessThan(t, "4.15"):
qt.Assert(t, ok, qt.IsFalse)
qt.Assert(t, ids, qt.HasLen, 0)
default:
qt.Assert(t, ok, qt.IsTrue)
qt.Assert(t, ids, qt.HasLen, 0)
}
}
func TestScanFdInfoReader(t *testing.T) {
tests := []struct {
fields map[string]interface{}
valid bool
}{
{nil, true},
{map[string]interface{}{"foo": new(string)}, true},
{map[string]interface{}{"zap": new(string)}, false},
{map[string]interface{}{"foo": new(int)}, false},
}
for _, test := range tests {
err := scanFdInfoReader(strings.NewReader("foo:\tbar\n"), test.fields)
if test.valid {
if err != nil {
t.Errorf("fields %v returns an error: %s", test.fields, err)
}
} else {
if err == nil {
t.Errorf("fields %v doesn't return an error", test.fields)
}
}
}
}
// TestStats loads a BPF program once and executes back-to-back test runs
// of the program. See testStats for details.
func TestStats(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.8", "BPF_ENABLE_STATS")
prog := mustSocketFilter(t)
pi, err := prog.Info()
if err != nil {
t.Errorf("failed to get ProgramInfo: %v", err)
}
rc, ok := pi.RunCount()
if !ok {
t.Errorf("expected run count info to be available")
}
if rc != 0 {
t.Errorf("expected a run count of 0 but got %d", rc)
}
rt, ok := pi.Runtime()
if !ok {
t.Errorf("expected runtime info to be available")
}
if rt != 0 {
t.Errorf("expected a runtime of 0ns but got %v", rt)
}
if err := testStats(prog); err != nil {
t.Error(err)
}
}
// BenchmarkStats is a benchmark of TestStats. See testStats for details.
func BenchmarkStats(b *testing.B) {
testutils.SkipOnOldKernel(b, "5.8", "BPF_ENABLE_STATS")
prog := mustSocketFilter(b)
for n := 0; n < b.N; n++ {
if err := testStats(prog); err != nil {
b.Fatal(fmt.Errorf("iter %d: %w", n, err))
}
}
}
// testStats implements the behaviour under test for TestStats
// and BenchmarkStats. First, a test run is executed with runtime statistics
// enabled, followed by another with runtime stats disabled. Counters are only
// expected to increase on the runs where runtime stats are enabled.
//
// Due to runtime behaviour on Go 1.14 and higher, the syscall backing
// (*Program).Test() could be invoked multiple times for each call to Test(),
// resulting in RunCount incrementing by more than one. Expecting RunCount to
// be of a specific value after a call to Test() is therefore not possible.
// See https://golang.org/doc/go1.14#runtime for more details.
func testStats(prog *Program) error {
in := internal.EmptyBPFContext
stats, err := EnableStats(uint32(unix.BPF_STATS_RUN_TIME))
if err != nil {
return fmt.Errorf("failed to enable stats: %v", err)
}
defer stats.Close()
// Program execution with runtime statistics enabled.
// Should increase both runtime and run counter.
if _, _, err := prog.Test(in); err != nil {
return fmt.Errorf("failed to trigger program: %v", err)
}
pi, err := prog.Info()
if err != nil {
return fmt.Errorf("failed to get ProgramInfo: %v", err)
}
rc, ok := pi.RunCount()
if !ok {
return errors.New("expected run count info to be available")
}
if rc < 1 {
return fmt.Errorf("expected a run count of at least 1 but got %d", rc)
}
// Store the run count for the next invocation.
lc := rc
rt, ok := pi.Runtime()
if !ok {
return errors.New("expected runtime info to be available")
}
if rt == 0 {
return errors.New("expected a runtime other than 0ns")
}
// Store the runtime value for the next invocation.
lt := rt
if err := stats.Close(); err != nil {
return fmt.Errorf("failed to disable statistics: %v", err)
}
// Second program execution, with runtime statistics gathering disabled.
// Total runtime and run counters are not expected to increase.
if _, _, err := prog.Test(in); err != nil {
return fmt.Errorf("failed to trigger program: %v", err)
}
pi, err = prog.Info()
if err != nil {
return fmt.Errorf("failed to get ProgramInfo: %v", err)
}
rc, ok = pi.RunCount()
if !ok {
return errors.New("expected run count info to be available")
}
if rc != lc {
return fmt.Errorf("run count unexpectedly increased over previous value (current: %v, prev: %v)", rc, lc)
}
rt, ok = pi.Runtime()
if !ok {
return errors.New("expected runtime info to be available")
}
if rt != lt {
return fmt.Errorf("runtime unexpectedly increased over the previous value (current: %v, prev: %v)", rt, lt)
}
return nil
}
func TestHaveProgramInfoMapIDs(t *testing.T) {
testutils.CheckFeatureTest(t, haveProgramInfoMapIDs)
}