• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * filetop Trace file reads/writes by process.
5  * Copyright (c) 2021 Hengqi Chen
6  *
7  * Based on filetop(8) from BCC by Brendan Gregg.
8  * 17-Jul-2021   Hengqi Chen   Created this.
9  */
10 #include <argp.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <time.h>
17 #include <unistd.h>
18 
19 #include <bpf/libbpf.h>
20 #include <bpf/bpf.h>
21 #include "filetop.h"
22 #include "filetop.skel.h"
23 #include "trace_helpers.h"
24 
25 #define warn(...) fprintf(stderr, __VA_ARGS__)
26 #define OUTPUT_ROWS_LIMIT 10240
27 
28 enum SORT {
29 	ALL,
30 	READS,
31 	WRITES,
32 	RBYTES,
33 	WBYTES,
34 };
35 
36 static volatile sig_atomic_t exiting = 0;
37 
38 static pid_t target_pid = 0;
39 static bool clear_screen = true;
40 static bool regular_file_only = true;
41 static int output_rows = 20;
42 static int sort_by = ALL;
43 static int interval = 1;
44 static int count = 99999999;
45 static bool verbose = false;
46 
47 const char *argp_program_version = "filetop 0.1";
48 const char *argp_program_bug_address =
49 	"https://github.com/iovisor/bcc/tree/master/libbpf-tools";
50 const char argp_program_doc[] =
51 "Trace file reads/writes by process.\n"
52 "\n"
53 "USAGE: filetop [-h] [-p PID] [interval] [count]\n"
54 "\n"
55 "EXAMPLES:\n"
56 "    filetop            # file I/O top, refresh every 1s\n"
57 "    filetop -p 1216    # only trace PID 1216\n"
58 "    filetop 5 10       # 5s summaries, 10 times\n";
59 
60 static const struct argp_option opts[] = {
61 	{ "pid", 'p', "PID", 0, "Process ID to trace" },
62 	{ "noclear", 'C', NULL, 0, "Don't clear the screen" },
63 	{ "all", 'a', NULL, 0, "Include special files" },
64 	{ "sort", 's', "SORT", 0, "Sort columns, default all [all, reads, writes, rbytes, wbytes]" },
65 	{ "rows", 'r', "ROWS", 0, "Maximum rows to print, default 20" },
66 	{ "verbose", 'v', NULL, 0, "Verbose debug output" },
67 	{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
68 	{},
69 };
70 
parse_arg(int key,char * arg,struct argp_state * state)71 static error_t parse_arg(int key, char *arg, struct argp_state *state)
72 {
73 	long pid, rows;
74 	static int pos_args;
75 
76 	switch (key) {
77 	case 'p':
78 		errno = 0;
79 		pid = strtol(arg, NULL, 10);
80 		if (errno || pid <= 0) {
81 			warn("invalid PID: %s\n", arg);
82 			argp_usage(state);
83 		}
84 		target_pid = pid;
85 		break;
86 	case 'C':
87 		clear_screen = false;
88 		break;
89 	case 'a':
90 		regular_file_only = false;
91 		break;
92 	case 's':
93 		if (!strcmp(arg, "all")) {
94 			sort_by = ALL;
95 		} else if (!strcmp(arg, "reads")) {
96 			sort_by = READS;
97 		} else if (!strcmp(arg, "writes")) {
98 			sort_by = WRITES;
99 		} else if (!strcmp(arg, "rbytes")) {
100 			sort_by = RBYTES;
101 		} else if (!strcmp(arg, "wbytes")) {
102 			sort_by = WBYTES;
103 		} else {
104 			warn("invalid sort method: %s\n", arg);
105 			argp_usage(state);
106 		}
107 		break;
108 	case 'r':
109 		errno = 0;
110 		rows = strtol(arg, NULL, 10);
111 		if (errno || rows <= 0) {
112 			warn("invalid rows: %s\n", arg);
113 			argp_usage(state);
114 		}
115 		output_rows = rows;
116 		if (output_rows > OUTPUT_ROWS_LIMIT)
117 			output_rows = OUTPUT_ROWS_LIMIT;
118 		break;
119 	case 'v':
120 		verbose = true;
121 		break;
122 	case 'h':
123 		argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
124 		break;
125 	case ARGP_KEY_ARG:
126 		errno = 0;
127 		if (pos_args == 0) {
128 			interval = strtol(arg, NULL, 10);
129 			if (errno || interval <= 0) {
130 				warn("invalid interval\n");
131 				argp_usage(state);
132 			}
133 		} else if (pos_args == 1) {
134 			count = strtol(arg, NULL, 10);
135 			if (errno || count <= 0) {
136 				warn("invalid count\n");
137 				argp_usage(state);
138 			}
139 		} else {
140 			warn("unrecognized positional argument: %s\n", arg);
141 			argp_usage(state);
142 		}
143 		pos_args++;
144 		break;
145 	default:
146 		return ARGP_ERR_UNKNOWN;
147 	}
148 	return 0;
149 }
150 
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)151 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
152 {
153 	if (level == LIBBPF_DEBUG && !verbose)
154 		return 0;
155 	return vfprintf(stderr, format, args);
156 }
157 
sig_int(int signo)158 static void sig_int(int signo)
159 {
160 	exiting = 1;
161 }
162 
sort_column(const void * obj1,const void * obj2)163 static int sort_column(const void *obj1, const void *obj2)
164 {
165 	struct file_stat *s1 = (struct file_stat *)obj1;
166 	struct file_stat *s2 = (struct file_stat *)obj2;
167 
168 	if (sort_by == READS) {
169 		return s2->reads - s1->reads;
170 	} else if (sort_by == WRITES) {
171 		return s2->writes - s1->writes;
172 	} else if (sort_by == RBYTES) {
173 		return s2->read_bytes - s1->read_bytes;
174 	} else if (sort_by == WBYTES) {
175 		return s2->write_bytes - s1->write_bytes;
176 	} else {
177 		return (s2->reads + s2->writes + s2->read_bytes + s2->write_bytes)
178 		     - (s1->reads + s1->writes + s1->read_bytes + s1->write_bytes);
179 	}
180 }
181 
print_stat(struct filetop_bpf * obj)182 static int print_stat(struct filetop_bpf *obj)
183 {
184 	FILE *f;
185 	time_t t;
186 	struct tm *tm;
187 	char ts[16], buf[256];
188 	struct file_id key, *prev_key = NULL;
189 	static struct file_stat values[OUTPUT_ROWS_LIMIT];
190 	int n, i, err = 0, rows = 0;
191 	int fd = bpf_map__fd(obj->maps.entries);
192 
193 	f = fopen("/proc/loadavg", "r");
194 	if (f) {
195 		time(&t);
196 		tm = localtime(&t);
197 		strftime(ts, sizeof(ts), "%H:%M:%S", tm);
198 		memset(buf, 0, sizeof(buf));
199 		n = fread(buf, 1, sizeof(buf), f);
200 		if (n)
201 			printf("%8s loadavg: %s\n", ts, buf);
202 		fclose(f);
203 	}
204 
205 	printf("%-7s %-16s %-6s %-6s %-7s %-7s %1s %s\n",
206 	       "TID", "COMM", "READS", "WRITES", "R_Kb", "W_Kb", "T", "FILE");
207 
208 	while (1) {
209 		err = bpf_map_get_next_key(fd, prev_key, &key);
210 		if (err) {
211 			if (errno == ENOENT) {
212 				err = 0;
213 				break;
214 			}
215 			warn("bpf_map_get_next_key failed: %s\n", strerror(errno));
216 			return err;
217 		}
218 		err = bpf_map_lookup_elem(fd, &key, &values[rows++]);
219 		if (err) {
220 			warn("bpf_map_lookup_elem failed: %s\n", strerror(errno));
221 			return err;
222 		}
223 		prev_key = &key;
224 	}
225 
226 	qsort(values, rows, sizeof(struct file_stat), sort_column);
227 	rows = rows < output_rows ? rows : output_rows;
228 	for (i = 0; i < rows; i++)
229 		printf("%-7d %-16s %-6lld %-6lld %-7lld %-7lld %c %s\n",
230 		       values[i].tid, values[i].comm, values[i].reads, values[i].writes,
231 		       values[i].read_bytes / 1024, values[i].write_bytes / 1024,
232 		       values[i].type, values[i].filename);
233 
234 	printf("\n");
235 	prev_key = NULL;
236 
237 	while (1) {
238 		err = bpf_map_get_next_key(fd, prev_key, &key);
239 		if (err) {
240 			if (errno == ENOENT) {
241 				err = 0;
242 				break;
243 			}
244 			warn("bpf_map_get_next_key failed: %s\n", strerror(errno));
245 			return err;
246 		}
247 		err = bpf_map_delete_elem(fd, &key);
248 		if (err) {
249 			warn("bpf_map_delete_elem failed: %s\n", strerror(errno));
250 			return err;
251 		}
252 		prev_key = &key;
253 	}
254 	return err;
255 }
256 
main(int argc,char ** argv)257 int main(int argc, char **argv)
258 {
259 	static const struct argp argp = {
260 		.options = opts,
261 		.parser = parse_arg,
262 		.doc = argp_program_doc,
263 	};
264 	struct filetop_bpf *obj;
265 	int err;
266 
267 	err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
268 	if (err)
269 		return err;
270 
271 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
272 	libbpf_set_print(libbpf_print_fn);
273 
274 	obj = filetop_bpf__open();
275 	if (!obj) {
276 		warn("failed to open BPF object\n");
277 		return 1;
278 	}
279 
280 	obj->rodata->target_pid = target_pid;
281 	obj->rodata->regular_file_only = regular_file_only;
282 
283 	err = filetop_bpf__load(obj);
284 	if (err) {
285 		warn("failed to load BPF object: %d\n", err);
286 		goto cleanup;
287 	}
288 
289 	err = filetop_bpf__attach(obj);
290 	if (err) {
291 		warn("failed to attach BPF programs: %d\n", err);
292 		goto cleanup;
293 	}
294 
295 	if (signal(SIGINT, sig_int) == SIG_ERR) {
296 		warn("can't set signal handler: %s\n", strerror(errno));
297 		err = 1;
298 		goto cleanup;
299 	}
300 
301 	while (1) {
302 		sleep(interval);
303 
304 		if (clear_screen) {
305 			err = system("clear");
306 			if (err)
307 				goto cleanup;
308 		}
309 
310 		err = print_stat(obj);
311 		if (err)
312 			goto cleanup;
313 
314 		count--;
315 		if (exiting || !count)
316 			goto cleanup;
317 	}
318 
319 cleanup:
320 	filetop_bpf__destroy(obj);
321 
322 	return err != 0;
323 }
324