namespace_linux.go 8.5 KB

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