namespace_linux.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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 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) InvokeFunc(f func()) error {
  302. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  303. f()
  304. return nil
  305. })
  306. }
  307. // InitOSContext initializes OS context while configuring network resources
  308. func InitOSContext() func() {
  309. runtime.LockOSThread()
  310. if err := ns.SetNamespace(); err != nil {
  311. logrus.Error(err)
  312. }
  313. return runtime.UnlockOSThread
  314. }
  315. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  316. defer InitOSContext()()
  317. newNs, err := netns.GetFromPath(path)
  318. if err != nil {
  319. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  320. }
  321. defer newNs.Close()
  322. // Invoked before the namespace switch happens but after the namespace file
  323. // handle is obtained.
  324. if err := prefunc(int(newNs)); err != nil {
  325. return fmt.Errorf("failed in prefunc: %v", err)
  326. }
  327. if err = netns.Set(newNs); err != nil {
  328. return err
  329. }
  330. defer ns.SetNamespace()
  331. // Invoked after the namespace switch.
  332. return postfunc(ns.ParseHandlerInt())
  333. }
  334. func (n *networkNamespace) nsPath() string {
  335. n.Lock()
  336. defer n.Unlock()
  337. return n.path
  338. }
  339. func (n *networkNamespace) Info() Info {
  340. return n
  341. }
  342. func (n *networkNamespace) Key() string {
  343. return n.path
  344. }
  345. func (n *networkNamespace) Destroy() error {
  346. if n.nlHandle != nil {
  347. n.nlHandle.Delete()
  348. }
  349. // Assuming no running process is executing in this network namespace,
  350. // unmounting is sufficient to destroy it.
  351. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  352. return err
  353. }
  354. // Stash it into the garbage collection list
  355. addToGarbagePaths(n.path)
  356. return nil
  357. }
  358. // Restore restore the network namespace
  359. func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
  360. // restore interfaces
  361. for name, opts := range ifsopt {
  362. if !strings.Contains(name, "+") {
  363. return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
  364. }
  365. seps := strings.Split(name, "+")
  366. srcName := seps[0]
  367. dstPrefix := seps[1]
  368. i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
  369. i.processInterfaceOptions(opts...)
  370. if i.master != "" {
  371. i.dstMaster = n.findDst(i.master, true)
  372. if i.dstMaster == "" {
  373. return fmt.Errorf("could not find an appropriate master %q for %q",
  374. i.master, i.srcName)
  375. }
  376. }
  377. if n.isDefault {
  378. i.dstName = i.srcName
  379. } else {
  380. links, err := n.nlHandle.LinkList()
  381. if err != nil {
  382. return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
  383. }
  384. // due to the docker network connect/disconnect, so the dstName should
  385. // restore from the namespace
  386. for _, link := range links {
  387. addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
  388. if err != nil {
  389. return err
  390. }
  391. ifaceName := link.Attrs().Name
  392. if strings.HasPrefix(ifaceName, "vxlan") {
  393. if i.dstName == "vxlan" {
  394. i.dstName = ifaceName
  395. break
  396. }
  397. }
  398. // find the interface name by ip
  399. if i.address != nil {
  400. for _, addr := range addrs {
  401. if addr.IPNet.String() == i.address.String() {
  402. i.dstName = ifaceName
  403. break
  404. }
  405. continue
  406. }
  407. if i.dstName == ifaceName {
  408. break
  409. }
  410. }
  411. // This is to find the interface name of the pair in overlay sandbox
  412. if strings.HasPrefix(ifaceName, "veth") {
  413. if i.master != "" && i.dstName == "veth" {
  414. i.dstName = ifaceName
  415. }
  416. }
  417. }
  418. var index int
  419. indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
  420. if indexStr != "" {
  421. index, err = strconv.Atoi(indexStr)
  422. if err != nil {
  423. return err
  424. }
  425. }
  426. index++
  427. n.Lock()
  428. if index > n.nextIfIndex[dstPrefix] {
  429. n.nextIfIndex[dstPrefix] = index
  430. }
  431. n.iFaces = append(n.iFaces, i)
  432. n.Unlock()
  433. }
  434. }
  435. // restore routes
  436. for _, r := range routes {
  437. n.Lock()
  438. n.staticRoutes = append(n.staticRoutes, r)
  439. n.Unlock()
  440. }
  441. // restore gateway
  442. if len(gw) > 0 {
  443. n.Lock()
  444. n.gw = gw
  445. n.Unlock()
  446. }
  447. if len(gw6) > 0 {
  448. n.Lock()
  449. n.gwv6 = gw6
  450. n.Unlock()
  451. }
  452. return nil
  453. }
  454. // Checks whether IPv6 needs to be enabled/disabled on the loopback interface
  455. func (n *networkNamespace) checkLoV6() {
  456. var (
  457. enable = false
  458. action = "disable"
  459. )
  460. n.Lock()
  461. for _, iface := range n.iFaces {
  462. if iface.AddressIPv6() != nil {
  463. enable = true
  464. action = "enable"
  465. break
  466. }
  467. }
  468. n.Unlock()
  469. if n.loV6Enabled == enable {
  470. return
  471. }
  472. if err := setIPv6(n.path, "lo", enable); err != nil {
  473. logrus.Warnf("Failed to %s IPv6 on loopback interface on network namespace %q: %v", action, n.path, err)
  474. }
  475. n.loV6Enabled = enable
  476. }
  477. func reexecSetIPv6() {
  478. runtime.LockOSThread()
  479. defer runtime.UnlockOSThread()
  480. if len(os.Args) < 3 {
  481. logrus.Errorf("invalid number of arguments for %s", os.Args[0])
  482. os.Exit(1)
  483. }
  484. ns, err := netns.GetFromPath(os.Args[1])
  485. if err != nil {
  486. logrus.Errorf("failed get network namespace %q: %v", os.Args[1], err)
  487. os.Exit(2)
  488. }
  489. defer ns.Close()
  490. if err = netns.Set(ns); err != nil {
  491. logrus.Errorf("setting into container netns %q failed: %v", os.Args[1], err)
  492. os.Exit(3)
  493. }
  494. var (
  495. action = "disable"
  496. value = byte('1')
  497. path = fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/disable_ipv6", os.Args[2])
  498. )
  499. if os.Args[3] == "true" {
  500. action = "enable"
  501. value = byte('0')
  502. }
  503. if err = ioutil.WriteFile(path, []byte{value, '\n'}, 0644); err != nil {
  504. logrus.Errorf("failed to %s IPv6 forwarding for container's interface %s: %v", action, os.Args[2], err)
  505. os.Exit(4)
  506. }
  507. os.Exit(0)
  508. }
  509. func setIPv6(path, iface string, enable bool) error {
  510. cmd := &exec.Cmd{
  511. Path: reexec.Self(),
  512. Args: append([]string{"set-ipv6"}, path, iface, strconv.FormatBool(enable)),
  513. Stdout: os.Stdout,
  514. Stderr: os.Stderr,
  515. }
  516. if err := cmd.Run(); err != nil {
  517. return fmt.Errorf("reexec to set IPv6 failed: %v", err)
  518. }
  519. return nil
  520. }