namespace_linux.go 16 KB

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