manager

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2023 License: MIT Imports: 28 Imported by: 33

README

eBPF Manager

License

This repository implements a manager on top of Cilium's eBPF library. This declarative manager simplifies attaching and detaching eBPF programs by controlling their entire life cycle. It was built with the intention of unifying how eBPF is used in large scale projects such as the Datadog Agent. By using the same declarative conventions, multiple teams can quickly collaborate on complex eBPF programs by sharing maps, programs or even hook points without having to worry about the setup of complex program types.

Requirements

Getting started

You can find many examples using the manager in examples/. For a real world use case, check out the Datadog Agent.

Useful resources

License

  • Unless explicitly specified otherwise, the golang code in this repository is under the MIT License.
  • The eBPF programs are under the GPL v2 License.

Documentation

Index

Constants

View Source
const (
	Running procMask = iota
	Exited
)
View Source
const (
	Ingress = TrafficType(uint16(netlink.HANDLE_MIN_INGRESS & 0x0000FFFF))
	Egress  = TrafficType(uint16(netlink.HANDLE_MIN_EGRESS & 0x0000FFFF))

	UnknownProbeType = ""
	ProbeType        = "p"
	RetProbeType     = "r"
)

Variables

View Source
var (
	ErrManagerNotInitialized    = errors.New("the manager must be initialized first")
	ErrManagerNotStarted        = errors.New("the manager must be started first")
	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")
	ErrKprobeIDNotExist         = errors.New("kprobe id file doesn't exist")
	ErrUprobeIDNotExist         = errors.New("uprobe 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 (
	BpfFlagActDirect = uint32(1) // see TCA_BPF_FLAG_ACT_DIRECT
)

Functions

func FindFilterFunction

func FindFilterFunction(funcName string) (string, error)

func GetSyscallFnName

func GetSyscallFnName(name string) (string, error)

GetSyscallFnName - Returns the kernel function of the provided syscall, after reading /proc/kallsyms to retrieve the list of symbols of the current kernel.

func GetSyscallFnNameWithSymFile

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

GetSyscallFnNameWithSymFile - Returns the kernel function of the provided syscall, after reading symFile to retrieve the list of symbols of the current kernel.

func GetTracepointID

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

GetTracepointID - Returns a tracepoint ID from its category and name

func Getpid

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 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

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 BestEffort

type BestEffort struct {
	Selectors []ProbesSelector
}

BestEffort - This selector is used to load probes in 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 *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{}

	// 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.

type InnerOuterMapSpec

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 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 KprobeAttachMethod

type KprobeAttachMethod uint32
const (
	AttachKprobeMethodNotSet KprobeAttachMethod = iota
	AttachKprobeWithPerfEventOpen
	AttachKprobeWithKprobeEvents
)

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 []*RingBuffer

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

	// InstructionPatcher - Callback function called before loading probes, to
	// provide user the ability to perform last minute instruction patching.
	InstructionPatcher func(m *Manager) error
	// 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

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 workaround 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 note work with this method.

func (*Manager) DetachHook

func (m *Manager) DetachHook(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)

DumpMaps - Return a string containing 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) GetNetlinkSocket

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) 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) GetRingBuffer

func (m *Manager) GetRingBuffer(name string) (*RingBuffer, 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

func (*Manager) InitWithOptions

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

InitWithOptions - Initialize the manager. elf: reader containing the eBPF bytecode options: options provided to the manager to configure its initialization

func (*Manager) NewMap

func (m *Manager) NewMap(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, 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

func (m *Manager) NewRingBuffer(spec ebpf.MapSpec, options MapOptions, ringBufferOptions RingBufferOptions) (*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.2.4

func (m *Manager) Pause() error

func (*Manager) RenameProbeIdentificationPair

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.2.4

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) 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 - Whether to freeze a map after setting its initial contents.
	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. When externalCleanup is set to true, even if the map was recovered from an external source (pinned or rewritten from another manager), the map is cleaned up.

type MapCleanupType

type MapCleanupType int

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

We call "external" a map that wasn't loaded by the current manager. Those maps can end up being used by the current manager through 2 different ways: either because they were pinned or because they were edited into the programs of the manager before they were loaded. However those maps might still be used by other managers out there, even after the current one closes.

A map can only be in one of the following categories

             ----------------------         ---------------------------------------
            |   Internally loaded  |       |           Externally loaded           |
             ----------------------         ---------------------------------------
Categories: |  Pinned | Not Pinned |       |  Pinned | Pinned and Edited  | Edited |
             ----------------------         ---------------------------------------
const (
	CleanInternalPinned          MapCleanupType = 1 << 1
	CleanInternalNotPinned       MapCleanupType = 1 << 2
	CleanExternalPinned          MapCleanupType = 1 << 3
	CleanExternalPinnedAndEdited MapCleanupType = 1 << 4
	CleanExternalEdited          MapCleanupType = 1 << 5
	CleanInternal                MapCleanupType = CleanInternalPinned | CleanInternalNotPinned
	CleanExternal                MapCleanupType = CleanExternalPinned | CleanExternalPinnedAndEdited | CleanExternalEdited
	CleanAll                     MapCleanupType = CleanInternal | CleanExternal
)

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 clean up type given to the manager. See CleanupType for more.
	AlwaysCleanup bool
}

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
	// EditorFlag - Use this flag to specify what fields should be updated. See MapSpecEditorFlag.
	EditorFlag MapSpecEditorFlag
}

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
)

