ns_linux.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // Copyright 2015-2017 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. "crypto/rand"
  17. "fmt"
  18. "os"
  19. "path"
  20. "runtime"
  21. "sync"
  22. "golang.org/x/sys/unix"
  23. )
  24. // Returns an object representing the current OS thread's network namespace
  25. func GetCurrentNS() (NetNS, error) {
  26. return GetNS(getCurrentThreadNetNSPath())
  27. }
  28. func getCurrentThreadNetNSPath() string {
  29. // /proc/self/ns/net returns the namespace of the main thread, not
  30. // of whatever thread this goroutine is running on. Make sure we
  31. // use the thread's net namespace since the thread is switching around
  32. return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid())
  33. }
  34. // Creates a new persistent network namespace and returns an object
  35. // representing that namespace, without switching to it
  36. func NewNS() (NetNS, error) {
  37. const nsRunDir = "/var/run/netns"
  38. b := make([]byte, 16)
  39. _, err := rand.Reader.Read(b)
  40. if err != nil {
  41. return nil, fmt.Errorf("failed to generate random netns name: %v", err)
  42. }
  43. err = os.MkdirAll(nsRunDir, 0755)
  44. if err != nil {
  45. return nil, err
  46. }
  47. // create an empty file at the mount point
  48. nsName := fmt.Sprintf("cni-%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
  49. nsPath := path.Join(nsRunDir, nsName)
  50. mountPointFd, err := os.Create(nsPath)
  51. if err != nil {
  52. return nil, err
  53. }
  54. mountPointFd.Close()
  55. // Ensure the mount point is cleaned up on errors; if the namespace
  56. // was successfully mounted this will have no effect because the file
  57. // is in-use
  58. defer os.RemoveAll(nsPath)
  59. var wg sync.WaitGroup
  60. wg.Add(1)
  61. // do namespace work in a dedicated goroutine, so that we can safely
  62. // Lock/Unlock OSThread without upsetting the lock/unlock state of
  63. // the caller of this function
  64. var fd *os.File
  65. go (func() {
  66. defer wg.Done()
  67. runtime.LockOSThread()
  68. var origNS NetNS
  69. origNS, err = GetNS(getCurrentThreadNetNSPath())
  70. if err != nil {
  71. return
  72. }
  73. defer origNS.Close()
  74. // create a new netns on the current thread
  75. err = unix.Unshare(unix.CLONE_NEWNET)
  76. if err != nil {
  77. return
  78. }
  79. defer origNS.Set()
  80. // bind mount the new netns from the current thread onto the mount point
  81. err = unix.Mount(getCurrentThreadNetNSPath(), nsPath, "none", unix.MS_BIND, "")
  82. if err != nil {
  83. return
  84. }
  85. fd, err = os.Open(nsPath)
  86. if err != nil {
  87. return
  88. }
  89. })()
  90. wg.Wait()
  91. if err != nil {
  92. unix.Unmount(nsPath, unix.MNT_DETACH)
  93. return nil, fmt.Errorf("failed to create namespace: %v", err)
  94. }
  95. return &netNS{file: fd, mounted: true}, nil
  96. }
  97. func (ns *netNS) Close() error {
  98. if err := ns.errorIfClosed(); err != nil {
  99. return err
  100. }
  101. if err := ns.file.Close(); err != nil {
  102. return fmt.Errorf("Failed to close %q: %v", ns.file.Name(), err)
  103. }
  104. ns.closed = true
  105. if ns.mounted {
  106. if err := unix.Unmount(ns.file.Name(), unix.MNT_DETACH); err != nil {
  107. return fmt.Errorf("Failed to unmount namespace %s: %v", ns.file.Name(), err)
  108. }
  109. if err := os.RemoveAll(ns.file.Name()); err != nil {
  110. return fmt.Errorf("Failed to clean up namespace %s: %v", ns.file.Name(), err)
  111. }
  112. ns.mounted = false
  113. }
  114. return nil
  115. }
  116. func (ns *netNS) Set() error {
  117. if err := ns.errorIfClosed(); err != nil {
  118. return err
  119. }
  120. if err := unix.Setns(int(ns.Fd()), unix.CLONE_NEWNET); err != nil {
  121. return fmt.Errorf("Error switching to ns %v: %v", ns.file.Name(), err)
  122. }
  123. return nil
  124. }