overlay.go 22 KB

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