namespace_linux.go 16 KB

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