blob: a58633cfad79cc5b18649bc3abf52ba09f474ec5 [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.
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020061if language == "java":
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070062 # TODO for JVM entries, we actually have the real length of the class
Sasha Goldshteina245c792016-10-25 02:18:35 -070063 # and method strings in arg3 and arg5 respectively, so we can insert
64 # the null terminator in its proper position.
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070065 entry_probe = "method__entry"
66 return_probe = "method__return"
67 read_class = "bpf_usdt_readarg(2, ctx, &clazz);"
68 read_method = "bpf_usdt_readarg(4, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020069elif language == "python":
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070070 entry_probe = "function__entry"
71 return_probe = "function__return"
72 read_class = "bpf_usdt_readarg(1, ctx, &clazz);" # filename really
73 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020074elif language == "ruby":
Sasha Goldshtein6e5c6212016-10-25 04:30:54 -070075 # TODO Also probe cmethod__entry and cmethod__return with same arguments
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070076 entry_probe = "method__entry"
77 return_probe = "method__return"
78 read_class = "bpf_usdt_readarg(1, ctx, &clazz);"
79 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020080elif language == "php":
Sasha Goldshteincfb5ee72017-02-08 14:32:51 -050081 entry_probe = "function__entry"
82 return_probe = "function__return"
83 read_class = "bpf_usdt_readarg(4, ctx, &clazz);"
84 read_method = "bpf_usdt_readarg(1, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020085elif not language or language == "none":
Sasha Goldshteina245c792016-10-25 02:18:35 -070086 if not args.syscalls:
87 print("Nothing to do; use -S to trace syscalls.")
88 exit(1)
89 entry_probe, return_probe, read_class, read_method = ("", "", "", "")
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020090 if language:
91 language = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070092
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070093program = """
Sasha Goldshteina245c792016-10-25 02:18:35 -070094#include <linux/ptrace.h>
95
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070096#define MAX_STRING_LENGTH 80
Sasha Goldshteina245c792016-10-25 02:18:35 -070097DEFINE_NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070098DEFINE_LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -070099DEFINE_SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700100
101struct method_t {
102 char clazz[MAX_STRING_LENGTH];
103 char method[MAX_STRING_LENGTH];
104};
105struct entry_t {
106 u64 pid;
107 struct method_t method;
108};
109struct info_t {
110 u64 num_calls;
111 u64 total_ns;
112};
Sasha Goldshteina245c792016-10-25 02:18:35 -0700113struct syscall_entry_t {
114 u64 timestamp;
115 u64 ip;
116};
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700117
118#ifndef LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -0700119 BPF_HASH(counts, struct method_t, u64); // number of calls
120 #ifdef SYSCALLS
121 BPF_HASH(syscounts, u64, u64); // number of calls per IP
122 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700123#else
Sasha Goldshteina245c792016-10-25 02:18:35 -0700124 BPF_HASH(times, struct method_t, struct info_t);
125 BPF_HASH(entry, struct entry_t, u64); // timestamp at entry
126 #ifdef SYSCALLS
127 BPF_HASH(systimes, u64, struct info_t); // latency per IP
128 BPF_HASH(sysentry, u64, struct syscall_entry_t); // ts + IP at entry
129 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700130#endif
131
Sasha Goldshteina245c792016-10-25 02:18:35 -0700132#ifndef NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700133int trace_entry(struct pt_regs *ctx) {
134 u64 clazz = 0, method = 0, val = 0;
135 u64 *valp;
136 struct entry_t data = {0};
137#ifdef LATENCY
138 u64 timestamp = bpf_ktime_get_ns();
139 data.pid = bpf_get_current_pid_tgid();
140#endif
141 READ_CLASS
142 READ_METHOD
143 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
144 (void *)clazz);
145 bpf_probe_read(&data.method.method, sizeof(data.method.method),
146 (void *)method);
147#ifndef LATENCY
148 valp = counts.lookup_or_init(&data.method, &val);
149 ++(*valp);
150#endif
151#ifdef LATENCY
152 entry.update(&data, &timestamp);
153#endif
154 return 0;
155}
156
157#ifdef LATENCY
158int trace_return(struct pt_regs *ctx) {
159 u64 *entry_timestamp, clazz = 0, method = 0;
160 struct info_t *info, zero = {};
161 struct entry_t data = {};
162 data.pid = bpf_get_current_pid_tgid();
163 READ_CLASS
164 READ_METHOD
165 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
166 (void *)clazz);
167 bpf_probe_read(&data.method.method, sizeof(data.method.method),
168 (void *)method);
169 entry_timestamp = entry.lookup(&data);
170 if (!entry_timestamp) {
171 return 0; // missed the entry event
172 }
173 info = times.lookup_or_init(&data.method, &zero);
174 info->num_calls += 1;
175 info->total_ns += bpf_ktime_get_ns() - *entry_timestamp;
176 entry.delete(&data);
177 return 0;
178}
Sasha Goldshteina245c792016-10-25 02:18:35 -0700179#endif // LATENCY
180#endif // NOLANG
181
182#ifdef SYSCALLS
183int syscall_entry(struct pt_regs *ctx) {
184 u64 pid = bpf_get_current_pid_tgid();
185 u64 *valp, ip = ctx->ip, val = 0;
186 PID_FILTER
187#ifdef LATENCY
188 struct syscall_entry_t data = {};
189 data.timestamp = bpf_ktime_get_ns();
190 data.ip = ip;
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700191#endif
Sasha Goldshteina245c792016-10-25 02:18:35 -0700192#ifndef LATENCY
193 valp = syscounts.lookup_or_init(&ip, &val);
194 ++(*valp);
195#endif
196#ifdef LATENCY
197 sysentry.update(&pid, &data);
198#endif
199 return 0;
200}
201
202#ifdef LATENCY
203int syscall_return(struct pt_regs *ctx) {
204 struct syscall_entry_t *e;
205 struct info_t *info, zero = {};
206 u64 pid = bpf_get_current_pid_tgid(), ip;
207 PID_FILTER
208 e = sysentry.lookup(&pid);
209 if (!e) {
210 return 0; // missed the entry event
211 }
212 ip = e->ip;
213 info = systimes.lookup_or_init(&ip, &zero);
214 info->num_calls += 1;
215 info->total_ns += bpf_ktime_get_ns() - e->timestamp;
216 sysentry.delete(&pid);
217 return 0;
218}
219#endif // LATENCY
220#endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700221""".replace("READ_CLASS", read_class) \
222 .replace("READ_METHOD", read_method) \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700223 .replace("PID_FILTER", "if ((pid >> 32) != %d) { return 0; }" % args.pid) \
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200224 .replace("DEFINE_NOLANG", "#define NOLANG" if not language else "") \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700225 .replace("DEFINE_LATENCY", "#define LATENCY" if args.latency else "") \
226 .replace("DEFINE_SYSCALLS", "#define SYSCALLS" if args.syscalls else "")
227
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200228if language:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700229 usdt = USDT(pid=args.pid)
Sasha Goldshteindc3a57c2017-02-08 16:02:11 -0500230 usdt.enable_probe_or_bail(entry_probe, "trace_entry")
Sasha Goldshteina245c792016-10-25 02:18:35 -0700231 if args.latency:
Sasha Goldshteindc3a57c2017-02-08 16:02:11 -0500232 usdt.enable_probe_or_bail(return_probe, "trace_return")
Sasha Goldshteina245c792016-10-25 02:18:35 -0700233else:
234 usdt = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700235
236if args.verbose:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700237 if usdt:
238 print(usdt.get_text())
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700239 print(program)
240
Sasha Goldshteina245c792016-10-25 02:18:35 -0700241bpf = BPF(text=program, usdt_contexts=[usdt] if usdt else [])
242if args.syscalls:
243 syscall_regex = "^[Ss]y[Ss]_.*"
244 bpf.attach_kprobe(event_re=syscall_regex, fn_name="syscall_entry")
245 if args.latency:
246 bpf.attach_kretprobe(event_re=syscall_regex, fn_name="syscall_return")
247 print("Attached %d kernel probes for syscall tracing." %
248 bpf.num_open_kprobes())
249
250def get_data():
251 # Will be empty when no language was specified for tracing
252 if args.latency:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100253 data = list(map(lambda kv: (kv[0].clazz + "." + kv[0].method,
254 (kv[1].num_calls, kv[1].total_ns)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100255 bpf["times"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700256 else:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100257 data = list(map(lambda kv: (kv[0].clazz + "." + kv[0].method,
258 (kv[1].value, 0)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100259 bpf["counts"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700260
261 if args.syscalls:
262 if args.latency:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100263 syscalls = map(lambda kv: (bpf.ksym(kv[0].value),
264 (kv[1].num_calls, kv[1].total_ns)),
Sasha Goldshteina245c792016-10-25 02:18:35 -0700265 bpf["systimes"].items())
266 data.extend(syscalls)
267 else:
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100268 syscalls = map(lambda kv: (bpf.ksym(kv[0].value),
269 (kv[1].value, 0)),
Sasha Goldshteina245c792016-10-25 02:18:35 -0700270 bpf["syscounts"].items())
271 data.extend(syscalls)
272
Rafael Fonseca0d669062017-02-13 15:52:04 +0100273 return sorted(data, key=lambda kv: kv[1][1 if args.latency else 0])
Sasha Goldshteina245c792016-10-25 02:18:35 -0700274
275def clear_data():
276 if args.latency:
277 bpf["times"].clear()
278 else:
279 bpf["counts"].clear()
280
281 if args.syscalls:
282 if args.latency:
283 bpf["systimes"].clear()
284 else:
285 bpf["syscounts"].clear()
286
287exit_signaled = False
288print("Tracing calls in process %d (language: %s)... Ctrl-C to quit." %
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200289 (args.pid, language or "none"))
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700290while True:
291 try:
292 sleep(args.interval or 99999999)
293 except KeyboardInterrupt:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700294 exit_signaled = True
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700295 print()
Sasha Goldshteina245c792016-10-25 02:18:35 -0700296 data = get_data() # [(function, (num calls, latency in ns))]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700297 if args.latency:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700298 time_col = "TIME (ms)" if args.milliseconds else "TIME (us)"
299 print("%-50s %8s %8s" % ("METHOD", "# CALLS", time_col))
300 else:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700301 print("%-50s %8s" % ("METHOD", "# CALLS"))
302 if args.top:
303 data = data[-args.top:]
304 for key, value in data:
305 if args.latency:
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100306 time = value[1] / 1000000.0 if args.milliseconds else \
307 value[1] / 1000.0
Sasha Goldshteina245c792016-10-25 02:18:35 -0700308 print("%-50s %8d %6.2f" % (key, value[0], time))
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700309 else:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700310 print("%-50s %8d" % (key, value[0]))
311 if args.interval and not exit_signaled:
312 clear_data()
313 else:
314 if args.syscalls:
315 print("Detaching kernel probes, please wait...")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700316 exit()