bpf

package
v1.14.0-snapshot.1 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2023 License: Apache-2.0 Imports: 40 Imported by: 296

Documentation

Overview

Package bpf provides functions that allow golang programs to interact with bpf maps. +groupName=pkg

Index

Constants

View Source
const (
	// BPF syscall command constants. Must match enum bpf_cmd from linux/bpf.h
	BPF_MAP_CREATE          = 0
	BPF_MAP_LOOKUP_ELEM     = 1
	BPF_MAP_UPDATE_ELEM     = 2
	BPF_MAP_DELETE_ELEM     = 3
	BPF_MAP_GET_NEXT_KEY    = 4
	BPF_PROG_LOAD           = 5
	BPF_OBJ_PIN             = 6
	BPF_OBJ_GET             = 7
	BPF_PROG_ATTACH         = 8
	BPF_PROG_DETACH         = 9
	BPF_PROG_TEST_RUN       = 10
	BPF_PROG_GET_NEXT_ID    = 11
	BPF_MAP_GET_NEXT_ID     = 12
	BPF_PROG_GET_FD_BY_ID   = 13
	BPF_MAP_GET_FD_BY_ID    = 14
	BPF_OBJ_GET_INFO_BY_FD  = 15
	BPF_PROG_QUERY          = 16
	BPF_RAW_TRACEPOINT_OPEN = 17
	BPF_BTF_LOAD            = 18
	BPF_BTF_GET_FD_BY_ID    = 19
	BPF_TASK_FD_QUERY       = 20

	// BPF syscall attach types
	BPF_CGROUP_INET_INGRESS      = 0
	BPF_CGROUP_INET_EGRESS       = 1
	BPF_CGROUP_INET_SOCK_CREATE  = 2
	BPF_CGROUP_SOCK_OPS          = 3
	BPF_SK_SKB_STREAM_PARSER     = 4
	BPF_SK_SKB_STREAM_VERDICT    = 5
	BPF_CGROUP_DEVICE            = 6
	BPF_SK_MSG_VERDICT           = 7
	BPF_CGROUP_INET4_BIND        = 8
	BPF_CGROUP_INET6_BIND        = 9
	BPF_CGROUP_INET4_CONNECT     = 10
	BPF_CGROUP_INET6_CONNECT     = 11
	BPF_CGROUP_INET4_POST_BIND   = 12
	BPF_CGROUP_INET6_POST_BIND   = 13
	BPF_CGROUP_UDP4_SENDMSG      = 14
	BPF_CGROUP_UDP6_SENDMSG      = 15
	BPF_LIRC_MODE2               = 16
	BPF_FLOW_DISSECTOR           = 17
	BPF_CGROUP_SYSCTL            = 18
	BPF_CGROUP_UDP4_RECVMSG      = 19
	BPF_CGROUP_UDP6_RECVMSG      = 20
	BPF_CGROUP_INET4_GETPEERNAME = 29
	BPF_CGROUP_INET6_GETPEERNAME = 30
	BPF_CGROUP_INET4_GETSOCKNAME = 31
	BPF_CGROUP_INET6_GETSOCKNAME = 32

	// Flags for BPF_MAP_UPDATE_ELEM. Must match values from linux/bpf.h
	BPF_ANY     = 0
	BPF_NOEXIST = 1
	BPF_EXIST   = 2

	// Flags for BPF_MAP_CREATE. Must match values from linux/bpf.h
	BPF_F_NO_PREALLOC   = 1 << 0
	BPF_F_NO_COMMON_LRU = 1 << 1
	BPF_F_NUMA_NODE     = 1 << 2

	// Flags for BPF_PROG_QUERY
	BPF_F_QUERY_EFFECTVE = 1 << 0

	// Flags for accessing BPF object
	BPF_F_RDONLY = 1 << 3
	BPF_F_WRONLY = 1 << 4

	// Flag for stack_map, store build_id+offset instead of pointer
	BPF_F_STACK_BUILD_ID = 1 << 5
)
View Source
const (
	EndpointKeyIPv4 uint8 = 1
	EndpointKeyIPv6 uint8 = 2
)

