github.com/cilium/ebpf@v0.10.0/link/query_test.go (about)

     1  package link
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/cilium/ebpf"
     7  	"github.com/cilium/ebpf/internal/testutils"
     8  )
     9  
    10  func TestQueryPrograms(t *testing.T) {
    11  	for name, fn := range map[string]func(*testing.T) (*ebpf.Program, QueryOptions){
    12  		"cgroup": queryCgroupFixtures,
    13  		"netns":  queryNetNSFixtures,
    14  	} {
    15  		t.Run(name, func(t *testing.T) {
    16  			prog, opts := fn(t)
    17  			ids, err := QueryPrograms(opts)
    18  			testutils.SkipIfNotSupported(t, err)
    19  			if err != nil {
    20  				t.Fatal("Can't query programs:", err)
    21  			}
    22  
    23  			progInfo, err := prog.Info()
    24  			if err != nil {
    25  				t.Fatal("Can't get program info:", err)
    26  			}
    27  
    28  			progId, _ := progInfo.ID()
    29  
    30  			for _, id := range ids {
    31  				if id == progId {
    32  					return
    33  				}
    34  			}
    35  			t.Fatalf("Can't find program ID %d in query result: %v", progId, ids)
    36  		})
    37  	}
    38  }
    39  
    40  func queryCgroupFixtures(t *testing.T) (*ebpf.Program, QueryOptions) {
    41  	cgroup, prog := mustCgroupFixtures(t)
    42  
    43  	link, err := newProgAttachCgroup(cgroup, ebpf.AttachCGroupInetEgress, prog, 0)
    44  	if err != nil {
    45  		t.Fatal("Can't create link:", err)
    46  	}
    47  	t.Cleanup(func() {
    48  		link.Close()
    49  	})
    50  
    51  	return prog, QueryOptions{Path: cgroup.Name(), Attach: ebpf.AttachCGroupInetEgress}
    52  }
    53  
    54  func queryNetNSFixtures(t *testing.T) (*ebpf.Program, QueryOptions) {
    55  	testutils.SkipOnOldKernel(t, "4.20", "flow_dissector program")
    56  
    57  	prog := mustLoadProgram(t, ebpf.FlowDissector, ebpf.AttachFlowDissector, "")
    58  
    59  	// RawAttachProgramOptions.Target needs to be 0, as PROG_ATTACH with namespaces
    60  	// only works with the threads current netns. Any other fd will be rejected.
    61  	if err := RawAttachProgram(RawAttachProgramOptions{
    62  		Target:  0,
    63  		Program: prog,
    64  		Attach:  ebpf.AttachFlowDissector,
    65  	}); err != nil {
    66  		t.Fatal(err)
    67  	}
    68  
    69  	t.Cleanup(func() {
    70  		err := RawDetachProgram(RawDetachProgramOptions{
    71  			Target:  0,
    72  			Program: prog,
    73  			Attach:  ebpf.AttachFlowDissector,
    74  		})
    75  		if err != nil {
    76  			t.Fatal(err)
    77  		}
    78  	})
    79  
    80  	return prog, QueryOptions{Path: "/proc/self/ns/net", Attach: ebpf.AttachFlowDissector}
    81  }