blob: 03b05e0ab7e59e38f1a2925f637f0d2c5389fa7f [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08002# @lint-avoid-python-3-compatibility-imports
Brendan Gregg052f89c2015-10-13 15:35:58 -07003#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08004# tcpaccept Trace TCP accept()s.
5# For Linux, uses BCC, eBPF. Embedded C.
Brendan Gregg052f89c2015-10-13 15:35:58 -07006#
Xiaozhou Liu701bd732019-03-08 13:46:28 +08007# USAGE: tcpaccept [-h] [-T] [-t] [-p PID] [-P PORTS]
Brendan Gregg052f89c2015-10-13 15:35:58 -07008#
9# This uses dynamic tracing of the kernel inet_csk_accept() socket function
10# (from tcp_prot.accept), and will need to be modified to match kernel changes.
Brendan Gregg052f89c2015-10-13 15:35:58 -070011#
Brendan Gregg052f89c2015-10-13 15:35:58 -070012# Copyright (c) 2015 Brendan Gregg.
13# Licensed under the Apache License, Version 2.0 (the "License")
14#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080015# 13-Oct-2015 Brendan Gregg Created this.
Brendan Gregg24825522016-02-14 16:32:29 -080016# 14-Feb-2016 " " Switch to bpf_perf_output.
Brendan Gregg052f89c2015-10-13 15:35:58 -070017
18from __future__ import print_function
19from bcc import BPF
Mark Drayton11de2982016-06-26 21:14:44 +010020from socket import inet_ntop, AF_INET, AF_INET6
21from struct import pack
Brendan Gregg052f89c2015-10-13 15:35:58 -070022import argparse
japrocaed9b1e2019-01-04 20:21:46 +030023from bcc.utils import printb
Xiaozhou Liu701bd732019-03-08 13:46:28 +080024from time import strftime
Brendan Gregg052f89c2015-10-13 15:35:58 -070025
26# arguments
27examples = """examples:
Brendan Gregg000a4e62015-10-13 15:41:46 -070028 ./tcpaccept # trace all TCP accept()s
Brendan Gregg052f89c2015-10-13 15:35:58 -070029 ./tcpaccept -t # include timestamps
Xiaozhou Liu701bd732019-03-08 13:46:28 +080030 ./tcpaccept -P 80,81 # only trace port 80 and 81
Brendan Gregg052f89c2015-10-13 15:35:58 -070031 ./tcpaccept -p 181 # only trace PID 181
Alban Crequy1ce868f2020-02-19 17:07:41 +010032 ./tcpaccept --cgroupmap ./mappath # only trace cgroups in this BPF map
Brendan Gregg052f89c2015-10-13 15:35:58 -070033"""
34parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080035 description="Trace TCP accepts",
36 formatter_class=argparse.RawDescriptionHelpFormatter,
37 epilog=examples)
Xiaozhou Liu701bd732019-03-08 13:46:28 +080038parser.add_argument("-T", "--time", action="store_true",
39 help="include time column on output (HH:MM:SS)")
Brendan Gregg052f89c2015-10-13 15:35:58 -070040parser.add_argument("-t", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080041 help="include timestamp on output")
Brendan Gregg052f89c2015-10-13 15:35:58 -070042parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080043 help="trace this PID only")
Xiaozhou Liu701bd732019-03-08 13:46:28 +080044parser.add_argument("-P", "--port",
45 help="comma-separated list of local ports to trace")
Alban Crequy1ce868f2020-02-19 17:07:41 +010046parser.add_argument("--cgroupmap",
47 help="trace cgroups in this BPF map only")
Nathan Scottcf0792f2018-02-02 16:56:50 +110048parser.add_argument("--ebpf", action="store_true",
49 help=argparse.SUPPRESS)
Brendan Gregg052f89c2015-10-13 15:35:58 -070050args = parser.parse_args()
51debug = 0
52
53# define BPF program
54bpf_text = """
55#include <uapi/linux/ptrace.h>
56#include <net/sock.h>
57#include <bcc/proto.h>
58
Brendan Gregg24825522016-02-14 16:32:29 -080059// separate data structs for ipv4 and ipv6
60struct ipv4_data_t {
Brendan Gregg24825522016-02-14 16:32:29 -080061 u64 ts_us;
Joe Yin36ce1122018-08-17 06:04:00 +080062 u32 pid;
Joe Yin365eade2018-06-21 13:41:03 +080063 u32 saddr;
64 u32 daddr;
Mark Drayton11de2982016-06-26 21:14:44 +010065 u64 ip;
Joe Yin36ce1122018-08-17 06:04:00 +080066 u16 lport;
Xiaozhou Liu701bd732019-03-08 13:46:28 +080067 u16 dport;
Brendan Gregg24825522016-02-14 16:32:29 -080068 char task[TASK_COMM_LEN];
69};
70BPF_PERF_OUTPUT(ipv4_events);
71
72struct ipv6_data_t {
Brendan Gregg24825522016-02-14 16:32:29 -080073 u64 ts_us;
Joe Yin36ce1122018-08-17 06:04:00 +080074 u32 pid;
Mark Drayton11de2982016-06-26 21:14:44 +010075 unsigned __int128 saddr;
76 unsigned __int128 daddr;
Brendan Gregg24825522016-02-14 16:32:29 -080077 u64 ip;
Joe Yin36ce1122018-08-17 06:04:00 +080078 u16 lport;
Xiaozhou Liu701bd732019-03-08 13:46:28 +080079 u16 dport;
Brendan Gregg24825522016-02-14 16:32:29 -080080 char task[TASK_COMM_LEN];
81};
82BPF_PERF_OUTPUT(ipv6_events);
Alban Crequy1ce868f2020-02-19 17:07:41 +010083
84#if CGROUPSET
85BPF_TABLE_PINNED("hash", u64, u64, cgroupset, 1024, "CGROUPPATH");
86#endif
87
Joe Yin365eade2018-06-21 13:41:03 +080088"""
Brendan Gregg24825522016-02-14 16:32:29 -080089
Joe Yin365eade2018-06-21 13:41:03 +080090#
Xiaozhou Liufd737452019-04-10 23:35:16 +080091# The following code uses kprobes to instrument inet_csk_accept().
92# On Linux 4.16 and later, we could use sock:inet_sock_set_state
Michael Prokopc14d02a2020-01-09 02:29:18 +010093# tracepoint for efficiency, but it may output wrong PIDs. This is
Xiaozhou Liufd737452019-04-10 23:35:16 +080094# because sock:inet_sock_set_state may run outside of process context.
95# Hence, we stick to kprobes until we find a proper solution.
Joe Yin365eade2018-06-21 13:41:03 +080096#
97bpf_text_kprobe = """
Brendan Gregg052f89c2015-10-13 15:35:58 -070098int kretprobe__inet_csk_accept(struct pt_regs *ctx)
99{
Alban Crequy1ce868f2020-02-19 17:07:41 +0100100#if CGROUPSET
101 u64 cgroupid = bpf_get_current_cgroup_id();
102 if (cgroupset.lookup(&cgroupid) == NULL) {
103 return 0;
104 }
105#endif
106
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530107 struct sock *newsk = (struct sock *)PT_REGS_RC(ctx);
Brendan Gregg8cd3efd2019-04-07 12:32:53 -0700108 u32 pid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg052f89c2015-10-13 15:35:58 -0700109
detailyang54044d52019-01-10 00:43:39 +0800110 ##FILTER_PID##
111
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800112 if (newsk == NULL)
113 return 0;
Brendan Gregg052f89c2015-10-13 15:35:58 -0700114
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800115 // check this is TCP
116 u8 protocol = 0;
117 // workaround for reading the sk_protocol bitfield:
Joe Yin116bb402018-06-18 23:34:52 +0800118
119 // Following comments add by Joe Yin:
120 // Unfortunately,it can not work since Linux 4.10,
121 // because the sk_wmem_queued is not following the bitfield of sk_protocol.
122 // And the following member is sk_gso_max_segs.
123 // So, we can use this:
124 // bpf_probe_read(&protocol, 1, (void *)((u64)&newsk->sk_gso_max_segs) - 3);
125 // In order to diff the pre-4.10 and 4.10+ ,introduce the variables gso_max_segs_offset,sk_lingertime,
126 // sk_lingertime is closed to the gso_max_segs_offset,and
127 // the offset between the two members is 4
128
129 int gso_max_segs_offset = offsetof(struct sock, sk_gso_max_segs);
130 int sk_lingertime_offset = offsetof(struct sock, sk_lingertime);
131
132 if (sk_lingertime_offset - gso_max_segs_offset == 4)
133 // 4.10+ with little endian
134#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
Paul Chaignon8d78edd2018-06-29 07:47:44 +0200135 protocol = *(u8 *)((u64)&newsk->sk_gso_max_segs - 3);
Joe Yin116bb402018-06-18 23:34:52 +0800136 else
137 // pre-4.10 with little endian
Paul Chaignon8d78edd2018-06-29 07:47:44 +0200138 protocol = *(u8 *)((u64)&newsk->sk_wmem_queued - 3);
Joe Yin116bb402018-06-18 23:34:52 +0800139#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
140 // 4.10+ with big endian
Paul Chaignon8d78edd2018-06-29 07:47:44 +0200141 protocol = *(u8 *)((u64)&newsk->sk_gso_max_segs - 1);
Joe Yin116bb402018-06-18 23:34:52 +0800142 else
143 // pre-4.10 with big endian
Paul Chaignon8d78edd2018-06-29 07:47:44 +0200144 protocol = *(u8 *)((u64)&newsk->sk_wmem_queued - 1);
Joe Yin116bb402018-06-18 23:34:52 +0800145#else
146# error "Fix your compiler's __BYTE_ORDER__?!"
147#endif
148
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800149 if (protocol != IPPROTO_TCP)
150 return 0;
Brendan Gregg10e1b142015-10-13 16:35:25 -0700151
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800152 // pull in details
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800153 u16 family = 0, lport = 0, dport;
Paul Chaignona9f96c02018-06-15 00:27:08 +0200154 family = newsk->__sk_common.skc_family;
155 lport = newsk->__sk_common.skc_num;
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800156 dport = newsk->__sk_common.skc_dport;
157 dport = ntohs(dport);
158
159 ##FILTER_PORT##
Brendan Gregg052f89c2015-10-13 15:35:58 -0700160
Brendan Gregg24825522016-02-14 16:32:29 -0800161 if (family == AF_INET) {
162 struct ipv4_data_t data4 = {.pid = pid, .ip = 4};
163 data4.ts_us = bpf_ktime_get_ns() / 1000;
Paul Chaignona9f96c02018-06-15 00:27:08 +0200164 data4.saddr = newsk->__sk_common.skc_rcv_saddr;
165 data4.daddr = newsk->__sk_common.skc_daddr;
Brendan Gregg24825522016-02-14 16:32:29 -0800166 data4.lport = lport;
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800167 data4.dport = dport;
Brendan Gregg24825522016-02-14 16:32:29 -0800168 bpf_get_current_comm(&data4.task, sizeof(data4.task));
169 ipv4_events.perf_submit(ctx, &data4, sizeof(data4));
170
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800171 } else if (family == AF_INET6) {
Brendan Gregg24825522016-02-14 16:32:29 -0800172 struct ipv6_data_t data6 = {.pid = pid, .ip = 6};
173 data6.ts_us = bpf_ktime_get_ns() / 1000;
Mark Drayton11de2982016-06-26 21:14:44 +0100174 bpf_probe_read(&data6.saddr, sizeof(data6.saddr),
175 &newsk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
176 bpf_probe_read(&data6.daddr, sizeof(data6.daddr),
177 &newsk->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
Brendan Gregg24825522016-02-14 16:32:29 -0800178 data6.lport = lport;
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800179 data6.dport = dport;
Brendan Gregg24825522016-02-14 16:32:29 -0800180 bpf_get_current_comm(&data6.task, sizeof(data6.task));
181 ipv6_events.perf_submit(ctx, &data6, sizeof(data6));
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800182 }
183 // else drop
Brendan Gregg052f89c2015-10-13 15:35:58 -0700184
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800185 return 0;
Brendan Gregg052f89c2015-10-13 15:35:58 -0700186}
187"""
188
Xiaozhou Liufd737452019-04-10 23:35:16 +0800189bpf_text += bpf_text_kprobe
Joe Yin365eade2018-06-21 13:41:03 +0800190
Brendan Gregg052f89c2015-10-13 15:35:58 -0700191# code substitutions
192if args.pid:
detailyang54044d52019-01-10 00:43:39 +0800193 bpf_text = bpf_text.replace('##FILTER_PID##',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800194 'if (pid != %s) { return 0; }' % args.pid)
Brendan Gregg052f89c2015-10-13 15:35:58 -0700195else:
detailyang54044d52019-01-10 00:43:39 +0800196 bpf_text = bpf_text.replace('##FILTER_PID##', '')
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800197if args.port:
198 lports = [int(lport) for lport in args.port.split(',')]
199 lports_if = ' && '.join(['lport != %d' % lport for lport in lports])
200 bpf_text = bpf_text.replace('##FILTER_PORT##',
201 'if (%s) { return 0; }' % lports_if)
Alban Crequy1ce868f2020-02-19 17:07:41 +0100202if args.cgroupmap:
203 bpf_text = bpf_text.replace('CGROUPSET', '1')
204 bpf_text = bpf_text.replace('CGROUPPATH', args.cgroupmap)
205else:
206 bpf_text = bpf_text.replace('CGROUPSET', '0')
Nathan Scottcf0792f2018-02-02 16:56:50 +1100207if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800208 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100209 if args.ebpf:
210 exit()
Brendan Gregg052f89c2015-10-13 15:35:58 -0700211
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800212bpf_text = bpf_text.replace('##FILTER_PORT##', '')
213
Brendan Gregg24825522016-02-14 16:32:29 -0800214# process event
215def print_ipv4_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +0800216 event = b["ipv4_events"].event(data)
Mark Drayton11de2982016-06-26 21:14:44 +0100217 global start_ts
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800218 if args.time:
Gary Lin6c793312019-04-18 15:17:56 +0800219 printb(b"%-9s" % strftime("%H:%M:%S").encode('ascii'), nl="")
Brendan Gregg24825522016-02-14 16:32:29 -0800220 if args.timestamp:
221 if start_ts == 0:
222 start_ts = event.ts_us
Gary Lin6c793312019-04-18 15:17:56 +0800223 printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800224 printb(b"%-7d %-12.12s %-2d %-16s %-5d %-16s %-5d" % (event.pid,
Yonghong Songebe19512019-01-10 14:54:16 -0800225 event.task, event.ip,
226 inet_ntop(AF_INET, pack("I", event.daddr)).encode(),
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800227 event.dport,
Yonghong Songebe19512019-01-10 14:54:16 -0800228 inet_ntop(AF_INET, pack("I", event.saddr)).encode(),
229 event.lport))
Mark Drayton11de2982016-06-26 21:14:44 +0100230
Brendan Gregg24825522016-02-14 16:32:29 -0800231def print_ipv6_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +0800232 event = b["ipv6_events"].event(data)
Mark Drayton11de2982016-06-26 21:14:44 +0100233 global start_ts
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800234 if args.time:
Gary Lin6c793312019-04-18 15:17:56 +0800235 printb(b"%-9s" % strftime("%H:%M:%S").encode('ascii'), nl="")
Brendan Gregg24825522016-02-14 16:32:29 -0800236 if args.timestamp:
237 if start_ts == 0:
238 start_ts = event.ts_us
Gary Lin6c793312019-04-18 15:17:56 +0800239 printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800240 printb(b"%-7d %-12.12s %-2d %-16s %-5d %-16s %-5d" % (event.pid,
Yonghong Songebe19512019-01-10 14:54:16 -0800241 event.task, event.ip,
242 inet_ntop(AF_INET6, event.daddr).encode(),
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800243 event.dport,
Yonghong Songebe19512019-01-10 14:54:16 -0800244 inet_ntop(AF_INET6, event.saddr).encode(),
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200245 event.lport))
Brendan Gregg24825522016-02-14 16:32:29 -0800246
Brendan Gregg052f89c2015-10-13 15:35:58 -0700247# initialize BPF
248b = BPF(text=bpf_text)
249
250# header
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800251if args.time:
252 print("%-9s" % ("TIME"), end="")
Brendan Gregg052f89c2015-10-13 15:35:58 -0700253if args.timestamp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800254 print("%-9s" % ("TIME(s)"), end="")
Xiaozhou Liu701bd732019-03-08 13:46:28 +0800255print("%-7s %-12s %-2s %-16s %-5s %-16s %-5s" % ("PID", "COMM", "IP", "RADDR",
256 "RPORT", "LADDR", "LPORT"))
Brendan Gregg052f89c2015-10-13 15:35:58 -0700257
258start_ts = 0
259
Brendan Gregg24825522016-02-14 16:32:29 -0800260# read events
261b["ipv4_events"].open_perf_buffer(print_ipv4_event)
262b["ipv6_events"].open_perf_buffer(print_ipv6_event)
Brendan Gregg052f89c2015-10-13 15:35:58 -0700263while 1:
Jerome Marchand51671272018-12-19 01:57:24 +0100264 try:
265 b.perf_buffer_poll()
266 except KeyboardInterrupt:
267 exit()