github.com/cilium/ebpf@v0.10.0/examples/tracepoint_in_c/main.go (about)

     1  // This program demonstrates attaching an eBPF program to a kernel tracepoint.
     2  // The eBPF program will be attached to the page allocation tracepoint and
     3  // prints out the number of times it has been reached. The tracepoint fields
     4  // are printed into /sys/kernel/debug/tracing/trace_pipe.
     5  package main
     6  
     7  import (
     8  	"log"
     9  	"time"
    10  
    11  	"github.com/cilium/ebpf/link"
    12  	"github.com/cilium/ebpf/rlimit"
    13  )
    14  
    15  // $BPF_CLANG and $BPF_CFLAGS are set by the Makefile.
    16  //go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf tracepoint.c -- -I../headers
    17  
    18  const mapKey uint32 = 0
    19  
    20  func main() {
    21  	// Allow the current process to lock memory for eBPF resources.
    22  	if err := rlimit.RemoveMemlock(); err != nil {
    23  		log.Fatal(err)
    24  	}
    25  
    26  	// Load pre-compiled programs and maps into the kernel.
    27  	objs := bpfObjects{}
    28  	if err := loadBpfObjects(&objs, nil); err != nil {
    29  		log.Fatalf("loading objects: %v", err)
    30  	}
    31  	defer objs.Close()
    32  
    33  	// Open a tracepoint and attach the pre-compiled program. Each time
    34  	// the kernel function enters, the program will increment the execution
    35  	// counter by 1. The read loop below polls this map value once per
    36  	// second.
    37  	// The first two arguments are taken from the following pathname:
    38  	// /sys/kernel/debug/tracing/events/kmem/mm_page_alloc
    39  	kp, err := link.Tracepoint("kmem", "mm_page_alloc", objs.MmPageAlloc, nil)
    40  	if err != nil {
    41  		log.Fatalf("opening tracepoint: %s", err)
    42  	}
    43  	defer kp.Close()
    44  
    45  	// Read loop reporting the total amount of times the kernel
    46  	// function was entered, once per second.
    47  	ticker := time.NewTicker(1 * time.Second)
    48  	defer ticker.Stop()
    49  
    50  	log.Println("Waiting for events..")
    51  	for range ticker.C {
    52  		var value uint64
    53  		if err := objs.CountingMap.Lookup(mapKey, &value); err != nil {
    54  			log.Fatalf("reading map: %v", err)
    55  		}
    56  		log.Printf("%v times", value)
    57  	}
    58  }