blob: 83727b3d90109de1a3bc4d01f08d70fa781e91b7 [file] [log] [blame]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -07001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
Sasha Goldshteina245c792016-10-25 02:18:35 -07004# ucalls Summarize method calls in high-level languages and/or system calls.
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -07005# For Linux, uses BCC, eBPF.
6#
Sasha Goldshteina245c792016-10-25 02:18:35 -07007# USAGE: ucalls [-l {java,python,ruby}] [-h] [-T TOP] [-L] [-S] [-v] [-m]
8# pid [interval]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -07009#
10# Copyright 2016 Sasha Goldshtein
11# Licensed under the Apache License, Version 2.0 (the "License")
12#
13# 19-Oct-2016 Sasha Goldshtein Created this.
14
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070015from __future__ import print_function
16import argparse
17from bcc import BPF, USDT
18from time import sleep
19
20examples = """examples:
Sasha Goldshteina245c792016-10-25 02:18:35 -070021 ./ucalls -l java 185 # trace Java calls and print statistics on ^C
22 ./ucalls -l python 2020 1 # trace Python calls and print every second
23 ./ucalls -l java 185 -S # trace Java calls and syscalls
24 ./ucalls 6712 -S # trace only syscall counts
25 ./ucalls -l ruby 1344 -T 10 # trace top 10 Ruby method calls
26 ./ucalls -l ruby 1344 -L # trace Ruby calls including latency
27 ./ucalls -l ruby 1344 -LS # trace Ruby calls and syscalls with latency
28 ./ucalls -l python 2020 -mL # trace Python calls including latency in ms
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070029"""
30parser = argparse.ArgumentParser(
31 description="Summarize method calls in high-level languages.",
32 formatter_class=argparse.RawDescriptionHelpFormatter,
33 epilog=examples)
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070034parser.add_argument("pid", type=int, help="process id to attach to")
35parser.add_argument("interval", type=int, nargs='?',
36 help="print every specified number of seconds")
Sasha Goldshteina245c792016-10-25 02:18:35 -070037parser.add_argument("-l", "--language", choices=["java", "python", "ruby"],
38 help="language to trace (if none, trace syscalls only)")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070039parser.add_argument("-T", "--top", type=int,
40 help="number of most frequent/slow calls to print")
41parser.add_argument("-L", "--latency", action="store_true",
42 help="record method latency from enter to exit (except recursive calls)")
Sasha Goldshteina245c792016-10-25 02:18:35 -070043parser.add_argument("-S", "--syscalls", action="store_true",
44 help="record syscall latency (adds overhead)")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070045parser.add_argument("-v", "--verbose", action="store_true",
46 help="verbose mode: print the BPF program (for debugging purposes)")
47parser.add_argument("-m", "--milliseconds", action="store_true",
48 help="report times in milliseconds (default is microseconds)")
49args = parser.parse_args()
50
51# We assume that the entry and return probes have the same arguments. This is
52# the case for Java, Python, and Ruby. If there's a language where it's not the
53# case, we will need to build a custom correlator from entry to exit.
54if args.language == "java":
55 # TODO for JVM entries, we actually have the real length of the class
Sasha Goldshteina245c792016-10-25 02:18:35 -070056 # and method strings in arg3 and arg5 respectively, so we can insert
57 # the null terminator in its proper position.
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070058 entry_probe = "method__entry"
59 return_probe = "method__return"
60 read_class = "bpf_usdt_readarg(2, ctx, &clazz);"
61 read_method = "bpf_usdt_readarg(4, ctx, &method);"
62elif args.language == "python":
63 entry_probe = "function__entry"
64 return_probe = "function__return"
65 read_class = "bpf_usdt_readarg(1, ctx, &clazz);" # filename really
66 read_method = "bpf_usdt_readarg(2, ctx, &method);"
67elif args.language == "ruby":
Sasha Goldshtein6e5c6212016-10-25 04:30:54 -070068 # TODO Also probe cmethod__entry and cmethod__return with same arguments
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070069 entry_probe = "method__entry"
70 return_probe = "method__return"
71 read_class = "bpf_usdt_readarg(1, ctx, &clazz);"
72 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Sasha Goldshteina245c792016-10-25 02:18:35 -070073elif not args.language:
74 if not args.syscalls:
75 print("Nothing to do; use -S to trace syscalls.")
76 exit(1)
77 entry_probe, return_probe, read_class, read_method = ("", "", "", "")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070078
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070079program = """
Sasha Goldshteina245c792016-10-25 02:18:35 -070080#include <linux/ptrace.h>
81
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070082#define MAX_STRING_LENGTH 80
Sasha Goldshteina245c792016-10-25 02:18:35 -070083DEFINE_NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070084DEFINE_LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -070085DEFINE_SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070086
87struct method_t {
88 char clazz[MAX_STRING_LENGTH];
89 char method[MAX_STRING_LENGTH];
90};
91struct entry_t {
92 u64 pid;
93 struct method_t method;
94};
95struct info_t {
96 u64 num_calls;
97 u64 total_ns;
98};
Sasha Goldshteina245c792016-10-25 02:18:35 -070099struct syscall_entry_t {
100 u64 timestamp;
101 u64 ip;
102};
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700103
104#ifndef LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -0700105 BPF_HASH(counts, struct method_t, u64); // number of calls
106 #ifdef SYSCALLS
107 BPF_HASH(syscounts, u64, u64); // number of calls per IP
108 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700109#else
Sasha Goldshteina245c792016-10-25 02:18:35 -0700110 BPF_HASH(times, struct method_t, struct info_t);
111 BPF_HASH(entry, struct entry_t, u64); // timestamp at entry
112 #ifdef SYSCALLS
113 BPF_HASH(systimes, u64, struct info_t); // latency per IP
114 BPF_HASH(sysentry, u64, struct syscall_entry_t); // ts + IP at entry
115 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700116#endif
117
Sasha Goldshteina245c792016-10-25 02:18:35 -0700118#ifndef NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700119int trace_entry(struct pt_regs *ctx) {
120 u64 clazz = 0, method = 0, val = 0;
121 u64 *valp;
122 struct entry_t data = {0};
123#ifdef LATENCY
124 u64 timestamp = bpf_ktime_get_ns();
125 data.pid = bpf_get_current_pid_tgid();
126#endif
127 READ_CLASS
128 READ_METHOD
129 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
130 (void *)clazz);
131 bpf_probe_read(&data.method.method, sizeof(data.method.method),
132 (void *)method);
133#ifndef LATENCY
134 valp = counts.lookup_or_init(&data.method, &val);
135 ++(*valp);
136#endif
137#ifdef LATENCY
138 entry.update(&data, &timestamp);
139#endif
140 return 0;
141}
142
143#ifdef LATENCY
144int trace_return(struct pt_regs *ctx) {
145 u64 *entry_timestamp, clazz = 0, method = 0;
146 struct info_t *info, zero = {};
147 struct entry_t data = {};
148 data.pid = bpf_get_current_pid_tgid();
149 READ_CLASS
150 READ_METHOD
151 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
152 (void *)clazz);
153 bpf_probe_read(&data.method.method, sizeof(data.method.method),
154 (void *)method);
155 entry_timestamp = entry.lookup(&data);
156 if (!entry_timestamp) {
157 return 0; // missed the entry event
158 }
159 info = times.lookup_or_init(&data.method, &zero);
160 info->num_calls += 1;
161 info->total_ns += bpf_ktime_get_ns() - *entry_timestamp;
162 entry.delete(&data);
163 return 0;
164}
Sasha Goldshteina245c792016-10-25 02:18:35 -0700165#endif // LATENCY
166#endif // NOLANG
167
168#ifdef SYSCALLS
169int syscall_entry(struct pt_regs *ctx) {
170 u64 pid = bpf_get_current_pid_tgid();
171 u64 *valp, ip = ctx->ip, val = 0;
172 PID_FILTER
173#ifdef LATENCY
174 struct syscall_entry_t data = {};
175 data.timestamp = bpf_ktime_get_ns();
176 data.ip = ip;
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700177#endif
Sasha Goldshteina245c792016-10-25 02:18:35 -0700178#ifndef LATENCY
179 valp = syscounts.lookup_or_init(&ip, &val);
180 ++(*valp);
181#endif
182#ifdef LATENCY
183 sysentry.update(&pid, &data);
184#endif
185 return 0;
186}
187
188#ifdef LATENCY
189int syscall_return(struct pt_regs *ctx) {
190 struct syscall_entry_t *e;
191 struct info_t *info, zero = {};
192 u64 pid = bpf_get_current_pid_tgid(), ip;
193 PID_FILTER
194 e = sysentry.lookup(&pid);
195 if (!e) {
196 return 0; // missed the entry event
197 }
198 ip = e->ip;
199 info = systimes.lookup_or_init(&ip, &zero);
200 info->num_calls += 1;
201 info->total_ns += bpf_ktime_get_ns() - e->timestamp;
202 sysentry.delete(&pid);
203 return 0;
204}
205#endif // LATENCY
206#endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700207""".replace("READ_CLASS", read_class) \
208 .replace("READ_METHOD", read_method) \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700209 .replace("PID_FILTER", "if ((pid >> 32) != %d) { return 0; }" % args.pid) \
210 .replace("DEFINE_NOLANG", "#define NOLANG" if not args.language else "") \
211 .replace("DEFINE_LATENCY", "#define LATENCY" if args.latency else "") \
212 .replace("DEFINE_SYSCALLS", "#define SYSCALLS" if args.syscalls else "")
213
214if args.language:
215 usdt = USDT(pid=args.pid)
216 usdt.enable_probe(entry_probe, "trace_entry")
217 if args.latency:
218 usdt.enable_probe(return_probe, "trace_return")
219else:
220 usdt = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700221
222if args.verbose:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700223 if usdt:
224 print(usdt.get_text())
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700225 print(program)
226
Sasha Goldshteina245c792016-10-25 02:18:35 -0700227bpf = BPF(text=program, usdt_contexts=[usdt] if usdt else [])
228if args.syscalls:
229 syscall_regex = "^[Ss]y[Ss]_.*"
230 bpf.attach_kprobe(event_re=syscall_regex, fn_name="syscall_entry")
231 if args.latency:
232 bpf.attach_kretprobe(event_re=syscall_regex, fn_name="syscall_return")
233 print("Attached %d kernel probes for syscall tracing." %
234 bpf.num_open_kprobes())
235
236def get_data():
237 # Will be empty when no language was specified for tracing
238 if args.latency:
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100239 data = list(map(lambda (k, v): (k.clazz + "." + k.method,
Sasha Goldshteina245c792016-10-25 02:18:35 -0700240 (v.num_calls, v.total_ns)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100241 bpf["times"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700242 else:
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100243 data = list(map(lambda (k, v): (k.clazz + "." + k.method, (v.value, 0)),
244 bpf["counts"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700245
246 if args.syscalls:
247 if args.latency:
248 syscalls = map(lambda (k, v): (bpf.ksym(k.value),
249 (v.num_calls, v.total_ns)),
250 bpf["systimes"].items())
251 data.extend(syscalls)
252 else:
253 syscalls = map(lambda (k, v): (bpf.ksym(k.value), (v.value, 0)),
254 bpf["syscounts"].items())
255 data.extend(syscalls)
256
257 return sorted(data, key=lambda (k, v): v[1 if args.latency else 0])
258
259def clear_data():
260 if args.latency:
261 bpf["times"].clear()
262 else:
263 bpf["counts"].clear()
264
265 if args.syscalls:
266 if args.latency:
267 bpf["systimes"].clear()
268 else:
269 bpf["syscounts"].clear()
270
271exit_signaled = False
272print("Tracing calls in process %d (language: %s)... Ctrl-C to quit." %
273 (args.pid, args.language or "none"))
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700274while True:
275 try:
276 sleep(args.interval or 99999999)
277 except KeyboardInterrupt:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700278 exit_signaled = True
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700279 print()
Sasha Goldshteina245c792016-10-25 02:18:35 -0700280 data = get_data() # [(function, (num calls, latency in ns))]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700281 if args.latency:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700282 time_col = "TIME (ms)" if args.milliseconds else "TIME (us)"
283 print("%-50s %8s %8s" % ("METHOD", "# CALLS", time_col))
284 else:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700285 print("%-50s %8s" % ("METHOD", "# CALLS"))
286 if args.top:
287 data = data[-args.top:]
288 for key, value in data:
289 if args.latency:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700290 time = value[1]/1000000.0 if args.milliseconds else \
291 value[1]/1000.0
292 print("%-50s %8d %6.2f" % (key, value[0], time))
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700293 else:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700294 print("%-50s %8d" % (key, value[0]))
295 if args.interval and not exit_signaled:
296 clear_data()
297 else:
298 if args.syscalls:
299 print("Detaching kernel probes, please wait...")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700300 exit()