Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2019
1,048
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.82 KB | None | 0 0
  1. #!/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.  
  27. from __future__ import print_function
  28. from bcc import BPF
  29. import argparse
  30. from socket import inet_ntop, AF_INET, AF_INET6
  31. from struct import pack
  32. from time import sleep, strftime
  33. from subprocess import call
  34. from collections import namedtuple, defaultdict
  35.  
  36. # arguments
  37. def range_check(string):
  38. value = int(string)
  39. if value < 1:
  40. msg = "value must be stricly positive, got %d" % (value,)
  41. raise argparse.ArgumentTypeError(msg)
  42. return value
  43.  
  44. examples = """examples:
  45. ./tcptop # trace TCP send/recv by host
  46. ./tcptop -C # don't clear the screen
  47. ./tcptop -p 181 # only trace PID 181
  48. """
  49. parser = argparse.ArgumentParser(
  50. description="Summarize TCP send/recv throughput by host",
  51. formatter_class=argparse.RawDescriptionHelpFormatter,
  52. epilog=examples)
  53. parser.add_argument("-C", "--noclear", action="store_true",
  54. help="don't clear the screen")
  55. parser.add_argument("-S", "--nosummary", action="store_true",
  56. help="skip system summary line")
  57. parser.add_argument("-p", "--pid",
  58. help="trace this PID only")
  59. parser.add_argument("-t", "--threads", action="store_false",
  60. help="output by threads")
  61. parser.add_argument("interval", nargs="?", default=1, type=range_check,
  62. help="output interval, in seconds (default 1)")
  63. parser.add_argument("count", nargs="?", default=-1, type=range_check,
  64. help="number of outputs")
  65. parser.add_argument("--ebpf", action="store_true",
  66. help=argparse.SUPPRESS)
  67. args = parser.parse_args()
  68. debug = 0
  69.  
  70. # linux stats
  71. loadavg = "/proc/loadavg"
  72.  
  73. # define BPF program
  74. bpf_text = """
  75. #include <uapi/linux/ptrace.h>
  76. #include <net/sock.h>
  77. #include <bcc/proto.h>
  78.  
  79. struct ipv4_key_t {
  80. u32 pid;
  81. u32 tid;
  82. u32 saddr;
  83. u32 daddr;
  84. u16 lport;
  85. u16 dport;
  86. };
  87. BPF_HASH(ipv4_send_bytes, struct ipv4_key_t);
  88. BPF_HASH(ipv4_recv_bytes, struct ipv4_key_t);
  89. BPF_HASH(ipv4_send_count, struct ipv4_key_t);
  90. BPF_HASH(ipv4_recv_count, struct ipv4_key_t);
  91.  
  92. struct ipv6_key_t {
  93. u32 pid;
  94. u32 tid;
  95. unsigned __int128 saddr;
  96. unsigned __int128 daddr;
  97. u16 lport;
  98. u16 dport;
  99. };
  100. BPF_HASH(ipv6_send_bytes, struct ipv6_key_t);
  101. BPF_HASH(ipv6_recv_bytes, struct ipv6_key_t);
  102. BPF_HASH(ipv6_send_count, struct ipv6_key_t);
  103. BPF_HASH(ipv6_recv_count, struct ipv6_key_t);
  104.  
  105. int kprobe__tcp_sendmsg(struct pt_regs *ctx, struct sock *sk,
  106. struct msghdr *msg, size_t size)
  107. {
  108. u32 pid = bpf_get_current_pid_tgid() >> 32;
  109. u32 tid = bpf_get_current_pid_tgid();
  110. FILTER
  111. u16 dport = 0, family = sk->__sk_common.skc_family;
  112.  
  113. if (family == AF_INET) {
  114. struct ipv4_key_t ipv4_key = {.pid = pid, .tid = tid};
  115. ipv4_key.saddr = sk->__sk_common.skc_rcv_saddr;
  116. ipv4_key.daddr = sk->__sk_common.skc_daddr;
  117. ipv4_key.lport = sk->__sk_common.skc_num;
  118. dport = sk->__sk_common.skc_dport;
  119. ipv4_key.dport = ntohs(dport);
  120. ipv4_send_bytes.increment(ipv4_key, size);
  121. ipv4_send_count.increment(ipv4_key, 1);
  122.  
  123. } else if (family == AF_INET6) {
  124. struct ipv6_key_t ipv6_key = {.pid = pid, .tid = tid};
  125. __builtin_memcpy(&ipv6_key.saddr,
  126. sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32, sizeof(ipv6_key.saddr));
  127. __builtin_memcpy(&ipv6_key.daddr,
  128. sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32, sizeof(ipv6_key.daddr));
  129. ipv6_key.lport = sk->__sk_common.skc_num;
  130. dport = sk->__sk_common.skc_dport;
  131. ipv6_key.dport = ntohs(dport);
  132. ipv6_send_bytes.increment(ipv6_key, size);
  133. ipv6_send_count.increment(ipv6_key, 1);
  134. }
  135. // else drop
  136.  
  137. return 0;
  138. }
  139.  
  140. /*
  141. * tcp_recvmsg() would be obvious to trace, but is less suitable because:
  142. * - we'd need to trace both entry and return, to have both sock and size
  143. * - misses tcp_read_sock() traffic
  144. * we'd much prefer tracepoints once they are available.
  145. */
  146. int kprobe__tcp_cleanup_rbuf(struct pt_regs *ctx, struct sock *sk, int copied)
  147. {
  148. u32 pid = bpf_get_current_pid_tgid() >> 32;
  149. u32 tid = bpf_get_current_pid_tgid();
  150.  
  151. FILTER
  152. u16 dport = 0, family = sk->__sk_common.skc_family;
  153. u64 *val, zero = 0;
  154.  
  155. if (copied <= 0)
  156. return 0;
  157.  
  158. if (family == AF_INET) {
  159. struct ipv4_key_t ipv4_key = {.pid = pid, .tid = tid};
  160. ipv4_key.saddr = sk->__sk_common.skc_rcv_saddr;
  161. ipv4_key.daddr = sk->__sk_common.skc_daddr;
  162. ipv4_key.lport = sk->__sk_common.skc_num;
  163. dport = sk->__sk_common.skc_dport;
  164. ipv4_key.dport = ntohs(dport);
  165. ipv4_recv_bytes.increment(ipv4_key, copied);
  166. ipv4_recv_count.increment(ipv4_key, 1);
  167.  
  168. } else if (family == AF_INET6) {
  169. struct ipv6_key_t ipv6_key = {.pid = pid, .tid = tid};
  170. __builtin_memcpy(&ipv6_key.saddr,
  171. sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32, sizeof(ipv6_key.saddr));
  172. __builtin_memcpy(&ipv6_key.daddr,
  173. sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32, sizeof(ipv6_key.daddr));
  174. ipv6_key.lport = sk->__sk_common.skc_num;
  175. dport = sk->__sk_common.skc_dport;
  176. ipv6_key.dport = ntohs(dport);
  177. ipv6_recv_bytes.increment(ipv6_key, copied);
  178. ipv6_recv_count.increment(ipv6_key, 1);
  179. }
  180. // else drop
  181.  
  182. return 0;
  183. }
  184. """
  185.  
  186. # code substitutions
  187. if args.pid:
  188. bpf_text = bpf_text.replace('FILTER',
  189. 'if (pid != %s) { return 0; }' % args.pid)
  190. else:
  191. bpf_text = bpf_text.replace('FILTER', '')
  192. if debug or args.ebpf:
  193. print(bpf_text)
  194. if args.ebpf:
  195. exit()
  196.  
  197. TCPSessionKey = namedtuple('TCPSession', ['pid', 'laddr', 'lport', 'daddr', 'dport'])
  198.  
  199. def pid_to_comm(pid):
  200. try:
  201. comm = open("/proc/%d/comm" % pid, "r").read().rstrip()
  202. return comm
  203. except IOError:
  204. return str(pid)
  205.  
  206. def get_ipv4_session_key(k):
  207. pid = k.pid
  208. if not args.threads:
  209. pid = k.tid
  210.  
  211. return TCPSessionKey(pid=pid,
  212. laddr=inet_ntop(AF_INET, pack("I", k.saddr)),
  213. lport=k.lport,
  214. daddr=inet_ntop(AF_INET, pack("I", k.daddr)),
  215. dport=k.dport)
  216.  
  217. def get_ipv6_session_key(k):
  218. pid = k.pid
  219. if not args.threads:
  220. pid = k.tid
  221.  
  222. return TCPSessionKey(pid=pid,
  223. laddr=inet_ntop(AF_INET6, k.saddr),
  224. lport=k.lport,
  225. daddr=inet_ntop(AF_INET6, k.daddr),
  226. dport=k.dport)
  227.  
  228. # initialize BPF
  229. b = BPF(text=bpf_text)
  230.  
  231. ipv4_send_bytes = b["ipv4_send_bytes"]
  232. ipv4_recv_bytes = b["ipv4_recv_bytes"]
  233. ipv6_send_bytes = b["ipv6_send_bytes"]
  234. ipv6_recv_bytes = b["ipv6_recv_bytes"]
  235.  
  236. ipv4_send_count = b["ipv4_send_count"]
  237. ipv4_recv_count = b["ipv4_recv_count"]
  238. ipv6_send_count = b["ipv6_send_count"]
  239. ipv6_recv_count = b["ipv6_recv_count"]
  240.  
  241. print('Tracing... Output every %s secs. Hit Ctrl-C to end' % args.interval)
  242.  
  243. # output
  244. i = 0
  245. exiting = False
  246. while i != args.count and not exiting:
  247. try:
  248. sleep(args.interval)
  249. except KeyboardInterrupt:
  250. exiting = True
  251.  
  252. # header
  253. if args.noclear:
  254. print()
  255. else:
  256. call("clear")
  257. if not args.nosummary:
  258. with open(loadavg) as stats:
  259. print("%-8s loadavg: %s" % (strftime("%H:%M:%S"), stats.read()))
  260.  
  261. # IPv4: build dict of all seen keys
  262. ipv4_throughput = defaultdict(lambda: [0, 0, 0, 0])
  263. for k, v in ipv4_send_bytes.items():
  264. key = get_ipv4_session_key(k)
  265. ipv4_throughput[key][0] = v.value
  266. ipv4_send_bytes.clear()
  267.  
  268. for k, v in ipv4_recv_bytes.items():
  269. key = get_ipv4_session_key(k)
  270. ipv4_throughput[key][1] = v.value
  271. ipv4_recv_bytes.clear()
  272.  
  273. for k, v in ipv4_send_count.items():
  274. key = get_ipv4_session_key(k)
  275. ipv4_throughput[key][2] = v.value
  276. ipv4_send_count.clear()
  277.  
  278. for k, v in ipv4_recv_count.items():
  279. key = get_ipv4_session_key(k)
  280. ipv4_throughput[key][3] = v.value
  281. ipv4_recv_count.clear()
  282.  
  283. if ipv4_throughput:
  284. print("%-6s %-16s %-21s %-21s %6s %6s %6s %6s" % ("PID", "COMM",
  285. "LADDR", "RADDR", "RX_KB", "TX_KB", "RX_NUM", "TX_NUM"))
  286.  
  287. # output
  288. for k, (send_bytes, recv_bytes, send_count, recv_count) in sorted(ipv4_throughput.items(),
  289. key=lambda kv: sum(kv[1]),
  290. reverse=True):
  291. print("%-6d %-16.16s %-21s %-21s %6d %6d %6d %6d" % (k.pid,
  292. pid_to_comm(k.pid),
  293. k.laddr + ":" + str(k.lport),
  294. k.daddr + ":" + str(k.dport),
  295. int(recv_bytes / 1024), int(send_bytes / 1024),
  296. recv_count, send_count))
  297.  
  298. # IPv6: build dict of all seen keys
  299. ipv6_throughput = defaultdict(lambda: [0, 0, 0, 0])
  300. for k, v in ipv6_send_bytes.items():
  301. key = get_ipv6_session_key(k)
  302. ipv6_throughput[key][0] = v.value
  303. ipv6_send_bytes.clear()
  304.  
  305. for k, v in ipv6_recv_bytes.items():
  306. key = get_ipv6_session_key(k)
  307. ipv6_throughput[key][1] = v.value
  308. ipv6_recv_bytes.clear()
  309.  
  310. for k, v in ipv6_send_count.items():
  311. key = get_ipv6_session_key(k)
  312. ipv6_throughput[key][2] = v.value
  313. ipv6_send_count.clear()
  314.  
  315. for k, v in ipv6_recv_count.items():
  316. key = get_ipv6_session_key(k)
  317. ipv6_throughput[key][3] = v.value
  318. ipv6_recv_count.clear()
  319.  
  320. if ipv6_throughput:
  321. # more than 80 chars, sadly.
  322. print("\n%-6s %-16s %-32s %-32s %6s %6s %6s %6s" % ("PID", "COMM",
  323. "LADDR6", "RADDR6", "RX_KB", "TX_KB", "RX_NUM", "TX_NUM"))
  324.  
  325. # output
  326. for k, (send_bytes, recv_bytes, send_count, recv_count) in sorted(ipv6_throughput.items(),
  327. key=lambda kv: sum(kv[1]),
  328. reverse=True):
  329. print("%-6d %-16.16s %-32s %-32s %6d %6d %6d %6d" % (k.pid,
  330. pid_to_comm(k.pid),
  331. k.laddr + ":" + str(k.lport),
  332. k.daddr + ":" + str(k.dport),
  333. int(recv_bytes / 1024), int(send_bytes / 1024),
  334. recv_count, send_count))
  335.  
  336. i += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement