manager

package module
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 35 Imported by: 1

README

ebpfmanager

Go Reference Go-test

ebpfmanager 是面向 Linux 的 Go eBPF 管理库,fork 自 DataDog/ebpf-manager,并针对 eCapture 等调用方保留定制接口。本库直接依赖 cilium/ebpf,提供 eBPF 程序加载、探针挂载、Map 管理和事件读取的配置化封装。

主要能力包括:

  • 管理 kprobe/kretprobe、uprobe/uretprobe、tracepoint、raw tracepoint、TC、XDP、cgroup、socket、LSM、tracing 和 perf event 等探针。
  • 读取 perf buffer、ring buffer 事件,管理启动、停止和资源清理。
  • 编辑常量、指令和 Map 规格,替换 Map,配置程序路由、克隆程序和动态增删 hook。
  • 按选择器启用探针,并支持 Map、Program 和 Link pinning。

具体探针的可用性取决于 Linux 内核版本、内核配置、目标程序和运行权限。

依赖与安装

用途 要求
Go 开发 Go 1.26.0 或更新版本;完整依赖以 go.mod 为准
eBPF 加载 当前依赖 github.com/cilium/ebpf v0.22.0;运行需要 Linux 及相应 BPF 权限
编译示例和测试资产 clang、LLVM、make、C 编译器及 Linux 开发头文件;示例检查还使用 bpftool、iproute2、util-linux 和免密 sudo
示例资产生成 Makefile 通过 go run 调用 go.mod 中的 go-bindata,无需额外执行 go get -d 或全局安装

在应用的 Go module 中安装 v0.7.0:

go get github.com/gojue/ebpfmanager@v0.7.0

导入路径仍为 github.com/gojue/ebpfmanager,包名为 manager。

加载 eBPF 时建议先在具备 sudo 权限的 Linux 环境验证。bpffs 用于 pinning;不使用 pinning 的普通加载并不因此要求挂载 bpffs。tracepoint 和 tracefs 挂载路径需要可用的 tracefs;kprobe/uprobe 的 PMU 或 bpf_link 路径不普遍依赖 tracefs。挂载方式、符号查找和回退路径的具体要求应按实际探针配置判断。

快速开始

仓库中的示例包含 C 程序、Go 调用代码和 Makefile。例如,在 Linux 检出目录运行:

go mod download
make -C examples/programs/tracepoint

该命令会编译 eBPF、重新生成 probe.go、构建并以 sudo 运行示例。建议在一次性检出目录运行,避免覆盖正在编辑的生成文件。

Probe 配置

一个 Manager 可以管理多个 Probe。不要混淆 eBPF 函数名、ELF section 和被挂载的目标函数:

字段 含义
EbpfFuncName eBPF C 函数名,用于查找 ELF 中的程序,例如 tracepoint_sys_enter_mkdirat;不是 section 名
UID 可选标识,与 EbpfFuncName 共同组成 ProbeIdentificationPair,用于区分探针
Section 可选覆盖 ELF 程序的 section;未设置时使用 ELF 中的 section
AttachToFuncName 本 fork 保留的目标函数配置;kprobe 路径会尝试解析 syscall 前缀,uprobe 路径用于符号定位;不是所有探针的必填项
HookFuncName / SyscallFuncName / MatchFuncName 分别用于精确目标符号、syscall 名或匹配模式;HookFuncName 优先,详见 probe.go
BinaryPath uprobe/uretprobe 对应的用户态 ELF 路径
UAddress / UprobeOffset 调用方提供的 ELF 文件偏移,以及在其基础上增加的相对偏移;UAddress == 0 时先解析符号

UAddress 不是进程运行时虚拟地址,也不是未经换算的 ELF 虚拟地址。MatchFuncName 用来定位目标函数,不是 eBPF 程序表的索引。完整配置与兼容字段见 probe.go 和 compat.go。

在应用中加载对象文件

将以下代码保存为应用目录中的 main.go。它加载上述 tracepoint 示例产生的 probe.o,等待退出信号后清理探针:

package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/signal"
	"syscall"

	manager "github.com/gojue/ebpfmanager"
)

func main() {
	if len(os.Args) != 2 {
		log.Fatal("usage: tracepoint-demo /path/to/probe.o")
	}
	if err := run(os.Args[1]); err != nil {
		log.Fatal(err)
	}
}

func run(objectPath string) (err error) {
	object, err := os.Open(objectPath)
	if err != nil {
		return err
	}
	defer object.Close()

	m := &manager.Manager{
		Probes: []*manager.Probe{
			{
				Section:      "tracepoint/syscalls/sys_enter_mkdirat",
				EbpfFuncName: "tracepoint_sys_enter_mkdirat",
			},
		},
	}
	if err = m.InitWithOptions(object, manager.Options{RemoveRlimit: true}); err != nil {
		return err
	}
	defer func() {
		err = errors.Join(err, m.Stop(manager.CleanAll))
	}()

	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer cancel()
	if err = m.Start(); err != nil {
		return err
	}
	log.Print("probe attached; press Ctrl+C to stop")
	<-ctx.Done()
	return nil
}

在应用目录中构建并运行,将路径替换为实际生成的对象文件:

go build -o tracepoint-demo .
sudo ./tracepoint-demo /path/to/ebpfmanager/examples/programs/tracepoint/ebpf/bin/probe.o

本例的 C 程序通过 bpf_printk 输出到 tracefs 的 trace_pipe,Go 程序负责加载和生命周期管理。加载器接收 io.ReaderAt;除文件外,也可以使用 bytes.NewReader 加载嵌入的 eBPF 字节码。更多示例:

场景 示例目录
各种探针类型 examples/programs
探针选择器 activated_probes
指令修改、Map 规格编辑 instruction_patching、mapspec_editor
克隆程序与新增 hook clone_vs_add_hook
Map 替换与路由、程序路由 map_rewrite_vs_map_router、program_router
对象及 Link pinning object_pinning、link_pinning
Ring buffer、程序测试与基准 ringbuf_map、tests_and_benchmarks

上游同步与兼容性

v0.7.0 包含 PR #51 的上游同步,该 PR 于 2026-11-14 合入 master,合并提交为 6f15756。同步基线为 DataDog/ebpf-manager main 的 ecf203d。这是明确的同步快照,不表示持续自动跟随上游最新提交。前一次同步为本库 467114a3,对应上游 31843479。

核心实现、内部辅助包和测试跟随上游;模块路径、定制示例、kernel 包及下列调用约定保留,以兼容现有 eCapture 调用:

  • Probe 的平铺字段,以及 AttachToFuncName、UAddress、AttachPID、Ifname、Ifindex、IfindexNetns、SkipLoopback、LinkPinPath 等 fork 接口。
  • ConstantEditor 对符合条件的 BTF 全局常量自动选择编辑方式;保留汇编常量和回调编辑器。汇编常量值需要 uint64,具体条件见 constant_editor.go。
  • Options.RLimit、ExcludedEbpfFuncs、RingbufMaps、RingbufMapOptions、PerfMapStats、EditInnerMap 和公开的 Editor 接口。
  • DumpMaps 保留字符串返回值,流式接口为 DumpMapsTo;DetachHook 保留两个字符串参数,另提供 DetachHookByID。
  • NewMap / NewPerfRing 保留值参数,指针参数接口为 NewMapFromSpec / NewPerfRingFromSpec。
  • 默认保留程序指令,以兼容 CloneProgram。若启用 Options.DiscardProgramSpecs,需要克隆的探针应设置 KeepProgramSpec;没有关联 Probe 的程序还需考虑 KeepUnmappedProgramSpecs。

Map 替换使用 cilium 的独立 FD 引用,Manager 清理不会关闭调用方持有的原始 Map。旧 CleanExternal* 常量仍保留,清理以 Manager 持有的引用为准。MapOptions.Freeze 字段仅保留源码兼容性;需要冻结 Map 时,请对已加载的 *ebpf.Map 显式调用 Freeze()。

测试与 CI

库回归测试

在具有 BPF 权限和编译工具的 Linux 环境运行:

go mod download
C_INCLUDE_PATH="/usr/include/$(gcc -dumpmachine)${C_INCLUDE_PATH:+:$C_INCLUDE_PATH}" make -C testdata
go test -count=1 -race -exec 'sudo -n' ./...

涉及 pinning 的测试要求 bpffs;环境不满足时会明确跳过,跳过不等于该能力已验证。架构或工具链不支持 race detector 时,可运行不带 -race 的测试,但应单独说明验证范围。

