blob: 17ead81713bee57774cefb85a0056daa0583d62d [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 {
68 u32 pid;
Mark Drayton74347312016-08-25 20:46:35 +010069 u32 name_len;
70 char comm[TASK_COMM_LEN];
71 // de->d_name.name may point to de->d_iname so limit len accordingly
72 char name[DNAME_INLINE_LEN];
Brendan Gregg08c29812016-02-09 00:36:43 -080073 char type;
74};
75
76// the value of the output summary
77struct val_t {
78 u64 reads;
79 u64 writes;
80 u64 rbytes;
81 u64 wbytes;
82};
83
84BPF_HASH(counts, struct info_t, struct val_t);
85
86static int do_entry(struct pt_regs *ctx, struct file *file,
87 char __user *buf, size_t count, int is_read)
88{
Mark Drayton74347312016-08-25 20:46:35 +010089 u32 tgid = bpf_get_current_pid_tgid() >> 32;
90 if (TGID_FILTER)
Brendan Gregg08c29812016-02-09 00:36:43 -080091 return 0;
92
Mark Drayton74347312016-08-25 20:46:35 +010093 u32 pid = bpf_get_current_pid_tgid();
94
Brendan Gregg08c29812016-02-09 00:36:43 -080095 // skip I/O lacking a filename
96 struct dentry *de = file->f_path.dentry;
Mark Drayton74347312016-08-25 20:46:35 +010097 int mode = file->f_inode->i_mode;
Paul Chaignonf86f7e82018-06-14 02:20:03 +020098 struct qstr d_name = de->d_name;
99 if (d_name.len == 0 || TYPE_FILTER)
Brendan Gregg08c29812016-02-09 00:36:43 -0800100 return 0;
101
102 // store counts and sizes by pid & file
103 struct info_t info = {.pid = pid};
Mark Drayton74347312016-08-25 20:46:35 +0100104 bpf_get_current_comm(&info.comm, sizeof(info.comm));
Paul Chaignonf86f7e82018-06-14 02:20:03 +0200105 info.name_len = d_name.len;
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500106 bpf_probe_read_kernel(&info.name, sizeof(info.name), d_name.name);
Brendan Gregg08c29812016-02-09 00:36:43 -0800107 if (S_ISREG(mode)) {
108 info.type = 'R';
109 } else if (S_ISSOCK(mode)) {
110 info.type = 'S';
111 } else {
112 info.type = 'O';
113 }
114
115 struct val_t *valp, zero = {};
yonghong-song82f43022019-10-31 08:16:12 -0700116 valp = counts.lookup_or_try_init(&info, &zero);
Philip Gladstoneba64f032019-09-20 01:12:01 -0400117 if (valp) {
118 if (is_read) {
119 valp->reads++;
120 valp->rbytes += count;
121 } else {
122 valp->writes++;
123 valp->wbytes += count;
124 }
Brendan Gregg08c29812016-02-09 00:36:43 -0800125 }
126
127 return 0;
128}
129
130int trace_read_entry(struct pt_regs *ctx, struct file *file,
131 char __user *buf, size_t count)
132{
133 return do_entry(ctx, file, buf, count, 1);
134}
135
136int trace_write_entry(struct pt_regs *ctx, struct file *file,
137 char __user *buf, size_t count)
138{
139 return do_entry(ctx, file, buf, count, 0);
140}
141
142"""
Mark Drayton74347312016-08-25 20:46:35 +0100143if args.tgid:
144 bpf_text = bpf_text.replace('TGID_FILTER', 'tgid != %d' % args.tgid)
Brendan Gregg08c29812016-02-09 00:36:43 -0800145else:
Mark Drayton74347312016-08-25 20:46:35 +0100146 bpf_text = bpf_text.replace('TGID_FILTER', '0')
147if args.all_files:
148 bpf_text = bpf_text.replace('TYPE_FILTER', '0')
149else:
150 bpf_text = bpf_text.replace('TYPE_FILTER', '!S_ISREG(mode)')
151
Nathan Scottcf0792f2018-02-02 16:56:50 +1100152if debug or args.ebpf:
Brendan Gregg08c29812016-02-09 00:36:43 -0800153 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100154 if args.ebpf:
155 exit()
Brendan Gregg08c29812016-02-09 00:36:43 -0800156
157# initialize BPF
158b = BPF(text=bpf_text)
Jazel Canseco6d818b62018-04-13 11:39:56 -0700159b.attach_kprobe(event="vfs_read", fn_name="trace_read_entry")
160b.attach_kprobe(event="vfs_write", fn_name="trace_write_entry")
Mark Drayton74347312016-08-25 20:46:35 +0100161
162DNAME_INLINE_LEN = 32 # linux/dcache.h
Brendan Gregg08c29812016-02-09 00:36:43 -0800163
164print('Tracing... Output every %d secs. Hit Ctrl-C to end' % interval)
165
Joel Fernandes (Google)c2b371d2019-03-08 11:39:42 -0500166def sort_fn(counts):
167 if args.sort == "all":
168 return (counts[1].rbytes + counts[1].wbytes + counts[1].reads + counts[1].writes)
169 else:
170 return getattr(counts[1], args.sort)
171
Brendan Gregg08c29812016-02-09 00:36:43 -0800172# output
173exiting = 0
174while 1:
175 try:
176 sleep(interval)
177 except KeyboardInterrupt:
178 exiting = 1
179
180 # header
181 if clear:
182 call("clear")
183 else:
184 print()
185 with open(loadavg) as stats:
186 print("%-8s loadavg: %s" % (strftime("%H:%M:%S"), stats.read()))
Mark Drayton74347312016-08-25 20:46:35 +0100187 print("%-6s %-16s %-6s %-6s %-7s %-7s %1s %s" % ("TID", "COMM",
Brendan Gregg08c29812016-02-09 00:36:43 -0800188 "READS", "WRITES", "R_Kb", "W_Kb", "T", "FILE"))
189
Mark Drayton74347312016-08-25 20:46:35 +0100190 # by-TID output
Brendan Gregg08c29812016-02-09 00:36:43 -0800191 counts = b.get_table("counts")
192 line = 0
193 for k, v in reversed(sorted(counts.items(),
Joel Fernandes (Google)c2b371d2019-03-08 11:39:42 -0500194 key=sort_fn)):
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200195 name = k.name.decode('utf-8', 'replace')
Mark Drayton74347312016-08-25 20:46:35 +0100196 if k.name_len > DNAME_INLINE_LEN:
197 name = name[:-3] + "..."
Brendan Gregg08c29812016-02-09 00:36:43 -0800198
199 # print line
Rafael Fonseca29392652017-02-06 17:07:28 +0100200 print("%-6d %-16s %-6d %-6d %-7d %-7d %1s %s" % (k.pid,
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200201 k.comm.decode('utf-8', 'replace'), v.reads, v.writes,
202 v.rbytes / 1024, v.wbytes / 1024,
203 k.type.decode('utf-8', 'replace'), name))
Brendan Gregg08c29812016-02-09 00:36:43 -0800204
205 line += 1
206 if line >= maxrows:
207 break
208 counts.clear()
209
210 countdown -= 1
211 if exiting or countdown == 0:
212 print("Detaching...")
213 exit()