type NetlinkSocket

type NetlinkSocket struct {
	Sock          *netlink.Handle
	TCFilterCount map[int]int
}

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

func NewNetlinkSocket

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

NewNetlinkSocket - Returns a new NetlinkSocket instance

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

	// 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

	// 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

	// 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

	// RingBufferSize - Manager-level default value for the ring buffers. Defaults to the size of 1 page
	// on the system.
	DefaultRingBufferSize 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

	// 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

	// RLimit - 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.
	RLimit *unix.Rlimit

	// KeepKernelBTF - Defines if the kernel types defined in VerifierOptions.Programs.KernelTypes should be cleaned up
	// once the manager is done using them. By default, the manager will clean them up to save up space. DISCLAIMER: if
	// your program uses "manager.CloneProgram", you might want to enable "KeepKernelBTF". As a workaround, you can also
	// try to strip as much as possible the content of "KernelTypes" to reduce the memory overhead.
	KeepKernelBTF 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) 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

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

	// 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
}

PerfMapOptions - Perf map specific options

type Probe

type Probe struct {

	// ProbeIdentificationPair is used to identify the current probe
	ProbeIdentificationPair

	// 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

	// UprobeOffset - If UprobeOffset is provided, the uprobe will be attached to it directly without looking for the
	// symbol in the elf binary. If the file is a non-PIE executable, the provided address must be a virtual address,
	// otherwise it must be an offset relative to the file load address.
	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 virtuel 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 cleanup 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

func (p *Probe) GetEBPFFuncName() string

GetEBPFFuncName - Returns EBPFFuncName with the UID as a postfix if the Probe was copied

func (*Probe) GetKprobeType added in v0.2.0

func (p *Probe) GetKprobeType() string

GetKprobeType - Identifies the probe type of the provided KProbe section

func (*Probe) GetLastError

func (p *Probe) GetLastError() error

GetLastError - Returns the last error that the probe encountered

func (*Probe) GetUprobeType added in v0.2.0

func (p *Probe) GetUprobeType() string

GetUprobeType - Identifies the probe type of the provided Uprobe section

func (*Probe) IsInitialized

func (p *Probe) IsInitialized() bool

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

func (*Probe) IsRunning

func (p *Probe) IsRunning() bool

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

func (*Probe) IsTCFilterActive

func (p *Probe) IsTCFilterActive() bool

func (*Probe) Pause added in v0.2.4

func (p *Probe) Pause() error

func (*Probe) Program

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

func (*Probe) RenameProbeIdentificationPair

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.2.4

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

	// EBPFSection - Section in which EBPFFuncName lives.
	//
	// Deprecated: Only EBPFFuncName is necessary
	EBPFSection string
	// contains filtered or unexported fields
}

func (ProbeIdentificationPair) EBPFDefinitionMatches

func (pip ProbeIdentificationPair) EBPFDefinitionMatches(id ProbeIdentificationPair) bool

EBPFDefinitionMatches - Returns true if the eBPF definition matches.

func (ProbeIdentificationPair) Matches

Matches - Returns true if the identification pair (probe uid, probe section, probe func name) 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

type RingBuffer struct {

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

func (*RingBuffer) Start

func (rb *RingBuffer) Start() error

Start - Starts fetching events on a perf ring buffer

func (*RingBuffer) Stop

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

Stop - Stops the perf ring buffer

type RingBufferOptions

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

	// 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 *RingBuffer, manager *Manager)
}

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" - kernel automatically
	// selects best mode (would try Drv first, then fallback to Generic).
	// NOTE: Kernel will not fallback 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)
	// DefaultTCFilterPriority is the default TC filter priority if none were given
	DefaultTCFilterPriority = 50
)

Jump to

Keyboard shortcuts

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