namespace_linux.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. neighbors []*neigh
  36. nextIfIndex int
  37. sync.Mutex
  38. }
  39. func init() {
  40. reexec.Register("netns-create", reexecCreateNamespace)
  41. }
  42. func createBasePath() {
  43. err := os.MkdirAll(prefix, 0644)
  44. if err != nil && !os.IsExist(err) {
  45. panic("Could not create net namespace path directory")
  46. }
  47. // Start the garbage collection go routine
  48. go removeUnusedPaths()
  49. }
  50. func removeUnusedPaths() {
  51. gpmLock.Lock()
  52. period := gpmCleanupPeriod
  53. gpmLock.Unlock()
  54. ticker := time.NewTicker(period)
  55. for {
  56. var (
  57. gc chan struct{}
  58. gcOk bool
  59. )
  60. select {
  61. case <-ticker.C:
  62. case gc, gcOk = <-gpmChan:
  63. }
  64. gpmLock.Lock()
  65. pathList := make([]string, 0, len(garbagePathMap))
  66. for path := range garbagePathMap {
  67. pathList = append(pathList, path)
  68. }
  69. garbagePathMap = make(map[string]bool)
  70. gpmWg.Add(1)
  71. gpmLock.Unlock()
  72. for _, path := range pathList {
  73. os.Remove(path)
  74. }
  75. gpmWg.Done()
  76. if gcOk {
  77. close(gc)
  78. }
  79. }
  80. }
  81. func addToGarbagePaths(path string) {
  82. gpmLock.Lock()
  83. garbagePathMap[path] = true
  84. gpmLock.Unlock()
  85. }
  86. func removeFromGarbagePaths(path string) {
  87. gpmLock.Lock()
  88. delete(garbagePathMap, path)
  89. gpmLock.Unlock()
  90. }
  91. // GC triggers garbage collection of namespace path right away
  92. // and waits for it.
  93. func GC() {
  94. gpmLock.Lock()
  95. if len(garbagePathMap) == 0 {
  96. // No need for GC if map is empty
  97. gpmLock.Unlock()
  98. return
  99. }
  100. gpmLock.Unlock()
  101. // if content exists in the garbage paths
  102. // we can trigger GC to run, providing a
  103. // channel to be notified on completion
  104. waitGC := make(chan struct{})
  105. gpmChan <- waitGC
  106. // wait for GC completion
  107. <-waitGC
  108. }
  109. // GenerateKey generates a sandbox key based on the passed
  110. // container id.
  111. func GenerateKey(containerID string) string {
  112. maxLen := 12
  113. if len(containerID) < maxLen {
  114. maxLen = len(containerID)
  115. }
  116. return prefix + "/" + containerID[:maxLen]
  117. }
  118. // NewSandbox provides a new sandbox instance created in an os specific way
  119. // provided a key which uniquely identifies the sandbox
  120. func NewSandbox(key string, osCreate bool) (Sandbox, error) {
  121. err := createNetworkNamespace(key, osCreate)
  122. if err != nil {
  123. return nil, err
  124. }
  125. return &networkNamespace{path: key}, nil
  126. }
  127. func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
  128. return n
  129. }
  130. func (n *networkNamespace) NeighborOptions() NeighborOptionSetter {
  131. return n
  132. }
  133. func reexecCreateNamespace() {
  134. if len(os.Args) < 2 {
  135. log.Fatal("no namespace path provided")
  136. }
  137. if err := syscall.Mount("/proc/self/ns/net", os.Args[1], "bind", syscall.MS_BIND, ""); err != nil {
  138. log.Fatal(err)
  139. }
  140. if err := loopbackUp(); err != nil {
  141. log.Fatal(err)
  142. }
  143. }
  144. func createNetworkNamespace(path string, osCreate bool) error {
  145. runtime.LockOSThread()
  146. defer runtime.UnlockOSThread()
  147. origns, err := netns.Get()
  148. if err != nil {
  149. return err
  150. }
  151. defer origns.Close()
  152. if err := createNamespaceFile(path); err != nil {
  153. return err
  154. }
  155. cmd := &exec.Cmd{
  156. Path: reexec.Self(),
  157. Args: append([]string{"netns-create"}, path),
  158. Stdout: os.Stdout,
  159. Stderr: os.Stderr,
  160. }
  161. if osCreate {
  162. cmd.SysProcAttr = &syscall.SysProcAttr{}
  163. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  164. }
  165. if err := cmd.Run(); err != nil {
  166. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  167. }
  168. return nil
  169. }
  170. func unmountNamespaceFile(path string) {
  171. if _, err := os.Stat(path); err == nil {
  172. syscall.Unmount(path, syscall.MNT_DETACH)
  173. }
  174. }
  175. func createNamespaceFile(path string) (err error) {
  176. var f *os.File
  177. once.Do(createBasePath)
  178. // Remove it from garbage collection list if present
  179. removeFromGarbagePaths(path)
  180. // If the path is there unmount it first
  181. unmountNamespaceFile(path)
  182. // wait for garbage collection to complete if it is in progress
  183. // before trying to create the file.
  184. gpmWg.Wait()
  185. if f, err = os.Create(path); err == nil {
  186. f.Close()
  187. }
  188. return err
  189. }
  190. func loopbackUp() error {
  191. iface, err := netlink.LinkByName("lo")
  192. if err != nil {
  193. return err
  194. }
  195. return netlink.LinkSetUp(iface)
  196. }
  197. func (n *networkNamespace) InvokeFunc(f func()) error {
  198. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  199. f()
  200. return nil
  201. })
  202. }
  203. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  204. runtime.LockOSThread()
  205. defer runtime.UnlockOSThread()
  206. origns, err := netns.Get()
  207. if err != nil {
  208. return err
  209. }
  210. defer origns.Close()
  211. f, err := os.OpenFile(path, os.O_RDONLY, 0)
  212. if err != nil {
  213. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  214. }
  215. defer f.Close()
  216. nsFD := f.Fd()
  217. // Invoked before the namespace switch happens but after the namespace file
  218. // handle is obtained.
  219. if err := prefunc(int(nsFD)); err != nil {
  220. return fmt.Errorf("failed in prefunc: %v", err)
  221. }
  222. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  223. return err
  224. }
  225. defer netns.Set(origns)
  226. // Invoked after the namespace switch.
  227. return postfunc(int(origns))
  228. }
  229. func (n *networkNamespace) nsPath() string {
  230. n.Lock()
  231. defer n.Unlock()
  232. return n.path
  233. }
  234. func (n *networkNamespace) Info() Info {
  235. return n
  236. }
  237. func (n *networkNamespace) Key() string {
  238. return n.path
  239. }
  240. func (n *networkNamespace) Destroy() error {
  241. // Assuming no running process is executing in this network namespace,
  242. // unmounting is sufficient to destroy it.
  243. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  244. return err
  245. }
  246. // Stash it into the garbage collection list
  247. addToGarbagePaths(n.path)
  248. return nil
  249. }