ebpf

package
v0.0.0-...-6a467e6 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package ebpf provides eBPF program lifecycle management.

Index

Constants

View Source
const (
	Go = ProcessTracerType(iota)
	Generic
)

Variables

This section is empty.

Functions

func CreatePerfEventArray

func CreatePerfEventArray(name string, maxEntries uint32) (*ebpf.Map, error)

CreatePerfEventArray creates a perf event array map for use with perf buffers

func ReadBytes

func ReadBytes(data []byte, offset, size int) ([]byte, error)

ReadBytes reads a fixed-size byte slice from an event

func ReadCString

func ReadCString(data []byte, offset, maxLen int) (string, error)

ReadCString reads a null-terminated string from an event

func ReadU32

func ReadU32(data []byte, offset int) (uint32, error)

ReadU32 reads a uint32 from an event at the given offset

func ReadU64

func ReadU64(data []byte, offset int) (uint64, error)

ReadU64 reads a uint64 from an event at the given offset

Types

type CommonTracer

type CommonTracer interface {
	// Load the bpf object that is generated by the bpf2go compiler
	Load() (*ebpf.CollectionSpec, error)
	// AddCloser adds io.Closer instances that need to be invoked when the
	// Run function ends.
	AddCloser(c ...io.Closer)
	// BpfObjects that are created by the bpf2go compiler
	BpfObjects() any
	// Sets up any tail call tables if the BPF program has it
	SetupTailCalls()
}

type EventHandler

type EventHandler func(ctx context.Context, events []RingbufEvent) error

EventHandler processes ring buffer events

type Instrumentable

type Instrumentable struct {
	Type                 svc.InstrumentableType
	InstrumentationError error

	// in some runtimes, like python gunicorn, we need to allow
	// tracing both the parent pid and all of its children pid
	ChildPids []uint32

	FileInfo *exec.FileInfo
	Offsets  *goexec.Offsets
	Tracer   *ProcessTracer

	LogEnricherEnabled bool
}

func (*Instrumentable) CopyToServiceAttributes

func (ie *Instrumentable) CopyToServiceAttributes()

type KprobesTracer

type KprobesTracer interface {
	CommonTracer
	// KProbes returns a map with the name of the kernel probes that need to be
	// tapped into. Start matches kprobe, End matches kretprobe
	KProbes() map[string]ebpfcommon.ProbeDesc
	Tracepoints() map[string]ebpfcommon.ProbeDesc
}

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager manages the lifecycle of eBPF programs

func NewManager

func NewManager(cfg ManagerConfig, log *slog.Logger, st *selftelemetry.Metrics) (*Manager, error)

NewManager creates a new eBPF program manager

func (*Manager) AddCloser

func (m *Manager) AddCloser(c io.Closer)

AddCloser adds a closer to be called on shutdown

func (*Manager) AttachKprobe

func (m *Manager) AttachKprobe(collName, progName, symbol string) (link.Link, error)

AttachKprobe attaches a kprobe to a kernel function

func (*Manager) AttachKretprobe

func (m *Manager) AttachKretprobe(collName, progName, symbol string) (link.Link, error)

AttachKretprobe attaches a kretprobe to a kernel function

func (*Manager) AttachTracepoint

func (m *Manager) AttachTracepoint(collName, progName, group, name string) (link.Link, error)

AttachTracepoint attaches a tracepoint program

func (*Manager) AttachUprobe

func (m *Manager) AttachUprobe(collName, progName, path string, offset uint64) (link.Link, error)

AttachUprobe attaches a uprobe to a user-space function

func (m *Manager) DetachLink(linkName string) error

DetachLink detaches a specific link

func (*Manager) GetProgram

func (m *Manager) GetProgram(collName, progName string) (*ebpf.Program, error)

GetProgram retrieves a program by name

func (*Manager) ListPrograms

func (m *Manager) ListPrograms() []ProgramInfo

ListPrograms returns information about all loaded programs

func (*Manager) LoadCollection

func (m *Manager) LoadCollection(name string, opts *ebpf.CollectionOptions) (*ebpf.Collection, error)

LoadCollection creates a collection from a spec with optional options

func (*Manager) LoadSpec

func (m *Manager) LoadSpec(name string, spec *ebpf.CollectionSpec) error

LoadSpec loads an eBPF collection spec from bytes

func (*Manager) MapManager

func (m *Manager) MapManager() *MapManager

MapManager returns the map manager

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start initializes the manager

func (*Manager) Stats

func (m *Manager) Stats() ManagerStats

Stats returns manager statistics

func (*Manager) Stop

func (m *Manager) Stop(ctx context.Context) error

