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