示例构建与运行
bash examples/test.sh

该脚本依次执行当前 20 个示例的 Makefile:编译 eBPF、生成 probe.go、构建 Go 程序并运行。每个示例默认超时 180 秒,可通过 EXAMPLE_TIMEOUT 调整;构建、运行或超时返回非零时,脚本立即失败。

推荐在一次性 Linux 检出目录使用与 CI 相同的隔离入口:

bash .github/scripts/test-examples.sh

该入口先下载 Go 依赖,再在私有网络、挂载和 PID 命名空间中运行,使用专用 eth0、bpffs 和 /tmp,不会把 TC/XDP 探针挂到宿主机网卡。它不提供独立内核:kprobe、tracepoint 和 LSM 等仍作用于当前 Linux 内核。

示例检查是构建与运行的烟雾测试,不等同于完整业务断言:网络示例不检查 HTTP 成功,隔离环境中的外网请求会失败;LSM 示例在不支持时自行返回;tests_and_benchmarks 的 { Input:42 Output:128 } 是故意错误的演示输入,会打印 FAIL,但不代表脚本执行失败。

GitHub Actions

Go-test 工作流 在所有分支的 push、PR 更新及手动触发时运行:

Job 检查内容
build 根据 go.mod 设置 Go,构建测试资产,执行 go test -race -exec sudo ./...
examples 安装编译工具和可执行的 bpftool,通过隔离入口构建并运行全部示例

PR #51 最终提交的 PR 检查 和 push 检查 均通过;合并提交的 Go-test 也已通过。本仓库的 CI 不会自动执行 eCapture 的完整构建和 E2E。

eCapture 兼容性验证记录

2026-11-13 在 Linux ARM64 VM 和 LoongArch64 主机的隔离目录进行了下游验证。eCapture 基线为 6cac65fe2b60c2bbf3b27b3451d7611e28e88c30,manager 基线为 PR 开发阶段的 84822043e8e6696d9c5480f080e6de4c67814acc,并使用 v0.6.0 对照。只调整隔离副本中的库依赖,未修改 eCapture 调用代码。

两平台完成了 CO-RE、非 CO-RE、组合版的干净构建和启动检查,以及本库测试、eCapture 测试和生产标签 lint。下游 E2E 范围共 114 项:OpenSSL 27、GoTLS 52、GnuTLS 21、Bash/Zsh 3、CLI 11;不包含 Mysqld 和 PostgreSQL。

环境 组合版(该环境使用 CO-RE) 非 CO-RE
Linux ARM64 VM 114/114 114/114
Linux LoongArch64 主机 104/114 103/114

需要保留的结论边界:

  • 龙芯的 10 项 GnuTLS 失败在旧 manager 上也可复现。已确认 Debian 3.8.9-3+deb13u4 包回移补丁,使私有结构中 TLS 1.3 密钥偏移增加 264 字节;这不是本次 manager 升级或 bpffs 引起的问题。仅修改隔离 eCapture 副本的偏移后,CO-RE 和非 CO-RE 的 GnuTLS 21/21 均通过;该诊断补丁不属于 PR #51,不能据此将原版完整 E2E 改记为全部通过。
  • 龙芯非 CO-RE 另有一项 OpenSSL 进程参数元数据断言失败,旧 manager 同样可复现。构建头文件与运行内核不同,结果不能推广为跨内核普遍兼容。
  • GoTLS 首轮出现过一次 WebSocket 事件缺失,旧版与 PR 各重复 10 次通过,完整套件复测通过;表中结果包含复测,不代表最初一次运行全部成功。
  • 龙芯两项 pinning 回归因环境无法挂载 bpffs 而跳过;它们不属于上述 114 项,也没有阻止 GnuTLS E2E 执行。ARM64 对应 pinning 测试通过。
  • 这轮下游全量验证早于最终提交中的依赖更新及提交压缩,未在合并提交上重新执行。最终依赖版本已通过本库 CI 和 ARM64 的 20 个示例;不能将这些结果等同于重新跑过 eCapture 全量 E2E。

本轮没有要求 eCapture 修改调用接口;Android、所有最低内核版本及所有发行版 TLS 库布局不在此次完整验证范围内。

使用项目

  • eCapture:基于 eBPF 的 TLS 明文与密钥捕获工具。
  • eHIDS-Agent:基于 eBPF 的主机入侵检测 Agent。

许可证与致谢

本仓库许可证见 LICENSE(Apache-2.0);导入的 DataDog 代码保留 LICENSE.upstream 中的 MIT 许可证声明。其他文件已有的版权和许可证声明应一并保留。

感谢 JetBrains 提供 All Products Pack IDE 使用授权。

Documentation

Index

Examples

Constants

View Source
const (
	UnknownProbeType = ""
	ProbeType        = "p"
	RetProbeType     = "r"
)
View Source
const (
	AttachKprobeMethodNotSet      = AttachMethodNotSet
	AttachKprobeWithPerfEventOpen = AttachWithPerfEventOpen
	AttachKprobeWithKprobeEvents  = AttachWithProbeEvents
)
View Source
const (
	CleanInternalPinned          MapCleanupType = 1 << 1
	CleanInternalNotPinned       MapCleanupType = 1 << 2
	CleanInternal                               = CleanInternalPinned | CleanInternalNotPinned
	CleanExternalPinned          MapCleanupType = 1 << 3
	CleanExternalPinnedAndEdited MapCleanupType = 1 << 4
	CleanExternalEdited          MapCleanupType = 1 << 5
	CleanExternal                               = CleanExternalPinned | CleanExternalPinnedAndEdited | CleanExternalEdited
	CleanAll                                    = CleanInternal | CleanExternal
)
View Source
const (
	// DefaultTCFilterPriority is the default TC filter priority if none were given
	DefaultTCFilterPriority = 50

	Ingress = TrafficType(uint16(netlink.HANDLE_MIN_INGRESS & 0x0000FFFF))
	Egress  = TrafficType(uint16(netlink.HANDLE_MIN_EGRESS & 0x0000FFFF))
)

Variables

View Source
var (
	ErrUnknownMatchFuncName = ErrUnknownSectionOrFuncName
	ErrUnknownMatchFuncSpec = ErrUnknownSectionOrFuncName
	ErrUnknownMap           = ErrUnknownSection
	ErrLoopbackDisabled     = errors.New("loopback is disabled")
)
View Source
var (
	ErrManagerNotInitialized    = errors.New("the manager must be initialized first")
	ErrManagerNotStarted        = errors.New("the manager must be started first")
	ErrManagerNotELFLoaded      = errors.New("the manager has not loaded the ELF data")
	ErrManagerELFLoaded         = errors.New("the manager has already loaded the ELF data")
	ErrManagerRunning           = errors.New("the manager is already running")
	ErrUnknownSection           = errors.New("unknown section")
	ErrUnknownSectionOrFuncName = errors.New("unknown section or eBPF function name")
	ErrPinnedObjectNotFound     = errors.New("pinned object not found")
	ErrMapNameInUse             = errors.New("the provided map name is already taken")
	ErrIdentificationPairInUse  = errors.New("the provided identification pair already exists")
	ErrProbeNotInitialized      = errors.New("the probe must be initialized first")
	ErrProbeRunning             = errors.New("the probe is already running")
	ErrSectionFormat            = errors.New("invalid section format")
	ErrSymbolNotFound           = errors.New("symbol not found")
	ErrProbeIDNotExist          = errors.New("probe id file doesn't exist")
	ErrKProbeHookPointNotExist  = errors.New("the kprobe hook point doesn't exist")
	ErrCloneProbeRequired       = errors.New("use CloneProbe to load 2 instances of the same program")
	ErrInterfaceNotSet          = errors.New("interface not provided: at least one of IfIndex and IfName must be set")
	ErrMapInitialized           = errors.New("map already initialized")
	ErrMapNotInitialized        = errors.New("the map must be initialized first")
	ErrMapNotRunning            = errors.New("the map is not running")
	ErrNotSupported             = errors.New("not supported")
	ErrNoNetworkDirection       = errors.New("a valid network direction is required to attach a TC classifier")
	ErrMissingEditorFlags       = errors.New("missing editor flags in map editor")
)
View Source
var (
	ErrRingbufNotSupported = errors.New("ringbuf is not supported on this kernel, need kernel version >= 5.8.0")
	ErrLSMNotSupported     = errors.New("LSM is not supported on this kernel, need kernel version >= 5.7.0")
)
View Source
var TraceFSLock sync.Mutex

