blob: 2798793759b4c1a94b00755585586430b1b8b45e [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 Goldshteincfb5ee72017-02-08 14:32:51 -05007# USAGE: ucalls [-l {java,python,ruby,php}] [-h] [-T TOP] [-L] [-S] [-v] [-m]
Sasha Goldshteina245c792016-10-25 02:18:35 -07008# 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
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020017from bcc import BPF, USDT, utils
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070018from time import sleep
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020019import os
20
21languages = ["java", "python", "ruby", "php"]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070022
23examples = """examples:
Sasha Goldshteina245c792016-10-25 02:18:35 -070024 ./ucalls -l java 185 # trace Java calls and print statistics on ^C
25 ./ucalls -l python 2020 1 # trace Python calls and print every second
26 ./ucalls -l java 185 -S # trace Java calls and syscalls
27 ./ucalls 6712 -S # trace only syscall counts
28 ./ucalls -l ruby 1344 -T 10 # trace top 10 Ruby method calls
29 ./ucalls -l ruby 1344 -L # trace Ruby calls including latency
Sasha Goldshteincfb5ee72017-02-08 14:32:51 -050030 ./ucalls -l php 443 -LS # trace PHP calls and syscalls with latency
Sasha Goldshteina245c792016-10-25 02:18:35 -070031 ./ucalls -l python 2020 -mL # trace Python calls including latency in ms
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070032"""
33parser = argparse.ArgumentParser(
34 description="Summarize method calls in high-level languages.",
35 formatter_class=argparse.RawDescriptionHelpFormatter,
36 epilog=examples)
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070037parser.add_argument("pid", type=int, help="process id to attach to")
38parser.add_argument("interval", type=int, nargs='?',
39 help="print every specified number of seconds")
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020040parser.add_argument("-l", "--language", choices=languages + ["none"],
Sasha Goldshteina245c792016-10-25 02:18:35 -070041 help="language to trace (if none, trace syscalls only)")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070042parser.add_argument("-T", "--top", type=int,
43 help="number of most frequent/slow calls to print")
44parser.add_argument("-L", "--latency", action="store_true",
45 help="record method latency from enter to exit (except recursive calls)")
Sasha Goldshteina245c792016-10-25 02:18:35 -070046parser.add_argument("-S", "--syscalls", action="store_true",
47 help="record syscall latency (adds overhead)")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070048parser.add_argument("-v", "--verbose", action="store_true",
49 help="verbose mode: print the BPF program (for debugging purposes)")
50parser.add_argument("-m", "--milliseconds", action="store_true",
51 help="report times in milliseconds (default is microseconds)")
52args = parser.parse_args()
53
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020054language = args.language
55if not language:
56 language = utils.detect_language(languages, args.pid)
57
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070058# We assume that the entry and return probes have the same arguments. This is
Sasha Goldshteincfb5ee72017-02-08 14:32:51 -050059# the case for Java, Python, Ruby, and PHP. If there's a language where it's
60# not the case, we will need to build a custom correlator from entry to exit.
Geneviève Bastien830c1f72017-07-14 16:04:12 -040061extra_message = ""
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020062if language == "java":
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070063 # TODO for JVM entries, we actually have the real length of the class
Sasha Goldshteina245c792016-10-25 02:18:35 -070064 # and method strings in arg3 and arg5 respectively, so we can insert
65 # the null terminator in its proper position.
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070066 entry_probe = "method__entry"
67 return_probe = "method__return"
68 read_class = "bpf_usdt_readarg(2, ctx, &clazz);"
69 read_method = "bpf_usdt_readarg(4, ctx, &method);"
Geneviève Bastien830c1f72017-07-14 16:04:12 -040070 extra_message = "If you do not see any results, make sure you ran java with option -XX:+ExtendedDTraceProbes"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020071elif language == "python":
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070072 entry_probe = "function__entry"
73 return_probe = "function__return"
74 read_class = "bpf_usdt_readarg(1, ctx, &clazz);" # filename really
75 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020076elif language == "ruby":
Sasha Goldshtein6e5c6212016-10-25 04:30:54 -070077 # TODO Also probe cmethod__entry and cmethod__return with same arguments
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070078 entry_probe = "method__entry"
79 return_probe = "method__return"
80 read_class = "bpf_usdt_readarg(1, ctx, &clazz);"
81 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020082elif language == "php":
Sasha Goldshteincfb5ee72017-02-08 14:32:51 -050083 entry_probe = "function__entry"
84 return_probe = "function__return"
85 read_class = "bpf_usdt_readarg(4, ctx, &clazz);"
86 read_method = "bpf_usdt_readarg(1, ctx, &method);"
Geneviève Bastien830c1f72017-07-14 16:04:12 -040087 extra_message = "If you do not see any results, make sure the environment variable USE_ZEND_DTRACE is set to 1"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020088elif not language or language == "none":
Sasha Goldshteina245c792016-10-25 02:18:35 -070089 if not args.syscalls:
90 print("Nothing to do; use -S to trace syscalls.")
91 exit(1)
92 entry_probe, return_probe, read_class, read_method = ("", "", "", "")
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020093 if language:
94 language = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070095
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070096program = """
Sasha Goldshteina245c792016-10-25 02:18:35 -070097#include <linux/ptrace.h>
98
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070099#define MAX_STRING_LENGTH 80
Sasha Goldshteina245c792016-10-25 02:18:35 -0700100DEFINE_NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700101DEFINE_LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -0700102DEFINE_SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700103
104struct method_t {
105 char clazz[MAX_STRING_LENGTH];
106 char method[MAX_STRING_LENGTH];
107};
108struct entry_t {
109 u64 pid;
110 struct method_t method;
111};
112struct info_t {
113 u64 num_calls;
114 u64 total_ns;
115};
Sasha Goldshteina245c792016-10-25 02:18:35 -0700116struct syscall_entry_t {
117 u64 timestamp;
118 u64 ip;
119};
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700120
121#ifndef LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -0700122 BPF_HASH(counts, struct method_t, u64); // number of calls
123 #ifdef SYSCALLS
124 BPF_HASH(syscounts, u64, u64); // number of calls per IP
125 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700126#else
Sasha Goldshteina245c792016-10-25 02:18:35 -0700127 BPF_HASH(times, struct method_t, struct info_t);
128 BPF_HASH(entry, struct entry_t, u64); // timestamp at entry
129 #ifdef SYSCALLS
130 BPF_HASH(systimes, u64, struct info_t); // latency per IP
131 BPF_HASH(sysentry, u64, struct syscall_entry_t); // ts + IP at entry
132 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700133#endif
134
Sasha Goldshteina245c792016-10-25 02:18:35 -0700135#ifndef NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700136int trace_entry(struct pt_regs *ctx) {
137 u64 clazz = 0, method = 0, val = 0;
138 u64 *valp;
139 struct entry_t data = {0};
140#ifdef LATENCY
141 u64 timestamp = bpf_ktime_get_ns();
142 data.pid = bpf_get_current_pid_tgid();
143#endif
144 READ_CLASS
145 READ_METHOD
146 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
147 (void *)clazz);
148 bpf_probe_read(&data.method.method, sizeof(data.method.method),
149 (void *)method);
150#ifndef LATENCY
151 valp = counts.lookup_or_init(&data.method, &val);
152 ++(*valp);
153#endif
154#ifdef LATENCY
155 entry.update(&data, &timestamp);
156#endif
157 return 0;
158}
159
160#ifdef LATENCY
161int trace_return(struct pt_regs *ctx) {
162 u64 *entry_timestamp, clazz = 0, method = 0;
163 struct info_t *info, zero = {};
164 struct entry_t data = {};
165 data.pid = bpf_get_current_pid_tgid();
166 READ_CLASS
167 READ_METHOD
168 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
169 (void *)clazz);
170 bpf_probe_read(&data.method.method, sizeof(data.method.method),
171 (void *)method);
172 entry_timestamp = entry.lookup(&data);
173 if (!entry_timestamp) {
174 return 0; // missed the entry event
175 }
176 info = times.lookup_or_init(&data.method, &zero);
177 info->num_calls += 1;
178 info->total_ns += bpf_ktime_get_ns() - *entry_timestamp;
179 entry.delete(&data);
180 return 0;
181}
Sasha Goldshteina245c792016-10-25 02:18:35 -0700182#endif // LATENCY
183#endif // NOLANG
184
185#ifdef SYSCALLS
186int syscall_entry(struct pt_regs *ctx) {
187 u64 pid = bpf_get_current_pid_tgid();
188 u64 *valp, ip = ctx->ip, val = 0;
189 PID_FILTER
190#ifdef LATENCY
191 struct syscall_entry_t data = {};
192 data.timestamp = bpf_ktime_get_ns();
193 data.ip = ip;
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700194#endif
Sasha Goldshteina245c792016-10-25 02:18:35 -0700195#ifndef LATENCY
196 valp = syscounts.lookup_or_init(&ip, &val);
197 ++(*valp);
198#endif
199#ifdef LATENCY
200 sysentry.update(&pid, &data);
201#endif
202 return 0;
203}
204
205#ifdef LATENCY
206int syscall_return(struct pt_regs *ctx) {
207 struct syscall_entry_t *e;
208 struct info_t *info, zero = {};
209 u64 pid = bpf_get_current_pid_tgid(), ip;
210 PID_FILTER
211 e = sysentry.lookup(&pid);
212 if (!e) {
213 return 0; // missed the entry event
214 }
215 ip = e->ip;
216 info = systimes.lookup_or_init(&ip, &zero);
217 info->num_calls += 1;
218 info->total_ns += bpf_ktime_get_ns() - e->timestamp;
219 sysentry.delete(&pid);
220 return 0;
221}
222#endif // LATENCY
223#endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700224""".replace("READ_CLASS", read_class) \
225 .replace("READ_METHOD", read_method) \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700226 .replace("PID_FILTER", "if ((pid >> 32) != %d) { return 0; }" % args.pid) \
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200227 .replace("DEFINE_NOLANG", "#define NOLANG" if not language else "") \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700228 .replace("DEFINE_LATENCY", "#define LATENCY" if args.latency else "") \
229 .replace("DEFINE_SYSCALLS", "#define SYSCALLS" if args.syscalls else "")
230
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200231if language:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700232 usdt = USDT(pid=args.pid)
Sasha Goldshteindc3a57c2017-02-08 16:02:11 -0500233 usdt.enable_probe_or_bail(entry_probe, "trace_entry")
Sasha Goldshteina245c792016-10-25 02:18:35 -0700234 if args.latency:
Sasha Goldshteindc3a57c2017-02-08 16:02:11 -0500235 usdt.enable_probe_or_bail(return_probe, "trace_return")
Sasha Goldshteina245c792016-10-25 02:18:35 -0700236else:
237 usdt = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700238
239if args.verbose:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700240 if usdt:
241 print(usdt.get_text())
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700242 print(program)
243
Sasha Goldshteina245c792016-10-25 02:18:35 -0700244bpf = BPF(text=program, usdt_contexts=[usdt] if usdt else [])
245if args.syscalls:
246 syscall_regex = "^[Ss]y[Ss]_.*"
247 bpf.attach_kprobe(event_re=syscall_regex, fn_name="syscall_entry")
248 if args.latency:
249 bpf.attach_kretprobe(event_re=syscall_regex, fn_name="syscall_return")
250 print("Attached %d kernel probes for syscall tracing." %
251 bpf.num_open_kprobes())
252
253def get_data():
254 # Will be empty when no language was specified for tracing
255 if args.latency:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100256 data = list(map(lambda kv: (kv[0].clazz + "." + kv[0].method,
257 (kv[1].num_calls, kv[1].total_ns)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100258 bpf["times"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700259 else:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100260 data = list(map(lambda kv: (kv[0].clazz + "." + kv[0].method,
261 (kv[1].value, 0)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100262 bpf["counts"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700263
264 if args.syscalls:
265 if args.latency:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100266 syscalls = map(lambda kv: (bpf.ksym(kv[0].value),
267 (kv[1].num_calls, kv[1].total_ns)),
Sasha Goldshteina245c792016-10-25 02:18:35 -0700268 bpf["systimes"].items())
269 data.extend(syscalls)
270 else:
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100271 syscalls = map(lambda kv: (bpf.ksym(kv[0].value),
272 (kv[1].value, 0)),
Sasha Goldshteina245c792016-10-25 02:18:35 -0700273 bpf["syscounts"].items())
274 data.extend(syscalls)
275
Rafael Fonseca0d669062017-02-13 15:52:04 +0100276 return sorted(data, key=lambda kv: kv[1][1 if args.latency else 0])
Sasha Goldshteina245c792016-10-25 02:18:35 -0700277
278def clear_data():
279 if args.latency:
280 bpf["times"].clear()
281 else:
282 bpf["counts"].clear()
283
284 if args.syscalls:
285 if args.latency:
286 bpf["systimes"].clear()
287 else:
288 bpf["syscounts"].clear()
289
290exit_signaled = False
291print("Tracing calls in process %d (language: %s)... Ctrl-C to quit." %
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200292 (args.pid, language or "none"))
Geneviève Bastien830c1f72017-07-14 16:04:12 -0400293if extra_message:
294 print(extra_message)
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700295while True:
296 try:
297 sleep(args.interval or 99999999)
298 except KeyboardInterrupt:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700299 exit_signaled = True
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700300 print()
Sasha Goldshteina245c792016-10-25 02:18:35 -0700301 data = get_data() # [(function, (num calls, latency in ns))]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700302 if args.latency:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700303 time_col = "TIME (ms)" if args.milliseconds else "TIME (us)"
304 print("%-50s %8s %8s" % ("METHOD", "# CALLS", time_col))
305 else:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700306 print("%-50s %8s" % ("METHOD", "# CALLS"))
307 if args.top:
308 data = data[-args.top:]
309 for key, value in data:
310 if args.latency:
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100311 time = value[1] / 1000000.0 if args.milliseconds else \
312 value[1] / 1000.0
Sasha Goldshteina245c792016-10-25 02:18:35 -0700313 print("%-50s %8d %6.2f" % (key, value[0], time))
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700314 else:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700315 print("%-50s %8d" % (key, value[0]))
316 if args.interval and not exit_signaled:
317 clear_data()
318 else:
319 if args.syscalls:
320 print("Detaching kernel probes, please wait...")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700321 exit()