overlay.go 22 KB

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