...

Source file src/github.com/vishvananda/netns/nshandle_linux.go

Documentation: github.com/vishvananda/netns

     1  package netns
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"golang.org/x/sys/unix"
     7  )
     8  
     9  // NsHandle is a handle to a network namespace. It can be cast directly
    10  // to an int and used as a file descriptor.
    11  type NsHandle int
    12  
    13  // Equal determines if two network handles refer to the same network
    14  // namespace. This is done by comparing the device and inode that the
    15  // file descriptors point to.
    16  func (ns NsHandle) Equal(other NsHandle) bool {
    17  	if ns == other {
    18  		return true
    19  	}
    20  	var s1, s2 unix.Stat_t
    21  	if err := unix.Fstat(int(ns), &s1); err != nil {
    22  		return false
    23  	}
    24  	if err := unix.Fstat(int(other), &s2); err != nil {
    25  		return false
    26  	}
    27  	return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
    28  }
    29  
    30  // String shows the file descriptor number and its dev and inode.
    31  func (ns NsHandle) String() string {
    32  	if ns == -1 {
    33  		return "NS(none)"
    34  	}
    35  	var s unix.Stat_t
    36  	if err := unix.Fstat(int(ns), &s); err != nil {
    37  		return fmt.Sprintf("NS(%d: unknown)", ns)
    38  	}
    39  	return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino)
    40  }
    41  
    42  // UniqueId returns a string which uniquely identifies the namespace
    43  // associated with the network handle.
    44  func (ns NsHandle) UniqueId() string {
    45  	if ns == -1 {
    46  		return "NS(none)"
    47  	}
    48  	var s unix.Stat_t
    49  	if err := unix.Fstat(int(ns), &s); err != nil {
    50  		return "NS(unknown)"
    51  	}
    52  	return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino)
    53  }
    54  
    55  // IsOpen returns true if Close() has not been called.
    56  func (ns NsHandle) IsOpen() bool {
    57  	return ns != -1
    58  }
    59  
    60  // Close closes the NsHandle and resets its file descriptor to -1.
    61  // It is not safe to use an NsHandle after Close() is called.
    62  func (ns *NsHandle) Close() error {
    63  	if err := unix.Close(int(*ns)); err != nil {
    64  		return err
    65  	}
    66  	*ns = -1
    67  	return nil
    68  }
    69  
    70  // None gets an empty (closed) NsHandle.
    71  func None() NsHandle {
    72  	return NsHandle(-1)
    73  }
    74  

View as plain text