Must be in sync with ENDPOINT_KEY_* in <bpf/lib/common.h>

Variables

View Source
var ErrMaxLookup = errors.New("maximum number of lookups reached")

ErrMaxLookup is returned when the maximum number of map element lookups has been reached.

Functions

func CheckOrMountFS added in v0.15.7

func CheckOrMountFS(bpfRoot string)

CheckOrMountFS checks or mounts the BPF filesystem and then opens/creates/deletes all maps which have previously been scheduled to be opened/created/deleted.

If printWarning is set, will print a warning if bpffs has not previously been mounted.

func ConvertKeyValue added in v1.5.0

func ConvertKeyValue(bKey []byte, bValue []byte, key MapKey, value MapValue) (MapKey, MapValue, error)

ConvertKeyValue converts key and value from bytes to given Golang struct pointers.

func CreateMap

func CreateMap(mapType MapType, keySize, valueSize, maxEntries, flags, innerID uint32, fullPath string) (int, error)

CreateMap creates a Map of type mapType, with key size keySize, a value size of valueSize and the maximum amount of entries of maxEntries. mapType should be one of the bpf_map_type in "uapi/linux/bpf.h" When mapType is the type HASH_OF_MAPS an innerID is required to point at a map fd which has the same type/keySize/valueSize/maxEntries as expected map entries. For all other mapTypes innerID is ignored and should be zeroed.

func DeleteElement

func DeleteElement(fd int, key unsafe.Pointer) error

DeleteElement deletes the map element with the given key.

func DisableMapPreAllocation added in v0.15.7

func DisableMapPreAllocation()

DisableMapPreAllocation disables BPF map pre-allocation as a default setting. Some map types enforces pre-alloc strategy so this does not take effect in that case. Also note that this does not take effect on existing map although could be recreated later when objCheck() runs.

func EnableMapPreAllocation added in v0.15.7

func EnableMapPreAllocation()

EnableMapPreAllocation enables BPF map pre-allocation on map types that support it. This does not take effect on existing map although some map types could be recreated later when objCheck() runs.

func Environment added in v1.5.0

func Environment() []string

Environment returns a list of environment variables which are needed to make BPF programs and tc aware of the actual BPFFS mount path.

func FinalizeBPFFSMigration added in v0.15.7

func FinalizeBPFFSMigration(bpffsPath string, coll *ebpf.CollectionSpec, revert bool) error

FinalizeBPFFSMigration finalizes the migration of an ELF's maps. If revert is true, any pending maps are re-pinned back to their original locations. If revert is false, any pending maps are unpinned (deleted).

Takes a bpffsPath explicitly since it does not necessarily execute within the same runtime as the agent. It is imported from a Cilium cmd that takes its bpffs path from an env.

func GetFirstKey added in v1.6.0

func GetFirstKey(fd int, nextKey unsafe.Pointer) error

GetFirstKey fetches the first key in the map. If there are no keys in the map, io.EOF is returned.

func GetJtime added in v1.8.0

func GetJtime() (uint64, error)

GetJtime returns a close-enough approximation of kernel jiffies that can be used to compare against jiffies BPF helper. We parse it from /proc/timer_list. GetJtime() should be invoked only at mid-low frequencies.

func GetMapRoot

func GetMapRoot() string

func GetMtime added in v0.9.0

func GetMtime() (uint64, error)

GetMtime returns monotonic time that can be used to compare values with ktime_get_ns() BPF helper, e.g. needed to check the timeout in sec for BPF entries. We return the raw nsec, although that is not quite usable for comparison. Go has runtime.nanotime() but doesn't expose it as API.

func GetNextKey

func GetNextKey(fd int, key, nextKey unsafe.Pointer) error

