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