namespace_linux.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. gpmLock.Lock()
  47. period := gpmCleanupPeriod
  48. gpmLock.Unlock()
  49. for range time.Tick(period) {
  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 unmountNamespaceFile(path string) {
  132. if _, err := os.Stat(path); err == nil {
  133. syscall.Unmount(path, syscall.MNT_DETACH)
  134. }
  135. }
  136. func createNamespaceFile(path string) (err error) {
  137. var f *os.File
  138. once.Do(createBasePath)
  139. // Remove it from garbage collection list if present
  140. removeFromGarbagePaths(path)
  141. // If the path is there unmount it first
  142. unmountNamespaceFile(path)
  143. // wait for garbage collection to complete if it is in progress
  144. // before trying to create the file.
  145. gpmWg.Wait()
  146. if f, err = os.Create(path); err == nil {
  147. f.Close()
  148. }
  149. return err
  150. }
  151. func loopbackUp() error {
  152. iface, err := netlink.LinkByName("lo")
  153. if err != nil {
  154. return err
  155. }
  156. return netlink.LinkSetUp(iface)
  157. }
  158. func (n *networkNamespace) RemoveInterface(i *Interface) error {
  159. runtime.LockOSThread()
  160. defer runtime.UnlockOSThread()
  161. origns, err := netns.Get()
  162. if err != nil {
  163. return err
  164. }
  165. defer origns.Close()
  166. f, err := os.OpenFile(n.path, os.O_RDONLY, 0)
  167. if err != nil {
  168. return fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  169. }
  170. defer f.Close()
  171. nsFD := f.Fd()
  172. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  173. return err
  174. }
  175. defer netns.Set(origns)
  176. // Find the network inteerface identified by the DstName attribute.
  177. iface, err := netlink.LinkByName(i.DstName)
  178. if err != nil {
  179. return err
  180. }
  181. // Down the interface before configuring
  182. if err := netlink.LinkSetDown(iface); err != nil {
  183. return err
  184. }
  185. err = netlink.LinkSetName(iface, i.SrcName)
  186. if err != nil {
  187. fmt.Println("LinkSetName failed: ", err)
  188. return err
  189. }
  190. // Move the network interface to caller namespace.
  191. if err := netlink.LinkSetNsFd(iface, int(origns)); err != nil {
  192. fmt.Println("LinkSetNsPid failed: ", err)
  193. return err
  194. }
  195. n.Lock()
  196. for index, intf := range n.sinfo.Interfaces {
  197. if intf == i {
  198. n.sinfo.Interfaces = append(n.sinfo.Interfaces[:index], n.sinfo.Interfaces[index+1:]...)
  199. break
  200. }
  201. }
  202. n.Unlock()
  203. return nil
  204. }
  205. func (n *networkNamespace) AddInterface(i *Interface) error {
  206. n.Lock()
  207. i.DstName = fmt.Sprintf("%s%d", i.DstName, n.nextIfIndex)
  208. n.nextIfIndex++
  209. n.Unlock()
  210. runtime.LockOSThread()
  211. defer runtime.UnlockOSThread()
  212. origns, err := netns.Get()
  213. if err != nil {
  214. return err
  215. }
  216. defer origns.Close()
  217. f, err := os.OpenFile(n.path, os.O_RDONLY, 0)
  218. if err != nil {
  219. return fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  220. }
  221. defer f.Close()
  222. // Find the network interface identified by the SrcName attribute.
  223. iface, err := netlink.LinkByName(i.SrcName)
  224. if err != nil {
  225. return err
  226. }
  227. // Move the network interface to the destination namespace.
  228. nsFD := f.Fd()
  229. if err := netlink.LinkSetNsFd(iface, int(nsFD)); err != nil {
  230. return err
  231. }
  232. if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
  233. return err
  234. }
  235. defer netns.Set(origns)
  236. // Down the interface before configuring
  237. if err := netlink.LinkSetDown(iface); err != nil {
  238. return err
  239. }
  240. // Configure the interface now this is moved in the proper namespace.
  241. if err := configureInterface(iface, i); err != nil {
  242. return err
  243. }
  244. // Up the interface.
  245. if err := netlink.LinkSetUp(iface); err != nil {
  246. return err
  247. }
  248. n.Lock()
  249. n.sinfo.Interfaces = append(n.sinfo.Interfaces, i)
  250. n.Unlock()
  251. return nil
  252. }
  253. func (n *networkNamespace) SetGateway(gw net.IP) error {
  254. // Silently return if the gateway is empty
  255. if len(gw) == 0 {
  256. return nil
  257. }
  258. err := programGateway(n.path, gw, true)
  259. if err == nil {
  260. n.Lock()
  261. n.sinfo.Gateway = gw
  262. n.Unlock()
  263. }
  264. return err
  265. }
  266. func (n *networkNamespace) UnsetGateway() error {
  267. n.Lock()
  268. gw := n.sinfo.Gateway
  269. n.Unlock()
  270. // Silently return if the gateway is empty
  271. if len(gw) == 0 {
  272. return nil
  273. }
  274. err := programGateway(n.path, gw, false)
  275. if err == nil {
  276. n.Lock()
  277. n.sinfo.Gateway = net.IP{}
  278. n.Unlock()
  279. }
  280. return err
  281. }
  282. func (n *networkNamespace) SetGatewayIPv6(gw net.IP) error {
  283. // Silently return if the gateway is empty
  284. if len(gw) == 0 {
  285. return nil
  286. }
  287. err := programGateway(n.path, gw, true)
  288. if err == nil {
  289. n.Lock()
  290. n.sinfo.GatewayIPv6 = gw
  291. n.Unlock()
  292. }
  293. return err
  294. }
  295. func (n *networkNamespace) UnsetGatewayIPv6() error {
  296. n.Lock()
  297. gw := n.sinfo.GatewayIPv6
  298. n.Unlock()
  299. // Silently return if the gateway is empty
  300. if len(gw) == 0 {
  301. return nil
  302. }
  303. err := programGateway(n.path, gw, false)
  304. if err == nil {
  305. n.Lock()
  306. n.sinfo.GatewayIPv6 = net.IP{}
  307. n.Unlock()
  308. }
  309. return err
  310. }
  311. func (n *networkNamespace) AddStaticRoute(r *types.StaticRoute) error {
  312. err := programRoute(n.path, r.Destination, r.NextHop)
  313. if err == nil {
  314. n.Lock()
  315. n.sinfo.StaticRoutes = append(n.sinfo.StaticRoutes, r)
  316. n.Unlock()
  317. }
  318. return err
  319. }
  320. func (n *networkNamespace) RemoveStaticRoute(r *types.StaticRoute) error {
  321. err := removeRoute(n.path, r.Destination, r.NextHop)
  322. if err == nil {
  323. n.Lock()
  324. lastIndex := len(n.sinfo.StaticRoutes) - 1
  325. for i, v := range n.sinfo.StaticRoutes {
  326. if v == r {
  327. // Overwrite the route we're removing with the last element
  328. n.sinfo.StaticRoutes[i] = n.sinfo.StaticRoutes[lastIndex]
  329. // Shorten the slice to trim the extra element
  330. n.sinfo.StaticRoutes = n.sinfo.StaticRoutes[:lastIndex]
  331. break
  332. }
  333. }
  334. n.Unlock()
  335. }
  336. return err
  337. }
  338. func (n *networkNamespace) Interfaces() []*Interface {
  339. n.Lock()
  340. defer n.Unlock()
  341. return n.sinfo.Interfaces
  342. }
  343. func (n *networkNamespace) Key() string {
  344. return n.path
  345. }
  346. func (n *networkNamespace) Destroy() error {
  347. // Assuming no running process is executing in this network namespace,
  348. // unmounting is sufficient to destroy it.
  349. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  350. return err
  351. }
  352. // Stash it into the garbage collection list
  353. addToGarbagePaths(n.path)
  354. return nil
  355. }