github.com/dylandreimerink/gobpfld@v0.6.1-0.20220205171531-e79c330ad608/cmd/examples/kprobe_execve_stats/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"time"
     7  
     8  	"github.com/dylandreimerink/gobpfld"
     9  	"github.com/dylandreimerink/gobpfld/bpftypes"
    10  )
    11  
    12  func main() {
    13  	elf, err := os.Open("bpf/tracex1_kern")
    14  	if err != nil {
    15  		panic(err)
    16  	}
    17  
    18  	loadedElf, err := gobpfld.LoadProgramFromELF(elf, gobpfld.ELFParseSettings{
    19  		TruncateNames: true,
    20  	})
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  
    25  	stats := loadedElf.Maps["execve_stats"].(*gobpfld.ArrayMap)
    26  	err = stats.Load()
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  
    31  	program := loadedElf.Programs["bpf_prog1"].(*gobpfld.ProgramKProbe)
    32  
    33  	log, err := program.Load(gobpfld.ProgKPLoadOpts{
    34  		VerifierLogLevel: bpftypes.BPFLogLevelVerbose,
    35  		VerifierLogSize:  1 << 20,
    36  	})
    37  	if err != nil {
    38  		fmt.Println(log)
    39  		panic(err)
    40  	}
    41  
    42  	err = program.Attach(gobpfld.ProgKPAttachOpts{})
    43  	if err != nil {
    44  		panic(err)
    45  	}
    46  
    47  	defer func() {
    48  		err = program.Detach()
    49  		if err != nil {
    50  			panic(err)
    51  		}
    52  	}()
    53  
    54  	for i := 0; i < 10; i++ {
    55  		time.Sleep(1 * time.Second)
    56  		var val uint64
    57  		err = stats.Get(0, &val)
    58  		if err != nil {
    59  			fmt.Println(err.Error())
    60  		}
    61  		fmt.Println(val)
    62  	}
    63  }