namespace_linux.go 8.4 KB

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