blob: 995443e3faf30cb67d014f3981e04ed4163c8761 [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 Greggbedd1502015-09-17 21:52:52 -07003#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08004# opensnoop Trace open() syscalls.
5# For Linux, uses BCC, eBPF. Embedded C.
Brendan Greggbedd1502015-09-17 21:52:52 -07006#
Paul Chaignon702de382018-01-28 13:41:35 +01007# USAGE: opensnoop [-h] [-T] [-x] [-p PID] [-d DURATION] [-t TID] [-n NAME]
Brendan Greggbedd1502015-09-17 21:52:52 -07008#
9# Copyright (c) 2015 Brendan Gregg.
10# Licensed under the Apache License, Version 2.0 (the "License")
11#
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080012# 17-Sep-2015 Brendan Gregg Created this.
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030013# 29-Apr-2016 Allan McAleavy Updated for BPF_PERF_OUTPUT.
14# 08-Oct-2016 Dina Goldshtein Support filtering by PID and TID.
Tim Douglasd3583a82018-12-30 13:18:54 -050015# 28-Dec-2018 Tim Douglas Print flags argument, enable filtering
takumakumef8990372019-01-02 17:12:14 +090016# 06-Jan-2019 Takuma Kume Support filtering by UID
Brendan Greggbedd1502015-09-17 21:52:52 -070017
18from __future__ import print_function
Gary Lin40fd6692018-02-12 16:51:14 +080019from bcc import ArgString, BPF
japrocaed9b1e2019-01-04 20:21:46 +030020from bcc.utils import printb
Brendan Greggbedd1502015-09-17 21:52:52 -070021import argparse
Paul Chaignon702de382018-01-28 13:41:35 +010022from datetime import datetime, timedelta
Tim Douglasd3583a82018-12-30 13:18:54 -050023import os
Brendan Greggbedd1502015-09-17 21:52:52 -070024
25# arguments
26examples = """examples:
27 ./opensnoop # trace all open() syscalls
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030028 ./opensnoop -T # include timestamps
takumakumef8990372019-01-02 17:12:14 +090029 ./opensnoop -U # include UID
Brendan Greggbedd1502015-09-17 21:52:52 -070030 ./opensnoop -x # only show failed opens
31 ./opensnoop -p 181 # only trace PID 181
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030032 ./opensnoop -t 123 # only trace TID 123
takumakumef8990372019-01-02 17:12:14 +090033 ./opensnoop -u 1000 # only trace UID 1000
Paul Chaignon702de382018-01-28 13:41:35 +010034 ./opensnoop -d 10 # trace for 10 seconds only
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020035 ./opensnoop -n main # only print process names containing "main"
Tim Douglasd3583a82018-12-30 13:18:54 -050036 ./opensnoop -e # show extended fields
37 ./opensnoop -f O_WRONLY -f O_RDWR # only print calls for writing
Alban Crequyb2aa29f2019-12-16 10:54:18 +010038 ./opensnoop --cgroupmap ./mappath # only trace cgroups in this BPF map
Brendan Greggbedd1502015-09-17 21:52:52 -070039"""
40parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080041 description="Trace open() syscalls",
42 formatter_class=argparse.RawDescriptionHelpFormatter,
43 epilog=examples)
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030044parser.add_argument("-T", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080045 help="include timestamp on output")
takumakumef8990372019-01-02 17:12:14 +090046parser.add_argument("-U", "--print-uid", action="store_true",
47 help="print UID column")
Brendan Greggbedd1502015-09-17 21:52:52 -070048parser.add_argument("-x", "--failed", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080049 help="only show failed opens")
Brendan Greggbedd1502015-09-17 21:52:52 -070050parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080051 help="trace this PID only")
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030052parser.add_argument("-t", "--tid",
53 help="trace this TID only")
Alban Crequyb2aa29f2019-12-16 10:54:18 +010054parser.add_argument("--cgroupmap",
55 help="trace cgroups in this BPF map only")
takumakumef8990372019-01-02 17:12:14 +090056parser.add_argument("-u", "--uid",
57 help="trace this UID only")
Paul Chaignon702de382018-01-28 13:41:35 +010058parser.add_argument("-d", "--duration",
59 help="total duration of trace in seconds")
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020060parser.add_argument("-n", "--name",
Gary Lin40fd6692018-02-12 16:51:14 +080061 type=ArgString,
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020062 help="only print process names containing this name")
Nathan Scottcf0792f2018-02-02 16:56:50 +110063parser.add_argument("--ebpf", action="store_true",
64 help=argparse.SUPPRESS)
Tim Douglasd3583a82018-12-30 13:18:54 -050065parser.add_argument("-e", "--extended_fields", action="store_true",
66 help="show extended fields")
67parser.add_argument("-f", "--flag_filter", action="append",
68 help="filter on flags argument (e.g., O_WRONLY)")
Brendan Greggbedd1502015-09-17 21:52:52 -070069args = parser.parse_args()
70debug = 0
Paul Chaignon702de382018-01-28 13:41:35 +010071if args.duration:
72 args.duration = timedelta(seconds=int(args.duration))
Tim Douglasd3583a82018-12-30 13:18:54 -050073flag_filter_mask = 0
74for flag in args.flag_filter or []:
75 if not flag.startswith('O_'):
76 exit("Bad flag: %s" % flag)
77 try:
78 flag_filter_mask |= getattr(os, flag)
79 except AttributeError:
80 exit("Bad flag: %s" % flag)
Brendan Greggbedd1502015-09-17 21:52:52 -070081
82# define BPF program
83bpf_text = """
84#include <uapi/linux/ptrace.h>
mcaleavya3c446c72016-04-29 13:38:51 +010085#include <uapi/linux/limits.h>
86#include <linux/sched.h>
87
88struct val_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030089 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010090 char comm[TASK_COMM_LEN];
91 const char *fname;
Tim Douglasd3583a82018-12-30 13:18:54 -050092 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010093};
94
95struct data_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030096 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010097 u64 ts;
takumakumef8990372019-01-02 17:12:14 +090098 u32 uid;
mcaleavya3c446c72016-04-29 13:38:51 +010099 int ret;
100 char comm[TASK_COMM_LEN];
101 char fname[NAME_MAX];
Tim Douglasd3583a82018-12-30 13:18:54 -0500102 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +0100103};
Brendan Greggbedd1502015-09-17 21:52:52 -0700104
Alban Crequyb2aa29f2019-12-16 10:54:18 +0100105#if CGROUPSET
106BPF_TABLE_PINNED("hash", u64, u64, cgroupset, 1024, "CGROUPPATH");
107#endif
mcaleavya3c446c72016-04-29 13:38:51 +0100108BPF_PERF_OUTPUT(events);
Jiri Olsac347fe62019-12-22 15:52:39 +0100109"""
110
111bpf_text_kprobe = """
112BPF_HASH(infotmp, u64, struct val_t);
Brendan Greggbedd1502015-09-17 21:52:52 -0700113
Tim Douglasd3583a82018-12-30 13:18:54 -0500114int trace_entry(struct pt_regs *ctx, int dfd, const char __user *filename, int flags)
Brendan Greggbedd1502015-09-17 21:52:52 -0700115{
mcaleavya3c446c72016-04-29 13:38:51 +0100116 struct val_t val = {};
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300117 u64 id = bpf_get_current_pid_tgid();
118 u32 pid = id >> 32; // PID is higher part
119 u32 tid = id; // Cast and get the lower part
takumakumef8990372019-01-02 17:12:14 +0900120 u32 uid = bpf_get_current_uid_gid();
Brendan Greggbedd1502015-09-17 21:52:52 -0700121
Tim Douglasd3583a82018-12-30 13:18:54 -0500122 PID_TID_FILTER
takumakumef8990372019-01-02 17:12:14 +0900123 UID_FILTER
Tim Douglasd3583a82018-12-30 13:18:54 -0500124 FLAGS_FILTER
Alban Crequyb2aa29f2019-12-16 10:54:18 +0100125#if CGROUPSET
126 u64 cgroupid = bpf_get_current_cgroup_id();
127 if (cgroupset.lookup(&cgroupid) == NULL) {
128 return 0;
129 }
130#endif
mcaleavya3c446c72016-04-29 13:38:51 +0100131 if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300132 val.id = id;
mcaleavya3c446c72016-04-29 13:38:51 +0100133 val.fname = filename;
Tim Douglasd3583a82018-12-30 13:18:54 -0500134 val.flags = flags; // EXTENDED_STRUCT_MEMBER
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300135 infotmp.update(&id, &val);
mcaleavya3c446c72016-04-29 13:38:51 +0100136 }
Brendan Greggbedd1502015-09-17 21:52:52 -0700137
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800138 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700139};
140
mcaleavya3c446c72016-04-29 13:38:51 +0100141int trace_return(struct pt_regs *ctx)
Brendan Greggbedd1502015-09-17 21:52:52 -0700142{
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300143 u64 id = bpf_get_current_pid_tgid();
mcaleavya3c446c72016-04-29 13:38:51 +0100144 struct val_t *valp;
145 struct data_t data = {};
Brendan Greggbedd1502015-09-17 21:52:52 -0700146
mcaleavya3c446c72016-04-29 13:38:51 +0100147 u64 tsp = bpf_ktime_get_ns();
148
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300149 valp = infotmp.lookup(&id);
mcaleavya3c446c72016-04-29 13:38:51 +0100150 if (valp == 0) {
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800151 // missed entry
152 return 0;
153 }
mcaleavya3c446c72016-04-29 13:38:51 +0100154 bpf_probe_read(&data.comm, sizeof(data.comm), valp->comm);
Sumanth Korikkar023154c2020-04-20 05:54:57 -0500155 bpf_probe_read_user(&data.fname, sizeof(data.fname), (void *)valp->fname);
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300156 data.id = valp->id;
mcaleavya3c446c72016-04-29 13:38:51 +0100157 data.ts = tsp / 1000;
takumakumef8990372019-01-02 17:12:14 +0900158 data.uid = bpf_get_current_uid_gid();
Tim Douglasd3583a82018-12-30 13:18:54 -0500159 data.flags = valp->flags; // EXTENDED_STRUCT_MEMBER
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530160 data.ret = PT_REGS_RC(ctx);
Brendan Greggbedd1502015-09-17 21:52:52 -0700161
mcaleavya3c446c72016-04-29 13:38:51 +0100162 events.perf_submit(ctx, &data, sizeof(data));
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300163 infotmp.delete(&id);
Brendan Greggbedd1502015-09-17 21:52:52 -0700164
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800165 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700166}
167"""
Jiri Olsac347fe62019-12-22 15:52:39 +0100168
169bpf_text_kfunc= """
Sumanth Korikkar023154c2020-04-20 05:54:57 -0500170KRETFUNC_PROBE(do_sys_open, int dfd, const char __user *filename, int flags, int mode, int ret)
Jiri Olsac347fe62019-12-22 15:52:39 +0100171{
172 u64 id = bpf_get_current_pid_tgid();
173 u32 pid = id >> 32; // PID is higher part
174 u32 tid = id; // Cast and get the lower part
175 u32 uid = bpf_get_current_uid_gid();
176
177 PID_TID_FILTER
178 UID_FILTER
179 FLAGS_FILTER
Alban Crequy510fc742020-03-19 14:07:38 +0100180#if CGROUPSET
181 u64 cgroupid = bpf_get_current_cgroup_id();
182 if (cgroupset.lookup(&cgroupid) == NULL) {
183 return 0;
184 }
185#endif
Jiri Olsac347fe62019-12-22 15:52:39 +0100186
187 struct data_t data = {};
188 bpf_get_current_comm(&data.comm, sizeof(data.comm));
189
190 u64 tsp = bpf_ktime_get_ns();
191
Sumanth Korikkar023154c2020-04-20 05:54:57 -0500192 bpf_probe_read_user(&data.fname, sizeof(data.fname), (void *)filename);
Jiri Olsac347fe62019-12-22 15:52:39 +0100193 data.id = id;
194 data.ts = tsp / 1000;
195 data.uid = bpf_get_current_uid_gid();
196 data.flags = flags; // EXTENDED_STRUCT_MEMBER
197 data.ret = ret;
198
199 events.perf_submit(ctx, &data, sizeof(data));
200}
201"""
202
203is_support_kfunc = BPF.support_kfunc()
204if is_support_kfunc:
205 bpf_text += bpf_text_kfunc
206else:
207 bpf_text += bpf_text_kprobe
208
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300209if args.tid: # TID trumps PID
Tim Douglasd3583a82018-12-30 13:18:54 -0500210 bpf_text = bpf_text.replace('PID_TID_FILTER',
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300211 'if (tid != %s) { return 0; }' % args.tid)
212elif args.pid:
Tim Douglasd3583a82018-12-30 13:18:54 -0500213 bpf_text = bpf_text.replace('PID_TID_FILTER',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800214 'if (pid != %s) { return 0; }' % args.pid)
Brendan Greggbedd1502015-09-17 21:52:52 -0700215else:
Tim Douglasd3583a82018-12-30 13:18:54 -0500216 bpf_text = bpf_text.replace('PID_TID_FILTER', '')
takumakumef8990372019-01-02 17:12:14 +0900217if args.uid:
218 bpf_text = bpf_text.replace('UID_FILTER',
219 'if (uid != %s) { return 0; }' % args.uid)
220else:
221 bpf_text = bpf_text.replace('UID_FILTER', '')
Alban Crequyb2aa29f2019-12-16 10:54:18 +0100222if args.cgroupmap:
223 bpf_text = bpf_text.replace('CGROUPSET', '1')
224 bpf_text = bpf_text.replace('CGROUPPATH', args.cgroupmap)
225else:
226 bpf_text = bpf_text.replace('CGROUPSET', '0')
Tim Douglasd3583a82018-12-30 13:18:54 -0500227if args.flag_filter:
228 bpf_text = bpf_text.replace('FLAGS_FILTER',
229 'if (!(flags & %d)) { return 0; }' % flag_filter_mask)
230else:
231 bpf_text = bpf_text.replace('FLAGS_FILTER', '')
232if not (args.extended_fields or args.flag_filter):
233 bpf_text = '\n'.join(x for x in bpf_text.split('\n')
234 if 'EXTENDED_STRUCT_MEMBER' not in x)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100235if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800236 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100237 if args.ebpf:
238 exit()
Brendan Greggbedd1502015-09-17 21:52:52 -0700239
240# initialize BPF
241b = BPF(text=bpf_text)
Jiri Olsac347fe62019-12-22 15:52:39 +0100242if not is_support_kfunc:
243 b.attach_kprobe(event="do_sys_open", fn_name="trace_entry")
244 b.attach_kretprobe(event="do_sys_open", fn_name="trace_return")
mcaleavya3c446c72016-04-29 13:38:51 +0100245
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200246initial_ts = 0
Brendan Greggbedd1502015-09-17 21:52:52 -0700247
248# header
249if args.timestamp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800250 print("%-14s" % ("TIME(s)"), end="")
takumakumef8990372019-01-02 17:12:14 +0900251if args.print_uid:
252 print("%-6s" % ("UID"), end="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500253print("%-6s %-16s %4s %3s " %
254 ("TID" if args.tid else "PID", "COMM", "FD", "ERR"), end="")
255if args.extended_fields:
256 print("%-9s" % ("FLAGS"), end="")
257print("PATH")
Brendan Greggbedd1502015-09-17 21:52:52 -0700258
mcaleavya3c446c72016-04-29 13:38:51 +0100259# process event
260def print_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +0800261 event = b["events"].event(data)
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200262 global initial_ts
Brendan Greggbedd1502015-09-17 21:52:52 -0700263
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800264 # split return value into FD and errno columns
mcaleavya3c446c72016-04-29 13:38:51 +0100265 if event.ret >= 0:
266 fd_s = event.ret
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800267 err = 0
268 else:
mcaleavya3c446c72016-04-29 13:38:51 +0100269 fd_s = -1
270 err = - event.ret
Brendan Greggbedd1502015-09-17 21:52:52 -0700271
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200272 if not initial_ts:
273 initial_ts = event.ts
mcaleavya3c446c72016-04-29 13:38:51 +0100274
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200275 if args.failed and (event.ret >= 0):
mcaleavya3c446c72016-04-29 13:38:51 +0100276 return
277
Gary Lin40fd6692018-02-12 16:51:14 +0800278 if args.name and bytes(args.name) not in event.comm:
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +0200279 return
280
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800281 if args.timestamp:
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200282 delta = event.ts - initial_ts
Gary Lin6c793312019-04-18 15:17:56 +0800283 printb(b"%-14.9f" % (float(delta) / 1000000), nl="")
mcaleavya3c446c72016-04-29 13:38:51 +0100284
takumakumef8990372019-01-02 17:12:14 +0900285 if args.print_uid:
Gary Lin6c793312019-04-18 15:17:56 +0800286 printb(b"%-6d" % event.uid, nl="")
takumakumef8990372019-01-02 17:12:14 +0900287
Gary Lin6c793312019-04-18 15:17:56 +0800288 printb(b"%-6d %-16s %4d %3d " %
289 (event.id & 0xffffffff if args.tid else event.id >> 32,
290 event.comm, fd_s, err), nl="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500291
292 if args.extended_fields:
Gary Lin6c793312019-04-18 15:17:56 +0800293 printb(b"%08o " % event.flags, nl="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500294
Yonghong Songebe19512019-01-10 14:54:16 -0800295 printb(b'%s' % event.fname)
mcaleavya3c446c72016-04-29 13:38:51 +0100296
297# loop with callback to print_event
Mark Drayton5f5687e2017-02-20 18:13:03 +0000298b["events"].open_perf_buffer(print_event, page_cnt=64)
Paul Chaignon702de382018-01-28 13:41:35 +0100299start_time = datetime.now()
300while not args.duration or datetime.now() - start_time < args.duration:
Jerome Marchand51671272018-12-19 01:57:24 +0100301 try:
302 b.perf_buffer_poll()
303 except KeyboardInterrupt:
304 exit()