Stop shuts down all loaded programs and releases resources

type ManagerConfig

type ManagerConfig struct {
	// BTFPath is an optional path to a BTF file
	BTFPath string `mapstructure:"btf_path"`

	// PinPath is the path for pinning BPF objects
	PinPath string `mapstructure:"pin_path"`

	// LogLevel for eBPF verifier (0-2)
	LogLevel int `mapstructure:"log_level"`

	// LogSize for verifier log buffer
	LogSize int `mapstructure:"log_size"`

	// RemoveRlimit removes memory rlimit for BPF
	RemoveRlimit bool `mapstructure:"remove_rlimit"`
}

ManagerConfig holds eBPF manager configuration

func DefaultManagerConfig

func DefaultManagerConfig() ManagerConfig

DefaultManagerConfig returns default configuration

type ManagerStats

type ManagerStats struct {
	SpecsLoaded       int
	CollectionsLoaded int
	ProgramsLoaded    int
	LinksActive       int
}

ManagerStats holds manager statistics

type MapInfo

type MapInfo struct {
	Name       string
	Type       MapType
	KeySize    uint32
	ValueSize  uint32
	MaxEntries uint32
	Flags      uint32
	Pinned     bool
	PinPath    string
}

MapInfo holds information about a BPF map

type MapManager

type MapManager struct {
	// contains filtered or unexported fields
}

MapManager manages BPF maps and their lifecycle

func NewMapManager

func NewMapManager(pinPath string, log *slog.Logger, st *selftelemetry.Metrics) (*MapManager, error)

NewMapManager creates a new map manager

func (*MapManager) Close

func (m *MapManager) Close() error

Close closes all managed maps

func (*MapManager) CreateMap

func (m *MapManager) CreateMap(spec MapSpec) (*ebpf.Map, error)

CreateMap creates a new BPF map

func (*MapManager) DeleteFromMap

func (m *MapManager) DeleteFromMap(name string, key interface{}) error

DeleteFromMap deletes a key from a map

func (*MapManager) DeleteMap

func (m *MapManager) DeleteMap(name string) error

DeleteMap removes and closes a map

func (*MapManager) GetMap

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

GetMap retrieves a map by name

func (*MapManager) ListMaps

func (m *MapManager) ListMaps() []MapInfo

ListMaps returns information about all managed maps

func (*MapManager) LoadPinnedMap

func (m *MapManager) LoadPinnedMap(name string) (*ebpf.Map, error)

LoadPinnedMap loads a map from the pin path

func (*MapManager) LookupMap

func (m *MapManager) LookupMap(name string, key, value interface{}) error

LookupMap looks up a value in a map

func (*MapManager) RegisterMap

func (m *MapManager) RegisterMap(name string, mp *ebpf.Map)

RegisterMap registers an externally created map

func (*MapManager) Stats

func (m *MapManager) Stats() MapManagerStats

Stats returns map manager statistics

func (*MapManager) UpdateMap

func (m *MapManager) UpdateMap(name string, key, value interface{}, flags uint64) error

UpdateMap updates a value in a map

type MapManagerStats

type MapManagerStats struct {
	MapsLoaded int
}

MapManagerStats holds map manager statistics

type MapSpec

type MapSpec struct {
	Name       string
	Type       ebpf.MapType
	KeySize    uint32
	ValueSize  uint32
	MaxEntries uint32
	Flags      uint32
	Pinning    bool
}

MapSpec defines a map to be created

type MapType

type MapType string

MapType represents the type of BPF map

const (
	MapTypeHash        MapType = "hash"
	MapTypeArray       MapType = "array"
	MapTypePerfEvent   MapType = "perf_event"
	MapTypeRingbuf     MapType = "ringbuf"
	MapTypeLRUHash     MapType = "lru_hash"
	MapTypePercpuHash  MapType = "percpu_hash"
	MapTypePercpuArray MapType = "percpu_array"
	MapTypeLPMTrie     MapType = "lpm_trie"
)

type PIDsAccounter

type PIDsAccounter interface {
	// AllowPID notifies the tracer to accept traces from the process with the
	// provided PID. The Tracer should discard
	// traces from processes whose PID has not been allowed before
	// We must use a pointer for svc.Attrs so that all child processes share the same
	// object. This is important when we tag a service as exporting traces or metrics.
	AllowPID(uint32, uint32, *svc.Attrs)
	// BlockPID notifies the tracer to stop accepting traces from the process
	// with the provided PID. After receiving them via ringbuffer, it should
	// discard them.
	BlockPID(uint32, uint32)
}

type PerfEventHandler

type PerfEventHandler func(ctx context.Context, events []PerfbufEvent) error

