namespace_linux.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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/types"
  18. "github.com/sirupsen/logrus"
  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 map[string]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, nextIfIndex: make(map[string]int)}
  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. if !n.isDefault {
  194. err = setIPv6(n.path, "all", false)
  195. if err != nil {
  196. logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err)
  197. }
  198. }
  199. if err = n.loopbackUp(); err != nil {
  200. n.nlHandle.Delete()
  201. return nil, err
  202. }
  203. return n, nil
  204. }
  205. func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
  206. return n
  207. }
  208. func (n *networkNamespace) NeighborOptions() NeighborOptionSetter {
  209. return n
  210. }
  211. func mountNetworkNamespace(basePath string, lnPath string) error {
  212. return syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, "")
  213. }
  214. // GetSandboxForExternalKey returns sandbox object for the supplied path
  215. func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
  216. if err := createNamespaceFile(key); err != nil {
  217. return nil, err
  218. }
  219. if err := mountNetworkNamespace(basePath, key); err != nil {
  220. return nil, err
  221. }
  222. n := &networkNamespace{path: key, nextIfIndex: make(map[string]int)}
  223. sboxNs, err := netns.GetFromPath(n.path)
  224. if err != nil {
  225. return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  226. }
  227. defer sboxNs.Close()
  228. n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE)
  229. if err != nil {
  230. return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
  231. }
  232. err = n.nlHandle.SetSocketTimeout(ns.NetlinkSocketsTimeout)
  233. if err != nil {
  234. logrus.Warnf("Failed to set the timeout on the sandbox netlink handle sockets: %v", err)
  235. }
  236. // As starting point, disable IPv6 on all interfaces
  237. err = setIPv6(n.path, "all", false)
  238. if err != nil {
  239. logrus.Warnf("Failed to disable IPv6 on all interfaces on network namespace %q: %v", n.path, err)
  240. }
  241. if err = n.loopbackUp(); err != nil {
  242. n.nlHandle.Delete()
  243. return nil, err
  244. }
  245. return n, nil
  246. }
  247. func reexecCreateNamespace() {
  248. if len(os.Args) < 2 {
  249. logrus.Fatal("no namespace path provided")
  250. }
  251. if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil {
  252. logrus.Fatal(err)
  253. }
  254. }
  255. func createNetworkNamespace(path string, osCreate bool) error {
  256. if err := createNamespaceFile(path); err != nil {
  257. return err
  258. }
  259. cmd := &exec.Cmd{
  260. Path: reexec.Self(),
  261. Args: append([]string{"netns-create"}, path),
  262. Stdout: os.Stdout,
  263. Stderr: os.Stderr,
  264. }
  265. if osCreate {
  266. cmd.SysProcAttr = &syscall.SysProcAttr{}
  267. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  268. }
  269. if err := cmd.Run(); err != nil {
  270. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  271. }
  272. return nil
  273. }
  274. func unmountNamespaceFile(path string) {
  275. if _, err := os.Stat(path); err == nil {
  276. syscall.Unmount(path, syscall.MNT_DETACH)
  277. }
  278. }
  279. func createNamespaceFile(path string) (err error) {
  280. var f *os.File
  281. once.Do(createBasePath)
  282. // Remove it from garbage collection list if present
  283. removeFromGarbagePaths(path)
  284. // If the path is there unmount it first
  285. unmountNamespaceFile(path)
  286. // wait for garbage collection to complete if it is in progress
  287. // before trying to create the file.
  288. gpmWg.Wait()
  289. if f, err = os.Create(path); err == nil {
  290. f.Close()
  291. }
  292. return err
  293. }
  294. func (n *networkNamespace) loopbackUp() error {
  295. iface, err := n.nlHandle.LinkByName("lo")
  296. if err != nil {
  297. return err
  298. }
  299. return n.nlHandle.LinkSetUp(iface)
  300. }
  301. func (n *networkNamespace) AddLoopbackAliasIP(ip *net.IPNet) error {
  302. iface, err := n.nlHandle.LinkByName("lo")
  303. if err != nil {
  304. return err
  305. }
  306. return n.nlHandle.AddrAdd(iface, &netlink.Addr{IPNet: ip})
  307. }
  308. func (n *networkNamespace) RemoveLoopbackAliasIP(ip *net.IPNet) error {
  309. iface, err := n.nlHandle.LinkByName("lo")
  310. if err != nil {
  311. return err
  312. }
  313. return n.nlHandle.AddrDel(iface, &netlink.Addr{IPNet: ip})
  314. }
  315. func (n *networkNamespace) InvokeFunc(f func()) error {
  316. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  317. f()
  318. return nil
  319. })
  320. }
  321. // InitOSContext initializes OS context while configuring network resources
  322. func InitOSContext() func() {
  323. runtime.LockOSThread()
  324. if err := ns.SetNamespace(); err != nil {
  325. logrus.Error(err)
  326. }
  327. return runtime.UnlockOSThread
  328. }
  329. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  330. defer InitOSContext()()
  331. newNs, err := netns.GetFromPath(path)
  332. if err != nil {
  333. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  334. }
  335. defer newNs.Close()
  336. // Invoked before the namespace switch happens but after the namespace file
  337. // handle is obtained.
  338. if err := prefunc(int(newNs)); err != nil {
  339. return fmt.Errorf("failed in prefunc: %v", err)
  340. }
  341. if err = netns.Set(newNs); err != nil {
  342. return err
  343. }
  344. defer ns.SetNamespace()
  345. // Invoked after the namespace switch.
  346. return postfunc(ns.ParseHandlerInt())
  347. }
  348. func (n *networkNamespace) nsPath() string {
  349. n.Lock()
  350. defer n.Unlock()
  351. return n.path
  352. }
  353. func (n *networkNamespace) Info() Info {
  354. return n
  355. }
  356. func (n *networkNamespace) Key() string {
  357. return n.path
  358. }
  359. func (n *networkNamespace) Destroy() error {
  360. if n.nlHandle != nil {
  361. n.nlHandle.Delete()
  362. }
  363. // Assuming no running process is executing in this network namespace,
  364. // unmounting is sufficient to destroy it.
  365. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  366. return err
  367. }
  368. // Stash it into the garbage collection list
  369. addToGarbagePaths(n.path)
  370. return nil
  371. }
  372. // Restore restore the network namespace
  373. func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
  374. // restore interfaces
  375. for name, opts := range ifsopt {
  376. if !strings.Contains(name, "+") {
  377. return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
  378. }
  379. seps := strings.Split(name, "+")
  380. srcName := seps[0]
  381. dstPrefix := seps[1]
  382. i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
  383. i.processInterfaceOptions(opts...)
  384. if i.master != "" {
  385. i.dstMaster = n.findDst(i.master, true)
  386. if i.dstMaster == "" {
  387. return fmt.Errorf("could not find an appropriate master %q for %q",
  388. i.master, i.srcName)
  389. }
  390. }
  391. if n.isDefault {
  392. i.dstName = i.srcName
  393. } else {
  394. links, err := n.nlHandle.LinkList()
  395. if err != nil {
  396. return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
  397. }
  398. // due to the docker network connect/disconnect, so the dstName should
  399. // restore from the namespace
  400. for _, link := range links {
  401. addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
  402. if err != nil {
  403. return err
  404. }
  405. ifaceName := link.Attrs().Name
  406. if strings.HasPrefix(ifaceName, "vxlan") {
  407. if i.dstName == "vxlan" {
  408. i.dstName = ifaceName
  409. break
  410. }
  411. }
  412. // find the interface name by ip
  413. if i.address != nil {
  414. for _, addr := range addrs {
  415. if addr.IPNet.String() == i.address.String() {
  416. i.dstName = ifaceName
  417. break
  418. }
  419. continue
  420. }
  421. if i.dstName == ifaceName {
  422. break
  423. }
  424. }
  425. // This is to find the interface name of the pair in overlay sandbox
  426. if strings.HasPrefix(ifaceName, "veth") {
  427. if i.master != "" && i.dstName == "veth" {
  428. i.dstName = ifaceName
  429. }
  430. }
  431. }
  432. var index int
  433. indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
  434. if indexStr != "" {
  435. index, err = strconv.Atoi(indexStr)
  436. if err != nil {
  437. return err
  438. }
  439. }
  440. index++
  441. n.Lock()
  442. if index > n.nextIfIndex[dstPrefix] {
  443. n.nextIfIndex[dstPrefix] = index
  444. }
  445. n.iFaces = append(n.iFaces, i)
  446. n.Unlock()
  447. }
  448. }
  449. // restore routes
  450. for _, r := range routes {
  451. n.Lock()
  452. n.staticRoutes = append(n.staticRoutes, r)
  453. n.Unlock()
  454. }
  455. // restore gateway
  456. if len(gw) > 0 {
  457. n.Lock()
  458. n.gw = gw
  459. n.Unlock()
  460. }
  461. if len(gw6) > 0 {
  462. n.Lock()
  463. n.gwv6 = gw6
  464. n.Unlock()
  465. }
  466. return nil
  467. }
  468. // Checks whether IPv6 needs to be enabled/disabled on the loopback interface
  469. func (n *networkNamespace) checkLoV6() {
  470. var (
  471. enable = false
  472. action = "disable"
  473. )
  474. n.Lock()
  475. for _, iface := range n.iFaces {
  476. if iface.AddressIPv6() != nil {
  477. enable = true
  478. action = "enable"
  479. break
  480. }
  481. }
  482. n.Unlock()
  483. if n.loV6Enabled == enable {
  484. return
  485. }
  486. if err := setIPv6(n.path, "lo", enable); err != nil {
  487. logrus.Warnf("Failed to %s IPv6 on loopback interface on network namespace %q: %v", action, n.path, err)
  488. }
  489. n.loV6Enabled = enable
  490. }
  491. func reexecSetIPv6() {
  492. runtime.LockOSThread()
  493. defer runtime.UnlockOSThread()
  494. if len(os.Args) < 3 {
  495. logrus.Errorf("invalid number of arguments for %s", os.Args[0])
  496. os.Exit(1)
  497. }
  498. ns, err := netns.GetFromPath(os.Args[1])
  499. if err != nil {
  500. logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
  501. os.Exit(2)
  502. }
  503. defer ns.Close()
  504. if err = netns.Set(ns); err != nil {
  505. logrus.Errorf("setting into container netns %q failed: %v", os.Args[1], err)
  506. os.Exit(3)
  507. }
  508. var (
  509. action = "disable"
  510. value = byte('1')
  511. path = fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", os.Args[2])
  512. )
  513. if os.Args[3] == "true" {
  514. action = "enable"
  515. value = byte('0')
  516. }
  517. if err = ioutil.WriteFile(path, []byte{value, '\n'}, 0644); err != nil {
  518. logrus.Errorf("failed to %s IPv6 forwarding for container's interface %s: %v", action, os.Args[2], err)
  519. os.Exit(4)
  520. }
  521. os.Exit(0)
  522. }
  523. func setIPv6(path, iface string, enable bool) error {
  524. cmd := &exec.Cmd{
  525. Path: reexec.Self(),
  526. Args: append([]string{"set-ipv6"}, path, iface, strconv.FormatBool(enable)),
  527. Stdout: os.Stdout,
  528. Stderr: os.Stderr,
  529. }
  530. if err := cmd.Run(); err != nil {
  531. return fmt.Errorf("reexec to set IPv6 failed: %v", err)
  532. }
  533. return nil
  534. }