overlay.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. // +build linux
  2. package overlay2
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "github.com/sirupsen/logrus"
  17. "github.com/docker/docker/daemon/graphdriver"
  18. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  19. "github.com/docker/docker/daemon/graphdriver/quota"
  20. "github.com/docker/docker/pkg/archive"
  21. "github.com/docker/docker/pkg/chrootarchive"
  22. "github.com/docker/docker/pkg/containerfs"
  23. "github.com/docker/docker/pkg/directory"
  24. "github.com/docker/docker/pkg/fsutils"
  25. "github.com/docker/docker/pkg/idtools"
  26. "github.com/docker/docker/pkg/locker"
  27. "github.com/docker/docker/pkg/mount"
  28. "github.com/docker/docker/pkg/parsers"
  29. "github.com/docker/docker/pkg/parsers/kernel"
  30. "github.com/docker/docker/pkg/system"
  31. units "github.com/docker/go-units"
  32. "github.com/opencontainers/selinux/go-selinux/label"
  33. "golang.org/x/sys/unix"
  34. )
  35. var (
  36. // untar defines the untar method
  37. untar = chrootarchive.UntarUncompressed
  38. )
  39. // This backend uses the overlay union filesystem for containers
  40. // with diff directories for each layer.
  41. // This version of the overlay driver requires at least kernel
  42. // 4.0.0 in order to support mounting multiple diff directories.
  43. // Each container/image has at least a "diff" directory and "link" file.
  44. // If there is also a "lower" file when there are diff layers
  45. // below as well as "merged" and "work" directories. The "diff" directory
  46. // has the upper layer of the overlay and is used to capture any
  47. // changes to the layer. The "lower" file contains all the lower layer
  48. // mounts separated by ":" and ordered from uppermost to lowermost
  49. // layers. The overlay itself is mounted in the "merged" directory,
  50. // and the "work" dir is needed for overlay to work.
  51. // The "link" file for each layer contains a unique string for the layer.
  52. // Under the "l" directory at the root there will be a symbolic link
  53. // with that unique string pointing the "diff" directory for the layer.
  54. // The symbolic links are used to reference lower layers in the "lower"
  55. // file and on mount. The links are used to shorten the total length
  56. // of a layer reference without requiring changes to the layer identifier
  57. // or root directory. Mounts are always done relative to root and
  58. // referencing the symbolic links in order to ensure the number of
  59. // lower directories can fit in a single page for making the mount
  60. // syscall. A hard upper limit of 128 lower layers is enforced to ensure
  61. // that mounts do not fail due to length.
  62. const (
  63. driverName = "overlay2"
  64. linkDir = "l"
  65. lowerFile = "lower"
  66. maxDepth = 128
  67. // idLength represents the number of random characters
  68. // which can be used to create the unique link identifier
  69. // for every layer. If this value is too long then the
  70. // page size limit for the mount command may be exceeded.
  71. // The idLength should be selected such that following equation
  72. // is true (512 is a buffer for label metadata).
  73. // ((idLength + len(linkDir) + 1) * maxDepth) <= (pageSize - 512)
  74. idLength = 26
  75. )
  76. type overlayOptions struct {
  77. overrideKernelCheck bool
  78. quota quota.Quota
  79. }
  80. // Driver contains information about the home directory and the list of active
  81. // mounts that are created using this driver.
  82. type Driver struct {
  83. home string
  84. uidMaps []idtools.IDMap
  85. gidMaps []idtools.IDMap
  86. ctr *graphdriver.RefCounter
  87. quotaCtl *quota.Control
  88. options overlayOptions
  89. naiveDiff graphdriver.DiffDriver
  90. supportsDType bool
  91. locker *locker.Locker
  92. }
  93. var (
  94. backingFs = "<unknown>"
  95. projectQuotaSupported = false
  96. useNaiveDiffLock sync.Once
  97. useNaiveDiffOnly bool
  98. )
  99. func init() {
  100. graphdriver.Register(driverName, Init)
  101. }
  102. // Init returns the native diff driver for overlay filesystem.
  103. // If overlay filesystem is not supported on the host, the error
  104. // graphdriver.ErrNotSupported is returned.
  105. // If an overlay filesystem is not supported over an existing filesystem then
  106. // the error graphdriver.ErrIncompatibleFS is returned.
  107. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  108. opts, err := parseOptions(options)
  109. if err != nil {
  110. return nil, err
  111. }
  112. if err := supportsOverlay(); err != nil {
  113. return nil, graphdriver.ErrNotSupported
  114. }
  115. // require kernel 4.0.0 to ensure multiple lower dirs are supported
  116. v, err := kernel.GetKernelVersion()
  117. if err != nil {
  118. return nil, err
  119. }
  120. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 {
  121. if !opts.overrideKernelCheck {
  122. return nil, graphdriver.ErrNotSupported
  123. }
  124. logrus.Warn("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update")
  125. }
  126. fsMagic, err := graphdriver.GetFSMagic(home)
  127. if err != nil {
  128. return nil, err
  129. }
  130. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  131. backingFs = fsName
  132. }
  133. // check if they are running over btrfs, aufs, zfs, overlay, or ecryptfs
  134. switch fsMagic {
  135. case graphdriver.FsMagicAufs, graphdriver.FsMagicZfs, graphdriver.FsMagicOverlay, graphdriver.FsMagicEcryptfs:
  136. logrus.Errorf("'overlay2' is not supported over %s", backingFs)
  137. return nil, graphdriver.ErrIncompatibleFS
  138. case graphdriver.FsMagicBtrfs:
  139. // Support for OverlayFS on BTRFS was added in kernel 4.7
  140. // See https://btrfs.wiki.kernel.org/index.php/Changelog
  141. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 7, Minor: 0}) < 0 {
  142. if !opts.overrideKernelCheck {
  143. logrus.Errorf("'overlay2' requires kernel 4.7 to use on %s", backingFs)
  144. return nil, graphdriver.ErrIncompatibleFS
  145. }
  146. logrus.Warn("Using pre-4.7.0 kernel for overlay2 on btrfs, may require kernel update")
  147. }
  148. }
  149. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  150. if err != nil {
  151. return nil, err
  152. }
  153. // Create the driver home dir
  154. if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, idtools.IDPair{rootUID, rootGID}); err != nil && !os.IsExist(err) {
  155. return nil, err
  156. }
  157. if err := mount.MakePrivate(home); err != nil {
  158. return nil, err
  159. }
  160. supportsDType, err := fsutils.SupportsDType(home)
  161. if err != nil {
  162. return nil, err
  163. }
  164. if !supportsDType {
  165. // not a fatal error until v17.12 (#27443)
  166. logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
  167. }
  168. d := &Driver{
  169. home: home,
  170. uidMaps: uidMaps,
  171. gidMaps: gidMaps,
  172. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  173. supportsDType: supportsDType,
  174. locker: locker.New(),
  175. options: *opts,
  176. }
  177. d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps)
  178. if backingFs == "xfs" {
  179. // Try to enable project quota support over xfs.
  180. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  181. projectQuotaSupported = true
  182. } else if opts.quota.Size > 0 {
  183. return nil, fmt.Errorf("Storage option overlay2.size not supported. Filesystem does not support Project Quota: %v", err)
  184. }
  185. } else if opts.quota.Size > 0 {
  186. // if xfs is not the backing fs then error out if the storage-opt overlay2.size is used.
  187. return nil, fmt.Errorf("Storage Option overlay2.size only supported for backingFS XFS. Found %v", backingFs)
  188. }
  189. logrus.Debugf("backingFs=%s, projectQuotaSupported=%v", backingFs, projectQuotaSupported)
  190. return d, nil
  191. }
  192. func parseOptions(options []string) (*overlayOptions, error) {
  193. o := &overlayOptions{}
  194. for _, option := range options {
  195. key, val, err := parsers.ParseKeyValueOpt(option)
  196. if err != nil {
  197. return nil, err
  198. }
  199. key = strings.ToLower(key)
  200. switch key {
  201. case "overlay2.override_kernel_check":
  202. o.overrideKernelCheck, err = strconv.ParseBool(val)
  203. if err != nil {
  204. return nil, err
  205. }
  206. case "overlay2.size":
  207. size, err := units.RAMInBytes(val)
  208. if err != nil {
  209. return nil, err
  210. }
  211. o.quota.Size = uint64(size)
  212. default:
  213. return nil, fmt.Errorf("overlay2: unknown option %s", key)
  214. }
  215. }
  216. return o, nil
  217. }
  218. func supportsOverlay() error {
  219. // We can try to modprobe overlay first before looking at
  220. // proc/filesystems for when overlay is supported
  221. exec.Command("modprobe", "overlay").Run()
  222. f, err := os.Open("/proc/filesystems")
  223. if err != nil {
  224. return err
  225. }
  226. defer f.Close()
  227. s := bufio.NewScanner(f)
  228. for s.Scan() {
  229. if s.Text() == "nodev\toverlay" {
  230. return nil
  231. }
  232. }
  233. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  234. return graphdriver.ErrNotSupported
  235. }
  236. func useNaiveDiff(home string) bool {
  237. useNaiveDiffLock.Do(func() {
  238. if err := doesSupportNativeDiff(home); err != nil {
  239. logrus.Warnf("Not using native diff for overlay2, this may cause degraded performance for building images: %v", err)
  240. useNaiveDiffOnly = true
  241. }
  242. })
  243. return useNaiveDiffOnly
  244. }
  245. func (d *Driver) String() string {
  246. return driverName
  247. }
  248. // Status returns current driver information in a two dimensional string array.
  249. // Output contains "Backing Filesystem" used in this implementation.
  250. func (d *Driver) Status() [][2]string {
  251. return [][2]string{
  252. {"Backing Filesystem", backingFs},
  253. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  254. {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))},
  255. }
  256. }
  257. // GetMetadata returns metadata about the overlay driver such as the LowerDir,
  258. // UpperDir, WorkDir, and MergeDir used to store data.
  259. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  260. dir := d.dir(id)
  261. if _, err := os.Stat(dir); err != nil {
  262. return nil, err
  263. }
  264. metadata := map[string]string{
  265. "WorkDir": path.Join(dir, "work"),
  266. "MergedDir": path.Join(dir, "merged"),
  267. "UpperDir": path.Join(dir, "diff"),
  268. }
  269. lowerDirs, err := d.getLowerDirs(id)
  270. if err != nil {
  271. return nil, err
  272. }
  273. if len(lowerDirs) > 0 {
  274. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  275. }
  276. return metadata, nil
  277. }
  278. // Cleanup any state created by overlay which should be cleaned when daemon
  279. // is being shutdown. For now, we just have to unmount the bind mounted
  280. // we had created.
  281. func (d *Driver) Cleanup() error {
  282. return mount.Unmount(d.home)
  283. }
  284. // CreateReadWrite creates a layer that is writable for use as a container
  285. // file system.
  286. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  287. if opts != nil && len(opts.StorageOpt) != 0 && !projectQuotaSupported {
  288. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  289. }
  290. if opts == nil {
  291. opts = &graphdriver.CreateOpts{
  292. StorageOpt: map[string]string{},
  293. }
  294. }
  295. if _, ok := opts.StorageOpt["size"]; !ok {
  296. if opts.StorageOpt == nil {
  297. opts.StorageOpt = map[string]string{}
  298. }
  299. opts.StorageOpt["size"] = strconv.FormatUint(d.options.quota.Size, 10)
  300. }
  301. return d.create(id, parent, opts)
  302. }
  303. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  304. // The parent filesystem is used to configure these directories for the overlay.
  305. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  306. if opts != nil && len(opts.StorageOpt) != 0 {
  307. if _, ok := opts.StorageOpt["size"]; ok {
  308. return fmt.Errorf("--storage-opt size is only supported for ReadWrite Layers")
  309. }
  310. }
  311. return d.create(id, parent, opts)
  312. }
  313. func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  314. dir := d.dir(id)
  315. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  316. if err != nil {
  317. return err
  318. }
  319. root := idtools.IDPair{UID: rootUID, GID: rootGID}
  320. if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
  321. return err
  322. }
  323. if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
  324. return err
  325. }
  326. defer func() {
  327. // Clean up on failure
  328. if retErr != nil {
  329. os.RemoveAll(dir)
  330. }
  331. }()
  332. if opts != nil && len(opts.StorageOpt) > 0 {
  333. driver := &Driver{}
  334. if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil {
  335. return err
  336. }
  337. if driver.options.quota.Size > 0 {
  338. // Set container disk quota limit
  339. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  340. return err
  341. }
  342. }
  343. }
  344. if err := idtools.MkdirAndChown(path.Join(dir, "diff"), 0755, root); err != nil {
  345. return err
  346. }
  347. lid := generateID(idLength)
  348. if err := os.Symlink(path.Join("..", id, "diff"), path.Join(d.home, linkDir, lid)); err != nil {
  349. return err
  350. }
  351. // Write link id to link file
  352. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  353. return err
  354. }
  355. // if no parent directory, done
  356. if parent == "" {
  357. return nil
  358. }
  359. if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
  360. return err
  361. }
  362. lower, err := d.getLower(parent)
  363. if err != nil {
  364. return err
  365. }
  366. if lower != "" {
  367. if err := ioutil.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
  368. return err
  369. }
  370. }
  371. return nil
  372. }
  373. // Parse overlay storage options
  374. func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error {
  375. // Read size to set the disk project quota per container
  376. for key, val := range storageOpt {
  377. key := strings.ToLower(key)
  378. switch key {
  379. case "size":
  380. size, err := units.RAMInBytes(val)
  381. if err != nil {
  382. return err
  383. }
  384. driver.options.quota.Size = uint64(size)
  385. default:
  386. return fmt.Errorf("Unknown option %s", key)
  387. }
  388. }
  389. return nil
  390. }
  391. func (d *Driver) getLower(parent string) (string, error) {
  392. parentDir := d.dir(parent)
  393. // Ensure parent exists
  394. if _, err := os.Lstat(parentDir); err != nil {
  395. return "", err
  396. }
  397. // Read Parent link fileA
  398. parentLink, err := ioutil.ReadFile(path.Join(parentDir, "link"))
  399. if err != nil {
  400. return "", err
  401. }
  402. lowers := []string{path.Join(linkDir, string(parentLink))}
  403. parentLower, err := ioutil.ReadFile(path.Join(parentDir, lowerFile))
  404. if err == nil {
  405. parentLowers := strings.Split(string(parentLower), ":")
  406. lowers = append(lowers, parentLowers...)
  407. }
  408. if len(lowers) > maxDepth {
  409. return "", errors.New("max depth exceeded")
  410. }
  411. return strings.Join(lowers, ":"), nil
  412. }
  413. func (d *Driver) dir(id string) string {
  414. return path.Join(d.home, id)
  415. }
  416. func (d *Driver) getLowerDirs(id string) ([]string, error) {
  417. var lowersArray []string
  418. lowers, err := ioutil.ReadFile(path.Join(d.dir(id), lowerFile))
  419. if err == nil {
  420. for _, s := range strings.Split(string(lowers), ":") {
  421. lp, err := os.Readlink(path.Join(d.home, s))
  422. if err != nil {
  423. return nil, err
  424. }
  425. lowersArray = append(lowersArray, path.Clean(path.Join(d.home, linkDir, lp)))
  426. }
  427. } else if !os.IsNotExist(err) {
  428. return nil, err
  429. }
  430. return lowersArray, nil
  431. }
  432. // Remove cleans the directories that are created for this id.
  433. func (d *Driver) Remove(id string) error {
  434. d.locker.Lock(id)
  435. defer d.locker.Unlock(id)
  436. dir := d.dir(id)
  437. lid, err := ioutil.ReadFile(path.Join(dir, "link"))
  438. if err == nil {
  439. if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil {
  440. logrus.Debugf("Failed to remove link: %v", err)
  441. }
  442. }
  443. if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
  444. return err
  445. }
  446. return nil
  447. }
  448. // Get creates and mounts the required file system for the given id and returns the mount path.
  449. func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr error) {
  450. d.locker.Lock(id)
  451. defer d.locker.Unlock(id)
  452. dir := d.dir(id)
  453. if _, err := os.Stat(dir); err != nil {
  454. return nil, err
  455. }
  456. diffDir := path.Join(dir, "diff")
  457. lowers, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  458. if err != nil {
  459. // If no lower, just return diff directory
  460. if os.IsNotExist(err) {
  461. return containerfs.NewLocalContainerFS(diffDir), nil
  462. }
  463. return nil, err
  464. }
  465. mergedDir := path.Join(dir, "merged")
  466. if count := d.ctr.Increment(mergedDir); count > 1 {
  467. return containerfs.NewLocalContainerFS(mergedDir), nil
  468. }
  469. defer func() {
  470. if retErr != nil {
  471. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  472. if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
  473. logrus.Errorf("error unmounting %v: %v", mergedDir, mntErr)
  474. }
  475. // Cleanup the created merged directory; see the comment in Put's rmdir
  476. if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
  477. logrus.Debugf("Failed to remove %s: %v: %v", id, rmErr, err)
  478. }
  479. }
  480. }
  481. }()
  482. workDir := path.Join(dir, "work")
  483. splitLowers := strings.Split(string(lowers), ":")
  484. absLowers := make([]string, len(splitLowers))
  485. for i, s := range splitLowers {
  486. absLowers[i] = path.Join(d.home, s)
  487. }
  488. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(absLowers, ":"), path.Join(dir, "diff"), path.Join(dir, "work"))
  489. mountData := label.FormatMountLabel(opts, mountLabel)
  490. mount := unix.Mount
  491. mountTarget := mergedDir
  492. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  493. if err != nil {
  494. return nil, err
  495. }
  496. if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
  497. return nil, err
  498. }
  499. pageSize := unix.Getpagesize()
  500. // Go can return a larger page size than supported by the system
  501. // as of go 1.7. This will be fixed in 1.8 and this block can be
  502. // removed when building with 1.8.
  503. // See https://github.com/golang/go/commit/1b9499b06989d2831e5b156161d6c07642926ee1
  504. // See https://github.com/docker/docker/issues/27384
  505. if pageSize > 4096 {
  506. pageSize = 4096
  507. }
  508. // Use relative paths and mountFrom when the mount data has exceeded
  509. // the page size. The mount syscall fails if the mount data cannot
  510. // fit within a page and relative links make the mount data much
  511. // smaller at the expense of requiring a fork exec to chroot.
  512. if len(mountData) > pageSize {
  513. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", string(lowers), path.Join(id, "diff"), path.Join(id, "work"))
  514. mountData = label.FormatMountLabel(opts, mountLabel)
  515. if len(mountData) > pageSize {
  516. return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  517. }
  518. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  519. return mountFrom(d.home, source, target, mType, flags, label)
  520. }
  521. mountTarget = path.Join(id, "merged")
  522. }
  523. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  524. return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  525. }
  526. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  527. // user namespace requires this to move a directory from lower to upper.
  528. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  529. return nil, err
  530. }
  531. return containerfs.NewLocalContainerFS(mergedDir), nil
  532. }
  533. // Put unmounts the mount path created for the give id.
  534. // It also removes the 'merged' directory to force the kernel to unmount the
  535. // overlay mount in other namespaces.
  536. func (d *Driver) Put(id string) error {
  537. d.locker.Lock(id)
  538. defer d.locker.Unlock(id)
  539. dir := d.dir(id)
  540. _, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  541. if err != nil {
  542. // If no lower, no mount happened and just return directly
  543. if os.IsNotExist(err) {
  544. return nil
  545. }
  546. return err
  547. }
  548. mountpoint := path.Join(dir, "merged")
  549. if count := d.ctr.Decrement(mountpoint); count > 0 {
  550. return nil
  551. }
  552. if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
  553. logrus.Debugf("Failed to unmount %s overlay: %s - %v", id, mountpoint, err)
  554. }
  555. // Remove the mountpoint here. Removing the mountpoint (in newer kernels)
  556. // will cause all other instances of this mount in other mount namespaces
  557. // to be unmounted. This is necessary to avoid cases where an overlay mount
  558. // that is present in another namespace will cause subsequent mounts
  559. // operations to fail with ebusy. We ignore any errors here because this may
  560. // fail on older kernels which don't have
  561. // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
  562. if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) {
  563. logrus.Debugf("Failed to remove %s overlay: %v", id, err)
  564. }
  565. return nil
  566. }
  567. // Exists checks to see if the id is already mounted.
  568. func (d *Driver) Exists(id string) bool {
  569. _, err := os.Stat(d.dir(id))
  570. return err == nil
  571. }
  572. // isParent determines whether the given parent is the direct parent of the
  573. // given layer id
  574. func (d *Driver) isParent(id, parent string) bool {
  575. lowers, err := d.getLowerDirs(id)
  576. if err != nil {
  577. return false
  578. }
  579. if parent == "" && len(lowers) > 0 {
  580. return false
  581. }
  582. parentDir := d.dir(parent)
  583. var ld string
  584. if len(lowers) > 0 {
  585. ld = filepath.Dir(lowers[0])
  586. }
  587. if ld == "" && parent == "" {
  588. return true
  589. }
  590. return ld == parentDir
  591. }
  592. // ApplyDiff applies the new layer into a root
  593. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  594. if !d.isParent(id, parent) {
  595. return d.naiveDiff.ApplyDiff(id, parent, diff)
  596. }
  597. applyDir := d.getDiffPath(id)
  598. logrus.Debugf("Applying tar in %s", applyDir)
  599. // Overlay doesn't need the parent id to apply the diff
  600. if err := untar(diff, applyDir, &archive.TarOptions{
  601. UIDMaps: d.uidMaps,
  602. GIDMaps: d.gidMaps,
  603. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  604. }); err != nil {
  605. return 0, err
  606. }
  607. return directory.Size(applyDir)
  608. }
  609. func (d *Driver) getDiffPath(id string) string {
  610. dir := d.dir(id)
  611. return path.Join(dir, "diff")
  612. }
  613. // DiffSize calculates the changes between the specified id
  614. // and its parent and returns the size in bytes of the changes
  615. // relative to its base filesystem directory.
  616. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  617. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  618. return d.naiveDiff.DiffSize(id, parent)
  619. }
  620. return directory.Size(d.getDiffPath(id))
  621. }
  622. // Diff produces an archive of the changes between the specified
  623. // layer and its parent layer which may be "".
  624. func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) {
  625. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  626. return d.naiveDiff.Diff(id, parent)
  627. }
  628. diffPath := d.getDiffPath(id)
  629. logrus.Debugf("Tar with options on %s", diffPath)
  630. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  631. Compression: archive.Uncompressed,
  632. UIDMaps: d.uidMaps,
  633. GIDMaps: d.gidMaps,
  634. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  635. })
  636. }
  637. // Changes produces a list of changes between the specified layer and its
  638. // parent layer. If parent is "", then all changes will be ADD changes.
  639. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  640. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  641. return d.naiveDiff.Changes(id, parent)
  642. }
  643. // Overlay doesn't have snapshots, so we need to get changes from all parent
  644. // layers.
  645. diffPath := d.getDiffPath(id)
  646. layers, err := d.getLowerDirs(id)
  647. if err != nil {
  648. return nil, err
  649. }
  650. return archive.OverlayChanges(layers, diffPath)
  651. }