-
Notifications
You must be signed in to change notification settings - Fork 0
/
perfbuf.go
111 lines (95 loc) · 2.09 KB
/
perfbuf.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
package wbpf
import (
"errors"
"fmt"
"os"
"time"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/perf"
)
const DEFAULT_PERF_BUF_SIZE = 1024 * 1024
type (
PerfBufRawCallback func(raw []byte)
PerfBufLostCallback func(lost uint64)
)
type PerfBufOptions struct {
RawCallback PerfBufRawCallback
LostCallback PerfBufLostCallback
Async bool
PerCPUBufSize int
}
type PerfBuf struct {
table *Table
*perf.Reader
rawcb PerfBufRawCallback
lostcb PerfBufLostCallback
}
func NewPerfBuffer(table *Table, opts *PerfBufOptions) (*PerfBuf, error) {
if table.TableType() != ebpf.PerfEventArray {
return nil, ErrIncorrectTableType
}
if opts == nil {
opts = &PerfBufOptions{}
}
bufsize := opts.PerCPUBufSize
if bufsize <= 0 {
bufsize = DEFAULT_PERF_BUF_SIZE
}
reader, err := perf.NewReader(table.Map, bufsize)
if err != nil {
return nil, fmt.Errorf("perf new reader: %w", err)
}
this := &PerfBuf{
Reader: reader,
table: table,
}
if opts.Async {
if opts.RawCallback != nil {
this.rawcb = func(raw []byte) { go opts.RawCallback(raw) }
}
if opts.LostCallback != nil {
this.lostcb = func(lost uint64) { go opts.LostCallback(lost) }
}
} else {
this.rawcb = opts.RawCallback
this.lostcb = opts.LostCallback
}
return this, nil
}
func (pb *PerfBuf) Poll(timeout time.Duration) (int, error) {
if pb.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)
}
pb.SetDeadline(t)
var record perf.Record
for {
if err := pb.ReadInto(&record); err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, perf.ErrClosed) {
return count, nil
}
return -1, fmt.Errorf("ringbuf read: %w", err)
}
if pb.rawcb != nil {
pb.rawcb(record.RawSample)
}
if pb.lostcb != nil && record.LostSamples > 0 {
pb.lostcb(record.LostSamples)
}
// reset cap and data
record.RawSample = make([]byte, 0)
count++
}
}
func (rb *PerfBuf) Close() error {
if rb == nil || rb.Reader == nil {
return nil
}
return rb.Reader.Close()
}