github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/link/netns_test.go (about)

     1  package link
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/cilium/ebpf"
     8  	"github.com/cilium/ebpf/asm"
     9  	"github.com/cilium/ebpf/internal/testutils"
    10  )
    11  
    12  func TestSkLookup(t *testing.T) {
    13  	testutils.SkipOnOldKernel(t, "5.8", "sk_lookup program")
    14  
    15  	prog := mustLoadProgram(t, ebpf.SkLookup, ebpf.AttachSkLookup, "")
    16  
    17  	netns, err := os.Open("/proc/self/ns/net")
    18  	if err != nil {
    19  		t.Fatal(err)
    20  	}
    21  	defer netns.Close()
    22  
    23  	link, err := AttachNetNs(int(netns.Fd()), prog)
    24  	if err != nil {
    25  		t.Fatal("Can't attach link:", err)
    26  	}
    27  
    28  	testLink(t, link, prog)
    29  }
    30  
    31  func createSkLookupProgram() (*ebpf.Program, error) {
    32  	prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
    33  		Type:       ebpf.SkLookup,
    34  		AttachType: ebpf.AttachSkLookup,
    35  		License:    "MIT",
    36  		Instructions: asm.Instructions{
    37  			asm.Mov.Imm(asm.R0, 0),
    38  			asm.Return(),
    39  		},
    40  	})
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	return prog, nil
    45  }
    46  
    47  func ExampleAttachNetNs() {
    48  	prog, err := createSkLookupProgram()
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  	defer prog.Close()
    53  
    54  	// This can be a path to another netns as well.
    55  	netns, err := os.Open("/proc/self/ns/net")
    56  	if err != nil {
    57  		panic(err)
    58  	}
    59  	defer netns.Close()
    60  
    61  	link, err := AttachNetNs(int(netns.Fd()), prog)
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  
    66  	// The socket lookup program is now active until Close().
    67  	link.Close()
    68  }