PerfEventHandler processes perf buffer events

type PerfEventHeader

type PerfEventHeader struct {
	// Type identifies the event type
	Type uint32
	// Flags contains event flags
	Flags uint32
	// Size is the total size of the event including header
	Size uint32
}

PerfEventHeader represents the common header for perf events

func ParsePerfEventHeader

func ParsePerfEventHeader(data []byte) (*PerfEventHeader, error)

ParsePerfEventHeader parses a perf event header from raw data

type PerfbufConfig

type PerfbufConfig struct {
	// PerCPUBufferSize is the size of each per-CPU buffer
	PerCPUBufferSize int `mapstructure:"per_cpu_buffer_size"`

	// Watermark is the number of bytes after which the buffer is flushed
	Watermark int `mapstructure:"watermark"`

	// Workers is the number of worker goroutines processing events
	Workers int `mapstructure:"workers"`

	// BatchSize is the number of events to batch before processing
	BatchSize int `mapstructure:"batch_size"`

	// FlushInterval is the max time to wait before processing a partial batch
	FlushInterval time.Duration `mapstructure:"flush_interval"`
}

PerfbufConfig holds perf buffer reader configuration

func DefaultPerfbufConfig

func DefaultPerfbufConfig() PerfbufConfig

DefaultPerfbufConfig returns default configuration

type PerfbufEvent

type PerfbufEvent struct {
	// Raw is the raw event data
	Raw []byte

	// CPU is the CPU that generated the event
	CPU int

	// Timestamp is when the event was read
	Timestamp time.Time

	// Lost is the number of events lost before this one
	Lost uint64
}

PerfbufEvent represents an event read from a perf buffer

type PerfbufReader

type PerfbufReader struct {
	// contains filtered or unexported fields
}

PerfbufReader reads events from BPF perf event arrays

func NewPerfbufReader

func NewPerfbufReader(
	perfMap *ebpf.Map,
	mapName string,
	handler PerfEventHandler,
	cfg PerfbufConfig,
	log *slog.Logger,
	st *selftelemetry.Metrics,
) (*PerfbufReader, error)

NewPerfbufReader creates a new perf buffer reader

func (*PerfbufReader) Start

func (r *PerfbufReader) Start(ctx context.Context) error

Start begins reading events from the perf buffer

func (*PerfbufReader) Stats

func (r *PerfbufReader) Stats() PerfbufStats

Stats returns reader statistics

func (*PerfbufReader) Stop

func (r *PerfbufReader) Stop(ctx context.Context) error

Stop stops the perf buffer reader

type PerfbufStats

type PerfbufStats struct {
	EventsReceived int64
	EventsDropped  int64
	EventsLost     int64
	BytesReceived  int64
}

PerfbufStats holds perf buffer statistics

type ProcessTracer

type ProcessTracer struct {
	Programs []Tracer

	Type            ProcessTracerType
	Instrumentables map[uint64]*instrumenter
	// contains filtered or unexported fields
}

ProcessTracer instruments an executable with eBPF and provides the eBPF readers that will forward the traces to later stages in the pipeline TODO: We need to pass the ELFInfo from this ProcessTracker to inside a Tracer so that the GPU kernel event listener can find symbols names from addresses in the ELF file.

func (*ProcessTracer) AllowPID

func (pt *ProcessTracer) AllowPID(pid, ns uint32, svc *svc.Attrs)

func (*ProcessTracer) BlockPID

func (pt *ProcessTracer) BlockPID(pid, ns uint32)

type ProcessTracerType

type ProcessTracerType int

type ProgramInfo

type ProgramInfo struct {
	Name        string
	Type        ProgramType
	Tag         string
	ID          uint32
	LoadedAt    time.Time
	AttachPoint string
}

ProgramInfo holds information about a loaded eBPF program

type ProgramType

type ProgramType string

ProgramType represents the type of eBPF program

const (
	ProgramKprobe        ProgramType = "kprobe"
	ProgramKretprobe     ProgramType = "kretprobe"
	ProgramUprobe        ProgramType = "uprobe"
	ProgramUretprobe     ProgramType = "uretprobe"
	ProgramTracepoint    ProgramType = "tracepoint"
	ProgramRawTracepoint ProgramType = "raw_tracepoint"
	ProgramPerfEvent     ProgramType = "perf_event"
	ProgramSocketFilter  ProgramType = "socket_filter"
	ProgramTC            ProgramType = "tc"
	ProgramXDP           ProgramType = "xdp"
	ProgramIter          ProgramType = "iter"
)

type RingbufConfig

