namespace_linux.go 8.1 KB

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