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