You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import (
"log""os""os/signal""syscall""github.com/cilium/ebpf/link""github.com/cilium/ebpf/rlimit"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang bpf sync.c -- -I../headersfuncmain() {
// Allow the current process to lock memory for eBPF resources.iferr:=rlimit.RemoveMemlock(); err!=nil {
log.Fatal(err)
}
// Load pre-compiled programs and maps into the kernel.objs:=bpfObjects{}
iferr:=loadBpfObjects(&objs, nil); err!=nil {
log.Fatalf("loading objects: %v", err)
}
deferobjs.Close()
// Open a tracepoint and attach the pre-compiled program. Each time// the kernel function enters, the program will increment the execution// counter by 1. The read loop below polls this map value once per// second.// The first two arguments are taken from the following pathname:// tracepoint/syscalls/sys_enter_synckp, err:=link.Tracepoint("syscalls", "sys_enter_sync", objs.SyscallEnterSync, nil)
iferr!=nil {
log.Fatalf("opening tracepoint: %s", err)
}
deferkp.Close()
log.Println("waiting ctrl-c for stop...")
stopper:=make(chan os.Signal, 1)
signal.Notify(stopper, os.Interrupt, syscall.SIGTERM)
<-stopper
}
程序员的世界里第一个程序永远是从hello world 开始. ebpf 也不例外.
在上一篇中讲过 ebpf 编程需要将 ebpf 代码编译成字节码(需要使用llvm编译), 不过在golang的世界里这个就比较简单了,都有比较成熟的实现,我们这里使用 cilium 出的ebpf库(https://github.com/cilium/ebpf), 主要是有cilium 这个宇宙最火的 ebpf项目背书, 稳定性+性能都有保证.
在这里我们就以系统每次调用 sync 的时候打印出, 本次sync被那个程序调用了并且统计调用的耗时为例.
首先我们编写ebpf部分的代码, 当sync 系统调用时打印当前进程的pid以及cmd
以上就是一个hello world版本的 ebpf 程序, 这里有几个新概念
后两个都数据 ebpf 的help function, 都可以在 https://man7.org/linux/man-pages/man7/bpf-helpers.7.html 中查找.
然后通过 go generate 来生成字节码
下面就来看下怎么在golang中加载上面的ebpf代码
完整代码参考 https://github.com/lzh2nix/go-ebpf-workshop/tree/main/helloworld
The text was updated successfully, but these errors were encountered: