blob: 9a79a64f0f2291f14af175c9167c092e1afa61a0 [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Brendan Gregg08c29812016-02-09 00:36:43 -08002# @lint-avoid-python-3-compatibility-imports
3#
4# filetop file reads and writes by process.
5# For Linux, uses BCC, eBPF.
6#
7# USAGE: filetop.py [-h] [-C] [-r MAXROWS] [interval] [count]
8#
9# This uses in-kernel eBPF maps to store per process summaries for efficiency.
10#
11# Copyright 2016 Netflix, Inc.
12# Licensed under the Apache License, Version 2.0 (the "License")
13#
14# 06-Feb-2016 Brendan Gregg Created this.
15
16from __future__ import print_function
17from bcc import BPF
18from time import sleep, strftime
19import argparse
Brendan Gregg08c29812016-02-09 00:36:43 -080020from subprocess import call
21
22# arguments
23examples = """examples:
24 ./filetop # file I/O top, 1 second refresh
25 ./filetop -C # don't clear the screen
26 ./filetop -p 181 # PID 181 only
27 ./filetop 5 # 5 second summaries
28 ./filetop 5 10 # 5 second summaries, 10 times only
29"""
30parser = argparse.ArgumentParser(
31 description="File reads and writes by process",
32 formatter_class=argparse.RawDescriptionHelpFormatter,
33 epilog=examples)
Mark Drayton74347312016-08-25 20:46:35 +010034parser.add_argument("-a", "--all-files", action="store_true",
35 help="include non-regular file types (sockets, FIFOs, etc)")
Brendan Gregg08c29812016-02-09 00:36:43 -080036parser.add_argument("-C", "--noclear", action="store_true",
37 help="don't clear the screen")
38parser.add_argument("-r", "--maxrows", default=20,
39 help="maximum rows to print, default 20")
Joel Fernandes (Google)c2b371d2019-03-08 11:39:42 -050040parser.add_argument("-s", "--sort", default="all",
41 choices=["all", "reads", "writes", "rbytes", "wbytes"],
Felix Geisendörfer3106a822019-12-12 16:41:09 +080042 help="sort column, default all")
Mark Drayton74347312016-08-25 20:46:35 +010043parser.add_argument("-p", "--pid", type=int, metavar="PID", dest="tgid",
Brendan Gregg08c29812016-02-09 00:36:43 -080044 help="trace this PID only")
45parser.add_argument("interval", nargs="?", default=1,
46 help="output interval, in seconds")
47parser.add_argument("count", nargs="?", default=99999999,
48 help="number of outputs")
Nathan Scottcf0792f2018-02-02 16:56:50 +110049parser.add_argument("--ebpf", action="store_true",
50 help=argparse.SUPPRESS)
Brendan Gregg08c29812016-02-09 00:36:43 -080051args = parser.parse_args()
52interval = int(args.interval)
53countdown = int(args.count)
54maxrows = int(args.maxrows)
55clear = not int(args.noclear)
56debug = 0
57
58# linux stats
59loadavg = "/proc/loadavg"
60
Brendan Gregg08c29812016-02-09 00:36:43 -080061# define BPF program
62bpf_text = """
63#include <uapi/linux/ptrace.h>
64#include <linux/blkdev.h>
65
Brendan Gregg08c29812016-02-09 00:36:43 -080066// the key for the output summary
67struct info_t {
Hengqi Chend5673472021-07-28 23:49:11 +080068 unsigned long inode;
69 dev_t dev;
Brendan Gregg08c29812016-02-09 00:36:43 -080070 u32 pid;
Mark Drayton74347312016-08-25 20:46:35 +010071 u32 name_len;
72 char comm[TASK_COMM_LEN];
73 // de->d_name.name may point to de->d_iname so limit len accordingly
74 char name[DNAME_INLINE_LEN];
Brendan Gregg08c29812016-02-09 00:36:43 -080075 char type;
76};
77
78// the value of the output summary
79struct val_t {
80 u64 reads;
81 u64 writes;
82 u64 rbytes;
83 u64 wbytes;
84};
85
86BPF_HASH(counts, struct info_t, struct val_t);
87
88static int do_entry(struct pt_regs *ctx, struct file *file,
89 char __user *buf, size_t count, int is_read)
90{
Mark Drayton74347312016-08-25 20:46:35 +010091 u32 tgid = bpf_get_current_pid_tgid() >> 32;
92 if (TGID_FILTER)
Brendan Gregg08c29812016-02-09 00:36:43 -080093 return 0;
94
Mark Drayton74347312016-08-25 20:46:35 +010095 u32 pid = bpf_get_current_pid_tgid();
96
Brendan Gregg08c29812016-02-09 00:36:43 -080097 // skip I/O lacking a filename
98 struct dentry *de = file->f_path.dentry;
Mark Drayton74347312016-08-25 20:46:35 +010099 int mode = file->f_inode->i_mode;
Paul Chaignonf86f7e82018-06-14 02:20:03 +0200100 struct qstr d_name = de->d_name;
101 if (d_name.len == 0 || TYPE_FILTER)
Brendan Gregg08c29812016-02-09 00:36:43 -0800102 return 0;
103
104 // store counts and sizes by pid & file
Hengqi Chend5673472021-07-28 23:49:11 +0800105 struct info_t info = {
106 .pid = pid,
107 .inode = file->f_inode->i_ino,
108 .dev = file->f_inode->i_rdev,
109 };
Mark Drayton74347312016-08-25 20:46:35 +0100110 bpf_get_current_comm(&info.comm, sizeof(info.comm));
Paul Chaignonf86f7e82018-06-14 02:20:03 +0200111 info.name_len = d_name.len;
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500112 bpf_probe_read_kernel(&info.name, sizeof(info.name), d_name.name);
Brendan Gregg08c29812016-02-09 00:36:43 -0800113 if (S_ISREG(mode)) {
114 info.type = 'R';
115 } else if (S_ISSOCK(mode)) {
116 info.type = 'S';
117 } else {
118 info.type = 'O';
119 }
120
121 struct val_t *valp, zero = {};
yonghong-song82f43022019-10-31 08:16:12 -0700122 valp = counts.lookup_or_try_init(&info, &zero);
Philip Gladstoneba64f032019-09-20 01:12:01 -0400123 if (valp) {
124 if (is_read) {
125 valp->reads++;
126 valp->rbytes += count;
127 } else {
128 valp->writes++;
129 valp->wbytes += count;
130 }
Brendan Gregg08c29812016-02-09 00:36:43 -0800131 }
132
133 return 0;
134}
135
136int trace_read_entry(struct pt_regs *ctx, struct file *file,
137 char __user *buf, size_t count)
138{
139 return do_entry(ctx, file, buf, count, 1);
140}
141
142int trace_write_entry(struct pt_regs *ctx, struct file *file,
143 char __user *buf, size_t count)
144{
145 return do_entry(ctx, file, buf, count, 0);
146}
147
148"""
Mark Drayton74347312016-08-25 20:46:35 +0100149if args.tgid:
150 bpf_text = bpf_text.replace('TGID_FILTER', 'tgid != %d' % args.tgid)
Brendan Gregg08c29812016-02-09 00:36:43 -0800151else:
Mark Drayton74347312016-08-25 20:46:35 +0100152 bpf_text = bpf_text.replace('TGID_FILTER', '0')
153if args.all_files:
154 bpf_text = bpf_text.replace('TYPE_FILTER', '0')
155else:
156 bpf_text = bpf_text.replace('TYPE_FILTER', '!S_ISREG(mode)')
157
Nathan Scottcf0792f2018-02-02 16:56:50 +1100158if debug or args.ebpf:
Brendan Gregg08c29812016-02-09 00:36:43 -0800159 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100160 if args.ebpf:
161 exit()
Brendan Gregg08c29812016-02-09 00:36:43 -0800162
163# initialize BPF
164b = BPF(text=bpf_text)
Jazel Canseco6d818b62018-04-13 11:39:56 -0700165b.attach_kprobe(event="vfs_read", fn_name="trace_read_entry")
166b.attach_kprobe(event="vfs_write", fn_name="trace_write_entry")
Mark Drayton74347312016-08-25 20:46:35 +0100167
168DNAME_INLINE_LEN = 32 # linux/dcache.h
Brendan Gregg08c29812016-02-09 00:36:43 -0800169
170print('Tracing... Output every %d secs. Hit Ctrl-C to end' % interval)
171
Joel Fernandes (Google)c2b371d2019-03-08 11:39:42 -0500172def sort_fn(counts):
173 if args.sort == "all":
174 return (counts[1].rbytes + counts[1].wbytes + counts[1].reads + counts[1].writes)
175 else:
176 return getattr(counts[1], args.sort)
177
Brendan Gregg08c29812016-02-09 00:36:43 -0800178# output
179exiting = 0
180while 1:
181 try:
182 sleep(interval)
183 except KeyboardInterrupt:
184 exiting = 1
185
186 # header
187 if clear:
188 call("clear")
189 else:
190 print()
191 with open(loadavg) as stats:
192 print("%-8s loadavg: %s" % (strftime("%H:%M:%S"), stats.read()))
Hengqi Chend5673472021-07-28 23:49:11 +0800193 print("%-7s %-16s %-6s %-6s %-7s %-7s %1s %s" % ("TID", "COMM",
Brendan Gregg08c29812016-02-09 00:36:43 -0800194 "READS", "WRITES", "R_Kb", "W_Kb", "T", "FILE"))
195
Mark Drayton74347312016-08-25 20:46:35 +0100196 # by-TID output
Brendan Gregg08c29812016-02-09 00:36:43 -0800197 counts = b.get_table("counts")
198 line = 0
199 for k, v in reversed(sorted(counts.items(),
Joel Fernandes (Google)c2b371d2019-03-08 11:39:42 -0500200 key=sort_fn)):
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200201 name = k.name.decode('utf-8', 'replace')
Mark Drayton74347312016-08-25 20:46:35 +0100202 if k.name_len > DNAME_INLINE_LEN:
203 name = name[:-3] + "..."
Brendan Gregg08c29812016-02-09 00:36:43 -0800204
205 # print line
Hengqi Chend5673472021-07-28 23:49:11 +0800206 print("%-7d %-16s %-6d %-6d %-7d %-7d %1s %s" % (k.pid,
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200207 k.comm.decode('utf-8', 'replace'), v.reads, v.writes,
208 v.rbytes / 1024, v.wbytes / 1024,
209 k.type.decode('utf-8', 'replace'), name))
Brendan Gregg08c29812016-02-09 00:36:43 -0800210
211 line += 1
212 if line >= maxrows:
213 break
214 counts.clear()
215
216 countdown -= 1
217 if exiting or countdown == 0:
218 print("Detaching...")
219 exit()