-
Notifications
You must be signed in to change notification settings - Fork 42
/
manager.go
1590 lines (1407 loc) · 49.5 KB
/
manager.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package manager
import (
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/link"
"github.com/florianl/go-tc"
"github.com/hashicorp/go-multierror"
"golang.org/x/sys/unix"
)
// ConstantEditor - A constant editor tries to rewrite the value of a constant in a compiled eBPF program.
//
// Constant edition only works before the eBPF programs are loaded in the kernel, and therefore before the
// Manager is started. If no program sections are provided, the manager will try to edit the constant in all eBPF programs.
type ConstantEditor struct {
// Name - Name of the constant to rewrite
Name string
// Value - Value to write in the eBPF bytecode. When using the asm load method, the Value has to be a uint64.
Value interface{}
// FailOnMissing - If FailOMissing is set to true, the constant edition process will return an error if the constant
// was missing in at least one program
FailOnMissing bool
// ProbeIdentificationPairs - Identifies the list of programs to edit. If empty, it will apply to all the programs
// of the manager. Will return an error if at least one edition failed.
ProbeIdentificationPairs []ProbeIdentificationPair
}
// TailCallRoute - A tail call route defines how tail calls should be routed between eBPF programs.
//
// The provided eBPF program will be inserted in the provided eBPF program array, at the provided key. The eBPF program
// can be provided by its section or by its *ebpf.Program representation.
type TailCallRoute struct {
// ProgArrayName - Name of the BPF_MAP_TYPE_PROG_ARRAY map as defined in its section SEC("maps/[ProgArray]")
ProgArrayName string
// Key - Key at which the program will be inserted in the ProgArray map
Key uint32
// ProbeIdentificationPair - Selector of the program to insert in the ProgArray map
ProbeIdentificationPair ProbeIdentificationPair
// Program - Program to insert in the ProgArray map
Program *ebpf.Program
}
// MapRoute - A map route defines how multiple maps should be routed between eBPF programs.
//
// The provided eBPF map will be inserted in the provided eBPF array of maps (or hash of maps), at the provided key. The
// inserted eBPF map can be provided by its section or by its *ebpf.Map representation.
type MapRoute struct {
// RoutingMapName - Name of the BPF_MAP_TYPE_ARRAY_OF_MAPS or BPF_MAP_TYPE_HASH_OF_MAPS map, as defined in its
// section SEC("maps/[RoutingMapName]")
RoutingMapName string
// Key - Key at which the program will be inserted in the routing map
Key interface{}
// RoutedName - Section of the map that will be inserted
RoutedName string
// Map - Map to insert in the routing map
Map *ebpf.Map
}
// MapSpecEditorFlag - Flag used to specify what a MapSpecEditor should edit.
type MapSpecEditorFlag uint
const (
EditType MapSpecEditorFlag = 1 << 1
EditMaxEntries MapSpecEditorFlag = 1 << 2
EditFlags MapSpecEditorFlag = 1 << 3
EditInnerMap MapSpecEditorFlag = 1 << 4
)
// MapSpecEditor - A MapSpec editor defines how specific parameters of specific maps should be updated at runtime
//
// For example, this can be used if you need to change the max_entries of a map before it is loaded in the kernel, but
// you don't know what this value should be initially.
type MapSpecEditor struct {
// Type - Type of the map.
Type ebpf.MapType
// MaxEntries - Max Entries of the map.
MaxEntries uint32
// Flags - Flags provided to the kernel during the loading process.
Flags uint32
// EditorFlag - Use this flag to specify what fields should be updated. See MapSpecEditorFlag.
EditorFlag MapSpecEditorFlag
// InnerMap
InnerMap *ebpf.MapSpec
}
// ProbesSelector - A probe selector defines how a probe (or a group of probes) should be activated.
//
// For example, this can be used to specify that out of a group of optional probes, at least one should be activated.
type ProbesSelector interface {
// GetProbesIdentificationPairList - Returns the list of probes that this selector activates
GetProbesIdentificationPairList() []ProbeIdentificationPair
// RunValidator - Ensures that the probes that were successfully activated follow the selector goal.
// For example, see OneOf.
RunValidator(manager *Manager) error
// EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they
// mow select the new one
EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)
}
// ProbeSelector - This selector is used to unconditionally select a probe by its identification pair and validate
// that it is activated
type ProbeSelector struct {
ProbeIdentificationPair
}
// GetProbesIdentificationPairList - Returns the list of probes that this selector activates
func (ps *ProbeSelector) GetProbesIdentificationPairList() []ProbeIdentificationPair {
return []ProbeIdentificationPair{ps.ProbeIdentificationPair}
}
// RunValidator - Ensures that the probes that were successfully activated follow the selector goal.
// For example, see OneOf.
func (ps *ProbeSelector) RunValidator(manager *Manager) error {
p, ok := manager.GetProbe(ps.ProbeIdentificationPair)
if !ok {
return fmt.Errorf("probe not found: %s", ps.ProbeIdentificationPair)
}
if !p.IsRunning() && p.Enabled {
return fmt.Errorf("error:%v, %s", p.GetLastError(), ps.ProbeIdentificationPair.String())
}
if !p.Enabled {
return fmt.Errorf(
"%s: is disabled, add it to the activation list and check that it was not explicitly excluded by the manager options",
ps.ProbeIdentificationPair.String())
}
return nil
}
// EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they
// mow select the new one
func (ps *ProbeSelector) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair) {
if ps.Matches(old) {
ps.ProbeIdentificationPair = new
}
}
// Options - Options of a Manager. These options define how a manager should be initialized.
type Options struct {
// ActivatedProbes - List of the probes that should be activated, identified by their identification string.
// If the list is empty, all probes will be activated.
ActivatedProbes []ProbesSelector
// ExcludedSections - A list of sections that should not even be verified. This list overrides the ActivatedProbes
// list: since the excluded sections aren't loaded in the kernel, all the probes using those sections will be
// deactivated.
// Deprecated: 废弃段信息
ExcludedSections []string
// ExcludedEbpfFuncs 用于存储排除的符号表函数列表。来自ebpf字节码中符号表函数。
ExcludedEbpfFuncs []string
// ConstantsEditor - Post-compilation constant edition. See ConstantEditor for more.
ConstantEditors []ConstantEditor
// MapSpecEditor - Pre-loading MapSpec editors.
MapSpecEditors map[string]MapSpecEditor
// VerifierOptions - Defines the log level of the verifier and the size of its log buffer. Set to 0 to disable
// logging and 1 to get a verbose output of the error. Increase the buffer size if the output is truncated.
VerifierOptions ebpf.CollectionOptions
// MapEditors - External map editor. The provided eBPF maps will overwrite the maps of the Manager if their names
// match.
// This is particularly useful to share maps across Managers (and therefore across isolated eBPF programs), without
// having to use the MapRouter indirection. However this technique only works before the eBPF programs are loaded,
// and therefore before the Manager is started. The keys of the map are the names of the maps to edit, as defined
// in their sections SEC("maps/[name]").
MapEditors map[string]*ebpf.Map
// MapRouter - External map routing. See MapRoute for more.
MapRouter []MapRoute
// TailCallRouter - External tail call routing. See TailCallRoute for more.
TailCallRouter []TailCallRoute
// SymFile - Kernel symbol file. If not provided, the default `/proc/kallsyms` will be used.
SymFile string
// PerfRingBufferSize - Manager-level default value for the perf ring buffers. Defaults to the size of 1 page
// on the system. See PerfMap.PerfRingBuffer for more.
DefaultPerfRingBufferSize int
// Watermark - Manager-level default value for the watermarks of the perf ring buffers.
// See PerfMap.Watermark for more.
DefaultWatermark int
// DefaultKProbeMaxActive - Manager-level default value for the kprobe max active parameter.
// See Probe.MaxActive for more.
DefaultKProbeMaxActive int
// ProbeRetry - Defines the number of times that a probe will retry to attach / detach on error.
DefaultProbeRetry uint
// ProbeRetryDelay - Defines the delay to wait before a probe should retry to attach / detach on error.
DefaultProbeRetryDelay time.Duration
// RLimit - The maps & programs provided to the manager might exceed the maximum allowed memory lock.
// (RLIMIT_MEMLOCK) If a limit is provided here it will be applied when the manager is initialized.
RLimit *unix.Rlimit
// KeepKernelBTF - Defines if the kernel types defined in VerifierOptions.Programs.KernelTypes should be cleaned up
// once the manager is done using them. By default, the manager will clean them up to save up space. DISCLAIMER: if
// your program uses "manager.CloneProgram", you might want to enable "KeepKernelBTF". As a workaround, you can also
// try to strip as much as possible the content of "KernelTypes" to reduce the memory overhead.
KeepKernelBTF bool
}
// netlinkCacheKey - (TC classifier programs only) Key used to recover the netlink cache of an interface
type netlinkCacheKey struct {
Ifindex int32
Netns uint64
}
// netlinkCacheValue - (TC classifier programs only) Netlink socket and qdisc object used to update the classifiers of
// an interface
type netlinkCacheValue struct {
rtNetlink *tc.Tc
schedClsCount int
}
// InstructionPatcherFunc - A function that patches the instructions of a program
// more info https://github.com/DataDog/ebpf-manager/blob/main/manager.go#L158
type InstructionPatcherFunc func(m *Manager) error
// Manager - Helper structure that manages multiple eBPF programs and maps
type Manager struct {
wg *sync.WaitGroup
collectionSpec *ebpf.CollectionSpec
collection *ebpf.Collection
options Options
netlinkCache map[netlinkCacheKey]*netlinkCacheValue
state state
stateLock sync.RWMutex
// Probes - List of probes handled by the manager
Probes []*Probe
// Maps - List of maps handled by the manager. PerfMaps should not be defined here, but instead in the PerfMaps
// section
Maps []*Map
// PerfMaps - List of perf ring buffers handled by the manager
PerfMaps []*PerfMap
RingbufMaps []*RingbufMap
// InstructionPatchers - Callback functions called before loading probes, to
// provide user the ability to perform last minute instruction patching.
InstructionPatchers []InstructionPatcherFunc
}
// DumpMaps - Return a string containing human readable info about eBPF maps
// Dumps the set of maps provided, otherwise dumping all maps with a DumpHandler set.
func (m *Manager) DumpMaps(maps ...string) (string, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return "", ErrManagerNotInitialized
}
var mapsToDump map[string]struct{}
if len(maps) > 0 {
mapsToDump = make(map[string]struct{})
for _, m := range maps {
mapsToDump[m] = struct{}{}
}
}
needDump := func(name string) bool {
if mapsToDump == nil {
// dump all maps
return true
}
_, found := mapsToDump[name]
return found
}
var output strings.Builder
// Look in the list of maps
for _, managerMap := range m.Maps {
if managerMap.DumpHandler != nil && needDump(managerMap.Name) {
output.WriteString(managerMap.DumpHandler(managerMap, m))
}
}
// Look in the list of perf maps
for _, perfMap := range m.PerfMaps {
if perfMap.DumpHandler != nil && needDump(perfMap.Name) {
output.WriteString(perfMap.DumpHandler(perfMap, m))
}
}
return output.String(), nil
}
// GetMap - Return a pointer to the requested eBPF map
// name: name of the map, as defined by its section SEC("maps/[name]")
func (m *Manager) GetMap(name string) (*ebpf.Map, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return nil, false, ErrManagerNotInitialized
}
eBPFMap, ok := m.collection.Maps[name]
if ok {
return eBPFMap, true, nil
}
// Look in the list of maps
for _, managerMap := range m.Maps {
if managerMap.Name == name {
return managerMap.array, true, nil
}
}
// Look in the list of perf maps
for _, perfMap := range m.PerfMaps {
if perfMap.Name == name {
return perfMap.array, true, nil
}
}
return nil, false, nil
}
// GetMapSpec - Return a pointer to the requested eBPF MapSpec. This is useful when duplicating a map.
func (m *Manager) GetMapSpec(name string) (*ebpf.MapSpec, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collectionSpec == nil || m.state < initialized {
return nil, false, ErrManagerNotInitialized
}
eBPFMap, ok := m.collectionSpec.Maps[name]
if ok {
return eBPFMap, true, nil
}
// Look in the list of maps
for _, managerMap := range m.Maps {
if managerMap.Name == name {
return managerMap.arraySpec, true, nil
}
}
// Look in the list of perf maps
for _, perfMap := range m.PerfMaps {
if perfMap.Name == name {
return perfMap.arraySpec, true, nil
}
}
return nil, false, nil
}
// editMapSpec -
func (m *Manager) editMapSpec(name string, mapSpec *ebpf.MapSpec) error {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collectionSpec == nil || m.state < initialized {
return ErrManagerNotInitialized
}
// 判断是否存在该map
_, ok := m.collectionSpec.Maps[name]
if !ok {
return ErrUnknownMap
}
// 覆盖mapSpec
m.collectionSpec.Maps[name] = mapSpec
return nil
}
// GetPerfMap - Select a perf map by its name
func (m *Manager) GetPerfMap(name string) (*PerfMap, bool) {
for _, perfMap := range m.PerfMaps {
if perfMap.Name == name {
return perfMap, true
}
}
return nil, false
}
// GetProgram - Return a pointer to the requested eBPF program
// section: section of the program, as defined by its section SEC("[section]")
// id: unique identifier given to a probe. If UID is empty, then all the programs matching the provided section are
// returned.
func (m *Manager) GetProgram(id ProbeIdentificationPair) ([]*ebpf.Program, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
var programs []*ebpf.Program
if m.collection == nil || m.state < initialized {
return nil, false, ErrManagerNotInitialized
}
if id.UID == "" {
for _, probe := range m.Probes {
if probe.EbpfFuncName == id.EbpfFuncName {
programs = append(programs, probe.program)
}
}
if len(programs) > 0 {
return programs, true, nil
}
prog, ok := m.collection.Programs[id.EbpfFuncName]
return []*ebpf.Program{prog}, ok, nil
}
for _, probe := range m.Probes {
if probe.IdentificationPairMatches(id) {
return []*ebpf.Program{probe.program}, true, nil
}
}
return programs, false, nil
}
// GetProgramSpec - Return a pointer to the requested eBPF program spec
// section: section of the program, as defined by its section SEC("[section]")
// id: unique identifier given to a probe. If UID is empty, then the original program spec with the right section in the
// collection spec (if found) is return
func (m *Manager) GetProgramSpec(id ProbeIdentificationPair) ([]*ebpf.ProgramSpec, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
var programs []*ebpf.ProgramSpec
if m.collectionSpec == nil || m.state < initialized {
return nil, false, ErrManagerNotInitialized
}
if id.UID == "" {
for _, probe := range m.Probes {
//if probe.Section == id.Section {
// programs = append(programs, probe.programSpec)
//}
if probe.EbpfFuncName == id.EbpfFuncName {
programs = append(programs, probe.programSpec)
}
}
if len(programs) > 0 {
return programs, true, nil
}
// prog, ok := m.collectionSpec.Programs[id.Section]
prog, ok := m.collectionSpec.Programs[id.EbpfFuncName]
return []*ebpf.ProgramSpec{prog}, ok, nil
}
for _, probe := range m.Probes {
if probe.IdentificationPairMatches(id) {
return []*ebpf.ProgramSpec{probe.programSpec}, true, nil
}
}
return programs, false, nil
}
// GetProbe - Select a probe by its section and UID
func (m *Manager) GetProbe(id ProbeIdentificationPair) (*Probe, bool) {
for _, managerProbe := range m.Probes {
if managerProbe.IdentificationPairMatches(id) {
return managerProbe, true
}
}
return nil, false
}
// Init - Initialize the manager.
// elf: reader containing the eBPF bytecode
func (m *Manager) Init(elf io.ReaderAt) error {
return m.InitWithOptions(elf, Options{})
}
// InitWithOptions - Initialize the manager.
// elf: reader containing the eBPF bytecode
// options: options provided to the manager to configure its initialization
func (m *Manager) InitWithOptions(elf io.ReaderAt, options Options) error {
m.stateLock.Lock()
if m.state > initialized {
m.stateLock.Unlock()
return ErrManagerRunning
}
m.wg = &sync.WaitGroup{}
m.options = options
m.netlinkCache = make(map[netlinkCacheKey]*netlinkCacheValue)
if m.options.DefaultPerfRingBufferSize == 0 {
m.options.DefaultPerfRingBufferSize = os.Getpagesize()
}
// perform a quick sanity check on the provided probes and maps
if err := m.sanityCheck(); err != nil {
m.stateLock.Unlock()
return err
}
// set resource limit if requested
if m.options.RLimit != nil {
err := unix.Setrlimit(unix.RLIMIT_MEMLOCK, m.options.RLimit)
if err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't adjust RLIMIT_MEMLOCK", err))
}
}
// Load the provided elf buffer
var err error
m.collectionSpec, err = ebpf.LoadCollectionSpecFromReader(elf)
if err != nil {
m.stateLock.Unlock()
return err
}
// check probe field
for _, probe := range m.Probes {
err = probe.checkField()
if err != nil {
return err
}
}
// Remove excluded sections
for _, excludedMatchFun := range m.options.ExcludedEbpfFuncs {
delete(m.collectionSpec.Programs, excludedMatchFun)
}
// Match Maps and program specs
if err := m.matchSpecs(); err != nil {
m.stateLock.Unlock()
return err
}
// Configure activated probes
m.activateProbes()
m.state = initialized
m.stateLock.Unlock()
resetManager := func(m *Manager) {
m.stateLock.Lock()
m.state = reset
m.stateLock.Unlock()
}
// Edit program constants
if len(options.ConstantEditors) > 0 {
if err := m.editConstants(); err != nil {
return err
}
}
// Edit map spec
if len(options.MapSpecEditors) > 0 {
if err := m.editMapSpecs(); err != nil {
return err
}
}
// Edit program maps
if len(options.MapEditors) > 0 {
if err := m.editMaps(options.MapEditors); err != nil {
return err
}
}
// Patch instructions
for _, patcher := range m.InstructionPatchers {
if err := patcher(m); err != nil {
resetManager(m)
return err
}
}
// Load pinned maps and pinned programs to avoid loading them twice
if err := m.loadPinnedObjects(); err != nil {
return err
}
// Load eBPF program with the provided verifier options
if err := m.loadCollection(); err != nil {
return err
}
return nil
}
// Start - Attach eBPF programs, start perf ring readers and apply maps and tail calls routing.
func (m *Manager) Start() error {
m.stateLock.Lock()
if m.state < initialized {
m.stateLock.Unlock()
return ErrManagerNotInitialized
}
if m.state >= running {
m.stateLock.Unlock()
return nil
}
if !m.options.KeepKernelBTF {
// release kernel BTF. It should no longer be needed
m.options.VerifierOptions.Programs.KernelTypes = nil
}
// clean up tracefs TODO 作用是什么?
// Start perf ring readers
for _, perfRing := range m.PerfMaps {
if err := perfRing.Start(); err != nil {
// Clean up
_ = m.stop(CleanInternal)
m.stateLock.Unlock()
return err
}
}
// Start ring buf readers
for _, ringBuf := range m.RingbufMaps {
if err := ringBuf.Start(); err != nil {
// Clean up
m.Stop(CleanInternal)
m.stateLock.Unlock()
return err
}
}
// Attach eBPF programs
for _, probe := range m.Probes {
// ignore the error, they are already collected per probes and will be surfaced by the
// activation validators if needed.
_ = probe.Attach()
}
m.state = running
m.stateLock.Unlock()
// Check probe selectors
var validationErrs error
for _, selector := range m.options.ActivatedProbes {
if err := selector.RunValidator(m); err != nil {
validationErrs = multierror.Append(validationErrs, err)
}
}
if validationErrs != nil {
// Clean up
_ = m.Stop(CleanInternal)
return fmt.Errorf("error:%v, %s", validationErrs, "probes activation validation failed")
}
// Handle Maps router
if err := m.UpdateMapRoutes(m.options.MapRouter...); err != nil {
// Clean up
_ = m.Stop(CleanInternal)
return err
}
// Handle Program router
if err := m.UpdateTailCallRoutes(m.options.TailCallRouter...); err != nil {
// Clean up
_ = m.Stop(CleanInternal)
return err
}
return nil
}
// Stop - Detach all eBPF programs and stop perf ring readers. The cleanup parameter defines which maps should be closed.
// See MapCleanupType for mode.
func (m *Manager) Stop(cleanup MapCleanupType) error {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.state < initialized {
return ErrManagerNotInitialized
}
return m.stop(cleanup)
}
func (m *Manager) stop(cleanup MapCleanupType) error {
var err error
// Stop perf ring readers
for _, perfRing := range m.PerfMaps {
e := perfRing.Stop(cleanup)
if e != nil {
e = errors.New(fmt.Sprintf("error:%v , perf ring reader %s couldn't gracefully shut down", perfRing.Stop(cleanup), perfRing.Name))
}
err = ConcatErrors(err, e)
}
// Stop ring buf readers
for _, ringBuf := range m.RingbufMaps {
e := ringBuf.Stop(cleanup)
if e != nil {
e = errors.New(fmt.Sprintf("error:%v , ring buf reader %s couldn't gracefully shut down", ringBuf.Stop(cleanup), ringBuf.Name))
}
err = ConcatErrors(err, e)
}
// Detach eBPF programs
for _, probe := range m.Probes {
e := probe.Stop()
if e != nil {
e = errors.New(fmt.Sprintf("error:%v , program %s couldn't gracefully shut down", e, probe.EbpfFuncName))
}
err = ConcatErrors(err, e)
}
// Close maps
for _, managerMap := range m.Maps {
e := managerMap.Close(cleanup)
if e != nil {
e = errors.New(fmt.Sprintf("error:%v , couldn't gracefully close map %s", e, managerMap.Name))
}
err = ConcatErrors(err, e)
}
// Close all netlink sockets
for _, entry := range m.netlinkCache {
err = ConcatErrors(err, entry.rtNetlink.Close())
}
// Clean up collection
// Note: we might end up closing the same programs and maps multiple times but the library gracefully handles those
// situations. We can't only rely on the collection to close all maps and programs because some pinned objects were
// removed from the collection.
m.collection.Close()
// Wait for all go routines to stop
m.wg.Wait()
m.state = reset
return err
}
// NewMap - Create a new map using the provided parameters. The map is added to the list of maps managed by the manager.
// Use a MapRoute to make this map available to the programs of the manager.
func (m *Manager) NewMap(spec ebpf.MapSpec, options MapOptions) (*ebpf.Map, error) {
// check if the name of the new map is available
_, exists, _ := m.GetMap(spec.Name)
if exists {
return nil, ErrMapNameInUse
}
// Create the new map
managerMap, err := loadNewMap(spec, options)
if err != nil {
return nil, err
}
// Init map
if err := managerMap.Init(m); err != nil {
// Clean up
_ = managerMap.Close(CleanInternal)
return nil, err
}
// Add map to the list of maps managed by the manager
m.Maps = append(m.Maps, managerMap)
return managerMap.array, nil
}
// CloneMap - Duplicates the spec of an existing map, before creating a new one.
// Use a MapRoute to make this map available to the programs of the manager.
func (m *Manager) CloneMap(name string, newName string, options MapOptions) (*ebpf.Map, error) {
// Select map to clone
oldSpec, exists, err := m.GetMapSpec(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.New(fmt.Sprintf("error:%v , failed to clone maps/%s", ErrUnknownMap, name))
}
// Duplicate spec and create a new map
spec := oldSpec.Copy()
spec.Name = newName
return m.NewMap(*spec, options)
}
// NewPerfRing - Creates a new perf ring and start listening for events.
// Use a MapRoute to make this map available to the programs of the manager.
func (m *Manager) NewPerfRing(spec ebpf.MapSpec, options MapOptions, perfMapOptions PerfMapOptions) (*ebpf.Map, error) {
// check if the name of the new map is available
_, exists, _ := m.GetMap(spec.Name)
if exists {
return nil, ErrMapNameInUse
}
// Create new map and perf ring buffer reader
perfMap, err := loadNewPerfMap(spec, options, perfMapOptions)
if err != nil {
return nil, err
}
// Setup perf buffer reader
if err := perfMap.Init(m); err != nil {
return nil, err
}
// Start perf buffer reader
if err := perfMap.Start(); err != nil {
// clean up
_ = perfMap.Stop(CleanInternal)
return nil, err
}
// Add map to the list of perf ring managed by the manager
m.PerfMaps = append(m.PerfMaps, perfMap)
return perfMap.array, nil
}
// ClonePerfRing - Clone an existing perf map and create a new one with the same spec.
// Use a MapRoute to make this map available to the programs of the manager.
func (m *Manager) ClonePerfRing(name string, newName string, options MapOptions, perfMapOptions PerfMapOptions) (*ebpf.Map, error) {
// Select map to clone
oldSpec, exists, err := m.GetMapSpec(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.New(fmt.Sprintf("error:%v , failed to clone maps/%s: couldn't find map", ErrUnknownMap, name))
}
// Duplicate spec and create a new map
spec := oldSpec.Copy()
spec.Name = newName
return m.NewPerfRing(*spec, options, perfMapOptions)
}
// AddHook - Hook an existing program to a hook point. This is particularly useful when you need to trigger an
// existing program on a hook point that is determined at runtime. For example, you might want to hook an existing
// eBPF TC classifier to the newly created interface of a container. Make sure to specify a unique uid in the new probe,
// you will need it if you want to detach the program later. The original program is selected using the provided UID and
// the section provided in the new probe.
func (m *Manager) AddHook(UID string, newProbe *Probe) error {
oldID := ProbeIdentificationPair{UID, newProbe.EbpfFuncName}
// Look for the eBPF program
progs, found, err := m.GetProgram(oldID)
if err != nil {
return err
}
if !found || len(progs) == 0 {
return errors.New(fmt.Sprintf("error:%v , couldn't find program %v", ErrUnknownMatchFuncName, oldID))
}
prog := progs[0]
progSpecs, found, _ := m.GetProgramSpec(oldID)
if !found || len(progSpecs) == 0 {
return errors.New(fmt.Sprintf("error:%v , couldn't find programSpec %v", ErrUnknownMatchFuncSpec, oldID))
}
progSpec := progSpecs[0]
// Ensure that the new probe is enabled
newProbe.Enabled = true
// Make sure the provided identification pair is unique
_, exists, _ := m.GetProgramSpec(newProbe.GetIdentificationPair())
if exists {
return errors.New(fmt.Sprintf("error:%v , couldn't add probe %v", ErrIdentificationPairInUse, newProbe.GetIdentificationPair()))
}
// Clone program
clonedProg, err := prog.Clone()
if err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't clone %v", err, oldID))
}
newProbe.program = clonedProg
newProbe.programSpec = progSpec
// Init program
if err = newProbe.Init(m); err != nil {
// clean up
_ = newProbe.Stop()
return errors.New(fmt.Sprintf("error:%v , failed to initialize new probe", err))
}
// Pin if needed
if newProbe.PinPath != "" {
if err = newProbe.program.Pin(newProbe.PinPath); err != nil {
// clean up
_ = newProbe.Stop()
return errors.New(fmt.Sprintf("error:%v , couldn't pin new probe", err))
}
}
// Attach program
if err = newProbe.Attach(); err != nil {
// clean up
_ = newProbe.Stop()
return errors.New(fmt.Sprintf("error:%v , couldn't attach new probe", err))
}
// Add probe to the list of probes
m.Probes = append(m.Probes, newProbe)
return nil
}
// DetachHook - Detach an eBPF program from a hook point. If there is only one instance left of this program in the
// kernel, then the probe will be detached but the program will not be closed (so that it can be used later). In that
// case, calling DetachHook has essentially the same effect as calling Detach() on the right Probe instance. However,
// if there are more than one instance in the kernel of the requested program, then the probe selected by (section, UID)
// is detached, and its own version of the program is closed.
func (m *Manager) DetachHook(section string, UID string) error {
oldID := ProbeIdentificationPair{UID, section}
// Check how many instances of the program are left in the kernel
progs, _, err := m.GetProgram(ProbeIdentificationPair{"", section})
if err != nil {
return err
}
shouldStop := len(progs) > 1
// Look for the probe
idToDelete := -1
for id, managerProbe := range m.Probes {
if managerProbe.IdentificationPairMatches(oldID) {
// Detach or stop the probe depending on shouldStop
if shouldStop {
if err = managerProbe.Stop(); err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't stop probe %v", err, oldID))
}
} else {
if err = managerProbe.Detach(); err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't detach probe %v", err, oldID))
}
}
idToDelete = id
}
}
if idToDelete >= 0 {
m.Probes = append(m.Probes[:idToDelete], m.Probes[idToDelete+1:]...)
}
return nil
}
// CloneProgram - Create a clone of a program, load it in the kernel and attach it to its hook point. Since the eBPF
// program instructions are copied before the program is loaded, you can edit them with a ConstantEditor, or remap
// the eBPF maps as you like. This is particularly useful to workaround the absence of Array of Maps and Hash of Maps:
// first create the new maps you need, then clone the program you're interested in and rewrite it with the new maps,
// using a MapEditor. The original program is selected using the provided UID and the section provided in the new probe.
// Note that the BTF based constant edition will note work with this method.
func (m *Manager) CloneProgram(UID string, newProbe *Probe, constantsEditors []ConstantEditor, mapEditors map[string]*ebpf.Map) error {
oldID := ProbeIdentificationPair{UID, newProbe.EbpfFuncName}
// Find the program specs
progSpecs, found, err := m.GetProgramSpec(oldID)
if err != nil {
return err
}
if !found || len(progSpecs) == 0 {
return errors.New(fmt.Sprintf("error:%v , couldn't find programSpec %v", ErrUnknownMatchFuncSpec, oldID))
}
progSpec := progSpecs[0]
// Check if the new probe has a unique identification pair
_, exists, _ := m.GetProgram(newProbe.GetIdentificationPair())
if exists {
return errors.New(fmt.Sprintf("error:%v , couldn't add probe %v", ErrIdentificationPairInUse, newProbe.GetIdentificationPair()))
}
// Make sure the new probe is activated
newProbe.Enabled = true
// Clone the program
clonedSpec := progSpec.Copy()
newProbe.programSpec = clonedSpec
// Edit constants
for _, editor := range constantsEditors {
if err := m.editConstant(newProbe.programSpec, editor); err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't edit constant %s", err, editor.Name))
}
}
// Write current maps
if err = m.rewriteMaps(newProbe.programSpec, m.collection.Maps); err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't rewrite maps in %v", err, newProbe.GetIdentificationPair()))
}
// Rewrite with new maps
if err = m.rewriteMaps(newProbe.programSpec, mapEditors); err != nil {
return errors.New(fmt.Sprintf("error:%v , couldn't rewrite maps in %v", err, newProbe.GetIdentificationPair()))
}
// Init
if err = newProbe.InitWithOptions(m, true, true); err != nil {
// clean up
_ = newProbe.Stop()
return errors.New(fmt.Sprintf("error:%v , failed to initialize new probe %v", err, newProbe.GetIdentificationPair()))
}
// Attach new program
if err = newProbe.Attach(); err != nil {
// clean up
_ = newProbe.Stop()
return errors.New(fmt.Sprintf("error:%v , failed to attach new probe %v", err, newProbe.GetIdentificationPair()))
}
// Add probe to the list of probes
m.Probes = append(m.Probes, newProbe)
return nil
}
// UpdateMapRoutes - Update one or multiple map of maps structures so that the provided keys point to the provided maps.
func (m *Manager) UpdateMapRoutes(router ...MapRoute) error {
for _, route := range router {
if err := m.updateMapRoute(route); err != nil {
return err
}
}
return nil
}