namespace_linux.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package sandbox
  2. import (
  3. "fmt"
  4. "net"
  5. "os"
  6. "os/exec"
  7. "runtime"
  8. "sync"
  9. "syscall"
  10. "time"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/pkg/reexec"
  13. "github.com/docker/libnetwork/types"
  14. "github.com/vishvananda/netlink"
  15. "github.com/vishvananda/netns"
  16. )
  17. const prefix = "/var/run/docker/netns"
  18. var (
  19. once sync.Once
  20. garbagePathMap = make(map[string]bool)
  21. gpmLock sync.Mutex
  22. gpmWg sync.WaitGroup
  23. gpmCleanupPeriod = 60 * time.Second
  24. gpmChan = make(chan chan struct{})
  25. )
  26. // The networkNamespace type is the linux implementation of the Sandbox
  27. // interface. It represents a linux network namespace, and moves an interface
  28. // into it when called on method AddInterface or sets the gateway etc.
  29. type networkNamespace struct {
  30. path string
  31. iFaces []*nwIface
  32. gw net.IP
  33. gwv6 net.IP
  34. staticRoutes []*types.StaticRoute
  35. nextIfIndex int
  36. sync.Mutex
  37. }
  38. func init() {
  39. reexec.Register("netns-create", reexecCreateNamespace)
  40. }
  41. func createBasePath() {
  42. err := os.MkdirAll(prefix, 0644)
  43. if err != nil && !os.IsExist(err) {
  44. panic("Could not create net namespace path directory")
  45. }
  46. // Start the garbage collection go routine
  47. go removeUnusedPaths()
  48. }
  49. func removeUnusedPaths() {
  50. gpmLock.Lock()
  51. period := gpmCleanupPeriod
  52. gpmLock.Unlock()
  53. ticker := time.NewTicker(period)
  54. for {
  55. var (
  56. gc chan struct{}
  57. gcOk bool
  58. )
  59. select {
  60. case <-ticker.C:
  61. case gc, gcOk = <-gpmChan:
  62. }
  63. gpmLock.Lock()
  64. pathList := make([]string, 0, len(garbagePathMap))
  65. for path := range garbagePathMap {
  66. pathList = append(pathList, path)
  67. }
  68. garbagePathMap = make(map[string]bool)
  69. gpmWg.Add(1)
  70. gpmLock.Unlock()
  71. for _, path := range pathList {
  72. os.Remove(path)
  73. }
  74. gpmWg.Done()
  75. if gcOk {
  76. close(gc)
  77. }
  78. }
  79. }
  80. func addToGarbagePaths(path string) {
  81. gpmLock.Lock()
  82. garbagePathMap[path] = true
  83. gpmLock.Unlock()
  84. }
  85. func removeFromGarbagePaths(path string) {
  86. gpmLock.Lock()
  87. delete(garbagePathMap, path)
  88. gpmLock.Unlock()
  89. }
  90. // GC triggers garbage collection of namespace path right away
  91. // and waits for it.
  92. func GC() {
  93. waitGC := make(chan struct{})
  94. // Trigger GC now
  95. gpmChan <- waitGC
  96. // wait for gc to complete
  97. <-waitGC
  98. }
  99. // GenerateKey generates a sandbox key based on the passed
  100. // container id.
  101. func GenerateKey(containerID string) string {
  102. maxLen := 12
  103. if len(containerID) < maxLen {
  104. maxLen = len(containerID)
  105. }
  106. return prefix + "/" + containerID[:maxLen]
  107. }
  108. // NewSandbox provides a new sandbox instance created in an os specific way
  109. // provided a key which uniquely identifies the sandbox
  110. func NewSandbox(key string, osCreate bool) (Sandbox, error) {
  111. err := createNetworkNamespace(key, osCreate)
  112. if err != nil {
  113. return nil, err
  114. }
  115. return &networkNamespace{path: key}, nil
  116. }
  117. func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
  118. return n
  119. }
  120. func reexecCreateNamespace() {
  121. if len(os.Args) < 2 {
  122. log.Fatal("no namespace path provided")
  123. }
  124. if err := syscall.Mount("/proc/self/ns/net", os.Args[1], "bind", syscall.MS_BIND, ""); err != nil {
  125. log.Fatal(err)
  126. }
  127. if err := loopbackUp(); err != nil {
  128. log.Fatal(err)
  129. }
  130. }
  131. func createNetworkNamespace(path string, osCreate bool) error {
  132. runtime.LockOSThread()
  133. defer runtime.UnlockOSThread()
  134. origns, err := netns.Get()
  135. if err != nil {
  136. return err
  137. }
  138. defer origns.Close()
  139. if err := createNamespaceFile(path); err != nil {
  140. return err
  141. }
  142. cmd := &exec.Cmd{
  143. Path: reexec.Self(),
  144. Args: append([]string{"netns-create"}, path),
  145. Stdout: os.Stdout,
  146. Stderr: os.Stderr,
  147. }
  148. if osCreate {
  149. cmd.SysProcAttr = &syscall.SysProcAttr{}
  150. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  151. }
  152. if err := cmd.Run(); err != nil {
  153. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  154. }
  155. return nil
  156. }
  157. func unmountNamespaceFile(path string) {
  158. if _, err := os.Stat(path); err == nil {
  159. syscall.Unmount(path, syscall.MNT_DETACH)
  160. }
  161. }
  162. func createNamespaceFile(path string) (err error) {
  163. var f *os.File
  164. once.Do(createBasePath)
  165. // Remove it from garbage collection list if present
  166. removeFromGarbagePaths(path)
  167. // If the path is there unmount it first
  168. unmountNamespaceFile(path)
  169. // wait for garbage collection to complete if it is in progress
  170. // before trying to create the file.
  171. gpmWg.Wait()
  172. if f, err = os.Create(path); err == nil {
  173. f.Close()
  174. }
  175. return err
  176. }
  177. func loopbackUp() error {
  178. iface, err := netlink.LinkByName("lo")
  179. if err != nil {
  180. return err
  181. }
  182. return netlink.LinkSetUp(iface)
  183. }
  184. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  185. runtime.LockOSThread()
  186. defer runtime.UnlockOSThread()
  187. origns, err := netns.Get()
  188. if err != nil {
  189. return err
  190. }
  191. defer origns.Close()
  192. f, err := os.OpenFile(path, os.O_RDONLY, 0)
  193. if err != nil {
  194. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  195. }
  196. defer f.Close()
  197. nsFD := f.Fd()
  198. // Invoked before the namespace switch happens but after the namespace file
  199. // handle is obtained.
  200. if err := prefunc(int(nsFD)); err != nil {
  201. return fmt.Errorf("failed in prefunc: %v", err)
  202. }
  203. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  204. return err
  205. }
  206. defer netns.Set(origns)
  207. // Invoked after the namespace switch.
  208. return postfunc(int(origns))
  209. }
  210. func (n *networkNamespace) nsPath() string {
  211. n.Lock()
  212. defer n.Unlock()
  213. return n.path
  214. }
  215. func (n *networkNamespace) Info() Info {
  216. return n
  217. }
  218. func (n *networkNamespace) Key() string {
  219. return n.path
  220. }
  221. func (n *networkNamespace) Destroy() error {
  222. // Assuming no running process is executing in this network namespace,
  223. // unmounting is sufficient to destroy it.
  224. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  225. return err
  226. }
  227. // Stash it into the garbage collection list
  228. addToGarbagePaths(n.path)
  229. return nil
  230. }