ns.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright 2015 CNI authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ns
  15. import (
  16. "fmt"
  17. "os"
  18. "runtime"
  19. "sync"
  20. "syscall"
  21. )
  22. type NetNS interface {
  23. // Executes the passed closure in this object's network namespace,
  24. // attempting to restore the original namespace before returning.
  25. // However, since each OS thread can have a different network namespace,
  26. // and Go's thread scheduling is highly variable, callers cannot
  27. // guarantee any specific namespace is set unless operations that
  28. // require that namespace are wrapped with Do(). Also, no code called
  29. // from Do() should call runtime.UnlockOSThread(), or the risk
  30. // of executing code in an incorrect namespace will be greater. See
  31. // https://github.com/golang/go/wiki/LockOSThread for further details.
  32. Do(toRun func(NetNS) error) error
  33. // Sets the current network namespace to this object's network namespace.
  34. // Note that since Go's thread scheduling is highly variable, callers
  35. // cannot guarantee the requested namespace will be the current namespace
  36. // after this function is called; to ensure this wrap operations that
  37. // require the namespace with Do() instead.
  38. Set() error
  39. // Returns the filesystem path representing this object's network namespace
  40. Path() string
  41. // Returns a file descriptor representing this object's network namespace
  42. Fd() uintptr
  43. // Cleans up this instance of the network namespace; if this instance
  44. // is the last user the namespace will be destroyed
  45. Close() error
  46. }
  47. type netNS struct {
  48. file *os.File
  49. mounted bool
  50. closed bool
  51. }
  52. // netNS implements the NetNS interface
  53. var _ NetNS = &netNS{}
  54. const (
  55. // https://github.com/torvalds/linux/blob/master/include/uapi/linux/magic.h
  56. NSFS_MAGIC = 0x6e736673
  57. PROCFS_MAGIC = 0x9fa0
  58. )
  59. type NSPathNotExistErr struct{ msg string }
  60. func (e NSPathNotExistErr) Error() string { return e.msg }
  61. type NSPathNotNSErr struct{ msg string }
  62. func (e NSPathNotNSErr) Error() string { return e.msg }
  63. func IsNSorErr(nspath string) error {
  64. stat := syscall.Statfs_t{}
  65. if err := syscall.Statfs(nspath, &stat); err != nil {
  66. if os.IsNotExist(err) {
  67. err = NSPathNotExistErr{msg: fmt.Sprintf("failed to Statfs %q: %v", nspath, err)}
  68. } else {
  69. err = fmt.Errorf("failed to Statfs %q: %v", nspath, err)
  70. }
  71. return err
  72. }
  73. switch stat.Type {
  74. case PROCFS_MAGIC, NSFS_MAGIC:
  75. return nil
  76. default:
  77. return NSPathNotNSErr{msg: fmt.Sprintf("unknown FS magic on %q: %x", nspath, stat.Type)}
  78. }
  79. }
  80. // Returns an object representing the namespace referred to by @path
  81. func GetNS(nspath string) (NetNS, error) {
  82. err := IsNSorErr(nspath)
  83. if err != nil {
  84. return nil, err
  85. }
  86. fd, err := os.Open(nspath)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return &netNS{file: fd}, nil
  91. }
  92. func (ns *netNS) Path() string {
  93. return ns.file.Name()
  94. }
  95. func (ns *netNS) Fd() uintptr {
  96. return ns.file.Fd()
  97. }
  98. func (ns *netNS) errorIfClosed() error {
  99. if ns.closed {
  100. return fmt.Errorf("%q has already been closed", ns.file.Name())
  101. }
  102. return nil
  103. }
  104. func (ns *netNS) Do(toRun func(NetNS) error) error {
  105. if err := ns.errorIfClosed(); err != nil {
  106. return err
  107. }
  108. containedCall := func(hostNS NetNS) error {
  109. threadNS, err := GetCurrentNS()
  110. if err != nil {
  111. return fmt.Errorf("failed to open current netns: %v", err)
  112. }
  113. defer threadNS.Close()
  114. // switch to target namespace
  115. if err = ns.Set(); err != nil {
  116. return fmt.Errorf("error switching to ns %v: %v", ns.file.Name(), err)
  117. }
  118. defer threadNS.Set() // switch back
  119. return toRun(hostNS)
  120. }
  121. // save a handle to current network namespace
  122. hostNS, err := GetCurrentNS()
  123. if err != nil {
  124. return fmt.Errorf("Failed to open current namespace: %v", err)
  125. }
  126. defer hostNS.Close()
  127. var wg sync.WaitGroup
  128. wg.Add(1)
  129. var innerError error
  130. go func() {
  131. defer wg.Done()
  132. runtime.LockOSThread()
  133. innerError = containedCall(hostNS)
  134. }()
  135. wg.Wait()
  136. return innerError
  137. }
  138. // WithNetNSPath executes the passed closure under the given network
  139. // namespace, restoring the original namespace afterwards.
  140. func WithNetNSPath(nspath string, toRun func(NetNS) error) error {
  141. ns, err := GetNS(nspath)
  142. if err != nil {
  143. return err
  144. }
  145. defer ns.Close()
  146. return ns.Do(toRun)
  147. }