namespace_linux.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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/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. nsOnce sync.Once
  26. initNs netns.NsHandle
  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. runtime.LockOSThread()
  148. defer runtime.UnlockOSThread()
  149. origns, err := netns.Get()
  150. if err != nil {
  151. return err
  152. }
  153. defer origns.Close()
  154. if err := createNamespaceFile(path); err != nil {
  155. return err
  156. }
  157. cmd := &exec.Cmd{
  158. Path: reexec.Self(),
  159. Args: append([]string{"netns-create"}, path),
  160. Stdout: os.Stdout,
  161. Stderr: os.Stderr,
  162. }
  163. if osCreate {
  164. cmd.SysProcAttr = &syscall.SysProcAttr{}
  165. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  166. }
  167. if err := cmd.Run(); err != nil {
  168. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  169. }
  170. return nil
  171. }
  172. func unmountNamespaceFile(path string) {
  173. if _, err := os.Stat(path); err == nil {
  174. syscall.Unmount(path, syscall.MNT_DETACH)
  175. }
  176. }
  177. func createNamespaceFile(path string) (err error) {
  178. var f *os.File
  179. once.Do(createBasePath)
  180. // Remove it from garbage collection list if present
  181. removeFromGarbagePaths(path)
  182. // If the path is there unmount it first
  183. unmountNamespaceFile(path)
  184. // wait for garbage collection to complete if it is in progress
  185. // before trying to create the file.
  186. gpmWg.Wait()
  187. if f, err = os.Create(path); err == nil {
  188. f.Close()
  189. }
  190. return err
  191. }
  192. func loopbackUp() error {
  193. iface, err := netlink.LinkByName("lo")
  194. if err != nil {
  195. return err
  196. }
  197. return netlink.LinkSetUp(iface)
  198. }
  199. func (n *networkNamespace) InvokeFunc(f func()) error {
  200. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  201. f()
  202. return nil
  203. })
  204. }
  205. func getLink() (string, error) {
  206. return os.Readlink(fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid()))
  207. }
  208. func nsInit() {
  209. var err error
  210. if initNs, err = netns.Get(); err != nil {
  211. log.Errorf("could not get initial namespace: %v", err)
  212. }
  213. }
  214. // InitOSContext initializes OS context while configuring network resources
  215. func InitOSContext() func() {
  216. runtime.LockOSThread()
  217. nsOnce.Do(nsInit)
  218. if err := netns.Set(initNs); err != nil {
  219. linkInfo, linkErr := getLink()
  220. if linkErr != nil {
  221. linkInfo = linkErr.Error()
  222. }
  223. log.Errorf("failed to set to initial namespace, %v, initns fd %d: %v",
  224. linkInfo, initNs, 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 netns.Set(initNs)
  245. // Invoked after the namespace switch.
  246. return postfunc(int(initNs))
  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. }