github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/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.override_kernel_check": 238 // TODO(thaJeztah): change this to an error, see https://github.com/docker/cli/pull/3806 239 logger.Warn("DEPRECATED: the overlay2.override_kernel_check option is ignored and will be removed in the next release. You can safely remove this option from your configuration.") 240 case "overlay2.size": 241 size, err := units.RAMInBytes(val) 242 if err != nil { 243 return nil, err 244 } 245 o.quota.Size = uint64(size) 246 default: 247 return nil, fmt.Errorf("overlay2: unknown option %s", key) 248 } 249 } 250 return o, nil 251 } 252 253 func useNaiveDiff(home string) bool { 254 useNaiveDiffLock.Do(func() { 255 if err := doesSupportNativeDiff(home); err != nil { 256 logger.Warnf("Not using native diff for overlay2, this may cause degraded performance for building images: %v", err) 257 useNaiveDiffOnly = true 258 } 259 }) 260 return useNaiveDiffOnly 261 } 262 263 func (d *Driver) String() string { 264 return driverName 265 } 266 267 // Status returns current driver information in a two dimensional string array. 268 // Output contains "Backing Filesystem" used in this implementation. 269 func (d *Driver) Status() [][2]string { 270 return [][2]string{ 271 {"Backing Filesystem", backingFs}, 272 {"Supports d_type", strconv.FormatBool(d.supportsDType)}, 273 {"Using metacopy", strconv.FormatBool(d.usingMetacopy)}, 274 {"Native Overlay Diff", strconv.FormatBool(!useNaiveDiff(d.home))}, 275 {"userxattr", strconv.FormatBool(userxattr != "")}, 276 } 277 } 278 279 // GetMetadata returns metadata about the overlay driver such as the LowerDir, 280 // UpperDir, WorkDir, and MergeDir used to store data. 281 func (d *Driver) GetMetadata(id string) (map[string]string, error) { 282 dir := d.dir(id) 283 if _, err := os.Stat(dir); err != nil { 284 return nil, err 285 } 286 287 metadata := map[string]string{ 288 "WorkDir": path.Join(dir, workDirName), 289 "MergedDir": path.Join(dir, mergedDirName), 290 "UpperDir": path.Join(dir, diffDirName), 291 } 292 293 lowerDirs, err := d.getLowerDirs(id) 294 if err != nil { 295 return nil, err 296 } 297 if len(lowerDirs) > 0 { 298 metadata["LowerDir"] = strings.Join(lowerDirs, ":") 299 } 300 301 return metadata, nil 302 } 303 304 // Cleanup any state created by overlay which should be cleaned when daemon 305 // is being shutdown. For now, we just have to unmount the bind mounted 306 // we had created. 307 func (d *Driver) Cleanup() error { 308 return mount.RecursiveUnmount(d.home) 309 } 310 311 // CreateReadWrite creates a layer that is writable for use as a container 312 // file system. 313 func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error { 314 if opts == nil { 315 opts = &graphdriver.CreateOpts{ 316 StorageOpt: make(map[string]string), 317 } 318 } else if opts.StorageOpt == nil { 319 opts.StorageOpt = make(map[string]string) 320 } 321 322 // Merge daemon default config. 323 if _, ok := opts.StorageOpt["size"]; !ok && d.options.quota.Size != 0 { 324 opts.StorageOpt["size"] = strconv.FormatUint(d.options.quota.Size, 10) 325 } 326 327 if _, ok := opts.StorageOpt["size"]; ok && !projectQuotaSupported { 328 return fmt.Errorf("--storage-opt is supported only for overlay over xfs with 'pquota' mount option") 329 } 330 331 return d.create(id, parent, opts) 332 } 333 334 // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id. 335 // The parent filesystem is used to configure these directories for the overlay. 336 func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) { 337 if opts != nil && len(opts.StorageOpt) != 0 { 338 if _, ok := opts.StorageOpt["size"]; ok { 339 return fmt.Errorf("--storage-opt size is only supported for ReadWrite Layers") 340 } 341 } 342 return d.create(id, parent, opts) 343 } 344 345 func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) { 346 dir := d.dir(id) 347 348 root := d.idMap.RootPair() 349 dirID := idtools.Identity{ 350 UID: idtools.CurrentIdentity().UID, 351 GID: root.GID, 352 } 353 354 if err := idtools.MkdirAllAndChown(path.Dir(dir), 0710, dirID); err != nil { 355 return err 356 } 357 if err := idtools.MkdirAndChown(dir, 0710, dirID); err != nil { 358 return err 359 } 360 361 defer func() { 362 // Clean up on failure 363 if retErr != nil { 364 os.RemoveAll(dir) 365 } 366 }() 367 368 if opts != nil && len(opts.StorageOpt) > 0 { 369 driver := &Driver{} 370 if err := d.parseStorageOpt(opts.StorageOpt, driver); err != nil { 371 return err 372 } 373 374 if driver.options.quota.Size > 0 { 375 // Set container disk quota limit 376 if err := d.quotaCtl.SetQuota(dir, driver.options.quota); err != nil { 377 return err 378 } 379 } 380 } 381 382 if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0755, root); err != nil { 383 return err 384 } 385 386 lid := overlayutils.GenerateID(idLength, logger) 387 if err := os.Symlink(path.Join("..", id, diffDirName), path.Join(d.home, linkDir, lid)); err != nil { 388 return err 389 } 390 391 // Write link id to link file 392 if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil { 393 return err 394 } 395 396 // if no parent directory, done 397 if parent == "" { 398 return nil 399 } 400 401 if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0700, root); err != nil { 402 return err 403 } 404 405 if err := os.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0600); err != nil { 406 return err 407 } 408 409 lower, err := d.getLower(parent) 410 if err != nil { 411 return err 412 } 413 if lower != "" { 414 if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil { 415 return err 416 } 417 } 418 419 return nil 420 } 421 422 // Parse overlay storage options 423 func (d *Driver) parseStorageOpt(storageOpt map[string]string, driver *Driver) error { 424 // Read size to set the disk project quota per container 425 for key, val := range storageOpt { 426 key := strings.ToLower(key) 427 switch key { 428 case "size": 429 size, err := units.RAMInBytes(val) 430 if err != nil { 431 return err 432 } 433 driver.options.quota.Size = uint64(size) 434 default: 435 return fmt.Errorf("Unknown option %s", key) 436 } 437 } 438 439 return nil 440 } 441 442 func (d *Driver) getLower(parent string) (string, error) { 443 parentDir := d.dir(parent) 444 445 // Ensure parent exists 446 if _, err := os.Lstat(parentDir); err != nil { 447 return "", err 448 } 449 450 // Read Parent link fileA 451 parentLink, err := os.ReadFile(path.Join(parentDir, "link")) 452 if err != nil { 453 return "", err 454 } 455 lowers := []string{path.Join(linkDir, string(parentLink))} 456 457 parentLower, err := os.ReadFile(path.Join(parentDir, lowerFile)) 458 if err == nil { 459 parentLowers := strings.Split(string(parentLower), ":") 460 lowers = append(lowers, parentLowers...) 461 } 462 if len(lowers) > maxDepth { 463 return "", errors.New("max depth exceeded") 464 } 465 return strings.Join(lowers, ":"), nil 466 } 467 468 func (d *Driver) dir(id string) string { 469 return path.Join(d.home, id) 470 } 471 472 func (d *Driver) getLowerDirs(id string) ([]string, error) { 473 var lowersArray []string 474 lowers, err := os.ReadFile(path.Join(d.dir(id), lowerFile)) 475 if err == nil { 476 for _, s := range strings.Split(string(lowers), ":") { 477 lp, err := os.Readlink(path.Join(d.home, s)) 478 if err != nil { 479 return nil, err 480 } 481 lowersArray = append(lowersArray, path.Clean(path.Join(d.home, linkDir, lp))) 482 } 483 } else if !os.IsNotExist(err) { 484 return nil, err 485 } 486 return lowersArray, nil 487 } 488 489 // Remove cleans the directories that are created for this id. 490 func (d *Driver) Remove(id string) error { 491 if id == "" { 492 return fmt.Errorf("refusing to remove the directories: id is empty") 493 } 494 d.locker.Lock(id) 495 defer d.locker.Unlock(id) 496 dir := d.dir(id) 497 lid, err := os.ReadFile(path.Join(dir, "link")) 498 if err == nil { 499 if len(lid) == 0 { 500 logger.Errorf("refusing to remove empty link for layer %v", id) 501 } else if err := os.RemoveAll(path.Join(d.home, linkDir, string(lid))); err != nil { 502 logger.Debugf("Failed to remove link: %v", err) 503 } 504 } 505 506 if err := containerfs.EnsureRemoveAll(dir); err != nil && !os.IsNotExist(err) { 507 return err 508 } 509 return nil 510 } 511 512 // Get creates and mounts the required file system for the given id and returns the mount path. 513 func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) { 514 d.locker.Lock(id) 515 defer d.locker.Unlock(id) 516 dir := d.dir(id) 517 if _, err := os.Stat(dir); err != nil { 518 return "", err 519 } 520 521 diffDir := path.Join(dir, diffDirName) 522 lowers, err := os.ReadFile(path.Join(dir, lowerFile)) 523 if err != nil { 524 // If no lower, just return diff directory 525 if os.IsNotExist(err) { 526 return diffDir, nil 527 } 528 return "", err 529 } 530 531 mergedDir := path.Join(dir, mergedDirName) 532 if count := d.ctr.Increment(mergedDir); count > 1 { 533 return mergedDir, nil 534 } 535 defer func() { 536 if retErr != nil { 537 if c := d.ctr.Decrement(mergedDir); c <= 0 { 538 if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil { 539 logger.Errorf("error unmounting %v: %v", mergedDir, mntErr) 540 } 541 // Cleanup the created merged directory; see the comment in Put's rmdir 542 if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) { 543 logger.Debugf("Failed to remove %s: %v: %v", id, rmErr, err) 544 } 545 } 546 } 547 }() 548 549 workDir := path.Join(dir, workDirName) 550 splitLowers := strings.Split(string(lowers), ":") 551 absLowers := make([]string, len(splitLowers)) 552 for i, s := range splitLowers { 553 absLowers[i] = path.Join(d.home, s) 554 } 555 var readonly bool 556 if _, err := os.Stat(path.Join(dir, "committed")); err == nil { 557 readonly = true 558 } else if !os.IsNotExist(err) { 559 return "", err 560 } 561 562 var opts string 563 if readonly { 564 opts = indexOff + userxattr + "lowerdir=" + diffDir + ":" + strings.Join(absLowers, ":") 565 } else { 566 opts = indexOff + userxattr + "lowerdir=" + strings.Join(absLowers, ":") + ",upperdir=" + diffDir + ",workdir=" + workDir 567 } 568 569 mountData := label.FormatMountLabel(opts, mountLabel) 570 mount := unix.Mount 571 mountTarget := mergedDir 572 573 root := d.idMap.RootPair() 574 if err := idtools.MkdirAndChown(mergedDir, 0700, root); err != nil { 575 return "", err 576 } 577 578 pageSize := unix.Getpagesize() 579 580 // Use relative paths and mountFrom when the mount data has exceeded 581 // the page size. The mount syscall fails if the mount data cannot 582 // fit within a page and relative links make the mount data much 583 // smaller at the expense of requiring a fork exec to chroot. 584 if len(mountData) > pageSize-1 { 585 if readonly { 586 opts = indexOff + userxattr + "lowerdir=" + path.Join(id, diffDirName) + ":" + string(lowers) 587 } else { 588 opts = indexOff + userxattr + "lowerdir=" + string(lowers) + ",upperdir=" + path.Join(id, diffDirName) + ",workdir=" + path.Join(id, workDirName) 589 } 590 mountData = label.FormatMountLabel(opts, mountLabel) 591 if len(mountData) > pageSize-1 { 592 return "", fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData)) 593 } 594 595 mount = func(source string, target string, mType string, flags uintptr, label string) error { 596 return mountFrom(d.home, source, target, mType, flags, label) 597 } 598 mountTarget = path.Join(id, mergedDirName) 599 } 600 601 if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil { 602 return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) 603 } 604 605 if !readonly { 606 // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a 607 // user namespace requires this to move a directory from lower to upper. 608 if err := root.Chown(path.Join(workDir, workDirName)); err != nil { 609 return "", err 610 } 611 } 612 613 return mergedDir, nil 614 } 615 616 // Put unmounts the mount path created for the give id. 617 // It also removes the 'merged' directory to force the kernel to unmount the 618 // overlay mount in other namespaces. 619 func (d *Driver) Put(id string) error { 620 d.locker.Lock(id) 621 defer d.locker.Unlock(id) 622 dir := d.dir(id) 623 _, err := os.ReadFile(path.Join(dir, lowerFile)) 624 if err != nil { 625 // If no lower, no mount happened and just return directly 626 if os.IsNotExist(err) { 627 return nil 628 } 629 return err 630 } 631 632 mountpoint := path.Join(dir, mergedDirName) 633 if count := d.ctr.Decrement(mountpoint); count > 0 { 634 return nil 635 } 636 if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil { 637 logger.Debugf("Failed to unmount %s overlay: %s - %v", id, mountpoint, err) 638 } 639 // Remove the mountpoint here. Removing the mountpoint (in newer kernels) 640 // will cause all other instances of this mount in other mount namespaces 641 // to be unmounted. This is necessary to avoid cases where an overlay mount 642 // that is present in another namespace will cause subsequent mounts 643 // operations to fail with ebusy. We ignore any errors here because this may 644 // fail on older kernels which don't have 645 // torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied. 646 if err := unix.Rmdir(mountpoint); err != nil && !os.IsNotExist(err) { 647 logger.Debugf("Failed to remove %s overlay: %v", id, err) 648 } 649 return nil 650 } 651 652 // Exists checks to see if the id is already mounted. 653 func (d *Driver) Exists(id string) bool { 654 _, err := os.Stat(d.dir(id)) 655 return err == nil 656 } 657 658 // isParent determines whether the given parent is the direct parent of the 659 // given layer id 660 func (d *Driver) isParent(id, parent string) bool { 661 lowers, err := d.getLowerDirs(id) 662 if err != nil { 663 return false 664 } 665 if parent == "" && len(lowers) > 0 { 666 return false 667 } 668 669 parentDir := d.dir(parent) 670 var ld string 671 if len(lowers) > 0 { 672 ld = filepath.Dir(lowers[0]) 673 } 674 if ld == "" && parent == "" { 675 return true 676 } 677 return ld == parentDir 678 } 679 680 // ApplyDiff applies the new layer into a root 681 func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) { 682 if useNaiveDiff(d.home) || !d.isParent(id, parent) { 683 return d.naiveDiff.ApplyDiff(id, parent, diff) 684 } 685 686 // never reach here if we are running in UserNS 687 applyDir := d.getDiffPath(id) 688 689 logger.Debugf("Applying tar in %s", applyDir) 690 // Overlay doesn't need the parent id to apply the diff 691 if err := untar(diff, applyDir, &archive.TarOptions{ 692 IDMap: d.idMap, 693 WhiteoutFormat: archive.OverlayWhiteoutFormat, 694 }); err != nil { 695 return 0, err 696 } 697 698 return directory.Size(context.TODO(), applyDir) 699 } 700 701 func (d *Driver) getDiffPath(id string) string { 702 dir := d.dir(id) 703 704 return path.Join(dir, diffDirName) 705 } 706 707 // DiffSize calculates the changes between the specified id 708 // and its parent and returns the size in bytes of the changes 709 // relative to its base filesystem directory. 710 func (d *Driver) DiffSize(id, parent string) (size int64, err error) { 711 if useNaiveDiff(d.home) || !d.isParent(id, parent) { 712 return d.naiveDiff.DiffSize(id, parent) 713 } 714 return directory.Size(context.TODO(), d.getDiffPath(id)) 715 } 716 717 // Diff produces an archive of the changes between the specified 718 // layer and its parent layer which may be "". 719 func (d *Driver) Diff(id, parent string) (io.ReadCloser, error) { 720 if useNaiveDiff(d.home) || !d.isParent(id, parent) { 721 return d.naiveDiff.Diff(id, parent) 722 } 723 724 // never reach here if we are running in UserNS 725 diffPath := d.getDiffPath(id) 726 logger.Debugf("Tar with options on %s", diffPath) 727 return archive.TarWithOptions(diffPath, &archive.TarOptions{ 728 Compression: archive.Uncompressed, 729 IDMap: d.idMap, 730 WhiteoutFormat: archive.OverlayWhiteoutFormat, 731 }) 732 } 733 734 // Changes produces a list of changes between the specified layer and its 735 // parent layer. If parent is "", then all changes will be ADD changes. 736 func (d *Driver) Changes(id, parent string) ([]archive.Change, error) { 737 return d.naiveDiff.Changes(id, parent) 738 }