namespace_linux.go 17 KB

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