netns.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Package netns allows ultra-simple network namespace handling. NsHandles
  2. // can be retrieved and set. Note that the current namespace is thread
  3. // local so actions that set and reset namespaces should use LockOSThread
  4. // to make sure the namespace doesn't change due to a goroutine switch.
  5. // It is best to close NsHandles when you are done with them. This can be
  6. // accomplished via a `defer ns.Close()` on the handle. Changing namespaces
  7. // requires elevated privileges, so in most cases this code needs to be run
  8. // as root.
  9. package netns
  10. import (
  11. "fmt"
  12. "syscall"
  13. )
  14. // NsHandle is a handle to a network namespace. It can be cast directly
  15. // to an int and used as a file descriptor.
  16. type NsHandle int
  17. // Equal determines if two network handles refer to the same network
  18. // namespace. This is done by comparing the device and inode that the
  19. // file descripors point to.
  20. func (ns NsHandle) Equal(other NsHandle) bool {
  21. if ns == other {
  22. return true
  23. }
  24. var s1, s2 syscall.Stat_t
  25. if err := syscall.Fstat(int(ns), &s1); err != nil {
  26. return false
  27. }
  28. if err := syscall.Fstat(int(other), &s2); err != nil {
  29. return false
  30. }
  31. return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino)
  32. }
  33. // String shows the file descriptor number and its dev and inode.
  34. func (ns NsHandle) String() string {
  35. var s syscall.Stat_t
  36. if ns == -1 {
  37. return "NS(None)"
  38. }
  39. if err := syscall.Fstat(int(ns), &s); err != nil {
  40. return fmt.Sprintf("NS(%d: unknown)", ns)
  41. }
  42. return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino)
  43. }
  44. // IsOpen returns true if Close() has not been called.
  45. func (ns NsHandle) IsOpen() bool {
  46. return ns != -1
  47. }
  48. // Close closes the NsHandle and resets its file descriptor to -1.
  49. // It is not safe to use an NsHandle after Close() is called.
  50. func (ns *NsHandle) Close() error {
  51. if err := syscall.Close(int(*ns)); err != nil {
  52. return err
  53. }
  54. (*ns) = -1
  55. return nil
  56. }
  57. // Get an empty (closed) NsHandle
  58. func None() NsHandle {
  59. return NsHandle(-1)
  60. }