GetNextKey stores, in nextKey, the next key after the key of the map in fd. Deprecated, use GetNextKeyFromPointers

func GetNextKeyFromPointers added in v1.5.1

func GetNextKeyFromPointers(fd int, structPtr unsafe.Pointer, sizeOfStruct uintptr) error

GetNextKeyFromPointers stores, in nextKey, the next key after the key of the map in fd. When there are no more keys, io.EOF is returned.

func GetOpenMaps added in v0.15.7

func GetOpenMaps() []*models.BPFMap

GetOpenMaps returns a slice of all open BPF maps. This is identical to calling GetMap() on all open maps.

func GetPreAllocateMapFlags added in v0.15.7

func GetPreAllocateMapFlags(t MapType) uint32

GetPreAllocateMapFlags returns the map flags for map which use conditional pre-allocation.

func LoadCollection added in v0.15.7

func LoadCollection(spec *ebpf.CollectionSpec, opts ebpf.CollectionOptions) (*ebpf.Collection, error)

LoadCollection loads the given spec into the kernel with the specified opts.

The value given in ProgramOptions.LogSize is used as the starting point for sizing the verifier's log buffer and defaults to 4MiB. On each retry, the log buffer quadruples in size, for a total of 5 attempts. If that proves insufficient, a truncated ebpf.VerifierError is returned.

Any maps marked as pinned in the spec are automatically loaded from the path given in opts.Maps.PinPath and will be used instead of creating new ones. MapSpecs that differ (type/key/value/max/flags) from their pinned versions will result in an ebpf.ErrMapIncompatible here and the map must be removed before loading the CollectionSpec.

func LoadCollectionSpec added in v0.15.7

func LoadCollectionSpec(path string) (*ebpf.CollectionSpec, error)

LoadCollectionSpec loads the eBPF ELF at the given path and parses it into a CollectionSpec. This spec is only a blueprint of the contents of the ELF and does not represent any live resources that have been loaded into the kernel.

This is a wrapper around ebpf.LoadCollectionSpec that parses legacy iproute2 bpf_elf_map definitions (only used for prog_arrays at the time of writing) and assigns tail calls annotated with `__section_tail` macros to their intended maps and slots.

func LocalMapName added in v0.15.7

func LocalMapName(name string, id uint16) string

LocalMapName returns the name for a BPF map that is local to the specified ID.

func LocalMapPath added in v0.15.7

func LocalMapPath(name string, id uint16) string

LocalMapPath returns the path for a BPF map that is local to the specified ID.

func LookupElement

func LookupElement(fd int, key, value unsafe.Pointer) error

LookupElement looks up for the map value stored in fd with the given key. The value is stored in the value unsafe.Pointer. Deprecated, use LookupElementFromPointers

func LookupElementFromPointers added in v1.5.1

func LookupElementFromPointers(fd int, structPtr unsafe.Pointer, sizeOfStruct uintptr) error

LookupElement looks up for the map value stored in fd with the given key. The value is stored in the value unsafe.Pointer.

func MapFdFromID added in v1.5.0

func MapFdFromID(id int) (int, error)

MapFdFromID retrieves a file descriptor based on a map ID.

func MapPath

func MapPath(name string) string

MapPath returns a path for a BPF map with a given name.

func MapPrefixPath

func MapPrefixPath() string

func ObjClose added in v0.9.0

func ObjClose(fd int) error

ObjClose closes the map's fd.

func ObjGet

func ObjGet(pathname string) (int, error)

ObjGet reads the pathname and returns the map's fd read.

func ObjPin

func ObjPin(fd int, pathname string) error

ObjPin stores the map's fd in pathname.

func OpenOrCreateMap

func OpenOrCreateMap(path string, mapType MapType, keySize, valueSize, maxEntries, flags uint32, innerID uint32, pin bool) (int, bool, error)

