我思故我在 – 笛卡尔
systemtap基于kprobes,可以非常方便的进行内核跟踪、性能分析,是系统程序员、架构师必备的工具。下面是systemtap在centos环境的使用总结,同样适用于redhat环境,如果想在其他linux发行版使用systemtap,可能环境安装过程相对来说更加麻烦一些。
systemtap本身需要安装systemtap-runtime、systemtap,centos发行版yum源有这两个rpm,直接yum安装即可。 另外systemtap的使用还需要内核环境的支持,需要安装与内核匹配的三个rpm包:kernel-devel、kernel-debuginfo、kernel-debuginfo-common,kernel-devel可以直接通过yum安装源,非常不幸的是centos yum安装源里面找不到kernel-debuginfo、kernel-debuginfo-common这两个rpm包,不过可以从 – centos debuginfo中找到这两个rpm包,直接下载下来手动安装即可,但是一定要注意这两个rpm包的版本号必须和内核版本号完全一致,包括小版本号,否则执行 systemtap脚本时非常有可能报错。
stp脚本基本由两种元素组成:探针、句柄,当我们跟踪的事件发生时,将触发我们定义的探针,并执行为这个探针定义的句柄,探针的定义以probe 关键字开头,探针的句柄包括在一对“{” 、“}”中。stp脚本基本上由基本块:probe event {statements}组成。和shell脚本一样,stp脚本开头通过语句 ”#!/usr/bin/stap“ 指定解释器的路径。
systemtap事件分为同步事件和异步事件,执行到内核指定位置代码时触发同步事件,systemtap可以探测的同步事件包括:
可以定义探针的异步事件包括:
句柄内部的语句和C语言语句类似,这里主要总结常用的systemtap 内置函数:
stap -r `uname -r` -e 'probe vfs.read {exit()}' -m simple
staprun simple.ko
stap -L 'kernel.function("vfs_read")'
#!/usr/bin/stap
probe begin
{
log("begin to probe")
}
probe syscall.pread.return
{
time = gettimeofday_us() - @entry(gettimeofday_us())
printf ("%d\n", time)
}
probe timer.ms(60000) # after 10 minutes
{
exit ()
}
probe end
{
log("end to probe")
}
enjoy the life !!!