overlay.go 22 KB

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