github.com/rish1988/moby@v25.0.2+incompatible/internal/testutils/netnsutils/sanity_linux.go (about)

     1  package netnsutils
     2  
     3  import (
     4  	"errors"
     5  	"syscall"
     6  	"testing"
     7  
     8  	"github.com/vishvananda/netns"
     9  	"golang.org/x/sys/unix"
    10  	"gotest.tools/v3/assert"
    11  )
    12  
    13  // AssertSocketSameNetNS makes a best-effort attempt to assert that conn is in
    14  // the same network namespace as the current goroutine's thread.
    15  func AssertSocketSameNetNS(t testing.TB, conn syscall.Conn) {
    16  	t.Helper()
    17  
    18  	sc, err := conn.SyscallConn()
    19  	assert.NilError(t, err)
    20  	sc.Control(func(fd uintptr) {
    21  		srvnsfd, err := unix.IoctlRetInt(int(fd), unix.SIOCGSKNS)
    22  		if err != nil {
    23  			if errors.Is(err, unix.EPERM) {
    24  				t.Log("Cannot determine socket's network namespace. Do we have CAP_NET_ADMIN?")
    25  				return
    26  			}
    27  			if errors.Is(err, unix.ENOSYS) {
    28  				t.Log("Cannot query socket's network namespace due to missing kernel support.")
    29  				return
    30  			}
    31  			t.Fatal(err)
    32  		}
    33  		srvns := netns.NsHandle(srvnsfd)
    34  		defer srvns.Close()
    35  
    36  		curns, err := netns.Get()
    37  		assert.NilError(t, err)
    38  		defer curns.Close()
    39  		if !srvns.Equal(curns) {
    40  			t.Fatalf("Socket is in network namespace %s, but test goroutine is in %s", srvns, curns)
    41  		}
    42  	})
    43  }