blob: 1a0fe219d8a7cd50a853196b6c4dce987d3529d7 [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#
Marko Myllynen9162be42018-09-04 19:45:16 +03007# USAGE: ucalls [-l {java,perl,php,python,ruby}] [-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
Marko Myllynen9162be42018-09-04 19:45:16 +030021languages = ["java", "perl", "php", "python", "ruby"]
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)")
Marko Myllynen27e7aea2018-09-26 20:09:07 +030052parser.add_argument("--ebpf", action="store_true",
53 help=argparse.SUPPRESS)
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070054args = parser.parse_args()
55
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020056language = args.language
57if not language:
58 language = utils.detect_language(languages, args.pid)
59
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070060# We assume that the entry and return probes have the same arguments. This is
Sasha Goldshteincfb5ee72017-02-08 14:32:51 -050061# the case for Java, Python, Ruby, and PHP. If there's a language where it's
62# not the case, we will need to build a custom correlator from entry to exit.
Geneviève Bastien830c1f72017-07-14 16:04:12 -040063extra_message = ""
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020064if language == "java":
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070065 # TODO for JVM entries, we actually have the real length of the class
Sasha Goldshteina245c792016-10-25 02:18:35 -070066 # and method strings in arg3 and arg5 respectively, so we can insert
67 # the null terminator in its proper position.
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070068 entry_probe = "method__entry"
69 return_probe = "method__return"
70 read_class = "bpf_usdt_readarg(2, ctx, &clazz);"
71 read_method = "bpf_usdt_readarg(4, ctx, &method);"
Paul Chaignonc8b4f672017-10-07 11:51:45 +020072 extra_message = ("If you do not see any results, make sure you ran java"
73 " with option -XX:+ExtendedDTraceProbes")
Marko Myllynen9162be42018-09-04 19:45:16 +030074elif language == "perl":
75 entry_probe = "sub__entry"
76 return_probe = "sub__return"
77 read_class = "bpf_usdt_readarg(2, ctx, &clazz);" # filename really
78 read_method = "bpf_usdt_readarg(1, ctx, &method);"
79elif language == "php":
80 entry_probe = "function__entry"
81 return_probe = "function__return"
82 read_class = "bpf_usdt_readarg(4, ctx, &clazz);"
83 read_method = "bpf_usdt_readarg(1, ctx, &method);"
84 extra_message = ("If you do not see any results, make sure the environment"
85 " variable USE_ZEND_DTRACE is set to 1")
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020086elif language == "python":
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070087 entry_probe = "function__entry"
88 return_probe = "function__return"
89 read_class = "bpf_usdt_readarg(1, ctx, &clazz);" # filename really
90 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020091elif language == "ruby":
Sasha Goldshtein6e5c6212016-10-25 04:30:54 -070092 # TODO Also probe cmethod__entry and cmethod__return with same arguments
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -070093 entry_probe = "method__entry"
94 return_probe = "method__return"
95 read_class = "bpf_usdt_readarg(1, ctx, &clazz);"
96 read_method = "bpf_usdt_readarg(2, ctx, &method);"
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +020097elif not language or language == "none":
Sasha Goldshteina245c792016-10-25 02:18:35 -070098 if not args.syscalls:
99 print("Nothing to do; use -S to trace syscalls.")
100 exit(1)
101 entry_probe, return_probe, read_class, read_method = ("", "", "", "")
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200102 if language:
103 language = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700104
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700105program = """
Sasha Goldshteina245c792016-10-25 02:18:35 -0700106#include <linux/ptrace.h>
107
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700108#define MAX_STRING_LENGTH 80
Sasha Goldshteina245c792016-10-25 02:18:35 -0700109DEFINE_NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700110DEFINE_LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -0700111DEFINE_SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700112
113struct method_t {
114 char clazz[MAX_STRING_LENGTH];
115 char method[MAX_STRING_LENGTH];
116};
117struct entry_t {
118 u64 pid;
119 struct method_t method;
120};
121struct info_t {
122 u64 num_calls;
123 u64 total_ns;
124};
Sasha Goldshteina245c792016-10-25 02:18:35 -0700125struct syscall_entry_t {
126 u64 timestamp;
127 u64 ip;
128};
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700129
130#ifndef LATENCY
Sasha Goldshteina245c792016-10-25 02:18:35 -0700131 BPF_HASH(counts, struct method_t, u64); // number of calls
132 #ifdef SYSCALLS
133 BPF_HASH(syscounts, u64, u64); // number of calls per IP
134 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700135#else
Sasha Goldshteina245c792016-10-25 02:18:35 -0700136 BPF_HASH(times, struct method_t, struct info_t);
137 BPF_HASH(entry, struct entry_t, u64); // timestamp at entry
138 #ifdef SYSCALLS
139 BPF_HASH(systimes, u64, struct info_t); // latency per IP
140 BPF_HASH(sysentry, u64, struct syscall_entry_t); // ts + IP at entry
141 #endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700142#endif
143
Sasha Goldshteina245c792016-10-25 02:18:35 -0700144#ifndef NOLANG
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700145int trace_entry(struct pt_regs *ctx) {
146 u64 clazz = 0, method = 0, val = 0;
147 u64 *valp;
148 struct entry_t data = {0};
149#ifdef LATENCY
150 u64 timestamp = bpf_ktime_get_ns();
151 data.pid = bpf_get_current_pid_tgid();
152#endif
153 READ_CLASS
154 READ_METHOD
155 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
156 (void *)clazz);
157 bpf_probe_read(&data.method.method, sizeof(data.method.method),
158 (void *)method);
159#ifndef LATENCY
160 valp = counts.lookup_or_init(&data.method, &val);
161 ++(*valp);
162#endif
163#ifdef LATENCY
164 entry.update(&data, &timestamp);
165#endif
166 return 0;
167}
168
169#ifdef LATENCY
170int trace_return(struct pt_regs *ctx) {
171 u64 *entry_timestamp, clazz = 0, method = 0;
172 struct info_t *info, zero = {};
173 struct entry_t data = {};
174 data.pid = bpf_get_current_pid_tgid();
175 READ_CLASS
176 READ_METHOD
177 bpf_probe_read(&data.method.clazz, sizeof(data.method.clazz),
178 (void *)clazz);
179 bpf_probe_read(&data.method.method, sizeof(data.method.method),
180 (void *)method);
181 entry_timestamp = entry.lookup(&data);
182 if (!entry_timestamp) {
183 return 0; // missed the entry event
184 }
185 info = times.lookup_or_init(&data.method, &zero);
186 info->num_calls += 1;
187 info->total_ns += bpf_ktime_get_ns() - *entry_timestamp;
188 entry.delete(&data);
189 return 0;
190}
Sasha Goldshteina245c792016-10-25 02:18:35 -0700191#endif // LATENCY
192#endif // NOLANG
193
194#ifdef SYSCALLS
195int syscall_entry(struct pt_regs *ctx) {
196 u64 pid = bpf_get_current_pid_tgid();
Yonghong Songeb6ddc02017-10-26 22:33:24 -0700197 u64 *valp, ip = PT_REGS_IP(ctx), val = 0;
Sasha Goldshteina245c792016-10-25 02:18:35 -0700198 PID_FILTER
199#ifdef LATENCY
200 struct syscall_entry_t data = {};
201 data.timestamp = bpf_ktime_get_ns();
202 data.ip = ip;
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700203#endif
Sasha Goldshteina245c792016-10-25 02:18:35 -0700204#ifndef LATENCY
205 valp = syscounts.lookup_or_init(&ip, &val);
206 ++(*valp);
207#endif
208#ifdef LATENCY
209 sysentry.update(&pid, &data);
210#endif
211 return 0;
212}
213
214#ifdef LATENCY
215int syscall_return(struct pt_regs *ctx) {
216 struct syscall_entry_t *e;
217 struct info_t *info, zero = {};
218 u64 pid = bpf_get_current_pid_tgid(), ip;
219 PID_FILTER
220 e = sysentry.lookup(&pid);
221 if (!e) {
222 return 0; // missed the entry event
223 }
224 ip = e->ip;
225 info = systimes.lookup_or_init(&ip, &zero);
226 info->num_calls += 1;
227 info->total_ns += bpf_ktime_get_ns() - e->timestamp;
228 sysentry.delete(&pid);
229 return 0;
230}
231#endif // LATENCY
232#endif // SYSCALLS
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700233""".replace("READ_CLASS", read_class) \
234 .replace("READ_METHOD", read_method) \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700235 .replace("PID_FILTER", "if ((pid >> 32) != %d) { return 0; }" % args.pid) \
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200236 .replace("DEFINE_NOLANG", "#define NOLANG" if not language else "") \
Sasha Goldshteina245c792016-10-25 02:18:35 -0700237 .replace("DEFINE_LATENCY", "#define LATENCY" if args.latency else "") \
238 .replace("DEFINE_SYSCALLS", "#define SYSCALLS" if args.syscalls else "")
239
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200240if language:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700241 usdt = USDT(pid=args.pid)
Sasha Goldshteindc3a57c2017-02-08 16:02:11 -0500242 usdt.enable_probe_or_bail(entry_probe, "trace_entry")
Sasha Goldshteina245c792016-10-25 02:18:35 -0700243 if args.latency:
Sasha Goldshteindc3a57c2017-02-08 16:02:11 -0500244 usdt.enable_probe_or_bail(return_probe, "trace_return")
Sasha Goldshteina245c792016-10-25 02:18:35 -0700245else:
246 usdt = None
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700247
Marko Myllynen27e7aea2018-09-26 20:09:07 +0300248if args.ebpf or args.verbose:
249 if args.verbose and usdt:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700250 print(usdt.get_text())
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700251 print(program)
Marko Myllynen27e7aea2018-09-26 20:09:07 +0300252 if args.ebpf:
253 exit()
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700254
Sasha Goldshteina245c792016-10-25 02:18:35 -0700255bpf = BPF(text=program, usdt_contexts=[usdt] if usdt else [])
256if args.syscalls:
257 syscall_regex = "^[Ss]y[Ss]_.*"
258 bpf.attach_kprobe(event_re=syscall_regex, fn_name="syscall_entry")
259 if args.latency:
260 bpf.attach_kretprobe(event_re=syscall_regex, fn_name="syscall_return")
261 print("Attached %d kernel probes for syscall tracing." %
262 bpf.num_open_kprobes())
263
264def get_data():
265 # Will be empty when no language was specified for tracing
266 if args.latency:
jeromemarchand4e4c9e02018-07-19 22:20:54 +0200267 data = list(map(lambda kv: (kv[0].clazz.decode('utf-8', 'replace') \
268 + "." + \
269 kv[0].method.decode('utf-8', 'replace'),
Rafael Fonseca0d669062017-02-13 15:52:04 +0100270 (kv[1].num_calls, kv[1].total_ns)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100271 bpf["times"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700272 else:
jeromemarchand4e4c9e02018-07-19 22:20:54 +0200273 data = list(map(lambda kv: (kv[0].clazz.decode('utf-8', 'replace') \
274 + "." + \
275 kv[0].method.decode('utf-8', 'replace'),
Rafael Fonseca0d669062017-02-13 15:52:04 +0100276 (kv[1].value, 0)),
Rafael Fonseca42900ae2017-02-13 15:46:54 +0100277 bpf["counts"].items()))
Sasha Goldshteina245c792016-10-25 02:18:35 -0700278
279 if args.syscalls:
280 if args.latency:
Rafael Fonseca0d669062017-02-13 15:52:04 +0100281 syscalls = map(lambda kv: (bpf.ksym(kv[0].value),
282 (kv[1].num_calls, kv[1].total_ns)),
Sasha Goldshteina245c792016-10-25 02:18:35 -0700283 bpf["systimes"].items())
284 data.extend(syscalls)
285 else:
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100286 syscalls = map(lambda kv: (bpf.ksym(kv[0].value),
287 (kv[1].value, 0)),
Sasha Goldshteina245c792016-10-25 02:18:35 -0700288 bpf["syscounts"].items())
289 data.extend(syscalls)
290
Rafael Fonseca0d669062017-02-13 15:52:04 +0100291 return sorted(data, key=lambda kv: kv[1][1 if args.latency else 0])
Sasha Goldshteina245c792016-10-25 02:18:35 -0700292
293def clear_data():
294 if args.latency:
295 bpf["times"].clear()
296 else:
297 bpf["counts"].clear()
298
299 if args.syscalls:
300 if args.latency:
301 bpf["systimes"].clear()
302 else:
303 bpf["syscounts"].clear()
304
305exit_signaled = False
306print("Tracing calls in process %d (language: %s)... Ctrl-C to quit." %
Paul Chaignon4bb6d7f2017-03-30 19:05:40 +0200307 (args.pid, language or "none"))
Geneviève Bastien830c1f72017-07-14 16:04:12 -0400308if extra_message:
309 print(extra_message)
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700310while True:
311 try:
312 sleep(args.interval or 99999999)
313 except KeyboardInterrupt:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700314 exit_signaled = True
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700315 print()
Sasha Goldshteina245c792016-10-25 02:18:35 -0700316 data = get_data() # [(function, (num calls, latency in ns))]
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700317 if args.latency:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700318 time_col = "TIME (ms)" if args.milliseconds else "TIME (us)"
319 print("%-50s %8s %8s" % ("METHOD", "# CALLS", time_col))
320 else:
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700321 print("%-50s %8s" % ("METHOD", "# CALLS"))
322 if args.top:
323 data = data[-args.top:]
324 for key, value in data:
325 if args.latency:
Paul Chaignon956ca1c2017-03-04 20:07:56 +0100326 time = value[1] / 1000000.0 if args.milliseconds else \
327 value[1] / 1000.0
Sasha Goldshteina245c792016-10-25 02:18:35 -0700328 print("%-50s %8d %6.2f" % (key, value[0], time))
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700329 else:
Sasha Goldshteina245c792016-10-25 02:18:35 -0700330 print("%-50s %8d" % (key, value[0]))
331 if args.interval and not exit_signaled:
332 clear_data()
333 else:
334 if args.syscalls:
335 print("Detaching kernel probes, please wait...")
Sasha Goldshteinc13d14f2016-10-17 04:13:48 -0700336 exit()