blob: d8d06d19fc6cf18a29996d4bfe55235cf4ba1da2 [file] [log] [blame]
Alexey Ivanov777e8022019-01-03 13:46:38 -08001#!/usr/bin/env 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
japrocaed9b1e2019-01-04 20:21:46 +030019from bcc.utils import printb
Brendan Greggbedd1502015-09-17 21:52:52 -070020import argparse
mcaleavya3c446c72016-04-29 13:38:51 +010021import ctypes as ct
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
Brendan Greggbedd1502015-09-17 21:52:52 -070029 ./opensnoop -x # only show failed opens
30 ./opensnoop -p 181 # only trace PID 181
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030031 ./opensnoop -t 123 # only trace TID 123
Paul Chaignon702de382018-01-28 13:41:35 +010032 ./opensnoop -d 10 # trace for 10 seconds only
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020033 ./opensnoop -n main # only print process names containing "main"
Tim Douglasd3583a82018-12-30 13:18:54 -050034 ./opensnoop -e # show extended fields
35 ./opensnoop -f O_WRONLY -f O_RDWR # only print calls for writing
Brendan Greggbedd1502015-09-17 21:52:52 -070036"""
37parser = argparse.ArgumentParser(
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080038 description="Trace open() syscalls",
39 formatter_class=argparse.RawDescriptionHelpFormatter,
40 epilog=examples)
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030041parser.add_argument("-T", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080042 help="include timestamp on output")
Brendan Greggbedd1502015-09-17 21:52:52 -070043parser.add_argument("-x", "--failed", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080044 help="only show failed opens")
Brendan Greggbedd1502015-09-17 21:52:52 -070045parser.add_argument("-p", "--pid",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080046 help="trace this PID only")
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030047parser.add_argument("-t", "--tid",
48 help="trace this TID only")
Paul Chaignon702de382018-01-28 13:41:35 +010049parser.add_argument("-d", "--duration",
50 help="total duration of trace in seconds")
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020051parser.add_argument("-n", "--name",
Gary Lin40fd6692018-02-12 16:51:14 +080052 type=ArgString,
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +020053 help="only print process names containing this name")
Nathan Scottcf0792f2018-02-02 16:56:50 +110054parser.add_argument("--ebpf", action="store_true",
55 help=argparse.SUPPRESS)
Tim Douglasd3583a82018-12-30 13:18:54 -050056parser.add_argument("-e", "--extended_fields", action="store_true",
57 help="show extended fields")
58parser.add_argument("-f", "--flag_filter", action="append",
59 help="filter on flags argument (e.g., O_WRONLY)")
Brendan Greggbedd1502015-09-17 21:52:52 -070060args = parser.parse_args()
61debug = 0
Paul Chaignon702de382018-01-28 13:41:35 +010062if args.duration:
63 args.duration = timedelta(seconds=int(args.duration))
Tim Douglasd3583a82018-12-30 13:18:54 -050064flag_filter_mask = 0
65for flag in args.flag_filter or []:
66 if not flag.startswith('O_'):
67 exit("Bad flag: %s" % flag)
68 try:
69 flag_filter_mask |= getattr(os, flag)
70 except AttributeError:
71 exit("Bad flag: %s" % flag)
Brendan Greggbedd1502015-09-17 21:52:52 -070072
73# define BPF program
74bpf_text = """
75#include <uapi/linux/ptrace.h>
mcaleavya3c446c72016-04-29 13:38:51 +010076#include <uapi/linux/limits.h>
77#include <linux/sched.h>
78
79struct val_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030080 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010081 char comm[TASK_COMM_LEN];
82 const char *fname;
Tim Douglasd3583a82018-12-30 13:18:54 -050083 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010084};
85
86struct data_t {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030087 u64 id;
mcaleavya3c446c72016-04-29 13:38:51 +010088 u64 ts;
mcaleavya3c446c72016-04-29 13:38:51 +010089 int ret;
90 char comm[TASK_COMM_LEN];
91 char fname[NAME_MAX];
Tim Douglasd3583a82018-12-30 13:18:54 -050092 int flags; // EXTENDED_STRUCT_MEMBER
mcaleavya3c446c72016-04-29 13:38:51 +010093};
Brendan Greggbedd1502015-09-17 21:52:52 -070094
Dina Goldshtein99a3bc82016-10-10 21:37:36 +030095BPF_HASH(infotmp, u64, struct val_t);
mcaleavya3c446c72016-04-29 13:38:51 +010096BPF_PERF_OUTPUT(events);
Brendan Greggbedd1502015-09-17 21:52:52 -070097
Tim Douglasd3583a82018-12-30 13:18:54 -050098int trace_entry(struct pt_regs *ctx, int dfd, const char __user *filename, int flags)
Brendan Greggbedd1502015-09-17 21:52:52 -070099{
mcaleavya3c446c72016-04-29 13:38:51 +0100100 struct val_t val = {};
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300101 u64 id = bpf_get_current_pid_tgid();
102 u32 pid = id >> 32; // PID is higher part
103 u32 tid = id; // Cast and get the lower part
Brendan Greggbedd1502015-09-17 21:52:52 -0700104
Tim Douglasd3583a82018-12-30 13:18:54 -0500105 PID_TID_FILTER
106 FLAGS_FILTER
mcaleavya3c446c72016-04-29 13:38:51 +0100107 if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) {
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300108 val.id = id;
mcaleavya3c446c72016-04-29 13:38:51 +0100109 val.fname = filename;
Tim Douglasd3583a82018-12-30 13:18:54 -0500110 val.flags = flags; // EXTENDED_STRUCT_MEMBER
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300111 infotmp.update(&id, &val);
mcaleavya3c446c72016-04-29 13:38:51 +0100112 }
Brendan Greggbedd1502015-09-17 21:52:52 -0700113
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800114 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700115};
116
mcaleavya3c446c72016-04-29 13:38:51 +0100117int trace_return(struct pt_regs *ctx)
Brendan Greggbedd1502015-09-17 21:52:52 -0700118{
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300119 u64 id = bpf_get_current_pid_tgid();
mcaleavya3c446c72016-04-29 13:38:51 +0100120 struct val_t *valp;
121 struct data_t data = {};
Brendan Greggbedd1502015-09-17 21:52:52 -0700122
mcaleavya3c446c72016-04-29 13:38:51 +0100123 u64 tsp = bpf_ktime_get_ns();
124
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300125 valp = infotmp.lookup(&id);
mcaleavya3c446c72016-04-29 13:38:51 +0100126 if (valp == 0) {
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800127 // missed entry
128 return 0;
129 }
mcaleavya3c446c72016-04-29 13:38:51 +0100130 bpf_probe_read(&data.comm, sizeof(data.comm), valp->comm);
131 bpf_probe_read(&data.fname, sizeof(data.fname), (void *)valp->fname);
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300132 data.id = valp->id;
mcaleavya3c446c72016-04-29 13:38:51 +0100133 data.ts = tsp / 1000;
Tim Douglasd3583a82018-12-30 13:18:54 -0500134 data.flags = valp->flags; // EXTENDED_STRUCT_MEMBER
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530135 data.ret = PT_REGS_RC(ctx);
Brendan Greggbedd1502015-09-17 21:52:52 -0700136
mcaleavya3c446c72016-04-29 13:38:51 +0100137 events.perf_submit(ctx, &data, sizeof(data));
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300138 infotmp.delete(&id);
Brendan Greggbedd1502015-09-17 21:52:52 -0700139
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800140 return 0;
Brendan Greggbedd1502015-09-17 21:52:52 -0700141}
142"""
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300143if args.tid: # TID trumps PID
Tim Douglasd3583a82018-12-30 13:18:54 -0500144 bpf_text = bpf_text.replace('PID_TID_FILTER',
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300145 'if (tid != %s) { return 0; }' % args.tid)
146elif args.pid:
Tim Douglasd3583a82018-12-30 13:18:54 -0500147 bpf_text = bpf_text.replace('PID_TID_FILTER',
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800148 'if (pid != %s) { return 0; }' % args.pid)
Brendan Greggbedd1502015-09-17 21:52:52 -0700149else:
Tim Douglasd3583a82018-12-30 13:18:54 -0500150 bpf_text = bpf_text.replace('PID_TID_FILTER', '')
151if args.flag_filter:
152 bpf_text = bpf_text.replace('FLAGS_FILTER',
153 'if (!(flags & %d)) { return 0; }' % flag_filter_mask)
154else:
155 bpf_text = bpf_text.replace('FLAGS_FILTER', '')
156if not (args.extended_fields or args.flag_filter):
157 bpf_text = '\n'.join(x for x in bpf_text.split('\n')
158 if 'EXTENDED_STRUCT_MEMBER' not in x)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100159if debug or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800160 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100161 if args.ebpf:
162 exit()
Brendan Greggbedd1502015-09-17 21:52:52 -0700163
164# initialize BPF
165b = BPF(text=bpf_text)
Joel Fernandes9af548f2018-01-07 11:59:09 -0800166b.attach_kprobe(event="do_sys_open", fn_name="trace_entry")
167b.attach_kretprobe(event="do_sys_open", fn_name="trace_return")
mcaleavya3c446c72016-04-29 13:38:51 +0100168
169TASK_COMM_LEN = 16 # linux/sched.h
170NAME_MAX = 255 # linux/limits.h
171
172class Data(ct.Structure):
173 _fields_ = [
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300174 ("id", ct.c_ulonglong),
mcaleavya3c446c72016-04-29 13:38:51 +0100175 ("ts", ct.c_ulonglong),
mcaleavya3c446c72016-04-29 13:38:51 +0100176 ("ret", ct.c_int),
177 ("comm", ct.c_char * TASK_COMM_LEN),
Tim Douglasd3583a82018-12-30 13:18:54 -0500178 ("fname", ct.c_char * NAME_MAX),
179 ("flags", ct.c_int),
mcaleavya3c446c72016-04-29 13:38:51 +0100180 ]
181
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200182initial_ts = 0
Brendan Greggbedd1502015-09-17 21:52:52 -0700183
184# header
185if args.timestamp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800186 print("%-14s" % ("TIME(s)"), end="")
Tim Douglasd3583a82018-12-30 13:18:54 -0500187print("%-6s %-16s %4s %3s " %
188 ("TID" if args.tid else "PID", "COMM", "FD", "ERR"), end="")
189if args.extended_fields:
190 print("%-9s" % ("FLAGS"), end="")
191print("PATH")
Brendan Greggbedd1502015-09-17 21:52:52 -0700192
mcaleavya3c446c72016-04-29 13:38:51 +0100193# process event
194def print_event(cpu, data, size):
195 event = ct.cast(data, ct.POINTER(Data)).contents
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200196 global initial_ts
Brendan Greggbedd1502015-09-17 21:52:52 -0700197
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800198 # split return value into FD and errno columns
mcaleavya3c446c72016-04-29 13:38:51 +0100199 if event.ret >= 0:
200 fd_s = event.ret
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800201 err = 0
202 else:
mcaleavya3c446c72016-04-29 13:38:51 +0100203 fd_s = -1
204 err = - event.ret
Brendan Greggbedd1502015-09-17 21:52:52 -0700205
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200206 if not initial_ts:
207 initial_ts = event.ts
mcaleavya3c446c72016-04-29 13:38:51 +0100208
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200209 if args.failed and (event.ret >= 0):
mcaleavya3c446c72016-04-29 13:38:51 +0100210 return
211
Gary Lin40fd6692018-02-12 16:51:14 +0800212 if args.name and bytes(args.name) not in event.comm:
KarimAllah Ahmed765dfe22016-09-10 12:01:07 +0200213 return
214
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800215 if args.timestamp:
KarimAllah Ahmeda17d1e82016-09-10 12:00:32 +0200216 delta = event.ts - initial_ts
217 print("%-14.9f" % (float(delta) / 1000000), end="")
mcaleavya3c446c72016-04-29 13:38:51 +0100218
Tim Douglasd3583a82018-12-30 13:18:54 -0500219 print("%-6d %-16s %4d %3d " %
Dina Goldshtein99a3bc82016-10-10 21:37:36 +0300220 (event.id & 0xffffffff if args.tid else event.id >> 32,
Tim Douglasd3583a82018-12-30 13:18:54 -0500221 event.comm.decode('utf-8', 'replace'), fd_s, err), end="")
222
223 if args.extended_fields:
224 print("%08o " % event.flags, end="")
225
japrocaed9b1e2019-01-04 20:21:46 +0300226 printb(b'%s' % event.fname.decode('utf-8', 'replace'))
mcaleavya3c446c72016-04-29 13:38:51 +0100227
228# loop with callback to print_event
Mark Drayton5f5687e2017-02-20 18:13:03 +0000229b["events"].open_perf_buffer(print_event, page_cnt=64)
Paul Chaignon702de382018-01-28 13:41:35 +0100230start_time = datetime.now()
231while not args.duration or datetime.now() - start_time < args.duration:
Jerome Marchand51671272018-12-19 01:57:24 +0100232 try:
233 b.perf_buffer_poll()
234 except KeyboardInterrupt:
235 exit()