namespace_linux.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. package osl
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. log "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/pkg/reexec"
  16. "github.com/docker/libnetwork/ns"
  17. "github.com/docker/libnetwork/types"
  18. "github.com/vishvananda/netlink"
  19. "github.com/vishvananda/netns"
  20. )
  21. const prefix = "/var/run/docker/netns"
  22. var (
  23. once sync.Once
  24. garbagePathMap = make(map[string]bool)
  25. gpmLock sync.Mutex
  26. gpmWg sync.WaitGroup
  27. gpmCleanupPeriod = 60 * time.Second
  28. gpmChan = make(chan chan struct{})
  29. nsOnce sync.Once
  30. )
  31. // The networkNamespace type is the linux implementation of the Sandbox
  32. // interface. It represents a linux network namespace, and moves an interface
  33. // into it when called on method AddInterface or sets the gateway etc.
  34. type networkNamespace struct {
  35. path string
  36. iFaces []*nwIface
  37. gw net.IP
  38. gwv6 net.IP
  39. staticRoutes []*types.StaticRoute
  40. neighbors []*neigh
  41. nextIfIndex int
  42. isDefault bool
  43. nlHandle *netlink.Handle
  44. sync.Mutex
  45. }
  46. func init() {
  47. reexec.Register("netns-create", reexecCreateNamespace)
  48. }
  49. func createBasePath() {
  50. err := os.MkdirAll(prefix, 0755)
  51. if err != nil {
  52. panic("Could not create net namespace path directory")
  53. }
  54. // Start the garbage collection go routine
  55. go removeUnusedPaths()
  56. }
  57. func removeUnusedPaths() {
  58. gpmLock.Lock()
  59. period := gpmCleanupPeriod
  60. gpmLock.Unlock()
  61. ticker := time.NewTicker(period)
  62. for {
  63. var (
  64. gc chan struct{}
  65. gcOk bool
  66. )
  67. select {
  68. case <-ticker.C:
  69. case gc, gcOk = <-gpmChan:
  70. }
  71. gpmLock.Lock()
  72. pathList := make([]string, 0, len(garbagePathMap))
  73. for path := range garbagePathMap {
  74. pathList = append(pathList, path)
  75. }
  76. garbagePathMap = make(map[string]bool)
  77. gpmWg.Add(1)
  78. gpmLock.Unlock()
  79. for _, path := range pathList {
  80. os.Remove(path)
  81. }
  82. gpmWg.Done()
  83. if gcOk {
  84. close(gc)
  85. }
  86. }
  87. }
  88. func addToGarbagePaths(path string) {
  89. gpmLock.Lock()
  90. garbagePathMap[path] = true
  91. gpmLock.Unlock()
  92. }
  93. func removeFromGarbagePaths(path string) {
  94. gpmLock.Lock()
  95. delete(garbagePathMap, path)
  96. gpmLock.Unlock()
  97. }
  98. // GC triggers garbage collection of namespace path right away
  99. // and waits for it.
  100. func GC() {
  101. gpmLock.Lock()
  102. if len(garbagePathMap) == 0 {
  103. // No need for GC if map is empty
  104. gpmLock.Unlock()
  105. return
  106. }
  107. gpmLock.Unlock()
  108. // if content exists in the garbage paths
  109. // we can trigger GC to run, providing a
  110. // channel to be notified on completion
  111. waitGC := make(chan struct{})
  112. gpmChan <- waitGC
  113. // wait for GC completion
  114. <-waitGC
  115. }
  116. // GenerateKey generates a sandbox key based on the passed
  117. // container id.
  118. func GenerateKey(containerID string) string {
  119. maxLen := 12
  120. // Read sandbox key from host for overlay
  121. if strings.HasPrefix(containerID, "-") {
  122. var (
  123. index int
  124. indexStr string
  125. tmpkey string
  126. )
  127. dir, err := ioutil.ReadDir(prefix)
  128. if err != nil {
  129. return ""
  130. }
  131. for _, v := range dir {
  132. id := v.Name()
  133. if strings.HasSuffix(id, containerID[:maxLen-1]) {
  134. indexStr = strings.TrimSuffix(id, containerID[:maxLen-1])
  135. tmpindex, err := strconv.Atoi(indexStr)
  136. if err != nil {
  137. return ""
  138. }
  139. if tmpindex > index {
  140. index = tmpindex
  141. tmpkey = id
  142. }
  143. }
  144. }
  145. containerID = tmpkey
  146. if containerID == "" {
  147. return ""
  148. }
  149. }
  150. if len(containerID) < maxLen {
  151. maxLen = len(containerID)
  152. }
  153. return prefix + "/" + containerID[:maxLen]
  154. }
  155. // NewSandbox provides a new sandbox instance created in an os specific way
  156. // provided a key which uniquely identifies the sandbox
  157. func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
  158. if !isRestore {
  159. err := createNetworkNamespace(key, osCreate)
  160. if err != nil {
  161. return nil, err
  162. }
  163. }
  164. n := &networkNamespace{path: key, isDefault: !osCreate}
  165. sboxNs, err := netns.GetFromPath(n.path)
  166. if err != nil {
  167. return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  168. }
  169. defer sboxNs.Close()
  170. n.nlHandle, err = netlink.NewHandleAt(sboxNs)
  171. if err != nil {
  172. return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
  173. }
  174. if err = n.loopbackUp(); err != nil {
  175. n.nlHandle.Delete()
  176. return nil, err
  177. }
  178. return n, nil
  179. }
  180. func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
  181. return n
  182. }
  183. func (n *networkNamespace) NeighborOptions() NeighborOptionSetter {
  184. return n
  185. }
  186. func mountNetworkNamespace(basePath string, lnPath string) error {
  187. return syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, "")
  188. }
  189. // GetSandboxForExternalKey returns sandbox object for the supplied path
  190. func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
  191. if err := createNamespaceFile(key); err != nil {
  192. return nil, err
  193. }
  194. if err := mountNetworkNamespace(basePath, key); err != nil {
  195. return nil, err
  196. }
  197. n := &networkNamespace{path: key}
  198. sboxNs, err := netns.GetFromPath(n.path)
  199. if err != nil {
  200. return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  201. }
  202. defer sboxNs.Close()
  203. n.nlHandle, err = netlink.NewHandleAt(sboxNs)
  204. if err != nil {
  205. return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
  206. }
  207. if err = n.loopbackUp(); err != nil {
  208. n.nlHandle.Delete()
  209. return nil, err
  210. }
  211. return n, nil
  212. }
  213. func reexecCreateNamespace() {
  214. if len(os.Args) < 2 {
  215. log.Fatal("no namespace path provided")
  216. }
  217. if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil {
  218. log.Fatal(err)
  219. }
  220. }
  221. func createNetworkNamespace(path string, osCreate bool) error {
  222. if err := createNamespaceFile(path); err != nil {
  223. return err
  224. }
  225. cmd := &exec.Cmd{
  226. Path: reexec.Self(),
  227. Args: append([]string{"netns-create"}, path),
  228. Stdout: os.Stdout,
  229. Stderr: os.Stderr,
  230. }
  231. if osCreate {
  232. cmd.SysProcAttr = &syscall.SysProcAttr{}
  233. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  234. }
  235. if err := cmd.Run(); err != nil {
  236. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  237. }
  238. return nil
  239. }
  240. func unmountNamespaceFile(path string) {
  241. if _, err := os.Stat(path); err == nil {
  242. syscall.Unmount(path, syscall.MNT_DETACH)
  243. }
  244. }
  245. func createNamespaceFile(path string) (err error) {
  246. var f *os.File
  247. once.Do(createBasePath)
  248. // Remove it from garbage collection list if present
  249. removeFromGarbagePaths(path)
  250. // If the path is there unmount it first
  251. unmountNamespaceFile(path)
  252. // wait for garbage collection to complete if it is in progress
  253. // before trying to create the file.
  254. gpmWg.Wait()
  255. if f, err = os.Create(path); err == nil {
  256. f.Close()
  257. }
  258. return err
  259. }
  260. func (n *networkNamespace) loopbackUp() error {
  261. iface, err := n.nlHandle.LinkByName("lo")
  262. if err != nil {
  263. return err
  264. }
  265. return n.nlHandle.LinkSetUp(iface)
  266. }
  267. func (n *networkNamespace) InvokeFunc(f func()) error {
  268. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  269. f()
  270. return nil
  271. })
  272. }
  273. // InitOSContext initializes OS context while configuring network resources
  274. func InitOSContext() func() {
  275. nsOnce.Do(ns.Init)
  276. runtime.LockOSThread()
  277. if err := ns.SetNamespace(); err != nil {
  278. log.Error(err)
  279. }
  280. return runtime.UnlockOSThread
  281. }
  282. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  283. defer InitOSContext()()
  284. newNs, err := netns.GetFromPath(path)
  285. if err != nil {
  286. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  287. }
  288. defer newNs.Close()
  289. // Invoked before the namespace switch happens but after the namespace file
  290. // handle is obtained.
  291. if err := prefunc(int(newNs)); err != nil {
  292. return fmt.Errorf("failed in prefunc: %v", err)
  293. }
  294. if err = netns.Set(newNs); err != nil {
  295. return err
  296. }
  297. defer ns.SetNamespace()
  298. // Invoked after the namespace switch.
  299. return postfunc(ns.ParseHandlerInt())
  300. }
  301. func (n *networkNamespace) nsPath() string {
  302. n.Lock()
  303. defer n.Unlock()
  304. return n.path
  305. }
  306. func (n *networkNamespace) Info() Info {
  307. return n
  308. }
  309. func (n *networkNamespace) Key() string {
  310. return n.path
  311. }
  312. func (n *networkNamespace) Destroy() error {
  313. if n.nlHandle != nil {
  314. n.nlHandle.Delete()
  315. }
  316. // Assuming no running process is executing in this network namespace,
  317. // unmounting is sufficient to destroy it.
  318. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  319. return err
  320. }
  321. // Stash it into the garbage collection list
  322. addToGarbagePaths(n.path)
  323. return nil
  324. }
  325. // Restore restore the network namespace
  326. func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
  327. // restore interfaces
  328. for name, opts := range ifsopt {
  329. if !strings.Contains(name, "+") {
  330. return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
  331. }
  332. seps := strings.Split(name, "+")
  333. srcName := seps[0]
  334. dstPrefix := seps[1]
  335. i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
  336. i.processInterfaceOptions(opts...)
  337. if i.master != "" {
  338. i.dstMaster = n.findDst(i.master, true)
  339. if i.dstMaster == "" {
  340. return fmt.Errorf("could not find an appropriate master %q for %q",
  341. i.master, i.srcName)
  342. }
  343. }
  344. if n.isDefault {
  345. i.dstName = i.srcName
  346. } else {
  347. links, err := n.nlHandle.LinkList()
  348. if err != nil {
  349. return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
  350. }
  351. // due to the docker network connect/disconnect, so the dstName should
  352. // restore from the namespace
  353. for _, link := range links {
  354. addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
  355. if err != nil {
  356. return err
  357. }
  358. ifaceName := link.Attrs().Name
  359. if strings.HasPrefix(ifaceName, "vxlan") {
  360. if i.dstName == "vxlan" {
  361. i.dstName = ifaceName
  362. break
  363. }
  364. }
  365. // find the interface name by ip
  366. if i.address != nil {
  367. for _, addr := range addrs {
  368. if addr.IPNet.String() == i.address.String() {
  369. i.dstName = ifaceName
  370. break
  371. }
  372. continue
  373. }
  374. if i.dstName == ifaceName {
  375. break
  376. }
  377. }
  378. // This is to find the interface name of the pair in overlay sandbox
  379. if strings.HasPrefix(ifaceName, "veth") {
  380. if i.master != "" && i.dstName == "veth" {
  381. i.dstName = ifaceName
  382. }
  383. }
  384. }
  385. var index int
  386. indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
  387. if indexStr != "" {
  388. index, err = strconv.Atoi(indexStr)
  389. if err != nil {
  390. return err
  391. }
  392. }
  393. index++
  394. n.Lock()
  395. if index > n.nextIfIndex {
  396. n.nextIfIndex = index
  397. }
  398. n.iFaces = append(n.iFaces, i)
  399. n.Unlock()
  400. }
  401. }
  402. // restore routes
  403. for _, r := range routes {
  404. n.Lock()
  405. n.staticRoutes = append(n.staticRoutes, r)
  406. n.Unlock()
  407. }
  408. // restore gateway
  409. if len(gw) > 0 {
  410. n.Lock()
  411. n.gw = gw
  412. n.Unlock()
  413. }
  414. if len(gw6) > 0 {
  415. n.Lock()
  416. n.gwv6 = gw6
  417. n.Unlock()
  418. }
  419. return nil
  420. }