forked from iovisor/bcc
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackcount.py
More file actions
Latest commit
executable file
·390 lines (353 loc) · 16.3 KB
/
Copy pathstackcount.py
File metadata and controls
executable file
·390 lines (353 loc) · 16.3 KB
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
#!/usr/bin/env python
#
# stackcount Count events and their stack traces.
# For Linux, uses BCC, eBPF.
#
# USAGE: stackcount.py [-h] [-p PID] [-c CPU] [-i INTERVAL] [-D DURATION] [-T]
# [-r] [-s] [-P] [-K] [-U] [-v] [-d] [-f] [--debug]
#
# The pattern is a string with optional '*' wildcards, similar to file
# globbing. If you'd prefer to use regular expressions, use the -r option.
#
# Copyright 2016 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 12-Jan-2016 Brendan Gregg Created this.
# 09-Jul-2016 Sasha Goldshtein Generalized for uprobes and tracepoints.
from __future__ importprint_function
frombccimportBPF, USDT
fromtimeimportsleep, strftime
importargparse
importre
importsignal
importsys
importtraceback
debug=False
classProbe(object):
def__init__(self, pattern, kernel_stack, user_stack, use_regex=False,
pid=None, per_pid=False, cpu=None):
"""Init a new probe.
Init the probe from the pattern provided by the user. The supported
patterns mimic the 'trace' and 'argdist' tools, but are simpler because
we don't have to distinguish between probes and retprobes.
func -- probe a kernel function
lib:func -- probe a user-space function in the library 'lib'
p::func -- same thing as 'func'
p:lib:func -- same thing as 'lib:func'
t:cat:event -- probe a kernel tracepoint
u:lib:probe -- probe a USDT tracepoint
"""
self.kernel_stack=kernel_stack
self.user_stack=user_stack
parts=pattern.split(':')
iflen(parts) ==1:
parts= ["p", "", parts[0]]
eliflen(parts) ==2:
parts= ["p", parts[0], parts[1]]
eliflen(parts) ==3:
ifparts[0] =="t":
parts= ["t", "", "%s:%s"%tuple(parts[1:])]
ifparts[0] notin ["p", "t", "u"]:
raiseException("Type must be 'p', 't', or 'u', but got %s"%
parts[0])
else:
raiseException("Too many ':'-separated components in pattern %s"%
pattern)
(self.type, self.library, self.pattern) =parts
ifnotuse_regex:
self.pattern=self.pattern.replace('*', '.*')
self.pattern='^'+self.pattern+'$'
if (self.type=="p"andself.library) orself.type=="u":
libpath=BPF.find_library(self.library)
iflibpathisNone:
# This might be an executable (e.g. 'bash')
libpath=BPF.find_exe(self.library)
iflibpathisNoneorlen(libpath) ==0:
raiseException("unable to find library %s"%self.library)
self.library=libpath
self.pid=pid
self.per_pid=per_pid
self.cpu=cpu
self.matched=0
defis_kernel_probe(self):
returnself.type=="t"or (self.type=="p"andself.library=="")
defattach(self):
ifself.type=="p":
ifself.library:
self.bpf.attach_uprobe(name=self.library,
sym_re=self.pattern,
fn_name="trace_count",
pid=self.pidor-1)
self.matched=self.bpf.num_open_uprobes()
else:
self.bpf.attach_kprobe(event_re=self.pattern,
fn_name="trace_count")
self.matched=self.bpf.num_open_kprobes()
elifself.type=="t":
self.bpf.attach_tracepoint(tp_re=self.pattern,
fn_name="trace_count")
self.matched=self.bpf.num_open_tracepoints()
elifself.type=="u":
pass# Nothing to do -- attach already happened in `load`
ifself.matched==0:
raiseException("No functions matched by pattern %s"%
self.pattern)
defload(self):
ctx_name="ctx"
stack_trace=""
ifself.user_stack:
stack_trace+="""
key.user_stack_id = stack_traces.get_stackid(
%s, BPF_F_USER_STACK
);"""% (ctx_name)
else:
stack_trace+="key.user_stack_id = -1;"
ifself.kernel_stack:
stack_trace+="""
key.kernel_stack_id = stack_traces.get_stackid(
%s, 0
);"""% (ctx_name)
else:
stack_trace+="key.kernel_stack_id = -1;"
trace_count_text="""
int trace_count(void *ctx) {
FILTER
struct key_t key = {};
key.tgid = GET_TGID;
STORE_COMM
%s
counts.atomic_increment(key);
return 0;
}
"""
trace_count_text=trace_count_text% (stack_trace)
bpf_text="""#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
struct key_t {
// no pid (thread ID) so that we do not needlessly split this key
u32 tgid;
int kernel_stack_id;
int user_stack_id;
char name[TASK_COMM_LEN];
};
BPF_HASH(counts, struct key_t);
BPF_STACK_TRACE(stack_traces, 1024);
"""
filter_text= []
# We really mean the tgid from the kernel's perspective, which is in
# the top 32 bits of bpf_get_current_pid_tgid().
ifself.is_kernel_probe() andself.pid:
filter_text.append('u32 pid; pid = bpf_get_current_pid_tgid() >> 32; '+
'if (pid != %d) { return 0; }'%self.pid)
ifself.is_kernel_probe() andself.cpu:
filter_text.append('struct task_struct *task; task = (struct task_struct*)bpf_get_current_task(); '+
'if (task->cpu != %d) { return 0; }'%self.cpu)
trace_count_text=trace_count_text.replace('FILTER', '\n '.join(filter_text))
# Do per-pid statistics iff -P is provided
ifself.per_pid:
trace_count_text=trace_count_text.replace('GET_TGID',
'bpf_get_current_pid_tgid() >> 32')
trace_count_text=trace_count_text.replace('STORE_COMM',
'bpf_get_current_comm(&key.name, sizeof(key.name));')
else:
# skip splitting on PID so these aggregate
# together, and don't store the process name.
trace_count_text=trace_count_text.replace(
'GET_TGID', '0xffffffff')
trace_count_text=trace_count_text.replace('STORE_COMM', '')
self.usdt=None
ifself.type=="u":
self.usdt=USDT(path=self.library, pid=self.pid)
forprobeinself.usdt.enumerate_probes():
ifnotself.pidand (probe.bin_path!=self.library):
continue
ifre.match(self.pattern, probe.name):
# This hack is required because the bpf_usdt_readarg
# functions generated need different function names for
# each attached probe. If we just stick to trace_count,
# we'd get multiple bpf_usdt_readarg helpers with the same
# name when enabling more than one USDT probe.
new_func="trace_count_%d"%self.matched
bpf_text+=trace_count_text.replace(
"trace_count", new_func)
self.usdt.enable_probe(probe.name, new_func)
self.matched+=1
ifdebug:
print(self.usdt.get_text())
else:
bpf_text+=trace_count_text
ifdebug:
print(bpf_text)
self.bpf=BPF(text=bpf_text,
usdt_contexts=[self.usdt] ifself.usdtelse [])
classTool(object):
def__init__(self):
examples="""examples:
./stackcount submit_bio # count kernel stack traces for submit_bio
./stackcount -d ip_output # include a user/kernel stack delimiter
./stackcount -s ip_output # show symbol offsets
./stackcount -sv ip_output # show offsets and raw addresses (verbose)
./stackcount 'tcp_send*' # count stacks for funcs matching tcp_send*
./stackcount -r '^tcp_send.*' # same as above, using regular expressions
./stackcount -Ti 5 ip_output # output every 5 seconds, with timestamps
./stackcount -p 185 ip_output # count ip_output stacks for PID 185 only
./stackcount -c 1 put_prev_entity # count put_prev_entity stacks for CPU 1 only
./stackcount -p 185 c:malloc # count stacks for malloc in PID 185
./stackcount t:sched:sched_fork # count stacks for sched_fork tracepoint
./stackcount -p 185 u:node:* # count stacks for all USDT probes in node
./stackcount -K t:sched:sched_switch # kernel stacks only
./stackcount -U t:sched:sched_switch # user stacks only
"""
parser=argparse.ArgumentParser(
description="Count events and their stack traces",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)
parser.add_argument("-p", "--pid", type=int,
help="trace this PID only")
parser.add_argument("-c", "--cpu", type=int,
help="trace this CPU only")
parser.add_argument("-i", "--interval",
help="summary interval, seconds")
parser.add_argument("-D", "--duration",
help="total duration of trace, seconds")
parser.add_argument("-T", "--timestamp", action="store_true",
help="include timestamp on output")
parser.add_argument("-r", "--regexp", action="store_true",
help="use regular expressions. Default is \"*\" wildcards only.")
parser.add_argument("-s", "--offset", action="store_true",
help="show address offsets")
parser.add_argument("-P", "--perpid", action="store_true",
help="display stacks separately for each process")
parser.add_argument("-K", "--kernel-stacks-only",
action="store_true", help="kernel stack only", default=False)
parser.add_argument("-U", "--user-stacks-only",
action="store_true", help="user stack only", default=False)
parser.add_argument("-v", "--verbose", action="store_true",
help="show raw addresses")
parser.add_argument("-d", "--delimited", action="store_true",
help="insert delimiter between kernel/user stacks")
parser.add_argument("-f", "--folded", action="store_true",
help="output folded format")
parser.add_argument("--debug", action="store_true",
help="print BPF program before starting (for debugging purposes)")
parser.add_argument("pattern",
help="search expression for events")
self.args=parser.parse_args()
globaldebug
debug=self.args.debug
ifself.args.durationandnotself.args.interval:
self.args.interval=self.args.duration
ifnotself.args.interval:
self.args.interval=99999999
ifself.args.kernel_stacks_onlyandself.args.user_stacks_only:
print("ERROR: -K and -U are mutually exclusive. If you want "+
"both stacks, that is the default.")
exit(1)
ifnotself.args.kernel_stacks_onlyandnotself.args.user_stacks_only:
self.kernel_stack=True
self.user_stack=True
else:
self.kernel_stack=self.args.kernel_stacks_only
self.user_stack=self.args.user_stacks_only
# For tracing single processes in isolation, explicitly set perpid
# to True, if not already set. This is required to generate the correct
# BPF program that can store pid in the tgid field of the key_t object.
ifself.args.pidisnotNoneandself.args.pid>0:
self.args.perpid=True
self.probe=Probe(self.args.pattern,
self.kernel_stack, self.user_stack,
self.args.regexp, self.args.pid, self.args.perpid, self.args.cpu)
self.need_delimiter=self.args.delimitedandnot (
self.args.kernel_stacks_onlyorself.args.user_stacks_only)
def_print_kframe(self, addr):
print(" ", end="")
ifself.args.verbose:
print("%-16x "%addr, end="")
ifself.args.offset:
print("%s"%self.probe.bpf.ksym(addr, show_offset=True).decode())
else:
print("%s"%self.probe.bpf.ksym(addr).decode())
def_print_uframe(self, addr, pid):
print(" ", end="")
ifself.args.verbose:
print("%-16x "%addr, end="")
ifself.args.offset:
print("%s"%self.probe.bpf.sym(addr, pid, show_offset=True).decode())
else:
print("%s"%self.probe.bpf.sym(addr, pid).decode())
@staticmethod
def_signal_ignore(signal, frame):
print()
def_print_comm(self, comm, pid):
print(" %s [%d]"% (comm, pid))
defrun(self):
self.probe.load()
self.probe.attach()
ifnotself.args.folded:
print("Tracing %d functions for \"%s\"... Hit Ctrl-C to end."%
(self.probe.matched, self.args.pattern))
b=self.probe.bpf
# check whether hash table batch ops is supported
htab_batch_ops=TrueifBPF.kernel_struct_has_field(b'bpf_map_ops',
b'map_lookup_and_delete_batch') ==1elseFalse
exiting=0ifself.args.intervalelse1
seconds=0
whileTrue:
try:
sleep(int(self.args.interval))
seconds+=int(self.args.interval)
exceptKeyboardInterrupt:
exiting=1
# as cleanup can take many seconds, trap Ctrl-C:
signal.signal(signal.SIGINT, Tool._signal_ignore)
ifself.args.durationandseconds>=int(self.args.duration):
exiting=1
ifnotself.args.folded:
print()
ifself.args.timestamp:
print("%-8s\n"%strftime("%H:%M:%S"), end="")
counts=self.probe.bpf["counts"]
stack_traces=self.probe.bpf["stack_traces"]
self.comm_cache= {}
fork, vinsorted(counts.items_lookup_and_delete_batch()
ifhtab_batch_opselsecounts.items(),
key=lambdacounts: counts[1].value):
user_stack= [] ifk.user_stack_id<0else \
stack_traces.walk(k.user_stack_id)
kernel_stack= [] ifk.kernel_stack_id<0else \
stack_traces.walk(k.kernel_stack_id)
ifself.args.folded:
# print folded stack output
user_stack=list(user_stack)
kernel_stack=list(kernel_stack)
line= [k.name.decode('utf-8', 'replace')] + \
[b.sym(addr, k.tgid).decode('utf-8', 'replace') foraddrin
reversed(user_stack)] + \
(self.need_delimiterand ["-"] or []) + \
[b.ksym(addr).decode('utf-8', 'replace') foraddrinreversed(kernel_stack)]
print("%s %d"% (";".join(line), v.value))
else:
# print multi-line stack output
foraddrinkernel_stack:
self._print_kframe(addr)
ifself.need_delimiter:
print(" --")
foraddrinuser_stack:
self._print_uframe(addr, k.tgid)
ifnotself.args.pidandk.tgid!=0xffffffff:
self._print_comm(k.name, k.tgid)
print(" %d\n"%v.value)
ifnothtab_batch_ops:
counts.clear()
ifexiting:
ifnotself.args.folded:
print("Detaching...")
exit()
if__name__=="__main__":
try:
Tool().run()
exceptException:
ifdebug:
traceback.print_exc()
elifsys.exc_info()[0] isnotSystemExit:
print(sys.exc_info()[1])