namespace_linux.go 9.3 KB

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