namespace_linux.go 13 KB

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