overlay.go 22 KB

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