func StartBPFFSMigration added in v0.15.7

func StartBPFFSMigration(bpffsPath string, coll *ebpf.CollectionSpec) error

StartBPFFSMigration the map migration process for a given ELF's maps. When a new ELF contains a map definition that differs from its existing (pinned) counterpart, re-pin it to its current path suffixed by ':pending'. A map's type, key size, value size, flags and max entries are compared to the given spec.

Takes a bpffsPath explicitly since it does not necessarily execute within the same runtime as the agent. It is imported from a Cilium cmd that takes its bpffs path from an env.

func TestDummyProg added in v1.6.0

func TestDummyProg(progType ProgType, attachType uint32) error

TestDummyProg loads a minimal BPF program into the kernel and probes whether it succeeds in doing so. This can be used to bail out early in the daemon when a given type is not supported.

func UnpinMapIfExists added in v1.7.0

func UnpinMapIfExists(name string) error

UnpinMapIfExists unpins the given map identified by name. If the map doesn't exist, returns success.

func UpdateElement

func UpdateElement(fd int, mapName string, key, value unsafe.Pointer, flags uint64) error

UpdateElement updates the map in fd with the given value in the given key. The flags can have the following values: bpf.BPF_ANY to create new element or update existing; bpf.BPF_NOEXIST to create new element if it didn't exist; bpf.BPF_EXIST to update existing element. Deprecated, use UpdateElementFromPointers

func UpdateElementFromPointers added in v1.5.1

func UpdateElementFromPointers(fd int, mapName string, structPtr unsafe.Pointer, sizeOfStruct uintptr) error

UpdateElementFromPointers updates the map in fd with the given value in the given key.

Types

type Action added in v0.15.7

type Action uint8

Action describes an action for map buffer events.

const (
	// MapUpdate describes a map.Update event.
	MapUpdate Action = iota
	// MapDelete describes a map.Delete event.
	MapDelete
	// MapDeleteAll describes a map.DeleteAll event which is aggregated into a single event
	// to minimize memory and subscription buffer usage.
	MapDeleteAll
)

func (Action) String added in v0.15.7

func (e Action) String() string

String returns a string representation of an Action.

type DesiredAction added in v0.15.7

type DesiredAction uint8

DesiredAction is the action to be performed on the BPF map

const (
	// OK indicates that to further action is required and the entry is in
	// sync
	OK DesiredAction = iota

	// Insert indicates that the entry needs to be created or updated
	Insert

	// Delete indicates that the entry needs to be deleted
	Delete
)

func (DesiredAction) String added in v0.15.7

func (d DesiredAction) String() string

type DumpCallback

type DumpCallback func(key MapKey, value MapValue)

type DumpParser

type DumpParser func(key []byte, value []byte, mapKey MapKey, mapValue MapValue) (MapKey, MapValue, error)

type DumpStats added in v0.15.7

type DumpStats struct {
	// Started is the timestamp when the gc run was started.
	Started time.Time

	// Finished is the timestamp when the gc run completed.
	Finished time.Time

	// Lookup is the number of key lookups performed.
	Lookup uint32

	// LookupFailed is the number of key lookups that failed.
	LookupFailed uint32

	// PrevKeyUnavailable is the number of times the previous key was not
	// available.
	PrevKeyUnavailable uint32

	// KeyFallback is the number of times the current key became invalid
	// while traversing and we had to fall back to the previous key.
	KeyFallback uint32

	// MaxEntries is the maximum number of entries in the gc table.
	MaxEntries uint32

	// Interrupted is the number of times the gc run was interrupted and
	// had to start from scratch.
	Interrupted uint32

	// Completed is true when the gc run has been completed.
	Completed bool
}

DumpStats tracks statistics over the dump of a map.

func NewDumpStats added in v0.15.7

func NewDumpStats(m *Map) *DumpStats

NewDumpStats returns a new stats structure for collecting dump statistics.

