netns.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 descriptors 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. // UniqueId returns a string which uniquely identifies the namespace
  45. // associated with the network handle.
  46. func (ns NsHandle) UniqueId() string {
  47. var s syscall.Stat_t
  48. if ns == -1 {
  49. return "NS(none)"
  50. }
  51. if err := syscall.Fstat(int(ns), &s); err != nil {
  52. return "NS(unknown)"
  53. }
  54. return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino)
  55. }
  56. // IsOpen returns true if Close() has not been called.
  57. func (ns NsHandle) IsOpen() bool {
  58. return ns != -1
  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 := syscall.Close(int(*ns)); err != nil {
  64. return err
  65. }
  66. (*ns) = -1
  67. return nil
  68. }
  69. // None gets an empty (closed) NsHandle.
  70. func None() NsHandle {
  71. return NsHandle(-1)
  72. }