github.com/dylandreimerink/gobpfld@v0.6.1-0.20220205171531-e79c330ad608/program_tracepoint.go (about)

     1  package gobpfld
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/dylandreimerink/gobpfld/bpfsys"
     7  	"github.com/dylandreimerink/gobpfld/bpftypes"
     8  	"github.com/dylandreimerink/gobpfld/perf"
     9  )
    10  
    11  var _ BPFProgram = (*ProgramTracepoint)(nil)
    12  
    13  type ProgramTracepoint struct {
    14  	AbstractBPFProgram
    15  
    16  	// DefaultCategory is the tracepoint category used if no category is specified during attaching.
    17  	// It can be set when loading from ELF file.
    18  	DefaultCategory string
    19  	// DefaultName is the tracepoint name used if no name is specified during attaching.
    20  	// It can be set when loading from ELF file.
    21  	DefaultName string
    22  
    23  	attachedEvent *perf.Event
    24  }
    25  
    26  type ProgTPLoadOpts struct {
    27  	VerifierLogLevel bpftypes.BPFLogLevel
    28  	VerifierLogSize  int
    29  }
    30  
    31  func (p *ProgramTracepoint) Load(opts ProgTPLoadOpts) (log string, err error) {
    32  	return p.load(bpfsys.BPFAttrProgramLoad{
    33  		LogLevel: opts.VerifierLogLevel,
    34  		LogSize:  uint32(opts.VerifierLogSize),
    35  	})
    36  }
    37  
    38  // Unpin captures the file descriptor of the program at the given 'relativePath' from the kernel.
    39  // If 'deletePin' is true the bpf FS pin will be removed after successfully loading the program, thus transferring
    40  // ownership of the program in a scenario where the program is not shared between multiple userspace programs.
    41  // Otherwise the pin will keep existing which will cause the map to not be deleted when this program exits.
    42  func (p *ProgramTracepoint) Unpin(relativePath string, deletePin bool) error {
    43  	return p.unpin(relativePath, deletePin)
    44  }
    45  
    46  type ProgTPAttachOpts struct {
    47  	Category string
    48  	Name     string
    49  }
    50  
    51  func (p *ProgramTracepoint) Attach(opts ProgTPAttachOpts) error {
    52  	category := p.DefaultCategory
    53  	if opts.Category != "" {
    54  		category = opts.Category
    55  	}
    56  
    57  	name := p.DefaultName
    58  	if opts.Category != "" {
    59  		name = opts.Name
    60  	}
    61  
    62  	var err error
    63  	p.attachedEvent, err = perf.OpenTracepointEvent(category, name)
    64  	if err != nil {
    65  		return fmt.Errorf("open tracepoint: %w", err)
    66  	}
    67  
    68  	err = p.attachedEvent.AttachBPFProgram(p.fd)
    69  	if err != nil {
    70  		return fmt.Errorf("attach program: %w", err)
    71  	}
    72  
    73  	return nil
    74  }
    75  
    76  func (p *ProgramTracepoint) Detach() error {
    77  	return p.attachedEvent.DetachBPFProgram()
    78  }