overlay.go 22 KB

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