overlay.go 22 KB

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