TraceFSLock is used to synchronize access to the tracefs events files, preventing some issues with concurrent access to it, that can cause some kernel crashes.

Functions

func ConcatErrors

func ConcatErrors(a, b error) error

func FindFilterFunction

func FindFilterFunction(funcName string) (string, error)

func FindSymbolOffsets

func FindSymbolOffsets(path string, pattern *regexp.Regexp) ([]elf.Symbol, error)

func GenerateEventName

func GenerateEventName(probeType, funcName, uid string, pid int) (string, error)

func GetSyscallFnName

func GetSyscallFnName(name string) (string, error)

func GetSyscallFnNameWithSymFile

func GetSyscallFnNameWithSymFile(name, symFile string) (string, error)

GetSyscallFnNameWithSymFile preserves exact kernel symbols before applying architecture-specific syscall prefixes. Both "open" and "sys_open" are accepted.

func GetTracepointID added in v0.7.0

func GetTracepointID(category, name string) (int, error)

GetTracepointID - Returns a tracepoint ID from its category and name

func Getpid added in v0.7.0

func Getpid() int

Getpid returns the current process ID in the host namespace if $HOST_PROC is defined, the pid in the current namespace otherwise

func IsUnreferencedSymbol

func IsUnreferencedSymbol(err error) bool

func OpenAndListSymbols

func OpenAndListSymbols(path string) (*elf.File, []elf.Symbol, error)

OpenAndListSymbols - Opens an elf file and extracts all its symbols

func SanitizeUprobeAddresses

func SanitizeUprobeAddresses(f *elf.File, syms []elf.Symbol)

SanitizeUprobeAddresses - sanitizes the addresses of the provided symbols

func TracefsOpen added in v0.5.0

func TracefsOpen(name string) (*os.File, error)

func TracefsOpenFile added in v0.5.0

func TracefsOpenFile(name string, flags int, mode os.FileMode) (*os.File, error)

func TracefsReadFile added in v0.5.0

func TracefsReadFile(name string) ([]byte, error)

func TracefsRoot added in v0.5.0

func TracefsRoot() (string, error)

Types

type AllOf

type AllOf struct {
	Selectors []ProbesSelector
}

AllOf - This selector is used to ensure that all the proves in the provided list are running.

func (*AllOf) EditProbeIdentificationPair

func (ao *AllOf) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they now select the new one

func (*AllOf) GetProbesIdentificationPairList

func (ao *AllOf) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*AllOf) RunValidator

func (ao *AllOf) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

func (*AllOf) String

func (ao *AllOf) String() string

type AttachMethod added in v0.7.0

type AttachMethod uint32
const (
	AttachMethodNotSet AttachMethod = iota
	AttachWithPerfEventOpen
	AttachWithProbeEvents
)

type BestEffort

type BestEffort struct {
	Selectors []ProbesSelector
}

BestEffort - This selector is used to load probes in the best effort mode

func (*BestEffort) EditProbeIdentificationPair

func (be *BestEffort) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they now select the new one

func (*BestEffort) GetProbesIdentificationPairList

func (be *BestEffort) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*BestEffort) RunValidator

func (be *BestEffort) RunValidator(_ *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

func (*BestEffort) String

func (be *BestEffort) String() string

type ConstantEditor

type ConstantEditor struct {
	// Name - Name of the constant to rewrite
	Name string

	// Value - Value to write in the eBPF bytecode. When using the asm load method, the Value has to be a `uint64`.
	Value interface{}

	// ValueCallback - Called to get the value to write in the eBPF bytecode
	ValueCallback func(prog *ebpf.ProgramSpec) interface{}

	// FailOnMissing - If FailOMissing is set to true, the constant edition process will return an error if the constant
	// was missing in at least one program
	FailOnMissing bool

	// BTFGlobalConstant - Indicates if the constant is a BTF global constant.
	BTFGlobalConstant bool

	// ProbeIdentificationPairs - Identifies the list of programs to edit. If empty, it will apply to all the programs
	// of the manager. Will return an error if at least one edition failed.
	ProbeIdentificationPairs []ProbeIdentificationPair
}

ConstantEditor - A constant editor tries to rewrite the value of a constant in a compiled eBPF program.

Constant edition only works before the eBPF programs are loaded in the kernel, and therefore before the Manager is started. If no program sections are provided, the manager will try to edit the constant in all eBPF programs.

func (*ConstantEditor) GetValue added in v0.7.0

func (ce *ConstantEditor) GetValue(prog *ebpf.ProgramSpec) interface{}

type Editor

type Editor = editor

Editor retains the exported instruction editor API of the fork.

Example (RewriteConstant)

ExampleEditor_rewriteConstant shows how to change constants in compiled eBPF byte code.

The C should look something like this:

#define LOAD_CONSTANT(param, var) asm("%0 = " param " ll" : "=r"(var))

int xdp() {
    bool my_constant;
    LOAD_CONSTANT("SYMBOL_NAME", my_constant);

    if (my_constant) ...
// This assembly is roughly equivalent to what clang
// would emit for the C above.
insns := asm.Instructions{
	asm.LoadImm(asm.R0, 0, asm.DWord).WithReference("my_ret"),
	asm.Return(),
}

editor := Edit(&insns)
if err := editor.RewriteConstant("my_ret", 42); err != nil {
	panic(err)
}

fmt.Printf("%0.0s", insns)
Output:
0: LdImmDW dst: r0 imm: 42 <my_ret>
2: Exit

func Edit

func Edit(insns *asm.Instructions) *Editor

type FunctionExcluder added in v0.7.0

type FunctionExcluder interface {
	// ShouldExcludeFunction - Returns true if the function should be excluded
	ShouldExcludeFunction(name string, prog *ebpf.ProgramSpec) bool
	// CleanCaches - Is called when the manager is done with the excluder (for memory reclaiming for example)
	CleanCaches()
}

FunctionExcluder - An interface for types that can be used for `AdditionalExcludedFunctionCollector`

type InnerOuterMapSpec added in v0.7.0

type InnerOuterMapSpec struct {
	// OuterMapName - Name of the BPF_MAP_TYPE_ARRAY_OF_MAPS or BPF_MAP_TYPE_HASH_OF_MAPS map, as defined in its
	// section SEC("maps/[OuterMapName]")
	OuterMapName string

	// InnerMapName - Name of the inner map of the provided outer map, as defined in its section SEC("maps/[InnerMapName]")
	InnerMapName string
}

InnerOuterMapSpec - An InnerOuterMapSpec defines the map that should be used as the inner map of the provided outer map.

type InstructionPatcherFunc added in v0.4.5

type InstructionPatcherFunc func(m *Manager) error

InstructionPatcherFunc - A function that patches the instructions of a program

type KprobeAttachMethod added in v0.7.0

type KprobeAttachMethod = AttachMethod

type Manager

type Manager struct {

	// Probes - List of probes handled by the manager
	Probes []*Probe

	// Maps - List of maps handled by the manager. PerfMaps should not be defined here, but instead in the PerfMaps
	// section
	Maps []*Map

	// PerfMaps - List of perf ring buffers handled by the manager
	PerfMaps []*PerfMap

	// RingBuffers - List of perf ring buffers handled by the manager
	RingBuffers []*RingbufMap
	RingbufMaps []*RingbufMap

	// DumpHandler - Callback function called when manager.DumpMaps() is called
	// and dump the current state (human-readable)
	DumpHandler func(w io.Writer, manager *Manager, mapName string, currentMap *ebpf.Map)

	// InstructionPatchers - Callback functions called before loading probes, to
	// provide user the ability to perform last minute instruction patching.
	InstructionPatchers []InstructionPatcherFunc
	// contains filtered or unexported fields
}

Manager - Helper structure that manages multiple eBPF programs and maps

func (*Manager) AddHook

func (m *Manager) AddHook(UID string, newProbe *Probe) error

AddHook - Hook an existing program to a hook point. This is particularly useful when you need to trigger an existing program on a hook point that is determined at runtime. For example, you might want to hook an existing eBPF TC classifier to the newly created interface of a container. Make sure to specify a unique uid in the new probe, you will need it if you want to detach the program later. The original program is selected using the provided UID, the section and the eBPF function name provided in the new probe.

func (*Manager) CleanupNetworkNamespace added in v0.7.0

func (m *Manager) CleanupNetworkNamespace(nsID uint32) error

CleanupNetworkNamespace - Cleans up all references to the provided network namespace within the manager. This means that any TC classifier or XDP probe in that network namespace will be stopped and all opened netlink socket in that namespace will be closed. WARNING: Don't forget to call this method if you've provided a IfIndexNetns and IfIndexNetnsID to one of the probes of this manager. Failing to call this cleanup function may lead to leaking the network namespace. Only call this function when you're sure that the manager no longer needs to perform anything in the provided network namespace (or else call NewNetlinkSocket first).

func (*Manager) CloneMap

func (m *Manager) CloneMap(name string, newName string, options MapOptions) (*ebpf.Map, error)

CloneMap - Duplicates the spec of an existing map, before creating a new one. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) ClonePerfRing

func (m *Manager) ClonePerfRing(name string, newName string, options MapOptions, perfMapOptions PerfMapOptions) (*ebpf.Map, error)

ClonePerfRing - Clone an existing perf map and create a new one with the same spec. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) CloneProgram

