blob: 51d3dc055345a20ced915c8be1d313481a292d8f [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
Alban Crequy32ab8582020-03-22 16:06:44 +010020from bcc.containers import filter_by_containers
japrocaed9b1e2019-01-04 20:21:46 +030021from bcc.utils import printb
Brendan Greggbedd1502015-09-17 21:52:52 -070022import argparse
Paul Chaignon702de382018-01-28 13:41:35 +010023from datetime import datetime, timedelta
Tim Douglasd3583a82018-12-30 13:18:54 -050024import os
Brendan Greggbedd1502015-09-17 21:52:52 -070025
26# arguments
27examples = """examples:
28 ./opensnoop # trace all open() syscalls
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030029 ./opensnoop -T # include timestamps
takumakumef8990372019-01-02 17:12:14 +090030 ./opensnoop -U # include UID
Brendan Greggbedd1502015-09-17 21:52:52 -070031 ./opensnoop -x # only show failed opens
32 ./opensnoop -p 181 # only trace PID 181
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030033 ./opensnoop -t 123 # only trace TID 123
takumakumef8990372019-01-02 17:12:14 +090034 ./opensnoop -u 1000 # only trace UID 1000
Paul Chaignon702de382018-01-28 13:41:35 +010035 ./opensnoop -d 10 # trace for 10 seconds only
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020036 ./opensnoop -n main # only print process names containing "main"
Tim Douglasd3583a82018-12-30 13:18:54 -050037 ./opensnoop -e # show extended fields
38 ./opensnoop -f O_WRONLY -f O_RDWR # only print calls for writing
Alban Crequy32ab8582020-03-22 16:06:44 +010039 ./opensnoop --cgroupmap mappath # only trace cgroups in this BPF map
40 ./opensnoop --mntnsmap mappath # only trace mount namespaces in the map
Brendan Greggbedd1502015-09-17 21:52:52 -070041"""
42parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080043 description="Trace open() syscalls",
44 formatter_class=argparse.RawDescriptionHelpFormatter,
45 epilog=examples)
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030046parser.add_argument("-T", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080047 help="include timestamp on output")
takumakumef8990372019-01-02 17:12:14 +090048parser.add_argument("-U", "--print-uid", action="store_true",
49 help="print UID column")
Brendan Greggbedd1502015-09-17 21:52:52 -070050parser.add_argument("-x", "--failed", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080051 help="only show failed opens")
Brendan Greggbedd1502015-09-17 21:52:52 -070052parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080053 help="trace this PID only")
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030054parser.add_argument("-t", "--tid",
55 help="trace this TID only")
Alban Crequyb2aa29f2019-12-16 10:54:18 +010056parser.add_argument("--cgroupmap",
57 help="trace cgroups in this BPF map only")
Alban Crequy32ab8582020-03-22 16:06:44 +010058parser.add_argument("--mntnsmap",
59 help="trace mount namespaces in this BPF map only")
takumakumef8990372019-01-02 17:12:14 +090060parser.add_argument("-u", "--uid",
61 help="trace this UID only")
Paul Chaignon702de382018-01-28 13:41:35 +010062parser.add_argument("-d", "--duration",
63 help="total duration of trace in seconds")
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020064parser.add_argument("-n", "--name",
Gary Lin40fd6692018-02-12 16:51:14 +080065 type=ArgString,
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020066 help="only print process names containing this name")
Nathan Scottcf0792f2018-02-02 16:56:50 +110067parser.add_argument("--ebpf", action="store_true",
68 help=argparse.SUPPRESS)
Tim Douglasd3583a82018-12-30 13:18:54 -050069parser.add_argument("-e", "--extended_fields", action="store_true",
70 help="show extended fields")
71parser.add_argument("-f", "--flag_filter", action="append",
72 help="filter on flags argument (e.g., O_WRONLY)")
Brendan Greggbedd1502015-09-17 21:52:52 -070073args = parser.parse_args()
74debug = 0
Paul Chaignon702de382018-01-28 13:41:35 +010075if args.duration:
76 args.duration = timedelta(seconds=int(args.duration))
Tim Douglasd3583a82018-12-30 13:18:54 -050077flag_filter_mask = 0
78for flag in args.flag_filter or []:
79 if not flag.startswith('O_'):
80 exit("Bad flag: %s" % flag)
81 try:
82 flag_filter_mask |= getattr(os, flag)
83 except AttributeError:
84 exit("Bad flag: %s" % flag)
Brendan Greggbedd1502015-09-17 21:52:52 -070085
86# define BPF program
87bpf_text = """
88#include <uapi/linux/ptrace.h>
mcaleavya3c446c72016-04-29 13:38:51 +010089#include <uapi/linux/limits.h>
90#include <linux/sched.h>
91
92struct val_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030093 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010094 char comm[TASK_COMM_LEN];
95 const char *fname;
Tim Douglasd3583a82018-12-30 13:18:54 -050096 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010097};
98
99struct data_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300100 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +0100101 u64 ts;
takumakumef8990372019-01-02 17:12:14 +0900102 u32 uid;
mcaleavya3c446c72016-04-29 13:38:51 +0100103 int ret;
104 char comm[TASK_COMM_LEN];
105 char fname[NAME_MAX];
Tim Douglasd3583a82018-12-30 13:18:54 -0500106 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +0100107};
Brendan Greggbedd1502015-09-17 21:52:52 -0700108
mcaleavya3c446c72016-04-29 13:38:51 +0100109BPF_PERF_OUTPUT(events);
Jiri Olsac347fe62019-12-22 15:52:39 +0100110"""
111
112bpf_text_kprobe = """
113BPF_HASH(infotmp, u64, struct val_t);
Brendan Greggbedd1502015-09-17 21:52:52 -0700114
Tim Douglasd3583a82018-12-30 13:18:54 -0500115int trace_entry(struct pt_regs *ctx, int dfd, const char __user *filename, int flags)
Brendan Greggbedd1502015-09-17 21:52:52 -0700116{
mcaleavya3c446c72016-04-29 13:38:51 +0100117 struct val_t val = {};
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300118 u64 id = bpf_get_current_pid_tgid();
119 u32 pid = id >> 32; // PID is higher part
120 u32 tid = id; // Cast and get the lower part
takumakumef8990372019-01-02 17:12:14 +0900121 u32 uid = bpf_get_current_uid_gid();
Brendan Greggbedd1502015-09-17 21:52:52 -0700122
Tim Douglasd3583a82018-12-30 13:18:54 -0500123 PID_TID_FILTER
takumakumef8990372019-01-02 17:12:14 +0900124 UID_FILTER
Tim Douglasd3583a82018-12-30 13:18:54 -0500125 FLAGS_FILTER
Alban Crequy32ab8582020-03-22 16:06:44 +0100126
127 if (container_should_be_filtered()) {
128 return 0;
Alban Crequyb2aa29f2019-12-16 10:54:18 +0100129 }
Alban Crequy32ab8582020-03-22 16:06:44 +0100130
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 }
Sumanth Korikkar7f6066d2020-05-20 10:49:56 -0500154 bpf_probe_read_kernel(&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 Crequy32ab8582020-03-22 16:06:44 +0100180 if (container_should_be_filtered()) {
181 return 0;
Alban Crequy510fc742020-03-19 14:07:38 +0100182 }
Jiri Olsac347fe62019-12-22 15:52:39 +0100183
184 struct data_t data = {};
185 bpf_get_current_comm(&data.comm, sizeof(data.comm));
186
187 u64 tsp = bpf_ktime_get_ns();
188
Sumanth Korikkar023154c2020-04-20 05:54:57 -0500189 bpf_probe_read_user(&data.fname, sizeof(data.fname), (void *)filename);
Jiri Olsac347fe62019-12-22 15:52:39 +0100190 data.id = id;
191 data.ts = tsp / 1000;
192 data.uid = bpf_get_current_uid_gid();
193 data.flags = flags; // EXTENDED_STRUCT_MEMBER
194 data.ret = ret;
195
196 events.perf_submit(ctx, &data, sizeof(data));
Mauricio Vásquez44e0f432020-05-21 11:50:52 -0500197
Mauricio Vásquez8cd27172020-06-08 08:12:08 -0500198 return 0;
Jiri Olsac347fe62019-12-22 15:52:39 +0100199}
200"""
201
202is_support_kfunc = BPF.support_kfunc()
203if is_support_kfunc:
204 bpf_text += bpf_text_kfunc
205else:
206 bpf_text += bpf_text_kprobe
207
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300208if args.tid: # TID trumps PID
Tim Douglasd3583a82018-12-30 13:18:54 -0500209 bpf_text = bpf_text.replace('PID_TID_FILTER',
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300210 'if (tid != %s) { return 0; }' % args.tid)
211elif args.pid:
Tim Douglasd3583a82018-12-30 13:18:54 -0500212 bpf_text = bpf_text.replace('PID_TID_FILTER',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800213 'if (pid != %s) { return 0; }' % args.pid)
Brendan Greggbedd1502015-09-17 21:52:52 -0700214else:
Tim Douglasd3583a82018-12-30 13:18:54 -0500215 bpf_text = bpf_text.replace('PID_TID_FILTER', '')
takumakumef8990372019-01-02 17:12:14 +0900216if args.uid:
217 bpf_text = bpf_text.replace('UID_FILTER',
218 'if (uid != %s) { return 0; }' % args.uid)
219else:
220 bpf_text = bpf_text.replace('UID_FILTER', '')
Alban Crequy32ab8582020-03-22 16:06:44 +0100221bpf_text = filter_by_containers(args) + bpf_text
Tim Douglasd3583a82018-12-30 13:18:54 -0500222if args.flag_filter:
223 bpf_text = bpf_text.replace('FLAGS_FILTER',
224 'if (!(flags & %d)) { return 0; }' % flag_filter_mask)
225else:
226 bpf_text = bpf_text.replace('FLAGS_FILTER', '')
227if not (args.extended_fields or args.flag_filter):
228 bpf_text = '\n'.join(x for x in bpf_text.split('\n')
229 if 'EXTENDED_STRUCT_MEMBER' not in x)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100230if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800231 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100232 if args.ebpf:
233 exit()
Brendan Greggbedd1502015-09-17 21:52:52 -0700234
235# initialize BPF
236b = BPF(text=bpf_text)
Jiri Olsac347fe62019-12-22 15:52:39 +0100237if not is_support_kfunc:
238 b.attach_kprobe(event="do_sys_open", fn_name="trace_entry")
239 b.attach_kretprobe(event="do_sys_open", fn_name="trace_return")
mcaleavya3c446c72016-04-29 13:38:51 +0100240
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200241initial_ts = 0
Brendan Greggbedd1502015-09-17 21:52:52 -0700242
243# header
244if args.timestamp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800245 print("%-14s" % ("TIME(s)"), end="")
takumakumef8990372019-01-02 17:12:14 +0900246if args.print_uid:
247 print("%-6s" % ("UID"), end="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500248print("%-6s %-16s %4s %3s " %
249 ("TID" if args.tid else "PID", "COMM", "FD", "ERR"), end="")
250if args.extended_fields:
251 print("%-9s" % ("FLAGS"), end="")
252print("PATH")
Brendan Greggbedd1502015-09-17 21:52:52 -0700253
mcaleavya3c446c72016-04-29 13:38:51 +0100254# process event
255def print_event(cpu, data, size):
Xiaozhou Liu51d62d32019-02-15 13:03:05 +0800256 event = b["events"].event(data)
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200257 global initial_ts
Brendan Greggbedd1502015-09-17 21:52:52 -0700258
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800259 # split return value into FD and errno columns
mcaleavya3c446c72016-04-29 13:38:51 +0100260 if event.ret >= 0:
261 fd_s = event.ret
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800262 err = 0
263 else:
mcaleavya3c446c72016-04-29 13:38:51 +0100264 fd_s = -1
265 err = - event.ret
Brendan Greggbedd1502015-09-17 21:52:52 -0700266
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200267 if not initial_ts:
268 initial_ts = event.ts
mcaleavya3c446c72016-04-29 13:38:51 +0100269
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200270 if args.failed and (event.ret >= 0):
mcaleavya3c446c72016-04-29 13:38:51 +0100271 return
272
Gary Lin40fd6692018-02-12 16:51:14 +0800273 if args.name and bytes(args.name) not in event.comm:
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +0200274 return
275
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800276 if args.timestamp:
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200277 delta = event.ts - initial_ts
Gary Lin6c793312019-04-18 15:17:56 +0800278 printb(b"%-14.9f" % (float(delta) / 1000000), nl="")
mcaleavya3c446c72016-04-29 13:38:51 +0100279
takumakumef8990372019-01-02 17:12:14 +0900280 if args.print_uid:
Gary Lin6c793312019-04-18 15:17:56 +0800281 printb(b"%-6d" % event.uid, nl="")
takumakumef8990372019-01-02 17:12:14 +0900282
Gary Lin6c793312019-04-18 15:17:56 +0800283 printb(b"%-6d %-16s %4d %3d " %
284 (event.id & 0xffffffff if args.tid else event.id >> 32,
285 event.comm, fd_s, err), nl="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500286
287 if args.extended_fields:
Gary Lin6c793312019-04-18 15:17:56 +0800288 printb(b"%08o " % event.flags, nl="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500289
Yonghong Songebe19512019-01-10 14:54:16 -0800290 printb(b'%s' % event.fname)
mcaleavya3c446c72016-04-29 13:38:51 +0100291
292# loop with callback to print_event
Mark Drayton5f5687e2017-02-20 18:13:03 +0000293b["events"].open_perf_buffer(print_event, page_cnt=64)
Paul Chaignon702de382018-01-28 13:41:35 +0100294start_time = datetime.now()
295while not args.duration or datetime.now() - start_time < args.duration:
Jerome Marchand51671272018-12-19 01:57:24 +0100296 try:
297 b.perf_buffer_poll()
298 except KeyboardInterrupt:
299 exit()