github.com/rita33cool1/iot-system-gateway@v0.0.0-20200911033302-e65bde238cc5/docker-engine/daemon/graphdriver/overlay/overlay.go (about)

     1  // +build linux
     2  
     3  package overlay // import "github.com/docker/docker/daemon/graphdriver/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  		return ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666)
   309  	}
   310  
   311  	// Otherwise, copy the upper and the lower-id from the parent
   312  
   313  	lowerID, err := ioutil.ReadFile(path.Join(parentDir, "lower-id"))
   314  	if err != nil {
   315  		return err
   316  	}
   317  
   318  	if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerID, 0666); err != nil {
   319  		return err
   320  	}
   321  
   322  	parentUpperDir := path.Join(parentDir, "upper")
   323  	s, err := os.Lstat(parentUpperDir)
   324  	if err != nil {
   325  		return err
   326  	}
   327  
   328  	upperDir := path.Join(dir, "upper")
   329  	if err := idtools.MkdirAndChown(upperDir, s.Mode(), root); err != nil {
   330  		return err
   331  	}
   332  	if err := idtools.MkdirAndChown(path.Join(dir, "work"), 0700, root); err != nil {
   333  		return err
   334  	}
   335  
   336  	return copy.DirCopy(parentUpperDir, upperDir, copy.Content, true)
   337  }
   338  
   339  func (d *Driver) dir(id string) string {
   340  	return path.Join(d.home, id)
   341  }
   342  
   343  // Remove cleans the directories that are created for this id.
   344  func (d *Driver) Remove(id string) error {
   345  	d.locker.Lock(id)
   346  	defer d.locker.Unlock(id)
   347  	return system.EnsureRemoveAll(d.dir(id))
   348  }
   349  
   350  // Get creates and mounts the required file system for the given id and returns the mount path.
   351  func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err error) {
   352  	d.locker.Lock(id)
   353  	defer d.locker.Unlock(id)
   354  	dir := d.dir(id)
   355  	if _, err := os.Stat(dir); err != nil {
   356  		return nil, err
   357  	}
   358  	// If id has a root, just return it
   359  	rootDir := path.Join(dir, "root")
   360  	if _, err := os.Stat(rootDir); err == nil {
   361  		return containerfs.NewLocalContainerFS(rootDir), nil
   362  	}
   363  
   364  	mergedDir := path.Join(dir, "merged")
   365  	if count := d.ctr.Increment(mergedDir); count > 1 {
   366  		return containerfs.NewLocalContainerFS(mergedDir), nil
   367  	}
   368  	defer func() {
   369  		if err != nil {
   370  			if c := d.ctr.Decrement(mergedDir); c <= 0 {
   371  				if mntErr := unix.Unmount(mergedDir, 0); mntErr != nil {
   372  					logrus.Debugf("Failed to unmount %s: %v: %v", id, mntErr, err)
   373  				}
   374  				// Cleanup the created merged directory; see the comment in Put's rmdir
   375  				if rmErr := unix.Rmdir(mergedDir); rmErr != nil && !os.IsNotExist(rmErr) {
   376  					logrus.Warnf("Failed to remove %s: %v: %v", id, rmErr, err)
   377  				}
   378  			}
   379  		}
   380  	}()
   381  	lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id"))
   382  	if err != nil {
   383  		return nil, err
   384  	}
   385  	rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
   386  	if err != nil {
   387  		return nil, err
   388  	}
   389  	if err := idtools.MkdirAndChown(mergedDir, 0700, idtools.IDPair{rootUID, rootGID}); err != nil {
   390  		return nil, err
   391  	}
   392  	var (
   393  		lowerDir = path.Join(d.dir(string(lowerID)), "root")
   394  		upperDir = path.Join(dir, "upper")
   395  		workDir  = path.Join(dir, "work")
   396  		opts     = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
   397  	)
   398  	if err := unix.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
   399  		return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
   400  	}
   401  	// chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
   402  	// user namespace requires this to move a directory from lower to upper.
   403  	if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
   404  		return nil, err
   405  	}
   406  	return containerfs.NewLocalContainerFS(mergedDir), nil
   407  }
   408  
   409  // Put unmounts the mount path created for the give id.
   410  // It also removes the 'merged' directory to force the kernel to unmount the
   411  // overlay mount in other namespaces.
   412  func (d *Driver) Put(id string) error {
   413  	d.locker.Lock(id)
   414  	defer d.locker.Unlock(id)
   415  	// If id has a root, just return
   416  	if _, err := os.Stat(path.Join(d.dir(id), "root")); err == nil {
   417  		return nil
   418  	}
   419  	mountpoint := path.Join(d.dir(id), "merged")
   420  	if count := d.ctr.Decrement(mountpoint); count > 0 {
   421  		return nil
   422  	}
   423  	if err := unix.Unmount(mountpoint, unix.MNT_DETACH); err != nil {
   424  		logrus.Debugf("Failed to unmount %s overlay: %v", id, err)
   425  	}
   426  
   427  	// Remove the mountpoint here. Removing the mountpoint (in newer kernels)
   428  	// will cause all other instances of this mount in other mount namespaces
   429  	// to be unmounted. This is necessary to avoid cases where an overlay mount
   430  	// that is present in another namespace will cause subsequent mounts
   431  	// operations to fail with ebusy.  We ignore any errors here because this may
   432  	// fail on older kernels which don't have
   433  	// torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe applied.
   434  	if err := unix.Rmdir(mountpoint); err != nil {
   435  		logrus.Debugf("Failed to remove %s overlay: %v", id, err)
   436  	}
   437  	return nil
   438  }
   439  
   440  // ApplyDiff applies the new layer on top of the root, if parent does not exist with will return an ErrApplyDiffFallback error.
   441  func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
   442  	dir := d.dir(id)
   443  
   444  	if parent == "" {
   445  		return 0, ErrApplyDiffFallback
   446  	}
   447  
   448  	parentRootDir := path.Join(d.dir(parent), "root")
   449  	if _, err := os.Stat(parentRootDir); err != nil {
   450  		return 0, ErrApplyDiffFallback
   451  	}
   452  
   453  	// We now know there is a parent, and it has a "root" directory containing
   454  	// the full root filesystem. We can just hardlink it and apply the
   455  	// layer. This relies on two things:
   456  	// 1) ApplyDiff is only run once on a clean (no writes to upper layer) container
   457  	// 2) ApplyDiff doesn't do any in-place writes to files (would break hardlinks)
   458  	// These are all currently true and are not expected to break
   459  
   460  	tmpRootDir, err := ioutil.TempDir(dir, "tmproot")
   461  	if err != nil {
   462  		return 0, err
   463  	}
   464  	defer func() {
   465  		if err != nil {
   466  			os.RemoveAll(tmpRootDir)
   467  		} else {
   468  			os.RemoveAll(path.Join(dir, "upper"))
   469  			os.RemoveAll(path.Join(dir, "work"))
   470  			os.RemoveAll(path.Join(dir, "merged"))
   471  			os.RemoveAll(path.Join(dir, "lower-id"))
   472  		}
   473  	}()
   474  
   475  	if err = copy.DirCopy(parentRootDir, tmpRootDir, copy.Hardlink, true); err != nil {
   476  		return 0, err
   477  	}
   478  
   479  	options := &archive.TarOptions{UIDMaps: d.uidMaps, GIDMaps: d.gidMaps}
   480  	if size, err = graphdriver.ApplyUncompressedLayer(tmpRootDir, diff, options); err != nil {
   481  		return 0, err
   482  	}
   483  
   484  	rootDir := path.Join(dir, "root")
   485  	if err := os.Rename(tmpRootDir, rootDir); err != nil {
   486  		return 0, err
   487  	}
   488  
   489  	return
   490  }
   491  
   492  // Exists checks to see if the id is already mounted.
   493  func (d *Driver) Exists(id string) bool {
   494  	_, err := os.Stat(d.dir(id))
   495  	return err == nil
   496  }