github.com/adityamillind98/moby@v23.0.0-rc.4+incompatible/libnetwork/testutils/context_unix.go (about)

     1  //go:build linux || freebsd
     2  // +build linux freebsd
     3  
     4  package testutils
     5  
     6  import (
     7  	"runtime"
     8  	"syscall"
     9  	"testing"
    10  
    11  	"github.com/docker/docker/libnetwork/ns"
    12  )
    13  
    14  // SetupTestOSContext joins a new network namespace, and returns its associated
    15  // teardown function.
    16  //
    17  // Example usage:
    18  //
    19  //	defer SetupTestOSContext(t)()
    20  func SetupTestOSContext(t *testing.T) func() {
    21  	runtime.LockOSThread()
    22  	if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
    23  		t.Fatalf("Failed to enter netns: %v", err)
    24  	}
    25  
    26  	fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0)
    27  	if err != nil {
    28  		t.Fatal("Failed to open netns file")
    29  	}
    30  
    31  	// Since we are switching to a new test namespace make
    32  	// sure to re-initialize initNs context
    33  	ns.Init()
    34  
    35  	runtime.LockOSThread()
    36  
    37  	return func() {
    38  		if err := syscall.Close(fd); err != nil {
    39  			t.Logf("Warning: netns closing failed (%v)", err)
    40  		}
    41  		runtime.UnlockOSThread()
    42  	}
    43  }