-
Notifications
You must be signed in to change notification settings - Fork 10
/
probe.go
749 lines (642 loc) · 23.8 KB
/
probe.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
package manager
import (
"errors"
"fmt"
"io"
"strings"
"sync"
"syscall"
"time"
"github.com/cilium/ebpf"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"github.com/DataDog/ebpf-manager/internal"
)
type AttachMethod uint32
const (
AttachMethodNotSet AttachMethod = iota
AttachWithPerfEventOpen
AttachWithProbeEvents
)
const bypassMapName = "program_bypassed"
const bypassOptInReference = "bypass_program"
// values used for map update to bypass/enable programs
var bypassValue any
var enableValue any
// Probe - Main eBPF probe wrapper. This structure is used to store the required data to attach a loaded eBPF
// program to its hook point.
type Probe struct {
netlinkSocketCache *netlinkSocketCache
program *ebpf.Program
programSpec *ebpf.ProgramSpec
state state
stateLock sync.RWMutex
manualLoadNeeded bool
checkPin bool
attachPID int
attachRetryAttempt uint
kprobeHookPointNotExist bool
systemWideID int
programTag string
kprobeType probeType
isReturnProbe bool
link netlink.Link
tcFilter netlink.BpfFilter
tcClsActQdisc netlink.Qdisc
progLink io.Closer
bypassIndex uint32
bypassMap *Map
// lastError - stores the last error that the probe encountered, it is used to surface a more useful error message
// when one of the validators (see Options.ActivatedProbes) fails.
lastError error
// ProbeIdentificationPair is used to identify the current probe
ProbeIdentificationPair
// CopyProgram - When enabled, this option will make a unique copy of the program section for the current program
CopyProgram bool
// KeepProgramSpec - Defines if the internal *ProgramSpec should be cleaned up after the probe has been successfully
// attached to free up memory. If you intend to make a copy of this Probe later, you should explicitly set this
// option to true.
KeepProgramSpec bool
// SyscallFuncName - Name of the syscall on which the program should be hooked. As the exact kernel symbol may
// differ from one kernel version to the other, the right prefix will be computed automatically at runtime.
// If a syscall name is not provided, the section name (without its probe type prefix) is assumed to be the
// hook point.
SyscallFuncName string
// MatchFuncName - Pattern used to find the function(s) to attach to
// FOR KPROBES: When this field is used, the provided pattern is matched against the list of available symbols
// in /sys/kernel/debug/tracing/available_filter_functions. If the exact function does not exist, then the first
// symbol matching the provided pattern will be used. This option requires debugfs.
//
// FOR UPROBES: When this field is used, the provided pattern is matched against the list of symbols in the symbol
// table of the provided elf binary. If the exact function does not exist, then the first symbol matching the
// provided pattern will be used.
MatchFuncName string
// HookFuncName - Exact name of the symbol to hook onto. When this field is set, MatchFuncName and SyscallFuncName
// are ignored.
HookFuncName string
// TracepointCategory - (Tracepoint) The manager expects the tracepoint category to be parsed from the eBPF section
// in which the eBPF function of this Probe lives (SEC("tracepoint/[category]/[name]")). However, you can use this
// field to override it.
TracepointCategory string
// TracepointName - (Tracepoint) The manager expects the tracepoint name to be parsed from the eBPF section
// in which the eBPF function of this Probe lives (SEC("tracepoint/[category]/[name]")). However, you can use this
// field to override it.
TracepointName string
// Enabled - Indicates if a probe should be enabled or not. This parameter can be set at runtime using the
// Manager options (see ActivatedProbes)
Enabled bool
// PinPath - Once loaded, the eBPF program will be pinned to this path. If the eBPF program has already been pinned
// and is already running in the kernel, then it will be loaded from this path.
PinPath string
// KProbeMaxActive - (kretprobes) With kretprobes, you can configure the maximum number of instances of the function that can be
// probed simultaneously with maxactive. If maxactive is 0 it will be set to the default value: if CONFIG_PREEMPT is
// enabled, this is max(10, 2*NR_CPUS); otherwise, it is NR_CPUS. For kprobes, maxactive is ignored.
KProbeMaxActive int
// KprobeAttachMethod - Method to use for attaching the kprobe. Either use perfEventOpen ABI or kprobe events
KprobeAttachMethod KprobeAttachMethod
// UprobeAttachMethod - Method to use for attaching the uprobe. Either use perfEventOpen ABI or uprobe events
UprobeAttachMethod AttachMethod
// UprobeOffset - If UprobeOffset is provided, the uprobe will be attached to it directly without looking for the
// symbol in the elf binary. If the file is a non-PIE executable, the provided address must be a virtual address,
// otherwise it must be an offset relative to the file load address.
UprobeOffset uint64
// ProbeRetry - Defines the number of times that the probe will retry to attach / detach on error.
ProbeRetry uint
// ProbeRetryDelay - Defines the delay to wait before the probe should retry to attach / detach on error.
ProbeRetryDelay time.Duration
// BinaryPath - (uprobes) A Uprobe is attached to a specific symbol in a user space binary. The offset is
// automatically computed for the symbol name provided in the uprobe section ( SEC("uprobe/[symbol_name]") ).
BinaryPath string
// CGroupPath - (cgroup family programs) All CGroup programs are attached to a CGroup (v2). This field provides the
// path to the CGroup to which the probe should be attached. The attach type is determined by the section.
CGroupPath string
// SocketFD - (socket filter) Socket filter programs are bound to a socket and filter the packets they receive
// before they reach user space. The probe will be bound to the provided file descriptor
SocketFD int
// IfIndex - (TC classifier & XDP) Interface index used to identify the interface on which the probe will be
// attached. If not set, fall back to `IfName`.
IfIndex int
// IfName - (TC Classifier & XDP) Interface name on which the probe will be attached.
IfName string
// IfIndexNetns - (TC Classifier & XDP) Network namespace in which the network interface lives. If this value is
// provided, then IfIndexNetnsID is required too.
// WARNING: it is up to the caller of "Probe.Start()" to close this netns handle. Failing to close this handle may
// lead to leaking the network namespace. This handle can be safely closed once "Probe.Start()" returns.
IfIndexNetns uint64
// IfIndexNetnsID - (TC Classifier & XDP) Network namespace ID associated of the IfIndexNetns handle. If this value
// is provided, then IfIndexNetns is required too.
// WARNING: it is up to the caller of "Probe.Start()" to call "manager.CleanupNetworkNamespace()" once the provided
// IfIndexNetnsID is no longer needed. Failing to call this cleanup function may lead to leaking the network
// namespace. Remember that "manager.CleanupNetworkNamespace()" will close the netlink socket opened with the netns
// handle provided above. If you want to start the probe again, you'll need to provide a new valid netns handle so
// that a new netlink socket can be created in that namespace.
IfIndexNetnsID uint32
// XDPAttachMode - (XDP) XDP attach mode. If not provided the kernel will automatically select the best available
// mode.
XDPAttachMode XdpAttachMode
// NetworkDirection - (TC classifier) Network traffic direction of the classifier. Can be either Ingress or Egress. Keep
// in mind that if you are hooking on the host side of a virtual ethernet pair, Ingress and Egress are inverted.
NetworkDirection TrafficType
// TCFilterHandle - (TC classifier) defines the handle to use when loading the classifier. Leave unset to let the kernel decide which handle to use.
TCFilterHandle uint32
// TCFilterPrio - (TC classifier) defines the priority of the classifier added to the clsact qdisc. Defaults to DefaultTCFilterPriority.
TCFilterPrio uint16
// TCCleanupQDisc - (TC classifier) defines if the manager should clean up the clsact qdisc when a probe is unloaded
TCCleanupQDisc bool
// TCFilterProtocol - (TC classifier) defines the protocol to match in order to trigger the classifier. Defaults to
// ETH_P_ALL.
TCFilterProtocol uint16
// SamplePeriod - (Perf event) This parameter defines when the perf_event eBPF program is triggered. When SamplePeriod > 0
// the program will be triggered every SamplePeriod events.
SamplePeriod int
// SampleFrequency - (Perf event) This parameter defines when the perf_event eBPF program is triggered. When
// SampleFrequency > 0, SamplePeriod is ignored and the eBPF program is triggered at the requested frequency.
SampleFrequency int
// PerfEventType - (Perf event) This parameter defines the type of the perf_event program. Allowed values are
// unix.PERF_TYPE_HARDWARE and unix.PERF_TYPE_SOFTWARE
PerfEventType int
// PerfEventPID - (Perf event, uprobes) This parameter defines the PID for which the program should be triggered.
// Do not set this value to monitor the whole host.
PerfEventPID int
// PerfEventConfig - (Perf event) This parameter defines which software or hardware event is being monitored. See the
// PERF_COUNT_SW_* and PERF_COUNT_HW_* constants in the unix package.
PerfEventConfig int
// PerfEventCPUCount - (Perf event) This parameter defines the number of CPUs to monitor. If not set, defaults to
// runtime.NumCPU(). Disclaimer: in containerized environment and depending on the CPU affinity of the program
// holding the manager, runtime.NumCPU might not return the real CPU count of the host.
PerfEventCPUCount int
}
// GetEBPFFuncName - Returns EBPFFuncName with the UID as a postfix if the Probe was copied
func (p *Probe) GetEBPFFuncName() string {
if p.CopyProgram {
return fmt.Sprintf("%s_%s", p.EBPFFuncName, p.UID)
}
return p.EBPFFuncName
}
// Copy - Returns a copy of the current probe instance. Only the exported fields are copied.
func (p *Probe) Copy() *Probe {
return &Probe{
ProbeIdentificationPair: ProbeIdentificationPair{
UID: p.UID,
EBPFFuncName: p.EBPFFuncName,
},
SyscallFuncName: p.SyscallFuncName,
CopyProgram: p.CopyProgram,
KeepProgramSpec: p.KeepProgramSpec,
SamplePeriod: p.SamplePeriod,
SampleFrequency: p.SampleFrequency,
PerfEventType: p.PerfEventType,
PerfEventPID: p.PerfEventPID,
PerfEventConfig: p.PerfEventConfig,
MatchFuncName: p.MatchFuncName,
TracepointCategory: p.TracepointCategory,
TracepointName: p.TracepointName,
Enabled: p.Enabled,
PinPath: p.PinPath,
KProbeMaxActive: p.KProbeMaxActive,
BinaryPath: p.BinaryPath,
CGroupPath: p.CGroupPath,
SocketFD: p.SocketFD,
IfIndex: p.IfIndex,
IfName: p.IfName,
IfIndexNetns: p.IfIndexNetns,
IfIndexNetnsID: p.IfIndexNetnsID,
XDPAttachMode: p.XDPAttachMode,
NetworkDirection: p.NetworkDirection,
ProbeRetry: p.ProbeRetry,
ProbeRetryDelay: p.ProbeRetryDelay,
TCFilterProtocol: p.TCFilterProtocol,
TCFilterPrio: p.TCFilterPrio,
}
}
// GetLastError - Returns the last error that the probe encountered
func (p *Probe) GetLastError() error {
return p.lastError
}
// ID returns the system-wide unique ID for this program
func (p *Probe) ID() uint32 {
p.stateLock.RLock()
defer p.stateLock.RUnlock()
return uint32(p.systemWideID)
}
// IsRunning - Returns true if the probe was successfully initialized, started and is currently running or paused.
func (p *Probe) IsRunning() bool {
p.stateLock.RLock()
defer p.stateLock.RUnlock()
return p.state == running || p.state == paused
}
// IsInitialized - Returns true if the probe was successfully initialized.
func (p *Probe) IsInitialized() bool {
p.stateLock.RLock()
defer p.stateLock.RUnlock()
return p.state >= initialized
}
// Test - Triggers the probe with the provided test data. Returns the length of the output, the raw output or an error.
func (p *Probe) Test(in []byte) (uint32, []byte, error) {
return p.program.Test(in)
}
// Benchmark - Benchmark runs the Program with the given input for a number of times and returns the time taken per
// iteration.
//
// Returns the result of the last execution of the program and the time per run or an error. reset is called whenever
// the benchmark syscall is interrupted, and should be set to testing.B.ResetTimer or similar.
func (p *Probe) Benchmark(in []byte, repeat int, reset func()) (uint32, time.Duration, error) {
return p.program.Benchmark(in, repeat, reset)
}
// initWithOptions - Initializes a probe with options
func (p *Probe) initWithOptions(manager *Manager, manualLoadNeeded bool, checkPin bool) error {
if !p.Enabled {
p.cleanupProgramSpec()
return nil
}
p.stateLock.Lock()
defer p.stateLock.Unlock()
p.manualLoadNeeded = manualLoadNeeded
p.checkPin = checkPin
return p.internalInit(manager)
}
// init - Initialize a probe
func (p *Probe) init(manager *Manager) error {
if !p.Enabled {
p.cleanupProgramSpec()
return nil
}
p.stateLock.Lock()
defer p.stateLock.Unlock()
return p.internalInit(manager)
}
func (p *Probe) Program() *ebpf.Program {
return p.program
}
func (p *Probe) internalInit(manager *Manager) error {
if p.state >= initialized {
return nil
}
p.netlinkSocketCache = manager.netlinkSocketCache
p.state = reset
// Load spec if necessary
if p.manualLoadNeeded {
prog, err := ebpf.NewProgramWithOptions(p.programSpec, manager.options.VerifierOptions.Programs)
if err != nil {
p.lastError = err
var ve *ebpf.VerifierError
if errors.As(err, &ve) {
// include error twice to preserve context, and still allow unwrapping if desired
return fmt.Errorf("verifier error loading new probe %v: %w\n%+v", p.ProbeIdentificationPair, err, ve)
}
return fmt.Errorf("couldn't load new probe %v: %w", p.ProbeIdentificationPair, err)
}
p.program = prog
}
// Retrieve eBPF program if one isn't already set
if p.program == nil {
if p.program, p.lastError = manager.getProbeProgram(p.GetEBPFFuncName()); p.lastError != nil {
return fmt.Errorf("couldn't find program %s: %w", p.GetEBPFFuncName(), ErrUnknownSectionOrFuncName)
}
p.checkPin = true
}
if p.programSpec == nil {
if p.programSpec, p.lastError = manager.getProbeProgramSpec(p.GetEBPFFuncName()); p.lastError != nil {
return fmt.Errorf("couldn't find program spec %s: %w", p.GetEBPFFuncName(), ErrUnknownSectionOrFuncName)
}
}
if p.programSpec.Type == ebpf.SchedCLS {
// sanity check
if p.NetworkDirection != Egress && p.NetworkDirection != Ingress {
return fmt.Errorf("%s has an invalid configuration: %w", p.ProbeIdentificationPair, ErrNoNetworkDirection)
}
}
if p.checkPin {
// Pin program if needed
if p.PinPath != "" {
if err := p.program.Pin(p.PinPath); err != nil {
p.lastError = err
return fmt.Errorf("couldn't pin program %s at %s: %w", p.GetEBPFFuncName(), p.PinPath, err)
}
}
p.checkPin = false
}
// Update syscall function name with the correct arch prefix
if p.SyscallFuncName != "" && len(p.HookFuncName) == 0 {
var err error
p.HookFuncName, err = GetSyscallFnNameWithSymFile(p.SyscallFuncName, manager.options.SymFile)
if err != nil {
p.lastError = err
return err
}
}
if p.programSpec.Type == ebpf.Kprobe {
progType, _, _ := strings.Cut(p.programSpec.SectionName, "/")
switch progType {
case "kprobe":
p.kprobeType = kprobe
case "kretprobe":
p.kprobeType = kprobe
p.isReturnProbe = true
case "uprobe":
p.kprobeType = uprobe
case "uretprobe":
p.kprobeType = uprobe
p.isReturnProbe = true
}
// Find function name match if required
if p.MatchFuncName != "" && len(p.HookFuncName) == 0 {
// if this is a kprobe or a kretprobe, look for the symbol now
if p.kprobeType == kprobe {
var err error
p.HookFuncName, err = FindFilterFunction(p.MatchFuncName)
if err != nil {
p.lastError = err
return err
}
}
}
}
if len(p.HookFuncName) == 0 {
// default back to the AttachTo field in Program, as parsed by Cilium
p.HookFuncName = p.programSpec.AttachTo
}
// resolve netns ID from netns handle
if p.IfIndexNetns == 0 && p.IfIndexNetnsID != 0 || p.IfIndexNetns != 0 && p.IfIndexNetnsID == 0 {
return fmt.Errorf("both IfIndexNetns and IfIndexNetnsID are required if one is provided (IfIndexNetns: %d IfIndexNetnsID: %d)", p.IfIndexNetns, p.IfIndexNetnsID)
}
// set default TC classifier priority
if p.TCFilterPrio == 0 {
p.TCFilterPrio = DefaultTCFilterPriority
}
// set default TC classifier protocol
if p.TCFilterProtocol == 0 {
p.TCFilterProtocol = unix.ETH_P_ALL
}
// Default max active value
if p.KProbeMaxActive == 0 {
p.KProbeMaxActive = manager.options.DefaultKProbeMaxActive
}
// Default retry
if p.ProbeRetry == 0 {
p.ProbeRetry = manager.options.DefaultProbeRetry
}
// Default retry delay
if p.ProbeRetryDelay == 0 {
p.ProbeRetryDelay = manager.options.DefaultProbeRetryDelay
}
// fetch system-wide program ID, if the feature is available
if p.program != nil {
programInfo, err := p.program.Info()
if err == nil {
p.programTag = programInfo.Tag
id, available := programInfo.ID()
if available {
p.systemWideID = int(id)
}
}
}
// set default kprobe attach method
if p.KprobeAttachMethod == AttachKprobeMethodNotSet {
p.KprobeAttachMethod = manager.options.DefaultKprobeAttachMethod
if p.KprobeAttachMethod == AttachKprobeMethodNotSet {
p.KprobeAttachMethod = AttachKprobeWithPerfEventOpen
}
}
// set default uprobe attach method
if p.UprobeAttachMethod == AttachMethodNotSet {
p.UprobeAttachMethod = manager.options.DefaultUprobeAttachMethod
if p.UprobeAttachMethod == AttachMethodNotSet {
p.UprobeAttachMethod = AttachWithPerfEventOpen
}
}
// update probe state
p.state = initialized
p.cleanupProgramSpec()
return nil
}
// Attach - Attaches the probe to the right hook point in the kernel depending on the program type and the provided
// parameters.
func (p *Probe) Attach() error {
return internal.Retry(func() error {
p.attachRetryAttempt++
err := p.attach()
if err == nil {
return nil
}
// not available, not a temporary error
if errors.Is(err, syscall.ENOENT) || errors.Is(err, syscall.EINVAL) {
return nil
}
return err
}, p.getRetryAttemptCount(), p.ProbeRetryDelay)
}
func (p *Probe) Pause() error {
return p.pause()
}
func (p *Probe) Resume() error {
return p.resume()
}
// attach - Thread unsafe version of attach
func (p *Probe) attach() error {
p.stateLock.Lock()
defer p.stateLock.Unlock()
if p.state >= paused || !p.Enabled {
return nil
}
if p.state < initialized {
if p.lastError == nil {
p.lastError = ErrProbeNotInitialized
}
return ErrProbeNotInitialized
}
p.attachPID = Getpid()
// Per program type start
var err error
switch p.programSpec.Type {
case ebpf.UnspecifiedProgram:
err = fmt.Errorf("invalid program type, make sure to use the right section prefix: %w", ErrSectionFormat)
case ebpf.Kprobe:
switch p.kprobeType {
case kprobe:
err = p.attachKprobe()
case uprobe:
err = p.attachUprobe()
}
case ebpf.TracePoint:
err = p.attachTracepoint()
case ebpf.RawTracepoint, ebpf.RawTracepointWritable:
err = p.attachRawTracepoint()
case ebpf.CGroupDevice, ebpf.CGroupSKB, ebpf.CGroupSock, ebpf.CGroupSockAddr, ebpf.CGroupSockopt, ebpf.CGroupSysctl:
err = p.attachCGroup()
case ebpf.SocketFilter:
err = p.attachSocket()
case ebpf.SchedCLS:
err = p.attachTCCLS()
case ebpf.XDP:
err = p.attachXDP()
case ebpf.LSM:
err = p.attachLSM()
case ebpf.PerfEvent:
err = p.attachPerfEvent()
case ebpf.Tracing:
err = p.attachTracing()
default:
err = fmt.Errorf("program type %s not implemented yet", p.programSpec.Type)
}
if err != nil {
p.lastError = err
// Clean up any progress made in the attach attempt
_ = p.stop(false)
return fmt.Errorf("couldn't start probe %s: %w", p.ProbeIdentificationPair, err)
}
// update probe state
p.state = running
p.attachRetryAttempt = p.getRetryAttemptCount()
return nil
}
// cleanupProgramSpec - Cleans up the internal ProgramSpec attribute to free up some memory
func (p *Probe) cleanupProgramSpec() {
if p.KeepProgramSpec {
return
}
cleanupProgramSpec(p.programSpec)
}
func (p *Probe) pause() error {
p.stateLock.Lock()
defer p.stateLock.Unlock()
if p.state <= paused || !p.Enabled {
return nil
}
v, ok := p.progLink.(pauser)
if ok {
if err := v.Pause(); err != nil {
p.lastError = err
return fmt.Errorf("error pausing probe %s: %w", p.ProbeIdentificationPair, err)
}
p.state = paused
return nil
}
if p.bypassIndex > 0 && p.bypassMap != nil {
if err := p.bypassMap.array.Update(p.bypassIndex, bypassValue, ebpf.UpdateExist); err != nil {
return err
}
p.state = paused
return nil
}
return nil
}
func (p *Probe) resume() error {
p.stateLock.Lock()
defer p.stateLock.Unlock()
if p.state != paused || !p.Enabled {
return nil
}
v, ok := p.progLink.(pauser)
if ok {
if err := v.Resume(); err != nil {
p.lastError = err
return fmt.Errorf("error resuming probe %s: %w", p.ProbeIdentificationPair, err)
}
p.state = running
return nil
}
if err := p.disableBypass(); err != nil {
return err
}
p.state = running
return nil
}
func (p *Probe) disableBypass() error {
if p.bypassIndex > 0 && p.bypassMap != nil {
return p.bypassMap.array.Update(p.bypassIndex, enableValue, ebpf.UpdateExist)
}
return nil
}
// Detach - Detaches the probe from its hook point depending on the program type and the provided parameters. This
// method does not close the underlying eBPF program, which means that Attach can be called again later.
func (p *Probe) Detach() error {
p.stateLock.Lock()
defer p.stateLock.Unlock()
if p.state < paused || !p.Enabled {
return nil
}
// detach from hook point
err := p.detachRetry()
// update state of the probe
if err != nil {
p.lastError = err
} else {
p.state = initialized
}
_ = p.disableBypass()
return err
}
// detachRetry - Thread unsafe version of Detach with retry
func (p *Probe) detachRetry() error {
return internal.Retry(p.detach, p.getRetryAttemptCount(), p.ProbeRetryDelay)
}
// detach - Thread unsafe version of Detach.
func (p *Probe) detach() error {
err := p.program.Unpin()
// Per program type cleanup
switch p.programSpec.Type {
case ebpf.UnspecifiedProgram:
// nothing to do
break
case ebpf.SchedCLS:
err = errors.Join(err, p.detachTCCLS())
default:
if p.progLink != nil {
err = errors.Join(err, p.progLink.Close())
}
}
return err
}
// Stop - Detaches the probe from its hook point and close the underlying eBPF program.
func (p *Probe) Stop() error {
p.stateLock.Lock()
defer p.stateLock.Unlock()
if p.state < paused || !p.Enabled {
p.reset()
return nil
}
return p.stop(true)
}
func (p *Probe) stop(saveStopError bool) error {
// detach from hook point
err := p.detachRetry()
// close the loaded program
if p.attachRetryAttempt >= p.getRetryAttemptCount() {
err = errors.Join(err, p.program.Close())
}
// update state of the probe
if saveStopError {
p.lastError = errors.Join(p.lastError, err)
}
// Cleanup probe if stop was successful
if err == nil && p.attachRetryAttempt >= p.getRetryAttemptCount() {
p.reset()
}
if err != nil {
return fmt.Errorf("couldn't stop probe %s: %w", p.ProbeIdentificationPair, err)
}
return nil
}
// reset - Cleans up the internal fields of the probe
func (p *Probe) reset() {
p.kprobeType = kprobe
p.isReturnProbe = false
p.netlinkSocketCache = nil
p.program = nil
p.programSpec = nil
p.progLink = nil
p.state = reset
p.manualLoadNeeded = false
p.checkPin = false
p.attachPID = 0
p.attachRetryAttempt = 0
p.kprobeHookPointNotExist = false
p.systemWideID = 0
p.programTag = ""
p.tcFilter = netlink.BpfFilter{}
p.tcClsActQdisc = nil
}
func (p *Probe) getRetryAttemptCount() uint {
return p.ProbeRetry + 1
}