func (m *Manager) CloneProgram(UID string, newProbe *Probe, constantsEditors []ConstantEditor, mapEditors map[string]*ebpf.Map) error

CloneProgram - Create a clone of a program, load it in the kernel and attach it to its hook point. Since the eBPF program instructions are copied before the program is loaded, you can edit them with a ConstantEditor, or remap the eBPF maps as you like. This is particularly useful to work around the absence of Array of Maps and Hash of Maps: first create the new maps you need, then clone the program you're interested in and rewrite it with the new maps, using a MapEditor. The original program is selected using the provided UID and the section provided in the new probe. Note that the BTF based constant edition will not work with this method.

func (*Manager) CloneProgramWithSpecEditor added in v0.7.0

func (m *Manager) CloneProgramWithSpecEditor(UID string, newProbe *Probe, constantsEditors []ConstantEditor, mapEditors map[string]*ebpf.Map, specEditor func(spec *ebpf.ProgramSpec)) error

CloneProgramWithSpecEditor - does the same thing as CloneProgram, but allows to intercept the new program spec before the probe is initialized. This is useful for example to clone an fentry probe, and edit the AttachTo field before the init of the new probe.

func (*Manager) DetachHook

func (m *Manager) DetachHook(ebpfFuncName, uid string) error

func (*Manager) DetachHookByID added in v0.7.0

func (m *Manager) DetachHookByID(id ProbeIdentificationPair) error

DetachHook - Detach an eBPF program from a hook point. If there is only one instance left of this program in the kernel, then the probe will be detached but the program will not be closed (so that it can be used later). In that case, calling DetachHook has essentially the same effect as calling Detach() on the right Probe instance. However, if there are more than one instance in the kernel of the requested program, then the probe selected by the provided ProbeIdentificationPair is detached, and its own handle of the program is closed.

func (*Manager) DumpMaps

func (m *Manager) DumpMaps(maps ...string) (string, error)

func (*Manager) DumpMapsTo added in v0.7.0

func (m *Manager) DumpMapsTo(w io.Writer, maps ...string) error

DumpMaps - Write in the w writer argument human-readable info about eBPF maps Dumps the set of maps provided, otherwise dumping all maps with a DumpHandler set.

func (*Manager) GetMap

func (m *Manager) GetMap(name string) (*ebpf.Map, bool, error)

GetMap - Return a pointer to the requested eBPF map name: name of the map, as defined by its section SEC("maps/[name]")

func (*Manager) GetMapSpec

func (m *Manager) GetMapSpec(name string) (*ebpf.MapSpec, bool, error)

GetMapSpec - Return a pointer to the requested eBPF MapSpec. This is useful when duplicating a map.

func (*Manager) GetMapSpecs added in v0.7.0

func (m *Manager) GetMapSpecs() (map[string]*ebpf.MapSpec, error)

GetMapSpecs - Return the list of eBPF map specs in the manager

func (*Manager) GetMaps added in v0.7.0

func (m *Manager) GetMaps() (map[string]*ebpf.Map, error)

GetMaps - Return the list of eBPF maps in the manager

func (*Manager) GetNetlinkSocket added in v0.7.0

func (m *Manager) GetNetlinkSocket(nsHandle uint64, nsID uint32) (*NetlinkSocket, error)

func (*Manager) GetPerfMap

func (m *Manager) GetPerfMap(name string) (*PerfMap, bool)

GetPerfMap - Select a perf map by its name

func (*Manager) GetProbe

func (m *Manager) GetProbe(id ProbeIdentificationPair) (*Probe, bool)

GetProbe - Select a probe by its section and UID

func (*Manager) GetProbes added in v0.7.0

func (m *Manager) GetProbes() []*Probe

GetProbes returns a copy of the Probes list

func (*Manager) GetProgram

func (m *Manager) GetProgram(id ProbeIdentificationPair) ([]*ebpf.Program, bool, error)

GetProgram - Return a pointer to the requested eBPF program section: section of the program, as defined by its section SEC("[section]") id: unique identifier given to a probe. If UID is empty, then all the programs matching the provided section are returned.

func (*Manager) GetProgramSpec

func (m *Manager) GetProgramSpec(id ProbeIdentificationPair) ([]*ebpf.ProgramSpec, bool, error)

GetProgramSpec - Return a pointer to the requested eBPF program spec section: section of the program, as defined by its section SEC("[section]") id: unique identifier given to a probe. If UID is empty, then the original program spec with the right section in the collection spec (if found) is return

func (*Manager) GetProgramSpecs added in v0.7.0

func (m *Manager) GetProgramSpecs() (map[string]*ebpf.ProgramSpec, error)

GetProgramSpecs - Return the list of eBPF program specs in the manager

func (*Manager) GetPrograms added in v0.7.0

func (m *Manager) GetPrograms() (map[string]*ebpf.Program, error)

GetPrograms - Return the list of eBPF programs in the manager

func (*Manager) GetRingBuffer added in v0.7.0

func (m *Manager) GetRingBuffer(name string) (*RingbufMap, bool)

GetRingBuffer - Select a ring buffer by its name

func (*Manager) Init

func (m *Manager) Init(elf io.ReaderAt) error

Init - Initialize the manager. elf: reader containing the eBPF bytecode, must be nil if LoadELF already called

func (*Manager) InitWithOptions

func (m *Manager) InitWithOptions(elf io.ReaderAt, options Options) error

InitWithOptions - Initialize the manager. elf: reader containing the eBPF bytecode, must be nil if LoadELF already called options: options provided to the manager to configure its initialization

func (*Manager) LoadELF added in v0.7.0

func (m *Manager) LoadELF(elf io.ReaderAt) error

LoadELF loads the collection spec from the provided ELF reader

func (*Manager) NewMap

func (m *Manager) NewMap(spec ebpf.MapSpec, options MapOptions) (*ebpf.Map, error)

func (*Manager) NewMapFromSpec added in v0.7.0

func (m *Manager) NewMapFromSpec(spec *ebpf.MapSpec, options MapOptions) (*ebpf.Map, error)

NewMap - Create a new map using the provided parameters. The map is added to the list of maps managed by the manager. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) NewPerfRing

func (m *Manager) NewPerfRing(spec ebpf.MapSpec, options MapOptions, perfOptions PerfMapOptions) (*ebpf.Map, error)

func (*Manager) NewPerfRingFromSpec added in v0.7.0

func (m *Manager) NewPerfRingFromSpec(spec *ebpf.MapSpec, options MapOptions, perfMapOptions PerfMapOptions) (*ebpf.Map, error)

NewPerfRing - Creates a new perf ring and start listening for events. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) NewRingBuffer added in v0.7.0

func (m *Manager) NewRingBuffer(spec *ebpf.MapSpec, options MapOptions, ringBufferOptions RingbufMapOptions) (*ebpf.Map, error)

NewRingBuffer - Creates a new ring buffer and start listening for events. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) Pause added in v0.7.0

func (m *Manager) Pause() error

func (*Manager) RenameProbeIdentificationPair added in v0.7.0

func (m *Manager) RenameProbeIdentificationPair(oldID ProbeIdentificationPair, newID ProbeIdentificationPair) error

RenameProbeIdentificationPair - Renames a probe identification pair. This change will propagate to all the features in the manager that will try to select the probe by its old ProbeIdentificationPair.

func (*Manager) Resume added in v0.7.0

func (m *Manager) Resume() error

func (*Manager) Start

func (m *Manager) Start() error

Start - Attach eBPF programs, start perf ring readers and apply maps and tail calls routing.

func (*Manager) Stop

func (m *Manager) Stop(cleanup MapCleanupType) error

