namespace_linux.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 mountNetworkNamespace(basePath string, lnPath string) error {
  136. if err := syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, ""); err != nil {
  137. return err
  138. }
  139. if err := loopbackUp(); err != nil {
  140. return err
  141. }
  142. return nil
  143. }
  144. // GetSandboxForExternalKey returns sandbox object for the supplied path
  145. func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
  146. var err error
  147. if err = createNamespaceFile(key); err != nil {
  148. return nil, err
  149. }
  150. n := &networkNamespace{path: basePath}
  151. n.InvokeFunc(func() {
  152. err = mountNetworkNamespace(basePath, key)
  153. })
  154. if err != nil {
  155. return nil, err
  156. }
  157. return &networkNamespace{path: key}, nil
  158. }
  159. func reexecCreateNamespace() {
  160. if len(os.Args) < 2 {
  161. log.Fatal("no namespace path provided")
  162. }
  163. if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil {
  164. log.Fatal(err)
  165. }
  166. }
  167. func createNetworkNamespace(path string, osCreate bool) error {
  168. if err := createNamespaceFile(path); err != nil {
  169. return err
  170. }
  171. cmd := &exec.Cmd{
  172. Path: reexec.Self(),
  173. Args: append([]string{"netns-create"}, path),
  174. Stdout: os.Stdout,
  175. Stderr: os.Stderr,
  176. }
  177. if osCreate {
  178. cmd.SysProcAttr = &syscall.SysProcAttr{}
  179. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  180. }
  181. if err := cmd.Run(); err != nil {
  182. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  183. }
  184. return nil
  185. }
  186. func unmountNamespaceFile(path string) {
  187. if _, err := os.Stat(path); err == nil {
  188. syscall.Unmount(path, syscall.MNT_DETACH)
  189. }
  190. }
  191. func createNamespaceFile(path string) (err error) {
  192. var f *os.File
  193. once.Do(createBasePath)
  194. // Remove it from garbage collection list if present
  195. removeFromGarbagePaths(path)
  196. // If the path is there unmount it first
  197. unmountNamespaceFile(path)
  198. // wait for garbage collection to complete if it is in progress
  199. // before trying to create the file.
  200. gpmWg.Wait()
  201. if f, err = os.Create(path); err == nil {
  202. f.Close()
  203. }
  204. return err
  205. }
  206. func loopbackUp() error {
  207. iface, err := netlink.LinkByName("lo")
  208. if err != nil {
  209. return err
  210. }
  211. return netlink.LinkSetUp(iface)
  212. }
  213. func (n *networkNamespace) InvokeFunc(f func()) error {
  214. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  215. f()
  216. return nil
  217. })
  218. }
  219. // InitOSContext initializes OS context while configuring network resources
  220. func InitOSContext() func() {
  221. runtime.LockOSThread()
  222. nsOnce.Do(ns.Init)
  223. if err := ns.SetNamespace(); err != nil {
  224. log.Error(err)
  225. }
  226. return runtime.UnlockOSThread
  227. }
  228. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  229. defer InitOSContext()()
  230. f, err := os.OpenFile(path, os.O_RDONLY, 0)
  231. if err != nil {
  232. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  233. }
  234. defer f.Close()
  235. nsFD := f.Fd()
  236. // Invoked before the namespace switch happens but after the namespace file
  237. // handle is obtained.
  238. if err := prefunc(int(nsFD)); err != nil {
  239. return fmt.Errorf("failed in prefunc: %v", err)
  240. }
  241. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  242. return err
  243. }
  244. defer ns.SetNamespace()
  245. // Invoked after the namespace switch.
  246. return postfunc(ns.ParseHandlerInt())
  247. }
  248. func (n *networkNamespace) nsPath() string {
  249. n.Lock()
  250. defer n.Unlock()
  251. return n.path
  252. }
  253. func (n *networkNamespace) Info() Info {
  254. return n
  255. }
  256. func (n *networkNamespace) Key() string {
  257. return n.path
  258. }
  259. func (n *networkNamespace) Destroy() error {
  260. // Assuming no running process is executing in this network namespace,
  261. // unmounting is sufficient to destroy it.
  262. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  263. return err
  264. }
  265. // Stash it into the garbage collection list
  266. addToGarbagePaths(n.path)
  267. return nil
  268. }