github.com/lazyboychen7/engine@v17.12.1-ce-rc2+incompatible/daemon/graphdriver/overlay/overlay.go (about)

     1  // +build linux
     2  
     3  package overlay
     4  
     5  import (
     6  	"bufio"
     7  	"fmt"
     8  	"io"
     9  	"io/ioutil"
    10  	"os"
    11  	"os/exec"
    12  	"path"
    13  	"path/filepath"
    14  	"strconv"
    15  
    16  	"github.com/docker/docker/daemon/graphdriver"
    17  	"github.com/docker/docker/daemon/graphdriver/copy"
    18  	"github.com/docker/docker/daemon/graphdriver/overlayutils"
    19  	"github.com/docker/docker/pkg/archive"
    20  	"github.com/docker/docker/pkg/containerfs"
    21  	"github.com/docker/docker/pkg/fsutils"
    22  	"github.com/docker/docker/pkg/idtools"
    23  	"github.com/docker/docker/pkg/locker"
    24  	"github.com/docker/docker/pkg/mount"
    25  	"github.com/docker/docker/pkg/system"
    26  	"github.com/opencontainers/selinux/go-selinux/label"
    27  	"github.com/sirupsen/logrus"
    28  	"golang.org/x/sys/unix"
    29  )
    30  
    31  // This is a small wrapper over the NaiveDiffWriter that lets us have a custom
    32  // implementation of ApplyDiff()
    33  
    34  var (
    35  	// ErrApplyDiffFallback is returned to indicate that a normal ApplyDiff is applied as a fallback from Naive diff writer.
    36  	ErrApplyDiffFallback = fmt.Errorf("Fall back to normal ApplyDiff")
    37  	backingFs            = "<unknown>"
    38  )
    39  
    40  // ApplyDiffProtoDriver wraps the ProtoDriver by extending the interface with ApplyDiff method.
    41  type ApplyDiffProtoDriver interface {
    42  	graphdriver.ProtoDriver
    43  	// ApplyDiff writes the diff to the archive for the given id and parent id.
    44  	// It returns the size in bytes written if successful, an error ErrApplyDiffFallback is returned otherwise.
    45  	ApplyDiff(id, parent string, diff io.Reader) (size int64, err error)
    46  }
    47  
    48  type naiveDiffDriverWithApply struct {
    49  	graphdriver.Driver
    50  	applyDiff ApplyDiffProtoDriver
    51  }
    52  
    53  // NaiveDiffDriverWithApply returns a NaiveDiff driver with custom ApplyDiff.
    54  func NaiveDiffDriverWithApply(driver ApplyDiffProtoDriver, uidMaps, gidMaps []idtools.IDMap) graphdriver.Driver {
    55  	return &naiveDiffDriverWithApply{
    56  		Driver:    graphdriver.NewNaiveDiffDriver(driver, uidMaps, gidMaps),
    57  		applyDiff: driver,
    58  	}
    59  }
    60  
    61  // ApplyDiff creates a diff layer with either the NaiveDiffDriver or with a fallback.
    62  func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff io.Reader) (int64, error) {
    63  	b, err := d.applyDiff.ApplyDiff(id, parent, diff)
    64  	if err == ErrApplyDiffFallback {
    65  		return d.Driver.ApplyDiff(id, parent, diff)
    66  	}
    67  	return b, err
    68  }
    69  
    70  // This backend uses the overlay union filesystem for containers
    71  // plus hard link file sharing for images.
    72  
    73  // Each container/image can have a "root" subdirectory which is a plain
    74  // filesystem hierarchy, or they can use overlay.
    75  
    76  // If they use overlay there is a "upper" directory and a "lower-id"
    77  // file, as well as "merged" and "work" directories. The "upper"
    78  // directory has the upper layer of the overlay, and "lower-id" contains
    79  // the id of the parent whose "root" directory shall be used as the lower
    80  // layer in the overlay. The overlay itself is mounted in the "merged"
    81  // directory, and the "work" dir is needed for overlay to work.
    82  
    83  // When an overlay layer is created there are two cases, either the
    84  // parent has a "root" dir, then we start out with an empty "upper"
    85  // directory overlaid on the parents root. This is typically the
    86  // case with the init layer of a container which is based on an image.
    87  // If there is no "root" in the parent, we inherit the lower-id from
    88  // the parent and start by making a copy in the parent's "upper" dir.
    89  // This is typically the case for a container layer which copies
    90  // its parent -init upper layer.
    91  
    92  // Additionally we also have a custom implementation of ApplyLayer
    93  // which makes a recursive copy of the parent "root" layer using
    94  // hardlinks to share file data, and then applies the layer on top
    95  // of that. This means all child images share file (but not directory)
    96  // data with the parent.
    97  
    98  // Driver contains information about the home directory and the list of active mounts that are created using this driver.
    99  type Driver struct {
   100  	home          string
   101  	uidMaps       []idtools.IDMap
   102  	gidMaps       []idtools.IDMap
   103  	ctr           *graphdriver.RefCounter
   104  	supportsDType bool
   105  	locker        *locker.Locker
   106  }
   107  
   108  func init() {
   109  	graphdriver.Register("overlay", Init)
   110  }
   111  
   112  // Init returns the NaiveDiffDriver, a native diff driver for overlay filesystem.
   113  // If overlay filesystem is not supported on the host, the error
   114  // graphdriver.ErrNotSupported is returned.
   115  // If an overlay filesystem is not supported over an existing filesystem then
   116  // error graphdriver.ErrIncompatibleFS is returned.
   117  func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
   118  
   119  	if err := supportsOverlay(); err != nil {
   120  		return nil, graphdriver.ErrNotSupported
   121  	}
   122  
   123  	// Perform feature detection on /var/lib/docker/overlay if it's an existing directory.
   124  	// This covers situations where /var/lib/docker/overlay is a mount, and on a different
   125  	// filesystem than /var/lib/docker.
   126  	// If the path does not exist, fall back to using /var/lib/docker for feature detection.
   127  	testdir := home
   128  	if _, err := os.Stat(testdir); os.IsNotExist(err) {
   129  		testdir = filepath.Dir(testdir)
   130  	}
   131  
   132  	fsMagic, err := graphdriver.GetFSMagic(testdir)
   133  	if err != nil {
   134  		return nil, err
   135  	}
   136  	if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
   137  		backingFs = fsName
   138  	}
   139  
   140  	switch fsMagic {
   141  	case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicEcryptfs, graphdriver.FsMagicNfsFs, graphdriver.FsMagicOverlay, graphdriver.FsMagicZfs:
   142  		logrus.Errorf("'overlay' is not supported over %s", backingFs)
   143  		return nil, graphdriver.ErrIncompatibleFS
   144  	}
   145  
   146  	supportsDType, err := fsutils.SupportsDType(testdir)
   147  	if err != nil {
   148  		return nil, err
   149  	}
   150  	if !supportsDType {
   151  		if !graphdriver.IsInitialized(home) {
   152  			return nil, overlayutils.ErrDTypeNotSupported("overlay", backingFs)
   153  		}
   154  		// allow running without d_type only for existing setups (#27443)
   155  		logrus.Warn(overlayutils.ErrDTypeNotSupported("overlay", backingFs))
   156  	}
   157  
   158  	rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
   159  	if err != nil {
   160  		return nil, err
   161  	}
   162  	// Create the driver home dir
   163  	if err := idtools.MkdirAllAndChown(home, 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
   164  		return nil, err
   165  	}
   166  
   167  	d := &Driver{
   168  		home:          home,
   169  		uidMaps:       uidMaps,
   170  		gidMaps:       gidMaps,
   171  		ctr:           graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicOverlay)),
   172  		supportsDType: supportsDType,
   173  		locker:        locker.New(),
   174  	}
   175  
   176  	return NaiveDiffDriverWithApply(d, uidMaps, gidMaps), nil
   177  }
   178  
   179  func supportsOverlay() error {
   180  	// We can try to modprobe overlay first before looking at
   181  	// proc/filesystems for when overlay is supported
   182  	exec.Command("modprobe", "overlay").Run()
   183  
   184  	f, err := os.Open("/proc/filesystems")
   185  	if err != nil {
   186  		return err
   187  	}
   188  	defer f.Close()
   189  
   190  	s := bufio.NewScanner(f)
   191  	for s.Scan() {
   192  		if s.Text() == "nodev\toverlay" {
   193  			return nil
   194  		}
   195  	}
   196  	logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.")
   197  	return graphdriver.ErrNotSupported
   198  }
   199  
   200  func (d *Driver) String() string {
   201  	return "overlay"
   202  }
   203  
   204  // Status returns current driver information in a two dimensional string array.
   205  // Output contains "Backing Filesystem" used in this implementation.
   206  func (d *Driver) Status() [][2]string {
   207  	return [][2]string{
   208  		{"Backing Filesystem", backingFs},
   209  		{"Supports d_type", strconv.FormatBool(d.supportsDType)},
   210  	}
   211  }
   212  
   213  // GetMetadata returns metadata about the overlay driver such as root,
   214  // LowerDir, UpperDir, WorkDir and MergeDir used to store data.
   215  func (d *Driver) GetMetadata(id string) (map[string]string, error) {
   216  	dir := d.dir(id)
   217  	if _, err := os.Stat(dir); err != nil {
   218  		return nil, err
   219  	}
   220  
   221  	metadata := make(map[string]string)
   222  
   223  	// If id has a root, it is an image
   224  	rootDir := path.Join(dir, "root")
   225  	if _, err := os.Stat(rootDir); err == nil {
   226  		metadata["RootDir"] = rootDir
   227  		return metadata, nil
   228  	}
   229  
   230  	lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
   231  	if err != nil {
   232  		return nil, err
   233  	}
   234  
   235  	metadata["LowerDir"] = path.Join(d.dir(string(lowerID)), "root")
   236  	metadata["UpperDir"] = path.Join(dir, "upper")
   237  	metadata["WorkDir"] = path.Join(dir, "work")
   238  	metadata["MergedDir"] = path.Join(dir, "merged")
   239  
   240  	return metadata, nil
   241  }
   242  
   243  // Cleanup any state created by overlay which should be cleaned when daemon
   244  // is being shutdown. For now, we just have to unmount the bind mounted
   245  // we had created.
   246  func (d *Driver) Cleanup() error {
   247  	return mount.RecursiveUnmount(d.home)
   248  }
   249  
   250  // CreateReadWrite creates a layer that is writable for use as a container
   251  // file system.
   252  func (d *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts) error {
   253  	return d.Create(id, parent, opts)
   254  }
   255  
   256  // Create is used to create the upper, lower, and merge directories required for overlay fs for a given id.
   257  // The parent filesystem is used to configure these directories for the overlay.
   258  func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr error) {
   259  
   260  	if opts != nil && len(opts.StorageOpt) != 0 {
   261  		return fmt.Errorf("--storage-opt is not supported for overlay")
   262  	}
   263  
   264  	dir := d.dir(id)
   265  
   266  	rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
   267  	if err != nil {
   268  		return err
   269  	}
   270  	root := idtools.IDPair{UID: rootUID, GID: rootGID}
   271  
   272  	if err := idtools.MkdirAllAndChown(path.Dir(dir), 0700, root); err != nil {
   273  		return err
   274  	}
   275  	if err := idtools.MkdirAndChown(dir, 0700, root); err != nil {
   276  		return err
   277  	}
   278  
   279  	defer func() {
   280  		// Clean up on failure
   281  		if retErr != nil {
   282  			os.RemoveAll(dir)
   283  		}
   284  	}()
   285  
   286  	// Toplevel images are just a "root" dir
   287  	if parent == "" {
   288  		return idtools.MkdirAndChown(path.Join(dir, "root"), 0755, root)
   289  	}
   290  
   291  	parentDir := d.dir(parent)
   292  
   293  	// Ensure parent exists
   294  	if _, err := os.Lstat(parentDir); err != nil {
   295  		return err
   296  	}
   297  
   298  	// If parent has a root, just do an overlay to it
   299  	parentRoot := path.Join(parentDir, "root")
   300  
   301  	if s, err := os.Lstat(parentRoot); err == nil {
   302  		if err := idtools.MkdirAndChown(path.Join(dir, "upper"), s.Mode(), root); err != nil {
   303  			return err
   304  		}
   305  		if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
   306  			return err
   307  		}
   308  		if err := ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666); err != nil {
   309  			return err
   310  		}
   311  		return nil
   312  	}
   313  
   314  	// Otherwise, copy the upper and the lower-id from the parent
   315  
   316  	lowerID, err := ioutil.ReadFile(path.Join(parentDir, "lower-id"))
   317  	if err != nil {
   318  		return err
   319  	}
   320  
   321  	if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0666); err != nil {
   322  		return err
   323  	}
   324  
   325  	parentUpperDir := path.Join(parentDir, "upper")
   326  	s, err := os.Lstat(parentUpperDir)
   327  	if err != nil {
   328  		return err
   329  	}
   330  
   331  	upperDir := path.Join(dir, "upper")
   332  	if err := idtools.MkdirAndChown(upperDir, s.Mode(), root); err != nil {
   333  		return err
   334  	}
   335  	if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
   336  		return err
   337  	}
   338  
   339  	return copy.DirCopy(parentUpperDir, upperDir, copy.Content, true)
   340  }
   341  
   342  func (d *Driver) dir(id string) string {
   343  	return path.Join(d.home, id)
   344  }
   345  
   346  // Remove cleans the directories that are created for this id.
   347  func (d *Driver) Remove(id string) error {
   348  	d.locker.Lock(id)
   349  	defer d.locker.Unlock(id)
   350  	return system.EnsureRemoveAll(d.dir(id))
   351  }
   352  
   353  // Get creates and mounts the required file system for the given id and returns the mount path.
   354  func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err error) {
   355  	d.locker.Lock(id)
   356  	defer d.locker.Unlock(id)
   357  	dir := d.dir(id)
   358  	if _, err := os.Stat(dir); err != nil {
   359  		return nil, err
   360  	}
   361  	// If id has a root, just return it
   362  	rootDir := path.Join(dir, "root")
   363  	if _, err := os.Stat(rootDir); err == nil {
   364  		return containerfs.NewLocalContainerFS(rootDir), nil
   365  	}
   366  
   367  	mergedDir := path.Join(dir, "merged")
   368  	if count := d.ctr.Increment(mergedDir); count > 1 {
   369  		return containerfs.NewLocalContainerFS(mergedDir), nil
   370  	}
   371  	defer func() {
   372  		if err != nil {
   373  			if c := d.ctr.Decrement(mergedDir); c <= 0 {
   374  				if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
   375  					logrus.Debugf("Failed to unmount %s: %v: %v", id, mntErr, err)
   376  				}
   377  				// Cleanup the created merged directory; see the comment in Put's rmdir
   378  				if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
   379  					logrus.Warnf("Failed to remove %s: %v: %v", id, rmErr, err)
   380  				}
   381  			}
   382  		}
   383  	}()
   384  	lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
   385  	if err != nil {
   386  		return nil, err
   387  	}
   388  	rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
   389  	if err != nil {
   390  		return nil, err
   391  	}
   392  	if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
   393  		return nil, err
   394  	}
   395  	var (
   396  		lowerDir = path.Join(d.dir(string(lowerID)), "root")
   397  		upperDir = path.Join(dir, "upper")
   398  		workDir  = path.Join(dir, "work")
   399  		opts     = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
   400  	)
   401  	if err := unix.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
   402  		return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
   403  	}
   404  	// chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
   405  	// user namespace requires this to move a directory from lower to upper.
   406  	if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
   407  		return nil, err
   408  	}
   409  	return containerfs.NewLocalContainerFS(mergedDir), nil
   410  }
   411  
   412  // Put unmounts the mount path created for the give id.
   413  // It also removes the 'merged' directory to force the kernel to unmount the
   414  // overlay mount in other namespaces.
   415  func (d *Driver) Put(id string) error {
   416  	d.locker.Lock(id)
   417  	defer d.locker.Unlock(id)
   418  	// If id has a root, just return
   419  	if _, err := os.Stat(path.Join(d.dir(id), "root")); err == nil {
   420  		return nil
   421  	}
   422  	mountpoint := path.Join(d.dir(id), "merged")
   423  	if count := d.ctr.Decrement(mountpoint); count > 0 {
   424  		return nil
   425  	}
   426  	if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
   427  		logrus.Debugf("Failed to unmount %s overlay: %v", id, err)
   428  	}
   429  
   430  	// Remove the mountpoint here. Removing the mountpoint (in newer kernels)
   431  	// will cause all other instances of this mount in other mount namespaces
   432  	// to be unmounted. This is necessary to avoid cases where an overlay mount
   433  	// that is present in another namespace will cause subsequent mounts
   434  	// operations to fail with ebusy.  We ignore any errors here because this may
   435  	// fail on older kernels which don't have
   436  	// torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
   437  	if err := unix.Rmdir(mountpoint); err != nil {
   438  		logrus.Debugf("Failed to remove %s overlay: %v", id, err)
   439  	}
   440  	return nil
   441  }
   442  
   443  // ApplyDiff applies the new layer on top of the root, if parent does not exist with will return an ErrApplyDiffFallback error.
   444  func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
   445  	dir := d.dir(id)
   446  
   447  	if parent == "" {
   448  		return 0, ErrApplyDiffFallback
   449  	}
   450  
   451  	parentRootDir := path.Join(d.dir(parent), "root")
   452  	if _, err := os.Stat(parentRootDir); err != nil {
   453  		return 0, ErrApplyDiffFallback
   454  	}
   455  
   456  	// We now know there is a parent, and it has a "root" directory containing
   457  	// the full root filesystem. We can just hardlink it and apply the
   458  	// layer. This relies on two things:
   459  	// 1) ApplyDiff is only run once on a clean (no writes to upper layer) container
   460  	// 2) ApplyDiff doesn't do any in-place writes to files (would break hardlinks)
   461  	// These are all currently true and are not expected to break
   462  
   463  	tmpRootDir, err := ioutil.TempDir(dir, "tmproot")
   464  	if err != nil {
   465  		return 0, err
   466  	}
   467  	defer func() {
   468  		if err != nil {
   469  			os.RemoveAll(tmpRootDir)
   470  		} else {
   471  			os.RemoveAll(path.Join(dir, "upper"))
   472  			os.RemoveAll(path.Join(dir, "work"))
   473  			os.RemoveAll(path.Join(dir, "merged"))
   474  			os.RemoveAll(path.Join(dir, "lower-id"))
   475  		}
   476  	}()
   477  
   478  	if err = copy.DirCopy(parentRootDir, tmpRootDir, copy.Hardlink, true); err != nil {
   479  		return 0, err
   480  	}
   481  
   482  	options := &archive.TarOptions{UIDMaps: d.uidMaps, GIDMaps: d.gidMaps}
   483  	if size, err = graphdriver.ApplyUncompressedLayer(tmpRootDir, diff, options); err != nil {
   484  		return 0, err
   485  	}
   486  
   487  	rootDir := path.Join(dir, "root")
   488  	if err := os.Rename(tmpRootDir, rootDir); err != nil {
   489  		return 0, err
   490  	}
   491  
   492  	return
   493  }
   494  
   495  // Exists checks to see if the id is already mounted.
   496  func (d *Driver) Exists(id string) bool {
   497  	_, err := os.Stat(d.dir(id))
   498  	return err == nil
   499  }