github.com/shishir-a412ed/docker@v1.3.2-0.20180103180333-fda904911d87/daemon/graphdriver/aufs/aufs.go (about) 1 // +build linux 2 3 /* 4 5 aufs driver directory structure 6 7 . 8 ├── layers // Metadata of layers 9 │ ├── 1 10 │ ├── 2 11 │ └── 3 12 ├── diff // Content of the layer 13 │ ├── 1 // Contains layers that need to be mounted for the id 14 │ ├── 2 15 │ └── 3 16 └── mnt // Mount points for the rw layers to be mounted 17 ├── 1 18 ├── 2 19 └── 3 20 21 */ 22 23 package aufs 24 25 import ( 26 "bufio" 27 "fmt" 28 "io" 29 "io/ioutil" 30 "os" 31 "os/exec" 32 "path" 33 "path/filepath" 34 "strings" 35 "sync" 36 "time" 37 38 "github.com/docker/docker/daemon/graphdriver" 39 "github.com/docker/docker/pkg/archive" 40 "github.com/docker/docker/pkg/chrootarchive" 41 "github.com/docker/docker/pkg/containerfs" 42 "github.com/docker/docker/pkg/directory" 43 "github.com/docker/docker/pkg/idtools" 44 "github.com/docker/docker/pkg/locker" 45 mountpk "github.com/docker/docker/pkg/mount" 46 "github.com/docker/docker/pkg/system" 47 rsystem "github.com/opencontainers/runc/libcontainer/system" 48 "github.com/opencontainers/selinux/go-selinux/label" 49 "github.com/pkg/errors" 50 "github.com/sirupsen/logrus" 51 "github.com/vbatts/tar-split/tar/storage" 52 "golang.org/x/sys/unix" 53 ) 54 55 var ( 56 // ErrAufsNotSupported is returned if aufs is not supported by the host. 57 ErrAufsNotSupported = fmt.Errorf("AUFS was not found in /proc/filesystems") 58 // ErrAufsNested means aufs cannot be used bc we are in a user namespace 59 ErrAufsNested = fmt.Errorf("AUFS cannot be used in non-init user namespace") 60 backingFs = "<unknown>" 61 62 enableDirpermLock sync.Once 63 enableDirperm bool 64 ) 65 66 func init() { 67 graphdriver.Register("aufs", Init) 68 } 69 70 // Driver contains information about the filesystem mounted. 71 type Driver struct { 72 sync.Mutex 73 root string 74 uidMaps []idtools.IDMap 75 gidMaps []idtools.IDMap 76 ctr *graphdriver.RefCounter 77 pathCacheLock sync.Mutex 78 pathCache map[string]string 79 naiveDiff graphdriver.DiffDriver 80 locker *locker.Locker 81 } 82 83 // Init returns a new AUFS driver. 84 // An error is returned if AUFS is not supported. 85 func Init(root string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) { 86 87 // Try to load the aufs kernel module 88 if err := supportsAufs(); err != nil { 89 return nil, graphdriver.ErrNotSupported 90 } 91 92 // Perform feature detection on /var/lib/docker/aufs if it's an existing directory. 93 // This covers situations where /var/lib/docker/aufs is a mount, and on a different 94 // filesystem than /var/lib/docker. 95 // If the path does not exist, fall back to using /var/lib/docker for feature detection. 96 testdir := root 97 if _, err := os.Stat(testdir); os.IsNotExist(err) { 98 testdir = filepath.Dir(testdir) 99 } 100 101 fsMagic, err := graphdriver.GetFSMagic(testdir) 102 if err != nil { 103 return nil, err 104 } 105 if fsName, ok := graphdriver.FsNames[fsMagic]; ok { 106 backingFs = fsName 107 } 108 109 switch fsMagic { 110 case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicEcryptfs: 111 logrus.Errorf("AUFS is not supported over %s", backingFs) 112 return nil, graphdriver.ErrIncompatibleFS 113 } 114 115 paths := []string{ 116 "mnt", 117 "diff", 118 "layers", 119 } 120 121 a := &Driver{ 122 root: root, 123 uidMaps: uidMaps, 124 gidMaps: gidMaps, 125 pathCache: make(map[string]string), 126 ctr: graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicAufs)), 127 locker: locker.New(), 128 } 129 130 rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps) 131 if err != nil { 132 return nil, err 133 } 134 // Create the root aufs driver dir 135 if err := idtools.MkdirAllAndChown(root, 0700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { 136 return nil, err 137 } 138 139 if err := mountpk.MakePrivate(root); err != nil { 140 return nil, err 141 } 142 143 // Populate the dir structure 144 for _, p := range paths { 145 if err := idtools.MkdirAllAndChown(path.Join(root, p), 0700, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { 146 return nil, err 147 } 148 } 149 logger := logrus.WithFields(logrus.Fields{ 150 "module": "graphdriver", 151 "driver": "aufs", 152 }) 153 154 for _, path := range []string{"mnt", "diff"} { 155 p := filepath.Join(root, path) 156 entries, err := ioutil.ReadDir(p) 157 if err != nil { 158 logger.WithError(err).WithField("dir", p).Error("error reading dir entries") 159 continue 160 } 161 for _, entry := range entries { 162 if !entry.IsDir() { 163 continue 164 } 165 if strings.HasSuffix(entry.Name(), "-removing") { 166 logger.WithField("dir", entry.Name()).Debug("Cleaning up stale layer dir") 167 if err := system.EnsureRemoveAll(filepath.Join(p, entry.Name())); err != nil { 168 logger.WithField("dir", entry.Name()).WithError(err).Error("Error removing stale layer dir") 169 } 170 } 171 } 172 } 173 174 a.naiveDiff = graphdriver.NewNaiveDiffDriver(a, uidMaps, gidMaps) 175 return a, nil 176 } 177 178 // Return a nil error if the kernel supports aufs 179 // We cannot modprobe because inside dind modprobe fails 180 // to run 181 func supportsAufs() error { 182 // We can try to modprobe aufs first before looking at 183 // proc/filesystems for when aufs is supported 184 exec.Command("modprobe", "aufs").Run() 185 186 if rsystem.RunningInUserNS() { 187 return ErrAufsNested 188 } 189 190 f, err := os.Open("/proc/filesystems") 191 if err != nil { 192 return err 193 } 194 defer f.Close() 195 196 s := bufio.NewScanner(f) 197 for s.Scan() { 198 if strings.Contains(s.Text(), "aufs") { 199 return nil 200 } 201 } 202 return ErrAufsNotSupported 203 } 204 205 func (a *Driver) rootPath() string { 206 return a.root 207 } 208 209 func (*Driver) String() string { 210 return "aufs" 211 } 212 213 // Status returns current information about the filesystem such as root directory, number of directories mounted, etc. 214 func (a *Driver) Status() [][2]string { 215 ids, _ := loadIds(path.Join(a.rootPath(), "layers")) 216 return [][2]string{ 217 {"Root Dir", a.rootPath()}, 218 {"Backing Filesystem", backingFs}, 219 {"Dirs", fmt.Sprintf("%d", len(ids))}, 220 {"Dirperm1 Supported", fmt.Sprintf("%v", useDirperm())}, 221 } 222 } 223 224 // GetMetadata not implemented 225 func (a *Driver) GetMetadata(id string) (map[string]string, error) { 226 return nil, nil 227 } 228 229 // Exists returns true if the given id is registered with 230 // this driver 231 func (a *Driver) Exists(id string) bool { 232 if _, err := os.Lstat(path.Join(a.rootPath(), "layers", id)); err != nil { 233 return false 234 } 235 return true 236 } 237 238 // CreateReadWrite creates a layer that is writable for use as a container 239 // file system. 240 func (a *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error { 241 return a.Create(id, parent, opts) 242 } 243 244 // Create three folders for each id 245 // mnt, layers, and diff 246 func (a *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { 247 248 if opts != nil && len(opts.StorageOpt) != 0 { 249 return fmt.Errorf("--storage-opt is not supported for aufs") 250 } 251 252 if err := a.createDirsFor(id); err != nil { 253 return err 254 } 255 // Write the layers metadata 256 f, err := os.Create(path.Join(a.rootPath(), "layers", id)) 257 if err != nil { 258 return err 259 } 260 defer f.Close() 261 262 if parent != "" { 263 ids, err := getParentIDs(a.rootPath(), parent) 264 if err != nil { 265 return err 266 } 267 268 if _, err := fmt.Fprintln(f, parent); err != nil { 269 return err 270 } 271 for _, i := range ids { 272 if _, err := fmt.Fprintln(f, i); err != nil { 273 return err 274 } 275 } 276 } 277 278 return nil 279 } 280 281 // createDirsFor creates two directories for the given id. 282 // mnt and diff 283 func (a *Driver) createDirsFor(id string) error { 284 paths := []string{ 285 "mnt", 286 "diff", 287 } 288 289 rootUID, rootGID, err := idtools.GetRootUIDGID(a.uidMaps, a.gidMaps) 290 if err != nil { 291 return err 292 } 293 // Directory permission is 0755. 294 // The path of directories are <aufs_root_path>/mnt/<image_id> 295 // and <aufs_root_path>/diff/<image_id> 296 for _, p := range paths { 297 if err := idtools.MkdirAllAndChown(path.Join(a.rootPath(), p, id), 0755, idtools.IDPair{UID: rootUID, GID: rootGID}); err != nil { 298 return err 299 } 300 } 301 return nil 302 } 303 304 // Remove will unmount and remove the given id. 305 func (a *Driver) Remove(id string) error { 306 a.locker.Lock(id) 307 defer a.locker.Unlock(id) 308 a.pathCacheLock.Lock() 309 mountpoint, exists := a.pathCache[id] 310 a.pathCacheLock.Unlock() 311 if !exists { 312 mountpoint = a.getMountpoint(id) 313 } 314 315 logger := logrus.WithFields(logrus.Fields{ 316 "module": "graphdriver", 317 "driver": "aufs", 318 "layer": id, 319 }) 320 321 var retries int 322 for { 323 mounted, err := a.mounted(mountpoint) 324 if err != nil { 325 if os.IsNotExist(err) { 326 break 327 } 328 return err 329 } 330 if !mounted { 331 break 332 } 333 334 err = a.unmount(mountpoint) 335 if err == nil { 336 break 337 } 338 339 if err != unix.EBUSY { 340 return errors.Wrapf(err, "aufs: unmount error: %s", mountpoint) 341 } 342 if retries >= 5 { 343 return errors.Wrapf(err, "aufs: unmount error after retries: %s", mountpoint) 344 } 345 // If unmount returns EBUSY, it could be a transient error. Sleep and retry. 346 retries++ 347 logger.Warnf("unmount failed due to EBUSY: retry count: %d", retries) 348 time.Sleep(100 * time.Millisecond) 349 } 350 351 // Remove the layers file for the id 352 if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) { 353 return errors.Wrapf(err, "error removing layers dir for %s", id) 354 } 355 356 if err := atomicRemove(a.getDiffPath(id)); err != nil { 357 return errors.Wrapf(err, "could not remove diff path for id %s", id) 358 } 359 360 // Atomically remove each directory in turn by first moving it out of the 361 // way (so that docker doesn't find it anymore) before doing removal of 362 // the whole tree. 363 if err := atomicRemove(mountpoint); err != nil { 364 if errors.Cause(err) == unix.EBUSY { 365 logger.WithField("dir", mountpoint).WithError(err).Warn("error performing atomic remove due to EBUSY") 366 } 367 return errors.Wrapf(err, "could not remove mountpoint for id %s", id) 368 } 369 370 a.pathCacheLock.Lock() 371 delete(a.pathCache, id) 372 a.pathCacheLock.Unlock() 373 return nil 374 } 375 376 func atomicRemove(source string) error { 377 target := source + "-removing" 378 379 err := os.Rename(source, target) 380 switch { 381 case err == nil, os.IsNotExist(err): 382 case os.IsExist(err): 383 // Got error saying the target dir already exists, maybe the source doesn't exist due to a previous (failed) remove 384 if _, e := os.Stat(source); !os.IsNotExist(e) { 385 return errors.Wrapf(err, "target rename dir '%s' exists but should not, this needs to be manually cleaned up") 386 } 387 default: 388 return errors.Wrapf(err, "error preparing atomic delete") 389 } 390 391 return system.EnsureRemoveAll(target) 392 } 393 394 // Get returns the rootfs path for the id. 395 // This will mount the dir at its given path 396 func (a *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { 397 a.locker.Lock(id) 398 defer a.locker.Unlock(id) 399 parents, err := a.getParentLayerPaths(id) 400 if err != nil && !os.IsNotExist(err) { 401 return nil, err 402 } 403 404 a.pathCacheLock.Lock() 405 m, exists := a.pathCache[id] 406 a.pathCacheLock.Unlock() 407 408 if !exists { 409 m = a.getDiffPath(id) 410 if len(parents) > 0 { 411 m = a.getMountpoint(id) 412 } 413 } 414 if count := a.ctr.Increment(m); count > 1 { 415 return containerfs.NewLocalContainerFS(m), nil 416 } 417 418 // If a dir does not have a parent ( no layers )do not try to mount 419 // just return the diff path to the data 420 if len(parents) > 0 { 421 if err := a.mount(id, m, mountLabel, parents); err != nil { 422 return nil, err 423 } 424 } 425 426 a.pathCacheLock.Lock() 427 a.pathCache[id] = m 428 a.pathCacheLock.Unlock() 429 return containerfs.NewLocalContainerFS(m), nil 430 } 431 432 // Put unmounts and updates list of active mounts. 433 func (a *Driver) Put(id string) error { 434 a.locker.Lock(id) 435 defer a.locker.Unlock(id) 436 a.pathCacheLock.Lock() 437 m, exists := a.pathCache[id] 438 if !exists { 439 m = a.getMountpoint(id) 440 a.pathCache[id] = m 441 } 442 a.pathCacheLock.Unlock() 443 if count := a.ctr.Decrement(m); count > 0 { 444 return nil 445 } 446 447 err := a.unmount(m) 448 if err != nil { 449 logrus.Debugf("Failed to unmount %s aufs: %v", id, err) 450 } 451 return err 452 } 453 454 // isParent returns if the passed in parent is the direct parent of the passed in layer 455 func (a *Driver) isParent(id, parent string) bool { 456 parents, _ := getParentIDs(a.rootPath(), id) 457 if parent == "" && len(parents) > 0 { 458 return false 459 } 460 return !(len(parents) > 0 && parent != parents[0]) 461 } 462 463 // Diff produces an archive of the changes between the specified 464 // layer and its parent layer which may be "". 465 func (a *Driver) Diff(id, parent string) (io.ReadCloser, error) { 466 if !a.isParent(id, parent) { 467 return a.naiveDiff.Diff(id, parent) 468 } 469 470 // AUFS doesn't need the parent layer to produce a diff. 471 return archive.TarWithOptions(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{ 472 Compression: archive.Uncompressed, 473 ExcludePatterns: []string{archive.WhiteoutMetaPrefix + "*", "!" + archive.WhiteoutOpaqueDir}, 474 UIDMaps: a.uidMaps, 475 GIDMaps: a.gidMaps, 476 }) 477 } 478 479 type fileGetNilCloser struct { 480 storage.FileGetter 481 } 482 483 func (f fileGetNilCloser) Close() error { 484 return nil 485 } 486 487 // DiffGetter returns a FileGetCloser that can read files from the directory that 488 // contains files for the layer differences. Used for direct access for tar-split. 489 func (a *Driver) DiffGetter(id string) (graphdriver.FileGetCloser, error) { 490 p := path.Join(a.rootPath(), "diff", id) 491 return fileGetNilCloser{storage.NewPathFileGetter(p)}, nil 492 } 493 494 func (a *Driver) applyDiff(id string, diff io.Reader) error { 495 return chrootarchive.UntarUncompressed(diff, path.Join(a.rootPath(), "diff", id), &archive.TarOptions{ 496 UIDMaps: a.uidMaps, 497 GIDMaps: a.gidMaps, 498 }) 499 } 500 501 // DiffSize calculates the changes between the specified id 502 // and its parent and returns the size in bytes of the changes 503 // relative to its base filesystem directory. 504 func (a *Driver) DiffSize(id, parent string) (size int64, err error) { 505 if !a.isParent(id, parent) { 506 return a.naiveDiff.DiffSize(id, parent) 507 } 508 // AUFS doesn't need the parent layer to calculate the diff size. 509 return directory.Size(path.Join(a.rootPath(), "diff", id)) 510 } 511 512 // ApplyDiff extracts the changeset from the given diff into the 513 // layer with the specified id and parent, returning the size of the 514 // new layer in bytes. 515 func (a *Driver) ApplyDiff(id, parent string, diff io.Reader) (size int64, err error) { 516 if !a.isParent(id, parent) { 517 return a.naiveDiff.ApplyDiff(id, parent, diff) 518 } 519 520 // AUFS doesn't need the parent id to apply the diff if it is the direct parent. 521 if err = a.applyDiff(id, diff); err != nil { 522 return 523 } 524 525 return a.DiffSize(id, parent) 526 } 527 528 // Changes produces a list of changes between the specified layer 529 // and its parent layer. If parent is "", then all changes will be ADD changes. 530 func (a *Driver) Changes(id, parent string) ([]archive.Change, error) { 531 if !a.isParent(id, parent) { 532 return a.naiveDiff.Changes(id, parent) 533 } 534 535 // AUFS doesn't have snapshots, so we need to get changes from all parent 536 // layers. 537 layers, err := a.getParentLayerPaths(id) 538 if err != nil { 539 return nil, err 540 } 541 return archive.Changes(layers, path.Join(a.rootPath(), "diff", id)) 542 } 543 544 func (a *Driver) getParentLayerPaths(id string) ([]string, error) { 545 parentIds, err := getParentIDs(a.rootPath(), id) 546 if err != nil { 547 return nil, err 548 } 549 layers := make([]string, len(parentIds)) 550 551 // Get the diff paths for all the parent ids 552 for i, p := range parentIds { 553 layers[i] = path.Join(a.rootPath(), "diff", p) 554 } 555 return layers, nil 556 } 557 558 func (a *Driver) mount(id string, target string, mountLabel string, layers []string) error { 559 a.Lock() 560 defer a.Unlock() 561 562 // If the id is mounted or we get an error return 563 if mounted, err := a.mounted(target); err != nil || mounted { 564 return err 565 } 566 567 rw := a.getDiffPath(id) 568 569 if err := a.aufsMount(layers, rw, target, mountLabel); err != nil { 570 return fmt.Errorf("error creating aufs mount to %s: %v", target, err) 571 } 572 return nil 573 } 574 575 func (a *Driver) unmount(mountPath string) error { 576 a.Lock() 577 defer a.Unlock() 578 579 if mounted, err := a.mounted(mountPath); err != nil || !mounted { 580 return err 581 } 582 if err := Unmount(mountPath); err != nil { 583 return err 584 } 585 return nil 586 } 587 588 func (a *Driver) mounted(mountpoint string) (bool, error) { 589 return graphdriver.Mounted(graphdriver.FsMagicAufs, mountpoint) 590 } 591 592 // Cleanup aufs and unmount all mountpoints 593 func (a *Driver) Cleanup() error { 594 var dirs []string 595 if err := filepath.Walk(a.mntPath(), func(path string, info os.FileInfo, err error) error { 596 if err != nil { 597 return err 598 } 599 if !info.IsDir() { 600 return nil 601 } 602 dirs = append(dirs, path) 603 return nil 604 }); err != nil { 605 return err 606 } 607 608 for _, m := range dirs { 609 if err := a.unmount(m); err != nil { 610 logrus.Debugf("aufs error unmounting %s: %s", m, err) 611 } 612 } 613 return mountpk.Unmount(a.root) 614 } 615 616 func (a *Driver) aufsMount(ro []string, rw, target, mountLabel string) (err error) { 617 defer func() { 618 if err != nil { 619 Unmount(target) 620 } 621 }() 622 623 // Mount options are clipped to page size(4096 bytes). If there are more 624 // layers then these are remounted individually using append. 625 626 offset := 54 627 if useDirperm() { 628 offset += len(",dirperm1") 629 } 630 b := make([]byte, unix.Getpagesize()-len(mountLabel)-offset) // room for xino & mountLabel 631 bp := copy(b, fmt.Sprintf("br:%s=rw", rw)) 632 633 index := 0 634 for ; index < len(ro); index++ { 635 layer := fmt.Sprintf(":%s=ro+wh", ro[index]) 636 if bp+len(layer) > len(b) { 637 break 638 } 639 bp += copy(b[bp:], layer) 640 } 641 642 opts := "dio,xino=/dev/shm/aufs.xino" 643 if useDirperm() { 644 opts += ",dirperm1" 645 } 646 data := label.FormatMountLabel(fmt.Sprintf("%s,%s", string(b[:bp]), opts), mountLabel) 647 if err = mount("none", target, "aufs", 0, data); err != nil { 648 return 649 } 650 651 for ; index < len(ro); index++ { 652 layer := fmt.Sprintf(":%s=ro+wh", ro[index]) 653 data := label.FormatMountLabel(fmt.Sprintf("append%s", layer), mountLabel) 654 if err = mount("none", target, "aufs", unix.MS_REMOUNT, data); err != nil { 655 return 656 } 657 } 658 659 return 660 } 661 662 // useDirperm checks dirperm1 mount option can be used with the current 663 // version of aufs. 664 func useDirperm() bool { 665 enableDirpermLock.Do(func() { 666 base, err := ioutil.TempDir("", "docker-aufs-base") 667 if err != nil { 668 logrus.Errorf("error checking dirperm1: %v", err) 669 return 670 } 671 defer os.RemoveAll(base) 672 673 union, err := ioutil.TempDir("", "docker-aufs-union") 674 if err != nil { 675 logrus.Errorf("error checking dirperm1: %v", err) 676 return 677 } 678 defer os.RemoveAll(union) 679 680 opts := fmt.Sprintf("br:%s,dirperm1,xino=/dev/shm/aufs.xino", base) 681 if err := mount("none", union, "aufs", 0, opts); err != nil { 682 return 683 } 684 enableDirperm = true 685 if err := Unmount(union); err != nil { 686 logrus.Errorf("error checking dirperm1: failed to unmount %v", err) 687 } 688 }) 689 return enableDirperm 690 }