func (*DumpStats) Duration added in v0.15.7

func (d *DumpStats) Duration() time.Duration

Duration returns the duration of the dump.

type EndpointKey added in v0.15.7

type EndpointKey struct {
	// represents both IPv6 and IPv4 (in the lowest four bytes)
	IP        types.IPv6 `align:"$union0"`
	Family    uint8      `align:"family"`
	Key       uint8      `align:"key"`
	ClusterID uint8      `align:"cluster_id"`
	Pad       uint8      `align:"pad"`
}

EndpointKey represents the key value of the endpoints BPF map

Must be in sync with struct endpoint_key in <bpf/lib/common.h> +k8s:deepcopy-gen=true

func NewEndpointKey added in v0.15.7

func NewEndpointKey(ip net.IP, clusterID uint8) EndpointKey

NewEndpointKey returns an EndpointKey based on the provided IP address. The address family is automatically detected.

func (*EndpointKey) DeepCopy added in v1.5.1

func (in *EndpointKey) DeepCopy() *EndpointKey

DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointKey.

func (*EndpointKey) DeepCopyInto added in v1.5.1

func (in *EndpointKey) DeepCopyInto(out *EndpointKey)

DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (*EndpointKey) GetKeyPtr added in v1.5.0

func (k *EndpointKey) GetKeyPtr() unsafe.Pointer

GetKeyPtr returns the unsafe pointer to the BPF key

func (*EndpointKey) GetValuePtr added in v1.5.0

func (k *EndpointKey) GetValuePtr() unsafe.Pointer

GetValuePtr returns the unsafe pointer to the BPF key for users that use EndpointKey as a value in bpf maps

func (EndpointKey) String added in v0.15.7

func (k EndpointKey) String() string

String provides a string representation of the EndpointKey.

func (EndpointKey) ToIP added in v0.15.7

func (k EndpointKey) ToIP() net.IP

ToIP converts the EndpointKey into a net.IP structure.

type Event added in v0.15.7

type Event struct {
	Timestamp time.Time
	// contains filtered or unexported fields
}

Event contains data about a bpf operation event.

func (*Event) GetAction added in v0.15.7

func (e *Event) GetAction() string

GetAction returns the event action string.

func (Event) GetDesiredAction added in v0.15.7

func (e Event) GetDesiredAction() DesiredAction

GetDesiredAction returns the desired action enum for an event.

func (Event) GetKey added in v0.15.7

func (e Event) GetKey() string

GetKey returns the string representation of a event key.

func (Event) GetLastError added in v0.15.7

func (e Event) GetLastError() error

GetLastError returns the last error for an event.

func (Event) GetValue added in v0.15.7

func (e Event) GetValue() string

GetValue returns the string representation of a event value. Nil values (such as with deletes) are returned as a canonical string representation.

type EventCallbackFunc added in v0.15.7

type EventCallbackFunc func(*Event)

EventCallbackFunc is used to dump events from a event buffer.

type Handle added in v0.15.7

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

Handle allows for handling event streams safely outside of this package. The key design consideration for event streaming is that it is non-blocking. The eventsBuffer takes care of closing handles when their consumer is not reading off the buffer (or is not reading off it fast enough).

func (*Handle) C added in v0.15.7

func (h *Handle) C() <-chan *Event

Returns read only channel for Handle subscription events. Channel should be closed with handle.Close() function.

func (*Handle) Close added in v0.15.7

func (h *Handle) Close()

Close allows for safaley closing of a handle.

type Map

type Map struct {
	MapInfo

	// NonPersistent is true if the map does not contain persistent data
	// and should be removed on startup.
	NonPersistent bool

	// DumpParser is a function for parsing keys and values from BPF maps
	DumpParser DumpParser
	// contains filtered or unexported fields
}

func GetMap added in v0.15.7

func GetMap(name string) *Map

GetMap returns the registered map with the given name or absolute path

func NewMap