Stop - Detach all eBPF programs and stop perf ring readers. The cleanup parameter defines which maps should be closed. See MapCleanupType for mode.

func (*Manager) StopReaders added in v0.7.0

func (m *Manager) StopReaders(cleanup MapCleanupType) error

StopReaders - Stop the kernel events readers Perf or Ring buffer.

func (*Manager) UpdateActivatedProbes

func (m *Manager) UpdateActivatedProbes(selectors []ProbesSelector) error

UpdateActivatedProbes - update the list of activated probes

func (*Manager) UpdateMapRoutes

func (m *Manager) UpdateMapRoutes(router ...MapRoute) error

UpdateMapRoutes - Update one or multiple map of maps structures so that the provided keys point to the provided maps.

func (*Manager) UpdateTailCallRoutes

func (m *Manager) UpdateTailCallRoutes(router ...TailCallRoute) error

UpdateTailCallRoutes - Update one or multiple program arrays so that the provided keys point to the provided programs.

type Map

type Map struct {

	// Name - Name of the map as defined in its section SEC("maps/[name]")
	Name string

	// Contents - The initial contents of the map. May be nil.
	Contents []ebpf.MapKV
	// Freeze is retained for compatibility; use Map.Freeze explicitly after loading.
	// cilium/ebpf removed MapSpec.Freeze.
	Freeze bool

	// Other options
	MapOptions
	// contains filtered or unexported fields
}

func (*Map) Close

func (m *Map) Close(cleanup MapCleanupType) error

Close - Close underlying eBPF map.

func (*Map) Init

func (m *Map) Init(manager *Manager) error

type MapCleanupType

type MapCleanupType int

MapCleanupType - The map clean up type defines how the maps of a manager should be cleaned up on exit.

A map can only be in one of the following categories

             ----------------------
            |   Internally loaded  |
             ----------------------
Categories: |  Pinned | Not Pinned |
             ----------------------

type MapOptions

type MapOptions struct {
	// PinPath - Once loaded, the eBPF map will be pinned to this path. If the map has already been pinned and is
	// already present in the kernel, then it will be loaded from this path.
	PinPath string

	// AlwaysCleanup - Overrides the cleanup type given to the manager. See CleanupType for more.
	AlwaysCleanup bool
	DumpHandler   func(currentMap *Map, manager *Manager) string
}

MapOptions - Generic Map options that are not shared with the MapSpec definition

type MapRoute

type MapRoute struct {
	// RoutingMapName - Name of the BPF_MAP_TYPE_ARRAY_OF_MAPS or BPF_MAP_TYPE_HASH_OF_MAPS map, as defined in its
	// section SEC("maps/[RoutingMapName]")
	RoutingMapName string

	// Key - Key at which the program will be inserted in the routing map
	Key interface{}

	// RoutedName - Section of the map that will be inserted
	RoutedName string

	// Map - Map to insert in the routing map
	Map *ebpf.Map
}

MapRoute - A map route defines how multiple maps should be routed between eBPF programs.

The provided eBPF map will be inserted in the provided eBPF array of maps (or hash of maps), at the provided key. The inserted eBPF map can be provided by its section or by its *ebpf.Map representation.

type MapSpecEditor

type MapSpecEditor struct {
	// Type - Type of the map.
	Type ebpf.MapType
	// MaxEntries - Max Entries of the map.
	MaxEntries uint32
	// Flags - Flags provided to the kernel during the loading process.
	Flags uint32
	// KeySize - Defines the key size of the map
	KeySize uint32
	// Key - Defines the BTF type of the keys of the map
	Key btf.Type
	// ValueSize - Defines the value size of the map
	ValueSize uint32
	// Value - Defines the BTF type of the values of the map
	Value btf.Type
	// EditorFlag - Use this flag to specify what fields should be updated. See MapSpecEditorFlag.
	EditorFlag MapSpecEditorFlag
	InnerMap   *ebpf.MapSpec
}

MapSpecEditor - A MapSpec editor defines how specific parameters of specific maps should be updated at runtime

For example, this can be used if you need to change the max_entries of a map before it is loaded in the kernel, but you don't know what this value should be initially.

type MapSpecEditorFlag

type MapSpecEditorFlag uint

MapSpecEditorFlag - Flag used to specify what a MapSpecEditor should edit.

const (
	EditType       MapSpecEditorFlag = 1 << 1
	EditMaxEntries MapSpecEditorFlag = 1 << 2
	EditFlags      MapSpecEditorFlag = 1 << 3
	EditInnerMap   MapSpecEditorFlag = 1 << 4
	EditKey        MapSpecEditorFlag = 1 << 5
	EditValue      MapSpecEditorFlag = 1 << 6
	EditKeyValue   MapSpecEditorFlag = EditKey | EditValue
)

type NetlinkSocket added in v0.7.0

type NetlinkSocket struct {
	Sock *netlink.Handle
	// contains filtered or unexported fields
}

NetlinkSocket - (TC classifier programs and XDP) Netlink socket cache entry holding the netlink socket and the TC filter count

func NewNetlinkSocket added in v0.7.0

func NewNetlinkSocket(nsHandle uint64) (*NetlinkSocket, error)

NewNetlinkSocket - Returns a new NetlinkSocket instance

func (*NetlinkSocket) DecreaseFilterCount added in v0.7.0

func (ns *NetlinkSocket) DecreaseFilterCount(index int) int

DecreaseFilterCount decreases the count for the given index in a thread-safe manner. It will delete the entry if the count reaches 0. The return value is the count after the decrease. If the entry was deleted, the return value is 0.

func (*NetlinkSocket) IncreaseFilterCount added in v0.7.0

func (ns *NetlinkSocket) IncreaseFilterCount(index int)

IncreaseFilterCount increases the count for the given index in a thread-safe manner. The return value is the new count.

type OneOf

type OneOf struct {
	Selectors []ProbesSelector
}

OneOf - This selector is used to ensure that at least of a list of probe selectors is valid. In other words, this can be used to ensure that at least one of a list of optional probes is activated.

func (*OneOf) EditProbeIdentificationPair

func (oo *OneOf) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they now select the new one

func (*OneOf) GetProbesIdentificationPairList

func (oo *OneOf) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*OneOf) RunValidator

func (oo *OneOf) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

func (*OneOf) String

func (oo *OneOf) String() string

type Options

