-
Notifications
You must be signed in to change notification settings - Fork 0
/
ringbuf.go
88 lines (75 loc) · 1.7 KB
/
ringbuf.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
package wbpf
import (
"errors"
"fmt"
"os"
"time"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/ringbuf"
)
type RingBufCallback func(raw []byte)
type RingBufOptions struct {
Callback RingBufCallback
Async bool
}
type RingBuf struct {
table *Table
*ringbuf.Reader
callback RingBufCallback
}
func NewRingBuf(table *Table, opts *RingBufOptions) (*RingBuf, error) {
if table.TableType() != ebpf.RingBuf {
return nil, ErrIncorrectTableType
}
reader, err := ringbuf.NewReader(table.Map)
if err != nil {
return nil, fmt.Errorf("ringbuf new reader: %w", err)
}
if opts == nil {
opts = &RingBufOptions{}
}
this := &RingBuf{
Reader: reader,
table: table,
}
if opts.Async && opts.Callback != nil {
this.callback = func(raw []byte) { go opts.Callback(raw) }
} else {
this.callback = opts.Callback
}
return this, nil
}
func (rb *RingBuf) Poll(timeout time.Duration) (int, error) {
if rb.Reader == nil {
return -1, nil
}
var count int
var t time.Time
if timeout == 0 {
t = time.Now().Add(-10 * time.Minute)
} else if timeout > 0 {
t = time.Now().Add(timeout)
}
rb.SetDeadline(t)
var record ringbuf.Record
for {
if err := rb.ReadInto(&record); err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, ringbuf.ErrClosed) {
return count, nil
}
return -1, fmt.Errorf("ringbuf read: %w", err)
}
if rb.callback != nil {
rb.callback(record.RawSample)
}
// reset cap and data. ref: https://github.com/cilium/ebpf/blob/14adc787359b2a2f948773ed286cfee2e7b3bffe/ringbuf/reader.go#L92
record.RawSample = make([]byte, 0)
count++
}
}
func (rb *RingBuf) Close() error {
if rb == nil || rb.Reader == nil {
return nil
}
return rb.Reader.Close()
}