func NewMap(name string, mapType MapType, mapKey MapKey, keySize int,
	mapValue MapValue, valueSize, maxEntries int, flags uint32, innerID uint32,
	dumpParser DumpParser) *Map

NewMap creates a new Map instance - object representing a BPF map

func NewPerCPUHashMap added in v1.6.0

func NewPerCPUHashMap(name string, mapKey MapKey, keySize int, mapValue MapValue, valueSize, cpus, maxEntries int, flags uint32, innerID uint32, dumpParser DumpParser) *Map

NewPerCPUHashMap creates a new Map type of "per CPU hash" - object representing a BPF map The number of cpus is used to have the size representation of a value when a lookup is made on this map types.

func OpenMap

func OpenMap(name string) (*Map, error)

OpenMap opens the given bpf map and generates the Map info based in the information stored in the bpf map. *Warning*: Calling this function requires the caller to properly setup the MapInfo.MapKey and MapInfo.MapValues fields as those structures are not stored in the bpf map.

func (*Map) CheckAndUpgrade added in v0.15.7

func (m *Map) CheckAndUpgrade(desired *MapInfo) bool

CheckAndUpgrade checks the received map's properties (for the map currently loaded into the kernel) against the desired properties, and if they do not match, deletes the map.

Returns true if the map was upgraded.

func (*Map) Close

func (m *Map) Close() error

func (*Map) Create added in v0.15.7

func (m *Map) Create() (bool, error)

Create is similar to OpenOrCreate, but closes the map after creating or opening it.

func (*Map) CreateUnpinned added in v0.15.7

func (m *Map) CreateUnpinned() error

CreateUnpinned creates the map without pinning it to the file system.

func (*Map) Delete

func (m *Map) Delete(key MapKey) error

Delete deletes the map entry corresponding to the given key.

func (*Map) DeleteAll

func (m *Map) DeleteAll() error

DeleteAll deletes all entries of a map by traversing the map and deleting individual entries. Note that if entries are added while the taversal is in progress, such entries may survive the deletion process.

func (*Map) Dump

func (m *Map) Dump(hash map[string][]string) error

Dump returns the map (type map[string][]string) which contains all data stored in BPF map.

func (*Map) DumpAndSubscribe added in v0.15.7

func (m *Map) DumpAndSubscribe(callback EventCallbackFunc, follow bool) (*Handle, error)

DumpAndSubscribe dumps existing buffer, if callback is not nil. Followed by creating a subscription to the maps events buffer and returning the handle. These actions are done together so as to prevent possible missed events between the handoff of the callback and sub handle creation.

func (*Map) DumpIfExists added in v0.15.7

func (m *Map) DumpIfExists(hash map[string][]string) error

DumpIfExists dumps the contents of the map into hash via Dump() if the map file exists

func (*Map) DumpReliablyWithCallback added in v0.15.7

func (m *Map) DumpReliablyWithCallback(cb DumpCallback, stats *DumpStats) error

DumpReliablyWithCallback is similar to DumpWithCallback, but performs additional tracking of the current and recently seen keys, so that if an element is removed from the underlying kernel map during the dump, the dump can continue from a recently seen key rather than restarting from scratch. In addition, it caps the maximum number of map entry iterations at 4 times the maximum map size. If this limit is reached, ErrMaxLookup is returned.

The caller must provide a callback for handling each entry, and a stats object initialized via a call to NewDumpStats().

func (*Map) DumpWithCallback added in v0.15.7

func (m *Map) DumpWithCallback(cb DumpCallback) error

DumpWithCallback iterates over the Map and calls the given callback function on each iteration. That callback function is receiving the actual key and value. The callback function should consider creating a deepcopy of the key and value on between each iterations to avoid memory corruption.

func (*Map) DumpWithCallbackIfExists added in v0.15.7

func (m *Map) DumpWithCallbackIfExists(cb DumpCallback) error

