Linux bpftrace学习笔记(持续更新)
清泛原创
图:BPF性能工具及其可见性
bpftrace安装请参考:bpftrace-install 。1、查看哪些程序(如head,tail)正在打开什么文件:
# bpftrace -e 'tracepoint:syscalls:sys_enter_open { printf("%s %s\n", comm, str(args->filename)); }'
Attaching 1 probe...
head /usr/lib/locale/locale-archive
head /usr/share/locale/locale.alias
head /usr/lib/locale/en_US.UTF-8/LC_CTYPE
head /usr/lib/locale/en_US.utf8/LC_CTYPE
head /usr/lib64/gconv/gconv-modules.cache
head /usr/lib/locale/locale-archive
head /usr/share/locale/locale.alias
head /usr/lib/locale/en_US.UTF-8/LC_CTYPE
head /usr/lib/locale/en_US.utf8/LC_CTYPE
head /usr/lib64/gconv/gconv-modules.cache
tail /usr/lib/locale/locale-archive
tail /usr/share/locale/locale.alias
tail /usr/lib/locale/en_US.UTF-8/LC_CTYPE
tail /usr/lib/locale/en_US.utf8/LC_CTYPE
tail /usr/lib64/gconv/gconv-modules.cache
[...]
2、列出与open系统调用相关的跟踪点函数名:
# bpftrace -l 'tracepoint:syscalls:sys_enter_open*'
tracepoint:syscalls:sys_enter_open_by_handle_at
tracepoint:syscalls:sys_enter_open
tracepoint:syscalls:sys_enter_openat
3、工具开始运行至Ctrl + C退出,这个时段各个open相关跟踪点调用次数,这个摘要信息是由BPF程序在内核中高效计算出来的:
# bpftrace -e 'tracepoint:syscalls:sys_enter_open* { @[probe] = count(); }'
Attaching 3 probes...
^C
@[tracepoint:syscalls:sys_enter_open]: 576
@[tracepoint:syscalls:sys_enter_openat]: 1260
4、自带现成的脚本工具(没有的话请安装 zypper in bpftrace-tools),跟踪每个系统调用开始及结束位置:
# /usr/share/bpftrace/tools/opensnoop.bt
Attaching 6 probes...
Tracing open syscalls... Hit Ctrl-C to end.
PID COMM FD ERR PATH
4235 head -1 2 tls/x86_64/x86_64/libc.so.6
4235 head -1 2 tls/x86_64/libc.so.6
4235 head -1 2 tls/x86_64/libc.so.6
4235 head -1 2 tls/libc.so.6
4235 head -1 2 x86_64/x86_64/libc.so.6
4235 head -1 2 x86_64/libc.so.6
4235 head -1 2 x86_64/libc.so.6
4235 head -1 2 libc.so.6
4235 head 3 0 /etc/ld.so.cache
4235 head 3 0 /lib64/libc.so.6
4235 head -1 2 /usr/lib/locale/locale-archive
4235 head 3 0 /usr/share/locale/locale.alias
4235 head -1 2 /usr/lib/locale/en_US.UTF-8/LC_CTYPE
[...]
脚本内容如下:
# cat /usr/share/bpftrace/tools/opensnoop.bt
#!/usr/bin/bpftrace
/*
* opensnoop Trace open() syscalls.
* For Linux, uses bpftrace and eBPF.
*
* Also a basic example of bpftrace.
*
* USAGE: opensnoop.bt
*
* This is a bpftrace version of the bcc tool of the same name.
*
* Copyright 2018 Netflix, Inc.
* Licensed under the Apache License, Version 2.0 (the "License")
*
* 08-Sep-2018 Brendan Gregg Created this.
*/
BEGIN
{
printf("Tracing open syscalls... Hit Ctrl-C to end.\n");
printf("%-6s %-16s %4s %3s %s\n", "PID", "COMM", "FD", "ERR", "PATH");
}
tracepoint:syscalls:sys_enter_open,
tracepoint:syscalls:sys_enter_openat
{
@filename[tid] = args->filename;
}
tracepoint:syscalls:sys_exit_open,
tracepoint:syscalls:sys_exit_openat
/@filename[tid]/
{
$ret = args->ret;
$fd = $ret > 0 ? $ret : -1;
$errno = $ret > 0 ? 0 : - $ret;
printf("%-6d %-16s %4d %3d %s\n", pid, comm, $fd, $errno,
str(@filename[tid]));
delete(@filename[tid]);
}
END
{
clear(@filename);
}
--End--