type Options struct {
	// ActivatedProbes - List of the probes that should be activated, identified by their identification string.
	// If the list is empty, all probes will be activated.
	ActivatedProbes []ProbesSelector

	// KeepUnmappedProgramSpecs - Defines if the manager should keep unmapped ProgramSpec instances in the collection.
	// Enable this feature if you're going to clone one of these ProgramSpec.
	KeepUnmappedProgramSpecs bool
	// DiscardProgramSpecs opts into upstream instruction cleanup. By default,
	// retain specs so existing CloneProgram callers continue to work.
	DiscardProgramSpecs bool

	// ExcludedFunctions - A list of functions that should not even be verified. This list overrides the ActivatedProbes
	// list: since the excluded sections aren't loaded in the kernel, all the probes using those sections will be
	// deactivated.
	ExcludedFunctions []string
	// ExcludedEbpfFuncs is the fork spelling of ExcludedFunctions.
	ExcludedEbpfFuncs []string
	// ExcludedSections is retained for compatibility; prefer function names.
	ExcludedSections []string
	RLimit           *unix.Rlimit

	// AdditionalExcludedFunctionCollector - A dynamic function excluder, allowing to exclude functions with a callback.
	AdditionalExcludedFunctionCollector FunctionExcluder

	// ExcludedMaps - A list of maps that should not be created.
	ExcludedMaps []string

	// ConstantsEditor - Post-compilation constant edition. See ConstantEditor for more.
	ConstantEditors []ConstantEditor

	// MapSpecEditor - Pre-loading MapSpec editors.
	MapSpecEditors map[string]MapSpecEditor

	// VerifierOptions - Defines the log level of the verifier and the size of its log buffer. Set to 0 to disable
	// logging and 1 to get a verbose output of the error. Increase the buffer size if the output is truncated.
	VerifierOptions ebpf.CollectionOptions

	// MapEditors - External map editor. The provided eBPF maps will overwrite the maps of the Manager if their names
	// match.
	// This is particularly useful to share maps across Managers (and therefore across isolated eBPF programs), without
	// having to use the MapRouter indirection. However, this technique only works before the eBPF programs are loaded,
	// and therefore before the Manager is started. The keys of the map are the names of the maps to edit, as defined
	// in their sections SEC("maps/[name]").
	MapEditors map[string]*ebpf.Map

	// MapEditorsIgnoreMissingMaps - If MapEditorsIgnoreMissingMaps is set to true, the map edition process will return an
	// error if a map was missing in at least one program
	MapEditorsIgnoreMissingMaps bool

	// MapRouter - External map routing. See MapRoute for more.
	MapRouter []MapRoute

	// InnerOuterMapSpecs - Defines the mapping between inner and outer maps. See InnerOuterMapSpec for more.
	InnerOuterMapSpecs []InnerOuterMapSpec

	// TailCallRouter - External tail call routing. See TailCallRoute for more.
	TailCallRouter []TailCallRoute

	// SymFile - Kernel symbol file. If not provided, the default `/proc/kallsyms` will be used.
	SymFile string

	// PerfRingBufferSize - Manager-level default value for the perf ring buffers. Defaults to the size of 1 page
	// on the system. See PerfMap.PerfRingBuffer for more.
	DefaultPerfRingBufferSize int

	// Watermark - Manager-level default value for the watermarks of the perf ring buffers.
	// See PerfMap.Watermark for more.
	DefaultWatermark int

	// DefaultKProbeMaxActive - Manager-level default value for the kprobe max active parameter.
	// See Probe.MaxActive for more.
	DefaultKProbeMaxActive int

	// DefaultKprobeAttachMethod - Manager-level default value for the Kprobe attach method. Defaults to AttachKprobeWithPerfEventOpen if unset.
	DefaultKprobeAttachMethod KprobeAttachMethod

	// DefaultUprobeAttachMethod - Manager-level default value for the Uprobe attach method. Defaults to AttachWithPerfEventOpen if unset.
	DefaultUprobeAttachMethod AttachMethod

	// ProbeRetry - Defines the number of times that a probe will retry to attach / detach on error.
	DefaultProbeRetry uint

	// ProbeRetryDelay - Defines the delay to wait before a probe should retry to attach / detach on error.
	DefaultProbeRetryDelay time.Duration

	// RemoveRlimit - The maps & programs provided to the manager might exceed the maximum allowed memory lock.
	// `RLIMIT_MEMLOCK` If a limit is provided here it will be applied when the manager is initialized.
	RemoveRlimit bool

	// KeepKernelBTF - Defines if the kernel BTF used while loading programs should be cleaned up once the manager is done
	// using them. This governs both VerifierOptions.Programs.KernelTypes and the shared VerifierOptions.Cache. By default,
	// the manager will clean both up after Start() to save up space: otherwise a long-lived manager keeps the parsed
	// kernel BTF (vmlinux) pinned for the whole process lifetime, even though it is only needed while loading programs.
	// DISCLAIMER: if your program uses "manager.CloneProgram", you might want to enable "KeepKernelBTF", as cloning
	// reloads a program and needs "KernelTypes" for its CO-RE relocations. As a workaround, you can also try to strip as
	// much as possible the content of "KernelTypes" to reduce the memory overhead.
	KeepKernelBTF bool

	// SkipPerfMapReaderStartup - Perf maps whose name is set to true with this option will not have their reader goroutine started when calling the manager.Start() function.
	// PerfMap.Start() can then be used to start reading events from the corresponding PerfMap.
	SkipPerfMapReaderStartup map[string]bool

	// SkipRingbufferReaderStartup - Ringbuffer maps whose name is set to true with this option will not have their reader goroutine started when calling the manager.Start() function.
	// RingbufMap.Start() can then be used to start reading events from the corresponding RingbufMap.
	SkipRingbufferReaderStartup map[string]bool

	// BypassEnabled controls whether program bypass is enabled for this manager
	BypassEnabled bool
}

Options - Options of a Manager. These options define how a manager should be initialized.

type PerfMap

type PerfMap struct {

	// Map - A PerfMap has the same features as a normal Map
	Map
	PerfMapOptions
	// contains filtered or unexported fields
}

PerfMap - Perf ring buffer reader wrapper

func (*PerfMap) BufferSize added in v0.7.0

func (m *PerfMap) BufferSize() int

BufferSize is the size in bytes of each per-CPU buffer

func (*PerfMap) Flush added in v0.7.0

func (m *PerfMap) Flush()

Flush unblocks the underlying reader and will cause the pending samples to be read

func (*PerfMap) Init

func (m *PerfMap) Init(manager *Manager) error

func (*PerfMap) Pause

func (m *PerfMap) Pause() error

Pause - Pauses a perf ring buffer reader

func (*PerfMap) Resume

func (m *PerfMap) Resume() error

Resume - Resumes a perf ring buffer reader

func (*PerfMap) Start

func (m *PerfMap) Start() error

Start - Starts fetching events on a perf ring buffer

func (*PerfMap) Stop

func (m *PerfMap) Stop(cleanup MapCleanupType) error

Stop - Stops the perf ring buffer. Warning: Stop waits for the reader goroutine while holding stateLock. If the caller also holds manager.stateLock, and a handler callback needs manager.stateLock.RLock(), this will deadlock.

func (*PerfMap) Telemetry added in v0.7.0

func (m *PerfMap) Telemetry() (usage []uint64, lost []uint64)

Telemetry returns the usage and lost telemetry

type PerfMapOptions

type PerfMapOptions struct {
	// PerfRingBufferSize - Size in bytes of the perf ring buffer. Defaults to the manager value if not set.
	PerfRingBufferSize int

	// Watermark - The reader will start processing samples once their sizes in the perf ring buffer
	// exceed this value. Must be smaller than PerfRingBufferSize. Defaults to the manager value if not set.
	Watermark int

	// The number of events required in any per CPU buffer before
	// Read will process data. This is mutually exclusive with Watermark.
	// The default is zero, which means Watermark will take precedence.
	WakeupEvents int

	// PerfErrChan - Perf reader error channel
	PerfErrChan chan error

	// DataHandler - Callback function called when a new sample was retrieved from the perf
	// ring buffer.
	DataHandler func(CPU int, data []byte, perfMap *PerfMap, manager *Manager)

	// RecordHandler - Callback function called when a new record was retrieved from the perf
	// ring buffer.
	RecordHandler func(record *perf.Record, perfMap *PerfMap, manager *Manager)

	// LostHandler - Callback function called when one or more events where dropped by the kernel
	// because the perf ring buffer was full.
	LostHandler func(CPU int, count uint64, perfMap *PerfMap, manager *Manager)

	// RecordGetter - if specified this getter will be used to get a new record
	RecordGetter func() *perf.Record

	// TelemetryEnabled turns on telemetry about the usage of the perf ring buffer
	TelemetryEnabled bool
	PerfMapStats     *PerfMapStats
	DumpHandler      func(perfMap *PerfMap, manager *Manager) string
}

PerfMapOptions - Perf map specific options

type PerfMapStats

type PerfMapStats struct {
	ReadErrors  uint64
	RawSamples  map[int]uint64
	LostSamples map[int]uint64
}

PerfMapStats contain perf map read/errors statistics including per CPU map bytes and lost bytes

func NewPerfMapStats

func NewPerfMapStats() *PerfMapStats

NewPerfMapStats create/enable counting the perf map statistics performance/debug information

func (*PerfMapStats) Diff

func (new *PerfMapStats) Diff(old *PerfMapStats) (diff *PerfMapStats)

type Probe

