Advanced Topics and Go Integration

Go Integration

Managing eBPF programs with Go - userspace controller pattern.

cilium/ebpf Fundamentals

Docs: ebpf-go.dev

What you will learn:

  • //go:generate go run github.com/cilium/ebpf/cmd/bpf2go - bind a BPF program to Go
  • CollectionSpec, Program, Map types
  • Program attach/detach
  • Map operations (from Go)

bpf2go Workflow

//go:generate go run github.com/cilium/ebpf/cmd/bpf2go counter xdp_prog.c

func main() {
    objs := counterObjects{}
    if err := loadCounterObjects(&objs, nil); err != nil {
        log.Fatal(err)
    }
    defer objs.Close()

    link, err := link.AttachXDP(link.XDPOptions{
        Program:   objs.XdpProg,
        Interface: ifindex,
    })
    // ...
}

Practical Project

Building an eBPF Process Monitor with Go

  • Process monitor: execve syscall hook
  • Tracepoint usage (sys_enter_execve)
  • Reading events with perf buffer
  • Generating Go bindings with bpf2go
  • Repo

Userspace Controller Pattern

The Go side of a production eBPF application:

Map Management

// Writing to a map
key := uint32(ipAddr)
value := uint32(1) // blocked
err := objs.Blocklist.Put(key, value)

// Reading from a map
var val uint32
err := objs.Blocklist.Lookup(key, &val)

// Deleting from a map
err := objs.Blocklist.Delete(key)

Ring Buffer Consumer

rd, err := ringbuf.NewReader(objs.Events, nil)
for {
    record, err := rd.Read()
    // process record.RawSample
}

Production Requirements

  • Graceful shutdown (signal handling)
  • Exposing Prometheus metrics
  • Config hot-reload (map update)
  • Health check endpoint