overlay.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. // +build linux
  2. package overlay2
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "github.com/Sirupsen/logrus"
  18. "github.com/docker/docker/daemon/graphdriver"
  19. "github.com/docker/docker/daemon/graphdriver/overlayutils"
  20. "github.com/docker/docker/daemon/graphdriver/quota"
  21. "github.com/docker/docker/pkg/archive"
  22. "github.com/docker/docker/pkg/chrootarchive"
  23. "github.com/docker/docker/pkg/directory"
  24. "github.com/docker/docker/pkg/fsutils"
  25. "github.com/docker/docker/pkg/idtools"
  26. "github.com/docker/docker/pkg/locker"
  27. "github.com/docker/docker/pkg/mount"
  28. "github.com/docker/docker/pkg/parsers"
  29. "github.com/docker/docker/pkg/parsers/kernel"
  30. "github.com/docker/docker/pkg/system"
  31. units "github.com/docker/go-units"
  32. "github.com/opencontainers/selinux/go-selinux/label"
  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. lowerFile = "lower"
  65. maxDepth = 128
  66. // idLength represents the number of random characters
  67. // which can be used to create the unique link identifer
  68. // for every layer. If this value is too long then the
  69. // page size limit for the mount command may be exceeded.
  70. // The idLength should be selected such that following equation
  71. // is true (512 is a buffer for label metadata).
  72. // ((idLength + len(linkDir) + 1) * maxDepth) <= (pageSize - 512)
  73. idLength = 26
  74. )
  75. type overlayOptions struct {
  76. overrideKernelCheck bool
  77. quota quota.Quota
  78. }
  79. // Driver contains information about the home directory and the list of active mounts that are created using this driver.
  80. type Driver struct {
  81. home string
  82. uidMaps []idtools.IDMap
  83. gidMaps []idtools.IDMap
  84. ctr *graphdriver.RefCounter
  85. quotaCtl *quota.Control
  86. options overlayOptions
  87. naiveDiff graphdriver.DiffDriver
  88. supportsDType bool
  89. locker *locker.Locker
  90. }
  91. var (
  92. backingFs = "<unknown>"
  93. projectQuotaSupported = false
  94. useNaiveDiffLock sync.Once
  95. useNaiveDiffOnly bool
  96. )
  97. func init() {
  98. graphdriver.Register(driverName, Init)
  99. }
  100. // Init returns the a native diff driver for overlay filesystem.
  101. // If overlay filesystem is not supported on the host, graphdriver.ErrNotSupported is returned as error.
  102. // If an overlay filesystem is not supported over an existing filesystem then error graphdriver.ErrIncompatibleFS is returned.
  103. func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
  104. opts, err := parseOptions(options)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if err := supportsOverlay(); err != nil {
  109. return nil, graphdriver.ErrNotSupported
  110. }
  111. // require kernel 4.0.0 to ensure multiple lower dirs are supported
  112. v, err := kernel.GetKernelVersion()
  113. if err != nil {
  114. return nil, err
  115. }
  116. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 {
  117. if !opts.overrideKernelCheck {
  118. return nil, graphdriver.ErrNotSupported
  119. }
  120. logrus.Warn("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update")
  121. }
  122. fsMagic, err := graphdriver.GetFSMagic(home)
  123. if err != nil {
  124. return nil, err
  125. }
  126. if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
  127. backingFs = fsName
  128. }
  129. // check if they are running over btrfs, aufs, zfs, overlay, or ecryptfs
  130. switch fsMagic {
  131. case graphdriver.FsMagicAufs, graphdriver.FsMagicZfs, graphdriver.FsMagicOverlay, graphdriver.FsMagicEcryptfs:
  132. logrus.Errorf("'overlay2' is not supported over %s", backingFs)
  133. return nil, graphdriver.ErrIncompatibleFS
  134. case graphdriver.FsMagicBtrfs:
  135. // Support for OverlayFS on BTRFS was added in kernel 4.7
  136. // See https://btrfs.wiki.kernel.org/index.php/Changelog
  137. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 7, Minor: 0}) < 0 {
  138. if !opts.overrideKernelCheck {
  139. logrus.Errorf("'overlay2' requires kernel 4.7 to use on %s", backingFs)
  140. return nil, graphdriver.ErrIncompatibleFS
  141. }
  142. logrus.Warn("Using pre-4.7.0 kernel for overlay2 on btrfs, may require kernel update")
  143. }
  144. }
  145. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  146. if err != nil {
  147. return nil, err
  148. }
  149. // Create the driver home dir
  150. if err := idtools.MkdirAllAs(path.Join(home, linkDir), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  151. return nil, err
  152. }
  153. if err := mount.MakePrivate(home); err != nil {
  154. return nil, err
  155. }
  156. supportsDType, err := fsutils.SupportsDType(home)
  157. if err != nil {
  158. return nil, err
  159. }
  160. if !supportsDType {
  161. // not a fatal error until v17.12 (#27443)
  162. logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay2", backingFs))
  163. }
  164. d := &Driver{
  165. home: home,
  166. uidMaps: uidMaps,
  167. gidMaps: gidMaps,
  168. ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
  169. supportsDType: supportsDType,
  170. locker: locker.New(),
  171. }
  172. d.naiveDiff = graphdriver.NewNaiveDiffDriver(d, uidMaps, gidMaps)
  173. if backingFs == "xfs" {
  174. // Try to enable project quota support over xfs.
  175. if d.quotaCtl, err = quota.NewControl(home); err == nil {
  176. projectQuotaSupported = true
  177. }
  178. }
  179. logrus.Debugf("backingFs=%s, projectQuotaSupported=%v", backingFs, projectQuotaSupported)
  180. return d, nil
  181. }
  182. func parseOptions(options []string) (*overlayOptions, error) {
  183. o := &overlayOptions{}
  184. for _, option := range options {
  185. key, val, err := parsers.ParseKeyValueOpt(option)
  186. if err != nil {
  187. return nil, err
  188. }
  189. key = strings.ToLower(key)
  190. switch key {
  191. case "overlay2.override_kernel_check":
  192. o.overrideKernelCheck, err = strconv.ParseBool(val)
  193. if err != nil {
  194. return nil, err
  195. }
  196. default:
  197. return nil, fmt.Errorf("overlay2: Unknown option %s\n", key)
  198. }
  199. }
  200. return o, nil
  201. }
  202. func supportsOverlay() error {
  203. // We can try to modprobe overlay first before looking at
  204. // proc/filesystems for when overlay is supported
  205. exec.Command("modprobe", "overlay").Run()
  206. f, err := os.Open("/proc/filesystems")
  207. if err != nil {
  208. return err
  209. }
  210. defer f.Close()
  211. s := bufio.NewScanner(f)
  212. for s.Scan() {
  213. if s.Text() == "nodev\toverlay" {
  214. return nil
  215. }
  216. }
  217. logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
  218. return graphdriver.ErrNotSupported
  219. }
  220. func useNaiveDiff(home string) bool {
  221. useNaiveDiffLock.Do(func() {
  222. if err := hasOpaqueCopyUpBug(home); err != nil {
  223. logrus.Warnf("Not using native diff for overlay2: %v", err)
  224. useNaiveDiffOnly = true
  225. }
  226. })
  227. return useNaiveDiffOnly
  228. }
  229. func (d *Driver) String() string {
  230. return driverName
  231. }
  232. // Status returns current driver information in a two dimensional string array.
  233. // Output contains "Backing Filesystem" used in this implementation.
  234. func (d *Driver) Status() [][2]string {
  235. return [][2]string{
  236. {"Backing Filesystem", backingFs},
  237. {"Supports d_type", strconv.FormatBool(d.supportsDType)},
  238. {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))},
  239. }
  240. }
  241. // GetMetadata returns meta data about the overlay driver such as
  242. // LowerDir, UpperDir, WorkDir and MergeDir used to store data.
  243. func (d *Driver) GetMetadata(id string) (map[string]string, error) {
  244. dir := d.dir(id)
  245. if _, err := os.Stat(dir); err != nil {
  246. return nil, err
  247. }
  248. metadata := map[string]string{
  249. "WorkDir": path.Join(dir, "work"),
  250. "MergedDir": path.Join(dir, "merged"),
  251. "UpperDir": path.Join(dir, "diff"),
  252. }
  253. lowerDirs, err := d.getLowerDirs(id)
  254. if err != nil {
  255. return nil, err
  256. }
  257. if len(lowerDirs) > 0 {
  258. metadata["LowerDir"] = strings.Join(lowerDirs, ":")
  259. }
  260. return metadata, nil
  261. }
  262. // Cleanup any state created by overlay which should be cleaned when daemon
  263. // is being shutdown. For now, we just have to unmount the bind mounted
  264. // we had created.
  265. func (d *Driver) Cleanup() error {
  266. return mount.Unmount(d.home)
  267. }
  268. // CreateReadWrite creates a layer that is writable for use as a container
  269. // file system.
  270. func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
  271. return d.Create(id, parent, opts)
  272. }
  273. // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
  274. // The parent filesystem is used to configure these directories for the overlay.
  275. func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
  276. if opts != nil && len(opts.StorageOpt) != 0 && !projectQuotaSupported {
  277. return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option")
  278. }
  279. dir := d.dir(id)
  280. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  281. if err != nil {
  282. return err
  283. }
  284. if err := idtools.MkdirAllAs(path.Dir(dir), 0700, rootUID, rootGID); err != nil {
  285. return err
  286. }
  287. if err := idtools.MkdirAs(dir, 0700, rootUID, rootGID); err != nil {
  288. return err
  289. }
  290. defer func() {
  291. // Clean up on failure
  292. if retErr != nil {
  293. os.RemoveAll(dir)
  294. }
  295. }()
  296. if opts != nil && len(opts.StorageOpt) > 0 {
  297. driver := &Driver{}
  298. if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil {
  299. return err
  300. }
  301. if driver.options.quota.Size > 0 {
  302. // Set container disk quota limit
  303. if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil {
  304. return err
  305. }
  306. }
  307. }
  308. if err := idtools.MkdirAs(path.Join(dir, "diff"), 0755, rootUID, rootGID); err != nil {
  309. return err
  310. }
  311. lid := generateID(idLength)
  312. if err := os.Symlink(path.Join("..", id, "diff"), path.Join(d.home, linkDir, lid)); err != nil {
  313. return err
  314. }
  315. // Write link id to link file
  316. if err := ioutil.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
  317. return err
  318. }
  319. // if no parent directory, done
  320. if parent == "" {
  321. return nil
  322. }
  323. if err := idtools.MkdirAs(path.Join(dir, "work"), 0700, rootUID, rootGID); err != nil {
  324. return err
  325. }
  326. if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); err != nil {
  327. return err
  328. }
  329. lower, err := d.getLower(parent)
  330. if err != nil {
  331. return err
  332. }
  333. if lower != "" {
  334. if err := ioutil.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
  335. return err
  336. }
  337. }
  338. return nil
  339. }
  340. // Parse overlay storage options
  341. func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error {
  342. // Read size to set the disk project quota per container
  343. for key, val := range storageOpt {
  344. key := strings.ToLower(key)
  345. switch key {
  346. case "size":
  347. size, err := units.RAMInBytes(val)
  348. if err != nil {
  349. return err
  350. }
  351. driver.options.quota.Size = uint64(size)
  352. default:
  353. return fmt.Errorf("Unknown option %s", key)
  354. }
  355. }
  356. return nil
  357. }
  358. func (d *Driver) getLower(parent string) (string, error) {
  359. parentDir := d.dir(parent)
  360. // Ensure parent exists
  361. if _, err := os.Lstat(parentDir); err != nil {
  362. return "", err
  363. }
  364. // Read Parent link fileA
  365. parentLink, err := ioutil.ReadFile(path.Join(parentDir, "link"))
  366. if err != nil {
  367. return "", err
  368. }
  369. lowers := []string{path.Join(linkDir, string(parentLink))}
  370. parentLower, err := ioutil.ReadFile(path.Join(parentDir, lowerFile))
  371. if err == nil {
  372. parentLowers := strings.Split(string(parentLower), ":")
  373. lowers = append(lowers, parentLowers...)
  374. }
  375. if len(lowers) > maxDepth {
  376. return "", errors.New("max depth exceeded")
  377. }
  378. return strings.Join(lowers, ":"), nil
  379. }
  380. func (d *Driver) dir(id string) string {
  381. return path.Join(d.home, id)
  382. }
  383. func (d *Driver) getLowerDirs(id string) ([]string, error) {
  384. var lowersArray []string
  385. lowers, err := ioutil.ReadFile(path.Join(d.dir(id), lowerFile))
  386. if err == nil {
  387. for _, s := range strings.Split(string(lowers), ":") {
  388. lp, err := os.Readlink(path.Join(d.home, s))
  389. if err != nil {
  390. return nil, err
  391. }
  392. lowersArray = append(lowersArray, path.Clean(path.Join(d.home, linkDir, lp)))
  393. }
  394. } else if !os.IsNotExist(err) {
  395. return nil, err
  396. }
  397. return lowersArray, nil
  398. }
  399. // Remove cleans the directories that are created for this id.
  400. func (d *Driver) Remove(id string) error {
  401. d.locker.Lock(id)
  402. defer d.locker.Unlock(id)
  403. dir := d.dir(id)
  404. lid, err := ioutil.ReadFile(path.Join(dir, "link"))
  405. if err == nil {
  406. if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil {
  407. logrus.Debugf("Failed to remove link: %v", err)
  408. }
  409. }
  410. if err := system.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) {
  411. return err
  412. }
  413. return nil
  414. }
  415. // Get creates and mounts the required file system for the given id and returns the mount path.
  416. func (d *Driver) Get(id string, mountLabel string) (s string, err error) {
  417. d.locker.Lock(id)
  418. defer d.locker.Unlock(id)
  419. dir := d.dir(id)
  420. if _, err := os.Stat(dir); err != nil {
  421. return "", err
  422. }
  423. diffDir := path.Join(dir, "diff")
  424. lowers, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  425. if err != nil {
  426. // If no lower, just return diff directory
  427. if os.IsNotExist(err) {
  428. return diffDir, nil
  429. }
  430. return "", err
  431. }
  432. mergedDir := path.Join(dir, "merged")
  433. if count := d.ctr.Increment(mergedDir); count > 1 {
  434. return mergedDir, nil
  435. }
  436. defer func() {
  437. if err != nil {
  438. if c := d.ctr.Decrement(mergedDir); c <= 0 {
  439. syscall.Unmount(mergedDir, 0)
  440. }
  441. }
  442. }()
  443. workDir := path.Join(dir, "work")
  444. splitLowers := strings.Split(string(lowers), ":")
  445. absLowers := make([]string, len(splitLowers))
  446. for i, s := range splitLowers {
  447. absLowers[i] = path.Join(d.home, s)
  448. }
  449. opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(absLowers, ":"), path.Join(dir, "diff"), path.Join(dir, "work"))
  450. mountData := label.FormatMountLabel(opts, mountLabel)
  451. mount := syscall.Mount
  452. mountTarget := mergedDir
  453. pageSize := syscall.Getpagesize()
  454. // Go can return a larger page size than supported by the system
  455. // as of go 1.7. This will be fixed in 1.8 and this block can be
  456. // removed when building with 1.8.
  457. // See https://github.com/golang/go/commit/1b9499b06989d2831e5b156161d6c07642926ee1
  458. // See https://github.com/docker/docker/issues/27384
  459. if pageSize > 4096 {
  460. pageSize = 4096
  461. }
  462. // Use relative paths and mountFrom when the mount data has exceeded
  463. // the page size. The mount syscall fails if the mount data cannot
  464. // fit within a page and relative links make the mount data much
  465. // smaller at the expense of requiring a fork exec to chroot.
  466. if len(mountData) > pageSize {
  467. opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", string(lowers), path.Join(id, "diff"), path.Join(id, "work"))
  468. mountData = label.FormatMountLabel(opts, mountLabel)
  469. if len(mountData) > pageSize {
  470. return "", fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData))
  471. }
  472. mount = func(source string, target string, mType string, flags uintptr, label string) error {
  473. return mountFrom(d.home, source, target, mType, flags, label)
  474. }
  475. mountTarget = path.Join(id, "merged")
  476. }
  477. if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil {
  478. return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
  479. }
  480. // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
  481. // user namespace requires this to move a directory from lower to upper.
  482. rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
  483. if err != nil {
  484. return "", err
  485. }
  486. if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
  487. return "", err
  488. }
  489. return mergedDir, nil
  490. }
  491. // Put unmounts the mount path created for the give id.
  492. func (d *Driver) Put(id string) error {
  493. d.locker.Lock(id)
  494. defer d.locker.Unlock(id)
  495. dir := d.dir(id)
  496. _, err := ioutil.ReadFile(path.Join(dir, lowerFile))
  497. if err != nil {
  498. // If no lower, no mount happened and just return directly
  499. if os.IsNotExist(err) {
  500. return nil
  501. }
  502. return err
  503. }
  504. mountpoint := path.Join(dir, "merged")
  505. if count := d.ctr.Decrement(mountpoint); count > 0 {
  506. return nil
  507. }
  508. if err := syscall.Unmount(mountpoint, 0); err != nil {
  509. logrus.Debugf("Failed to unmount %s overlay: %s - %v", id, mountpoint, err)
  510. }
  511. return nil
  512. }
  513. // Exists checks to see if the id is already mounted.
  514. func (d *Driver) Exists(id string) bool {
  515. _, err := os.Stat(d.dir(id))
  516. return err == nil
  517. }
  518. // isParent returns if the passed in parent is the direct parent of the passed in layer
  519. func (d *Driver) isParent(id, parent string) bool {
  520. lowers, err := d.getLowerDirs(id)
  521. if err != nil {
  522. return false
  523. }
  524. if parent == "" && len(lowers) > 0 {
  525. return false
  526. }
  527. parentDir := d.dir(parent)
  528. var ld string
  529. if len(lowers) > 0 {
  530. ld = filepath.Dir(lowers[0])
  531. }
  532. if ld == "" && parent == "" {
  533. return true
  534. }
  535. return ld == parentDir
  536. }
  537. // ApplyDiff applies the new layer into a root
  538. func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
  539. if !d.isParent(id, parent) {
  540. return d.naiveDiff.ApplyDiff(id, parent, diff)
  541. }
  542. applyDir := d.getDiffPath(id)
  543. logrus.Debugf("Applying tar in %s", applyDir)
  544. // Overlay doesn't need the parent id to apply the diff
  545. if err := untar(diff, applyDir, &archive.TarOptions{
  546. UIDMaps: d.uidMaps,
  547. GIDMaps: d.gidMaps,
  548. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  549. }); err != nil {
  550. return 0, err
  551. }
  552. return directory.Size(applyDir)
  553. }
  554. func (d *Driver) getDiffPath(id string) string {
  555. dir := d.dir(id)
  556. return path.Join(dir, "diff")
  557. }
  558. // DiffSize calculates the changes between the specified id
  559. // and its parent and returns the size in bytes of the changes
  560. // relative to its base filesystem directory.
  561. func (d *Driver) DiffSize(id, parent string) (size int64, err error) {
  562. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  563. return d.naiveDiff.DiffSize(id, parent)
  564. }
  565. return directory.Size(d.getDiffPath(id))
  566. }
  567. // Diff produces an archive of the changes between the specified
  568. // layer and its parent layer which may be "".
  569. func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) {
  570. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  571. return d.naiveDiff.Diff(id, parent)
  572. }
  573. diffPath := d.getDiffPath(id)
  574. logrus.Debugf("Tar with options on %s", diffPath)
  575. return archive.TarWithOptions(diffPath, &archive.TarOptions{
  576. Compression: archive.Uncompressed,
  577. UIDMaps: d.uidMaps,
  578. GIDMaps: d.gidMaps,
  579. WhiteoutFormat: archive.OverlayWhiteoutFormat,
  580. })
  581. }
  582. // Changes produces a list of changes between the specified layer
  583. // and its parent layer. If parent is "", then all changes will be ADD changes.
  584. func (d *Driver) Changes(id, parent string) ([]archive.Change, error) {
  585. if useNaiveDiff(d.home) || !d.isParent(id, parent) {
  586. return d.naiveDiff.Changes(id, parent)
  587. }
  588. // Overlay doesn't have snapshots, so we need to get changes from all parent
  589. // layers.
  590. diffPath := d.getDiffPath(id)
  591. layers, err := d.getLowerDirs(id)
  592. if err != nil {
  593. return nil, err
  594. }
  595. return archive.OverlayChanges(layers, diffPath)
  596. }