type Probe struct {

	// ProbeIdentificationPair is used to identify the current probe
	UID          string
	EbpfFuncName string

	// Section and AttachToFuncName retain the fork's probe configuration API.
	// Section overrides the ELF section used to select the attachment type.
	Section          string
	AttachToFuncName string
	// UAddress is a file offset supplied by the caller. UprobeOffset is relative
	// to UAddress, or to the resolved symbol when UAddress is zero.
	UAddress     uint64
	AttachPID    int
	LinkPinPath  string
	Ifindex      int32
	Ifname       string
	IfindexNetns uint64
	SkipLoopback bool

	// CopyProgram - When enabled, this option will make a unique copy of the program section for the current program
	CopyProgram bool

	// KeepProgramSpec - Defines if the internal *ProgramSpec should be cleaned up after the probe has been successfully
	// attached to free up memory. If you intend to make a copy of this Probe later, you should explicitly set this
	// option to true.
	KeepProgramSpec bool

	// SyscallFuncName - Name of the syscall on which the program should be hooked. As the exact kernel symbol may
	// differ from one kernel version to the other, the right prefix will be computed automatically at runtime.
	// If a syscall name is not provided, the section name (without its probe type prefix) is assumed to be the
	// hook point.
	SyscallFuncName string

	// MatchFuncName - Pattern used to find the function(s) to attach to
	// FOR KPROBES: When this field is used, the provided pattern is matched against the list of available symbols
	// in /sys/kernel/debug/tracing/available_filter_functions. If the exact function does not exist, then the first
	// symbol matching the provided pattern will be used. This option requires debugfs.
	//
	// FOR UPROBES: When this field is used, the provided pattern is matched against the list of symbols in the symbol
	// table of the provided elf binary. If the exact function does not exist, then the first symbol matching the
	// provided pattern will be used.
	MatchFuncName string

	// HookFuncName - Exact name of the symbol to hook onto. When this field is set, MatchFuncName and SyscallFuncName
	// are ignored.
	HookFuncName string

	// TracepointCategory - (Tracepoint) The manager expects the tracepoint category to be parsed from the eBPF section
	// in which the eBPF function of this Probe lives (SEC("tracepoint/[category]/[name]")). However, you can use this
	// field to override it.
	TracepointCategory string

	// TracepointName - (Tracepoint) The manager expects the tracepoint name to be parsed from the eBPF section
	// in which the eBPF function of this Probe lives (SEC("tracepoint/[category]/[name]")). However, you can use this
	// field to override it.
	TracepointName string

	// Enabled - Indicates if a probe should be enabled or not. This parameter can be set at runtime using the
	// Manager options (see ActivatedProbes)
	Enabled bool

	// PinPath - Once loaded, the eBPF program will be pinned to this path. If the eBPF program has already been pinned
	// and is already running in the kernel, then it will be loaded from this path.
	PinPath string

	// KProbeMaxActive - (kretprobes) With kretprobes, you can configure the maximum number of instances of the function that can be
	// probed simultaneously with maxactive. If maxactive is 0 it will be set to the default value: if CONFIG_PREEMPT is
	// enabled, this is max(10, 2*NR_CPUS); otherwise, it is NR_CPUS. For kprobes, maxactive is ignored.
	KProbeMaxActive int

	// KprobeAttachMethod - Method to use for attaching the kprobe. Either use perfEventOpen ABI or kprobe events
	KprobeAttachMethod KprobeAttachMethod

	// UprobeAttachMethod - Method to use for attaching the uprobe. Either use perfEventOpen ABI or uprobe events
	UprobeAttachMethod AttachMethod

	// UprobeOffset is added to UAddress or the resolved symbol's file offset.
	UprobeOffset uint64

	// ProbeRetry - Defines the number of times that the probe will retry to attach / detach on error.
	ProbeRetry uint

	// ProbeRetryDelay - Defines the delay to wait before the probe should retry to attach / detach on error.
	ProbeRetryDelay time.Duration

	// BinaryPath - (uprobes) A Uprobe is attached to a specific symbol in a user space binary. The offset is
	// automatically computed for the symbol name provided in the uprobe section ( SEC("uprobe/[symbol_name]") ).
	BinaryPath string

	// CGroupPath - (cgroup family programs) All CGroup programs are attached to a CGroup (v2). This field provides the
	// path to the CGroup to which the probe should be attached. The attach type is determined by the section.
	CGroupPath string

	// SocketFD - (socket filter) Socket filter programs are bound to a socket and filter the packets they receive
	// before they reach user space. The probe will be bound to the provided file descriptor
	SocketFD int

	// IfIndex - (TC classifier & XDP) Interface index used to identify the interface on which the probe will be
	// attached. If not set, fall back to `IfName`.
	IfIndex int

	// IfName - (TC Classifier & XDP) Interface name on which the probe will be attached.
	IfName string

	// IfIndexNetns - (TC Classifier & XDP) Network namespace in which the network interface lives. If this value is
	// provided, then IfIndexNetnsID is required too.
	// WARNING: it is up to the caller of "Probe.Start()" to close this netns handle. Failing to close this handle may
	// lead to leaking the network namespace. This handle can be safely closed once "Probe.Start()" returns.
	IfIndexNetns uint64

	// IfIndexNetnsID - (TC Classifier & XDP) Network namespace ID associated of the IfIndexNetns handle. If this value
	// is provided, then IfIndexNetns is required too.
	// WARNING: it is up to the caller of "Probe.Start()" to call "manager.CleanupNetworkNamespace()" once the provided
	// IfIndexNetnsID is no longer needed. Failing to call this cleanup function may lead to leaking the network
	// namespace. Remember that "manager.CleanupNetworkNamespace()" will close the netlink socket opened with the netns
	// handle provided above. If you want to start the probe again, you'll need to provide a new valid netns handle so
	// that a new netlink socket can be created in that namespace.
	IfIndexNetnsID uint32

	// XDPAttachMode - (XDP) XDP attach mode. If not provided the kernel will automatically select the best available
	// mode.
	XDPAttachMode XdpAttachMode

	// NetworkDirection - (TC classifier) Network traffic direction of the classifier. Can be either Ingress or Egress. Keep
	// in mind that if you are hooking on the host side of a virtual ethernet pair, Ingress and Egress are inverted.
	NetworkDirection TrafficType

	// TCFilterHandle - (TC classifier) defines the handle to use when loading the classifier. Leave unset to let the kernel decide which handle to use.
	TCFilterHandle uint32

	// TCFilterPrio - (TC classifier) defines the priority of the classifier added to the clsact qdisc. Defaults to DefaultTCFilterPriority.
	TCFilterPrio uint16

	// TCCleanupQDisc - (TC classifier) defines if the manager should clean up the clsact qdisc when a probe is unloaded
	TCCleanupQDisc bool

	// TCFilterProtocol - (TC classifier) defines the protocol to match in order to trigger the classifier. Defaults to
	// ETH_P_ALL.
	TCFilterProtocol uint16

	// SamplePeriod - (Perf event) This parameter defines when the perf_event eBPF program is triggered. When SamplePeriod > 0
	// the program will be triggered every SamplePeriod events.
	SamplePeriod int

	// SampleFrequency - (Perf event) This parameter defines when the perf_event eBPF program is triggered. When
	// SampleFrequency > 0, SamplePeriod is ignored and the eBPF program is triggered at the requested frequency.
	SampleFrequency int

	// PerfEventType - (Perf event) This parameter defines the type of the perf_event program. Allowed values are
	// unix.PERF_TYPE_HARDWARE and unix.PERF_TYPE_SOFTWARE
	PerfEventType int

	// PerfEventPID - (Perf event, uprobes) This parameter defines the PID for which the program should be triggered.
	// Do not set this value to monitor the whole host.
	PerfEventPID int

	// PerfEventConfig - (Perf event) This parameter defines which software or hardware event is being monitored. See the
	// PERF_COUNT_SW_* and PERF_COUNT_HW_* constants in the unix package.
	PerfEventConfig int

	// PerfEventCPUCount - (Perf event) This parameter defines the number of CPUs to monitor. If not set, defaults to
	// runtime.NumCPU(). Disclaimer: in containerized environment and depending on the CPU affinity of the program
	// holding the manager, runtime.NumCPU might not return the real CPU count of the host.
	PerfEventCPUCount int
	// contains filtered or unexported fields
}

Probe - Main eBPF probe wrapper. This structure is used to store the required data to attach a loaded eBPF program to its hook point.

func (*Probe) Attach

func (p *Probe) Attach() error

Attach - Attaches the probe to the right hook point in the kernel depending on the program type and the provided parameters.

func (*Probe) Benchmark

func (p *Probe) Benchmark(in []byte, repeat int, reset func()) (uint32, time.Duration, error)

Benchmark - Benchmark runs the Program with the given input for a number of times and returns the time taken per iteration.

Returns the result of the last execution of the program and the time per run or an error. reset is called whenever the benchmark syscall is interrupted, and should be set to testing.B.ResetTimer or similar.

func (*Probe) Copy

func (p *Probe) Copy() *Probe

Copy - Returns a copy of the current probe instance. Only the exported fields are copied.

func (*Probe) Detach

func (p *Probe) Detach() error

Detach - Detaches the probe from its hook point depending on the program type and the provided parameters. This method does not close the underlying eBPF program, which means that Attach can be called again later.

func (*Probe) GetEBPFFuncName added in v0.7.0

func (p *Probe) GetEBPFFuncName() string

func (*Probe) GetEbpfFuncName added in v0.7.0

func (p *Probe) GetEbpfFuncName() string