type RingbufConfig struct {
	// BufferSize is the size hint for the ring buffer reader
	BufferSize int `mapstructure:"buffer_size"`

	// Workers is the number of worker goroutines processing events
	Workers int `mapstructure:"workers"`

	// BatchSize is the number of events to batch before processing
	BatchSize int `mapstructure:"batch_size"`

	// FlushInterval is the max time to wait before processing a partial batch
	FlushInterval time.Duration `mapstructure:"flush_interval"`
}

RingbufConfig holds ring buffer reader configuration

func DefaultRingbufConfig

func DefaultRingbufConfig() RingbufConfig

DefaultRingbufConfig returns default configuration

type RingbufEvent

type RingbufEvent struct {
	// Raw is the raw event data
	Raw []byte

	// Timestamp is when the event was read
	Timestamp time.Time
}

RingbufEvent represents an event read from a ring buffer

type RingbufReader

type RingbufReader struct {
	// contains filtered or unexported fields
}

RingbufReader reads events from BPF ring buffers

func NewRingbufReader

func NewRingbufReader(
	ringbufMap *ebpf.Map,
	mapName string,
	handler EventHandler,
	cfg RingbufConfig,
	log *slog.Logger,
	st *selftelemetry.Metrics,
) (*RingbufReader, error)

NewRingbufReader creates a new ring buffer reader

func (*RingbufReader) Start

func (r *RingbufReader) Start(ctx context.Context) error

Start begins reading events from the ring buffer

func (*RingbufReader) Stats

func (r *RingbufReader) Stats() RingbufStats

Stats returns reader statistics

func (*RingbufReader) Stop

func (r *RingbufReader) Stop(ctx context.Context) error

Stop stops the ring buffer reader

type RingbufStats

type RingbufStats struct {
	EventsReceived int64
	EventsDropped  int64
	EventsLost     int64
	BytesReceived  int64
}

RingbufStats holds ring buffer statistics

type Tracer

type Tracer interface {
	PIDsAccounter
	KprobesTracer
	// Constants returns a map of constants to be overridden into the eBPF program.
	// The key is the constant name and the value is the value to overwrite.
	Constants() map[string]any
	// GoProbes returns a slice with the name of Go functions that need to be inspected
	// in the executable, as well as the eBPF programs that optionally need to be
	// inserted as the Go function start and end probes
	GoProbes() map[string][]*ebpfcommon.ProbeDesc
	// UProbes returns a map with the module name mapping to the uprobes that need to be
	// tapped into. Start matches uprobe, End matches uretprobe
	UProbes() map[string]map[string][]*ebpfcommon.ProbeDesc
	// SocketFilters  returns a list of programs that need to be loaded as a
	// generic eBPF socket filter
	SocketFilters() []*ebpf.Program
	// SockMsgs returns a list of programs that need to be loaded as a
	// BPF_PROG_TYPE_SK_MSG eBPF programs
	SockMsgs() []ebpfcommon.SockMsg
	// SockOps returns a list of programs that need to be loaded as a
	// BPF_PROG_TYPE_SOCK_OPS eBPF programs
	SockOps() []ebpfcommon.SockOps
	// Iters returns a list of programs that need to be loaded as a
	// BPF_PROG_TYPE_TRACING with BPF_TRACE_ITER attach type
	Iters() []*ebpfcommon.Iter
	// Probes can potentially instrument a shared library among multiple executables
	// These two functions alow programs to remember this and avoid duplicated instrumentations
	// The argument is the OS file id
	// Closers are the associated closable resources to this lib, that may be
	// closed when UnlinkInstrumentedLib() is called
	RecordInstrumentedLib(uint64, []io.Closer)
	AddInstrumentedLibRef(uint64)
	AlreadyInstrumentedLib(uint64) bool
	UnlinkInstrumentedLib(uint64)
	RegisterOffsets(*exec.FileInfo, *goexec.Offsets)
	ProcessBinary(*exec.FileInfo)
	Required() bool
	// Run will do the action of listening for eBPF traces and forward them
	// periodically to the output channel.
	Run(context.Context, *ebpfcommon.EBPFEventContext, *msg.Queue[[]request.Span])
}

Tracer is an individual eBPF program (e.g. the net/http or the grpc tracers)

type UtilityTracer

type UtilityTracer interface {
	KprobesTracer
	Run(context.Context)
}

Subset of the above interface, which supports loading eBPF programs which are not tied to service monitoring

Directories

Path Synopsis
Package ebpfcommon provides shared eBPF consumers.
Package ebpfcommon provides shared eBPF consumers.
line below avoids linter errors on Mac
line below avoids linter errors on Mac

Jump to

Keyboard shortcuts

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