namespace_linux.go 6.3 KB

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