GetEbpfFuncName - Returns EbpfFuncName with the UID as a postfix if the Probe was copied

func (*Probe) GetIdentificationPair

func (p *Probe) GetIdentificationPair() ProbeIdentificationPair

func (*Probe) GetLastError

func (p *Probe) GetLastError() error

GetLastError - Returns the last error that the probe encountered

func (*Probe) ID added in v0.7.0

func (p *Probe) ID() uint32

ID returns the system-wide unique ID for this program

func (*Probe) IdentificationPairMatches

func (p *Probe) IdentificationPairMatches(id ProbeIdentificationPair) bool

func (*Probe) Init

func (p *Probe) Init(m *Manager) error

func (*Probe) InitWithOptions

func (p *Probe) InitWithOptions(m *Manager, manualLoadNeeded, checkPin bool) error

func (*Probe) IsInitialized

func (p *Probe) IsInitialized() bool

IsInitialized - Returns true if the probe was successfully initialized.

func (*Probe) IsRunning

func (p *Probe) IsRunning() bool

IsRunning - Returns true if the probe was successfully initialized, started and is currently running or paused.

func (*Probe) IsTCFilterActive added in v0.7.0

func (p *Probe) IsTCFilterActive() bool

func (*Probe) Iterator added in v0.7.0

func (p *Probe) Iterator() (io.ReadCloser, error)

func (*Probe) Pause added in v0.7.0

func (p *Probe) Pause() error

func (*Probe) PerfEventFD added in v0.7.0

func (p *Probe) PerfEventFD() (uint32, error)

PerfEventFD returns the associated perf event's fd for this Probe

func (*Probe) Program

func (p *Probe) Program() *ebpf.Program

func (*Probe) RenameProbeIdentificationPair added in v0.7.0

func (p *Probe) RenameProbeIdentificationPair(newID ProbeIdentificationPair) error

RenameProbeIdentificationPair - Renames the probe identification pair of a probe

func (p *Probe) ResolveLink() (netlink.Link, error)

ResolveLink - Resolves the Probe's network interface

func (*Probe) Resume added in v0.7.0

func (p *Probe) Resume() error

func (*Probe) Stop

func (p *Probe) Stop() error

Stop - Detaches the probe from its hook point and close the underlying eBPF program.

func (*Probe) Test

func (p *Probe) Test(in []byte) (uint32, []byte, error)

Test - Triggers the probe with the provided test data. Returns the length of the output, the raw output or an error.

type ProbeIdentificationPair

type ProbeIdentificationPair struct {
	// UID - (optional) this field can be used to identify your probes when the same eBPF program is used on multiple
	// hook points. Keep in mind that the pair (probe section, probe UID) needs to be unique
	// system-wide for the kprobes and uprobes registration to work.
	UID string

	// EbpfFuncName - Name of the main eBPF function of your eBPF program.
	EbpfFuncName string
}

func (ProbeIdentificationPair) Matches

func (ProbeIdentificationPair) String

func (pip ProbeIdentificationPair) String() string

type ProbeSelector

type ProbeSelector struct {
	ProbeIdentificationPair
}

ProbeSelector - This selector is used to unconditionally select a probe by its identification pair and validate that it is activated

func (*ProbeSelector) EditProbeIdentificationPair

func (ps *ProbeSelector) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they mow select the new one

func (*ProbeSelector) GetProbesIdentificationPairList

func (ps *ProbeSelector) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*ProbeSelector) RunValidator

func (ps *ProbeSelector) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

type ProbesSelector

type ProbesSelector interface {
	// GetProbesIdentificationPairList - Returns the list of probes that this selector activates
	GetProbesIdentificationPairList() []ProbeIdentificationPair
	// RunValidator - Ensures that the probes that were successfully activated follow the selector goal.
	// For example, see OneOf.
	RunValidator(manager *Manager) error
	// EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they
	// mow select the new one
	EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)
}

ProbesSelector - A probe selector defines how a probe (or a group of probes) should be activated.

For example, this can be used to specify that out of a group of optional probes, at least one should be activated.

type RingBuffer added in v0.7.0

type RingBuffer = RingbufMap

Compatibility with the public API used by eCapture and existing fork clients.

type RingBufferOptions added in v0.7.0

type RingBufferOptions = RingbufMapOptions

type RingbufMap added in v0.4.4

type RingbufMap struct {

	// Map - A PerfMap has the same features as a normal Map
	Map
	RingbufMapOptions
	// contains filtered or unexported fields
}

func (*RingbufMap) BufferSize added in v0.7.0

func (rb *RingbufMap) BufferSize() int

BufferSize returns the size in bytes of the ring buffer

func (*RingbufMap) Flush added in v0.7.0

func (rb *RingbufMap) Flush()

Flush unblocks the underlying reader and will cause the pending samples to be read

func (*RingbufMap) Init added in v0.4.4

func (m *RingbufMap) Init(manager *Manager) error

func (*RingbufMap) Start added in v0.4.4

func (rb *RingbufMap) Start() error

Start - Starts fetching events on a perf ring buffer

func (*RingbufMap) Stop added in v0.4.4

func (rb *RingbufMap) Stop(cleanup MapCleanupType) error

Stop - Stops the ring buffer. Warning: Stop waits for the reader goroutine while holding stateLock. If the caller also holds manager.stateLock, and a handler callback needs manager.stateLock.RLock(), this will deadlock.

func (*RingbufMap) Telemetry added in v0.7.0

func (rb *RingbufMap) Telemetry() (usage uint64, ok bool)

Telemetry returns the usage telemetry

type RingbufMapOptions added in v0.4.4

type RingbufMapOptions struct {
	// Legacy fields retained for source compatibility. Ring buffers have no watermark.
	Watermark    int
	PerfErrChan  chan error
	PerfMapStats *PerfMapStats
	DumpHandler  func(*PerfMap, *Manager) string

	// ErrChan - Reader error channel
	ErrChan chan error

	// DataHandler - Callback function called when a new sample was retrieved from the perf
	// ring buffer.
	DataHandler func(CPU int, data []byte, ringBuffer *RingbufMap, manager *Manager)

	// RecordHandler - Callback function called when a new record was retrieved from the perf
	// ring buffer.
	RecordHandler func(record *ringbuf.Record, ringBuffer *RingbufMap, manager *Manager)

	// RecordGetter - if specified this getter will be used to get a new record
	RecordGetter func() *ringbuf.Record

	// TelemetryEnabled turns on telemetry about the usage of the ring buffer
	TelemetryEnabled bool
}

type TailCallRoute

type TailCallRoute struct {
	// ProgArrayName - Name of the BPF_MAP_TYPE_PROG_ARRAY map as defined in its section SEC("maps/[ProgArray]")
	ProgArrayName string

	// Key - Key at which the program will be inserted in the ProgArray map
	Key uint32

	// ProbeIdentificationPair - Selector of the program to insert in the ProgArray map
	ProbeIdentificationPair ProbeIdentificationPair

	// Program - Program to insert in the ProgArray map
	Program *ebpf.Program
}

TailCallRoute - A tail call route defines how tail calls should be routed between eBPF programs.

The provided eBPF program will be inserted in the provided eBPF program array, at the provided key. The eBPF program can be provided by its function name or by its *ebpf.Program representation.

type TrafficType

type TrafficType uint16

func (TrafficType) String

func (tt TrafficType) String() string

type XdpAttachMode

type XdpAttachMode int

XdpAttachMode selects a way how XDP program will be attached to interface

const (
	// XdpAttachModeNone stands for "best effort" - the kernel automatically
	// selects the best mode (would try Drv first, then fallback to Generic).
	// NOTE: Kernel will not fall back to Generic XDP if NIC driver failed
	//       to install XDP program.
	XdpAttachModeNone XdpAttachMode = 0
	// XdpAttachModeSkb is "generic", kernel mode, less performant comparing to native,
	// but does not requires driver support.
	XdpAttachModeSkb XdpAttachMode = 1 << 1
	// XdpAttachModeDrv is native, driver mode (support from driver side required)
	XdpAttachModeDrv XdpAttachMode = 1 << 2
	// XdpAttachModeHw suitable for NICs with hardware XDP support
	XdpAttachModeHw XdpAttachMode = 1 << 3
)

Directories

Path Synopsis
examples
link_pinning command
mapspec_editor command
object_pinning command
program_router command
programs/cgroup command
programs/kprobe command
programs/lsm command
programs/socket command
programs/tc command
programs/uprobe command
programs/xdp command
ringbuf_map command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL