blob: 43666fbcd1ff62f0868abab74006d2f71a4a4a63 [file] [log] [blame]
Brendan Gregg60393ea2016-10-04 15:18:11 -07001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# tcptop Summarize TCP send/recv throughput by host.
5# For Linux, uses BCC, eBPF. Embedded C.
6#
7# USAGE: tcptop [-h] [-C] [-S] [-p PID] [interval [count]]
8#
9# This uses dynamic tracing of kernel functions, and will need to be updated
10# to match kernel changes.
11#
12# WARNING: This traces all send/receives at the TCP level, and while it
13# summarizes data in-kernel to reduce overhead, there may still be some
14# overhead at high TCP send/receive rates (eg, ~13% of one CPU at 100k TCP
15# events/sec. This is not the same as packet rate: funccount can be used to
16# count the kprobes below to find out the TCP rate). Test in a lab environment
17# first. If your send/receive rate is low (eg, <1k/sec) then the overhead is
18# expected to be negligible.
19#
20# ToDo: Fit output to screen size (top X only) in default (not -C) mode.
21#
22# Copyright 2016 Netflix, Inc.
23# Licensed under the Apache License, Version 2.0 (the "License")
24#
25# 02-Sep-2016 Brendan Gregg Created this.
26
27from __future__ import print_function
28from bcc import BPF
29import argparse
30from socket import inet_ntop, AF_INET, AF_INET6
31from struct import pack
32from time import sleep, strftime
33from subprocess import call
34import ctypes as ct
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +020035from collections import namedtuple, defaultdict
Brendan Gregg60393ea2016-10-04 15:18:11 -070036
37# arguments
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -070038def range_check(string):
39 value = int(string)
40 if value < 1:
41 msg = "value must be stricly positive, got %d" % (value,)
42 raise argparse.ArgumentTypeError(msg)
43 return value
44
Brendan Gregg60393ea2016-10-04 15:18:11 -070045examples = """examples:
46 ./tcptop # trace TCP send/recv by host
47 ./tcptop -C # don't clear the screen
48 ./tcptop -p 181 # only trace PID 181
49"""
50parser = argparse.ArgumentParser(
51 description="Summarize TCP send/recv throughput by host",
52 formatter_class=argparse.RawDescriptionHelpFormatter,
53 epilog=examples)
54parser.add_argument("-C", "--noclear", action="store_true",
55 help="don't clear the screen")
56parser.add_argument("-S", "--nosummary", action="store_true",
57 help="skip system summary line")
58parser.add_argument("-p", "--pid",
59 help="trace this PID only")
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -070060parser.add_argument("interval", nargs="?", default=1, type=range_check,
Brendan Gregg60393ea2016-10-04 15:18:11 -070061 help="output interval, in seconds (default 1)")
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -070062parser.add_argument("count", nargs="?", default=-1, type=range_check,
Brendan Gregg60393ea2016-10-04 15:18:11 -070063 help="number of outputs")
Nathan Scottcf0792f2018-02-02 16:56:50 +110064parser.add_argument("--ebpf", action="store_true",
65 help=argparse.SUPPRESS)
Brendan Gregg60393ea2016-10-04 15:18:11 -070066args = parser.parse_args()
Brendan Gregg60393ea2016-10-04 15:18:11 -070067debug = 0
68
69# linux stats
70loadavg = "/proc/loadavg"
71
72# define BPF program
73bpf_text = """
74#include <uapi/linux/ptrace.h>
75#include <net/sock.h>
76#include <bcc/proto.h>
77
78struct ipv4_key_t {
79 u32 pid;
80 u32 saddr;
81 u32 daddr;
82 u16 lport;
83 u16 dport;
84};
85BPF_HASH(ipv4_send_bytes, struct ipv4_key_t);
86BPF_HASH(ipv4_recv_bytes, struct ipv4_key_t);
87
88struct ipv6_key_t {
89 u32 pid;
90 // workaround until unsigned __int128 support:
91 u64 saddr0;
92 u64 saddr1;
93 u64 daddr0;
94 u64 daddr1;
95 u16 lport;
96 u16 dport;
97};
98BPF_HASH(ipv6_send_bytes, struct ipv6_key_t);
99BPF_HASH(ipv6_recv_bytes, struct ipv6_key_t);
100
101int kprobe__tcp_sendmsg(struct pt_regs *ctx, struct sock *sk,
102 struct msghdr *msg, size_t size)
103{
104 u32 pid = bpf_get_current_pid_tgid();
105 FILTER
106 u16 dport = 0, family = sk->__sk_common.skc_family;
107 u64 *val, zero = 0;
108
109 if (family == AF_INET) {
110 struct ipv4_key_t ipv4_key = {.pid = pid};
111 ipv4_key.saddr = sk->__sk_common.skc_rcv_saddr;
112 ipv4_key.daddr = sk->__sk_common.skc_daddr;
113 ipv4_key.lport = sk->__sk_common.skc_num;
114 dport = sk->__sk_common.skc_dport;
115 ipv4_key.dport = ntohs(dport);
116 val = ipv4_send_bytes.lookup_or_init(&ipv4_key, &zero);
117 (*val) += size;
118
119 } else if (family == AF_INET6) {
120 struct ipv6_key_t ipv6_key = {.pid = pid};
121
Yonghong Song20fb64c2018-06-02 00:28:38 -0700122 ipv6_key.saddr0 = *(u64 *)&sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32[0];
123 ipv6_key.saddr1 = *(u64 *)&sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32[2];
124 ipv6_key.daddr0 = *(u64 *)&sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32[0];
125 ipv6_key.daddr1 = *(u64 *)&sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32[2];
Brendan Gregg60393ea2016-10-04 15:18:11 -0700126 ipv6_key.lport = sk->__sk_common.skc_num;
127 dport = sk->__sk_common.skc_dport;
128 ipv6_key.dport = ntohs(dport);
129 val = ipv6_send_bytes.lookup_or_init(&ipv6_key, &zero);
130 (*val) += size;
131 }
132 // else drop
133
134 return 0;
135}
136
137/*
138 * tcp_recvmsg() would be obvious to trace, but is less suitable because:
139 * - we'd need to trace both entry and return, to have both sock and size
140 * - misses tcp_read_sock() traffic
141 * we'd much prefer tracepoints once they are available.
142 */
143int kprobe__tcp_cleanup_rbuf(struct pt_regs *ctx, struct sock *sk, int copied)
144{
145 u32 pid = bpf_get_current_pid_tgid();
146 FILTER
147 u16 dport = 0, family = sk->__sk_common.skc_family;
148 u64 *val, zero = 0;
149
Benjamin Poirier81ad0542017-07-28 13:25:14 -0700150 if (copied <= 0)
Paul Chaignon6d9b1b22017-10-07 11:06:41 +0200151 return 0;
Benjamin Poirier81ad0542017-07-28 13:25:14 -0700152
Brendan Gregg60393ea2016-10-04 15:18:11 -0700153 if (family == AF_INET) {
154 struct ipv4_key_t ipv4_key = {.pid = pid};
155 ipv4_key.saddr = sk->__sk_common.skc_rcv_saddr;
156 ipv4_key.daddr = sk->__sk_common.skc_daddr;
157 ipv4_key.lport = sk->__sk_common.skc_num;
158 dport = sk->__sk_common.skc_dport;
159 ipv4_key.dport = ntohs(dport);
160 val = ipv4_recv_bytes.lookup_or_init(&ipv4_key, &zero);
161 (*val) += copied;
162
163 } else if (family == AF_INET6) {
164 struct ipv6_key_t ipv6_key = {.pid = pid};
Yonghong Song20fb64c2018-06-02 00:28:38 -0700165 ipv6_key.saddr0 = *(u64 *)&sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32[0];
166 ipv6_key.saddr1 = *(u64 *)&sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32[2];
167 ipv6_key.daddr0 = *(u64 *)&sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32[0];
168 ipv6_key.daddr1 = *(u64 *)&sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32[2];
Brendan Gregg60393ea2016-10-04 15:18:11 -0700169 ipv6_key.lport = sk->__sk_common.skc_num;
170 dport = sk->__sk_common.skc_dport;
171 ipv6_key.dport = ntohs(dport);
172 val = ipv6_recv_bytes.lookup_or_init(&ipv6_key, &zero);
173 (*val) += copied;
174 }
175 // else drop
176
177 return 0;
178}
179"""
180
181# code substitutions
182if args.pid:
183 bpf_text = bpf_text.replace('FILTER',
184 'if (pid != %s) { return 0; }' % args.pid)
185else:
186 bpf_text = bpf_text.replace('FILTER', '')
Nathan Scottcf0792f2018-02-02 16:56:50 +1100187if debug or args.ebpf:
Brendan Gregg60393ea2016-10-04 15:18:11 -0700188 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100189 if args.ebpf:
190 exit()
Brendan Gregg60393ea2016-10-04 15:18:11 -0700191
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200192TCPSessionKey = namedtuple('TCPSession', ['pid', 'laddr', 'lport', 'daddr', 'dport'])
193
Brendan Gregg60393ea2016-10-04 15:18:11 -0700194def pid_to_comm(pid):
195 try:
196 comm = open("/proc/%d/comm" % pid, "r").read().rstrip()
197 return comm
198 except IOError:
199 return str(pid)
200
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200201def get_ipv4_session_key(k):
202 return TCPSessionKey(pid=k.pid,
203 laddr=inet_ntop(AF_INET, pack("I", k.saddr)),
204 lport=k.lport,
205 daddr=inet_ntop(AF_INET, pack("I", k.daddr)),
206 dport=k.dport)
207
208def get_ipv6_session_key(k):
209 return TCPSessionKey(pid=k.pid,
210 laddr=inet_ntop(AF_INET6, pack("QQ", k.saddr0, k.saddr1)),
211 lport=k.lport,
212 daddr=inet_ntop(AF_INET6, pack("QQ", k.daddr0, k.daddr1)),
213 dport=k.dport)
214
Brendan Gregg60393ea2016-10-04 15:18:11 -0700215# initialize BPF
216b = BPF(text=bpf_text)
217
218ipv4_send_bytes = b["ipv4_send_bytes"]
219ipv4_recv_bytes = b["ipv4_recv_bytes"]
220ipv6_send_bytes = b["ipv6_send_bytes"]
221ipv6_recv_bytes = b["ipv6_recv_bytes"]
222
223print('Tracing... Output every %s secs. Hit Ctrl-C to end' % args.interval)
224
225# output
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -0700226i = 0
227exiting = False
228while i != args.count and not exiting:
Brendan Gregg60393ea2016-10-04 15:18:11 -0700229 try:
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -0700230 sleep(args.interval)
Brendan Gregg60393ea2016-10-04 15:18:11 -0700231 except KeyboardInterrupt:
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -0700232 exiting = True
Brendan Gregg60393ea2016-10-04 15:18:11 -0700233
234 # header
235 if args.noclear:
236 print()
237 else:
238 call("clear")
239 if not args.nosummary:
240 with open(loadavg) as stats:
241 print("%-8s loadavg: %s" % (strftime("%H:%M:%S"), stats.read()))
242
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200243 # IPv4: build dict of all seen keys
244 ipv4_throughput = defaultdict(lambda: [0, 0])
Brendan Gregg60393ea2016-10-04 15:18:11 -0700245 for k, v in ipv4_send_bytes.items():
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200246 key = get_ipv4_session_key(k)
247 ipv4_throughput[key][0] = v.value
248 ipv4_send_bytes.clear()
Brendan Gregg60393ea2016-10-04 15:18:11 -0700249
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200250 for k, v in ipv4_recv_bytes.items():
251 key = get_ipv4_session_key(k)
252 ipv4_throughput[key][1] = v.value
253 ipv4_recv_bytes.clear()
254
255 if ipv4_throughput:
Brendan Gregg60393ea2016-10-04 15:18:11 -0700256 print("%-6s %-12s %-21s %-21s %6s %6s" % ("PID", "COMM",
257 "LADDR", "RADDR", "RX_KB", "TX_KB"))
258
259 # output
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200260 for k, (send_bytes, recv_bytes) in sorted(ipv4_throughput.items(),
261 key=lambda kv: sum(kv[1]),
262 reverse=True):
Brendan Gregg60393ea2016-10-04 15:18:11 -0700263 print("%-6d %-12.12s %-21s %-21s %6d %6d" % (k.pid,
264 pid_to_comm(k.pid),
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200265 k.laddr + ":" + str(k.lport),
266 k.daddr + ":" + str(k.dport),
267 int(recv_bytes / 1024), int(send_bytes / 1024)))
Brendan Gregg60393ea2016-10-04 15:18:11 -0700268
269 # IPv6: build dict of all seen keys
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200270 ipv6_throughput = defaultdict(lambda: [0, 0])
Brendan Gregg60393ea2016-10-04 15:18:11 -0700271 for k, v in ipv6_send_bytes.items():
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200272 key = get_ipv6_session_key(k)
273 ipv6_throughput[key][0] = v.value
274 ipv6_send_bytes.clear()
Brendan Gregg60393ea2016-10-04 15:18:11 -0700275
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200276 for k, v in ipv6_recv_bytes.items():
277 key = get_ipv6_session_key(k)
278 ipv6_throughput[key][1] = v.value
279 ipv6_recv_bytes.clear()
280
281 if ipv6_throughput:
Brendan Gregg60393ea2016-10-04 15:18:11 -0700282 # more than 80 chars, sadly.
283 print("\n%-6s %-12s %-32s %-32s %6s %6s" % ("PID", "COMM",
284 "LADDR6", "RADDR6", "RX_KB", "TX_KB"))
285
286 # output
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200287 for k, (send_bytes, recv_bytes) in sorted(ipv6_throughput.items(),
288 key=lambda kv: sum(kv[1]),
289 reverse=True):
Brendan Gregg60393ea2016-10-04 15:18:11 -0700290 print("%-6d %-12.12s %-32s %-32s %6d %6d" % (k.pid,
291 pid_to_comm(k.pid),
Andreas Gerstmayrc64f4872018-07-06 14:59:07 +0200292 k.laddr + ":" + str(k.lport),
293 k.daddr + ":" + str(k.dport),
294 int(recv_bytes / 1024), int(send_bytes / 1024)))
Brendan Gregg60393ea2016-10-04 15:18:11 -0700295
Benjamin Poirier8e86b9e2017-07-27 16:07:06 -0700296 i += 1