DumpWithCallbackIfExists is similar to DumpWithCallback, but returns earlier if the given map does not exist.

func (*Map) EndParallelMode added in v1.5.0

func (m *Map) EndParallelMode()

EndParallelMode ends the parallel mode of a map

func (*Map) GetFd

func (m *Map) GetFd() int

func (*Map) GetModel added in v0.15.7

func (m *Map) GetModel() *models.BPFMap

GetModel returns a BPF map in the representation served via the API

func (*Map) GetNextKey added in v0.9.0

func (m *Map) GetNextKey(key MapKey, nextKey MapKey) error

GetNextKey returns the next key in the Map after key.

func (*Map) IsEventsEnabled added in v0.15.7

func (m *Map) IsEventsEnabled() bool

func (*Map) Lookup

func (m *Map) Lookup(key MapKey) (MapValue, error)

func (*Map) Name added in v0.15.7

func (m *Map) Name() string

Name returns the basename of this map.

func (*Map) NonPrefixedName added in v0.15.7

func (m *Map) NonPrefixedName() string

func (*Map) Open

func (m *Map) Open() error

Open opens the BPF map. All calls to Open() are serialized due to acquiring m.lock

func (*Map) OpenOrCreate

func (m *Map) OpenOrCreate() (bool, error)

OpenOrCreate attempts to open the Map, or if it does not yet exist, create the Map. If the existing map's attributes such as map type, key/value size, capacity, etc. do not match the Map's attributes, then the map will be deleted and reopened without any attempt to retain its previous contents. If the map is marked as non-persistent, it will always be recreated.

Returns whether the map was deleted and recreated, or an optional error.

func (*Map) OpenParallel added in v1.5.0

func (m *Map) OpenParallel() (bool, error)

OpenParallel is similar to OpenOrCreate() but prepares the existing map to be faded out while a new map is taking over. This can be used if a map is shared between multiple consumers and the context of the shared map is changing. Any update to the shared map would impact all consumers and consumers can only be updated one by one. Parallel mode allows for consumers to continue using the old version of the map until the consumer is updated to use the new version.

func (*Map) Path added in v0.15.7

func (m *Map) Path() (string, error)

Path returns the path to this map on the filesystem.

func (*Map) Reopen added in v1.5.0

func (m *Map) Reopen() error

Reopen attempts to close and re-open the received map.

func (*Map) SilentDelete added in v0.15.7

func (m *Map) SilentDelete(key MapKey) (deleted bool, err error)

SilentDelete deletes the map entry corresponding to the given key. If a map entry is not found this returns (true, nil).

func (*Map) Unpin added in v0.15.7

func (m *Map) Unpin() error

Unpin attempts to unpin (remove) the map from the filesystem.

func (*Map) UnpinIfExists added in v0.15.7

func (m *Map) UnpinIfExists() error

UnpinIfExists tries to unpin (remove) the map only if it exists.

func (*Map) Update

func (m *Map) Update(key MapKey, value MapValue) error

func (*Map) WithCache added in v0.15.7

func (m *Map) WithCache() *Map

WithCache enables use of a cache. This will store all entries inserted from user space in a local cache (map) and will indicate the status of each individual entry.

func (*Map) WithEvents added in v0.15.7

func (m *Map) WithEvents(c option.BPFEventBufferConfig) *Map

WithEvents enables use of the event buffer, if the buffer is enabled. This stores all map events (i.e. add/update/delete) in a bounded event buffer. If eventTTL is not zero, than events that are older than the TTL will periodically be removed from the buffer. Enabling events will use aprox proportional to 100MB for every million capacity in maxSize.

TODO: The IPCache map have many periodic update events added by a controller for entries such as the 0.0.0.0/0 range. These fill the event buffer with possibly unnecessary events. We should either provide an option to aggregate these events, ignore hem from the ipcache event buffer or store them in a separate buffer.

func (*Map) WithNonPersistent added in v0.10.0

