namespace_linux.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. var (
  24. once sync.Once
  25. garbagePathMap = make(map[string]bool)
  26. gpmLock sync.Mutex
  27. gpmWg sync.WaitGroup
  28. gpmCleanupPeriod = 60 * time.Second
  29. gpmChan = make(chan chan struct{})
  30. prefix = defaultPrefix
  31. )
  32. // The networkNamespace type is the linux implementation of the Sandbox
  33. // interface. It represents a linux network namespace, and moves an interface
  34. // into it when called on method AddInterface or sets the gateway etc.
  35. type networkNamespace struct {
  36. path string
  37. iFaces []*nwIface
  38. gw net.IP
  39. gwv6 net.IP
  40. staticRoutes []*types.StaticRoute
  41. neighbors []*neigh
  42. nextIfIndex int
  43. isDefault bool
  44. nlHandle *netlink.Handle
  45. sync.Mutex
  46. }
  47. // SetBasePath sets the base url prefix for the ns path
  48. func SetBasePath(path string) {
  49. prefix = path
  50. }
  51. func init() {
  52. reexec.Register("netns-create", reexecCreateNamespace)
  53. }
  54. func basePath() string {
  55. return filepath.Join(prefix, "netns")
  56. }
  57. func createBasePath() {
  58. err := os.MkdirAll(basePath(), 0755)
  59. if err != nil {
  60. panic("Could not create net namespace path directory")
  61. }
  62. // Start the garbage collection go routine
  63. go removeUnusedPaths()
  64. }
  65. func removeUnusedPaths() {
  66. gpmLock.Lock()
  67. period := gpmCleanupPeriod
  68. gpmLock.Unlock()
  69. ticker := time.NewTicker(period)
  70. for {
  71. var (
  72. gc chan struct{}
  73. gcOk bool
  74. )
  75. select {
  76. case <-ticker.C:
  77. case gc, gcOk = <-gpmChan:
  78. }
  79. gpmLock.Lock()
  80. pathList := make([]string, 0, len(garbagePathMap))
  81. for path := range garbagePathMap {
  82. pathList = append(pathList, path)
  83. }
  84. garbagePathMap = make(map[string]bool)
  85. gpmWg.Add(1)
  86. gpmLock.Unlock()
  87. for _, path := range pathList {
  88. os.Remove(path)
  89. }
  90. gpmWg.Done()
  91. if gcOk {
  92. close(gc)
  93. }
  94. }
  95. }
  96. func addToGarbagePaths(path string) {
  97. gpmLock.Lock()
  98. garbagePathMap[path] = true
  99. gpmLock.Unlock()
  100. }
  101. func removeFromGarbagePaths(path string) {
  102. gpmLock.Lock()
  103. delete(garbagePathMap, path)
  104. gpmLock.Unlock()
  105. }
  106. // GC triggers garbage collection of namespace path right away
  107. // and waits for it.
  108. func GC() {
  109. gpmLock.Lock()
  110. if len(garbagePathMap) == 0 {
  111. // No need for GC if map is empty
  112. gpmLock.Unlock()
  113. return
  114. }
  115. gpmLock.Unlock()
  116. // if content exists in the garbage paths
  117. // we can trigger GC to run, providing a
  118. // channel to be notified on completion
  119. waitGC := make(chan struct{})
  120. gpmChan <- waitGC
  121. // wait for GC completion
  122. <-waitGC
  123. }
  124. // GenerateKey generates a sandbox key based on the passed
  125. // container id.
  126. func GenerateKey(containerID string) string {
  127. maxLen := 12
  128. // Read sandbox key from host for overlay
  129. if strings.HasPrefix(containerID, "-") {
  130. var (
  131. index int
  132. indexStr string
  133. tmpkey string
  134. )
  135. dir, err := ioutil.ReadDir(basePath())
  136. if err != nil {
  137. return ""
  138. }
  139. for _, v := range dir {
  140. id := v.Name()
  141. if strings.HasSuffix(id, containerID[:maxLen-1]) {
  142. indexStr = strings.TrimSuffix(id, containerID[:maxLen-1])
  143. tmpindex, err := strconv.Atoi(indexStr)
  144. if err != nil {
  145. return ""
  146. }
  147. if tmpindex > index {
  148. index = tmpindex
  149. tmpkey = id
  150. }
  151. }
  152. }
  153. containerID = tmpkey
  154. if containerID == "" {
  155. return ""
  156. }
  157. }
  158. if len(containerID) < maxLen {
  159. maxLen = len(containerID)
  160. }
  161. return basePath() + "/" + containerID[:maxLen]
  162. }
  163. // NewSandbox provides a new sandbox instance created in an os specific way
  164. // provided a key which uniquely identifies the sandbox
  165. func NewSandbox(key string, osCreate, isRestore bool) (Sandbox, error) {
  166. if !isRestore {
  167. err := createNetworkNamespace(key, osCreate)
  168. if err != nil {
  169. return nil, err
  170. }
  171. } else {
  172. once.Do(createBasePath)
  173. }
  174. n := &networkNamespace{path: key, isDefault: !osCreate}
  175. sboxNs, err := netns.GetFromPath(n.path)
  176. if err != nil {
  177. return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  178. }
  179. defer sboxNs.Close()
  180. n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE)
  181. if err != nil {
  182. return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
  183. }
  184. if err = n.loopbackUp(); err != nil {
  185. n.nlHandle.Delete()
  186. return nil, err
  187. }
  188. return n, nil
  189. }
  190. func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
  191. return n
  192. }
  193. func (n *networkNamespace) NeighborOptions() NeighborOptionSetter {
  194. return n
  195. }
  196. func mountNetworkNamespace(basePath string, lnPath string) error {
  197. return syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, "")
  198. }
  199. // GetSandboxForExternalKey returns sandbox object for the supplied path
  200. func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
  201. if err := createNamespaceFile(key); err != nil {
  202. return nil, err
  203. }
  204. if err := mountNetworkNamespace(basePath, key); err != nil {
  205. return nil, err
  206. }
  207. n := &networkNamespace{path: key}
  208. sboxNs, err := netns.GetFromPath(n.path)
  209. if err != nil {
  210. return nil, fmt.Errorf("failed get network namespace %q: %v", n.path, err)
  211. }
  212. defer sboxNs.Close()
  213. n.nlHandle, err = netlink.NewHandleAt(sboxNs, syscall.NETLINK_ROUTE)
  214. if err != nil {
  215. return nil, fmt.Errorf("failed to create a netlink handle: %v", err)
  216. }
  217. if err = n.loopbackUp(); err != nil {
  218. n.nlHandle.Delete()
  219. return nil, err
  220. }
  221. return n, nil
  222. }
  223. func reexecCreateNamespace() {
  224. if len(os.Args) < 2 {
  225. logrus.Fatal("no namespace path provided")
  226. }
  227. if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil {
  228. logrus.Fatal(err)
  229. }
  230. }
  231. func createNetworkNamespace(path string, osCreate bool) error {
  232. if err := createNamespaceFile(path); err != nil {
  233. return err
  234. }
  235. cmd := &exec.Cmd{
  236. Path: reexec.Self(),
  237. Args: append([]string{"netns-create"}, path),
  238. Stdout: os.Stdout,
  239. Stderr: os.Stderr,
  240. }
  241. if osCreate {
  242. cmd.SysProcAttr = &syscall.SysProcAttr{}
  243. cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
  244. }
  245. if err := cmd.Run(); err != nil {
  246. return fmt.Errorf("namespace creation reexec command failed: %v", err)
  247. }
  248. return nil
  249. }
  250. func unmountNamespaceFile(path string) {
  251. if _, err := os.Stat(path); err == nil {
  252. syscall.Unmount(path, syscall.MNT_DETACH)
  253. }
  254. }
  255. func createNamespaceFile(path string) (err error) {
  256. var f *os.File
  257. once.Do(createBasePath)
  258. // Remove it from garbage collection list if present
  259. removeFromGarbagePaths(path)
  260. // If the path is there unmount it first
  261. unmountNamespaceFile(path)
  262. // wait for garbage collection to complete if it is in progress
  263. // before trying to create the file.
  264. gpmWg.Wait()
  265. if f, err = os.Create(path); err == nil {
  266. f.Close()
  267. }
  268. return err
  269. }
  270. func (n *networkNamespace) loopbackUp() error {
  271. iface, err := n.nlHandle.LinkByName("lo")
  272. if err != nil {
  273. return err
  274. }
  275. return n.nlHandle.LinkSetUp(iface)
  276. }
  277. func (n *networkNamespace) InvokeFunc(f func()) error {
  278. return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
  279. f()
  280. return nil
  281. })
  282. }
  283. // InitOSContext initializes OS context while configuring network resources
  284. func InitOSContext() func() {
  285. runtime.LockOSThread()
  286. if err := ns.SetNamespace(); err != nil {
  287. logrus.Error(err)
  288. }
  289. return runtime.UnlockOSThread
  290. }
  291. func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
  292. defer InitOSContext()()
  293. newNs, err := netns.GetFromPath(path)
  294. if err != nil {
  295. return fmt.Errorf("failed get network namespace %q: %v", path, err)
  296. }
  297. defer newNs.Close()
  298. // Invoked before the namespace switch happens but after the namespace file
  299. // handle is obtained.
  300. if err := prefunc(int(newNs)); err != nil {
  301. return fmt.Errorf("failed in prefunc: %v", err)
  302. }
  303. if err = netns.Set(newNs); err != nil {
  304. return err
  305. }
  306. defer ns.SetNamespace()
  307. // Invoked after the namespace switch.
  308. return postfunc(ns.ParseHandlerInt())
  309. }
  310. func (n *networkNamespace) nsPath() string {
  311. n.Lock()
  312. defer n.Unlock()
  313. return n.path
  314. }
  315. func (n *networkNamespace) Info() Info {
  316. return n
  317. }
  318. func (n *networkNamespace) Key() string {
  319. return n.path
  320. }
  321. func (n *networkNamespace) Destroy() error {
  322. if n.nlHandle != nil {
  323. n.nlHandle.Delete()
  324. }
  325. // Assuming no running process is executing in this network namespace,
  326. // unmounting is sufficient to destroy it.
  327. if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
  328. return err
  329. }
  330. // Stash it into the garbage collection list
  331. addToGarbagePaths(n.path)
  332. return nil
  333. }
  334. // Restore restore the network namespace
  335. func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
  336. // restore interfaces
  337. for name, opts := range ifsopt {
  338. if !strings.Contains(name, "+") {
  339. return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
  340. }
  341. seps := strings.Split(name, "+")
  342. srcName := seps[0]
  343. dstPrefix := seps[1]
  344. i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
  345. i.processInterfaceOptions(opts...)
  346. if i.master != "" {
  347. i.dstMaster = n.findDst(i.master, true)
  348. if i.dstMaster == "" {
  349. return fmt.Errorf("could not find an appropriate master %q for %q",
  350. i.master, i.srcName)
  351. }
  352. }
  353. if n.isDefault {
  354. i.dstName = i.srcName
  355. } else {
  356. links, err := n.nlHandle.LinkList()
  357. if err != nil {
  358. return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
  359. }
  360. // due to the docker network connect/disconnect, so the dstName should
  361. // restore from the namespace
  362. for _, link := range links {
  363. addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
  364. if err != nil {
  365. return err
  366. }
  367. ifaceName := link.Attrs().Name
  368. if strings.HasPrefix(ifaceName, "vxlan") {
  369. if i.dstName == "vxlan" {
  370. i.dstName = ifaceName
  371. break
  372. }
  373. }
  374. // find the interface name by ip
  375. if i.address != nil {
  376. for _, addr := range addrs {
  377. if addr.IPNet.String() == i.address.String() {
  378. i.dstName = ifaceName
  379. break
  380. }
  381. continue
  382. }
  383. if i.dstName == ifaceName {
  384. break
  385. }
  386. }
  387. // This is to find the interface name of the pair in overlay sandbox
  388. if strings.HasPrefix(ifaceName, "veth") {
  389. if i.master != "" && i.dstName == "veth" {
  390. i.dstName = ifaceName
  391. }
  392. }
  393. }
  394. var index int
  395. indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
  396. if indexStr != "" {
  397. index, err = strconv.Atoi(indexStr)
  398. if err != nil {
  399. return err
  400. }
  401. }
  402. index++
  403. n.Lock()
  404. if index > n.nextIfIndex {
  405. n.nextIfIndex = index
  406. }
  407. n.iFaces = append(n.iFaces, i)
  408. n.Unlock()
  409. }
  410. }
  411. // restore routes
  412. for _, r := range routes {
  413. n.Lock()
  414. n.staticRoutes = append(n.staticRoutes, r)
  415. n.Unlock()
  416. }
  417. // restore gateway
  418. if len(gw) > 0 {
  419. n.Lock()
  420. n.gw = gw
  421. n.Unlock()
  422. }
  423. if len(gw6) > 0 {
  424. n.Lock()
  425. n.gwv6 = gw6
  426. n.Unlock()
  427. }
  428. return nil
  429. }