namespace_linux.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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/vishvananda/netlink"
  14. "github.com/vishvananda/netns"
  15. )
  16. const prefix = "/var/run/docker/netns"
  17. var (
  18. once sync.Once
  19. garbagePathMap = make(map[string]bool)
  20. gpmLock sync.Mutex
  21. gpmWg sync.WaitGroup
  22. gpmCleanupPeriod = 60 * time.Second
  23. gpmChan = make(chan chan struct{})
  24. )
  25. // The networkNamespace type is the linux implementation of the Sandbox
  26. // interface. It represents a linux network namespace, and moves an interface
  27. // into it when called on method AddInterface or sets the gateway etc.
  28. type networkNamespace struct {
  29. path string
  30. sinfo *Info
  31. nextIfIndex int
  32. sync.Mutex
  33. }
  34. func init() {
  35. reexec.Register("netns-create", reexecCreateNamespace)
  36. }
  37. func createBasePath() {
  38. err := os.MkdirAll(prefix, 0644)
  39. if err != nil && !os.IsExist(err) {
  40. panic("Could not create net namespace path directory")
  41. }
  42. // Start the garbage collection go routine
  43. go removeUnusedPaths()
  44. }
  45. func removeUnusedPaths() {
  46. gpmLock.Lock()
  47. period := gpmCleanupPeriod
  48. gpmLock.Unlock()
  49. ticker := time.NewTicker(period)
  50. for {
  51. var (
  52. gc chan struct{}
  53. gcOk bool
  54. )
  55. select {
  56. case <-ticker.C:
  57. case gc, gcOk = <-gpmChan:
  58. }
  59. gpmLock.Lock()
  60. pathList := make([]string, 0, len(garbagePathMap))
  61. for path := range garbagePathMap {
  62. pathList = append(pathList, path)
  63. }
  64. garbagePathMap = make(map[string]bool)
  65. gpmWg.Add(1)
  66. gpmLock.Unlock()
  67. for _, path := range pathList {
  68. os.Remove(path)
  69. }
  70. gpmWg.Done()
  71. if gcOk {
  72. close(gc)
  73. }
  74. }
  75. }
  76. func addToGarbagePaths(path string) {
  77. gpmLock.Lock()
  78. garbagePathMap[path] = true
  79. gpmLock.Unlock()
  80. }
  81. func removeFromGarbagePaths(path string) {
  82. gpmLock.Lock()
  83. delete(garbagePathMap, path)
  84. gpmLock.Unlock()
  85. }
  86. // GC triggers garbage collection of namespace path right away
  87. // and waits for it.
  88. func GC() {
  89. waitGC := make(chan struct{})
  90. // Trigger GC now
  91. gpmChan <- waitGC
  92. // wait for gc to complete
  93. <-waitGC
  94. }
  95. // GenerateKey generates a sandbox key based on the passed
  96. // container id.
  97. func GenerateKey(containerID string) string {
  98. maxLen := 12
  99. if len(containerID) < maxLen {
  100. maxLen = len(containerID)
  101. }
  102. return prefix + "/" + containerID[:maxLen]
  103. }
  104. // NewSandbox provides a new sandbox instance created in an os specific way
  105. // provided a key which uniquely identifies the sandbox
  106. func NewSandbox(key string, osCreate bool) (Sandbox, error) {
  107. info, err := createNetworkNamespace(key, osCreate)
  108. if err != nil {
  109. return nil, err
  110. }
  111. return &networkNamespace{path: key, sinfo: info}, nil
  112. }
  113. func reexecCreateNamespace() {
  114. if len(os.Args) < 2 {
  115. log.Fatal("no namespace path provided")
  116. }
  117. if err := syscall.Mount("/proc/self/ns/net", os.Args[1], "bind", syscall.MS_BIND, ""); err != nil {
  118. log.Fatal(err)
  119. }
  120. if err := loopbackUp(); err != nil {
  121. log.Fatal(err)
  122. }
  123. }
  124. func createNetworkNamespace(path string, osCreate bool) (*Info, error) {
  125. runtime.LockOSThread()
  126. defer runtime.UnlockOSThread()
  127. origns, err := netns.Get()
  128. if err != nil {
  129. return nil, err
  130. }
  131. defer origns.Close()
  132. if err := createNamespaceFile(path); err != nil {
  133. return nil, err
  134. }
  135. cmd := &exec.Cmd{
  136. Path: reexec.Self(),
  137. Args: append([]string{"netns-create"}, path),
  138. Stdout: os.Stdout,
  139. Stderr: os.Stderr,
  140. }
  141. if osCreate {
  142. cmd.SysProcAttr = &syscall.SysProcAttr{}
  143. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  144. }
  145. if err := cmd.Run(); err != nil {
  146. return nil, fmt.Errorf("namespace creation reexec command failed: %v", err)
  147. }
  148. interfaces := []*Interface{}
  149. info := &Info{Interfaces: interfaces}
  150. return info, nil
  151. }
  152. func unmountNamespaceFile(path string) {
  153. if _, err := os.Stat(path); err == nil {
  154. syscall.Unmount(path, syscall.MNT_DETACH)
  155. }
  156. }
  157. func createNamespaceFile(path string) (err error) {
  158. var f *os.File
  159. once.Do(createBasePath)
  160. // Remove it from garbage collection list if present
  161. removeFromGarbagePaths(path)
  162. // If the path is there unmount it first
  163. unmountNamespaceFile(path)
  164. // wait for garbage collection to complete if it is in progress
  165. // before trying to create the file.
  166. gpmWg.Wait()
  167. if f, err = os.Create(path); err == nil {
  168. f.Close()
  169. }
  170. return err
  171. }
  172. func loopbackUp() error {
  173. iface, err := netlink.LinkByName("lo")
  174. if err != nil {
  175. return err
  176. }
  177. return netlink.LinkSetUp(iface)
  178. }
  179. func (n *networkNamespace) RemoveInterface(i *Interface) error {
  180. runtime.LockOSThread()
  181. defer runtime.UnlockOSThread()
  182. origns, err := netns.Get()
  183. if err != nil {
  184. return err
  185. }
  186. defer origns.Close()
  187. f, err := os.OpenFile(n.path, os.O_RDONLY, 0)
  188. if err != nil {
  189. return fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  190. }
  191. defer f.Close()
  192. nsFD := f.Fd()
  193. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  194. return err
  195. }
  196. defer netns.Set(origns)
  197. // Find the network inteerface identified by the DstName attribute.
  198. iface, err := netlink.LinkByName(i.DstName)
  199. if err != nil {
  200. return err
  201. }
  202. // Down the interface before configuring
  203. if err := netlink.LinkSetDown(iface); err != nil {
  204. return err
  205. }
  206. err = netlink.LinkSetName(iface, i.SrcName)
  207. if err != nil {
  208. fmt.Println("LinkSetName failed: ", err)
  209. return err
  210. }
  211. // Move the network interface to caller namespace.
  212. if err := netlink.LinkSetNsFd(iface, int(origns)); err != nil {
  213. fmt.Println("LinkSetNsPid failed: ", err)
  214. return err
  215. }
  216. return nil
  217. }
  218. func (n *networkNamespace) AddInterface(i *Interface) error {
  219. n.Lock()
  220. i.DstName = fmt.Sprintf("%s%d", i.DstName, n.nextIfIndex)
  221. n.nextIfIndex++
  222. n.Unlock()
  223. runtime.LockOSThread()
  224. defer runtime.UnlockOSThread()
  225. origns, err := netns.Get()
  226. if err != nil {
  227. return err
  228. }
  229. defer origns.Close()
  230. f, err := os.OpenFile(n.path, os.O_RDONLY, 0)
  231. if err != nil {
  232. return fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  233. }
  234. defer f.Close()
  235. // Find the network interface identified by the SrcName attribute.
  236. iface, err := netlink.LinkByName(i.SrcName)
  237. if err != nil {
  238. return err
  239. }
  240. // Move the network interface to the destination namespace.
  241. nsFD := f.Fd()
  242. if err := netlink.LinkSetNsFd(iface, int(nsFD)); err != nil {
  243. return err
  244. }
  245. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  246. return err
  247. }
  248. defer netns.Set(origns)
  249. // Down the interface before configuring
  250. if err := netlink.LinkSetDown(iface); err != nil {
  251. return err
  252. }
  253. // Configure the interface now this is moved in the proper namespace.
  254. if err := configureInterface(iface, i); err != nil {
  255. return err
  256. }
  257. // Up the interface.
  258. if err := netlink.LinkSetUp(iface); err != nil {
  259. return err
  260. }
  261. n.Lock()
  262. n.sinfo.Interfaces = append(n.sinfo.Interfaces, i)
  263. n.Unlock()
  264. return nil
  265. }
  266. func (n *networkNamespace) SetGateway(gw net.IP) error {
  267. if len(gw) == 0 {
  268. return nil
  269. }
  270. err := programGateway(n.path, gw)
  271. if err == nil {
  272. n.sinfo.Gateway = gw
  273. }
  274. return err
  275. }
  276. func (n *networkNamespace) SetGatewayIPv6(gw net.IP) error {
  277. if len(gw) == 0 {
  278. return nil
  279. }
  280. err := programGateway(n.path, gw)
  281. if err == nil {
  282. n.sinfo.GatewayIPv6 = gw
  283. }
  284. return err
  285. }
  286. func (n *networkNamespace) Interfaces() []*Interface {
  287. return n.sinfo.Interfaces
  288. }
  289. func (n *networkNamespace) Key() string {
  290. return n.path
  291. }
  292. func (n *networkNamespace) Destroy() error {
  293. // Assuming no running process is executing in this network namespace,
  294. // unmounting is sufficient to destroy it.
  295. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  296. return err
  297. }
  298. // Stash it into the garbage collection list
  299. addToGarbagePaths(n.path)
  300. return nil
  301. }