-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
330 lines (295 loc) · 7.09 KB
/
main.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
package main
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"log"
"os"
"os/signal"
"sort"
"syscall"
"time"
"unsafe"
bpf "github.com/aquasecurity/libbpfgo"
"github.com/mozillazg/libbpfgo-tools/common"
flag "github.com/spf13/pflag"
)
const TASK_COMM_LEN = 16
type Data struct {
Count uint64
TotalNs uint64
Comm [TASK_COMM_LEN]byte
}
type DataExt struct {
Data
key uint32
}
type Options struct {
bpfObjPath string
verbose bool
pid uint32
interval uint
duration uint
top uint
cgroup string
failures bool
latency bool
milliseconds bool
process bool
errno int
list bool
}
var opts = Options{
bpfObjPath: "syscount.bpf.o",
verbose: false,
pid: 0,
interval: 0,
duration: 0,
top: 10,
cgroup: "",
failures: false,
latency: false,
milliseconds: false,
process: false,
errno: 0,
list: false,
}
func init() {
flag.StringVar(&opts.bpfObjPath, "objpath", opts.bpfObjPath, "Path to the bpf object file")
flag.Uint32VarP(&opts.pid, "pid", "p", opts.pid, "Process PID to trace")
flag.UintVarP(&opts.interval, "interval", "i", opts.interval,
"Print summary at this interval (seconds), 0 for infinite wait (default)")
flag.UintVarP(&opts.duration, "duration", "d", opts.duration, "Total tracing duration (seconds)")
flag.UintVarP(&opts.top, "top", "T", opts.top, "Print only the top syscalls")
flag.StringVarP(&opts.cgroup, "cgroup", "c", opts.cgroup, "Trace process in cgroup path")
flag.BoolVarP(&opts.failures, "failures", "x", opts.failures, "Trace only failed syscalls")
flag.BoolVarP(&opts.latency, "latency", "L", opts.latency, "Collect syscall latency")
flag.BoolVarP(&opts.milliseconds, "milliseconds", "m", opts.milliseconds,
"Display latency in milliseconds (default: microseconds)")
flag.BoolVarP(&opts.process, "process", "P", opts.process, "Count by process and not by syscall")
flag.IntVarP(&opts.errno, "errno", "e", opts.errno,
"Trace only syscalls that return this error (numeric or EPERM, etc.)")
flag.BoolVarP(&opts.list, "list", "l", opts.list, "Print list of recognized syscalls and exit")
// flag.BoolVarP(&opts.verbose, "verbose", "v", opts.verbose, "Verbose debug output")
}
func initGlobalVars(bpfModule *bpf.Module) {
if opts.pid > 0 {
if err := bpfModule.InitGlobalVariable("filter_pid", opts.pid); err != nil {
log.Fatalln(err)
}
}
if opts.failures {
if err := bpfModule.InitGlobalVariable("filter_failed", true); err != nil {
log.Fatalln(err)
}
}
if opts.latency {
if err := bpfModule.InitGlobalVariable("measure_latency", true); err != nil {
log.Fatalln(err)
}
}
if opts.process {
if err := bpfModule.InitGlobalVariable("count_by_process", true); err != nil {
log.Fatalln(err)
}
}
if opts.cgroup != "" {
if err := bpfModule.InitGlobalVariable("filter_cg", true); err != nil {
log.Fatalln(err)
}
}
// TODO: filter_errno
}
func loadBPFObj(bpfModule *bpf.Module) {
if err := bpfModule.BPFLoadObject(); err != nil {
log.Fatalln(err)
}
}
func applyFilters(bpfModule *bpf.Module) {
if opts.cgroup != "" {
idx := 0
cgroupFd, err := common.GetCgroupDirFD(opts.cgroup)
if err != nil {
log.Fatalln(err)
}
cgroupMap, err := bpfModule.GetMap("cgroup_map")
if err != nil {
log.Fatalln(err)
}
if err := cgroupMap.Update(unsafe.Pointer(&idx), unsafe.Pointer(&cgroupFd)); err != nil {
log.Fatalln(err)
}
}
}
func attachPrograms(bpfModule *bpf.Module) {
names := []string{"sys_exit"}
if opts.latency {
names = append(names, "sys_enter")
}
progIter := bpfModule.Iterator()
for {
prog := progIter.NextProgram()
if prog == nil {
break
}
if !common.Contains(names, prog.Name()) {
continue
}
if _, err := prog.AttachGeneric(); err != nil {
log.Fatalln(err)
}
}
}
func printTimestamp() {
now := time.Now()
fmt.Printf("[%02d:%02d:%02d]\n", now.Hour(), now.Minute(), now.Second())
}
func getAggColName() string {
if opts.process {
return "PID COMM"
}
return "SYSCALL"
}
func printLatencyHeader() {
timeCol := "TIME (us)"
if opts.milliseconds {
timeCol = "TIME (ms)"
}
fmt.Printf("%-22s %8s %16s\n", getAggColName(), "COUNT", timeCol)
}
func printCountHeader() {
fmt.Printf("%-22s %8s\n", getAggColName(), "COUNT")
}
func aggCol(val DataExt) string {
var col string
if opts.process {
col = fmt.Sprintf("%-6d %-15s", val.key, common.GoString(val.Comm[:]))
} else {
col = common.SyscallName(int(val.key))
}
return col
}
func printLatency(vals []DataExt) {
div := 1000.0
if opts.milliseconds {
div = 1000000.0
}
printLatencyHeader()
count := int(opts.top)
if count > len(vals) {
count = len(vals)
}
for i := 0; i < count; i++ {
fmt.Printf("%-22s %8d %16.3f\n",
aggCol(vals[i]), vals[i].Count, float64(vals[i].TotalNs)/div)
}
fmt.Printf("\n")
}
func printCount(vals []DataExt) {
printCountHeader()
count := int(opts.top)
if count > len(vals) {
count = len(vals)
}
for i := 0; i < count; i++ {
fmt.Printf("%-22s %8d\n", aggCol(vals[i]), vals[i].Count)
}
fmt.Printf("\n")
}
func printData(dataMap *bpf.BPFMap) {
vals := readVals(dataMap)
if len(vals) == 0 {
return
}
if opts.latency {
sortValsByLatency(vals)
} else {
sortValsByCount(vals)
}
printTimestamp()
if opts.latency {
printLatency(vals)
} else {
printCount(vals)
}
}
func readVals(dataMap *bpf.BPFMap) []DataExt {
items, err := common.DumpThenClearHash(dataMap)
if err != nil {
log.Fatalln(err)
}
var vals []DataExt
for _, ret := range items {
var key uint32
if err := binary.Read(bytes.NewReader(ret[0]), binary.LittleEndian, &key); err != nil {
log.Fatalln(err)
}
var value Data
if err := binary.Read(bytes.NewReader(ret[1]), binary.LittleEndian, &value); err != nil {
log.Fatalln(err)
}
vals = append(vals, DataExt{
Data: value,
key: key,
})
}
return vals
}
func sortValsByCount(vals []DataExt) {
sort.Slice(vals, func(i, j int) bool {
iC := vals[i].Count
jC := vals[j].Count
return iC > jC
})
}
func sortValsByLatency(vals []DataExt) {
sort.Slice(vals, func(i, j int) bool {
iN := vals[i].TotalNs
jN := vals[j].TotalNs
return iN > jN
})
}
func main() {
flag.Parse()
bpfModule, err := bpf.NewModuleFromFile(opts.bpfObjPath)
if err != nil {
log.Fatalln(err)
}
defer bpfModule.Close()
initGlobalVars(bpfModule)
loadBPFObj(bpfModule)
applyFilters(bpfModule)
attachPrograms(bpfModule)
data, err := bpfModule.GetMap("data")
if err != nil {
log.Fatalln(err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
var intervalC <-chan time.Time
if opts.interval > 0 {
ticket := time.NewTicker(time.Second * time.Duration(opts.interval))
defer ticket.Stop()
intervalC = ticket.C
}
if opts.duration > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Second*time.Duration(opts.duration))
defer cancel()
}
var done bool
fmt.Printf("Tracing syscalls, printing top %d... Ctrl+C to quit.\n", opts.top)
loop:
for {
select {
case <-intervalC:
case <-ctx.Done():
done = true
}
printData(data)
if done {
break loop
}
}
}