blob: 2a00737217b5361412966054671fdaabe179b609 [file] [log] [blame]
Brendan Greggbedd1502015-09-17 21:52:52 -07001#!/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
Brendan Greggbedd1502015-09-17 21:52:52 -070016
17from __future__ import print_function
Gary Lin40fd6692018-02-12 16:51:14 +080018from bcc import ArgString, BPF
Brendan Greggbedd1502015-09-17 21:52:52 -070019import argparse
mcaleavya3c446c72016-04-29 13:38:51 +010020import ctypes as ct
Paul Chaignon702de382018-01-28 13:41:35 +010021from datetime import datetime, timedelta
Tim Douglasd3583a82018-12-30 13:18:54 -050022import os
Brendan Greggbedd1502015-09-17 21:52:52 -070023
24# arguments
25examples = """examples:
26 ./opensnoop # trace all open() syscalls
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030027 ./opensnoop -T # include timestamps
Brendan Greggbedd1502015-09-17 21:52:52 -070028 ./opensnoop -x # only show failed opens
29 ./opensnoop -p 181 # only trace PID 181
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030030 ./opensnoop -t 123 # only trace TID 123
Paul Chaignon702de382018-01-28 13:41:35 +010031 ./opensnoop -d 10 # trace for 10 seconds only
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020032 ./opensnoop -n main # only print process names containing "main"
Tim Douglasd3583a82018-12-30 13:18:54 -050033 ./opensnoop -e # show extended fields
34 ./opensnoop -f O_WRONLY -f O_RDWR # only print calls for writing
Brendan Greggbedd1502015-09-17 21:52:52 -070035"""
36parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080037 description="Trace open() syscalls",
38 formatter_class=argparse.RawDescriptionHelpFormatter,
39 epilog=examples)
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030040parser.add_argument("-T", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080041 help="include timestamp on output")
Brendan Greggbedd1502015-09-17 21:52:52 -070042parser.add_argument("-x", "--failed", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080043 help="only show failed opens")
Brendan Greggbedd1502015-09-17 21:52:52 -070044parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080045 help="trace this PID only")
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030046parser.add_argument("-t", "--tid",
47 help="trace this TID only")
Paul Chaignon702de382018-01-28 13:41:35 +010048parser.add_argument("-d", "--duration",
49 help="total duration of trace in seconds")
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020050parser.add_argument("-n", "--name",
Gary Lin40fd6692018-02-12 16:51:14 +080051 type=ArgString,
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020052 help="only print process names containing this name")
Nathan Scottcf0792f2018-02-02 16:56:50 +110053parser.add_argument("--ebpf", action="store_true",
54 help=argparse.SUPPRESS)
Tim Douglasd3583a82018-12-30 13:18:54 -050055parser.add_argument("-e", "--extended_fields", action="store_true",
56 help="show extended fields")
57parser.add_argument("-f", "--flag_filter", action="append",
58 help="filter on flags argument (e.g., O_WRONLY)")
Brendan Greggbedd1502015-09-17 21:52:52 -070059args = parser.parse_args()
60debug = 0
Paul Chaignon702de382018-01-28 13:41:35 +010061if args.duration:
62 args.duration = timedelta(seconds=int(args.duration))
Tim Douglasd3583a82018-12-30 13:18:54 -050063flag_filter_mask = 0
64for flag in args.flag_filter or []:
65 if not flag.startswith('O_'):
66 exit("Bad flag: %s" % flag)
67 try:
68 flag_filter_mask |= getattr(os, flag)
69 except AttributeError:
70 exit("Bad flag: %s" % flag)
Brendan Greggbedd1502015-09-17 21:52:52 -070071
72# define BPF program
73bpf_text = """
74#include <uapi/linux/ptrace.h>
mcaleavya3c446c72016-04-29 13:38:51 +010075#include <uapi/linux/limits.h>
76#include <linux/sched.h>
77
78struct val_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030079 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010080 char comm[TASK_COMM_LEN];
81 const char *fname;
Tim Douglasd3583a82018-12-30 13:18:54 -050082 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010083};
84
85struct data_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030086 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010087 u64 ts;
mcaleavya3c446c72016-04-29 13:38:51 +010088 int ret;
89 char comm[TASK_COMM_LEN];
90 char fname[NAME_MAX];
Tim Douglasd3583a82018-12-30 13:18:54 -050091 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010092};
Brendan Greggbedd1502015-09-17 21:52:52 -070093
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030094BPF_HASH(infotmp, u64, struct val_t);
mcaleavya3c446c72016-04-29 13:38:51 +010095BPF_PERF_OUTPUT(events);
Brendan Greggbedd1502015-09-17 21:52:52 -070096
Tim Douglasd3583a82018-12-30 13:18:54 -050097int trace_entry(struct pt_regs *ctx, int dfd, const char __user *filename, int flags)
Brendan Greggbedd1502015-09-17 21:52:52 -070098{
mcaleavya3c446c72016-04-29 13:38:51 +010099 struct val_t val = {};
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300100 u64 id = bpf_get_current_pid_tgid();
101 u32 pid = id >> 32; // PID is higher part
102 u32 tid = id; // Cast and get the lower part
Brendan Greggbedd1502015-09-17 21:52:52 -0700103
Tim Douglasd3583a82018-12-30 13:18:54 -0500104 PID_TID_FILTER
105 FLAGS_FILTER
mcaleavya3c446c72016-04-29 13:38:51 +0100106 if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300107 val.id = id;
mcaleavya3c446c72016-04-29 13:38:51 +0100108 val.fname = filename;
Tim Douglasd3583a82018-12-30 13:18:54 -0500109 val.flags = flags; // EXTENDED_STRUCT_MEMBER
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300110 infotmp.update(&id, &val);
mcaleavya3c446c72016-04-29 13:38:51 +0100111 }
Brendan Greggbedd1502015-09-17 21:52:52 -0700112
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800113 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700114};
115
mcaleavya3c446c72016-04-29 13:38:51 +0100116int trace_return(struct pt_regs *ctx)
Brendan Greggbedd1502015-09-17 21:52:52 -0700117{
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300118 u64 id = bpf_get_current_pid_tgid();
mcaleavya3c446c72016-04-29 13:38:51 +0100119 struct val_t *valp;
120 struct data_t data = {};
Brendan Greggbedd1502015-09-17 21:52:52 -0700121
mcaleavya3c446c72016-04-29 13:38:51 +0100122 u64 tsp = bpf_ktime_get_ns();
123
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300124 valp = infotmp.lookup(&id);
mcaleavya3c446c72016-04-29 13:38:51 +0100125 if (valp == 0) {
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800126 // missed entry
127 return 0;
128 }
mcaleavya3c446c72016-04-29 13:38:51 +0100129 bpf_probe_read(&data.comm, sizeof(data.comm), valp->comm);
130 bpf_probe_read(&data.fname, sizeof(data.fname), (void *)valp->fname);
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300131 data.id = valp->id;
mcaleavya3c446c72016-04-29 13:38:51 +0100132 data.ts = tsp / 1000;
Tim Douglasd3583a82018-12-30 13:18:54 -0500133 data.flags = valp->flags; // EXTENDED_STRUCT_MEMBER
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530134 data.ret = PT_REGS_RC(ctx);
Brendan Greggbedd1502015-09-17 21:52:52 -0700135
mcaleavya3c446c72016-04-29 13:38:51 +0100136 events.perf_submit(ctx, &data, sizeof(data));
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300137 infotmp.delete(&id);
Brendan Greggbedd1502015-09-17 21:52:52 -0700138
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800139 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700140}
141"""
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300142if args.tid: # TID trumps PID
Tim Douglasd3583a82018-12-30 13:18:54 -0500143 bpf_text = bpf_text.replace('PID_TID_FILTER',
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300144 'if (tid != %s) { return 0; }' % args.tid)
145elif args.pid:
Tim Douglasd3583a82018-12-30 13:18:54 -0500146 bpf_text = bpf_text.replace('PID_TID_FILTER',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800147 'if (pid != %s) { return 0; }' % args.pid)
Brendan Greggbedd1502015-09-17 21:52:52 -0700148else:
Tim Douglasd3583a82018-12-30 13:18:54 -0500149 bpf_text = bpf_text.replace('PID_TID_FILTER', '')
150if args.flag_filter:
151 bpf_text = bpf_text.replace('FLAGS_FILTER',
152 'if (!(flags & %d)) { return 0; }' % flag_filter_mask)
153else:
154 bpf_text = bpf_text.replace('FLAGS_FILTER', '')
155if not (args.extended_fields or args.flag_filter):
156 bpf_text = '\n'.join(x for x in bpf_text.split('\n')
157 if 'EXTENDED_STRUCT_MEMBER' not in x)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100158if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800159 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100160 if args.ebpf:
161 exit()
Brendan Greggbedd1502015-09-17 21:52:52 -0700162
163# initialize BPF
164b = BPF(text=bpf_text)
Joel Fernandes9af548f2018-01-07 11:59:09 -0800165b.attach_kprobe(event="do_sys_open", fn_name="trace_entry")
166b.attach_kretprobe(event="do_sys_open", fn_name="trace_return")
mcaleavya3c446c72016-04-29 13:38:51 +0100167
168TASK_COMM_LEN = 16 # linux/sched.h
169NAME_MAX = 255 # linux/limits.h
170
171class Data(ct.Structure):
172 _fields_ = [
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300173 ("id", ct.c_ulonglong),
mcaleavya3c446c72016-04-29 13:38:51 +0100174 ("ts", ct.c_ulonglong),
mcaleavya3c446c72016-04-29 13:38:51 +0100175 ("ret", ct.c_int),
176 ("comm", ct.c_char * TASK_COMM_LEN),
Tim Douglasd3583a82018-12-30 13:18:54 -0500177 ("fname", ct.c_char * NAME_MAX),
178 ("flags", ct.c_int),
mcaleavya3c446c72016-04-29 13:38:51 +0100179 ]
180
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200181initial_ts = 0
Brendan Greggbedd1502015-09-17 21:52:52 -0700182
183# header
184if args.timestamp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800185 print("%-14s" % ("TIME(s)"), end="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500186print("%-6s %-16s %4s %3s " %
187 ("TID" if args.tid else "PID", "COMM", "FD", "ERR"), end="")
188if args.extended_fields:
189 print("%-9s" % ("FLAGS"), end="")
190print("PATH")
Brendan Greggbedd1502015-09-17 21:52:52 -0700191
mcaleavya3c446c72016-04-29 13:38:51 +0100192# process event
193def print_event(cpu, data, size):
194 event = ct.cast(data, ct.POINTER(Data)).contents
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200195 global initial_ts
Brendan Greggbedd1502015-09-17 21:52:52 -0700196
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800197 # split return value into FD and errno columns
mcaleavya3c446c72016-04-29 13:38:51 +0100198 if event.ret >= 0:
199 fd_s = event.ret
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800200 err = 0
201 else:
mcaleavya3c446c72016-04-29 13:38:51 +0100202 fd_s = -1
203 err = - event.ret
Brendan Greggbedd1502015-09-17 21:52:52 -0700204
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200205 if not initial_ts:
206 initial_ts = event.ts
mcaleavya3c446c72016-04-29 13:38:51 +0100207
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200208 if args.failed and (event.ret >= 0):
mcaleavya3c446c72016-04-29 13:38:51 +0100209 return
210
Gary Lin40fd6692018-02-12 16:51:14 +0800211 if args.name and bytes(args.name) not in event.comm:
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +0200212 return
213
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800214 if args.timestamp:
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200215 delta = event.ts - initial_ts
216 print("%-14.9f" % (float(delta) / 1000000), end="")
mcaleavya3c446c72016-04-29 13:38:51 +0100217
Tim Douglasd3583a82018-12-30 13:18:54 -0500218 print("%-6d %-16s %4d %3d " %
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300219 (event.id & 0xffffffff if args.tid else event.id >> 32,
Tim Douglasd3583a82018-12-30 13:18:54 -0500220 event.comm.decode('utf-8', 'replace'), fd_s, err), end="")
221
222 if args.extended_fields:
223 print("%08o " % event.flags, end="")
224
225 print(event.fname.decode('utf-8', 'replace'))
mcaleavya3c446c72016-04-29 13:38:51 +0100226
227# loop with callback to print_event
Mark Drayton5f5687e2017-02-20 18:13:03 +0000228b["events"].open_perf_buffer(print_event, page_cnt=64)
Paul Chaignon702de382018-01-28 13:41:35 +0100229start_time = datetime.now()
230while not args.duration or datetime.now() - start_time < args.duration:
Jerome Marchand51671272018-12-19 01:57:24 +0100231 try:
232 b.perf_buffer_poll()
233 except KeyboardInterrupt:
234 exit()