func (m *Map) WithNonPersistent() *Map

WithNonPersistent turns the map non-persistent and returns the map

func (*Map) WithPressureMetric added in v0.15.7

func (m *Map) WithPressureMetric() *Map

WithPressureMetric enables tracking and reporting of this map pressure with threshold 0.

func (*Map) WithPressureMetricThreshold added in v0.15.7

func (m *Map) WithPressureMetricThreshold(threshold float64) *Map

WithPressureMetricThreshold enables the tracking of a metric that measures the pressure of this map. This metric is only reported if over the threshold.

type MapInfo

type MapInfo struct {
	MapType  MapType
	MapKey   MapKey
	KeySize  uint32
	MapValue MapValue
	// ReadValueSize is the value size that is used to read from the BPF maps
	// this value and the ValueSize values can be different for MapTypePerCPUHash.
	ReadValueSize uint32
	ValueSize     uint32
	MaxEntries    uint32
	Flags         uint32
	InnerID       uint32
	OwnerProgType ProgType
}

func GetMapInfo

func GetMapInfo(pid int, fd int) (*MapInfo, error)

type MapKey

type MapKey interface {
	fmt.Stringer

	// Returns pointer to start of key
	GetKeyPtr() unsafe.Pointer

	// Allocates a new value matching the key type
	NewValue() MapValue

	// DeepCopyMapKey returns a deep copy of the map key
	DeepCopyMapKey() MapKey
}

type MapType

type MapType int

MapType is an enumeration for valid BPF map types

const (
	MapTypeUnspec MapType = iota
	MapTypeHash
	MapTypeArray
	MapTypeProgArray
	MapTypePerfEventArray
	MapTypePerCPUHash
	MapTypePerCPUArray
	MapTypeStackTrace
	MapTypeCgroupArray
	MapTypeLRUHash
	MapTypeLRUPerCPUHash
	MapTypeLPMTrie
	MapTypeArrayOfMaps
	MapTypeHashOfMaps
	MapTypeDevMap
	MapTypeSockMap
	MapTypeCPUMap
	MapTypeXSKMap
	MapTypeSockHash
	// MapTypeMaximum is the maximum supported known map type.
	MapTypeMaximum
)

This enumeration must be in sync with enum bpf_map_type in <linux/bpf.h>

func (MapType) String

func (t MapType) String() string

type MapValidator added in v1.5.0

type MapValidator func(path string) (bool, error)

type MapValue

type MapValue interface {
	fmt.Stringer

	// Returns pointer to start of value
	GetValuePtr() unsafe.Pointer

	// DeepCopyMapValue returns a deep copy of the map value
	DeepCopyMapValue() MapValue
}

type ProgType added in v0.10.0

type ProgType int

ProgType is an enumeration for valid BPF program types

const (
	ProgTypeUnspec ProgType = iota
	ProgTypeSocketFilter
	ProgTypeKprobe
	ProgTypeSchedCls
	ProgTypeSchedAct
	ProgTypeTracepoint
	ProgTypeXdp
	ProgTypePerfEvent
	ProgTypeCgroupSkb
	ProgTypeCgroupSock
	ProgTypeLwtIn
	ProgTypeLwtOut
	ProgTypeLwtXmit
	ProgTypeSockOps
	ProgTypeSkSkb
	ProgTypeCgroupDevice
	ProgTypeSkMsg
	ProgTypeRawTracepoint
	ProgTypeCgroupSockAddr
	ProgTypeLwtSeg6Local
	ProgTypeLircMode2
	ProgTypeSkReusePort
)

This enumeration must be in sync with enum bpf_prog_type in <linux/bpf.h>

func (ProgType) String added in v0.10.0

func (t ProgType) String() string

Directories

Path Synopsis
Package binary is a fork of the upstream golang library.
Package binary is a fork of the upstream golang library.

Jump to

Keyboard shortcuts

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