nshandle_linux.go 1.7 KB

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