namespace_linux.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 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. runtime.LockOSThread()
  169. defer runtime.UnlockOSThread()
  170. origns, err := netns.Get()
  171. if err != nil {
  172. return err
  173. }
  174. defer origns.Close()
  175. if err := createNamespaceFile(path); err != nil {
  176. return err
  177. }
  178. cmd := &exec.Cmd{
  179. Path: reexec.Self(),
  180. Args: append([]string{"netns-create"}, path),
  181. Stdout: os.Stdout,
  182. Stderr: os.Stderr,
  183. }
  184. if osCreate {
  185. cmd.SysProcAttr = &syscall.SysProcAttr{}
  186. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  187. }
  188. if err := cmd.Run(); err != nil {
  189. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  190. }
  191. return nil
  192. }
  193. func unmountNamespaceFile(path string) {
  194. if _, err := os.Stat(path); err == nil {
  195. syscall.Unmount(path, syscall.MNT_DETACH)
  196. }
  197. }
  198. func createNamespaceFile(path string) (err error) {
  199. var f *os.File
  200. once.Do(createBasePath)
  201. // Remove it from garbage collection list if present
  202. removeFromGarbagePaths(path)
  203. // If the path is there unmount it first
  204. unmountNamespaceFile(path)
  205. // wait for garbage collection to complete if it is in progress
  206. // before trying to create the file.
  207. gpmWg.Wait()
  208. if f, err = os.Create(path); err == nil {
  209. f.Close()
  210. }
  211. return err
  212. }
  213. func loopbackUp() error {
  214. iface, err := netlink.LinkByName("lo")
  215. if err != nil {
  216. return err
  217. }
  218. return netlink.LinkSetUp(iface)
  219. }
  220. func (n *networkNamespace) InvokeFunc(f func()) error {
  221. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  222. f()
  223. return nil
  224. })
  225. }
  226. func getLink() (string, error) {
  227. return os.Readlink(fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid()))
  228. }
  229. func nsInit() {
  230. var err error
  231. if initNs, err = netns.Get(); err != nil {
  232. log.Errorf("could not get initial namespace: %v", err)
  233. }
  234. }
  235. // InitOSContext initializes OS context while configuring network resources
  236. func InitOSContext() func() {
  237. runtime.LockOSThread()
  238. nsOnce.Do(nsInit)
  239. if err := netns.Set(initNs); err != nil {
  240. linkInfo, linkErr := getLink()
  241. if linkErr != nil {
  242. linkInfo = linkErr.Error()
  243. }
  244. log.Errorf("failed to set to initial namespace, %v, initns fd %d: %v",
  245. linkInfo, initNs, err)
  246. }
  247. return runtime.UnlockOSThread
  248. }
  249. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  250. defer InitOSContext()()
  251. f, err := os.OpenFile(path, os.O_RDONLY, 0)
  252. if err != nil {
  253. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  254. }
  255. defer f.Close()
  256. nsFD := f.Fd()
  257. // Invoked before the namespace switch happens but after the namespace file
  258. // handle is obtained.
  259. if err := prefunc(int(nsFD)); err != nil {
  260. return fmt.Errorf("failed in prefunc: %v", err)
  261. }
  262. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  263. return err
  264. }
  265. defer netns.Set(initNs)
  266. // Invoked after the namespace switch.
  267. return postfunc(int(initNs))
  268. }
  269. func (n *networkNamespace) nsPath() string {
  270. n.Lock()
  271. defer n.Unlock()
  272. return n.path
  273. }
  274. func (n *networkNamespace) Info() Info {
  275. return n
  276. }
  277. func (n *networkNamespace) Key() string {
  278. return n.path
  279. }
  280. func (n *networkNamespace) Destroy() error {
  281. // Assuming no running process is executing in this network namespace,
  282. // unmounting is sufficient to destroy it.
  283. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  284. return err
  285. }
  286. // Stash it into the garbage collection list
  287. addToGarbagePaths(n.path)
  288. return nil
  289. }